@tangle-network/agent-bench 0.4.1 → 0.4.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (194) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/dist/adapters.d.ts +4 -11
  3. package/dist/adapters.js +78 -41
  4. package/dist/adapters.js.map +1 -1
  5. package/dist/benchmarks/_harness.d.ts +48 -66
  6. package/dist/benchmarks/_harness.js +329 -33
  7. package/dist/benchmarks/_harness.js.map +1 -1
  8. package/dist/benchmarks/aec-bench.d.ts +4 -25
  9. package/dist/benchmarks/aec-bench.js +242 -7
  10. package/dist/benchmarks/aec-bench.js.map +1 -1
  11. package/dist/benchmarks/agentbench.d.ts +5 -13
  12. package/dist/benchmarks/agentbench.js +114 -9
  13. package/dist/benchmarks/agentbench.js.map +1 -1
  14. package/dist/benchmarks/appworld.d.ts +9 -29
  15. package/dist/benchmarks/appworld.js +317 -12
  16. package/dist/benchmarks/appworld.js.map +1 -1
  17. package/dist/benchmarks/bfcl.d.ts +5 -15
  18. package/dist/benchmarks/bfcl.js +264 -9
  19. package/dist/benchmarks/bfcl.js.map +1 -1
  20. package/dist/benchmarks/cad-design.d.ts +16 -41
  21. package/dist/benchmarks/cad-design.js +512 -6
  22. package/dist/benchmarks/cad-design.js.map +1 -1
  23. package/dist/benchmarks/cadbench.d.ts +4 -17
  24. package/dist/benchmarks/cadbench.js +2 -8
  25. package/dist/benchmarks/cadgenbench.d.ts +4 -20
  26. package/dist/benchmarks/cadgenbench.js +2 -8
  27. package/dist/benchmarks/commit0.d.ts +5 -27
  28. package/dist/benchmarks/commit0.js +187 -9
  29. package/dist/benchmarks/commit0.js.map +1 -1
  30. package/dist/benchmarks/crag.d.ts +4 -12
  31. package/dist/benchmarks/crag.js +110 -8
  32. package/dist/benchmarks/crag.js.map +1 -1
  33. package/dist/benchmarks/dabstep.d.ts +5 -15
  34. package/dist/benchmarks/dabstep.js +177 -9
  35. package/dist/benchmarks/dabstep.js.map +1 -1
  36. package/dist/benchmarks/enterpriseops-gym.d.ts +5 -34
  37. package/dist/benchmarks/enterpriseops-gym.js +236 -9
  38. package/dist/benchmarks/enterpriseops-gym.js.map +1 -1
  39. package/dist/benchmarks/finresearchbench.d.ts +4 -13
  40. package/dist/benchmarks/finresearchbench.js +218 -7
  41. package/dist/benchmarks/finresearchbench.js.map +1 -1
  42. package/dist/benchmarks/finsearchcomp.d.ts +8 -39
  43. package/dist/benchmarks/finsearchcomp.js +267 -6
  44. package/dist/benchmarks/finsearchcomp.js.map +1 -1
  45. package/dist/benchmarks/frames.d.ts +15 -37
  46. package/dist/benchmarks/frames.js +408 -11
  47. package/dist/benchmarks/frames.js.map +1 -1
  48. package/dist/benchmarks/hotpotqa.d.ts +4 -24
  49. package/dist/benchmarks/hotpotqa.js +250 -14
  50. package/dist/benchmarks/hotpotqa.js.map +1 -1
  51. package/dist/benchmarks/humaneval.d.ts +19 -37
  52. package/dist/benchmarks/humaneval.js +279 -16
  53. package/dist/benchmarks/humaneval.js.map +1 -1
  54. package/dist/benchmarks/mind2web.d.ts +7 -34
  55. package/dist/benchmarks/mind2web.js +257 -8
  56. package/dist/benchmarks/mind2web.js.map +1 -1
  57. package/dist/benchmarks/nomiracl.d.ts +4 -13
  58. package/dist/benchmarks/nomiracl.js +146 -8
  59. package/dist/benchmarks/nomiracl.js.map +1 -1
  60. package/dist/benchmarks/open-rag-bench.d.ts +4 -12
  61. package/dist/benchmarks/open-rag-bench.js +110 -8
  62. package/dist/benchmarks/open-rag-bench.js.map +1 -1
  63. package/dist/benchmarks/programbench.d.ts +5 -29
  64. package/dist/benchmarks/programbench.js +161 -9
  65. package/dist/benchmarks/programbench.js.map +1 -1
  66. package/dist/benchmarks/rag-shared.d.ts +21 -20
  67. package/dist/benchmarks/rag-shared.js +245 -38
  68. package/dist/benchmarks/rag-shared.js.map +1 -1
  69. package/dist/benchmarks/ragbench.d.ts +4 -14
  70. package/dist/benchmarks/ragbench.js +127 -8
  71. package/dist/benchmarks/ragbench.js.map +1 -1
  72. package/dist/benchmarks/simpleqa.d.ts +17 -44
  73. package/dist/benchmarks/simpleqa.js +293 -10
  74. package/dist/benchmarks/simpleqa.js.map +1 -1
  75. package/dist/benchmarks/swe-bench.d.ts +23 -36
  76. package/dist/benchmarks/swe-bench.js +234 -13
  77. package/dist/benchmarks/swe-bench.js.map +1 -1
  78. package/dist/benchmarks/t2-ragbench.d.ts +4 -12
  79. package/dist/benchmarks/t2-ragbench.js +118 -8
  80. package/dist/benchmarks/t2-ragbench.js.map +1 -1
  81. package/dist/benchmarks/tau-bench-shared.d.ts +14 -22
  82. package/dist/benchmarks/tau-bench-shared.js +169 -9
  83. package/dist/benchmarks/tau-bench-shared.js.map +1 -1
  84. package/dist/benchmarks/tau2-bench.d.ts +5 -5
  85. package/dist/benchmarks/tau2-bench.js +28 -10
  86. package/dist/benchmarks/tau2-bench.js.map +1 -1
  87. package/dist/benchmarks/tau3-banking.d.ts +4 -13
  88. package/dist/benchmarks/tau3-banking.js +28 -8
  89. package/dist/benchmarks/tau3-banking.js.map +1 -1
  90. package/dist/benchmarks/terminal-bench.d.ts +4 -22
  91. package/dist/benchmarks/terminal-bench.js +140 -7
  92. package/dist/benchmarks/terminal-bench.js.map +1 -1
  93. package/dist/benchmarks/toollm.d.ts +5 -13
  94. package/dist/benchmarks/toollm.js +184 -9
  95. package/dist/benchmarks/toollm.js.map +1 -1
  96. package/dist/benchmarks/trata-hedge.d.ts +4 -30
  97. package/dist/benchmarks/trata-hedge.js +336 -6
  98. package/dist/benchmarks/trata-hedge.js.map +1 -1
  99. package/dist/benchmarks/types.d.ts +85 -94
  100. package/dist/benchmarks/types.js +1 -1
  101. package/dist/benchmarks/webarena-verified.d.ts +5 -13
  102. package/dist/benchmarks/webarena-verified.js +152 -9
  103. package/dist/benchmarks/webarena-verified.js.map +1 -1
  104. package/dist/cadbench-DpQWZHp4.js +285 -0
  105. package/dist/cadbench-DpQWZHp4.js.map +1 -0
  106. package/dist/cadgenbench-DRhczfsG.js +151 -0
  107. package/dist/cadgenbench-DRhczfsG.js.map +1 -0
  108. package/dist/index.d.ts +245 -293
  109. package/dist/index.js +1669 -1791
  110. package/dist/index.js.map +1 -1
  111. package/package.json +17 -14
  112. package/scripts/verify-packed-consumer.mjs +20 -17
  113. package/src/corpus.test.mts +13 -0
  114. package/src/corpus.ts +4 -0
  115. package/src/profile-coordinates.ts +2 -2
  116. package/src/rollout-ledger/backfill-swe-arena.mts +5 -1
  117. package/src/rollout-ledger/settle-capture.mts +7 -1
  118. package/src/search-bench/profiles.ts +1 -1
  119. package/src/skill-sandbox-smoke.mts +2 -1
  120. package/src/swe-arena/gepa-seat.mts +1 -1
  121. package/src/swe-arena/ledger-orphans.test.mts +36 -34
  122. package/dist/benchmarks/cadbench.js.map +0 -1
  123. package/dist/benchmarks/cadgenbench.js.map +0 -1
  124. package/dist/benchmarks/types.js.map +0 -1
  125. package/dist/chunk-53UPUNBZ.js +0 -325
  126. package/dist/chunk-53UPUNBZ.js.map +0 -1
  127. package/dist/chunk-5FEQDSCT.js +0 -211
  128. package/dist/chunk-5FEQDSCT.js.map +0 -1
  129. package/dist/chunk-5H5XV76F.js +0 -240
  130. package/dist/chunk-5H5XV76F.js.map +0 -1
  131. package/dist/chunk-67ACKDCX.js +0 -118
  132. package/dist/chunk-67ACKDCX.js.map +0 -1
  133. package/dist/chunk-7FKBWOQT.js +0 -147
  134. package/dist/chunk-7FKBWOQT.js.map +0 -1
  135. package/dist/chunk-BEN6IF2X.js +0 -221
  136. package/dist/chunk-BEN6IF2X.js.map +0 -1
  137. package/dist/chunk-BZY5QARD.js +0 -120
  138. package/dist/chunk-BZY5QARD.js.map +0 -1
  139. package/dist/chunk-C7T7WEK2.js +0 -103
  140. package/dist/chunk-C7T7WEK2.js.map +0 -1
  141. package/dist/chunk-CLIKAXKH.js +0 -276
  142. package/dist/chunk-CLIKAXKH.js.map +0 -1
  143. package/dist/chunk-CWIOBFSP.js +0 -197
  144. package/dist/chunk-CWIOBFSP.js.map +0 -1
  145. package/dist/chunk-CXDUTWQE.js +0 -318
  146. package/dist/chunk-CXDUTWQE.js.map +0 -1
  147. package/dist/chunk-DWALFME7.js +0 -182
  148. package/dist/chunk-DWALFME7.js.map +0 -1
  149. package/dist/chunk-EEOC6QPJ.js +0 -144
  150. package/dist/chunk-EEOC6QPJ.js.map +0 -1
  151. package/dist/chunk-EIETHPD5.js +0 -321
  152. package/dist/chunk-EIETHPD5.js.map +0 -1
  153. package/dist/chunk-GC2EPS6L.js +0 -130
  154. package/dist/chunk-GC2EPS6L.js.map +0 -1
  155. package/dist/chunk-GCHL6XPM.js +0 -169
  156. package/dist/chunk-GCHL6XPM.js.map +0 -1
  157. package/dist/chunk-HQ5HCCKF.js +0 -142
  158. package/dist/chunk-HQ5HCCKF.js.map +0 -1
  159. package/dist/chunk-HVW25KSX.js +0 -208
  160. package/dist/chunk-HVW25KSX.js.map +0 -1
  161. package/dist/chunk-INNOYXCP.js +0 -387
  162. package/dist/chunk-INNOYXCP.js.map +0 -1
  163. package/dist/chunk-J6BU3NTM.js +0 -251
  164. package/dist/chunk-J6BU3NTM.js.map +0 -1
  165. package/dist/chunk-JSQOUKXS.js +0 -149
  166. package/dist/chunk-JSQOUKXS.js.map +0 -1
  167. package/dist/chunk-JTHWEDEW.js +0 -32
  168. package/dist/chunk-JTHWEDEW.js.map +0 -1
  169. package/dist/chunk-NRMGT25X.js +0 -116
  170. package/dist/chunk-NRMGT25X.js.map +0 -1
  171. package/dist/chunk-PA2ZKHJC.js +0 -230
  172. package/dist/chunk-PA2ZKHJC.js.map +0 -1
  173. package/dist/chunk-PUIRNYI7.js +0 -189
  174. package/dist/chunk-PUIRNYI7.js.map +0 -1
  175. package/dist/chunk-QZZEAHWJ.js +0 -136
  176. package/dist/chunk-QZZEAHWJ.js.map +0 -1
  177. package/dist/chunk-SEVJPLZC.js +0 -260
  178. package/dist/chunk-SEVJPLZC.js.map +0 -1
  179. package/dist/chunk-TBKU5XQI.js +0 -228
  180. package/dist/chunk-TBKU5XQI.js.map +0 -1
  181. package/dist/chunk-UPAMRDX4.js +0 -233
  182. package/dist/chunk-UPAMRDX4.js.map +0 -1
  183. package/dist/chunk-VQRS7VUC.js +0 -342
  184. package/dist/chunk-VQRS7VUC.js.map +0 -1
  185. package/dist/chunk-WG7TM7UV.js +0 -30
  186. package/dist/chunk-WG7TM7UV.js.map +0 -1
  187. package/dist/chunk-X3BTXCJ4.js +0 -262
  188. package/dist/chunk-X3BTXCJ4.js.map +0 -1
  189. package/dist/chunk-XXFF3RRD.js +0 -162
  190. package/dist/chunk-XXFF3RRD.js.map +0 -1
  191. package/dist/chunk-ZFNOM7WR.js +0 -27
  192. package/dist/chunk-ZFNOM7WR.js.map +0 -1
  193. package/dist/chunk-ZNCCYTFG.js +0 -170
  194. package/dist/chunk-ZNCCYTFG.js.map +0 -1
