@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,5 +1,6 @@
|
|
|
1
|
-
import { benchRoot } from "./_harness.js";
|
|
2
1
|
import { t as runBenchRouterTurn } from "../router-turn-DNbQ_GjQ.js";
|
|
2
|
+
import { benchRoot } from "./_harness.js";
|
|
3
|
+
import { runtimeBenchmark } from "./types.js";
|
|
3
4
|
import { readFile, stat } from "node:fs/promises";
|
|
4
5
|
import { join } from "node:path";
|
|
5
6
|
// src/benchmarks/finresearchbench.ts
|
|
@@ -19,7 +20,7 @@ function routerConfig() {
|
|
|
19
20
|
return {
|
|
20
21
|
baseUrl: process.env.ROUTER_BASE ?? "https://router.tangle.tools/v1",
|
|
21
22
|
key,
|
|
22
|
-
model: process.env.FINRESEARCHBENCH_JUDGE_MODEL ?? process.env.JUDGE_MODEL ?? "deepseek-v4-flash"
|
|
23
|
+
model: process.env.FINRESEARCHBENCH_JUDGE_MODEL ?? process.env.JUDGE_MODEL ?? "deepseek/deepseek-v4.1-flash"
|
|
23
24
|
};
|
|
24
25
|
}
|
|
25
26
|
async function assertReadable(path, label) {
|
|
@@ -55,24 +56,26 @@ function rowToTask(row, fixturesMode) {
|
|
|
55
56
|
};
|
|
56
57
|
return {
|
|
57
58
|
id: row.id,
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
59
|
+
payload: {
|
|
60
|
+
subset: row.category,
|
|
61
|
+
prompt: [
|
|
62
|
+
"Complete this FinResearchBench financial research task.",
|
|
63
|
+
"Produce a decision-grade research answer with explicit reasoning, evidence, and final conclusion.",
|
|
64
|
+
"",
|
|
65
|
+
row.question
|
|
66
|
+
].join("\n")
|
|
67
|
+
},
|
|
65
68
|
metadata: meta
|
|
66
69
|
};
|
|
67
70
|
}
|
|
68
71
|
function readMeta(task) {
|
|
69
72
|
const md = task.metadata;
|
|
70
|
-
if (!md || typeof md.question !== "string") throw new Error(`FinResearchBench task ${task.id} missing metadata —
|
|
73
|
+
if (!md || typeof md.question !== "string") throw new Error(`FinResearchBench task ${task.id} missing metadata — loadAll did not populate it`);
|
|
71
74
|
return md;
|
|
72
75
|
}
|
|
73
76
|
function selectRows(rows, opts, fixturesMode) {
|
|
74
77
|
let tasks = rows.map((row) => rowToTask(row, fixturesMode));
|
|
75
|
-
if (opts.
|
|
78
|
+
if (opts.subset) tasks = tasks.filter((task) => task.payload.subset === opts.subset);
|
|
76
79
|
if (opts.ids) {
|
|
77
80
|
const want = new Set(opts.ids);
|
|
78
81
|
tasks = tasks.filter((task) => want.has(task.id));
|
|
@@ -121,7 +124,7 @@ function parseJudgeScore(content) {
|
|
|
121
124
|
throw new Error(`FinResearchBench judge produced no parseable JSON score: ${content.slice(0, 400)}`);
|
|
122
125
|
}
|
|
123
126
|
/**
|
|
124
|
-
* Map one drained judge turn to a
|
|
127
|
+
* Map one drained judge turn to a BenchEvaluation. The judge turn's exact Runtime
|
|
125
128
|
* usage record lands on `judgeUsage` verbatim, so an unproven token count or
|
|
126
129
|
* dollar amount stays flagged (`tokensKnown`/`usdKnown` false) instead of
|
|
127
130
|
* reading as a known zero cost.
|
|
@@ -131,15 +134,17 @@ function scoreOfficialJudgeTurn(task, turn, requestedJudgeModel) {
|
|
|
131
134
|
const content = turn.finalText;
|
|
132
135
|
if (!content) throw new Error("FinResearchBench judge returned no message content");
|
|
133
136
|
const { score, raw } = parseJudgeScore(content);
|
|
137
|
+
const detail = {
|
|
138
|
+
scoring: meta.scoring,
|
|
139
|
+
category: meta.category,
|
|
140
|
+
judgeModel: requestedJudgeModel,
|
|
141
|
+
raw
|
|
142
|
+
};
|
|
134
143
|
return {
|
|
135
|
-
|
|
144
|
+
passed: score >= Number(process.env.FINRESEARCHBENCH_PASS_THRESHOLD ?? .8),
|
|
136
145
|
score,
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
category: meta.category,
|
|
140
|
-
judgeModel: requestedJudgeModel,
|
|
141
|
-
raw
|
|
142
|
-
}),
|
|
146
|
+
notes: JSON.stringify(detail),
|
|
147
|
+
raw: detail,
|
|
143
148
|
judgeUsage: turn.usage
|
|
144
149
|
};
|
|
145
150
|
}
|
|
@@ -168,55 +173,63 @@ function scoreFixture(meta, artifact) {
|
|
|
168
173
|
const answer = normalizeText(meta.referenceAnswer || meta.referenceReport);
|
|
169
174
|
const response = normalizeText(artifact);
|
|
170
175
|
const score = answer.length > 0 && response.includes(answer) ? 1 : 0;
|
|
176
|
+
const raw = {
|
|
177
|
+
scoring: meta.scoring,
|
|
178
|
+
category: meta.category
|
|
179
|
+
};
|
|
171
180
|
return {
|
|
172
|
-
|
|
181
|
+
passed: score === 1,
|
|
173
182
|
score,
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
category: meta.category
|
|
177
|
-
})
|
|
183
|
+
notes: JSON.stringify(raw),
|
|
184
|
+
raw
|
|
178
185
|
};
|
|
179
186
|
}
|
|
180
187
|
function createFinResearchBenchAdapter() {
|
|
181
188
|
const fixturesMode = process.env.FINRESEARCHBENCH_FIXTURES === "1";
|
|
182
|
-
return {
|
|
183
|
-
|
|
184
|
-
async
|
|
185
|
-
if (fixturesMode) {
|
|
186
|
-
await assertReadable(FIXTURES, "fixture file");
|
|
187
|
-
return;
|
|
188
|
-
}
|
|
189
|
-
const file = dataFile();
|
|
190
|
-
if (!file) throw new Error("FINRESEARCHBENCH_DATA_FILE is required. Fix: export the official FinResearchBench rows as JSON/JSONL with judge_system_prompt and judge_prompt_template fields, then set FINRESEARCHBENCH_DATA_FILE=/path/to/export.jsonl.");
|
|
191
|
-
routerConfig();
|
|
192
|
-
await assertReadable(file, "data file");
|
|
193
|
-
await loadOfficialTasks(file, { limit: 1 });
|
|
194
|
-
},
|
|
195
|
-
async loadTasks(opts = {}) {
|
|
189
|
+
return runtimeBenchmark({
|
|
190
|
+
id: "finresearchbench",
|
|
191
|
+
async loadAll(opts = {}) {
|
|
196
192
|
if (fixturesMode) return loadFixtures(opts);
|
|
197
193
|
const file = dataFile();
|
|
198
194
|
if (!file) throw new Error("FINRESEARCHBENCH_DATA_FILE is required to load FinResearchBench rows");
|
|
199
195
|
return loadOfficialTasks(file, opts);
|
|
200
196
|
},
|
|
201
|
-
async
|
|
202
|
-
const meta = readMeta(task);
|
|
203
|
-
return meta.referenceReport || meta.referenceAnswer || void 0;
|
|
204
|
-
},
|
|
205
|
-
async judge(task, artifact) {
|
|
197
|
+
async evaluate(task, artifact) {
|
|
206
198
|
const meta = readMeta(task);
|
|
207
199
|
if (fixturesMode) return scoreFixture(meta, artifact);
|
|
208
|
-
if (artifact.trim().length === 0)
|
|
209
|
-
|
|
210
|
-
score: 0,
|
|
211
|
-
detail: JSON.stringify({
|
|
200
|
+
if (artifact.trim().length === 0) {
|
|
201
|
+
const raw = {
|
|
212
202
|
scoring: meta.scoring,
|
|
213
203
|
category: meta.category,
|
|
214
204
|
reason: "empty answer"
|
|
215
|
-
}
|
|
216
|
-
|
|
205
|
+
};
|
|
206
|
+
return {
|
|
207
|
+
passed: false,
|
|
208
|
+
score: 0,
|
|
209
|
+
notes: JSON.stringify(raw),
|
|
210
|
+
raw
|
|
211
|
+
};
|
|
212
|
+
}
|
|
217
213
|
return runOfficialJudge(task, meta, artifact);
|
|
214
|
+
},
|
|
215
|
+
runtime: {
|
|
216
|
+
async preflight() {
|
|
217
|
+
if (fixturesMode) {
|
|
218
|
+
await assertReadable(FIXTURES, "fixture file");
|
|
219
|
+
return;
|
|
220
|
+
}
|
|
221
|
+
const file = dataFile();
|
|
222
|
+
if (!file) throw new Error("FINRESEARCHBENCH_DATA_FILE is required. Fix: export the official FinResearchBench rows as JSON/JSONL with judge_system_prompt and judge_prompt_template fields, then set FINRESEARCHBENCH_DATA_FILE=/path/to/export.jsonl.");
|
|
223
|
+
routerConfig();
|
|
224
|
+
await assertReadable(file, "data file");
|
|
225
|
+
await loadOfficialTasks(file, { limit: 1 });
|
|
226
|
+
},
|
|
227
|
+
async goldArtifact(task) {
|
|
228
|
+
const meta = readMeta(task);
|
|
229
|
+
return meta.referenceReport || meta.referenceAnswer || void 0;
|
|
230
|
+
}
|
|
218
231
|
}
|
|
219
|
-
};
|
|
232
|
+
});
|
|
220
233
|
}
|
|
221
234
|
export { createFinResearchBenchAdapter, scoreOfficialJudgeTurn };
|
|
222
235
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"finresearchbench.js","names":[],"sources":["../../src/benchmarks/finresearchbench.ts"],"sourcesContent":["/**\n * FinResearchBench-compatible adapter.\n *\n * The paper defines a logic-tree Agent-as-a-Judge benchmark for financial\n * research reports, but there is no stable public scorer package wired here.\n * Live mode therefore requires a local data export whose rows carry the official\n * judge prompt/template/logic tree. The adapter refuses to invent a judge.\n */\n\nimport { readFile, stat } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport type { AgentTurnUsage } from '@tangle-network/agent-runtime/kernel'\nimport { runBenchRouterTurn } from '../router-turn'\nimport { benchRoot } from './_harness'\nimport type { BenchmarkAdapter, BenchScore, BenchTask, LoadOptions } from './types'\n\nconst FIXTURES = join(benchRoot, 'fixtures', 'finresearchbench.json')\n\ninterface FinResearchRecord {\n id: string\n question: string\n category?: string\n reference_answer?: string\n reference_report?: string\n logic_tree?: unknown\n rubric?: unknown\n judge_system_prompt?: string\n judge_prompt_template?: string\n}\n\ninterface FinResearchMeta {\n id: string\n category: string\n question: string\n referenceAnswer: string\n referenceReport: string\n logicTree: unknown\n rubric: unknown\n judgeSystemPrompt?: string\n judgePromptTemplate?: string\n scoring: 'official-logic-tree-judge' | 'fixture-exact-reference'\n}\n\nconst dataFile = (): string | undefined => process.env.FINRESEARCHBENCH_DATA_FILE\n\nfunction routerConfig(): { baseUrl: string; key: string; model: string } {\n const key = process.env.TANGLE_API_KEY\n if (!key) throw new Error('TANGLE_API_KEY is required for FinResearchBench live LLM judging')\n return {\n baseUrl: process.env.ROUTER_BASE ?? 'https://router.tangle.tools/v1',\n key,\n model: process.env.FINRESEARCHBENCH_JUDGE_MODEL ?? process.env.JUDGE_MODEL ?? 'deepseek-v4-flash',\n }\n}\n\nasync function assertReadable(path: string, label: string): Promise<void> {\n try {\n await stat(path)\n } catch (err) {\n throw new Error(`FinResearchBench: missing ${label} at ${path} (${err instanceof Error ? err.message : err})`)\n }\n}\n\nfunction readRecords(raw: string): FinResearchRecord[] {\n const trimmed = raw.trim()\n if (trimmed.startsWith('[')) return JSON.parse(trimmed) as FinResearchRecord[]\n return trimmed\n .split(/\\r?\\n/)\n .map((line) => line.trim())\n .filter((line) => line.length > 0)\n .map((line) => JSON.parse(line) as FinResearchRecord)\n}\n\nfunction assertLiveJudgeFields(records: readonly FinResearchRecord[], source: string): void {\n const missing = records\n .filter((row) => !row.judge_system_prompt || !row.judge_prompt_template)\n .map((row) => row.id)\n if (missing.length > 0) {\n throw new Error(\n `FinResearchBench live rows from ${source} missing official judge prompts for ${missing.length}/${records.length} row(s): ${missing.slice(0, 5).join(', ')}. ` +\n 'Use a benchmark export with judge_system_prompt and judge_prompt_template, or do not score this benchmark live.',\n )\n }\n}\n\nfunction rowToTask(row: FinResearchRecord, fixturesMode: boolean): BenchTask {\n const referenceAnswer = row.reference_answer ?? ''\n const referenceReport = row.reference_report ?? referenceAnswer\n const meta: FinResearchMeta = {\n id: row.id,\n category: row.category ?? 'unknown',\n question: row.question,\n referenceAnswer,\n referenceReport,\n logicTree: row.logic_tree ?? null,\n rubric: row.rubric ?? null,\n judgeSystemPrompt: row.judge_system_prompt,\n judgePromptTemplate: row.judge_prompt_template,\n scoring: fixturesMode ? 'fixture-exact-reference' : 'official-logic-tree-judge',\n }\n return {\n id: row.id,\n split: row.category,\n prompt: [\n 'Complete this FinResearchBench financial research task.',\n 'Produce a decision-grade research answer with explicit reasoning, evidence, and final conclusion.',\n '',\n row.question,\n ].join('\\n'),\n metadata: meta as unknown as Record<string, unknown>,\n }\n}\n\nfunction readMeta(task: BenchTask): FinResearchMeta {\n const md = task.metadata\n if (!md || typeof md.question !== 'string') {\n throw new Error(`FinResearchBench task ${task.id} missing metadata — loadTasks did not populate it`)\n }\n return md as unknown as FinResearchMeta\n}\n\nfunction selectRows(rows: FinResearchRecord[], opts: LoadOptions, fixturesMode: boolean): BenchTask[] {\n let tasks = rows.map((row) => rowToTask(row, fixturesMode))\n if (opts.split) tasks = tasks.filter((task) => task.split === opts.split)\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(`FinResearchBench: no tasks matched ${JSON.stringify(opts)}`)\n return tasks\n}\n\nasync function loadFixtures(opts: LoadOptions): Promise<BenchTask[]> {\n const records = readRecords(await readFile(FIXTURES, 'utf8'))\n console.warn(`[finresearchbench] FINRESEARCHBENCH_FIXTURES=1 — loading ${records.length} adapter fixtures`)\n return selectRows(records, opts, true)\n}\n\nasync function loadOfficialTasks(path: string, opts: LoadOptions): Promise<BenchTask[]> {\n const records = readRecords(await readFile(path, 'utf8'))\n assertLiveJudgeFields(records, path)\n return selectRows(records, opts, false)\n}\n\nfunction fillTemplate(meta: FinResearchMeta, response: string): string {\n const template = meta.judgePromptTemplate\n if (!template) throw new Error(`FinResearchBench task ${meta.id} missing judge_prompt_template`)\n return template\n .replaceAll('{question}', meta.question)\n .replaceAll('{response}', response)\n .replaceAll('{reference_answer}', meta.referenceAnswer)\n .replaceAll('{reference_report}', meta.referenceReport)\n .replaceAll('{logic_tree}', JSON.stringify(meta.logicTree, null, 2))\n .replaceAll('{rubric}', JSON.stringify(meta.rubric, null, 2))\n}\n\nfunction parseJudgeScore(content: string): { score: number; raw: unknown } {\n const candidates: string[] = []\n for (const m of content.matchAll(/```(?:json)?\\s*([\\s\\S]*?)```/g)) candidates.push(m[1].trim())\n for (const m of content.matchAll(/\\{[\\s\\S]*?\\}/g)) candidates.push(m[0])\n candidates.push(content.trim())\n for (const candidate of candidates) {\n let parsed: Record<string, unknown>\n try {\n parsed = JSON.parse(candidate) as Record<string, unknown>\n } catch {\n continue\n }\n const raw = parsed.score ?? parsed.overall_score ?? parsed.total_score ?? parsed.answer_score\n const n = typeof raw === 'number' ? raw : typeof raw === 'string' ? Number(raw) : NaN\n if (!Number.isFinite(n)) continue\n if (n < 0) throw new Error(`FinResearchBench judge score is negative: ${JSON.stringify(parsed)}`)\n const score = n <= 1 ? n : n <= 10 ? n / 10 : n / 100\n if (score > 1) throw new Error(`FinResearchBench judge score outside supported range: ${JSON.stringify(parsed)}`)\n return { score, raw: parsed }\n }\n throw new Error(`FinResearchBench judge produced no parseable JSON score: ${content.slice(0, 400)}`)\n}\n\n/**\n * Map one drained judge turn to a BenchScore. The judge turn's exact Runtime\n * usage record lands on `judgeUsage` verbatim, so an unproven token count or\n * dollar amount stays flagged (`tokensKnown`/`usdKnown` false) instead of\n * reading as a known zero cost.\n */\nexport function scoreOfficialJudgeTurn(\n task: BenchTask,\n turn: Readonly<{ finalText?: string; usage: AgentTurnUsage }>,\n requestedJudgeModel: string,\n): BenchScore {\n const meta = readMeta(task)\n const content = turn.finalText\n if (!content) throw new Error('FinResearchBench judge returned no message content')\n const { score, raw } = parseJudgeScore(content)\n return {\n resolved: score >= Number(process.env.FINRESEARCHBENCH_PASS_THRESHOLD ?? 0.8),\n score,\n detail: JSON.stringify({ scoring: meta.scoring, category: meta.category, judgeModel: requestedJudgeModel, raw }),\n judgeUsage: turn.usage,\n }\n}\n\nasync function runOfficialJudge(task: BenchTask, meta: FinResearchMeta, response: string): Promise<BenchScore> {\n if (!meta.judgeSystemPrompt) throw new Error(`FinResearchBench task ${meta.id} missing judge_system_prompt`)\n const router = routerConfig()\n const turn = await runBenchRouterTurn(\n {\n routerBaseUrl: router.baseUrl,\n routerKey: router.key,\n profile: {\n name: 'finresearchbench-judge',\n harness: 'cli-base',\n model: {\n provider: 'tangle-router',\n default: router.model,\n metadata: { temperature: 0 },\n },\n prompt: { systemPrompt: meta.judgeSystemPrompt },\n },\n },\n fillTemplate(meta, response),\n )\n return scoreOfficialJudgeTurn(task, turn, router.model)\n}\n\nfunction normalizeText(value: string): string {\n return value.toLowerCase().replace(/\\s+/g, ' ').trim()\n}\n\nfunction scoreFixture(meta: FinResearchMeta, artifact: string): BenchScore {\n const answer = normalizeText(meta.referenceAnswer || meta.referenceReport)\n const response = normalizeText(artifact)\n const score = answer.length > 0 && response.includes(answer) ? 1 : 0\n return {\n resolved: score === 1,\n score,\n detail: JSON.stringify({ scoring: meta.scoring, category: meta.category }),\n }\n}\n\nexport function createFinResearchBenchAdapter(): BenchmarkAdapter {\n const fixturesMode = process.env.FINRESEARCHBENCH_FIXTURES === '1'\n\n return {\n name: 'finresearchbench',\n\n async preflight() {\n if (fixturesMode) {\n await assertReadable(FIXTURES, 'fixture file')\n return\n }\n const file = dataFile()\n if (!file) {\n throw new Error(\n 'FINRESEARCHBENCH_DATA_FILE is required. Fix: export the official FinResearchBench rows as JSON/JSONL with judge_system_prompt and judge_prompt_template fields, then set FINRESEARCHBENCH_DATA_FILE=/path/to/export.jsonl.',\n )\n }\n routerConfig()\n await assertReadable(file, 'data file')\n await loadOfficialTasks(file, { limit: 1 })\n },\n\n async loadTasks(opts: LoadOptions = {}) {\n if (fixturesMode) return loadFixtures(opts)\n const file = dataFile()\n if (!file) throw new Error('FINRESEARCHBENCH_DATA_FILE is required to load FinResearchBench rows')\n return loadOfficialTasks(file, opts)\n },\n\n async goldArtifact(task: BenchTask) {\n const meta = readMeta(task)\n return meta.referenceReport || meta.referenceAnswer || undefined\n },\n\n async judge(task: BenchTask, artifact: string): Promise<BenchScore> {\n const meta = readMeta(task)\n if (fixturesMode) return scoreFixture(meta, artifact)\n if (artifact.trim().length === 0) {\n return {\n resolved: false,\n score: 0,\n detail: JSON.stringify({ scoring: meta.scoring, category: meta.category, reason: 'empty answer' }),\n }\n }\n return runOfficialJudge(task, meta, artifact)\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAgBA,MAAM,WAAW,KAAK,WAAW,YAAY,uBAAuB;AA2BpE,MAAM,iBAAqC,QAAQ,IAAI;AAEvD,SAAS,eAAgE;CACvE,MAAM,MAAM,QAAQ,IAAI;CACxB,IAAI,CAAC,KAAK,MAAM,IAAI,MAAM,kEAAkE;CAC5F,OAAO;EACL,SAAS,QAAQ,IAAI,eAAe;EACpC;EACA,OAAO,QAAQ,IAAI,gCAAgC,QAAQ,IAAI,eAAe;CAChF;AACF;AAEA,eAAe,eAAe,MAAc,OAA8B;CACxE,IAAI;EACF,MAAM,KAAK,IAAI;CACjB,SAAS,KAAK;EACZ,MAAM,IAAI,MAAM,6BAA6B,MAAM,MAAM,KAAK,IAAI,eAAe,QAAQ,IAAI,UAAU,IAAI,EAAE;CAC/G;AACF;AAEA,SAAS,YAAY,KAAkC;CACrD,MAAM,UAAU,IAAI,KAAK;CACzB,IAAI,QAAQ,WAAW,GAAG,GAAG,OAAO,KAAK,MAAM,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,MAAM,IAAI,MAAM,sEAAsE;GACjG,OAAO,kBAAkB,MAAM,IAAI;EACrC;EAEA,MAAM,aAAa,MAAiB;GAClC,MAAM,OAAO,SAAS,IAAI;GAC1B,OAAO,KAAK,mBAAmB,KAAK,mBAAmB,KAAA;EACzD;EAEA,MAAM,MAAM,MAAiB,UAAuC;GAClE,MAAM,OAAO,SAAS,IAAI;GAC1B,IAAI,cAAc,OAAO,aAAa,MAAM,QAAQ;GACpD,IAAI,SAAS,KAAK,CAAC,CAAC,WAAW,GAC7B,OAAO;IACL,UAAU;IACV,OAAO;IACP,QAAQ,KAAK,UAAU;KAAE,SAAS,KAAK;KAAS,UAAU,KAAK;KAAU,QAAQ;IAAe,CAAC;GACnG;GAEF,OAAO,iBAAiB,MAAM,MAAM,QAAQ;EAC9C;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"finresearchbench.js","names":[],"sources":["../../src/benchmarks/finresearchbench.ts"],"sourcesContent":["/**\n * FinResearchBench-compatible adapter.\n *\n * The paper defines a logic-tree Agent-as-a-Judge benchmark for financial\n * research reports, but there is no stable public scorer package wired here.\n * Live mode therefore requires a local data export whose rows carry the official\n * judge prompt/template/logic tree. The adapter refuses to invent a judge.\n */\n\nimport { readFile, stat } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport type { AgentTurnUsage } from '@tangle-network/agent-runtime/kernel'\nimport { runBenchRouterTurn } from '../router-turn'\nimport { benchRoot } from './_harness'\nimport { type BenchEvaluation, type BenchTask, type LoadOptions, type RuntimeBenchmark, runtimeBenchmark } from './types'\n\nconst FIXTURES = join(benchRoot, 'fixtures', 'finresearchbench.json')\n\ninterface FinResearchRecord {\n id: string\n question: string\n category?: string\n reference_answer?: string\n reference_report?: string\n logic_tree?: unknown\n rubric?: unknown\n judge_system_prompt?: string\n judge_prompt_template?: string\n}\n\ninterface FinResearchMeta {\n id: string\n category: string\n question: string\n referenceAnswer: string\n referenceReport: string\n logicTree: unknown\n rubric: unknown\n judgeSystemPrompt?: string\n judgePromptTemplate?: string\n scoring: 'official-logic-tree-judge' | 'fixture-exact-reference'\n}\n\nconst dataFile = (): string | undefined => process.env.FINRESEARCHBENCH_DATA_FILE\n\nfunction routerConfig(): { baseUrl: string; key: string; model: string } {\n const key = process.env.TANGLE_API_KEY\n if (!key) throw new Error('TANGLE_API_KEY is required for FinResearchBench live LLM judging')\n return {\n baseUrl: process.env.ROUTER_BASE ?? 'https://router.tangle.tools/v1',\n key,\n model: process.env.FINRESEARCHBENCH_JUDGE_MODEL ?? process.env.JUDGE_MODEL ?? 'deepseek/deepseek-v4.1-flash',\n }\n}\n\nasync function assertReadable(path: string, label: string): Promise<void> {\n try {\n await stat(path)\n } catch (err) {\n throw new Error(`FinResearchBench: missing ${label} at ${path} (${err instanceof Error ? err.message : err})`)\n }\n}\n\nfunction readRecords(raw: string): FinResearchRecord[] {\n const trimmed = raw.trim()\n if (trimmed.startsWith('[')) return JSON.parse(trimmed) as FinResearchRecord[]\n return trimmed\n .split(/\\r?\\n/)\n .map((line) => line.trim())\n .filter((line) => line.length > 0)\n .map((line) => JSON.parse(line) as FinResearchRecord)\n}\n\nfunction assertLiveJudgeFields(records: readonly FinResearchRecord[], source: string): void {\n const missing = records\n .filter((row) => !row.judge_system_prompt || !row.judge_prompt_template)\n .map((row) => row.id)\n if (missing.length > 0) {\n throw new Error(\n `FinResearchBench live rows from ${source} missing official judge prompts for ${missing.length}/${records.length} row(s): ${missing.slice(0, 5).join(', ')}. ` +\n 'Use a benchmark export with judge_system_prompt and judge_prompt_template, or do not score this benchmark live.',\n )\n }\n}\n\nfunction rowToTask(row: FinResearchRecord, fixturesMode: boolean): BenchTask {\n const referenceAnswer = row.reference_answer ?? ''\n const referenceReport = row.reference_report ?? referenceAnswer\n const meta: FinResearchMeta = {\n id: row.id,\n category: row.category ?? 'unknown',\n question: row.question,\n referenceAnswer,\n referenceReport,\n logicTree: row.logic_tree ?? null,\n rubric: row.rubric ?? null,\n judgeSystemPrompt: row.judge_system_prompt,\n judgePromptTemplate: row.judge_prompt_template,\n scoring: fixturesMode ? 'fixture-exact-reference' : 'official-logic-tree-judge',\n }\n return {\n id: row.id,\n payload: {\n subset: row.category,\n prompt: [\n 'Complete this FinResearchBench financial research task.',\n 'Produce a decision-grade research answer with explicit reasoning, evidence, and final conclusion.',\n '',\n row.question,\n ].join('\\n'),\n },\n metadata: meta as unknown as Record<string, unknown>,\n }\n}\n\nfunction readMeta(task: BenchTask): FinResearchMeta {\n const md = task.metadata\n if (!md || typeof md.question !== 'string') {\n throw new Error(`FinResearchBench task ${task.id} missing metadata — loadAll did not populate it`)\n }\n return md as unknown as FinResearchMeta\n}\n\nfunction selectRows(rows: FinResearchRecord[], opts: LoadOptions, fixturesMode: boolean): BenchTask[] {\n let tasks = rows.map((row) => rowToTask(row, fixturesMode))\n if (opts.subset) tasks = tasks.filter((task) => task.payload.subset === opts.subset)\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(`FinResearchBench: no tasks matched ${JSON.stringify(opts)}`)\n return tasks\n}\n\nasync function loadFixtures(opts: LoadOptions): Promise<BenchTask[]> {\n const records = readRecords(await readFile(FIXTURES, 'utf8'))\n console.warn(`[finresearchbench] FINRESEARCHBENCH_FIXTURES=1 — loading ${records.length} adapter fixtures`)\n return selectRows(records, opts, true)\n}\n\nasync function loadOfficialTasks(path: string, opts: LoadOptions): Promise<BenchTask[]> {\n const records = readRecords(await readFile(path, 'utf8'))\n assertLiveJudgeFields(records, path)\n return selectRows(records, opts, false)\n}\n\nfunction fillTemplate(meta: FinResearchMeta, response: string): string {\n const template = meta.judgePromptTemplate\n if (!template) throw new Error(`FinResearchBench task ${meta.id} missing judge_prompt_template`)\n return template\n .replaceAll('{question}', meta.question)\n .replaceAll('{response}', response)\n .replaceAll('{reference_answer}', meta.referenceAnswer)\n .replaceAll('{reference_report}', meta.referenceReport)\n .replaceAll('{logic_tree}', JSON.stringify(meta.logicTree, null, 2))\n .replaceAll('{rubric}', JSON.stringify(meta.rubric, null, 2))\n}\n\nfunction parseJudgeScore(content: string): { score: number; raw: unknown } {\n const candidates: string[] = []\n for (const m of content.matchAll(/```(?:json)?\\s*([\\s\\S]*?)```/g)) candidates.push(m[1].trim())\n for (const m of content.matchAll(/\\{[\\s\\S]*?\\}/g)) candidates.push(m[0])\n candidates.push(content.trim())\n for (const candidate of candidates) {\n let parsed: Record<string, unknown>\n try {\n parsed = JSON.parse(candidate) as Record<string, unknown>\n } catch {\n continue\n }\n const raw = parsed.score ?? parsed.overall_score ?? parsed.total_score ?? parsed.answer_score\n const n = typeof raw === 'number' ? raw : typeof raw === 'string' ? Number(raw) : NaN\n if (!Number.isFinite(n)) continue\n if (n < 0) throw new Error(`FinResearchBench judge score is negative: ${JSON.stringify(parsed)}`)\n const score = n <= 1 ? n : n <= 10 ? n / 10 : n / 100\n if (score > 1) throw new Error(`FinResearchBench judge score outside supported range: ${JSON.stringify(parsed)}`)\n return { score, raw: parsed }\n }\n throw new Error(`FinResearchBench judge produced no parseable JSON score: ${content.slice(0, 400)}`)\n}\n\n/**\n * Map one drained judge turn to a BenchEvaluation. The judge turn's exact Runtime\n * usage record lands on `judgeUsage` verbatim, so an unproven token count or\n * dollar amount stays flagged (`tokensKnown`/`usdKnown` false) instead of\n * reading as a known zero cost.\n */\nexport function scoreOfficialJudgeTurn(\n task: BenchTask,\n turn: Readonly<{ finalText?: string; usage: AgentTurnUsage }>,\n requestedJudgeModel: string,\n): BenchEvaluation {\n const meta = readMeta(task)\n const content = turn.finalText\n if (!content) throw new Error('FinResearchBench judge returned no message content')\n const { score, raw } = parseJudgeScore(content)\n const detail = { scoring: meta.scoring, category: meta.category, judgeModel: requestedJudgeModel, raw }\n return {\n passed: score >= Number(process.env.FINRESEARCHBENCH_PASS_THRESHOLD ?? 0.8),\n score,\n notes: JSON.stringify(detail),\n raw: detail,\n judgeUsage: turn.usage,\n }\n}\n\nasync function runOfficialJudge(task: BenchTask, meta: FinResearchMeta, response: string): Promise<BenchEvaluation> {\n if (!meta.judgeSystemPrompt) throw new Error(`FinResearchBench task ${meta.id} missing judge_system_prompt`)\n const router = routerConfig()\n const turn = await runBenchRouterTurn(\n {\n routerBaseUrl: router.baseUrl,\n routerKey: router.key,\n profile: {\n name: 'finresearchbench-judge',\n harness: 'cli-base',\n model: {\n provider: 'tangle-router',\n default: router.model,\n metadata: { temperature: 0 },\n },\n prompt: { systemPrompt: meta.judgeSystemPrompt },\n },\n },\n fillTemplate(meta, response),\n )\n return scoreOfficialJudgeTurn(task, turn, router.model)\n}\n\nfunction normalizeText(value: string): string {\n return value.toLowerCase().replace(/\\s+/g, ' ').trim()\n}\n\nfunction scoreFixture(meta: FinResearchMeta, artifact: string): BenchEvaluation {\n const answer = normalizeText(meta.referenceAnswer || meta.referenceReport)\n const response = normalizeText(artifact)\n const score = answer.length > 0 && response.includes(answer) ? 1 : 0\n const raw = { scoring: meta.scoring, category: meta.category }\n return {\n passed: score === 1,\n score,\n notes: JSON.stringify(raw),\n raw,\n }\n}\n\nexport function createFinResearchBenchAdapter(): RuntimeBenchmark {\n const fixturesMode = process.env.FINRESEARCHBENCH_FIXTURES === '1'\n\n return runtimeBenchmark({\n id: 'finresearchbench',\n\n async loadAll(opts: LoadOptions = {}) {\n if (fixturesMode) return loadFixtures(opts)\n const file = dataFile()\n if (!file) throw new Error('FINRESEARCHBENCH_DATA_FILE is required to load FinResearchBench rows')\n return loadOfficialTasks(file, opts)\n },\n\n async evaluate(task: BenchTask, artifact: string): Promise<BenchEvaluation> {\n const meta = readMeta(task)\n if (fixturesMode) return scoreFixture(meta, artifact)\n if (artifact.trim().length === 0) {\n const raw = { scoring: meta.scoring, category: meta.category, reason: 'empty answer' }\n return {\n passed: false,\n score: 0,\n notes: JSON.stringify(raw),\n raw,\n }\n }\n return runOfficialJudge(task, meta, artifact)\n },\n\n runtime: {\n async preflight() {\n if (fixturesMode) {\n await assertReadable(FIXTURES, 'fixture file')\n return\n }\n const file = dataFile()\n if (!file) {\n throw new Error(\n 'FINRESEARCHBENCH_DATA_FILE is required. Fix: export the official FinResearchBench rows as JSON/JSONL with judge_system_prompt and judge_prompt_template fields, then set FINRESEARCHBENCH_DATA_FILE=/path/to/export.jsonl.',\n )\n }\n routerConfig()\n await assertReadable(file, 'data file')\n await loadOfficialTasks(file, { limit: 1 })\n },\n\n async goldArtifact(task: BenchTask) {\n const meta = readMeta(task)\n return meta.referenceReport || meta.referenceAnswer || undefined\n },\n },\n })\n}\n"],"mappings":";;;;;;;;;;;;;;AAgBA,MAAM,WAAW,KAAK,WAAW,YAAY,uBAAuB;AA2BpE,MAAM,iBAAqC,QAAQ,IAAI;AAEvD,SAAS,eAAgE;CACvE,MAAM,MAAM,QAAQ,IAAI;CACxB,IAAI,CAAC,KAAK,MAAM,IAAI,MAAM,kEAAkE;CAC5F,OAAO;EACL,SAAS,QAAQ,IAAI,eAAe;EACpC;EACA,OAAO,QAAQ,IAAI,gCAAgC,QAAQ,IAAI,eAAe;CAChF;AACF;AAEA,eAAe,eAAe,MAAc,OAA8B;CACxE,IAAI;EACF,MAAM,KAAK,IAAI;CACjB,SAAS,KAAK;EACZ,MAAM,IAAI,MAAM,6BAA6B,MAAM,MAAM,KAAK,IAAI,eAAe,QAAQ,IAAI,UAAU,IAAI,EAAE;CAC/G;AACF;AAEA,SAAS,YAAY,KAAkC;CACrD,MAAM,UAAU,IAAI,KAAK;CACzB,IAAI,QAAQ,WAAW,GAAG,GAAG,OAAO,KAAK,MAAM,OAAO;CACtD,OAAO,QACJ,MAAM,OAAO,CAAC,CACd,KAAK,SAAS,KAAK,KAAK,CAAC,CAAC,CAC1B,QAAQ,SAAS,KAAK,SAAS,CAAC,CAAC,CACjC,KAAK,SAAS,KAAK,MAAM,IAAI,CAAsB;AACxD;AAEA,SAAS,sBAAsB,SAAuC,QAAsB;CAC1F,MAAM,UAAU,QACb,QAAQ,QAAQ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AAM,QAAQ;EAC9C;EAEA,SAAS;GACP,MAAM,YAAY;IAChB,IAAI,cAAc;KAChB,MAAM,eAAe,UAAU,cAAc;KAC7C;IACF;IACA,MAAM,OAAO,SAAS;IACtB,IAAI,CAAC,MACH,MAAM,IAAI,MACR,4NACF;IAEF,aAAa;IACb,MAAM,eAAe,MAAM,WAAW;IACtC,MAAM,kBAAkB,MAAM,EAAE,OAAO,EAAE,CAAC;GAC5C;GAEA,MAAM,aAAa,MAAiB;IAClC,MAAM,OAAO,SAAS,IAAI;IAC1B,OAAO,KAAK,mBAAmB,KAAK,mBAAmB,KAAA;GACzD;EACF;CACF,CAAC;AACH"}
|
|
@@ -1,15 +1,15 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { RuntimeBenchmark } from "./types.js";
|
|
2
2
|
/**
|
|
3
3
|
* Typed seam for T1 (Time_Sensitive_Data_Fetching). T1 records score against a
|
|
4
4
|
* live market snapshot the judge consumes via a {ground_truth} template slot;
|
|
5
5
|
* the adapter does NOT fabricate that snapshot. Wiring T1 means supplying a
|
|
6
6
|
* resolver that fetches the akshare/market value for the record at judge time
|
|
7
|
-
* and filling {ground_truth}. Until then T1 is excluded from
|
|
7
|
+
* and filling {ground_truth}. Until then T1 is excluded from loadAll.
|
|
8
8
|
*/
|
|
9
9
|
export interface T1Seam {
|
|
10
10
|
promptId: string;
|
|
11
11
|
/** Resolver that returns the real-time ground-truth block for the {ground_truth} slot. */
|
|
12
12
|
resolveGroundTruth(promptId: string): Promise<string>;
|
|
13
13
|
}
|
|
14
|
-
export declare function createFinsearchcompAdapter():
|
|
14
|
+
export declare function createFinsearchcompAdapter(): RuntimeBenchmark;
|
|
15
15
|
//# sourceMappingURL=finsearchcomp.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 { readFile } from "node:fs/promises";
|
|
3
4
|
import { join } from "node:path";
|
|
4
5
|
import { fileURLToPath } from "node:url";
|
|
@@ -13,23 +14,23 @@ import { fileURLToPath } from "node:url";
|
|
|
13
14
|
* and {response} (the student answer) placeholders. We faithfully REPLICATE the
|
|
14
15
|
* benchmark's judge — fill the template, run it under the record's system prompt
|
|
15
16
|
* via the pinned router (temperature 0), and parse the JSON the judge emits. The
|
|
16
|
-
* judge returns an `answer_score` field; 1/positive =
|
|
17
|
+
* judge returns an `answer_score` field; 1/positive = passed, else not.
|
|
17
18
|
* This matches the FinSearchComp leaderboard (Grok-4-web 68.9%).
|
|
18
19
|
*
|
|
19
20
|
* There is NO deterministic Tier-1 path here: the gold answer is prose with
|
|
20
21
|
* region-specific units, embedded tolerances ("允许1%的误差"), and multi-point
|
|
21
22
|
* scoring criteria. The benchmark intends its own LLM judge to be the arbiter,
|
|
22
23
|
* so the judge IS the score — fail loud on unparseable judge output (never
|
|
23
|
-
* default to
|
|
24
|
+
* default to passed).
|
|
24
25
|
*
|
|
25
26
|
* SCOPE: T2 (Simple_Historical_Lookup) + T3 (Complex_Historical_Investigation)
|
|
26
27
|
* are fully self-contained and supported. T1 (Time_Sensitive_Data_Fetching)
|
|
27
28
|
* needs a live market snapshot / akshare ground truth to fill the judge's
|
|
28
|
-
* {ground_truth} slot — it is SKIPPED in
|
|
29
|
+
* {ground_truth} slot — it is SKIPPED in loadAll and flagged in preflight.
|
|
29
30
|
* See {@link T1Seam}.
|
|
30
31
|
*
|
|
31
32
|
* Requires for a live run: network access to the GitHub-hosted dataset JSON and
|
|
32
|
-
* a TANGLE_API_KEY for the judge. For offline/CI verification,
|
|
33
|
+
* a TANGLE_API_KEY for the judge. For offline/CI verification, loadAll falls back
|
|
33
34
|
* to the committed fixtures (bench/fixtures/finsearchcomp.json) with an explicit
|
|
34
35
|
* console.warn — never a silent fallback.
|
|
35
36
|
*/
|
|
@@ -75,14 +76,16 @@ function recordToTask(rec) {
|
|
|
75
76
|
};
|
|
76
77
|
return {
|
|
77
78
|
id: rec.prompt_id,
|
|
78
|
-
|
|
79
|
-
|
|
79
|
+
payload: {
|
|
80
|
+
prompt: rec.prompt + WORKER_CONTRACT,
|
|
81
|
+
subset: taskType
|
|
82
|
+
},
|
|
80
83
|
metadata: meta
|
|
81
84
|
};
|
|
82
85
|
}
|
|
83
86
|
function readMeta(task) {
|
|
84
87
|
const md = task.metadata;
|
|
85
|
-
if (!md || typeof md.responseReference !== "string" || typeof md.judgePromptTemplate !== "string" || typeof md.judgeSystemPrompt !== "string" || typeof md.rawPrompt !== "string") throw new Error(`FinSearchComp task ${task.id} missing judge metadata —
|
|
88
|
+
if (!md || typeof md.responseReference !== "string" || typeof md.judgePromptTemplate !== "string" || typeof md.judgeSystemPrompt !== "string" || typeof md.rawPrompt !== "string") throw new Error(`FinSearchComp task ${task.id} missing judge metadata — loadAll did not populate it`);
|
|
86
89
|
return md;
|
|
87
90
|
}
|
|
88
91
|
/** Fill the per-record judge_prompt_template. {ground_truth} is T1-only and unused for T2/T3. */
|
|
@@ -92,7 +95,7 @@ function fillJudgePrompt(meta, response) {
|
|
|
92
95
|
function judgeRouter() {
|
|
93
96
|
const key = process.env.TANGLE_API_KEY;
|
|
94
97
|
if (!key) throw new Error("TANGLE_API_KEY is required for the FinSearchComp per-record LLM judge");
|
|
95
|
-
const model = process.env.JUDGE_MODEL ?? "deepseek-v4-flash";
|
|
98
|
+
const model = process.env.JUDGE_MODEL ?? "deepseek/deepseek-v4.1-flash";
|
|
96
99
|
return {
|
|
97
100
|
baseUrl: process.env.ROUTER_BASE ?? "https://router.tangle.tools/v1",
|
|
98
101
|
key,
|
|
@@ -156,20 +159,22 @@ async function runRecordJudge(meta, response, router) {
|
|
|
156
159
|
}, fillJudgePrompt(meta, response))).finalText;
|
|
157
160
|
if (!content) throw new Error("FinSearchComp judge returned no message content");
|
|
158
161
|
const { resolved, score, raw } = parseJudgeOutput(content);
|
|
162
|
+
const evidence = {
|
|
163
|
+
taskType: meta.taskType,
|
|
164
|
+
region: meta.region,
|
|
165
|
+
answerScore: raw,
|
|
166
|
+
judgeModel: router.model
|
|
167
|
+
};
|
|
159
168
|
return {
|
|
160
|
-
resolved,
|
|
169
|
+
passed: resolved,
|
|
161
170
|
score,
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
region: meta.region,
|
|
165
|
-
answerScore: raw,
|
|
166
|
-
judgeModel: router.model
|
|
167
|
-
})
|
|
171
|
+
notes: JSON.stringify(evidence),
|
|
172
|
+
raw: evidence
|
|
168
173
|
};
|
|
169
174
|
}
|
|
170
175
|
function selectRecords(records, opts) {
|
|
171
176
|
let tasks = records.filter((r) => SUPPORTED_TYPES.has(parseTaskType(r.prompt_id))).map(recordToTask);
|
|
172
|
-
if (opts.
|
|
177
|
+
if (opts.subset) tasks = tasks.filter((t) => t.payload.subset === opts.subset);
|
|
173
178
|
if (opts.ids) {
|
|
174
179
|
const want = new Set(opts.ids);
|
|
175
180
|
tasks = tasks.filter((t) => want.has(t.id));
|
|
@@ -211,23 +216,9 @@ async function fetchDataset() {
|
|
|
211
216
|
}
|
|
212
217
|
function createFinsearchcompAdapter() {
|
|
213
218
|
const fixturesMode = process.env.FINSEARCHCOMP_FIXTURES === "1";
|
|
214
|
-
return {
|
|
215
|
-
|
|
216
|
-
async
|
|
217
|
-
judgeRouter();
|
|
218
|
-
console.warn("[finsearchcomp] T1 (Time_Sensitive_Data_Fetching) is NOT scored: it needs a live market snapshot / akshare ground truth for the judge {ground_truth} slot. loadTasks supports T2 + T3 only; wire T1Seam to add T1.");
|
|
219
|
-
if (fixturesMode) {
|
|
220
|
-
await readFile(FIXTURES, "utf8").catch((err) => {
|
|
221
|
-
throw new Error(`FINSEARCHCOMP_FIXTURES=1 but ${FIXTURES} unreadable: ${err instanceof Error ? err.message : err}`);
|
|
222
|
-
});
|
|
223
|
-
return;
|
|
224
|
-
}
|
|
225
|
-
const res = await fetch(DATASET_URL, { method: "HEAD" }).catch((err) => {
|
|
226
|
-
throw new Error(`finsearchcomp preflight failed reaching ${DATASET_URL}: ${err instanceof Error ? err.message : err}\nFix: ensure network access to raw.githubusercontent.com, or set FINSEARCHCOMP_FIXTURES=1 to run against the committed fixtures offline.`);
|
|
227
|
-
});
|
|
228
|
-
if (!res.ok) throw new Error(`finsearchcomp preflight: dataset HEAD ${res.status} for ${DATASET_URL}. Set FINSEARCHCOMP_FIXTURES=1 to run against the committed fixtures offline.`);
|
|
229
|
-
},
|
|
230
|
-
async loadTasks(opts = {}) {
|
|
219
|
+
return runtimeBenchmark({
|
|
220
|
+
id: "finsearchcomp",
|
|
221
|
+
async loadAll(opts = {}) {
|
|
231
222
|
if (fixturesMode) return loadFixtures(opts);
|
|
232
223
|
let records;
|
|
233
224
|
try {
|
|
@@ -238,24 +229,44 @@ function createFinsearchcompAdapter() {
|
|
|
238
229
|
}
|
|
239
230
|
return selectRecords(records, opts);
|
|
240
231
|
},
|
|
241
|
-
async
|
|
242
|
-
return readMeta(task).responseReference;
|
|
243
|
-
},
|
|
244
|
-
async judge(task, artifact) {
|
|
232
|
+
async evaluate(task, artifact) {
|
|
245
233
|
const meta = readMeta(task);
|
|
246
234
|
const response = artifact.trim();
|
|
247
|
-
if (response.length === 0)
|
|
248
|
-
|
|
249
|
-
score: 0,
|
|
250
|
-
detail: JSON.stringify({
|
|
235
|
+
if (response.length === 0) {
|
|
236
|
+
const raw = {
|
|
251
237
|
taskType: meta.taskType,
|
|
252
238
|
region: meta.region,
|
|
253
239
|
reason: "empty answer"
|
|
254
|
-
}
|
|
255
|
-
|
|
240
|
+
};
|
|
241
|
+
return {
|
|
242
|
+
passed: false,
|
|
243
|
+
score: 0,
|
|
244
|
+
notes: JSON.stringify(raw),
|
|
245
|
+
raw
|
|
246
|
+
};
|
|
247
|
+
}
|
|
256
248
|
return runRecordJudge(meta, response, judgeRouter());
|
|
249
|
+
},
|
|
250
|
+
runtime: {
|
|
251
|
+
async preflight() {
|
|
252
|
+
judgeRouter();
|
|
253
|
+
console.warn("[finsearchcomp] T1 (Time_Sensitive_Data_Fetching) is NOT scored: it needs a live market snapshot / akshare ground truth for the judge {ground_truth} slot. loadAll supports T2 + T3 only; wire T1Seam to add T1.");
|
|
254
|
+
if (fixturesMode) {
|
|
255
|
+
await readFile(FIXTURES, "utf8").catch((err) => {
|
|
256
|
+
throw new Error(`FINSEARCHCOMP_FIXTURES=1 but ${FIXTURES} unreadable: ${err instanceof Error ? err.message : err}`);
|
|
257
|
+
});
|
|
258
|
+
return;
|
|
259
|
+
}
|
|
260
|
+
const res = await fetch(DATASET_URL, { method: "HEAD" }).catch((err) => {
|
|
261
|
+
throw new Error(`finsearchcomp preflight failed reaching ${DATASET_URL}: ${err instanceof Error ? err.message : err}\nFix: ensure network access to raw.githubusercontent.com, or set FINSEARCHCOMP_FIXTURES=1 to run against the committed fixtures offline.`);
|
|
262
|
+
});
|
|
263
|
+
if (!res.ok) throw new Error(`finsearchcomp preflight: dataset HEAD ${res.status} for ${DATASET_URL}. Set FINSEARCHCOMP_FIXTURES=1 to run against the committed fixtures offline.`);
|
|
264
|
+
},
|
|
265
|
+
async goldArtifact(task) {
|
|
266
|
+
return readMeta(task).responseReference;
|
|
267
|
+
}
|
|
257
268
|
}
|
|
258
|
-
};
|
|
269
|
+
});
|
|
259
270
|
}
|
|
260
271
|
export { createFinsearchcompAdapter };
|
|
261
272
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"finsearchcomp.js","names":[],"sources":["../../src/benchmarks/finsearchcomp.ts"],"sourcesContent":["/**\n * FinSearchComp adapter (randomtutu/FinSearchComp). Agentic financial search +\n * reasoning. Worker artifact = the agent's free-form final answer text (zh/en).\n *\n * Each record is SELF-CONTAINED and carries its OWN judge: a per-record\n * `judge_system_prompt` + a `judge_prompt_template` with {prompt},\n * {response_reference} (gold answer WITH embedded tolerance/scoring-criteria),\n * and {response} (the student answer) placeholders. We faithfully REPLICATE the\n * benchmark's judge — fill the template, run it under the record's system prompt\n * via the pinned router (temperature 0), and parse the JSON the judge emits. The\n * judge returns an `answer_score` field; 1/positive = resolved, else not.\n * This matches the FinSearchComp leaderboard (Grok-4-web 68.9%).\n *\n * There is NO deterministic Tier-1 path here: the gold answer is prose with\n * region-specific units, embedded tolerances (\"允许1%的误差\"), and multi-point\n * scoring criteria. The benchmark intends its own LLM judge to be the arbiter,\n * so the judge IS the score — fail loud on unparseable judge output (never\n * default to resolved).\n *\n * SCOPE: T2 (Simple_Historical_Lookup) + T3 (Complex_Historical_Investigation)\n * are fully self-contained and supported. T1 (Time_Sensitive_Data_Fetching)\n * needs a live market snapshot / akshare ground truth to fill the judge's\n * {ground_truth} slot — it is SKIPPED in loadTasks and flagged in preflight.\n * See {@link T1Seam}.\n *\n * Requires for a live run: network access to the GitHub-hosted dataset JSON and\n * a TANGLE_API_KEY for the judge. For offline/CI verification, loadTasks falls back\n * to the committed fixtures (bench/fixtures/finsearchcomp.json) with an explicit\n * console.warn — never a silent fallback.\n */\n\nimport { readFile } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport { runBenchRouterTurn } from '../router-turn'\nimport type { BenchmarkAdapter, BenchScore, BenchTask, LoadOptions } from './types'\n\nconst BENCH_ROOT = fileURLToPath(new URL('../..', import.meta.url))\nconst FIXTURES = join(BENCH_ROOT, 'fixtures', 'finsearchcomp.json')\n\nconst DATASET_URL =\n 'https://raw.githubusercontent.com/randomtutu/FinSearchComp/main/data/finsearchcomp_data.json'\n\n/** Task-type prefix on prompt_id, e.g. \"(T2)Simple_Historical_Lookup_001\". */\ntype TaskType = 'T1' | 'T2' | 'T3'\n/** Only these are self-contained (gold + own judge, no external ground truth). */\nconst SUPPORTED_TYPES: ReadonlySet<TaskType> = new Set<TaskType>(['T2', 'T3'])\n\n/**\n * Worker contract appended to every task prompt. The judge is paraphrase- and\n * keyword-aware (\"答案为\", \"the answer is\"), so we do not impose a sentinel; we\n * pass the whole artifact through as {response}. We DO ask the worker to lead\n * with its final value so a truncated artifact still carries the answer.\n */\nconst WORKER_CONTRACT = [\n '',\n 'Research this financial question using live web/market sources and answer it.',\n 'State your final answer explicitly, with the exact units and precision the question requests.',\n 'Respect any tolerance the question implies; show the value you settled on, not just intermediate work.',\n].join('\\n')\n\n/**\n * Typed seam for T1 (Time_Sensitive_Data_Fetching). T1 records score against a\n * live market snapshot the judge consumes via a {ground_truth} template slot;\n * the adapter does NOT fabricate that snapshot. Wiring T1 means supplying a\n * resolver that fetches the akshare/market value for the record at judge time\n * and filling {ground_truth}. Until then T1 is excluded from loadTasks.\n */\nexport interface T1Seam {\n promptId: string\n /** Resolver that returns the real-time ground-truth block for the {ground_truth} slot. */\n resolveGroundTruth(promptId: string): Promise<string>\n}\n\ninterface FinSearchRecord {\n prompt_id: string\n prompt: string\n response_reference: string\n judge_prompt_template: string\n judge_system_prompt: string\n label: string\n}\n\ninterface FinSearchMeta {\n promptId: string\n label: string\n taskType: TaskType\n region: string\n responseReference: string\n judgePromptTemplate: string\n judgeSystemPrompt: string\n rawPrompt: string\n}\n\n/** \"(T2)Simple_Historical_Lookup_001\" → \"T2\"; throws on an unknown/missing prefix. */\nfunction parseTaskType(promptId: string): TaskType {\n const m = promptId.match(/^\\((T[123])\\)/)\n if (!m) throw new Error(`FinSearchComp prompt_id has no (T1|T2|T3) prefix: ${JSON.stringify(promptId)}`)\n return m[1] as TaskType\n}\n\n/** \"Simple_Historical_Lookup(Greater China)\" → \"Greater China\"; '' when absent. */\nfunction parseRegion(label: string): string {\n const m = label.match(/\\(([^()]+)\\)\\s*$/)\n return m ? m[1].trim() : ''\n}\n\nfunction recordToTask(rec: FinSearchRecord): BenchTask {\n const taskType = parseTaskType(rec.prompt_id)\n const meta: FinSearchMeta = {\n promptId: rec.prompt_id,\n label: rec.label,\n taskType,\n region: parseRegion(rec.label),\n responseReference: rec.response_reference,\n judgePromptTemplate: rec.judge_prompt_template,\n judgeSystemPrompt: rec.judge_system_prompt,\n rawPrompt: rec.prompt,\n }\n return {\n id: rec.prompt_id,\n split: taskType,\n prompt: rec.prompt + WORKER_CONTRACT,\n metadata: meta as unknown as Record<string, unknown>,\n }\n}\n\nfunction readMeta(task: BenchTask): FinSearchMeta {\n const md = task.metadata\n if (\n !md ||\n typeof md.responseReference !== 'string' ||\n typeof md.judgePromptTemplate !== 'string' ||\n typeof md.judgeSystemPrompt !== 'string' ||\n typeof md.rawPrompt !== 'string'\n ) {\n throw new Error(`FinSearchComp task ${task.id} missing judge metadata — loadTasks did not populate it`)\n }\n return md as unknown as FinSearchMeta\n}\n\n/** Fill the per-record judge_prompt_template. {ground_truth} is T1-only and unused for T2/T3. */\nfunction fillJudgePrompt(meta: FinSearchMeta, response: string): string {\n return meta.judgePromptTemplate\n .replaceAll('{prompt}', meta.rawPrompt)\n .replaceAll('{response_reference}', meta.responseReference)\n .replaceAll('{response}', response)\n}\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 FinSearchComp per-record LLM judge')\n const model = process.env.JUDGE_MODEL ?? 'deepseek-v4-flash'\n const baseUrl = process.env.ROUTER_BASE ?? 'https://router.tangle.tools/v1'\n return { baseUrl, key, model }\n}\n\n/**\n * The judge emits a JSON object with an `answer_score`. In this dataset it is a\n * flat integer ({\"answer_score\": 1}); we also accept the nested-array form\n * ([[1]] → read [0][0]) the upstream scorer can produce. 1/positive = resolved.\n * A \"null\" sentinel (judge could not obtain ground truth) is NOT a pass.\n */\nfunction readAnswerScore(value: unknown): { resolved: boolean; score: number; raw: unknown } {\n let v: unknown = value\n // unwrap nested-array form: [[s]] / [s]\n while (Array.isArray(v)) v = v[0]\n if (v === null || v === undefined || v === 'null') {\n return { resolved: false, score: 0, raw: value }\n }\n const n = typeof v === 'number' ? v : typeof v === 'string' ? Number(v) : NaN\n if (!Number.isFinite(n)) {\n throw new Error(`FinSearchComp judge answer_score not numeric: ${JSON.stringify(value)}`)\n }\n // Their scale: 1 = correct, 0 = wrong. Treat any positive as resolved; clamp to 0..1.\n const resolved = n >= 1\n const score = n <= 0 ? 0 : n >= 1 ? 1 : n\n return { resolved, score, raw: value }\n}\n\n/** Extract the first JSON object carrying `answer_score` from judge output; throw if none. */\nfunction parseJudgeOutput(content: string): { resolved: boolean; score: number; raw: unknown } {\n // Prefer a fenced block, then fall back to scanning for a {...} with answer_score.\n const candidates: string[] = []\n for (const m of content.matchAll(/```(?:json)?\\s*([\\s\\S]*?)```/g)) candidates.push(m[1].trim())\n for (const m of content.matchAll(/\\{[^{}]*\"answer_score\"[\\s\\S]*?\\}/g)) candidates.push(m[0])\n candidates.push(content.trim())\n for (const c of candidates) {\n let parsed: { answer_score?: unknown }\n try {\n parsed = JSON.parse(c) as { answer_score?: unknown }\n } catch {\n continue\n }\n if ('answer_score' in parsed) return readAnswerScore(parsed.answer_score)\n }\n throw new Error(\n `FinSearchComp judge produced no parseable {\"answer_score\": …}: ${content.slice(0, 400)}`,\n )\n}\n\n/** Run the record's own judge via the router. Fail loud on transport/parse errors. */\nasync function runRecordJudge(meta: FinSearchMeta, response: string, router: JudgeRouter): Promise<BenchScore> {\n const turn = await runBenchRouterTurn(\n {\n routerBaseUrl: router.baseUrl,\n routerKey: router.key,\n profile: {\n name: 'finsearchcomp-judge',\n harness: 'cli-base',\n model: {\n provider: 'tangle-router',\n default: router.model,\n metadata: { temperature: 0 },\n },\n prompt: { systemPrompt: meta.judgeSystemPrompt },\n },\n },\n fillJudgePrompt(meta, response),\n )\n const content = turn.finalText\n if (!content) throw new Error('FinSearchComp judge returned no message content')\n const { resolved, score, raw } = parseJudgeOutput(content)\n return {\n resolved,\n score,\n detail: JSON.stringify({\n taskType: meta.taskType,\n region: meta.region,\n answerScore: raw,\n judgeModel: router.model,\n }),\n }\n}\n\nfunction selectRecords(records: FinSearchRecord[], opts: LoadOptions): BenchTask[] {\n let tasks = records\n .filter((r) => SUPPORTED_TYPES.has(parseTaskType(r.prompt_id)))\n .map(recordToTask)\n if (opts.split) tasks = tasks.filter((t) => t.split === opts.split)\n if (opts.ids) {\n const want = new Set(opts.ids)\n tasks = tasks.filter((t) => want.has(t.id))\n } else if (opts.limit !== undefined) {\n tasks = balanceByType(tasks, opts.limit)\n }\n return tasks\n}\n\n/** Round-robin across task types (T2/T3) so a `limit` pulls a balanced mix\n * rather than slicing the type-ordered dataset's first N (which yields all\n * T2). Deterministic — preserves dataset order within each type. */\nfunction balanceByType(tasks: BenchTask[], limit: number): BenchTask[] {\n const queues = new Map<TaskType, BenchTask[]>()\n for (const t of tasks) {\n const k = parseTaskType(t.id)\n const q = queues.get(k)\n if (q) q.push(t)\n else queues.set(k, [t])\n }\n const lanes = [...queues.values()]\n const out: BenchTask[] = []\n for (let i = 0; out.length < limit; i++) {\n const before = out.length\n for (const lane of lanes) {\n if (i < lane.length) out.push(lane[i])\n if (out.length >= limit) break\n }\n if (out.length === before) break // all lanes exhausted\n }\n return out\n}\n\nasync function loadFixtures(opts: LoadOptions): Promise<BenchTask[]> {\n const records = JSON.parse(await readFile(FIXTURES, 'utf8')) as FinSearchRecord[]\n return selectRecords(records, opts)\n}\n\nasync function fetchDataset(): Promise<FinSearchRecord[]> {\n const res = await fetch(DATASET_URL)\n if (!res.ok) throw new Error(`FinSearchComp dataset HTTP ${res.status} fetching ${DATASET_URL}`)\n const data = (await res.json()) as FinSearchRecord[]\n if (!Array.isArray(data) || data.length === 0) {\n throw new Error(`FinSearchComp dataset empty or not an array: ${DATASET_URL}`)\n }\n return data\n}\n\nexport function createFinsearchcompAdapter(): BenchmarkAdapter {\n const fixturesMode = process.env.FINSEARCHCOMP_FIXTURES === '1'\n\n return {\n name: 'finsearchcomp',\n\n async preflight() {\n // The per-record LLM judge is the arbiter in both modes — its router\n // config must exist or no score can be produced.\n judgeRouter()\n console.warn(\n '[finsearchcomp] T1 (Time_Sensitive_Data_Fetching) is NOT scored: it needs a live ' +\n 'market snapshot / akshare ground truth for the judge {ground_truth} slot. ' +\n 'loadTasks supports T2 + T3 only; wire T1Seam to add T1.',\n )\n if (fixturesMode) {\n await readFile(FIXTURES, 'utf8').catch((err) => {\n throw new Error(\n `FINSEARCHCOMP_FIXTURES=1 but ${FIXTURES} unreadable: ${err instanceof Error ? err.message : err}`,\n )\n })\n return\n }\n const res = await fetch(DATASET_URL, { method: 'HEAD' }).catch((err) => {\n throw new Error(\n `finsearchcomp preflight failed reaching ${DATASET_URL}: ${err instanceof Error ? err.message : err}\\n` +\n `Fix: ensure network access to raw.githubusercontent.com, or set FINSEARCHCOMP_FIXTURES=1 ` +\n `to run against the committed fixtures offline.`,\n )\n })\n if (!res.ok) {\n throw new Error(\n `finsearchcomp preflight: dataset HEAD ${res.status} for ${DATASET_URL}. ` +\n `Set FINSEARCHCOMP_FIXTURES=1 to run against the committed fixtures offline.`,\n )\n }\n },\n\n async loadTasks(opts: LoadOptions = {}) {\n if (fixturesMode) return loadFixtures(opts)\n let records: FinSearchRecord[]\n try {\n records = await fetchDataset()\n } catch (err) {\n console.warn(\n `[finsearchcomp] live dataset fetch failed (${err instanceof Error ? err.message : err}); ` +\n `falling back to committed fixtures at ${FIXTURES}`,\n )\n return loadFixtures(opts)\n }\n return selectRecords(records, opts)\n },\n\n async goldArtifact(task: BenchTask) {\n // Gold artifact = the record's response_reference fed back as the student\n // answer, so verify-judge proves gold→resolved through the SAME per-record\n // judge the real artifact takes. The reference may carry tolerance/criteria\n // prose; the judge is built to read the value out of it.\n const meta = readMeta(task)\n return meta.responseReference\n },\n\n async judge(task: BenchTask, artifact: string): Promise<BenchScore> {\n const meta = readMeta(task)\n const response = artifact.trim()\n if (response.length === 0) {\n // Fail-closed — the benchmark's own judges score an empty answer 0.\n return {\n resolved: false,\n score: 0,\n detail: JSON.stringify({ taskType: meta.taskType, region: meta.region, reason: 'empty answer' }),\n }\n }\n return runRecordJudge(meta, response, judgeRouter())\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA,MAAM,aAAa,cAAc,IA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IAAI,MACR,yCAAyC,IAAI,OAAO,OAAO,YAAY,8EAEzE;EAEJ;EAEA,MAAM,UAAU,OAAoB,CAAC,GAAG;GACtC,IAAI,cAAc,OAAO,aAAa,IAAI;GAC1C,IAAI;GACJ,IAAI;IACF,UAAU,MAAM,aAAa;GAC/B,SAAS,KAAK;IACZ,QAAQ,KACN,8CAA8C,eAAe,QAAQ,IAAI,UAAU,IAAI,2CAC5C,UAC7C;IACA,OAAO,aAAa,IAAI;GAC1B;GACA,OAAO,cAAc,SAAS,IAAI;EACpC;EAEA,MAAM,aAAa,MAAiB;GAMlC,OADa,SAAS,IACZ,CAAC,CAAC;EACd;EAEA,MAAM,MAAM,MAAiB,UAAuC;GAClE,MAAM,OAAO,SAAS,IAAI;GAC1B,MAAM,WAAW,SAAS,KAAK;GAC/B,IAAI,SAAS,WAAW,GAEtB,OAAO;IACL,UAAU;IACV,OAAO;IACP,QAAQ,KAAK,UAAU;KAAE,UAAU,KAAK;KAAU,QAAQ,KAAK;KAAQ,QAAQ;IAAe,CAAC;GACjG;GAEF,OAAO,eAAe,MAAM,UAAU,YAAY,CAAC;EACrD;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"finsearchcomp.js","names":[],"sources":["../../src/benchmarks/finsearchcomp.ts"],"sourcesContent":["/**\n * FinSearchComp adapter (randomtutu/FinSearchComp). Agentic financial search +\n * reasoning. Worker artifact = the agent's free-form final answer text (zh/en).\n *\n * Each record is SELF-CONTAINED and carries its OWN judge: a per-record\n * `judge_system_prompt` + a `judge_prompt_template` with {prompt},\n * {response_reference} (gold answer WITH embedded tolerance/scoring-criteria),\n * and {response} (the student answer) placeholders. We faithfully REPLICATE the\n * benchmark's judge — fill the template, run it under the record's system prompt\n * via the pinned router (temperature 0), and parse the JSON the judge emits. The\n * judge returns an `answer_score` field; 1/positive = passed, else not.\n * This matches the FinSearchComp leaderboard (Grok-4-web 68.9%).\n *\n * There is NO deterministic Tier-1 path here: the gold answer is prose with\n * region-specific units, embedded tolerances (\"允许1%的误差\"), and multi-point\n * scoring criteria. The benchmark intends its own LLM judge to be the arbiter,\n * so the judge IS the score — fail loud on unparseable judge output (never\n * default to passed).\n *\n * SCOPE: T2 (Simple_Historical_Lookup) + T3 (Complex_Historical_Investigation)\n * are fully self-contained and supported. T1 (Time_Sensitive_Data_Fetching)\n * needs a live market snapshot / akshare ground truth to fill the judge's\n * {ground_truth} slot — it is SKIPPED in loadAll and flagged in preflight.\n * See {@link T1Seam}.\n *\n * Requires for a live run: network access to the GitHub-hosted dataset JSON and\n * a TANGLE_API_KEY for the judge. For offline/CI verification, loadAll falls back\n * to the committed fixtures (bench/fixtures/finsearchcomp.json) with an explicit\n * console.warn — never a silent fallback.\n */\n\nimport { readFile } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport { runBenchRouterTurn } from '../router-turn'\nimport { type BenchEvaluation, type BenchTask, type LoadOptions, type RuntimeBenchmark, runtimeBenchmark } from './types'\n\nconst BENCH_ROOT = fileURLToPath(new URL('../..', import.meta.url))\nconst FIXTURES = join(BENCH_ROOT, 'fixtures', 'finsearchcomp.json')\n\nconst DATASET_URL =\n 'https://raw.githubusercontent.com/randomtutu/FinSearchComp/main/data/finsearchcomp_data.json'\n\n/** Task-type prefix on prompt_id, e.g. \"(T2)Simple_Historical_Lookup_001\". */\ntype TaskType = 'T1' | 'T2' | 'T3'\n/** Only these are self-contained (gold + own judge, no external ground truth). */\nconst SUPPORTED_TYPES: ReadonlySet<TaskType> = new Set<TaskType>(['T2', 'T3'])\n\n/**\n * Worker contract appended to every task prompt. The judge is paraphrase- and\n * keyword-aware (\"答案为\", \"the answer is\"), so we do not impose a sentinel; we\n * pass the whole artifact through as {response}. We DO ask the worker to lead\n * with its final value so a truncated artifact still carries the answer.\n */\nconst WORKER_CONTRACT = [\n '',\n 'Research this financial question using live web/market sources and answer it.',\n 'State your final answer explicitly, with the exact units and precision the question requests.',\n 'Respect any tolerance the question implies; show the value you settled on, not just intermediate work.',\n].join('\\n')\n\n/**\n * Typed seam for T1 (Time_Sensitive_Data_Fetching). T1 records score against a\n * live market snapshot the judge consumes via a {ground_truth} template slot;\n * the adapter does NOT fabricate that snapshot. Wiring T1 means supplying a\n * resolver that fetches the akshare/market value for the record at judge time\n * and filling {ground_truth}. Until then T1 is excluded from loadAll.\n */\nexport interface T1Seam {\n promptId: string\n /** Resolver that returns the real-time ground-truth block for the {ground_truth} slot. */\n resolveGroundTruth(promptId: string): Promise<string>\n}\n\ninterface FinSearchRecord {\n prompt_id: string\n prompt: string\n response_reference: string\n judge_prompt_template: string\n judge_system_prompt: string\n label: string\n}\n\ninterface FinSearchMeta {\n promptId: string\n label: string\n taskType: TaskType\n region: string\n responseReference: string\n judgePromptTemplate: string\n judgeSystemPrompt: string\n rawPrompt: string\n}\n\n/** \"(T2)Simple_Historical_Lookup_001\" → \"T2\"; throws on an unknown/missing prefix. */\nfunction parseTaskType(promptId: string): TaskType {\n const m = promptId.match(/^\\((T[123])\\)/)\n if (!m) throw new Error(`FinSearchComp prompt_id has no (T1|T2|T3) prefix: ${JSON.stringify(promptId)}`)\n return m[1] as TaskType\n}\n\n/** \"Simple_Historical_Lookup(Greater China)\" → \"Greater China\"; '' when absent. */\nfunction parseRegion(label: string): string {\n const m = label.match(/\\(([^()]+)\\)\\s*$/)\n return m ? m[1].trim() : ''\n}\n\nfunction recordToTask(rec: FinSearchRecord): BenchTask {\n const taskType = parseTaskType(rec.prompt_id)\n const meta: FinSearchMeta = {\n promptId: rec.prompt_id,\n label: rec.label,\n taskType,\n region: parseRegion(rec.label),\n responseReference: rec.response_reference,\n judgePromptTemplate: rec.judge_prompt_template,\n judgeSystemPrompt: rec.judge_system_prompt,\n rawPrompt: rec.prompt,\n }\n return {\n id: rec.prompt_id,\n payload: { prompt: rec.prompt + WORKER_CONTRACT, subset: taskType },\n metadata: meta as unknown as Record<string, unknown>,\n }\n}\n\nfunction readMeta(task: BenchTask): FinSearchMeta {\n const md = task.metadata\n if (\n !md ||\n typeof md.responseReference !== 'string' ||\n typeof md.judgePromptTemplate !== 'string' ||\n typeof md.judgeSystemPrompt !== 'string' ||\n typeof md.rawPrompt !== 'string'\n ) {\n throw new Error(`FinSearchComp task ${task.id} missing judge metadata — loadAll did not populate it`)\n }\n return md as unknown as FinSearchMeta\n}\n\n/** Fill the per-record judge_prompt_template. {ground_truth} is T1-only and unused for T2/T3. */\nfunction fillJudgePrompt(meta: FinSearchMeta, response: string): string {\n return meta.judgePromptTemplate\n .replaceAll('{prompt}', meta.rawPrompt)\n .replaceAll('{response_reference}', meta.responseReference)\n .replaceAll('{response}', response)\n}\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 FinSearchComp per-record LLM judge')\n const model = process.env.JUDGE_MODEL ?? 'deepseek/deepseek-v4.1-flash'\n const baseUrl = process.env.ROUTER_BASE ?? 'https://router.tangle.tools/v1'\n return { baseUrl, key, model }\n}\n\n/**\n * The judge emits a JSON object with an `answer_score`. In this dataset it is a\n * flat integer ({\"answer_score\": 1}); we also accept the nested-array form\n * ([[1]] → read [0][0]) the upstream scorer can produce. 1/positive = resolved.\n * A \"null\" sentinel (judge could not obtain ground truth) is NOT a pass.\n */\nfunction readAnswerScore(value: unknown): { resolved: boolean; score: number; raw: unknown } {\n let v: unknown = value\n // unwrap nested-array form: [[s]] / [s]\n while (Array.isArray(v)) v = v[0]\n if (v === null || v === undefined || v === 'null') {\n return { resolved: false, score: 0, raw: value }\n }\n const n = typeof v === 'number' ? v : typeof v === 'string' ? Number(v) : NaN\n if (!Number.isFinite(n)) {\n throw new Error(`FinSearchComp judge answer_score not numeric: ${JSON.stringify(value)}`)\n }\n // Their scale: 1 = correct, 0 = wrong. Treat any positive as resolved; clamp to 0..1.\n const resolved = n >= 1\n const score = n <= 0 ? 0 : n >= 1 ? 1 : n\n return { resolved, score, raw: value }\n}\n\n/** Extract the first JSON object carrying `answer_score` from judge output; throw if none. */\nfunction parseJudgeOutput(content: string): { resolved: boolean; score: number; raw: unknown } {\n // Prefer a fenced block, then fall back to scanning for a {...} with answer_score.\n const candidates: string[] = []\n for (const m of content.matchAll(/```(?:json)?\\s*([\\s\\S]*?)```/g)) candidates.push(m[1].trim())\n for (const m of content.matchAll(/\\{[^{}]*\"answer_score\"[\\s\\S]*?\\}/g)) candidates.push(m[0])\n candidates.push(content.trim())\n for (const c of candidates) {\n let parsed: { answer_score?: unknown }\n try {\n parsed = JSON.parse(c) as { answer_score?: unknown }\n } catch {\n continue\n }\n if ('answer_score' in parsed) return readAnswerScore(parsed.answer_score)\n }\n throw new Error(\n `FinSearchComp judge produced no parseable {\"answer_score\": …}: ${content.slice(0, 400)}`,\n )\n}\n\n/** Run the record's own judge via the router. Fail loud on transport/parse errors. */\nasync function runRecordJudge(meta: FinSearchMeta, response: string, router: JudgeRouter): Promise<BenchEvaluation> {\n const turn = await runBenchRouterTurn(\n {\n routerBaseUrl: router.baseUrl,\n routerKey: router.key,\n profile: {\n name: 'finsearchcomp-judge',\n harness: 'cli-base',\n model: {\n provider: 'tangle-router',\n default: router.model,\n metadata: { temperature: 0 },\n },\n prompt: { systemPrompt: meta.judgeSystemPrompt },\n },\n },\n fillJudgePrompt(meta, response),\n )\n const content = turn.finalText\n if (!content) throw new Error('FinSearchComp judge returned no message content')\n const { resolved, score, raw } = parseJudgeOutput(content)\n const evidence = {\n taskType: meta.taskType,\n region: meta.region,\n answerScore: raw,\n judgeModel: router.model,\n }\n return {\n passed: resolved,\n score,\n notes: JSON.stringify(evidence),\n raw: evidence,\n }\n}\n\nfunction selectRecords(records: FinSearchRecord[], opts: LoadOptions): BenchTask[] {\n let tasks = records\n .filter((r) => SUPPORTED_TYPES.has(parseTaskType(r.prompt_id)))\n .map(recordToTask)\n if (opts.subset) tasks = tasks.filter((t) => t.payload.subset === opts.subset)\n if (opts.ids) {\n const want = new Set(opts.ids)\n tasks = tasks.filter((t) => want.has(t.id))\n } else if (opts.limit !== undefined) {\n tasks = balanceByType(tasks, opts.limit)\n }\n return tasks\n}\n\n/** Round-robin across task types (T2/T3) so a `limit` pulls a balanced mix\n * rather than slicing the type-ordered dataset's first N (which yields all\n * T2). Deterministic — preserves dataset order within each type. */\nfunction balanceByType(tasks: BenchTask[], limit: number): BenchTask[] {\n const queues = new Map<TaskType, BenchTask[]>()\n for (const t of tasks) {\n const k = parseTaskType(t.id)\n const q = queues.get(k)\n if (q) q.push(t)\n else queues.set(k, [t])\n }\n const lanes = [...queues.values()]\n const out: BenchTask[] = []\n for (let i = 0; out.length < limit; i++) {\n const before = out.length\n for (const lane of lanes) {\n if (i < lane.length) out.push(lane[i])\n if (out.length >= limit) break\n }\n if (out.length === before) break // all lanes exhausted\n }\n return out\n}\n\nasync function loadFixtures(opts: LoadOptions): Promise<BenchTask[]> {\n const records = JSON.parse(await readFile(FIXTURES, 'utf8')) as FinSearchRecord[]\n return selectRecords(records, opts)\n}\n\nasync function fetchDataset(): Promise<FinSearchRecord[]> {\n const res = await fetch(DATASET_URL)\n if (!res.ok) throw new Error(`FinSearchComp dataset HTTP ${res.status} fetching ${DATASET_URL}`)\n const data = (await res.json()) as FinSearchRecord[]\n if (!Array.isArray(data) || data.length === 0) {\n throw new Error(`FinSearchComp dataset empty or not an array: ${DATASET_URL}`)\n }\n return data\n}\n\nexport function createFinsearchcompAdapter(): RuntimeBenchmark {\n const fixturesMode = process.env.FINSEARCHCOMP_FIXTURES === '1'\n\n return runtimeBenchmark({\n id: 'finsearchcomp',\n\n async loadAll(opts: LoadOptions = {}) {\n if (fixturesMode) return loadFixtures(opts)\n let records: FinSearchRecord[]\n try {\n records = await fetchDataset()\n } catch (err) {\n console.warn(\n `[finsearchcomp] live dataset fetch failed (${err instanceof Error ? err.message : err}); ` +\n `falling back to committed fixtures at ${FIXTURES}`,\n )\n return loadFixtures(opts)\n }\n return selectRecords(records, opts)\n },\n\n async evaluate(task: BenchTask, artifact: string): Promise<BenchEvaluation> {\n const meta = readMeta(task)\n const response = artifact.trim()\n if (response.length === 0) {\n // Fail-closed — the benchmark's own judges score an empty answer 0.\n const raw = { taskType: meta.taskType, region: meta.region, reason: 'empty answer' }\n return {\n passed: false,\n score: 0,\n notes: JSON.stringify(raw),\n raw,\n }\n }\n return runRecordJudge(meta, response, judgeRouter())\n },\n\n runtime: {\n async preflight() {\n // The per-record LLM judge is the arbiter in both modes — its router\n // config must exist or no score can be produced.\n judgeRouter()\n console.warn(\n '[finsearchcomp] T1 (Time_Sensitive_Data_Fetching) is NOT scored: it needs a live ' +\n 'market snapshot / akshare ground truth for the judge {ground_truth} slot. ' +\n 'loadAll supports T2 + T3 only; wire T1Seam to add T1.',\n )\n if (fixturesMode) {\n await readFile(FIXTURES, 'utf8').catch((err) => {\n throw new Error(\n `FINSEARCHCOMP_FIXTURES=1 but ${FIXTURES} unreadable: ${err instanceof Error ? err.message : err}`,\n )\n })\n return\n }\n const res = await fetch(DATASET_URL, { method: 'HEAD' }).catch((err) => {\n throw new Error(\n `finsearchcomp preflight failed reaching ${DATASET_URL}: ${err instanceof Error ? err.message : err}\\n` +\n `Fix: ensure network access to raw.githubusercontent.com, or set FINSEARCHCOMP_FIXTURES=1 ` +\n `to run against the committed fixtures offline.`,\n )\n })\n if (!res.ok) {\n throw new Error(\n `finsearchcomp preflight: dataset HEAD ${res.status} for ${DATASET_URL}. ` +\n `Set FINSEARCHCOMP_FIXTURES=1 to run against the committed fixtures offline.`,\n )\n }\n },\n\n async goldArtifact(task: BenchTask) {\n // Gold artifact = the record's response_reference fed back as the student\n // answer, so verify-judge proves gold→passed through the SAME per-record\n // judge the real artifact takes. The reference may carry tolerance/criteria\n // prose; the judge is built to read the value out of it.\n const meta = readMeta(task)\n return meta.responseReference\n },\n },\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA,MAAM,aAAa,cAAc,IAAI,IAAI,SAAS,YAAY,GA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AAI,SAAS,WAAW,GAAG;IAEzB,MAAM,MAAM;KAAE,UAAU,KAAK;KAAU,QAAQ,KAAK;KAAQ,QAAQ;IAAe;IACnF,OAAO;KACL,QAAQ;KACR,OAAO;KACP,OAAO,KAAK,UAAU,GAAG;KACzB;IACF;GACF;GACA,OAAO,eAAe,MAAM,UAAU,YAAY,CAAC;EACrD;EAEA,SAAS;GACP,MAAM,YAAY;IAGhB,YAAY;IACZ,QAAQ,KACN,kNAGF;IACA,IAAI,cAAc;KAChB,MAAM,SAAS,UAAU,MAAM,CAAC,CAAC,OAAO,QAAQ;MAC9C,MAAM,IAAI,MACR,gCAAgC,SAAS,eAAe,eAAe,QAAQ,IAAI,UAAU,KAC/F;KACF,CAAC;KACD;IACF;IACA,MAAM,MAAM,MAAM,MAAM,aAAa,EAAE,QAAQ,OAAO,CAAC,CAAC,CAAC,OAAO,QAAQ;KACtE,MAAM,IAAI,MACR,2CAA2C,YAAY,IAAI,eAAe,QAAQ,IAAI,UAAU,IAAI,0IAGtG;IACF,CAAC;IACD,IAAI,CAAC,IAAI,IACP,MAAM,IAAI,MACR,yCAAyC,IAAI,OAAO,OAAO,YAAY,8EAEzE;GAEJ;GAEA,MAAM,aAAa,MAAiB;IAMlC,OADa,SAAS,IACZ,CAAC,CAAC;GACd;EACF;CACF,CAAC;AACH"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { RuntimeBenchmark } from "./types.js";
|
|
2
2
|
/**
|
|
3
3
|
* Typed seam for the future dynamic-topology research worker. The benchmark
|
|
4
4
|
* adapter scores a plain `string` artifact (the BenchmarkAdapter contract); the
|
|
@@ -17,5 +17,5 @@ export interface FramesTask {
|
|
|
17
17
|
}
|
|
18
18
|
/** Port of the SQuAD/GAIA normalize_answer routine, plus number/date canonicalization. */
|
|
19
19
|
export declare function normalizeFramesAnswer(input: string): string;
|
|
20
|
-
export declare function createFramesAdapter():
|
|
20
|
+
export declare function createFramesAdapter(): RuntimeBenchmark;
|
|
21
21
|
//# sourceMappingURL=frames.d.ts.map
|