@tangle-network/agent-bench 1.0.2 → 3.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +29 -0
- package/README.md +24 -2
- package/dist/adapters.d.ts +3 -3
- package/dist/adapters.js +3 -5
- package/dist/adapters.js.map +1 -1
- package/dist/benchmarks/_harness.d.ts +4 -4
- package/dist/benchmarks/_harness.js +5 -2
- package/dist/benchmarks/_harness.js.map +1 -1
- package/dist/benchmarks/aec-bench.d.ts +2 -2
- package/dist/benchmarks/aec-bench.js +49 -42
- package/dist/benchmarks/aec-bench.js.map +1 -1
- package/dist/benchmarks/agentbench.d.ts +2 -2
- package/dist/benchmarks/agentbench.js +41 -34
- package/dist/benchmarks/agentbench.js.map +1 -1
- package/dist/benchmarks/appworld.d.ts +4 -4
- package/dist/benchmarks/appworld.js +67 -53
- package/dist/benchmarks/appworld.js.map +1 -1
- package/dist/benchmarks/bfcl.d.ts +2 -2
- package/dist/benchmarks/bfcl.js +52 -44
- package/dist/benchmarks/bfcl.js.map +1 -1
- package/dist/benchmarks/cad-design.d.ts +2 -2
- package/dist/benchmarks/cad-design.js +53 -44
- package/dist/benchmarks/cad-design.js.map +1 -1
- package/dist/benchmarks/cadbench.d.ts +2 -2
- package/dist/benchmarks/cadbench.js +1 -1
- package/dist/benchmarks/cadgenbench.d.ts +2 -2
- package/dist/benchmarks/cadgenbench.js +1 -1
- package/dist/benchmarks/commit0.d.ts +2 -2
- package/dist/benchmarks/commit0.js +38 -31
- package/dist/benchmarks/commit0.js.map +1 -1
- package/dist/benchmarks/crag.d.ts +2 -2
- package/dist/benchmarks/crag.js +37 -32
- package/dist/benchmarks/crag.js.map +1 -1
- package/dist/benchmarks/dabstep.d.ts +2 -2
- package/dist/benchmarks/dabstep.js +41 -34
- package/dist/benchmarks/dabstep.js.map +1 -1
- package/dist/benchmarks/finresearchbench.d.ts +4 -4
- package/dist/benchmarks/finresearchbench.js +63 -50
- package/dist/benchmarks/finresearchbench.js.map +1 -1
- package/dist/benchmarks/finsearchcomp.d.ts +3 -3
- package/dist/benchmarks/finsearchcomp.js +55 -44
- package/dist/benchmarks/finsearchcomp.js.map +1 -1
- package/dist/benchmarks/frames.d.ts +2 -2
- package/dist/benchmarks/frames.js +66 -51
- package/dist/benchmarks/frames.js.map +1 -1
- package/dist/benchmarks/hotpotqa.d.ts +2 -2
- package/dist/benchmarks/hotpotqa.js +59 -47
- package/dist/benchmarks/hotpotqa.js.map +1 -1
- package/dist/benchmarks/humaneval.d.ts +3 -3
- package/dist/benchmarks/humaneval.js +39 -35
- package/dist/benchmarks/humaneval.js.map +1 -1
- package/dist/benchmarks/mcad-bench.d.ts +2 -2
- package/dist/benchmarks/mcad-bench.js +68 -56
- package/dist/benchmarks/mcad-bench.js.map +1 -1
- package/dist/benchmarks/mcad-cq-bench.d.ts +3 -3
- package/dist/benchmarks/mcad-cq-bench.js +70 -58
- package/dist/benchmarks/mcad-cq-bench.js.map +1 -1
- package/dist/benchmarks/mcad-cq-golds.d.ts +1 -1
- package/dist/benchmarks/mcad-cq-golds.js +1 -1
- package/dist/benchmarks/mcad-cq-golds.js.map +1 -1
- package/dist/benchmarks/mcad-golds.d.ts +1 -1
- package/dist/benchmarks/mcad-golds.js.map +1 -1
- package/dist/benchmarks/mind2web.d.ts +3 -3
- package/dist/benchmarks/mind2web.js +62 -49
- package/dist/benchmarks/mind2web.js.map +1 -1
- package/dist/benchmarks/nomiracl.d.ts +2 -2
- package/dist/benchmarks/nomiracl.js +43 -36
- package/dist/benchmarks/nomiracl.js.map +1 -1
- package/dist/benchmarks/open-rag-bench.d.ts +2 -2
- package/dist/benchmarks/open-rag-bench.js +37 -32
- package/dist/benchmarks/open-rag-bench.js.map +1 -1
- package/dist/benchmarks/programbench.d.ts +2 -2
- package/dist/benchmarks/programbench.js +28 -23
- package/dist/benchmarks/programbench.js.map +1 -1
- package/dist/benchmarks/rag-shared.d.ts +2 -2
- package/dist/benchmarks/rag-shared.js +15 -13
- package/dist/benchmarks/rag-shared.js.map +1 -1
- package/dist/benchmarks/ragbench.d.ts +2 -2
- package/dist/benchmarks/ragbench.js +34 -29
- package/dist/benchmarks/ragbench.js.map +1 -1
- package/dist/benchmarks/simpleqa.d.ts +2 -2
- package/dist/benchmarks/simpleqa.js +63 -52
- package/dist/benchmarks/simpleqa.js.map +1 -1
- package/dist/benchmarks/swe-bench.d.ts +4 -4
- package/dist/benchmarks/swe-bench.js +47 -41
- package/dist/benchmarks/swe-bench.js.map +1 -1
- package/dist/benchmarks/t2-ragbench.d.ts +2 -2
- package/dist/benchmarks/t2-ragbench.js +37 -32
- package/dist/benchmarks/t2-ragbench.js.map +1 -1
- package/dist/benchmarks/tau-bench-shared.d.ts +2 -2
- package/dist/benchmarks/tau-bench-shared.js +43 -36
- package/dist/benchmarks/tau-bench-shared.js.map +1 -1
- package/dist/benchmarks/tau2-bench.d.ts +2 -2
- package/dist/benchmarks/tau2-bench.js.map +1 -1
- package/dist/benchmarks/tau3-banking.d.ts +2 -2
- package/dist/benchmarks/tau3-banking.js.map +1 -1
- package/dist/benchmarks/terminal-bench.d.ts +2 -2
- package/dist/benchmarks/terminal-bench.js +29 -23
- package/dist/benchmarks/terminal-bench.js.map +1 -1
- package/dist/benchmarks/toollm.d.ts +2 -2
- package/dist/benchmarks/toollm.js +40 -34
- package/dist/benchmarks/toollm.js.map +1 -1
- package/dist/benchmarks/trata-hedge.d.ts +2 -2
- package/dist/benchmarks/trata-hedge.js +49 -43
- package/dist/benchmarks/trata-hedge.js.map +1 -1
- package/dist/benchmarks/types.d.ts +33 -63
- package/dist/benchmarks/types.js +36 -1
- package/dist/benchmarks/types.js.map +1 -0
- package/dist/benchmarks/webarena-verified.d.ts +2 -2
- package/dist/benchmarks/webarena-verified.js +29 -24
- package/dist/benchmarks/webarena-verified.js.map +1 -1
- package/dist/{cadbench-DhAndllg.js → cadbench-htzAmMaI.js} +41 -36
- package/dist/cadbench-htzAmMaI.js.map +1 -0
- package/dist/{cadgenbench-Tvk16YKT.js → cadgenbench-BLvEtnxU.js} +28 -22
- package/dist/cadgenbench-BLvEtnxU.js.map +1 -0
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +667 -0
- package/dist/cli.js.map +1 -0
- package/dist/index.d.ts +11 -10
- package/dist/index.js +64 -59
- package/dist/index.js.map +1 -1
- package/package.json +9 -6
- package/scripts/enterpriseops-gym-run.sh +82 -0
- package/scripts/grade-recorded-evidence.mjs +50 -0
- package/scripts/harvey-lab-judge.py +50 -0
- package/scripts/harvey-lab-run.sh +53 -0
- package/scripts/harvey-lab-sandbox.sh +21 -0
- package/scripts/healthbench-professional-run.sh +30 -0
- package/scripts/healthbench_professional_run.py +112 -0
- package/scripts/mlcr-run.sh +17 -0
- package/scripts/mlcr_run.py +133 -0
- package/scripts/prbench-run.sh +39 -0
- package/scripts/prbench_run.py +53 -0
- package/scripts/verify-packed-consumer.mjs +32 -27
- package/src/adapters.ts +5 -7
- package/src/atom-mcp-e2e.mts +2 -2
- package/src/benchmarks/_harness.test.mts +18 -1
- package/src/benchmarks/_harness.ts +12 -7
- package/src/benchmarks/aec-bench.test.mts +14 -14
- package/src/benchmarks/aec-bench.ts +62 -56
- package/src/benchmarks/agent-eval-contract.test.mts +38 -0
- package/src/benchmarks/agentbench.ts +44 -37
- package/src/benchmarks/appworld.test.mts +7 -7
- package/src/benchmarks/appworld.ts +88 -75
- package/src/benchmarks/bfcl.ts +60 -53
- package/src/benchmarks/cad-design.ts +34 -32
- package/src/benchmarks/cadbench.ts +36 -36
- package/src/benchmarks/cadgenbench.ts +30 -28
- package/src/benchmarks/commit0.test.mts +9 -9
- package/src/benchmarks/commit0.ts +50 -43
- package/src/benchmarks/crag.ts +45 -40
- package/src/benchmarks/dabstep-official.test.mts +8 -8
- package/src/benchmarks/dabstep.test.mts +11 -11
- package/src/benchmarks/dabstep.ts +47 -40
- package/src/benchmarks/external-adapters.test.mts +43 -44
- package/src/benchmarks/finresearchbench.ts +58 -48
- package/src/benchmarks/finsearchcomp.ts +73 -68
- package/src/benchmarks/frames.ts +76 -69
- package/src/benchmarks/hotpotqa.ts +69 -64
- package/src/benchmarks/humaneval.ts +37 -35
- package/src/benchmarks/mcad-bench.test.mts +30 -30
- package/src/benchmarks/mcad-bench.ts +66 -60
- package/src/benchmarks/mcad-cq-bench.ts +69 -63
- package/src/benchmarks/mcad-cq-golds.ts +1 -1
- package/src/benchmarks/mcad-cq.test.mts +40 -40
- package/src/benchmarks/mcad-golds.ts +1 -1
- package/src/benchmarks/mind2web.ts +66 -58
- package/src/benchmarks/nomiracl.ts +53 -46
- package/src/benchmarks/open-rag-bench.ts +47 -42
- package/src/benchmarks/programbench.test.mts +10 -10
- package/src/benchmarks/programbench.ts +38 -33
- package/src/benchmarks/rag-benchmarks.test.mts +31 -31
- package/src/benchmarks/rag-shared.ts +13 -16
- package/src/benchmarks/ragbench.ts +44 -39
- package/src/benchmarks/simpleqa.ts +79 -74
- package/src/benchmarks/swe-bench.test.mts +3 -3
- package/src/benchmarks/swe-bench.ts +66 -61
- package/src/benchmarks/t2-ragbench.ts +47 -42
- package/src/benchmarks/tau-bench-shared.ts +51 -44
- package/src/benchmarks/tau-pin.test.mts +1 -1
- package/src/benchmarks/tau2-bench.ts +2 -2
- package/src/benchmarks/tau3-banking.ts +2 -2
- package/src/benchmarks/terminal-bench.test.mts +3 -3
- package/src/benchmarks/terminal-bench.ts +41 -36
- package/src/benchmarks/toollm.ts +54 -47
- package/src/benchmarks/trata-hedge.ts +61 -58
- package/src/benchmarks/types.ts +70 -59
- package/src/benchmarks/webarena-verified.ts +49 -42
- package/src/cli.ts +74 -0
- package/src/corpus-replay.mts +9 -9
- package/src/examples/benchmark-matrix.mts +19 -16
- package/src/examples/lean-proof-gate.mts +1 -1
- package/src/examples/math-demo.mts +2 -2
- package/src/examples/strategy-demo.mts +1 -1
- package/src/gate-cli.mts +6 -6
- package/src/gate.test.mts +14 -12
- package/src/gate.ts +23 -22
- package/src/generate-eval/certify.ts +4 -4
- package/src/index.ts +17 -11
- package/src/published.test.mts +534 -0
- package/src/published.ts +524 -0
- package/src/run-benchmarks-cli.mts +3 -3
- package/src/run-benchmarks.test.mts +58 -48
- package/src/run-benchmarks.ts +64 -57
- package/src/swe-bench-env.ts +6 -6
- package/src/swe-self-improve.mts +3 -3
- package/src/terminal-compare.ts +1 -1
- package/src/worker.ts +1 -1
- package/dist/benchmarks/enterpriseops-gym.d.ts +0 -6
- package/dist/benchmarks/enterpriseops-gym.js +0 -236
- package/dist/benchmarks/enterpriseops-gym.js.map +0 -1
- package/dist/cadbench-DhAndllg.js.map +0 -1
- package/dist/cadgenbench-Tvk16YKT.js.map +0 -1
- package/fixtures/enterpriseops-gym.json +0 -103
- package/scripts/enterpriseops_gym_judge.py +0 -281
- package/src/benchmarks/enterpriseops-gym.test.mts +0 -77
- package/src/benchmarks/enterpriseops-gym.ts +0 -343
- package/src/eops-skills/address-every-subtask.md +0 -5
- package/src/eops-skills/exact-tools-and-args.md +0 -5
- package/src/eops-skills/full-sequence-to-goal.md +0 -5
- package/src/eops-skills/ground-every-value.md +0 -5
- package/src/eops-skills/honor-the-policies.md +0 -5
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { benchRoot } from "./_harness.js";
|
|
2
|
+
import { runtimeBenchmark } from "./types.js";
|
|
2
3
|
import { readFile } from "node:fs/promises";
|
|
3
4
|
import { join } from "node:path";
|
|
4
5
|
// src/benchmarks/toollm.ts
|
|
@@ -33,7 +34,7 @@ function rowToTask(row) {
|
|
|
33
34
|
};
|
|
34
35
|
return {
|
|
35
36
|
id: String(row.query_id),
|
|
36
|
-
prompt: [
|
|
37
|
+
payload: { prompt: [
|
|
37
38
|
"Solve this ToolLLM/ToolBench API-use task.",
|
|
38
39
|
"Use only the listed APIs/tools and return the completed tool-use trace plus final answer.",
|
|
39
40
|
"",
|
|
@@ -42,7 +43,7 @@ function rowToTask(row) {
|
|
|
42
43
|
`Available APIs: ${JSON.stringify(row.api_list ?? [], null, 2)}`,
|
|
43
44
|
"",
|
|
44
45
|
"Return the APIs you used as JSON: {\"api_calls\":[{\"tool_name\":\"...\",\"api_name\":\"...\"}]}."
|
|
45
|
-
].join("\n"),
|
|
46
|
+
].join("\n") },
|
|
46
47
|
metadata: meta
|
|
47
48
|
};
|
|
48
49
|
}
|
|
@@ -61,7 +62,7 @@ function normalizeApiPairs(value) {
|
|
|
61
62
|
}
|
|
62
63
|
function readMeta(task) {
|
|
63
64
|
const md = task.metadata;
|
|
64
|
-
if (!md || !Array.isArray(md.relevantApis)) throw new Error(`ToolLLM task ${task.id} missing metadata —
|
|
65
|
+
if (!md || !Array.isArray(md.relevantApis)) throw new Error(`ToolLLM task ${task.id} missing metadata — loadAll did not populate deterministic API-selection labels`);
|
|
65
66
|
return md;
|
|
66
67
|
}
|
|
67
68
|
function selectRows(rows, opts) {
|
|
@@ -134,50 +135,55 @@ function scoreApiSelection(task, artifact) {
|
|
|
134
135
|
const precision = called.size === 0 ? 0 : truePositives / called.size;
|
|
135
136
|
const recall = truePositives / expected.size;
|
|
136
137
|
const score = expected.size === 0 ? 0 : recall;
|
|
138
|
+
const resolved = extracted.source === "structured-json" && recall === 1 && precision === 1;
|
|
139
|
+
const raw = {
|
|
140
|
+
scoring: "api-selection-only",
|
|
141
|
+
extractionSource: extracted.source,
|
|
142
|
+
queryId: meta.queryId,
|
|
143
|
+
expected: meta.relevantApis,
|
|
144
|
+
called: calledPairs,
|
|
145
|
+
precision,
|
|
146
|
+
recall,
|
|
147
|
+
fullToolEvalScore: null
|
|
148
|
+
};
|
|
137
149
|
return {
|
|
138
|
-
|
|
150
|
+
passed: resolved,
|
|
139
151
|
score,
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
extractionSource: extracted.source,
|
|
143
|
-
queryId: meta.queryId,
|
|
144
|
-
expected: meta.relevantApis,
|
|
145
|
-
called: calledPairs,
|
|
146
|
-
precision,
|
|
147
|
-
recall,
|
|
148
|
-
fullToolEvalScore: null
|
|
149
|
-
})
|
|
152
|
+
notes: JSON.stringify(raw),
|
|
153
|
+
raw
|
|
150
154
|
};
|
|
151
155
|
}
|
|
152
156
|
function createToolLlmAdapter() {
|
|
153
157
|
const fixturesMode = process.env.TOOLLM_FIXTURES === "1";
|
|
154
|
-
return {
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
async preflight() {
|
|
158
|
-
if (fixturesMode) return;
|
|
159
|
-
const dir = toolbenchDir();
|
|
160
|
-
if (!dir) throw new Error("TOOLBENCH_DIR is required. Fix: clone https://github.com/OpenBMB/ToolBench and set TOOLBENCH_DIR=/path/to/ToolBench.");
|
|
161
|
-
await loadOfficialTasks(dir, { limit: 1 });
|
|
162
|
-
},
|
|
163
|
-
async loadTasks(opts = {}) {
|
|
158
|
+
return runtimeBenchmark({
|
|
159
|
+
id: "toollm",
|
|
160
|
+
async loadAll(opts = {}) {
|
|
164
161
|
if (fixturesMode) return loadFixtures(opts);
|
|
165
162
|
const dir = toolbenchDir();
|
|
166
163
|
if (!dir) throw new Error("TOOLBENCH_DIR is required to load ToolLLM tasks");
|
|
167
164
|
return loadOfficialTasks(dir, opts);
|
|
168
165
|
},
|
|
169
|
-
async
|
|
170
|
-
const meta = readMeta(task);
|
|
171
|
-
if (meta.relevantApis.length === 0) return void 0;
|
|
172
|
-
return JSON.stringify({ api_calls: meta.relevantApis.map(([tool_name, api_name]) => ({
|
|
173
|
-
tool_name,
|
|
174
|
-
api_name
|
|
175
|
-
})) }, null, 2);
|
|
176
|
-
},
|
|
177
|
-
async judge(task, artifact) {
|
|
166
|
+
async evaluate(task, artifact) {
|
|
178
167
|
return scoreApiSelection(task, artifact);
|
|
168
|
+
},
|
|
169
|
+
runtime: {
|
|
170
|
+
output: toollmOutput,
|
|
171
|
+
async preflight() {
|
|
172
|
+
if (fixturesMode) return;
|
|
173
|
+
const dir = toolbenchDir();
|
|
174
|
+
if (!dir) throw new Error("TOOLBENCH_DIR is required. Fix: clone https://github.com/OpenBMB/ToolBench and set TOOLBENCH_DIR=/path/to/ToolBench.");
|
|
175
|
+
await loadOfficialTasks(dir, { limit: 1 });
|
|
176
|
+
},
|
|
177
|
+
async goldArtifact(task) {
|
|
178
|
+
const meta = readMeta(task);
|
|
179
|
+
if (meta.relevantApis.length === 0) return void 0;
|
|
180
|
+
return JSON.stringify({ api_calls: meta.relevantApis.map(([tool_name, api_name]) => ({
|
|
181
|
+
tool_name,
|
|
182
|
+
api_name
|
|
183
|
+
})) }, null, 2);
|
|
184
|
+
}
|
|
179
185
|
}
|
|
180
|
-
};
|
|
186
|
+
});
|
|
181
187
|
}
|
|
182
188
|
export { createToolLlmAdapter, toollmOutput };
|
|
183
189
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"toollm.js","names":[],"sources":["../../src/benchmarks/toollm.ts"],"sourcesContent":["/**\n * ToolLLM/ToolBench adapter.\n *\n * ToolBench task loading is useful for breadth, but the official ToolEval pass\n * rate evaluator is LLM-based and stochastic. This adapter therefore scores\n * only ToolBench's deterministic API-selection labels (`relevant APIs`). It\n * never records a full ToolEval pass-rate score.\n */\n\nimport { readFile } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport type { OutputAdapter } from '@tangle-network/agent-runtime/kernel'\nimport { benchRoot } from './_harness'\nimport type { BenchmarkAdapter, BenchScore, BenchTask, LoadOptions } from './types'\n\nconst FIXTURES = join(benchRoot, 'fixtures', 'toollm.json')\nconst DEFAULT_QUERY_REL = join('data_example', 'instruction', 'G1_query.json')\n\ninterface ToolApi {\n category_name?: string\n tool_name: string\n api_name: string\n api_description?: string\n required_parameters?: unknown[]\n optional_parameters?: unknown[]\n method?: string\n}\n\ninterface ToolBenchRow {\n query_id: number | string\n query: string\n api_list?: ToolApi[]\n 'relevant APIs'?: Array<[string, string]>\n}\n\ninterface ToolBenchMeta {\n queryId: string\n apiList: ToolApi[]\n relevantApis: Array<[string, string]>\n deterministicJudge: 'api-selection'\n}\n\nconst toolbenchDir = (): string | undefined => process.env.TOOLBENCH_DIR\nconst queryFile = (dir: string): string => process.env.TOOLLM_QUERY_FILE ?? join(dir, DEFAULT_QUERY_REL)\n\nexport const toollmOutput: 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 return text.trim()\n },\n}\n\nfunction rowToTask(row: ToolBenchRow): BenchTask {\n const relevantApis = normalizeApiPairs(row['relevant APIs'] ?? [])\n const meta: ToolBenchMeta = {\n queryId: String(row.query_id),\n apiList: row.api_list ?? [],\n relevantApis,\n deterministicJudge: 'api-selection',\n }\n return {\n id: String(row.query_id),\n prompt: [\n 'Solve this ToolLLM/ToolBench API-use task.',\n 'Use only the listed APIs/tools and return the completed tool-use trace plus final answer.',\n '',\n `Query: ${row.query}`,\n '',\n `Available APIs: ${JSON.stringify(row.api_list ?? [], null, 2)}`,\n '',\n 'Return the APIs you used as JSON: {\"api_calls\":[{\"tool_name\":\"...\",\"api_name\":\"...\"}]}.',\n ].join('\\n'),\n metadata: meta as unknown as Record<string, unknown>,\n }\n}\n\nfunction normalizeApiPart(value: string): string {\n return value.toLowerCase().replace(/[^a-z0-9]+/g, '')\n}\n\nfunction apiKey(pair: readonly [string, string]): string {\n return `${normalizeApiPart(pair[0])}.${normalizeApiPart(pair[1])}`\n}\n\nfunction normalizeApiPairs(value: unknown): Array<[string, string]> {\n if (!Array.isArray(value)) return []\n const out: Array<[string, string]> = []\n for (const item of value) {\n if (Array.isArray(item) && typeof item[0] === 'string' && typeof item[1] === 'string') {\n out.push([item[0], item[1]])\n } else if (\n item && typeof item === 'object'\n && typeof (item as { tool_name?: unknown }).tool_name === 'string'\n && typeof (item as { api_name?: unknown }).api_name === 'string'\n ) {\n out.push([(item as { tool_name: string }).tool_name, (item as { api_name: string }).api_name])\n }\n }\n return out\n}\n\nfunction readMeta(task: BenchTask): ToolBenchMeta {\n const md = task.metadata\n if (!md || !Array.isArray(md.relevantApis)) {\n throw new Error(`ToolLLM task ${task.id} missing metadata — loadTasks did not populate deterministic API-selection labels`)\n }\n return md as unknown as ToolBenchMeta\n}\n\nfunction selectRows(rows: ToolBenchRow[], opts: LoadOptions): BenchTask[] {\n let tasks = rows.map(rowToTask)\n if (opts.ids) {\n const want = new Set(opts.ids)\n tasks = tasks.filter((task) => want.has(task.id))\n } else if (opts.limit !== undefined) {\n tasks = tasks.slice(0, opts.limit)\n }\n if (tasks.length === 0) throw new Error(`ToolLLM: no tasks matched ${JSON.stringify(opts)}`)\n return tasks\n}\n\nfunction assertDeterministicSubset(tasks: readonly BenchTask[], source: string): void {\n const missing = tasks.filter((task) => readMeta(task).relevantApis.length === 0).map((task) => task.id)\n if (missing.length > 0) {\n throw new Error(\n `ToolLLM deterministic API-selection labels missing for ${missing.length}/${tasks.length} task(s) from ${source}: ${missing.slice(0, 5).join(', ')}. ` +\n 'Use a ToolBench query file that includes \"relevant APIs\" labels, or do not score ToolLLM in agent-bench.',\n )\n }\n}\n\nasync function loadFixtures(opts: LoadOptions): Promise<BenchTask[]> {\n const rows = JSON.parse(await readFile(FIXTURES, 'utf8')) as ToolBenchRow[]\n console.warn(`[toollm] TOOLLM_FIXTURES=1 — loading ${rows.length} adapter fixtures`)\n const tasks = selectRows(rows, opts)\n assertDeterministicSubset(tasks, FIXTURES)\n return tasks\n}\n\nasync function loadOfficialTasks(dir: string, opts: LoadOptions): Promise<BenchTask[]> {\n const source = queryFile(dir)\n const tasks = selectRows(JSON.parse(await readFile(source, 'utf8')) as ToolBenchRow[], opts)\n assertDeterministicSubset(tasks, source)\n return tasks\n}\n\nfunction extractJsonBlock(text: string): unknown {\n const fences = [...text.matchAll(/```(?:json)?\\s*\\n([\\s\\S]*?)```/g)]\n const raw = (fences.at(-1)?.[1] ?? text).trim()\n try {\n return JSON.parse(raw)\n } catch {\n return undefined\n }\n}\n\ninterface ExtractedApis {\n pairs: Array<[string, string]>\n source: 'structured-json' | 'text-mention'\n}\n\nfunction extractCalledApis(text: string, expected: readonly [string, string][]): ExtractedApis {\n const parsed = extractJsonBlock(text)\n if (parsed && typeof parsed === 'object') {\n const raw = parsed as Record<string, unknown>\n const fromApiCalls = normalizeApiPairs(raw.api_calls)\n if (fromApiCalls.length > 0) return { pairs: fromApiCalls, source: 'structured-json' }\n const fromCalls = normalizeApiPairs(raw.calls)\n if (fromCalls.length > 0) return { pairs: fromCalls, source: 'structured-json' }\n }\n\n const lower = text.toLowerCase()\n return {\n pairs: expected.filter(([tool, api]) => {\n const toolNeedle = normalizeApiPart(tool)\n const apiNeedle = normalizeApiPart(api)\n const compactText = lower.replace(/[^a-z0-9]+/g, '')\n return compactText.includes(`${toolNeedle}${apiNeedle}`) || (lower.includes(tool.toLowerCase()) && lower.includes(api.toLowerCase()))\n }),\n source: 'text-mention',\n }\n}\n\nfunction scoreApiSelection(task: BenchTask, artifact: string): BenchScore {\n const meta = readMeta(task)\n if (meta.relevantApis.length === 0) {\n throw new Error(`ToolLLM task ${task.id} has no deterministic API-selection labels; refusing to score`)\n }\n const expected = new Set(meta.relevantApis.map(apiKey))\n const extracted = extractCalledApis(artifact, meta.relevantApis)\n const calledPairs = extracted.pairs\n const called = new Set(calledPairs.map(apiKey))\n const truePositives = [...called].filter((key) => expected.has(key)).length\n const precision = called.size === 0 ? 0 : truePositives / called.size\n const recall = truePositives / expected.size\n const score = expected.size === 0 ? 0 : recall\n const resolved = extracted.source === 'structured-json' && recall === 1 && precision === 1\n return {\n resolved,\n score,\n detail: JSON.stringify({\n scoring: 'api-selection-only',\n extractionSource: extracted.source,\n queryId: meta.queryId,\n expected: meta.relevantApis,\n called: calledPairs,\n precision,\n recall,\n fullToolEvalScore: null,\n }),\n }\n}\n\nexport function createToolLlmAdapter(): BenchmarkAdapter {\n const fixturesMode = process.env.TOOLLM_FIXTURES === '1'\n\n return {\n name: 'toollm',\n output: toollmOutput,\n\n async preflight() {\n if (fixturesMode) return\n const dir = toolbenchDir()\n if (!dir) {\n throw new Error('TOOLBENCH_DIR is required. Fix: clone https://github.com/OpenBMB/ToolBench and set TOOLBENCH_DIR=/path/to/ToolBench.')\n }\n await loadOfficialTasks(dir, { limit: 1 })\n },\n\n async loadTasks(opts: LoadOptions = {}) {\n if (fixturesMode) return loadFixtures(opts)\n const dir = toolbenchDir()\n if (!dir) throw new Error('TOOLBENCH_DIR is required to load ToolLLM tasks')\n return loadOfficialTasks(dir, opts)\n },\n\n async goldArtifact(task: BenchTask) {\n const meta = readMeta(task)\n if (meta.relevantApis.length === 0) return undefined\n return JSON.stringify({\n api_calls: meta.relevantApis.map(([tool_name, api_name]) => ({ tool_name, api_name })),\n }, null, 2)\n },\n\n async judge(task: BenchTask, artifact: string): Promise<BenchScore> {\n return scoreApiSelection(task, artifact)\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;AAeA,MAAM,WAAW,KAAK,WAAW,YAAY,aAAa;AAC1D,MAAM,oBAAoB,KAAK,gBAAgB,eAAe,eAAe;AA0B7E,MAAM,qBAAyC,QAAQ,IAAI;AAC3D,MAAM,aAAa,QAAwB,QAAQ,IAAI,qBAAqB,KAAK,KAAK,iBAAiB;AAEvG,MAAa,eAAsC,EACjD,MAAM,QAAQ;CACZ,IAAI,OAAO;CACX,KAAK,MAAM,MAAM,QAAQ;EACvB,MAAM,IAAK,IAA2C;EACtD,MAAM,IAAI,GAAG,aAAa,GAAG,QAAQ,GAAG;EACxC,IAAI,OAAO,MAAM,YAAY,EAAE,SAAS,GAAG,OAAO;CACpD;CACA,OAAO,KAAK,KAAK;AACnB,EACF;AAEA,SAAS,UAAU,KAA8B;CAC/C,MAAM,eAAe,kBAAkB,IAAI,oBAAoB,CAAC,CAAC;CACjE,MAAM,OAAsB;EAC1B,SAAS,OAAO,IAAI,QAAQ;EAC5B,SAAS,IAAI,YAAY,CAAC;EAC1B;EACA,oBAAoB;CACtB;CACA,OAAO;EACL,IAAI,OAAO,IAAI,QAAQ;EACvB,QAAQ;GACN;GACA;GACA;GACA,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A,mBAAmB;EACrB,CAAC;CACH;AACF;AAEA,SAAgB,uBAAyC;CACvD,MAAM,eAAe,QAAQ,IAAI,oBAAoB;CAErD,OAAO;EACL,MAAM;EACN,QAAQ;EAER,MAAM,YAAY;GAChB,IAAI,cAAc;GAClB,MAAM,MAAM,aAAa;GACzB,IAAI,CAAC,KACH,MAAM,IAAI,MAAM,sHAAsH;GAExI,MAAM,kBAAkB,KAAK,EAAE,OAAO,EAAE,CAAC;EAC3C;EAEA,MAAM,UAAU,OAAoB,CAAC,GAAG;GACtC,IAAI,cAAc,OAAO,aAAa,IAAI;GAC1C,MAAM,MAAM,aAAa;GACzB,IAAI,CAAC,KAAK,MAAM,IAAI,MAAM,iDAAiD;GAC3E,OAAO,kBAAkB,KAAK,IAAI;EACpC;EAEA,MAAM,aAAa,MAAiB;GAClC,MAAM,OAAO,SAAS,IAAI;GAC1B,IAAI,KAAK,aAAa,WAAW,GAAG,OAAO,KAAA;GAC3C,OAAO,KAAK,UAAU,EACpB,WAAW,KAAK,aAAa,KAAK,CAAC,WAAW,eAAe;IAAE;IAAW;GAAS,EAAE,EACvF,GAAG,MAAM,CAAC;EACZ;EAEA,MAAM,MAAM,MAAiB,UAAuC;GAClE,OAAO,kBAAkB,MAAM,QAAQ;EACzC;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"toollm.js","names":[],"sources":["../../src/benchmarks/toollm.ts"],"sourcesContent":["/**\n * ToolLLM/ToolBench adapter.\n *\n * ToolBench task loading is useful for breadth, but the official ToolEval pass\n * rate evaluator is LLM-based and stochastic. This adapter therefore scores\n * only ToolBench's deterministic API-selection labels (`relevant APIs`). It\n * never records a full ToolEval pass-rate score.\n */\n\nimport { readFile } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport type { OutputAdapter } from '@tangle-network/agent-runtime/kernel'\nimport { benchRoot } from './_harness'\nimport { type BenchEvaluation, type BenchTask, type LoadOptions, type RuntimeBenchmark, runtimeBenchmark } from './types'\n\nconst FIXTURES = join(benchRoot, 'fixtures', 'toollm.json')\nconst DEFAULT_QUERY_REL = join('data_example', 'instruction', 'G1_query.json')\n\ninterface ToolApi {\n category_name?: string\n tool_name: string\n api_name: string\n api_description?: string\n required_parameters?: unknown[]\n optional_parameters?: unknown[]\n method?: string\n}\n\ninterface ToolBenchRow {\n query_id: number | string\n query: string\n api_list?: ToolApi[]\n 'relevant APIs'?: Array<[string, string]>\n}\n\ninterface ToolBenchMeta {\n queryId: string\n apiList: ToolApi[]\n relevantApis: Array<[string, string]>\n deterministicJudge: 'api-selection'\n}\n\nconst toolbenchDir = (): string | undefined => process.env.TOOLBENCH_DIR\nconst queryFile = (dir: string): string => process.env.TOOLLM_QUERY_FILE ?? join(dir, DEFAULT_QUERY_REL)\n\nexport const toollmOutput: 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 return text.trim()\n },\n}\n\nfunction rowToTask(row: ToolBenchRow): BenchTask {\n const relevantApis = normalizeApiPairs(row['relevant APIs'] ?? [])\n const meta: ToolBenchMeta = {\n queryId: String(row.query_id),\n apiList: row.api_list ?? [],\n relevantApis,\n deterministicJudge: 'api-selection',\n }\n return {\n id: String(row.query_id),\n payload: {\n prompt: [\n 'Solve this ToolLLM/ToolBench API-use task.',\n 'Use only the listed APIs/tools and return the completed tool-use trace plus final answer.',\n '',\n `Query: ${row.query}`,\n '',\n `Available APIs: ${JSON.stringify(row.api_list ?? [], null, 2)}`,\n '',\n 'Return the APIs you used as JSON: {\"api_calls\":[{\"tool_name\":\"...\",\"api_name\":\"...\"}]}.',\n ].join('\\n'),\n },\n metadata: meta as unknown as Record<string, unknown>,\n }\n}\n\nfunction normalizeApiPart(value: string): string {\n return value.toLowerCase().replace(/[^a-z0-9]+/g, '')\n}\n\nfunction apiKey(pair: readonly [string, string]): string {\n return `${normalizeApiPart(pair[0])}.${normalizeApiPart(pair[1])}`\n}\n\nfunction normalizeApiPairs(value: unknown): Array<[string, string]> {\n if (!Array.isArray(value)) return []\n const out: Array<[string, string]> = []\n for (const item of value) {\n if (Array.isArray(item) && typeof item[0] === 'string' && typeof item[1] === 'string') {\n out.push([item[0], item[1]])\n } else if (\n item && typeof item === 'object'\n && typeof (item as { tool_name?: unknown }).tool_name === 'string'\n && typeof (item as { api_name?: unknown }).api_name === 'string'\n ) {\n out.push([(item as { tool_name: string }).tool_name, (item as { api_name: string }).api_name])\n }\n }\n return out\n}\n\nfunction readMeta(task: BenchTask): ToolBenchMeta {\n const md = task.metadata\n if (!md || !Array.isArray(md.relevantApis)) {\n throw new Error(`ToolLLM task ${task.id} missing metadata — loadAll did not populate deterministic API-selection labels`)\n }\n return md as unknown as ToolBenchMeta\n}\n\nfunction selectRows(rows: ToolBenchRow[], opts: LoadOptions): BenchTask[] {\n let tasks = rows.map(rowToTask)\n if (opts.ids) {\n const want = new Set(opts.ids)\n tasks = tasks.filter((task) => want.has(task.id))\n } else if (opts.limit !== undefined) {\n tasks = tasks.slice(0, opts.limit)\n }\n if (tasks.length === 0) throw new Error(`ToolLLM: no tasks matched ${JSON.stringify(opts)}`)\n return tasks\n}\n\nfunction assertDeterministicSubset(tasks: readonly BenchTask[], source: string): void {\n const missing = tasks.filter((task) => readMeta(task).relevantApis.length === 0).map((task) => task.id)\n if (missing.length > 0) {\n throw new Error(\n `ToolLLM deterministic API-selection labels missing for ${missing.length}/${tasks.length} task(s) from ${source}: ${missing.slice(0, 5).join(', ')}. ` +\n 'Use a ToolBench query file that includes \"relevant APIs\" labels, or do not score ToolLLM in agent-bench.',\n )\n }\n}\n\nasync function loadFixtures(opts: LoadOptions): Promise<BenchTask[]> {\n const rows = JSON.parse(await readFile(FIXTURES, 'utf8')) as ToolBenchRow[]\n console.warn(`[toollm] TOOLLM_FIXTURES=1 — loading ${rows.length} adapter fixtures`)\n const tasks = selectRows(rows, opts)\n assertDeterministicSubset(tasks, FIXTURES)\n return tasks\n}\n\nasync function loadOfficialTasks(dir: string, opts: LoadOptions): Promise<BenchTask[]> {\n const source = queryFile(dir)\n const tasks = selectRows(JSON.parse(await readFile(source, 'utf8')) as ToolBenchRow[], opts)\n assertDeterministicSubset(tasks, source)\n return tasks\n}\n\nfunction extractJsonBlock(text: string): unknown {\n const fences = [...text.matchAll(/```(?:json)?\\s*\\n([\\s\\S]*?)```/g)]\n const raw = (fences.at(-1)?.[1] ?? text).trim()\n try {\n return JSON.parse(raw)\n } catch {\n return undefined\n }\n}\n\ninterface ExtractedApis {\n pairs: Array<[string, string]>\n source: 'structured-json' | 'text-mention'\n}\n\nfunction extractCalledApis(text: string, expected: readonly [string, string][]): ExtractedApis {\n const parsed = extractJsonBlock(text)\n if (parsed && typeof parsed === 'object') {\n const raw = parsed as Record<string, unknown>\n const fromApiCalls = normalizeApiPairs(raw.api_calls)\n if (fromApiCalls.length > 0) return { pairs: fromApiCalls, source: 'structured-json' }\n const fromCalls = normalizeApiPairs(raw.calls)\n if (fromCalls.length > 0) return { pairs: fromCalls, source: 'structured-json' }\n }\n\n const lower = text.toLowerCase()\n return {\n pairs: expected.filter(([tool, api]) => {\n const toolNeedle = normalizeApiPart(tool)\n const apiNeedle = normalizeApiPart(api)\n const compactText = lower.replace(/[^a-z0-9]+/g, '')\n return compactText.includes(`${toolNeedle}${apiNeedle}`) || (lower.includes(tool.toLowerCase()) && lower.includes(api.toLowerCase()))\n }),\n source: 'text-mention',\n }\n}\n\nfunction scoreApiSelection(task: BenchTask, artifact: string): BenchEvaluation {\n const meta = readMeta(task)\n if (meta.relevantApis.length === 0) {\n throw new Error(`ToolLLM task ${task.id} has no deterministic API-selection labels; refusing to score`)\n }\n const expected = new Set(meta.relevantApis.map(apiKey))\n const extracted = extractCalledApis(artifact, meta.relevantApis)\n const calledPairs = extracted.pairs\n const called = new Set(calledPairs.map(apiKey))\n const truePositives = [...called].filter((key) => expected.has(key)).length\n const precision = called.size === 0 ? 0 : truePositives / called.size\n const recall = truePositives / expected.size\n const score = expected.size === 0 ? 0 : recall\n const resolved = extracted.source === 'structured-json' && recall === 1 && precision === 1\n const raw = {\n scoring: 'api-selection-only',\n extractionSource: extracted.source,\n queryId: meta.queryId,\n expected: meta.relevantApis,\n called: calledPairs,\n precision,\n recall,\n fullToolEvalScore: null,\n }\n return {\n passed: resolved,\n score,\n notes: JSON.stringify(raw),\n raw,\n }\n}\n\nexport function createToolLlmAdapter(): RuntimeBenchmark {\n const fixturesMode = process.env.TOOLLM_FIXTURES === '1'\n\n return runtimeBenchmark({\n id: 'toollm',\n\n async loadAll(opts: LoadOptions = {}) {\n if (fixturesMode) return loadFixtures(opts)\n const dir = toolbenchDir()\n if (!dir) throw new Error('TOOLBENCH_DIR is required to load ToolLLM tasks')\n return loadOfficialTasks(dir, opts)\n },\n\n async evaluate(task: BenchTask, artifact: string): Promise<BenchEvaluation> {\n return scoreApiSelection(task, artifact)\n },\n\n runtime: {\n output: toollmOutput,\n\n async preflight() {\n if (fixturesMode) return\n const dir = toolbenchDir()\n if (!dir) {\n throw new Error('TOOLBENCH_DIR is required. Fix: clone https://github.com/OpenBMB/ToolBench and set TOOLBENCH_DIR=/path/to/ToolBench.')\n }\n await loadOfficialTasks(dir, { limit: 1 })\n },\n\n async goldArtifact(task: BenchTask) {\n const meta = readMeta(task)\n if (meta.relevantApis.length === 0) return undefined\n return JSON.stringify({\n api_calls: meta.relevantApis.map(([tool_name, api_name]) => ({ tool_name, api_name })),\n }, null, 2)\n },\n },\n })\n}\n"],"mappings":";;;;;;;;;;;;;AAeA,MAAM,WAAW,KAAK,WAAW,YAAY,aAAa;AAC1D,MAAM,oBAAoB,KAAK,gBAAgB,eAAe,eAAe;AA0B7E,MAAM,qBAAyC,QAAQ,IAAI;AAC3D,MAAM,aAAa,QAAwB,QAAQ,IAAI,qBAAqB,KAAK,KAAK,iBAAiB;AAEvG,MAAa,eAAsC,EACjD,MAAM,QAAQ;CACZ,IAAI,OAAO;CACX,KAAK,MAAM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a,KAAK,CAAC,WAAW,eAAe;KAAE;KAAW;IAAS,EAAE,EACvF,GAAG,MAAM,CAAC;GACZ;EACF;CACF,CAAC;AACH"}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import {
|
|
2
|
-
export declare function createTrataHedgeAdapter():
|
|
1
|
+
import { RuntimeBenchmark } from "./types.js";
|
|
2
|
+
export declare function createTrataHedgeAdapter(): RuntimeBenchmark;
|
|
3
3
|
//# sourceMappingURL=trata-hedge.d.ts.map
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { t as runBenchRouterTurn } from "../router-turn-DNbQ_GjQ.js";
|
|
2
|
+
import { runtimeBenchmark } from "./types.js";
|
|
2
3
|
import { join } from "node:path";
|
|
3
4
|
import { readFileSync, readdirSync, statSync } from "node:fs";
|
|
4
5
|
// src/benchmarks/trata-hedge.ts
|
|
@@ -21,8 +22,8 @@ import { readFileSync, readdirSync, statSync } from "node:fs";
|
|
|
21
22
|
* Task 2: per-move coverage check (ground truth + agent answer + flagged claims)
|
|
22
23
|
* Task 3: synthesis check (ground truth + agent answer)
|
|
23
24
|
* Score 0–4: themes_covered == num_themes && synthesis → 4, all themes → 3,
|
|
24
|
-
* ≥2 themes → 2, ≥1 theme → 1, else → 0. Normalized to 0..1 for
|
|
25
|
-
*
|
|
25
|
+
* ≥2 themes → 2, ≥1 theme → 1, else → 0. Normalized to 0..1 for BenchEvaluation;
|
|
26
|
+
* passed = score 4 (sparse reward).
|
|
26
27
|
*
|
|
27
28
|
* Requires TANGLE_API_KEY and TRATA_BENCH_ROOT=/tmp/trata-hedge-bench.
|
|
28
29
|
* Clone: git clone --depth 1 https://github.com/Trata-Inc/trata-hedge-bench /tmp/trata-hedge-bench
|
|
@@ -36,7 +37,7 @@ const WORKER_SUFFIX = [
|
|
|
36
37
|
"Write your complete analysis to the text block that starts with \"ANALYSIS:\" on a line by itself.",
|
|
37
38
|
"Take a clear position on the topic. Every factual claim must name the file it comes from."
|
|
38
39
|
].join("\n");
|
|
39
|
-
const JUDGE_MODEL = "gemini-
|
|
40
|
+
const JUDGE_MODEL = "gemini-3.1-pro-preview";
|
|
40
41
|
function readText(p, maxBytes = MAX_FILE_BYTES) {
|
|
41
42
|
try {
|
|
42
43
|
const buf = readFileSync(p);
|
|
@@ -155,10 +156,8 @@ async function callJudge(router, prompt, maxAttempts = 2) {
|
|
|
155
156
|
model: {
|
|
156
157
|
provider: "tangle-router",
|
|
157
158
|
default: router.model,
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
maxTokens: Number(process.env.JUDGE_MAX_TOKENS ?? 16384)
|
|
161
|
-
}
|
|
159
|
+
maxVisibleOutputTokens: Number(process.env.JUDGE_MAX_TOKENS ?? 16384),
|
|
160
|
+
metadata: { temperature: 0 }
|
|
162
161
|
}
|
|
163
162
|
}
|
|
164
163
|
}, prompt)).finalText;
|
|
@@ -186,11 +185,15 @@ async function task3SynthesisCheck(meta, answer, router) {
|
|
|
186
185
|
return await callJudge(router, meta.gradingTask3.replace("{ground_truth}", meta.groundTruth).replace("{agent_answer}", answer)) ?? { synthesis_found: null };
|
|
187
186
|
}
|
|
188
187
|
async function runTriataJudge(meta, answer, router) {
|
|
189
|
-
if (!answer.trim())
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
188
|
+
if (!answer.trim()) {
|
|
189
|
+
const raw = { error: "empty answer" };
|
|
190
|
+
return {
|
|
191
|
+
passed: false,
|
|
192
|
+
score: 0,
|
|
193
|
+
notes: JSON.stringify(raw),
|
|
194
|
+
raw
|
|
195
|
+
};
|
|
196
|
+
}
|
|
194
197
|
const t1 = await task1HallucinationCheck(meta, answer, router);
|
|
195
198
|
const flaggedClaims = t1.unverifiable_claims ?? [];
|
|
196
199
|
const [t2, t3] = await Promise.all([task2PerMoveCheck(meta, answer, flaggedClaims, router), task3SynthesisCheck(meta, answer, router)]);
|
|
@@ -218,19 +221,20 @@ async function runTriataJudge(meta, answer, router) {
|
|
|
218
221
|
else if (themesHit.length >= 1) rawScore = 1;
|
|
219
222
|
else rawScore = 0;
|
|
220
223
|
const hallRaw = t1.hallucinations_detected;
|
|
221
|
-
const
|
|
224
|
+
const raw = {
|
|
225
|
+
rawScore,
|
|
226
|
+
themesHit,
|
|
227
|
+
themesMissed,
|
|
228
|
+
hallucinations: hallRaw === true || hallRaw === "true",
|
|
229
|
+
unverifiableClaims: flaggedClaims.length,
|
|
230
|
+
synthesis: synth ?? null,
|
|
231
|
+
judgeModel: router.model
|
|
232
|
+
};
|
|
222
233
|
return {
|
|
223
|
-
|
|
234
|
+
passed: rawScore === 4,
|
|
224
235
|
score: numThemes > 0 ? rawScore / 4 : 0,
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
themesHit,
|
|
228
|
-
themesMissed,
|
|
229
|
-
hallucinations,
|
|
230
|
-
unverifiableClaims: flaggedClaims.length,
|
|
231
|
-
synthesis: synth ?? null,
|
|
232
|
-
judgeModel: router.model
|
|
233
|
-
})
|
|
236
|
+
notes: JSON.stringify(raw),
|
|
237
|
+
raw
|
|
234
238
|
};
|
|
235
239
|
}
|
|
236
240
|
function benchRoot() {
|
|
@@ -267,7 +271,7 @@ function loadTask(taskId) {
|
|
|
267
271
|
return {
|
|
268
272
|
task: {
|
|
269
273
|
id: taskId,
|
|
270
|
-
prompt,
|
|
274
|
+
payload: { prompt },
|
|
271
275
|
metadata: meta
|
|
272
276
|
},
|
|
273
277
|
meta
|
|
@@ -299,22 +303,9 @@ function extractAnalysis(artifact) {
|
|
|
299
303
|
return "";
|
|
300
304
|
}
|
|
301
305
|
function createTrataHedgeAdapter() {
|
|
302
|
-
return {
|
|
303
|
-
|
|
304
|
-
async
|
|
305
|
-
const root = benchRoot();
|
|
306
|
-
const envDir = join(root, "environments");
|
|
307
|
-
try {
|
|
308
|
-
if (!statSync(envDir).isDirectory()) throw new Error("not a directory");
|
|
309
|
-
} catch {
|
|
310
|
-
throw new Error(`Trata hedge-bench not found at ${envDir}.\nClone: git clone --depth 1 https://github.com/Trata-Inc/trata-hedge-bench ${root}`);
|
|
311
|
-
}
|
|
312
|
-
judgeRouter();
|
|
313
|
-
const ids = listTaskIds(root);
|
|
314
|
-
if (ids.length === 0) throw new Error(`No task directories found under ${envDir}`);
|
|
315
|
-
console.warn(`[trata-hedge] ${ids.length} tasks loaded from ${root}. Worker model reads embedded data inline (Harbor/Docker not required). Judge uses ${process.env.JUDGE_MODEL ?? JUDGE_MODEL} via Tangle router.`);
|
|
316
|
-
},
|
|
317
|
-
async loadTasks(opts = {}) {
|
|
306
|
+
return runtimeBenchmark({
|
|
307
|
+
id: "trata-hedge",
|
|
308
|
+
async loadAll(opts = {}) {
|
|
318
309
|
let ids = listTaskIds(benchRoot());
|
|
319
310
|
if (opts.ids) {
|
|
320
311
|
const want = new Set(opts.ids);
|
|
@@ -322,11 +313,26 @@ function createTrataHedgeAdapter() {
|
|
|
322
313
|
} else if (opts.limit !== void 0) ids = ids.slice(0, opts.limit);
|
|
323
314
|
return ids.map((id) => loadTask(id).task);
|
|
324
315
|
},
|
|
325
|
-
async
|
|
326
|
-
async judge(task, artifact) {
|
|
316
|
+
async evaluate(task, artifact) {
|
|
327
317
|
return runTriataJudge(readMeta(task), extractAnalysis(artifact), judgeRouter());
|
|
318
|
+
},
|
|
319
|
+
runtime: {
|
|
320
|
+
async preflight() {
|
|
321
|
+
const root = benchRoot();
|
|
322
|
+
const envDir = join(root, "environments");
|
|
323
|
+
try {
|
|
324
|
+
if (!statSync(envDir).isDirectory()) throw new Error("not a directory");
|
|
325
|
+
} catch {
|
|
326
|
+
throw new Error(`Trata hedge-bench not found at ${envDir}.\nClone: git clone --depth 1 https://github.com/Trata-Inc/trata-hedge-bench ${root}`);
|
|
327
|
+
}
|
|
328
|
+
judgeRouter();
|
|
329
|
+
const ids = listTaskIds(root);
|
|
330
|
+
if (ids.length === 0) throw new Error(`No task directories found under ${envDir}`);
|
|
331
|
+
console.warn(`[trata-hedge] ${ids.length} tasks loaded from ${root}. Worker model reads embedded data inline (Harbor/Docker not required). Judge uses ${process.env.JUDGE_MODEL ?? JUDGE_MODEL} via Tangle router.`);
|
|
332
|
+
},
|
|
333
|
+
async goldArtifact(_task) {}
|
|
328
334
|
}
|
|
329
|
-
};
|
|
335
|
+
});
|
|
330
336
|
}
|
|
331
337
|
export { createTrataHedgeAdapter };
|
|
332
338
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"trata-hedge.js","names":[],"sources":["../../src/benchmarks/trata-hedge.ts"],"sourcesContent":["/**\n * Trata Hedge-Bench adapter (Trata-Inc/trata-hedge-bench). 102 financial\n * analysis tasks across 6 domains (private equity, managed care, industrials,\n * vertical SaaS, REITs, insurance). Each task bundles real earnings-call\n * transcripts, financial statements, press releases, and SEC filings under\n * `environment/data/`; the agent must produce a grounded analysis citing those\n * files.\n *\n * Harbor architecture: the original benchmark runs each task in a Docker\n * container with file-read tools. This adapter skips Harbor and embeds the data\n * files directly in the worker prompt so any router backend can score it. Large\n * files (> 30 KB) are truncated to fit within model context limits. The judge\n * reads the actual files from disk for citation verification.\n *\n * Judge: a 3-stage LLM cascade faithful to grade.py —\n * Task 1: hallucination check (cited-file context + agent answer)\n * Task 2: per-move coverage check (ground truth + agent answer + flagged claims)\n * Task 3: synthesis check (ground truth + agent answer)\n * Score 0–4: themes_covered == num_themes && synthesis → 4, all themes → 3,\n * ≥2 themes → 2, ≥1 theme → 1, else → 0. Normalized to 0..1 for BenchScore;\n * resolved = score 4 (sparse reward).\n *\n * Requires TANGLE_API_KEY and TRATA_BENCH_ROOT=/tmp/trata-hedge-bench.\n * Clone: git clone --depth 1 https://github.com/Trata-Inc/trata-hedge-bench /tmp/trata-hedge-bench\n */\n\nimport { readdirSync, readFileSync, statSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { runBenchRouterTurn } from '../router-turn'\nimport type { BenchmarkAdapter, BenchScore, BenchTask, LoadOptions } from './types'\n\nconst DEFAULT_BENCH_ROOT = '/tmp/trata-hedge-bench'\nconst MAX_FILE_BYTES = 8_000\n// Sandbox API rejects messages > 100K chars; instruction + suffix adds ~500 chars overhead.\nconst MAX_DATA_CHARS = 85_000\nconst WORKER_SUFFIX = [\n '',\n 'The data files above are your only source. Cite each claim with the filename that supports it.',\n 'Write your complete analysis to the text block that starts with \"ANALYSIS:\" on a line by itself.',\n 'Take a clear position on the topic. Every factual claim must name the file it comes from.',\n].join('\\n')\n\n// Judge model: Gemini 2.5 Pro via router (matches gemini-3.1-pro-preview tier used by grade.py).\nconst JUDGE_MODEL = 'gemini-2.5-pro'\n\ninterface TrataTaskMeta {\n taskDir: string\n taskId: string\n dataDir: string\n groundTruth: string\n gradingTask1: string\n gradingTask2: string\n gradingTask3: string\n /** [(label, n_moves)] in rubric order. */\n themeMoveCounts: Array<{ label: string; nMoves: number }>\n}\n\n// ── file reading helpers ──────────────────────────────────────────────────────\n\nfunction readText(p: string, maxBytes = MAX_FILE_BYTES): string {\n try {\n const buf = readFileSync(p)\n if (buf.length <= maxBytes) return buf.toString('utf8')\n return buf.subarray(0, maxBytes).toString('utf8') + `\\n[… truncated at ${maxBytes} bytes …]`\n } catch {\n return `[unreadable: ${p}]`\n }\n}\n\nfunction listFilesRec(dir: string): string[] {\n const out: string[] = []\n try {\n for (const name of readdirSync(dir)) {\n const full = join(dir, name)\n try {\n if (statSync(full).isDirectory()) out.push(...listFilesRec(full))\n else out.push(full)\n } catch {\n // skip unreadable entries\n }\n }\n } catch {\n // dir absent\n }\n return out.sort()\n}\n\nfunction buildDataBlock(dataDir: string): string {\n const files = listFilesRec(dataDir)\n if (files.length === 0) return '(no data files found)'\n // Prioritise: company profiles → earnings calls → primary-ticker financials →\n // sec filings → press releases → peers. Stop once total chars hit MAX_DATA_CHARS.\n const priority = (f: string) => {\n if (f.includes('company_profiles')) return 0\n if (f.includes('earnings_call')) return 1\n if (/financials\\/(income|cash_flow|balance)/.test(f) && !/bam_|bx_|kkr_|ares_|cg_|owl_|fsk_|cat_|de_|tdg_|car_/.test(f)) return 2\n if (f.includes('sec_filings')) return 3\n if (f.includes('investor_pres')) return 4\n if (f.includes('press_release')) return 5\n return 6\n }\n const sorted = [...files].sort((a, b) => priority(a) - priority(b) || a.localeCompare(b))\n const blocks: string[] = []\n let total = 0\n for (const f of sorted) {\n const rel = f.slice(dataDir.length + 1)\n const content = readText(f)\n const chunk = `\\n=== FILE: data/${rel} ===\\n${content}`\n if (total + chunk.length > MAX_DATA_CHARS) {\n blocks.push(`\\n[… ${sorted.length - blocks.length} more files omitted to stay within context limit …]`)\n break\n }\n blocks.push(chunk)\n total += chunk.length\n }\n return blocks.join('')\n}\n\nfunction buildCitedDataBlock(answerText: string, dataDir: string): string {\n const files = listFilesRec(dataDir)\n const cited: string[] = []\n for (const f of files) {\n const rel = f.slice(dataDir.length + 1)\n const name = rel.split('/').pop() ?? ''\n if (answerText.includes(rel) || answerText.includes(name)) cited.push(f)\n }\n if (cited.length === 0) {\n return '(The agent did not cite any data files, or no cited file could be located.)'\n }\n const blocks: string[] = []\n for (const f of cited) {\n const rel = f.slice(dataDir.length + 1)\n blocks.push(`\\n=== FILE: data/${rel} ===\\n${readText(f)}`)\n }\n return blocks.join('')\n}\n\n// ── ground-truth parser ───────────────────────────────────────────────────────\n\nfunction parseThemeMoveCounts(groundTruth: string): Array<{ label: string; nMoves: number }> {\n const lines = groundTruth.split('\\n')\n const themeStarts = lines.reduce<number[]>((acc, l, i) => {\n if (/^\\d+\\./.test(l.trim())) acc.push(i)\n return acc\n }, [])\n return themeStarts.map((start, k) => {\n const end = k + 1 < themeStarts.length ? themeStarts[k + 1] : lines.length\n const block = lines.slice(start, end).join('\\n')\n const label = lines[start].replace(/^\\d+\\.\\s*/, '').trim()\n const nMoves = (block.match(/^\\s*\\[[a-z]\\]\\s+/gm) ?? []).length\n return { label, nMoves }\n })\n}\n\nfunction coverageThreshold(nMoves: number): number {\n return Math.max(1, Math.min(nMoves - 1, 3))\n}\n\n// ── router judge calls ────────────────────────────────────────────────────────\n\ninterface JudgeRouter {\n baseUrl: string\n key: string\n model: string\n}\n\nfunction judgeRouter(): JudgeRouter {\n const key = process.env.TANGLE_API_KEY\n if (!key) throw new Error('TANGLE_API_KEY is required for the Trata hedge-bench judge')\n const model = process.env.JUDGE_MODEL ?? JUDGE_MODEL\n const baseUrl = process.env.ROUTER_BASE ?? 'https://router.tangle.tools/v1'\n return { baseUrl, key, model }\n}\n\nfunction parseJsonFallback(raw: string): unknown {\n let s = raw.trim()\n if (s.startsWith('```')) s = s.split('\\n').slice(1).join('\\n')\n if (s.endsWith('```')) s = s.slice(0, s.lastIndexOf('```'))\n s = s.replace(/,(\\s*[}\\]])/g, '$1').trim()\n try {\n return JSON.parse(s)\n } catch {\n try {\n const m = s.match(/\\{[\\s\\S]*\\}/)\n if (m) return JSON.parse(m[0])\n } catch {\n // fallthrough\n }\n }\n return null\n}\n\nasync function callJudge(router: JudgeRouter, prompt: string, maxAttempts = 2): Promise<unknown> {\n for (let i = 0; i < maxAttempts; i++) {\n try {\n const turn = await runBenchRouterTurn(\n {\n routerBaseUrl: router.baseUrl,\n routerKey: router.key,\n profile: {\n name: 'trata-hedge-judge',\n harness: 'cli-base',\n model: {\n provider: 'tangle-router',\n default: router.model,\n metadata: {\n temperature: 0,\n maxTokens: Number(process.env.JUDGE_MAX_TOKENS ?? 16384),\n },\n },\n },\n },\n prompt,\n )\n const content = turn.finalText\n const parsed = parseJsonFallback(content)\n if (parsed !== null) return parsed\n } catch (error) {\n if (i + 1 === maxAttempts) throw error\n }\n }\n return null\n}\n\ninterface Task1Result {\n hallucinations_detected?: boolean | string\n unverifiable_claims?: Array<{ claim: string; cited_file?: string; issue?: string; evidence_check?: string }>\n}\n\ninterface Task2ThemeResult {\n label?: string\n moves_hit?: string[]\n moves_missed?: string[]\n moves_tainted?: string[]\n move_reasoning?: Record<string, string>\n}\n\ninterface Task2Result {\n themes?: Task2ThemeResult[]\n}\n\ninterface Task3Result {\n synthesis_found?: string | null\n}\n\nasync function task1HallucinationCheck(\n meta: TrataTaskMeta,\n answer: string,\n router: JudgeRouter,\n): Promise<Task1Result> {\n const citedBlock = buildCitedDataBlock(answer, meta.dataDir)\n const dataContext =\n 'The block below contains the contents of the data files the agent cited in their answer. ' +\n 'Treat this as the ground truth for factual verification.\\n\\n' +\n `<cited_data>\\n${citedBlock}\\n</cited_data>`\n const prompt = meta.gradingTask1\n .replace('{data_context}', dataContext)\n .replace('{agent_answer}', answer)\n const result = await callJudge(router, prompt)\n return (result as Task1Result) ?? { hallucinations_detected: false, unverifiable_claims: [] }\n}\n\nasync function task2PerMoveCheck(\n meta: TrataTaskMeta,\n answer: string,\n flaggedClaims: Task1Result['unverifiable_claims'],\n router: JudgeRouter,\n): Promise<Task2Result> {\n const claimsBlock =\n flaggedClaims && flaggedClaims.length > 0\n ? JSON.stringify(flaggedClaims, null, 2)\n : '(No claims were flagged as hallucinations.)'\n const prompt = meta.gradingTask2\n .replace('{ground_truth}', meta.groundTruth)\n .replace('{agent_answer}', answer)\n .replace('{flagged_claims_block}', claimsBlock)\n .replace('{num_themes}', String(meta.themeMoveCounts.length))\n const result = await callJudge(router, prompt)\n return (result as Task2Result) ?? { themes: [] }\n}\n\nasync function task3SynthesisCheck(\n meta: TrataTaskMeta,\n answer: string,\n router: JudgeRouter,\n): Promise<Task3Result> {\n const prompt = meta.gradingTask3\n .replace('{ground_truth}', meta.groundTruth)\n .replace('{agent_answer}', answer)\n const result = await callJudge(router, prompt)\n return (result as Task3Result) ?? { synthesis_found: null }\n}\n\nasync function runTriataJudge(meta: TrataTaskMeta, answer: string, router: JudgeRouter): Promise<BenchScore> {\n if (!answer.trim()) {\n return { resolved: false, score: 0, detail: JSON.stringify({ error: 'empty answer' }) }\n }\n\n // Stage 1: hallucination check (serial — feeds into stage 2).\n const t1 = await task1HallucinationCheck(meta, answer, router)\n const flaggedClaims = t1.unverifiable_claims ?? []\n\n // Stages 2 + 3 in parallel.\n const [t2, t3] = await Promise.all([\n task2PerMoveCheck(meta, answer, flaggedClaims, router),\n task3SynthesisCheck(meta, answer, router),\n ])\n\n const judgeThemes = t2.themes ?? []\n const themesHit: string[] = []\n const themesMissed: string[] = []\n\n for (let i = 0; i < meta.themeMoveCounts.length; i++) {\n const { label, nMoves } = meta.themeMoveCounts[i]\n const judge = judgeThemes[i] ?? {}\n const movesHit = (judge.moves_hit ?? []).map((m: string) => m.replace(/[\\[\\]]/g, ''))\n const tainted = new Set((judge.moves_tainted ?? []).map((m: string) => m.replace(/[\\[\\]]/g, '')))\n const validHit = movesHit.filter((m: string) => !tainted.has(m))\n const threshold = coverageThreshold(nMoves)\n if (validHit.length >= threshold) themesHit.push(label)\n else themesMissed.push(label)\n }\n\n const numThemes = meta.themeMoveCounts.length\n const synth = t3.synthesis_found\n const hasSynthesis = typeof synth === 'string' && synth.length > 0 && synth !== 'null'\n\n let rawScore: number\n if (numThemes === 0) rawScore = 0\n else if (themesHit.length === numThemes && hasSynthesis) rawScore = 4\n else if (themesHit.length === numThemes) rawScore = 3\n else if (themesHit.length >= 2) rawScore = 2\n else if (themesHit.length >= 1) rawScore = 1\n else rawScore = 0\n\n const hallRaw = t1.hallucinations_detected\n const hallucinations = hallRaw === true || hallRaw === 'true'\n\n return {\n resolved: rawScore === 4,\n score: numThemes > 0 ? rawScore / 4 : 0,\n detail: JSON.stringify({\n rawScore,\n themesHit,\n themesMissed,\n hallucinations,\n unverifiableClaims: flaggedClaims.length,\n synthesis: synth ?? null,\n judgeModel: router.model,\n }),\n }\n}\n\n// ── task loading ──────────────────────────────────────────────────────────────\n\nfunction benchRoot(): string {\n return process.env.TRATA_BENCH_ROOT ?? DEFAULT_BENCH_ROOT\n}\n\nfunction loadTask(taskId: string): { task: BenchTask; meta: TrataTaskMeta } {\n const taskDir = join(benchRoot(), 'environments', taskId)\n const dataDir = join(taskDir, 'environment', 'data')\n const testsDir = join(taskDir, 'tests')\n\n const instruction = readText(join(taskDir, 'instruction.md'), Infinity)\n const dataBlock = buildDataBlock(dataDir)\n const groundTruth = readText(join(testsDir, 'ground_truth.txt'), Infinity)\n const gradingTask1 = readText(join(testsDir, 'grading_prompt_task1.md'), Infinity)\n const gradingTask2 = readText(join(testsDir, 'grading_prompt_task2.md'), Infinity)\n const gradingTask3 = readText(join(testsDir, 'grading_prompt_task3.md'), Infinity)\n\n const themeMoveCounts = parseThemeMoveCounts(groundTruth)\n\n // Rewrite the instruction so the agent knows data is inline (no /app/data/ FS).\n const prompt = [\n instruction\n .replace(\n \"You are a financial analyst with access to the data in `/app/data/`.\",\n 'You are a financial analyst. The relevant financial data files are provided inline below.',\n )\n .replace(/Write your full analysis to `\\/app\\/answer\\.txt`\\.?/, 'Write your full analysis below.')\n .replace(/`\\/app\\/data\\/`/g, 'the data files below'),\n '',\n '## Data files (inline)',\n dataBlock,\n WORKER_SUFFIX,\n ].join('\\n')\n\n const meta: TrataTaskMeta = {\n taskDir,\n taskId,\n dataDir,\n groundTruth,\n gradingTask1,\n gradingTask2,\n gradingTask3,\n themeMoveCounts,\n }\n\n // Store meta in the BenchTask so the judge can access it without re-reading.\n const task: BenchTask = {\n id: taskId,\n prompt,\n metadata: meta as unknown as Record<string, unknown>,\n }\n\n return { task, meta }\n}\n\nfunction readMeta(task: BenchTask): TrataTaskMeta {\n const md = task.metadata\n if (!md || typeof md.taskDir !== 'string' || typeof md.groundTruth !== 'string') {\n throw new Error(`Trata task ${task.id} missing judge metadata — was it loaded by this adapter?`)\n }\n return md as unknown as TrataTaskMeta\n}\n\n/** List all task ids from the environments directory. */\nfunction listTaskIds(root: string): string[] {\n try {\n return readdirSync(join(root, 'environments'))\n .filter((name) => {\n try {\n return statSync(join(root, 'environments', name)).isDirectory()\n } catch {\n return false\n }\n })\n .sort()\n } catch (err) {\n throw new Error(\n `Trata benchmark environments not found at ${join(root, 'environments')}: ` +\n `${err instanceof Error ? err.message : err}.\\n` +\n `Clone the repo: git clone --depth 1 https://github.com/Trata-Inc/trata-hedge-bench ${root}`,\n )\n }\n}\n\n// ── extract agent analysis from artifact ─────────────────────────────────────\n\nfunction extractAnalysis(artifact: string): string {\n // Model may write \"ANALYSIS:\" as its very first token (no leading newline) or\n // after some preamble. Both are valid; fail-closed on absence.\n if (artifact.startsWith('ANALYSIS:')) return artifact.slice('ANALYSIS:'.length).trim()\n const marker = artifact.indexOf('\\nANALYSIS:')\n if (marker !== -1) return artifact.slice(marker + '\\nANALYSIS:'.length).trim()\n return ''\n}\n\n// ── adapter factory ───────────────────────────────────────────────────────────\n\nexport function createTrataHedgeAdapter(): BenchmarkAdapter {\n return {\n name: 'trata-hedge',\n\n async preflight() {\n const root = benchRoot()\n const envDir = join(root, 'environments')\n try {\n const stat = statSync(envDir)\n if (!stat.isDirectory()) throw new Error('not a directory')\n } catch {\n throw new Error(\n `Trata hedge-bench not found at ${envDir}.\\n` +\n `Clone: git clone --depth 1 https://github.com/Trata-Inc/trata-hedge-bench ${root}`,\n )\n }\n // Validate judge router connectivity.\n judgeRouter()\n const ids = listTaskIds(root)\n if (ids.length === 0) throw new Error(`No task directories found under ${envDir}`)\n console.warn(\n `[trata-hedge] ${ids.length} tasks loaded from ${root}. ` +\n `Worker model reads embedded data inline (Harbor/Docker not required). ` +\n `Judge uses ${process.env.JUDGE_MODEL ?? JUDGE_MODEL} via Tangle router.`,\n )\n },\n\n async loadTasks(opts: LoadOptions = {}): Promise<BenchTask[]> {\n const root = benchRoot()\n let ids = listTaskIds(root)\n if (opts.ids) {\n const want = new Set(opts.ids)\n ids = ids.filter((id) => want.has(id))\n } else if (opts.limit !== undefined) {\n ids = ids.slice(0, opts.limit)\n }\n return ids.map((id) => loadTask(id).task)\n },\n\n async goldArtifact(_task: BenchTask): Promise<string | undefined> {\n // No single gold answer: the score comes from rubric theme coverage, not\n // string-match against a reference response. Return undefined — the bench\n // harness will skip judge self-verification for this adapter.\n return undefined\n },\n\n async judge(task: BenchTask, artifact: string): Promise<BenchScore> {\n const meta = readMeta(task)\n const answer = extractAnalysis(artifact)\n return runTriataJudge(meta, answer, judgeRouter())\n },\n }\n}\n"],"mappings":";;;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,eAAe,YAAY,oBACzD;EACF;EAEA,MAAM,UAAU,OAAoB,CAAC,GAAyB;GAE5D,IAAI,MAAM,YADG,UACY,CAAC;GAC1B,IAAI,KAAK,KAAK;IACZ,MAAM,OAAO,IAAI,IAAI,KAAK,GAAG;IAC7B,MAAM,IAAI,QAAQ,OAAO,KAAK,IAAI,EAAE,CAAC;GACvC,OAAO,IAAI,KAAK,UAAU,KAAA,GACxB,MAAM,IAAI,MAAM,GAAG,KAAK,KAAK;GAE/B,OAAO,IAAI,KAAK,OAAO,SAAS,EAAE,CAAC,CAAC,IAAI;EAC1C;EAEA,MAAM,aAAa,OAA+C,CAKlE;EAEA,MAAM,MAAM,MAAiB,UAAuC;GAGlE,OAAO,eAFM,SAAS,IAEG,GADV,gBAAgB,QACE,GAAG,YAAY,CAAC;EACnD;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"trata-hedge.js","names":[],"sources":["../../src/benchmarks/trata-hedge.ts"],"sourcesContent":["/**\n * Trata Hedge-Bench adapter (Trata-Inc/trata-hedge-bench). 102 financial\n * analysis tasks across 6 domains (private equity, managed care, industrials,\n * vertical SaaS, REITs, insurance). Each task bundles real earnings-call\n * transcripts, financial statements, press releases, and SEC filings under\n * `environment/data/`; the agent must produce a grounded analysis citing those\n * files.\n *\n * Harbor architecture: the original benchmark runs each task in a Docker\n * container with file-read tools. This adapter skips Harbor and embeds the data\n * files directly in the worker prompt so any router backend can score it. Large\n * files (> 30 KB) are truncated to fit within model context limits. The judge\n * reads the actual files from disk for citation verification.\n *\n * Judge: a 3-stage LLM cascade faithful to grade.py —\n * Task 1: hallucination check (cited-file context + agent answer)\n * Task 2: per-move coverage check (ground truth + agent answer + flagged claims)\n * Task 3: synthesis check (ground truth + agent answer)\n * Score 0–4: themes_covered == num_themes && synthesis → 4, all themes → 3,\n * ≥2 themes → 2, ≥1 theme → 1, else → 0. Normalized to 0..1 for BenchEvaluation;\n * passed = score 4 (sparse reward).\n *\n * Requires TANGLE_API_KEY and TRATA_BENCH_ROOT=/tmp/trata-hedge-bench.\n * Clone: git clone --depth 1 https://github.com/Trata-Inc/trata-hedge-bench /tmp/trata-hedge-bench\n */\n\nimport { readdirSync, readFileSync, statSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { runBenchRouterTurn } from '../router-turn'\nimport { type BenchEvaluation, type BenchTask, type LoadOptions, type RuntimeBenchmark, runtimeBenchmark } from './types'\n\nconst DEFAULT_BENCH_ROOT = '/tmp/trata-hedge-bench'\nconst MAX_FILE_BYTES = 8_000\n// Sandbox API rejects messages > 100K chars; instruction + suffix adds ~500 chars overhead.\nconst MAX_DATA_CHARS = 85_000\nconst WORKER_SUFFIX = [\n '',\n 'The data files above are your only source. Cite each claim with the filename that supports it.',\n 'Write your complete analysis to the text block that starts with \"ANALYSIS:\" on a line by itself.',\n 'Take a clear position on the topic. Every factual claim must name the file it comes from.',\n].join('\\n')\n\n// Judge model: Gemini 3.1 Pro preview via router, the model grade.py uses.\nconst JUDGE_MODEL = 'gemini-3.1-pro-preview'\n\ninterface TrataTaskMeta {\n taskDir: string\n taskId: string\n dataDir: string\n groundTruth: string\n gradingTask1: string\n gradingTask2: string\n gradingTask3: string\n /** [(label, n_moves)] in rubric order. */\n themeMoveCounts: Array<{ label: string; nMoves: number }>\n}\n\n// ── file reading helpers ──────────────────────────────────────────────────────\n\nfunction readText(p: string, maxBytes = MAX_FILE_BYTES): string {\n try {\n const buf = readFileSync(p)\n if (buf.length <= maxBytes) return buf.toString('utf8')\n return buf.subarray(0, maxBytes).toString('utf8') + `\\n[… truncated at ${maxBytes} bytes …]`\n } catch {\n return `[unreadable: ${p}]`\n }\n}\n\nfunction listFilesRec(dir: string): string[] {\n const out: string[] = []\n try {\n for (const name of readdirSync(dir)) {\n const full = join(dir, name)\n try {\n if (statSync(full).isDirectory()) out.push(...listFilesRec(full))\n else out.push(full)\n } catch {\n // skip unreadable entries\n }\n }\n } catch {\n // dir absent\n }\n return out.sort()\n}\n\nfunction buildDataBlock(dataDir: string): string {\n const files = listFilesRec(dataDir)\n if (files.length === 0) return '(no data files found)'\n // Prioritise: company profiles → earnings calls → primary-ticker financials →\n // sec filings → press releases → peers. Stop once total chars hit MAX_DATA_CHARS.\n const priority = (f: string) => {\n if (f.includes('company_profiles')) return 0\n if (f.includes('earnings_call')) return 1\n if (/financials\\/(income|cash_flow|balance)/.test(f) && !/bam_|bx_|kkr_|ares_|cg_|owl_|fsk_|cat_|de_|tdg_|car_/.test(f)) return 2\n if (f.includes('sec_filings')) return 3\n if (f.includes('investor_pres')) return 4\n if (f.includes('press_release')) return 5\n return 6\n }\n const sorted = [...files].sort((a, b) => priority(a) - priority(b) || a.localeCompare(b))\n const blocks: string[] = []\n let total = 0\n for (const f of sorted) {\n const rel = f.slice(dataDir.length + 1)\n const content = readText(f)\n const chunk = `\\n=== FILE: data/${rel} ===\\n${content}`\n if (total + chunk.length > MAX_DATA_CHARS) {\n blocks.push(`\\n[… ${sorted.length - blocks.length} more files omitted to stay within context limit …]`)\n break\n }\n blocks.push(chunk)\n total += chunk.length\n }\n return blocks.join('')\n}\n\nfunction buildCitedDataBlock(answerText: string, dataDir: string): string {\n const files = listFilesRec(dataDir)\n const cited: string[] = []\n for (const f of files) {\n const rel = f.slice(dataDir.length + 1)\n const name = rel.split('/').pop() ?? ''\n if (answerText.includes(rel) || answerText.includes(name)) cited.push(f)\n }\n if (cited.length === 0) {\n return '(The agent did not cite any data files, or no cited file could be located.)'\n }\n const blocks: string[] = []\n for (const f of cited) {\n const rel = f.slice(dataDir.length + 1)\n blocks.push(`\\n=== FILE: data/${rel} ===\\n${readText(f)}`)\n }\n return blocks.join('')\n}\n\n// ── ground-truth parser ───────────────────────────────────────────────────────\n\nfunction parseThemeMoveCounts(groundTruth: string): Array<{ label: string; nMoves: number }> {\n const lines = groundTruth.split('\\n')\n const themeStarts = lines.reduce<number[]>((acc, l, i) => {\n if (/^\\d+\\./.test(l.trim())) acc.push(i)\n return acc\n }, [])\n return themeStarts.map((start, k) => {\n const end = k + 1 < themeStarts.length ? themeStarts[k + 1] : lines.length\n const block = lines.slice(start, end).join('\\n')\n const label = lines[start].replace(/^\\d+\\.\\s*/, '').trim()\n const nMoves = (block.match(/^\\s*\\[[a-z]\\]\\s+/gm) ?? []).length\n return { label, nMoves }\n })\n}\n\nfunction coverageThreshold(nMoves: number): number {\n return Math.max(1, Math.min(nMoves - 1, 3))\n}\n\n// ── router judge calls ────────────────────────────────────────────────────────\n\ninterface JudgeRouter {\n baseUrl: string\n key: string\n model: string\n}\n\nfunction judgeRouter(): JudgeRouter {\n const key = process.env.TANGLE_API_KEY\n if (!key) throw new Error('TANGLE_API_KEY is required for the Trata hedge-bench judge')\n const model = process.env.JUDGE_MODEL ?? JUDGE_MODEL\n const baseUrl = process.env.ROUTER_BASE ?? 'https://router.tangle.tools/v1'\n return { baseUrl, key, model }\n}\n\nfunction parseJsonFallback(raw: string): unknown {\n let s = raw.trim()\n if (s.startsWith('```')) s = s.split('\\n').slice(1).join('\\n')\n if (s.endsWith('```')) s = s.slice(0, s.lastIndexOf('```'))\n s = s.replace(/,(\\s*[}\\]])/g, '$1').trim()\n try {\n return JSON.parse(s)\n } catch {\n try {\n const m = s.match(/\\{[\\s\\S]*\\}/)\n if (m) return JSON.parse(m[0])\n } catch {\n // fallthrough\n }\n }\n return null\n}\n\nasync function callJudge(router: JudgeRouter, prompt: string, maxAttempts = 2): Promise<unknown> {\n for (let i = 0; i < maxAttempts; i++) {\n try {\n const turn = await runBenchRouterTurn(\n {\n routerBaseUrl: router.baseUrl,\n routerKey: router.key,\n profile: {\n name: 'trata-hedge-judge',\n harness: 'cli-base',\n model: {\n provider: 'tangle-router',\n default: router.model,\n maxVisibleOutputTokens: Number(process.env.JUDGE_MAX_TOKENS ?? 16384),\n metadata: { temperature: 0 },\n },\n },\n },\n prompt,\n )\n const content = turn.finalText\n const parsed = parseJsonFallback(content)\n if (parsed !== null) return parsed\n } catch (error) {\n if (i + 1 === maxAttempts) throw error\n }\n }\n return null\n}\n\ninterface Task1Result {\n hallucinations_detected?: boolean | string\n unverifiable_claims?: Array<{ claim: string; cited_file?: string; issue?: string; evidence_check?: string }>\n}\n\ninterface Task2ThemeResult {\n label?: string\n moves_hit?: string[]\n moves_missed?: string[]\n moves_tainted?: string[]\n move_reasoning?: Record<string, string>\n}\n\ninterface Task2Result {\n themes?: Task2ThemeResult[]\n}\n\ninterface Task3Result {\n synthesis_found?: string | null\n}\n\nasync function task1HallucinationCheck(\n meta: TrataTaskMeta,\n answer: string,\n router: JudgeRouter,\n): Promise<Task1Result> {\n const citedBlock = buildCitedDataBlock(answer, meta.dataDir)\n const dataContext =\n 'The block below contains the contents of the data files the agent cited in their answer. ' +\n 'Treat this as the ground truth for factual verification.\\n\\n' +\n `<cited_data>\\n${citedBlock}\\n</cited_data>`\n const prompt = meta.gradingTask1\n .replace('{data_context}', dataContext)\n .replace('{agent_answer}', answer)\n const result = await callJudge(router, prompt)\n return (result as Task1Result) ?? { hallucinations_detected: false, unverifiable_claims: [] }\n}\n\nasync function task2PerMoveCheck(\n meta: TrataTaskMeta,\n answer: string,\n flaggedClaims: Task1Result['unverifiable_claims'],\n router: JudgeRouter,\n): Promise<Task2Result> {\n const claimsBlock =\n flaggedClaims && flaggedClaims.length > 0\n ? JSON.stringify(flaggedClaims, null, 2)\n : '(No claims were flagged as hallucinations.)'\n const prompt = meta.gradingTask2\n .replace('{ground_truth}', meta.groundTruth)\n .replace('{agent_answer}', answer)\n .replace('{flagged_claims_block}', claimsBlock)\n .replace('{num_themes}', String(meta.themeMoveCounts.length))\n const result = await callJudge(router, prompt)\n return (result as Task2Result) ?? { themes: [] }\n}\n\nasync function task3SynthesisCheck(\n meta: TrataTaskMeta,\n answer: string,\n router: JudgeRouter,\n): Promise<Task3Result> {\n const prompt = meta.gradingTask3\n .replace('{ground_truth}', meta.groundTruth)\n .replace('{agent_answer}', answer)\n const result = await callJudge(router, prompt)\n return (result as Task3Result) ?? { synthesis_found: null }\n}\n\nasync function runTriataJudge(meta: TrataTaskMeta, answer: string, router: JudgeRouter): Promise<BenchEvaluation> {\n if (!answer.trim()) {\n const raw = { error: 'empty answer' }\n return { passed: false, score: 0, notes: JSON.stringify(raw), raw }\n }\n\n // Stage 1: hallucination check (serial — feeds into stage 2).\n const t1 = await task1HallucinationCheck(meta, answer, router)\n const flaggedClaims = t1.unverifiable_claims ?? []\n\n // Stages 2 + 3 in parallel.\n const [t2, t3] = await Promise.all([\n task2PerMoveCheck(meta, answer, flaggedClaims, router),\n task3SynthesisCheck(meta, answer, router),\n ])\n\n const judgeThemes = t2.themes ?? []\n const themesHit: string[] = []\n const themesMissed: string[] = []\n\n for (let i = 0; i < meta.themeMoveCounts.length; i++) {\n const { label, nMoves } = meta.themeMoveCounts[i]\n const judge = judgeThemes[i] ?? {}\n const movesHit = (judge.moves_hit ?? []).map((m: string) => m.replace(/[\\[\\]]/g, ''))\n const tainted = new Set((judge.moves_tainted ?? []).map((m: string) => m.replace(/[\\[\\]]/g, '')))\n const validHit = movesHit.filter((m: string) => !tainted.has(m))\n const threshold = coverageThreshold(nMoves)\n if (validHit.length >= threshold) themesHit.push(label)\n else themesMissed.push(label)\n }\n\n const numThemes = meta.themeMoveCounts.length\n const synth = t3.synthesis_found\n const hasSynthesis = typeof synth === 'string' && synth.length > 0 && synth !== 'null'\n\n let rawScore: number\n if (numThemes === 0) rawScore = 0\n else if (themesHit.length === numThemes && hasSynthesis) rawScore = 4\n else if (themesHit.length === numThemes) rawScore = 3\n else if (themesHit.length >= 2) rawScore = 2\n else if (themesHit.length >= 1) rawScore = 1\n else rawScore = 0\n\n const hallRaw = t1.hallucinations_detected\n const hallucinations = hallRaw === true || hallRaw === 'true'\n\n const raw = {\n rawScore,\n themesHit,\n themesMissed,\n hallucinations,\n unverifiableClaims: flaggedClaims.length,\n synthesis: synth ?? null,\n judgeModel: router.model,\n }\n return {\n passed: rawScore === 4,\n score: numThemes > 0 ? rawScore / 4 : 0,\n notes: JSON.stringify(raw),\n raw,\n }\n}\n\n// ── task loading ──────────────────────────────────────────────────────────────\n\nfunction benchRoot(): string {\n return process.env.TRATA_BENCH_ROOT ?? DEFAULT_BENCH_ROOT\n}\n\nfunction loadTask(taskId: string): { task: BenchTask; meta: TrataTaskMeta } {\n const taskDir = join(benchRoot(), 'environments', taskId)\n const dataDir = join(taskDir, 'environment', 'data')\n const testsDir = join(taskDir, 'tests')\n\n const instruction = readText(join(taskDir, 'instruction.md'), Infinity)\n const dataBlock = buildDataBlock(dataDir)\n const groundTruth = readText(join(testsDir, 'ground_truth.txt'), Infinity)\n const gradingTask1 = readText(join(testsDir, 'grading_prompt_task1.md'), Infinity)\n const gradingTask2 = readText(join(testsDir, 'grading_prompt_task2.md'), Infinity)\n const gradingTask3 = readText(join(testsDir, 'grading_prompt_task3.md'), Infinity)\n\n const themeMoveCounts = parseThemeMoveCounts(groundTruth)\n\n // Rewrite the instruction so the agent knows data is inline (no /app/data/ FS).\n const prompt = [\n instruction\n .replace(\n \"You are a financial analyst with access to the data in `/app/data/`.\",\n 'You are a financial analyst. The relevant financial data files are provided inline below.',\n )\n .replace(/Write your full analysis to `\\/app\\/answer\\.txt`\\.?/, 'Write your full analysis below.')\n .replace(/`\\/app\\/data\\/`/g, 'the data files below'),\n '',\n '## Data files (inline)',\n dataBlock,\n WORKER_SUFFIX,\n ].join('\\n')\n\n const meta: TrataTaskMeta = {\n taskDir,\n taskId,\n dataDir,\n groundTruth,\n gradingTask1,\n gradingTask2,\n gradingTask3,\n themeMoveCounts,\n }\n\n // Store meta in the BenchTask so the judge can access it without re-reading.\n const task: BenchTask = {\n id: taskId,\n payload: { prompt },\n metadata: meta as unknown as Record<string, unknown>,\n }\n\n return { task, meta }\n}\n\nfunction readMeta(task: BenchTask): TrataTaskMeta {\n const md = task.metadata\n if (!md || typeof md.taskDir !== 'string' || typeof md.groundTruth !== 'string') {\n throw new Error(`Trata task ${task.id} missing judge metadata — was it loaded by this adapter?`)\n }\n return md as unknown as TrataTaskMeta\n}\n\n/** List all task ids from the environments directory. */\nfunction listTaskIds(root: string): string[] {\n try {\n return readdirSync(join(root, 'environments'))\n .filter((name) => {\n try {\n return statSync(join(root, 'environments', name)).isDirectory()\n } catch {\n return false\n }\n })\n .sort()\n } catch (err) {\n throw new Error(\n `Trata benchmark environments not found at ${join(root, 'environments')}: ` +\n `${err instanceof Error ? err.message : err}.\\n` +\n `Clone the repo: git clone --depth 1 https://github.com/Trata-Inc/trata-hedge-bench ${root}`,\n )\n }\n}\n\n// ── extract agent analysis from artifact ─────────────────────────────────────\n\nfunction extractAnalysis(artifact: string): string {\n // Model may write \"ANALYSIS:\" as its very first token (no leading newline) or\n // after some preamble. Both are valid; fail-closed on absence.\n if (artifact.startsWith('ANALYSIS:')) return artifact.slice('ANALYSIS:'.length).trim()\n const marker = artifact.indexOf('\\nANALYSIS:')\n if (marker !== -1) return artifact.slice(marker + '\\nANALYSIS:'.length).trim()\n return ''\n}\n\n// ── adapter factory ───────────────────────────────────────────────────────────\n\nexport function createTrataHedgeAdapter(): RuntimeBenchmark {\n return runtimeBenchmark({\n id: 'trata-hedge',\n\n async loadAll(opts: LoadOptions = {}): Promise<BenchTask[]> {\n const root = benchRoot()\n let ids = listTaskIds(root)\n if (opts.ids) {\n const want = new Set(opts.ids)\n ids = ids.filter((id) => want.has(id))\n } else if (opts.limit !== undefined) {\n ids = ids.slice(0, opts.limit)\n }\n return ids.map((id) => loadTask(id).task)\n },\n\n async evaluate(task: BenchTask, artifact: string): Promise<BenchEvaluation> {\n const meta = readMeta(task)\n const answer = extractAnalysis(artifact)\n return runTriataJudge(meta, answer, judgeRouter())\n },\n\n runtime: {\n async preflight() {\n const root = benchRoot()\n const envDir = join(root, 'environments')\n try {\n const stat = statSync(envDir)\n if (!stat.isDirectory()) throw new Error('not a directory')\n } catch {\n throw new Error(\n `Trata hedge-bench not found at ${envDir}.\\n` +\n `Clone: git clone --depth 1 https://github.com/Trata-Inc/trata-hedge-bench ${root}`,\n )\n }\n // Validate judge router connectivity.\n judgeRouter()\n const ids = listTaskIds(root)\n if (ids.length === 0) throw new Error(`No task directories found under ${envDir}`)\n console.warn(\n `[trata-hedge] ${ids.length} tasks loaded from ${root}. ` +\n `Worker model reads embedded data inline (Harbor/Docker not required). ` +\n `Judge uses ${process.env.JUDGE_MODEL ?? JUDGE_MODEL} via Tangle router.`,\n )\n },\n\n async goldArtifact(_task: BenchTask): Promise<string | undefined> {\n // No single gold answer: the score comes from rubric theme coverage, not\n // string-match against a reference response. Return undefined — the bench\n // harness will skip judge self-verification for this adapter.\n return undefined\n },\n },\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BA,MAAM,qBAAqB;AAC3B,MAAM,iBAAiB;AAEvB,MAAM,iBAAiB;AACvB,MAAM,gBAAgB;CACpB;CACA;CACA;CACA;AACF,CAAC,CAAC,KAAK,IAAI;AAGX,MAAM,cAAc;AAgBpB,SAAS,SAAS,GAAW,WAAW,gBAAwB;CAC9D,IAAI;EACF,MAAM,MAAM,aAAa,CAAC;EAC1B,IAAI,IAAI,UAAU,UAAU,OAAO,IAAI,SAAS,MAAM;EACtD,OAAO,IAAI,SAAS,GAAG,QAAQ,CAAC,CAAC,SAAS,MAAM,IAAI,qBAAqB,SAAS;CACpF,QAAQ;EACN,OAAO,gBAAgB,EAAE;CAC3B;AACF;AAEA,SAAS,aAAa,KAAuB;CAC3C,MAAM,MAAgB,CAAC;CACvB,IAAI;EACF,KAAK,MAAM,QAAQ,YAAY,GAAG,GAAG;GACnC,MAAM,OAAO,KAAK,KAAK,IAAI;GAC3B,IAAI;IACF,IAAI,SAAS,IAAI,CAAC,CAAC,YAAY,GAAG,IAAI,KAAK,GAAG,aAAa,IAAI,CAAC;SAC3D,IAAI,KAAK,IAAI;GACpB,QAAQ,CAER;EACF;CACF,QAAQ,CAER;CACA,OAAO,IAAI,KAAK;AAClB;AAEA,SAAS,eAAe,SAAyB;CAC/C,MAAM,QAAQ,aAAa,OAAO;CAClC,IAAI,MAAM,WAAW,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,OAAO,iBAAiB;EACtB,IAAI;EAEJ,MAAM,QAAQ,OAAoB,CAAC,GAAyB;GAE1D,IAAI,MAAM,YADG,UACY,CAAC;GAC1B,IAAI,KAAK,KAAK;IACZ,MAAM,OAAO,IAAI,IAAI,KAAK,GAAG;IAC7B,MAAM,IAAI,QAAQ,OAAO,KAAK,IAAI,EAAE,CAAC;GACvC,OAAO,IAAI,KAAK,UAAU,KAAA,GACxB,MAAM,IAAI,MAAM,GAAG,KAAK,KAAK;GAE/B,OAAO,IAAI,KAAK,OAAO,SAAS,EAAE,CAAC,CAAC,IAAI;EAC1C;EAEA,MAAM,SAAS,MAAiB,UAA4C;GAG1E,OAAO,eAFM,SAAS,IAEG,GADV,gBAAgB,QACE,GAAG,YAAY,CAAC;EACnD;EAEA,SAAS;GACP,MAAM,YAAY;IAChB,MAAM,OAAO,UAAU;IACvB,MAAM,SAAS,KAAK,MAAM,cAAc;IACxC,IAAI;KAEF,IAAI,CADS,SAAS,MACd,CAAC,CAAC,YAAY,GAAG,MAAM,IAAI,MAAM,iBAAiB;IAC5D,QAAQ;KACN,MAAM,IAAI,MACR,kCAAkC,OAAO,+EACsC,MACjF;IACF;IAEA,YAAY;IACZ,MAAM,MAAM,YAAY,IAAI;IAC5B,IAAI,IAAI,WAAW,GAAG,MAAM,IAAI,MAAM,mCAAmC,QAAQ;IACjF,QAAQ,KACN,iBAAiB,IAAI,OAAO,qBAAqB,KAAK,qFAEtC,QAAQ,IAAI,eAAe,YAAY,oBACzD;GACF;GAEA,MAAM,aAAa,OAA+C,CAKlE;EACF;CACF,CAAC;AACH"}
|
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
1
|
+
import { BenchmarkAdapter, BenchmarkDatasetItem, BenchmarkEvaluation, BenchmarkLoadOptions, BenchmarkRuntimeHooks } from "@tangle-network/agent-eval/benchmarks";
|
|
2
|
+
import { AgentTurnUsage } from "@tangle-network/agent-runtime/kernel";
|
|
3
|
+
import { SandboxEvent } from "@tangle-network/sandbox";
|
|
4
|
+
/** What the worker is handed, and the publisher's subset (domain, category, language, dataset version) the task is in. */
|
|
5
|
+
export interface BenchPayload {
|
|
6
6
|
prompt: string;
|
|
7
|
-
|
|
8
|
-
/** Benchmark-specific fields the worker/judge need (repo, base_commit, gold, …). */
|
|
9
|
-
metadata?: Record<string, unknown>;
|
|
7
|
+
subset?: string;
|
|
10
8
|
}
|
|
9
|
+
/** One benchmark instance. `metadata` carries the fields the worker and judge need (repo, base_commit, gold, …). */
|
|
10
|
+
export type BenchTask = BenchmarkDatasetItem<BenchPayload>;
|
|
11
11
|
export interface JudgeArtifactFileReceipt {
|
|
12
12
|
/** POSIX path relative to the capture directory. */
|
|
13
13
|
path: string;
|
|
@@ -32,12 +32,9 @@ export interface JudgeArtifactReceipt {
|
|
|
32
32
|
/** SHA-256 over every sorted path, kind, byte length, and content hash. */
|
|
33
33
|
treeSha256: `sha256:${string}`;
|
|
34
34
|
}
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
/** 0..1 — 1 = fully resolved; partial credit where the harness supports it. */
|
|
39
|
-
score: number;
|
|
40
|
-
detail?: string;
|
|
35
|
+
/** agent-eval's verdict (`passed`: the judge passed; `score` 0..1 with partial credit where the harness has it;
|
|
36
|
+
* `notes`), plus the evidence agent-bench's judges keep. */
|
|
37
|
+
export interface BenchEvaluation extends BenchmarkEvaluation {
|
|
41
38
|
/** Present only when the caller explicitly requested durable judge evidence. */
|
|
42
39
|
judgeArtifacts?: JudgeArtifactReceipt;
|
|
43
40
|
/** The judge model turn's exact Runtime usage record, present only when the
|
|
@@ -46,55 +43,28 @@ export interface BenchScore {
|
|
|
46
43
|
* unknown instead of reading as zero. Deterministic judges never set it. */
|
|
47
44
|
judgeUsage?: AgentTurnUsage;
|
|
48
45
|
}
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
ids?: string[];
|
|
46
|
+
/** agent-eval's load options (`limit`, `ids`), plus the publisher's subset. */
|
|
47
|
+
export interface LoadOptions extends BenchmarkLoadOptions {
|
|
48
|
+
subset?: string;
|
|
53
49
|
}
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
* so the gate runner (`runGate` / `runBenchmark`) needs no
|
|
67
|
-
* per-benchmark branching. */
|
|
68
|
-
output?: OutputAdapter<string>;
|
|
69
|
-
/** Post-shot deliverable extraction from the box FILESYSTEM, not the event stream.
|
|
70
|
-
* When set, the shot runner execs `command` in the STILL-ALIVE box after the agent
|
|
71
|
-
* turn drains and uses its stdout as the judged artifact — the durable way to capture
|
|
72
|
-
* a git diff of the agent's in-box edits (standard SWE-bench practice: SWE-agent /
|
|
73
|
-
* OpenHands read the diff from repo STATE), instead of hoping the model printed a
|
|
74
|
-
* fenced diff in its reply. Empty stdout ⇒ the runner falls back to `output` (the
|
|
75
|
-
* event-stream parse). `cwd` defaults to the box root. */
|
|
76
|
-
boxExtract?(task: BenchTask): {
|
|
77
|
-
command: string;
|
|
78
|
-
cwd?: string;
|
|
79
|
-
};
|
|
80
|
-
/** Optional workspace pre-stage run in the box BEFORE the agent shot (same
|
|
81
|
-
* session as `boxExtract`). For repo-state benchmarks (SWE-bench) this clones
|
|
82
|
-
* the instance repo at `base_commit` into a fixed path so the agent only edits
|
|
83
|
-
* — the harness owns the checkout, not the (stochastic) model. A non-zero exit
|
|
84
|
-
* fails the shot loud rather than letting the agent run against an empty box. */
|
|
85
|
-
boxSetup?(task: BenchTask): {
|
|
86
|
-
command: string;
|
|
87
|
-
cwd?: string;
|
|
88
|
-
};
|
|
89
|
-
/** Benchmark-owned worker leaf. Set when the benchmark's native protocol IS the
|
|
90
|
-
* worker (e.g. AppWorld's interactive ReAct episode runs inside the engine,
|
|
91
|
-
* not as a chat completion) — the experiment uses this instead of the
|
|
92
|
-
* BACKEND-selected client; the steer still flows through the per-round prompt.
|
|
93
|
-
* Typed loosely to avoid a runtime import cycle; the harness casts it. */
|
|
94
|
-
leafClient?: (cfg: {
|
|
95
|
-
model: string;
|
|
96
|
-
routerBaseUrl: string;
|
|
97
|
-
routerKey: string;
|
|
98
|
-
}) => unknown;
|
|
50
|
+
/** The runtime hooks over agent-runtime's sandbox events. `workspaceSetup` runs in the box before the agent
|
|
51
|
+
* shot (a non-zero exit fails the shot); `workspaceExtract` runs in the still-alive box after it, and its
|
|
52
|
+
* stdout is the judged artifact (empty stdout falls back to `output`, then the final answer text). */
|
|
53
|
+
export type BenchRuntime = BenchmarkRuntimeHooks<BenchPayload, string, SandboxEvent>;
|
|
54
|
+
/** An agent-eval `BenchmarkAdapter` an agent-runtime worker runs. */
|
|
55
|
+
export interface RuntimeBenchmark extends BenchmarkAdapter<BenchTask, BenchPayload, string, SandboxEvent> {
|
|
56
|
+
readonly id: string;
|
|
57
|
+
readonly runtime: BenchRuntime;
|
|
58
|
+
/** Every task in the publisher's order, ignoring agent-eval's splits. */
|
|
59
|
+
loadAll(options?: LoadOptions): Promise<BenchTask[]>;
|
|
60
|
+
/** The benchmark's own judge on the worker's artifact. */
|
|
61
|
+
evaluate(item: BenchTask, artifact: string): Promise<BenchEvaluation>;
|
|
99
62
|
}
|
|
63
|
+
export type RuntimeBenchmarkSpec = Omit<RuntimeBenchmark, 'loadDataset' | 'assignSplit' | 'runtime'> & {
|
|
64
|
+
assignSplit?: RuntimeBenchmark['assignSplit'];
|
|
65
|
+
/** `prompt` defaults to the task's `payload.prompt`. */
|
|
66
|
+
runtime?: Omit<BenchRuntime, 'prompt'> & Partial<Pick<BenchRuntime, 'prompt'>>;
|
|
67
|
+
};
|
|
68
|
+
/** Build a `RuntimeBenchmark`: splits default to agent-eval's `deterministicSplit` over `<id>::<task id>`. */
|
|
69
|
+
export declare function runtimeBenchmark(spec: RuntimeBenchmarkSpec): RuntimeBenchmark;
|
|
100
70
|
//# sourceMappingURL=types.d.ts.map
|
package/dist/benchmarks/types.js
CHANGED
|
@@ -1 +1,36 @@
|
|
|
1
|
-
|
|
1
|
+
import { deterministicSplit, selectBenchmarkItems } from "@tangle-network/agent-eval/benchmarks";
|
|
2
|
+
// src/benchmarks/types.ts
|
|
3
|
+
/**
|
|
4
|
+
* agent-bench's benchmarks are agent-eval `BenchmarkAdapter`s, the one benchmark contract, each with the
|
|
5
|
+
* `runtime` hooks an agent-runtime worker needs: the prompt, the deliverable parser, the in-box workspace
|
|
6
|
+
* setup and extraction, and, where the benchmark's own protocol is the worker, that worker.
|
|
7
|
+
*
|
|
8
|
+
* The point: no self-authored judge, no invented score noise. `evaluate` is the benchmark's published
|
|
9
|
+
* evaluation harness, run on the artifact the worker produced.
|
|
10
|
+
*
|
|
11
|
+
* A public benchmark reports every task, so each one also has `loadAll`, a loader that ignores agent-eval's
|
|
12
|
+
* search/dev/holdout splits, as agent-eval's own Harbor adapter has. `loadDataset(split)` serves the same
|
|
13
|
+
* tasks by agent-eval's deterministic split.
|
|
14
|
+
*/
|
|
15
|
+
/** Build a `RuntimeBenchmark`: splits default to agent-eval's `deterministicSplit` over `<id>::<task id>`. */
|
|
16
|
+
function runtimeBenchmark(spec) {
|
|
17
|
+
const assignSplit = spec.assignSplit ?? ((itemId) => deterministicSplit(`${spec.id}::${itemId}`));
|
|
18
|
+
return {
|
|
19
|
+
...spec,
|
|
20
|
+
runtime: {
|
|
21
|
+
prompt: (task) => task.payload.prompt,
|
|
22
|
+
...spec.runtime
|
|
23
|
+
},
|
|
24
|
+
assignSplit,
|
|
25
|
+
async loadDataset(split, options) {
|
|
26
|
+
const inSplit = (await spec.loadAll(options?.ids?.length ? { ids: options.ids } : {})).map((task) => ({
|
|
27
|
+
...task,
|
|
28
|
+
split: task.split ?? assignSplit(task.id)
|
|
29
|
+
})).filter((task) => task.split === split);
|
|
30
|
+
return selectBenchmarkItems(inSplit, options);
|
|
31
|
+
}
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
export { runtimeBenchmark };
|
|
35
|
+
|
|
36
|
+
//# sourceMappingURL=types.js.map
|