@@ -1,233 +0,0 @@
1
- // src/benchmarks/finsearchcomp.ts
2
- import { readFile } from "fs/promises";
3
- import { join } from "path";
4
- import { fileURLToPath } from "url";
5
- var BENCH_ROOT = fileURLToPath(new URL("../..", import.meta.url));
6
- var FIXTURES = join(BENCH_ROOT, "fixtures", "finsearchcomp.json");
7
- var DATASET_URL = "https://raw.githubusercontent.com/randomtutu/FinSearchComp/main/data/finsearchcomp_data.json";
8
- var SUPPORTED_TYPES = /* @__PURE__ */ new Set(["T2", "T3"]);
9
- var WORKER_CONTRACT = [
10
- "",
11
- "Research this financial question using live web/market sources and answer it.",
12
- "State your final answer explicitly, with the exact units and precision the question requests.",
13
- "Respect any tolerance the question implies; show the value you settled on, not just intermediate work."
14
- ].join("\n");
15
- function parseTaskType(promptId) {
16
- const m = promptId.match(/^\((T[123])\)/);
17
- if (!m) throw new Error(`FinSearchComp prompt_id has no (T1|T2|T3) prefix: ${JSON.stringify(promptId)}`);
18
- return m[1];
19
- }
20
- function parseRegion(label) {
21
- const m = label.match(/\(([^()]+)\)\s*$/);
22
- return m ? m[1].trim() : "";
23
- }
24
- function recordToTask(rec) {
25
- const taskType = parseTaskType(rec.prompt_id);
26
- const meta = {
27
- promptId: rec.prompt_id,
28
- label: rec.label,
29
- taskType,
30
- region: parseRegion(rec.label),
31
- responseReference: rec.response_reference,
32
- judgePromptTemplate: rec.judge_prompt_template,
33
- judgeSystemPrompt: rec.judge_system_prompt,
34
- rawPrompt: rec.prompt
35
- };
36
- return {
37
- id: rec.prompt_id,
38
- split: taskType,
39
- prompt: rec.prompt + WORKER_CONTRACT,
40
- metadata: meta
41
- };
42
- }
43
- function readMeta(task) {
44
- const md = task.metadata;
45
- if (!md || typeof md.responseReference !== "string" || typeof md.judgePromptTemplate !== "string" || typeof md.judgeSystemPrompt !== "string" || typeof md.rawPrompt !== "string") {
46
- throw new Error(`FinSearchComp task ${task.id} missing judge metadata \u2014 loadTasks did not populate it`);
47
- }
48
- return md;
49
- }
50
- function fillJudgePrompt(meta, response) {
51
- return meta.judgePromptTemplate.replaceAll("{prompt}", meta.rawPrompt).replaceAll("{response_reference}", meta.responseReference).replaceAll("{response}", response);
52
- }
53
- function judgeRouter() {
54
- const key = process.env.TANGLE_API_KEY;
55
- if (!key) throw new Error("TANGLE_API_KEY is required for the FinSearchComp per-record LLM judge");
56
- const model = process.env.JUDGE_MODEL ?? "deepseek-v4-flash";
57
- const baseUrl = process.env.ROUTER_BASE ?? "https://router.tangle.tools/v1";
58
- return { baseUrl, key, model };
59
- }
60
- function readAnswerScore(value) {
61
- let v = value;
62
- while (Array.isArray(v)) v = v[0];
63
- if (v === null || v === void 0 || v === "null") {
64
- return { resolved: false, score: 0, raw: value };
65
- }
66
- const n = typeof v === "number" ? v : typeof v === "string" ? Number(v) : NaN;
67
- if (!Number.isFinite(n)) {
68
- throw new Error(`FinSearchComp judge answer_score not numeric: ${JSON.stringify(value)}`);
69
- }
70
- const resolved = n >= 1;
71
- const score = n <= 0 ? 0 : n >= 1 ? 1 : n;
72
- return { resolved, score, raw: value };
73
- }
74
- function parseJudgeOutput(content) {
75
- const candidates = [];
76
- for (const m of content.matchAll(/```(?:json)?\s*([\s\S]*?)```/g)) candidates.push(m[1].trim());
77
- for (const m of content.matchAll(/\{[^{}]*"answer_score"[\s\S]*?\}/g)) candidates.push(m[0]);
78
- candidates.push(content.trim());
79
- for (const c of candidates) {
80
- let parsed;
81
- try {
82
- parsed = JSON.parse(c);
83
- } catch {
84
- continue;
85
- }
86
- if ("answer_score" in parsed) return readAnswerScore(parsed.answer_score);
87
- }
88
- throw new Error(
89
- `FinSearchComp judge produced no parseable {"answer_score": \u2026}: ${content.slice(0, 400)}`
90
- );
91
- }
92
- async function runRecordJudge(meta, response, router) {
93
- const res = await fetch(`${router.baseUrl}/chat/completions`, {
94
- method: "POST",
95
- headers: { "content-type": "application/json", authorization: `Bearer ${router.key}` },
96
- body: JSON.stringify({
97
- model: router.model,
98
- temperature: 0,
99
- messages: [
100
- { role: "system", content: meta.judgeSystemPrompt },
101
- { role: "user", content: fillJudgePrompt(meta, response) }
102
- ]
103
- })
104
- });
105
- if (!res.ok) {
106
- throw new Error(`FinSearchComp judge HTTP ${res.status}: ${(await res.text()).slice(0, 300)}`);
107
- }
108
- const body = await res.json();
109
- const content = body.choices?.[0]?.message?.content;
110
- if (typeof content !== "string") {
111
- throw new Error(`FinSearchComp judge returned no message content: ${JSON.stringify(body).slice(0, 300)}`);
112
- }
113
- const { resolved, score, raw } = parseJudgeOutput(content);
114
- return {
115
- resolved,
116
- score,
117
- detail: JSON.stringify({
118
- taskType: meta.taskType,
119
- region: meta.region,
120
- answerScore: raw,
121
- judgeModel: router.model
122
- })
123
- };
124
- }
125
- function selectRecords(records, opts) {
126
- let tasks = records.filter((r) => SUPPORTED_TYPES.has(parseTaskType(r.prompt_id))).map(recordToTask);
127
- if (opts.split) tasks = tasks.filter((t) => t.split === opts.split);
128
- if (opts.ids) {
129
- const want = new Set(opts.ids);
130
- tasks = tasks.filter((t) => want.has(t.id));
131
- } else if (opts.limit !== void 0) {
132
- tasks = balanceByType(tasks, opts.limit);
133
- }
134
- return tasks;
135
- }
136
- function balanceByType(tasks, limit) {
137
- const queues = /* @__PURE__ */ new Map();
138
- for (const t of tasks) {
139
- const k = parseTaskType(t.id);
140
- const q = queues.get(k);
141
- if (q) q.push(t);
142
- else queues.set(k, [t]);
143
- }
144
- const lanes = [...queues.values()];
145
- const out = [];
146
- for (let i = 0; out.length < limit; i++) {
147
- const before = out.length;
148
- for (const lane of lanes) {
149
- if (i < lane.length) out.push(lane[i]);
150
- if (out.length >= limit) break;
151
- }
152
- if (out.length === before) break;
153
- }
154
- return out;
155
- }
156
- async function loadFixtures(opts) {
157
- const records = JSON.parse(await readFile(FIXTURES, "utf8"));
158
- return selectRecords(records, opts);
159
- }
160
- async function fetchDataset() {
161
- const res = await fetch(DATASET_URL);
162
- if (!res.ok) throw new Error(`FinSearchComp dataset HTTP ${res.status} fetching ${DATASET_URL}`);
163
- const data = await res.json();
164
- if (!Array.isArray(data) || data.length === 0) {
165
- throw new Error(`FinSearchComp dataset empty or not an array: ${DATASET_URL}`);
166
- }
167
- return data;
168
- }
169
- function createFinsearchcompAdapter() {
170
- const fixturesMode = process.env.FINSEARCHCOMP_FIXTURES === "1";
171
- return {
172
- name: "finsearchcomp",
173
- async preflight() {
174
- judgeRouter();
175
- console.warn(
176
- "[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."
177
- );
178
- if (fixturesMode) {
179
- await readFile(FIXTURES, "utf8").catch((err) => {
180
- throw new Error(
181
- `FINSEARCHCOMP_FIXTURES=1 but ${FIXTURES} unreadable: ${err instanceof Error ? err.message : err}`
182
- );
183
- });
184
- return;
185
- }
186
- const res = await fetch(DATASET_URL, { method: "HEAD" }).catch((err) => {
187
- throw new Error(
188
- `finsearchcomp preflight failed reaching ${DATASET_URL}: ${err instanceof Error ? err.message : err}
189
- Fix: ensure network access to raw.githubusercontent.com, or set FINSEARCHCOMP_FIXTURES=1 to run against the committed fixtures offline.`
190
- );
191
- });
192
- if (!res.ok) {
193
- throw new Error(
194
- `finsearchcomp preflight: dataset HEAD ${res.status} for ${DATASET_URL}. Set FINSEARCHCOMP_FIXTURES=1 to run against the committed fixtures offline.`
195
- );
196
- }
197
- },
198
- async loadTasks(opts = {}) {
199
- if (fixturesMode) return loadFixtures(opts);
200
- let records;
201
- try {
202
- records = await fetchDataset();
203
- } catch (err) {
204
- console.warn(
205
- `[finsearchcomp] live dataset fetch failed (${err instanceof Error ? err.message : err}); falling back to committed fixtures at ${FIXTURES}`
206
- );
207
- return loadFixtures(opts);
208
- }
209
- return selectRecords(records, opts);
210
- },
211
- async goldArtifact(task) {
212
- const meta = readMeta(task);
213
- return meta.responseReference;
214
- },
215
- async judge(task, artifact) {
216
- const meta = readMeta(task);
217
- const response = artifact.trim();
218
- if (response.length === 0) {
219
- return {
220
- resolved: false,
221
- score: 0,
222
- detail: JSON.stringify({ taskType: meta.taskType, region: meta.region, reason: "empty answer" })
223
- };
224
- }
225
- return runRecordJudge(meta, response, judgeRouter());
226
- }
227
- };
228
- }
229
-
230
- export {
231
- createFinsearchcompAdapter
232
- };
233
- //# sourceMappingURL=chunk-UPAMRDX4.js.map
@@ -1 +0,0 @@
1
- {"version":3,"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 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 res = await fetch(`${router.baseUrl}/chat/completions`, {\n method: 'POST',\n headers: { 'content-type': 'application/json', authorization: `Bearer ${router.key}` },\n body: JSON.stringify({\n model: router.model,\n temperature: 0,\n messages: [\n { role: 'system', content: meta.judgeSystemPrompt },\n { role: 'user', content: fillJudgePrompt(meta, response) },\n ],\n }),\n })\n if (!res.ok) {\n throw new Error(`FinSearchComp judge HTTP ${res.status}: ${(await res.text()).slice(0, 300)}`)\n }\n const body = (await res.json()) as { choices?: Array<{ message?: { content?: string } }> }\n const content = body.choices?.[0]?.message?.content\n if (typeof content !== 'string') {\n throw new Error(`FinSearchComp judge returned no message content: ${JSON.stringify(body).slice(0, 300)}`)\n }\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":";AA+BA,SAAS,gBAAgB;AACzB,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AAAA,QACrD;AACA,eAAO,aAAa,IAAI;AAAA,MAC1B;AACA,aAAO,cAAc,SAAS,IAAI;AAAA,IACpC;AAAA,IAEA,MAAM,aAAa,MAAiB;AAKlC,YAAM,OAAO,SAAS,IAAI;AAC1B,aAAO,KAAK;AAAA,IACd;AAAA,IAEA,MAAM,MAAM,MAAiB,UAAuC;AAClE,YAAM,OAAO,SAAS,IAAI;AAC1B,YAAM,WAAW,SAAS,KAAK;AAC/B,UAAI,SAAS,WAAW,GAAG;AAEzB,eAAO;AAAA,UACL,UAAU;AAAA,UACV,OAAO;AAAA,UACP,QAAQ,KAAK,UAAU,EAAE,UAAU,KAAK,UAAU,QAAQ,KAAK,QAAQ,QAAQ,eAAe,CAAC;AAAA,QACjG;AAAA,MACF;AACA,aAAO,eAAe,MAAM,UAAU,YAAY,CAAC;AAAA,IACrD;AAAA,EACF;AACF;","names":[]}
@@ -1,342 +0,0 @@
1
- // src/benchmarks/trata-hedge.ts
2
- import { readdirSync, readFileSync, statSync } from "fs";
3
- import { join } from "path";
4
- var DEFAULT_BENCH_ROOT = "/tmp/trata-hedge-bench";
5
- var MAX_FILE_BYTES = 8e3;
6
- var MAX_DATA_CHARS = 85e3;
7
- var WORKER_SUFFIX = [
8
- "",
9
- "The data files above are your only source. Cite each claim with the filename that supports it.",
10
- 'Write your complete analysis to the text block that starts with "ANALYSIS:" on a line by itself.',
11
- "Take a clear position on the topic. Every factual claim must name the file it comes from."
12
- ].join("\n");
13
- var JUDGE_MODEL = "gemini-2.5-pro";
14
- function readText(p, maxBytes = MAX_FILE_BYTES) {
15
- try {
16
- const buf = readFileSync(p);
17
- if (buf.length <= maxBytes) return buf.toString("utf8");
18
- return buf.subarray(0, maxBytes).toString("utf8") + `
19
- [\u2026 truncated at ${maxBytes} bytes \u2026]`;
20
- } catch {
21
- return `[unreadable: ${p}]`;
22
- }
23
- }
24
- function listFilesRec(dir) {
25
- const out = [];
26
- try {
27
- for (const name of readdirSync(dir)) {
28
- const full = join(dir, name);
29
- try {
30
- if (statSync(full).isDirectory()) out.push(...listFilesRec(full));
31
- else out.push(full);
32
- } catch {
33
- }
34
- }
35
- } catch {
36
- }
37
- return out.sort();
38
- }
39
- function buildDataBlock(dataDir) {
40
- const files = listFilesRec(dataDir);
41
- if (files.length === 0) return "(no data files found)";
42
- const priority = (f) => {
43
- if (f.includes("company_profiles")) return 0;
44
- if (f.includes("earnings_call")) return 1;
45
- if (/financials\/(income|cash_flow|balance)/.test(f) && !/bam_|bx_|kkr_|ares_|cg_|owl_|fsk_|cat_|de_|tdg_|car_/.test(f)) return 2;
46
- if (f.includes("sec_filings")) return 3;
47
- if (f.includes("investor_pres")) return 4;
48
- if (f.includes("press_release")) return 5;
49
- return 6;
50
- };
51
- const sorted = [...files].sort((a, b) => priority(a) - priority(b) || a.localeCompare(b));
52
- const blocks = [];
53
- let total = 0;
54
- for (const f of sorted) {
55
- const rel = f.slice(dataDir.length + 1);
56
- const content = readText(f);
57
- const chunk = `
58
- === FILE: data/${rel} ===
59
- ${content}`;
60
- if (total + chunk.length > MAX_DATA_CHARS) {
61
- blocks.push(`
62
- [\u2026 ${sorted.length - blocks.length} more files omitted to stay within context limit \u2026]`);
63
- break;
64
- }
65
- blocks.push(chunk);
66
- total += chunk.length;
67
- }
68
- return blocks.join("");
69
- }
70
- function buildCitedDataBlock(answerText, dataDir) {
71
- const files = listFilesRec(dataDir);
72
- const cited = [];
73
- for (const f of files) {
74
- const rel = f.slice(dataDir.length + 1);
75
- const name = rel.split("/").pop() ?? "";
76
- if (answerText.includes(rel) || answerText.includes(name)) cited.push(f);
77
- }
78
- if (cited.length === 0) {
79
- return "(The agent did not cite any data files, or no cited file could be located.)";
80
- }
81
- const blocks = [];
82
- for (const f of cited) {
83
- const rel = f.slice(dataDir.length + 1);
84
- blocks.push(`
85
- === FILE: data/${rel} ===
86
- ${readText(f)}`);
87
- }
88
- return blocks.join("");
89
- }
90
- function parseThemeMoveCounts(groundTruth) {
91
- const lines = groundTruth.split("\n");
92
- const themeStarts = lines.reduce((acc, l, i) => {
93
- if (/^\d+\./.test(l.trim())) acc.push(i);
94
- return acc;
95
- }, []);
96
- return themeStarts.map((start, k) => {
97
- const end = k + 1 < themeStarts.length ? themeStarts[k + 1] : lines.length;
98
- const block = lines.slice(start, end).join("\n");
99
- const label = lines[start].replace(/^\d+\.\s*/, "").trim();
100
- const nMoves = (block.match(/^\s*\[[a-z]\]\s+/gm) ?? []).length;
101
- return { label, nMoves };
102
- });
103
- }
104
- function coverageThreshold(nMoves) {
105
- return Math.max(1, Math.min(nMoves - 1, 3));
106
- }
107
- function judgeRouter() {
108
- const key = process.env.TANGLE_API_KEY;
109
- if (!key) throw new Error("TANGLE_API_KEY is required for the Trata hedge-bench judge");
110
- const model = process.env.JUDGE_MODEL ?? JUDGE_MODEL;
111
- const baseUrl = process.env.ROUTER_BASE ?? "https://router.tangle.tools/v1";
112
- return { baseUrl, key, model };
113
- }
114
- function parseJsonFallback(raw) {
115
- let s = raw.trim();
116
- if (s.startsWith("```")) s = s.split("\n").slice(1).join("\n");
117
- if (s.endsWith("```")) s = s.slice(0, s.lastIndexOf("```"));
118
- s = s.replace(/,(\s*[}\]])/g, "$1").trim();
119
- try {
120
- return JSON.parse(s);
121
- } catch {
122
- try {
123
- const m = s.match(/\{[\s\S]*\}/);
124
- if (m) return JSON.parse(m[0]);
125
- } catch {
126
- }
127
- }
128
- return null;
129
- }
130
- async function callJudge(router, prompt, maxAttempts = 2) {
131
- for (let i = 0; i < maxAttempts; i++) {
132
- const res = await fetch(`${router.baseUrl}/chat/completions`, {
133
- method: "POST",
134
- headers: { "content-type": "application/json", authorization: `Bearer ${router.key}` },
135
- body: JSON.stringify({
136
- model: router.model,
137
- temperature: 0,
138
- max_tokens: 16384,
139
- messages: [{ role: "user", content: prompt }]
140
- })
141
- });
142
- if (!res.ok) {
143
- if (i < maxAttempts - 1) continue;
144
- throw new Error(`Trata judge HTTP ${res.status}: ${(await res.text()).slice(0, 300)}`);
145
- }
146
- const body = await res.json();
147
- const content = body.choices?.[0]?.message?.content;
148
- if (typeof content !== "string") continue;
149
- const parsed = parseJsonFallback(content);
150
- if (parsed !== null) return parsed;
151
- }
152
- return null;
153
- }
154
- async function task1HallucinationCheck(meta, answer, router) {
155
- const citedBlock = buildCitedDataBlock(answer, meta.dataDir);
156
- const dataContext = `The block below contains the contents of the data files the agent cited in their answer. Treat this as the ground truth for factual verification.
157
-
158
- <cited_data>
159
- ${citedBlock}
160
- </cited_data>`;
161
- const prompt = meta.gradingTask1.replace("{data_context}", dataContext).replace("{agent_answer}", answer);
162
- const result = await callJudge(router, prompt);
163
- return result ?? { hallucinations_detected: false, unverifiable_claims: [] };
164
- }
165
- async function task2PerMoveCheck(meta, answer, flaggedClaims, router) {
166
- const claimsBlock = flaggedClaims && flaggedClaims.length > 0 ? JSON.stringify(flaggedClaims, null, 2) : "(No claims were flagged as hallucinations.)";
167
- const prompt = meta.gradingTask2.replace("{ground_truth}", meta.groundTruth).replace("{agent_answer}", answer).replace("{flagged_claims_block}", claimsBlock).replace("{num_themes}", String(meta.themeMoveCounts.length));
168
- const result = await callJudge(router, prompt);
169
- return result ?? { themes: [] };
170
- }
171
- async function task3SynthesisCheck(meta, answer, router) {
172
- const prompt = meta.gradingTask3.replace("{ground_truth}", meta.groundTruth).replace("{agent_answer}", answer);
173
- const result = await callJudge(router, prompt);
174
- return result ?? { synthesis_found: null };
175
- }
176
- async function runTriataJudge(meta, answer, router) {
177
- if (!answer.trim()) {
178
- return { resolved: false, score: 0, detail: JSON.stringify({ error: "empty answer" }) };
179
- }
180
- const t1 = await task1HallucinationCheck(meta, answer, router);
181
- const flaggedClaims = t1.unverifiable_claims ?? [];
182
- const [t2, t3] = await Promise.all([
183
- task2PerMoveCheck(meta, answer, flaggedClaims, router),
184
- task3SynthesisCheck(meta, answer, router)
185
- ]);
186
- const judgeThemes = t2.themes ?? [];
187
- const themesHit = [];
188
- const themesMissed = [];
189
- for (let i = 0; i < meta.themeMoveCounts.length; i++) {
190
- const { label, nMoves } = meta.themeMoveCounts[i];
191
- const judge = judgeThemes[i] ?? {};
192
- const movesHit = (judge.moves_hit ?? []).map((m) => m.replace(/[\[\]]/g, ""));
193
- const tainted = new Set((judge.moves_tainted ?? []).map((m) => m.replace(/[\[\]]/g, "")));
194
- const validHit = movesHit.filter((m) => !tainted.has(m));
195
- const threshold = coverageThreshold(nMoves);
196
- if (validHit.length >= threshold) themesHit.push(label);
197
- else themesMissed.push(label);
198
- }
199
- const numThemes = meta.themeMoveCounts.length;
200
- const synth = t3.synthesis_found;
201
- const hasSynthesis = typeof synth === "string" && synth.length > 0 && synth !== "null";
202
- let rawScore;
203
- if (numThemes === 0) rawScore = 0;
204
- else if (themesHit.length === numThemes && hasSynthesis) rawScore = 4;
205
- else if (themesHit.length === numThemes) rawScore = 3;
206
- else if (themesHit.length >= 2) rawScore = 2;
207
- else if (themesHit.length >= 1) rawScore = 1;
208
- else rawScore = 0;
209
- const hallRaw = t1.hallucinations_detected;
210
- const hallucinations = hallRaw === true || hallRaw === "true";
211
- return {
212
- resolved: rawScore === 4,
213
- score: numThemes > 0 ? rawScore / 4 : 0,
214
- detail: JSON.stringify({
215
- rawScore,
216
- themesHit,
217
- themesMissed,
218
- hallucinations,
219
- unverifiableClaims: flaggedClaims.length,
220
- synthesis: synth ?? null,
221
- judgeModel: router.model
222
- })
223
- };
224
- }
225
- function benchRoot() {
226
- return process.env.TRATA_BENCH_ROOT ?? DEFAULT_BENCH_ROOT;
227
- }
228
- function loadTask(taskId) {
229
- const taskDir = join(benchRoot(), "environments", taskId);
230
- const dataDir = join(taskDir, "environment", "data");
231
- const testsDir = join(taskDir, "tests");
232
- const instruction = readText(join(taskDir, "instruction.md"), Infinity);
233
- const dataBlock = buildDataBlock(dataDir);
234
- const groundTruth = readText(join(testsDir, "ground_truth.txt"), Infinity);
235
- const gradingTask1 = readText(join(testsDir, "grading_prompt_task1.md"), Infinity);
236
- const gradingTask2 = readText(join(testsDir, "grading_prompt_task2.md"), Infinity);
237
- const gradingTask3 = readText(join(testsDir, "grading_prompt_task3.md"), Infinity);
238
- const themeMoveCounts = parseThemeMoveCounts(groundTruth);
239
- const prompt = [
240
- instruction.replace(
241
- "You are a financial analyst with access to the data in `/app/data/`.",
242
- "You are a financial analyst. The relevant financial data files are provided inline below."
243
- ).replace(/Write your full analysis to `\/app\/answer\.txt`\.?/, "Write your full analysis below.").replace(/`\/app\/data\/`/g, "the data files below"),
244
- "",
245
- "## Data files (inline)",
246
- dataBlock,
247
- WORKER_SUFFIX
248
- ].join("\n");
249
- const meta = {
250
- taskDir,
251
- taskId,
252
- dataDir,
253
- groundTruth,
254
- gradingTask1,
255
- gradingTask2,
256
- gradingTask3,
257
- themeMoveCounts
258
- };
259
- const task = {
260
- id: taskId,
261
- prompt,
262
- metadata: meta
263
- };
264
- return { task, meta };
265
- }
266
- function readMeta(task) {
267
- const md = task.metadata;
268
- if (!md || typeof md.taskDir !== "string" || typeof md.groundTruth !== "string") {
269
- throw new Error(`Trata task ${task.id} missing judge metadata \u2014 was it loaded by this adapter?`);
270
- }
271
- return md;
272
- }
273
- function listTaskIds(root) {
274
- try {
275
- return readdirSync(join(root, "environments")).filter((name) => {
276
- try {
277
- return statSync(join(root, "environments", name)).isDirectory();
278
- } catch {
279
- return false;
280
- }
281
- }).sort();
282
- } catch (err) {
283
- throw new Error(
284
- `Trata benchmark environments not found at ${join(root, "environments")}: ${err instanceof Error ? err.message : err}.
285
- Clone the repo: git clone --depth 1 https://github.com/Trata-Inc/trata-hedge-bench ${root}`
286
- );
287
- }
288
- }
289
- function extractAnalysis(artifact) {
290
- if (artifact.startsWith("ANALYSIS:")) return artifact.slice("ANALYSIS:".length).trim();
291
- const marker = artifact.indexOf("\nANALYSIS:");
292
- if (marker !== -1) return artifact.slice(marker + "\nANALYSIS:".length).trim();
293
- return "";
294
- }
295
- function createTrataHedgeAdapter() {
296
- return {
297
- name: "trata-hedge",
298
- async preflight() {
299
- const root = benchRoot();
300
- const envDir = join(root, "environments");
301
- try {
302
- const stat = statSync(envDir);
303
- if (!stat.isDirectory()) throw new Error("not a directory");
304
- } catch {
305
- throw new Error(
306
- `Trata hedge-bench not found at ${envDir}.
307
- Clone: git clone --depth 1 https://github.com/Trata-Inc/trata-hedge-bench ${root}`
308
- );
309
- }
310
- judgeRouter();
311
- const ids = listTaskIds(root);
312
- if (ids.length === 0) throw new Error(`No task directories found under ${envDir}`);
313
- console.warn(
314
- `[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.`
315
- );
316
- },
317
- async loadTasks(opts = {}) {
318
- const root = benchRoot();
319
- let ids = listTaskIds(root);
320
- if (opts.ids) {
321
- const want = new Set(opts.ids);
322
- ids = ids.filter((id) => want.has(id));
323
- } else if (opts.limit !== void 0) {
324
- ids = ids.slice(0, opts.limit);
325
- }
326
- return ids.map((id) => loadTask(id).task);
327
- },
328
- async goldArtifact(_task) {
329
- return void 0;
330
- },
331
- async judge(task, artifact) {
332
- const meta = readMeta(task);
333
- const answer = extractAnalysis(artifact);
334
- return runTriataJudge(meta, answer, judgeRouter());
335
- }
336
- };
337
- }
338
-
339
- export {
340
- createTrataHedgeAdapter
341
- };
342
- //# sourceMappingURL=chunk-VQRS7VUC.js.map