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