@tangle-network/agent-bench 1.0.0 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +17 -0
- package/dist/adapters.js +1 -1
- package/dist/benchmarks/cadbench.js +1 -1
- package/dist/benchmarks/finresearchbench.js +2 -2
- package/dist/benchmarks/finresearchbench.js.map +1 -1
- package/dist/benchmarks/finsearchcomp.js +1 -1
- package/dist/benchmarks/finsearchcomp.js.map +1 -1
- package/dist/benchmarks/mcad-bench.d.ts +1 -1
- package/dist/benchmarks/mcad-cq-bench.d.ts +2 -2
- package/dist/benchmarks/mcad-cq-bench.js +1 -1
- package/dist/benchmarks/simpleqa.js +1 -1
- package/dist/benchmarks/simpleqa.js.map +1 -1
- package/dist/benchmarks/swe-bench.d.ts +1 -1
- package/dist/benchmarks/trata-hedge.js +3 -5
- package/dist/benchmarks/trata-hedge.js.map +1 -1
- package/dist/{cadbench-DhAndllg.js → cadbench-Byr5gO1M.js} +3 -5
- package/dist/{cadbench-DhAndllg.js.map → cadbench-Byr5gO1M.js.map} +1 -1
- package/dist/index.d.ts +4 -4
- package/dist/index.js +4 -4
- package/package.json +4 -4
- package/scripts/grade-recorded-evidence.mjs +50 -0
- package/src/atom-mcp-e2e.mts +2 -2
- package/src/benchmarks/cadbench.ts +2 -4
- package/src/benchmarks/finresearchbench.ts +1 -1
- package/src/benchmarks/finsearchcomp.ts +1 -1
- package/src/benchmarks/simpleqa.ts +1 -1
- package/src/benchmarks/trata-hedge.ts +4 -6
- package/src/examples/benchmark-matrix.mts +6 -6
- package/src/examples/lean-proof-gate.mts +1 -1
- package/src/examples/math-demo.mts +2 -2
- package/src/examples/strategy-demo.mts +1 -1
- package/src/gate-cli.mts +1 -1
- package/src/generate-eval/certify.ts +4 -4
- package/src/run-benchmarks-cli.mts +1 -1
- package/src/swe-self-improve.mts +3 -3
- package/src/terminal-compare.ts +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,22 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 2.0.0
|
|
4
|
+
|
|
5
|
+
Breaking: the public types now come from `@tangle-network/agent-runtime` `^9.0.3` (was `^8.0.1`); consumers move to agent-runtime 9 with it. 1.0.3 to 1.0.5 were tagged, never published, and their changes ship here. Recorded runs are graded with a fresh terminal-bench cache (#2550). Default judge and worker models move to the newest Router model in their tier: `deepseek/deepseek-v4.1-flash` for `deepseek-v4-flash` (bare `deepseek-v4.1-flash` where a slash would select a harness), `gemini-3.1-pro-preview` for the Trata hedge judge's `gemini-2.5-pro`, and `opencode/zai-coding-plan/glm-5.3` for atom-mcp-e2e's `glm-5-turbo`, which the bridge no longer serves. The Trata hedge and CADBench judges and the generated-eval discrimination gate now build profiles Runtime accepts (`maxVisibleOutputTokens`, `harness: 'cli-base'`); before, each was refused before any model call.
|
|
6
|
+
|
|
7
|
+
## 1.0.3
|
|
8
|
+
|
|
9
|
+
Release qualification grades the three recorded 2026-09-24 agent outputs (Terminal-Bench `hello-world` and `fix-permissions`, SWE-bench Verified `astropy__astropy-12907`) with their official judges through the packed archive, and refuses unless each grade matches its recorded verdict.
|
|
10
|
+
`scripts/grade-recorded-evidence.mjs` runs it; no model is called. The stray compiled `script_agent` bytecode is removed from the source tree.
|
|
11
|
+
|
|
12
|
+
## 1.0.2
|
|
13
|
+
|
|
14
|
+
Follows `@tangle-network/agent-runtime` 8.0.1 (`^8.0.1`). No code change.
|
|
15
|
+
|
|
16
|
+
## 1.0.1
|
|
17
|
+
|
|
18
|
+
Tagged, never published: its manifest asked for `@tangle-network/agent-runtime` `^8.0.1` before 8.0.1 existed on npm, and its changelog wrongly said 1.0.0 had not been published. 1.0.0 was published on 2026-11-07 (22:51Z) from the tag at b035d49d.
|
|
19
|
+
|
|
3
20
|
## 1.0.0
|
|
4
21
|
|
|
5
22
|
First stable release, graduating from 0.14.4, the last version on npm; 0.14.5 to 0.14.10 were never published.
|
package/dist/adapters.js
CHANGED
|
@@ -2,7 +2,7 @@ import { createAecBenchAdapter } from "./benchmarks/aec-bench.js";
|
|
|
2
2
|
import { createAgentBenchAdapter } from "./benchmarks/agentbench.js";
|
|
3
3
|
import { createAppWorldAdapter, createAppWorldReactAdapter } from "./benchmarks/appworld.js";
|
|
4
4
|
import { createBfclAdapter } from "./benchmarks/bfcl.js";
|
|
5
|
-
import { t as createCadBenchAdapter } from "./cadbench-
|
|
5
|
+
import { t as createCadBenchAdapter } from "./cadbench-Byr5gO1M.js";
|
|
6
6
|
import { createCadDesignAdapter } from "./benchmarks/cad-design.js";
|
|
7
7
|
import { t as createCadGenBenchAdapter } from "./cadgenbench-Tvk16YKT.js";
|
|
8
8
|
import { createCommit0Adapter } from "./benchmarks/commit0.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export { t as createCadBenchAdapter } from "../cadbench-
|
|
1
|
+
export { t as createCadBenchAdapter } from "../cadbench-Byr5gO1M.js";
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { benchRoot } from "./_harness.js";
|
|
2
1
|
import { t as runBenchRouterTurn } from "../router-turn-DNbQ_GjQ.js";
|
|
2
|
+
import { benchRoot } from "./_harness.js";
|
|
3
3
|
import { readFile, stat } from "node:fs/promises";
|
|
4
4
|
import { join } from "node:path";
|
|
5
5
|
// src/benchmarks/finresearchbench.ts
|
|
@@ -19,7 +19,7 @@ function routerConfig() {
|
|
|
19
19
|
return {
|
|
20
20
|
baseUrl: process.env.ROUTER_BASE ?? "https://router.tangle.tools/v1",
|
|
21
21
|
key,
|
|
22
|
-
model: process.env.FINRESEARCHBENCH_JUDGE_MODEL ?? process.env.JUDGE_MODEL ?? "deepseek-v4-flash"
|
|
22
|
+
model: process.env.FINRESEARCHBENCH_JUDGE_MODEL ?? process.env.JUDGE_MODEL ?? "deepseek/deepseek-v4.1-flash"
|
|
23
23
|
};
|
|
24
24
|
}
|
|
25
25
|
async function assertReadable(path, label) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"finresearchbench.js","names":[],"sources":["../../src/benchmarks/finresearchbench.ts"],"sourcesContent":["/**\n * FinResearchBench-compatible adapter.\n *\n * The paper defines a logic-tree Agent-as-a-Judge benchmark for financial\n * research reports, but there is no stable public scorer package wired here.\n * Live mode therefore requires a local data export whose rows carry the official\n * judge prompt/template/logic tree. The adapter refuses to invent a judge.\n */\n\nimport { readFile, stat } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport type { AgentTurnUsage } from '@tangle-network/agent-runtime/kernel'\nimport { runBenchRouterTurn } from '../router-turn'\nimport { benchRoot } from './_harness'\nimport type { BenchmarkAdapter, BenchScore, BenchTask, LoadOptions } from './types'\n\nconst FIXTURES = join(benchRoot, 'fixtures', 'finresearchbench.json')\n\ninterface FinResearchRecord {\n id: string\n question: string\n category?: string\n reference_answer?: string\n reference_report?: string\n logic_tree?: unknown\n rubric?: unknown\n judge_system_prompt?: string\n judge_prompt_template?: string\n}\n\ninterface FinResearchMeta {\n id: string\n category: string\n question: string\n referenceAnswer: string\n referenceReport: string\n logicTree: unknown\n rubric: unknown\n judgeSystemPrompt?: string\n judgePromptTemplate?: string\n scoring: 'official-logic-tree-judge' | 'fixture-exact-reference'\n}\n\nconst dataFile = (): string | undefined => process.env.FINRESEARCHBENCH_DATA_FILE\n\nfunction routerConfig(): { baseUrl: string; key: string; model: string } {\n const key = process.env.TANGLE_API_KEY\n if (!key) throw new Error('TANGLE_API_KEY is required for FinResearchBench live LLM judging')\n return {\n baseUrl: process.env.ROUTER_BASE ?? 'https://router.tangle.tools/v1',\n key,\n model: process.env.FINRESEARCHBENCH_JUDGE_MODEL ?? process.env.JUDGE_MODEL ?? 'deepseek-v4-flash',\n }\n}\n\nasync function assertReadable(path: string, label: string): Promise<void> {\n try {\n await stat(path)\n } catch (err) {\n throw new Error(`FinResearchBench: missing ${label} at ${path} (${err instanceof Error ? err.message : err})`)\n }\n}\n\nfunction readRecords(raw: string): FinResearchRecord[] {\n const trimmed = raw.trim()\n if (trimmed.startsWith('[')) return JSON.parse(trimmed) as FinResearchRecord[]\n return trimmed\n .split(/\\r?\\n/)\n .map((line) => line.trim())\n .filter((line) => line.length > 0)\n .map((line) => JSON.parse(line) as FinResearchRecord)\n}\n\nfunction assertLiveJudgeFields(records: readonly FinResearchRecord[], source: string): void {\n const missing = records\n .filter((row) => !row.judge_system_prompt || !row.judge_prompt_template)\n .map((row) => row.id)\n if (missing.length > 0) {\n throw new Error(\n `FinResearchBench live rows from ${source} missing official judge prompts for ${missing.length}/${records.length} row(s): ${missing.slice(0, 5).join(', ')}. ` +\n 'Use a benchmark export with judge_system_prompt and judge_prompt_template, or do not score this benchmark live.',\n )\n }\n}\n\nfunction rowToTask(row: FinResearchRecord, fixturesMode: boolean): BenchTask {\n const referenceAnswer = row.reference_answer ?? ''\n const referenceReport = row.reference_report ?? referenceAnswer\n const meta: FinResearchMeta = {\n id: row.id,\n category: row.category ?? 'unknown',\n question: row.question,\n referenceAnswer,\n referenceReport,\n logicTree: row.logic_tree ?? null,\n rubric: row.rubric ?? null,\n judgeSystemPrompt: row.judge_system_prompt,\n judgePromptTemplate: row.judge_prompt_template,\n scoring: fixturesMode ? 'fixture-exact-reference' : 'official-logic-tree-judge',\n }\n return {\n id: row.id,\n split: row.category,\n prompt: [\n 'Complete this FinResearchBench financial research task.',\n 'Produce a decision-grade research answer with explicit reasoning, evidence, and final conclusion.',\n '',\n row.question,\n ].join('\\n'),\n metadata: meta as unknown as Record<string, unknown>,\n }\n}\n\nfunction readMeta(task: BenchTask): FinResearchMeta {\n const md = task.metadata\n if (!md || typeof md.question !== 'string') {\n throw new Error(`FinResearchBench task ${task.id} missing metadata — loadTasks did not populate it`)\n }\n return md as unknown as FinResearchMeta\n}\n\nfunction selectRows(rows: FinResearchRecord[], opts: LoadOptions, fixturesMode: boolean): BenchTask[] {\n let tasks = rows.map((row) => rowToTask(row, fixturesMode))\n if (opts.split) tasks = tasks.filter((task) => task.split === opts.split)\n if (opts.ids) {\n const want = new Set(opts.ids)\n tasks = tasks.filter((task) => want.has(task.id))\n } else if (opts.limit !== undefined) {\n tasks = tasks.slice(0, opts.limit)\n }\n if (tasks.length === 0) throw new Error(`FinResearchBench: no tasks matched ${JSON.stringify(opts)}`)\n return tasks\n}\n\nasync function loadFixtures(opts: LoadOptions): Promise<BenchTask[]> {\n const records = readRecords(await readFile(FIXTURES, 'utf8'))\n console.warn(`[finresearchbench] FINRESEARCHBENCH_FIXTURES=1 — loading ${records.length} adapter fixtures`)\n return selectRows(records, opts, true)\n}\n\nasync function loadOfficialTasks(path: string, opts: LoadOptions): Promise<BenchTask[]> {\n const records = readRecords(await readFile(path, 'utf8'))\n assertLiveJudgeFields(records, path)\n return selectRows(records, opts, false)\n}\n\nfunction fillTemplate(meta: FinResearchMeta, response: string): string {\n const template = meta.judgePromptTemplate\n if (!template) throw new Error(`FinResearchBench task ${meta.id} missing judge_prompt_template`)\n return template\n .replaceAll('{question}', meta.question)\n .replaceAll('{response}', response)\n .replaceAll('{reference_answer}', meta.referenceAnswer)\n .replaceAll('{reference_report}', meta.referenceReport)\n .replaceAll('{logic_tree}', JSON.stringify(meta.logicTree, null, 2))\n .replaceAll('{rubric}', JSON.stringify(meta.rubric, null, 2))\n}\n\nfunction parseJudgeScore(content: string): { score: number; raw: unknown } {\n const candidates: string[] = []\n for (const m of content.matchAll(/```(?:json)?\\s*([\\s\\S]*?)```/g)) candidates.push(m[1].trim())\n for (const m of content.matchAll(/\\{[\\s\\S]*?\\}/g)) candidates.push(m[0])\n candidates.push(content.trim())\n for (const candidate of candidates) {\n let parsed: Record<string, unknown>\n try {\n parsed = JSON.parse(candidate) as Record<string, unknown>\n } catch {\n continue\n }\n const raw = parsed.score ?? parsed.overall_score ?? parsed.total_score ?? parsed.answer_score\n const n = typeof raw === 'number' ? raw : typeof raw === 'string' ? Number(raw) : NaN\n if (!Number.isFinite(n)) continue\n if (n < 0) throw new Error(`FinResearchBench judge score is negative: ${JSON.stringify(parsed)}`)\n const score = n <= 1 ? n : n <= 10 ? n / 10 : n / 100\n if (score > 1) throw new Error(`FinResearchBench judge score outside supported range: ${JSON.stringify(parsed)}`)\n return { score, raw: parsed }\n }\n throw new Error(`FinResearchBench judge produced no parseable JSON score: ${content.slice(0, 400)}`)\n}\n\n/**\n * Map one drained judge turn to a BenchScore. The judge turn's exact Runtime\n * usage record lands on `judgeUsage` verbatim, so an unproven token count or\n * dollar amount stays flagged (`tokensKnown`/`usdKnown` false) instead of\n * reading as a known zero cost.\n */\nexport function scoreOfficialJudgeTurn(\n task: BenchTask,\n turn: Readonly<{ finalText?: string; usage: AgentTurnUsage }>,\n requestedJudgeModel: string,\n): BenchScore {\n const meta = readMeta(task)\n const content = turn.finalText\n if (!content) throw new Error('FinResearchBench judge returned no message content')\n const { score, raw } = parseJudgeScore(content)\n return {\n resolved: score >= Number(process.env.FINRESEARCHBENCH_PASS_THRESHOLD ?? 0.8),\n score,\n detail: JSON.stringify({ scoring: meta.scoring, category: meta.category, judgeModel: requestedJudgeModel, raw }),\n judgeUsage: turn.usage,\n }\n}\n\nasync function runOfficialJudge(task: BenchTask, meta: FinResearchMeta, response: string): Promise<BenchScore> {\n if (!meta.judgeSystemPrompt) throw new Error(`FinResearchBench task ${meta.id} missing judge_system_prompt`)\n const router = routerConfig()\n const turn = await runBenchRouterTurn(\n {\n routerBaseUrl: router.baseUrl,\n routerKey: router.key,\n profile: {\n name: 'finresearchbench-judge',\n harness: 'cli-base',\n model: {\n provider: 'tangle-router',\n default: router.model,\n metadata: { temperature: 0 },\n },\n prompt: { systemPrompt: meta.judgeSystemPrompt },\n },\n },\n fillTemplate(meta, response),\n )\n return scoreOfficialJudgeTurn(task, turn, router.model)\n}\n\nfunction normalizeText(value: string): string {\n return value.toLowerCase().replace(/\\s+/g, ' ').trim()\n}\n\nfunction scoreFixture(meta: FinResearchMeta, artifact: string): BenchScore {\n const answer = normalizeText(meta.referenceAnswer || meta.referenceReport)\n const response = normalizeText(artifact)\n const score = answer.length > 0 && response.includes(answer) ? 1 : 0\n return {\n resolved: score === 1,\n score,\n detail: JSON.stringify({ scoring: meta.scoring, category: meta.category }),\n }\n}\n\nexport function createFinResearchBenchAdapter(): BenchmarkAdapter {\n const fixturesMode = process.env.FINRESEARCHBENCH_FIXTURES === '1'\n\n return {\n name: 'finresearchbench',\n\n async preflight() {\n if (fixturesMode) {\n await assertReadable(FIXTURES, 'fixture file')\n return\n }\n const file = dataFile()\n if (!file) {\n throw new Error(\n 'FINRESEARCHBENCH_DATA_FILE is required. Fix: export the official FinResearchBench rows as JSON/JSONL with judge_system_prompt and judge_prompt_template fields, then set FINRESEARCHBENCH_DATA_FILE=/path/to/export.jsonl.',\n )\n }\n routerConfig()\n await assertReadable(file, 'data file')\n await loadOfficialTasks(file, { limit: 1 })\n },\n\n async loadTasks(opts: LoadOptions = {}) {\n if (fixturesMode) return loadFixtures(opts)\n const file = dataFile()\n if (!file) throw new Error('FINRESEARCHBENCH_DATA_FILE is required to load FinResearchBench rows')\n return loadOfficialTasks(file, opts)\n },\n\n async goldArtifact(task: BenchTask) {\n const meta = readMeta(task)\n return meta.referenceReport || meta.referenceAnswer || undefined\n },\n\n async judge(task: BenchTask, artifact: string): Promise<BenchScore> {\n const meta = readMeta(task)\n if (fixturesMode) return scoreFixture(meta, artifact)\n if (artifact.trim().length === 0) {\n return {\n resolved: false,\n score: 0,\n detail: JSON.stringify({ scoring: meta.scoring, category: meta.category, reason: 'empty answer' }),\n }\n }\n return runOfficialJudge(task, meta, artifact)\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAgBA,MAAM,WAAW,KAAK,WAAW,YAAY,uBAAuB;AA2BpE,MAAM,iBAAqC,QAAQ,IAAI;AAEvD,SAAS,eAAgE;CACvE,MAAM,MAAM,QAAQ,IAAI;CACxB,IAAI,CAAC,KAAK,MAAM,IAAI,MAAM,kEAAkE;CAC5F,OAAO;EACL,SAAS,QAAQ,IAAI,eAAe;EACpC;EACA,OAAO,QAAQ,IAAI,gCAAgC,Q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AChB,MAAM,eAAe,UAAU,cAAc;IAC7C;GACF;GACA,MAAM,OAAO,SAAS;GACtB,IAAI,CAAC,MACH,MAAM,IAAI,MACR,4NACF;GAEF,aAAa;GACb,MAAM,eAAe,MAAM,WAAW;GACtC,MAAM,kBAAkB,MAAM,EAAE,OAAO,EAAE,CAAC;EAC5C;EAEA,MAAM,UAAU,OAAoB,CAAC,GAAG;GACtC,IAAI,cAAc,OAAO,aAAa,IAAI;GAC1C,MAAM,OAAO,SAAS;GACtB,IAAI,CAAC,MAAM,MAAM,IAAI,MAAM,sEAAsE;GACjG,OAAO,kBAAkB,MAAM,IAAI;EACrC;EAEA,MAAM,aAAa,MAAiB;GAClC,MAAM,OAAO,SAAS,IAAI;GAC1B,OAAO,KAAK,mBAAmB,KAAK,mBAAmB,KAAA;EACzD;EAEA,MAAM,MAAM,MAAiB,UAAuC;GAClE,MAAM,OAAO,SAAS,IAAI;GAC1B,IAAI,cAAc,OAAO,aAAa,MAAM,QAAQ;GACpD,IAAI,SAAS,KAAK,CAAC,CAAC,WAAW,GAC7B,OAAO;IACL,UAAU;IACV,OAAO;IACP,QAAQ,KAAK,UAAU;KAAE,SAAS,KAAK;KAAS,UAAU,KAAK;KAAU,QAAQ;IAAe,CAAC;GACnG;GAEF,OAAO,iBAAiB,MAAM,MAAM,QAAQ;EAC9C;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"finresearchbench.js","names":[],"sources":["../../src/benchmarks/finresearchbench.ts"],"sourcesContent":["/**\n * FinResearchBench-compatible adapter.\n *\n * The paper defines a logic-tree Agent-as-a-Judge benchmark for financial\n * research reports, but there is no stable public scorer package wired here.\n * Live mode therefore requires a local data export whose rows carry the official\n * judge prompt/template/logic tree. The adapter refuses to invent a judge.\n */\n\nimport { readFile, stat } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport type { AgentTurnUsage } from '@tangle-network/agent-runtime/kernel'\nimport { runBenchRouterTurn } from '../router-turn'\nimport { benchRoot } from './_harness'\nimport type { BenchmarkAdapter, BenchScore, BenchTask, LoadOptions } from './types'\n\nconst FIXTURES = join(benchRoot, 'fixtures', 'finresearchbench.json')\n\ninterface FinResearchRecord {\n id: string\n question: string\n category?: string\n reference_answer?: string\n reference_report?: string\n logic_tree?: unknown\n rubric?: unknown\n judge_system_prompt?: string\n judge_prompt_template?: string\n}\n\ninterface FinResearchMeta {\n id: string\n category: string\n question: string\n referenceAnswer: string\n referenceReport: string\n logicTree: unknown\n rubric: unknown\n judgeSystemPrompt?: string\n judgePromptTemplate?: string\n scoring: 'official-logic-tree-judge' | 'fixture-exact-reference'\n}\n\nconst dataFile = (): string | undefined => process.env.FINRESEARCHBENCH_DATA_FILE\n\nfunction routerConfig(): { baseUrl: string; key: string; model: string } {\n const key = process.env.TANGLE_API_KEY\n if (!key) throw new Error('TANGLE_API_KEY is required for FinResearchBench live LLM judging')\n return {\n baseUrl: process.env.ROUTER_BASE ?? 'https://router.tangle.tools/v1',\n key,\n model: process.env.FINRESEARCHBENCH_JUDGE_MODEL ?? process.env.JUDGE_MODEL ?? 'deepseek/deepseek-v4.1-flash',\n }\n}\n\nasync function assertReadable(path: string, label: string): Promise<void> {\n try {\n await stat(path)\n } catch (err) {\n throw new Error(`FinResearchBench: missing ${label} at ${path} (${err instanceof Error ? err.message : err})`)\n }\n}\n\nfunction readRecords(raw: string): FinResearchRecord[] {\n const trimmed = raw.trim()\n if (trimmed.startsWith('[')) return JSON.parse(trimmed) as FinResearchRecord[]\n return trimmed\n .split(/\\r?\\n/)\n .map((line) => line.trim())\n .filter((line) => line.length > 0)\n .map((line) => JSON.parse(line) as FinResearchRecord)\n}\n\nfunction assertLiveJudgeFields(records: readonly FinResearchRecord[], source: string): void {\n const missing = records\n .filter((row) => !row.judge_system_prompt || !row.judge_prompt_template)\n .map((row) => row.id)\n if (missing.length > 0) {\n throw new Error(\n `FinResearchBench live rows from ${source} missing official judge prompts for ${missing.length}/${records.length} row(s): ${missing.slice(0, 5).join(', ')}. ` +\n 'Use a benchmark export with judge_system_prompt and judge_prompt_template, or do not score this benchmark live.',\n )\n }\n}\n\nfunction rowToTask(row: FinResearchRecord, fixturesMode: boolean): BenchTask {\n const referenceAnswer = row.reference_answer ?? ''\n const referenceReport = row.reference_report ?? referenceAnswer\n const meta: FinResearchMeta = {\n id: row.id,\n category: row.category ?? 'unknown',\n question: row.question,\n referenceAnswer,\n referenceReport,\n logicTree: row.logic_tree ?? null,\n rubric: row.rubric ?? null,\n judgeSystemPrompt: row.judge_system_prompt,\n judgePromptTemplate: row.judge_prompt_template,\n scoring: fixturesMode ? 'fixture-exact-reference' : 'official-logic-tree-judge',\n }\n return {\n id: row.id,\n split: row.category,\n prompt: [\n 'Complete this FinResearchBench financial research task.',\n 'Produce a decision-grade research answer with explicit reasoning, evidence, and final conclusion.',\n '',\n row.question,\n ].join('\\n'),\n metadata: meta as unknown as Record<string, unknown>,\n }\n}\n\nfunction readMeta(task: BenchTask): FinResearchMeta {\n const md = task.metadata\n if (!md || typeof md.question !== 'string') {\n throw new Error(`FinResearchBench task ${task.id} missing metadata — loadTasks did not populate it`)\n }\n return md as unknown as FinResearchMeta\n}\n\nfunction selectRows(rows: FinResearchRecord[], opts: LoadOptions, fixturesMode: boolean): BenchTask[] {\n let tasks = rows.map((row) => rowToTask(row, fixturesMode))\n if (opts.split) tasks = tasks.filter((task) => task.split === opts.split)\n if (opts.ids) {\n const want = new Set(opts.ids)\n tasks = tasks.filter((task) => want.has(task.id))\n } else if (opts.limit !== undefined) {\n tasks = tasks.slice(0, opts.limit)\n }\n if (tasks.length === 0) throw new Error(`FinResearchBench: no tasks matched ${JSON.stringify(opts)}`)\n return tasks\n}\n\nasync function loadFixtures(opts: LoadOptions): Promise<BenchTask[]> {\n const records = readRecords(await readFile(FIXTURES, 'utf8'))\n console.warn(`[finresearchbench] FINRESEARCHBENCH_FIXTURES=1 — loading ${records.length} adapter fixtures`)\n return selectRows(records, opts, true)\n}\n\nasync function loadOfficialTasks(path: string, opts: LoadOptions): Promise<BenchTask[]> {\n const records = readRecords(await readFile(path, 'utf8'))\n assertLiveJudgeFields(records, path)\n return selectRows(records, opts, false)\n}\n\nfunction fillTemplate(meta: FinResearchMeta, response: string): string {\n const template = meta.judgePromptTemplate\n if (!template) throw new Error(`FinResearchBench task ${meta.id} missing judge_prompt_template`)\n return template\n .replaceAll('{question}', meta.question)\n .replaceAll('{response}', response)\n .replaceAll('{reference_answer}', meta.referenceAnswer)\n .replaceAll('{reference_report}', meta.referenceReport)\n .replaceAll('{logic_tree}', JSON.stringify(meta.logicTree, null, 2))\n .replaceAll('{rubric}', JSON.stringify(meta.rubric, null, 2))\n}\n\nfunction parseJudgeScore(content: string): { score: number; raw: unknown } {\n const candidates: string[] = []\n for (const m of content.matchAll(/```(?:json)?\\s*([\\s\\S]*?)```/g)) candidates.push(m[1].trim())\n for (const m of content.matchAll(/\\{[\\s\\S]*?\\}/g)) candidates.push(m[0])\n candidates.push(content.trim())\n for (const candidate of candidates) {\n let parsed: Record<string, unknown>\n try {\n parsed = JSON.parse(candidate) as Record<string, unknown>\n } catch {\n continue\n }\n const raw = parsed.score ?? parsed.overall_score ?? parsed.total_score ?? parsed.answer_score\n const n = typeof raw === 'number' ? raw : typeof raw === 'string' ? Number(raw) : NaN\n if (!Number.isFinite(n)) continue\n if (n < 0) throw new Error(`FinResearchBench judge score is negative: ${JSON.stringify(parsed)}`)\n const score = n <= 1 ? n : n <= 10 ? n / 10 : n / 100\n if (score > 1) throw new Error(`FinResearchBench judge score outside supported range: ${JSON.stringify(parsed)}`)\n return { score, raw: parsed }\n }\n throw new Error(`FinResearchBench judge produced no parseable JSON score: ${content.slice(0, 400)}`)\n}\n\n/**\n * Map one drained judge turn to a BenchScore. The judge turn's exact Runtime\n * usage record lands on `judgeUsage` verbatim, so an unproven token count or\n * dollar amount stays flagged (`tokensKnown`/`usdKnown` false) instead of\n * reading as a known zero cost.\n */\nexport function scoreOfficialJudgeTurn(\n task: BenchTask,\n turn: Readonly<{ finalText?: string; usage: AgentTurnUsage }>,\n requestedJudgeModel: string,\n): BenchScore {\n const meta = readMeta(task)\n const content = turn.finalText\n if (!content) throw new Error('FinResearchBench judge returned no message content')\n const { score, raw } = parseJudgeScore(content)\n return {\n resolved: score >= Number(process.env.FINRESEARCHBENCH_PASS_THRESHOLD ?? 0.8),\n score,\n detail: JSON.stringify({ scoring: meta.scoring, category: meta.category, judgeModel: requestedJudgeModel, raw }),\n judgeUsage: turn.usage,\n }\n}\n\nasync function runOfficialJudge(task: BenchTask, meta: FinResearchMeta, response: string): Promise<BenchScore> {\n if (!meta.judgeSystemPrompt) throw new Error(`FinResearchBench task ${meta.id} missing judge_system_prompt`)\n const router = routerConfig()\n const turn = await runBenchRouterTurn(\n {\n routerBaseUrl: router.baseUrl,\n routerKey: router.key,\n profile: {\n name: 'finresearchbench-judge',\n harness: 'cli-base',\n model: {\n provider: 'tangle-router',\n default: router.model,\n metadata: { temperature: 0 },\n },\n prompt: { systemPrompt: meta.judgeSystemPrompt },\n },\n },\n fillTemplate(meta, response),\n )\n return scoreOfficialJudgeTurn(task, turn, router.model)\n}\n\nfunction normalizeText(value: string): string {\n return value.toLowerCase().replace(/\\s+/g, ' ').trim()\n}\n\nfunction scoreFixture(meta: FinResearchMeta, artifact: string): BenchScore {\n const answer = normalizeText(meta.referenceAnswer || meta.referenceReport)\n const response = normalizeText(artifact)\n const score = answer.length > 0 && response.includes(answer) ? 1 : 0\n return {\n resolved: score === 1,\n score,\n detail: JSON.stringify({ scoring: meta.scoring, category: meta.category }),\n }\n}\n\nexport function createFinResearchBenchAdapter(): BenchmarkAdapter {\n const fixturesMode = process.env.FINRESEARCHBENCH_FIXTURES === '1'\n\n return {\n name: 'finresearchbench',\n\n async preflight() {\n if (fixturesMode) {\n await assertReadable(FIXTURES, 'fixture file')\n return\n }\n const file = dataFile()\n if (!file) {\n throw new Error(\n 'FINRESEARCHBENCH_DATA_FILE is required. Fix: export the official FinResearchBench rows as JSON/JSONL with judge_system_prompt and judge_prompt_template fields, then set FINRESEARCHBENCH_DATA_FILE=/path/to/export.jsonl.',\n )\n }\n routerConfig()\n await assertReadable(file, 'data file')\n await loadOfficialTasks(file, { limit: 1 })\n },\n\n async loadTasks(opts: LoadOptions = {}) {\n if (fixturesMode) return loadFixtures(opts)\n const file = dataFile()\n if (!file) throw new Error('FINRESEARCHBENCH_DATA_FILE is required to load FinResearchBench rows')\n return loadOfficialTasks(file, opts)\n },\n\n async goldArtifact(task: BenchTask) {\n const meta = readMeta(task)\n return meta.referenceReport || meta.referenceAnswer || undefined\n },\n\n async judge(task: BenchTask, artifact: string): Promise<BenchScore> {\n const meta = readMeta(task)\n if (fixturesMode) return scoreFixture(meta, artifact)\n if (artifact.trim().length === 0) {\n return {\n resolved: false,\n score: 0,\n detail: JSON.stringify({ scoring: meta.scoring, category: meta.category, reason: 'empty answer' }),\n }\n }\n return runOfficialJudge(task, meta, artifact)\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAgBA,MAAM,WAAW,KAAK,WAAW,YAAY,uBAAuB;AA2BpE,MAAM,iBAAqC,QAAQ,IAAI;AAEvD,SAAS,eAAgE;CACvE,MAAM,MAAM,QAAQ,IAAI;CACxB,IAAI,CAAC,KAAK,MAAM,IAAI,MAAM,kEAAkE;CAC5F,OAAO;EACL,SAAS,QAAQ,IAAI,eAAe;EACpC;EACA,OAAO,QAAQ,IAAI,gCAAgC,QAAQ,IAAI,eAAe;CAChF;AACF;AAEA,eAAe,eAAe,MAAc,OAA8B;CACxE,IAAI;EACF,MAAM,KAAK,IAAI;CACjB,SAAS,KAAK;EACZ,MAAM,IAAI,MAAM,6BAA6B,MAAM,MAAM,KAAK,IAAI,eAAe,QAAQ,IAAI,UAAU,IAAI,EAAE;CAC/G;AACF;AAEA,SAAS,YAAY,KAAkC;CACrD,MAAM,UAAU,IAAI,KAAK;CACzB,IAAI,QAAQ,WAAW,GAAG,GAAG,OAAO,KAAK,MAAM,OAAO;CACtD,OAAO,QACJ,MAAM,OAAO,CAAC,CACd,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,MAAM,IAAI;EACrC;EAEA,MAAM,aAAa,MAAiB;GAClC,MAAM,OAAO,SAAS,IAAI;GAC1B,OAAO,KAAK,mBAAmB,KAAK,mBAAmB,KAAA;EACzD;EAEA,MAAM,MAAM,MAAiB,UAAuC;GAClE,MAAM,OAAO,SAAS,IAAI;GAC1B,IAAI,cAAc,OAAO,aAAa,MAAM,QAAQ;GACpD,IAAI,SAAS,KAAK,CAAC,CAAC,WAAW,GAC7B,OAAO;IACL,UAAU;IACV,OAAO;IACP,QAAQ,KAAK,UAAU;KAAE,SAAS,KAAK;KAAS,UAAU,KAAK;KAAU,QAAQ;IAAe,CAAC;GACnG;GAEF,OAAO,iBAAiB,MAAM,MAAM,QAAQ;EAC9C;CACF;AACF"}
|
|
@@ -92,7 +92,7 @@ function fillJudgePrompt(meta, response) {
|
|
|
92
92
|
function judgeRouter() {
|
|
93
93
|
const key = process.env.TANGLE_API_KEY;
|
|
94
94
|
if (!key) throw new Error("TANGLE_API_KEY is required for the FinSearchComp per-record LLM judge");
|
|
95
|
-
const model = process.env.JUDGE_MODEL ?? "deepseek-v4-flash";
|
|
95
|
+
const model = process.env.JUDGE_MODEL ?? "deepseek/deepseek-v4.1-flash";
|
|
96
96
|
return {
|
|
97
97
|
baseUrl: process.env.ROUTER_BASE ?? "https://router.tangle.tools/v1",
|
|
98
98
|
key,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"finsearchcomp.js","names":[],"sources":["../../src/benchmarks/finsearchcomp.ts"],"sourcesContent":["/**\n * FinSearchComp adapter (randomtutu/FinSearchComp). Agentic financial search +\n * reasoning. Worker artifact = the agent's free-form final answer text (zh/en).\n *\n * Each record is SELF-CONTAINED and carries its OWN judge: a per-record\n * `judge_system_prompt` + a `judge_prompt_template` with {prompt},\n * {response_reference} (gold answer WITH embedded tolerance/scoring-criteria),\n * and {response} (the student answer) placeholders. We faithfully REPLICATE the\n * benchmark's judge — fill the template, run it under the record's system prompt\n * via the pinned router (temperature 0), and parse the JSON the judge emits. The\n * judge returns an `answer_score` field; 1/positive = resolved, else not.\n * This matches the FinSearchComp leaderboard (Grok-4-web 68.9%).\n *\n * There is NO deterministic Tier-1 path here: the gold answer is prose with\n * region-specific units, embedded tolerances (\"允许1%的误差\"), and multi-point\n * scoring criteria. The benchmark intends its own LLM judge to be the arbiter,\n * so the judge IS the score — fail loud on unparseable judge output (never\n * default to resolved).\n *\n * SCOPE: T2 (Simple_Historical_Lookup) + T3 (Complex_Historical_Investigation)\n * are fully self-contained and supported. T1 (Time_Sensitive_Data_Fetching)\n * needs a live market snapshot / akshare ground truth to fill the judge's\n * {ground_truth} slot — it is SKIPPED in loadTasks and flagged in preflight.\n * See {@link T1Seam}.\n *\n * Requires for a live run: network access to the GitHub-hosted dataset JSON and\n * a TANGLE_API_KEY for the judge. For offline/CI verification, loadTasks falls back\n * to the committed fixtures (bench/fixtures/finsearchcomp.json) with an explicit\n * console.warn — never a silent fallback.\n */\n\nimport { readFile } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport { runBenchRouterTurn } from '../router-turn'\nimport type { BenchmarkAdapter, BenchScore, BenchTask, LoadOptions } from './types'\n\nconst BENCH_ROOT = fileURLToPath(new URL('../..', import.meta.url))\nconst FIXTURES = join(BENCH_ROOT, 'fixtures', 'finsearchcomp.json')\n\nconst DATASET_URL =\n 'https://raw.githubusercontent.com/randomtutu/FinSearchComp/main/data/finsearchcomp_data.json'\n\n/** Task-type prefix on prompt_id, e.g. \"(T2)Simple_Historical_Lookup_001\". */\ntype TaskType = 'T1' | 'T2' | 'T3'\n/** Only these are self-contained (gold + own judge, no external ground truth). */\nconst SUPPORTED_TYPES: ReadonlySet<TaskType> = new Set<TaskType>(['T2', 'T3'])\n\n/**\n * Worker contract appended to every task prompt. The judge is paraphrase- and\n * keyword-aware (\"答案为\", \"the answer is\"), so we do not impose a sentinel; we\n * pass the whole artifact through as {response}. We DO ask the worker to lead\n * with its final value so a truncated artifact still carries the answer.\n */\nconst WORKER_CONTRACT = [\n '',\n 'Research this financial question using live web/market sources and answer it.',\n 'State your final answer explicitly, with the exact units and precision the question requests.',\n 'Respect any tolerance the question implies; show the value you settled on, not just intermediate work.',\n].join('\\n')\n\n/**\n * Typed seam for T1 (Time_Sensitive_Data_Fetching). T1 records score against a\n * live market snapshot the judge consumes via a {ground_truth} template slot;\n * the adapter does NOT fabricate that snapshot. Wiring T1 means supplying a\n * resolver that fetches the akshare/market value for the record at judge time\n * and filling {ground_truth}. Until then T1 is excluded from loadTasks.\n */\nexport interface T1Seam {\n promptId: string\n /** Resolver that returns the real-time ground-truth block for the {ground_truth} slot. */\n resolveGroundTruth(promptId: string): Promise<string>\n}\n\ninterface FinSearchRecord {\n prompt_id: string\n prompt: string\n response_reference: string\n judge_prompt_template: string\n judge_system_prompt: string\n label: string\n}\n\ninterface FinSearchMeta {\n promptId: string\n label: string\n taskType: TaskType\n region: string\n responseReference: string\n judgePromptTemplate: string\n judgeSystemPrompt: string\n rawPrompt: string\n}\n\n/** \"(T2)Simple_Historical_Lookup_001\" → \"T2\"; throws on an unknown/missing prefix. */\nfunction parseTaskType(promptId: string): TaskType {\n const m = promptId.match(/^\\((T[123])\\)/)\n if (!m) throw new Error(`FinSearchComp prompt_id has no (T1|T2|T3) prefix: ${JSON.stringify(promptId)}`)\n return m[1] as TaskType\n}\n\n/** \"Simple_Historical_Lookup(Greater China)\" → \"Greater China\"; '' when absent. */\nfunction parseRegion(label: string): string {\n const m = label.match(/\\(([^()]+)\\)\\s*$/)\n return m ? m[1].trim() : ''\n}\n\nfunction recordToTask(rec: FinSearchRecord): BenchTask {\n const taskType = parseTaskType(rec.prompt_id)\n const meta: FinSearchMeta = {\n promptId: rec.prompt_id,\n label: rec.label,\n taskType,\n region: parseRegion(rec.label),\n responseReference: rec.response_reference,\n judgePromptTemplate: rec.judge_prompt_template,\n judgeSystemPrompt: rec.judge_system_prompt,\n rawPrompt: rec.prompt,\n }\n return {\n id: rec.prompt_id,\n split: taskType,\n prompt: rec.prompt + WORKER_CONTRACT,\n metadata: meta as unknown as Record<string, unknown>,\n }\n}\n\nfunction readMeta(task: BenchTask): FinSearchMeta {\n const md = task.metadata\n if (\n !md ||\n typeof md.responseReference !== 'string' ||\n typeof md.judgePromptTemplate !== 'string' ||\n typeof md.judgeSystemPrompt !== 'string' ||\n typeof md.rawPrompt !== 'string'\n ) {\n throw new Error(`FinSearchComp task ${task.id} missing judge metadata — loadTasks did not populate it`)\n }\n return md as unknown as FinSearchMeta\n}\n\n/** Fill the per-record judge_prompt_template. {ground_truth} is T1-only and unused for T2/T3. */\nfunction fillJudgePrompt(meta: FinSearchMeta, response: string): string {\n return meta.judgePromptTemplate\n .replaceAll('{prompt}', meta.rawPrompt)\n .replaceAll('{response_reference}', meta.responseReference)\n .replaceAll('{response}', response)\n}\n\ninterface JudgeRouter {\n baseUrl: string\n key: string\n model: string\n}\n\nfunction judgeRouter(): JudgeRouter {\n const key = process.env.TANGLE_API_KEY\n if (!key) throw new Error('TANGLE_API_KEY is required for the FinSearchComp per-record LLM judge')\n const model = process.env.JUDGE_MODEL ?? 'deepseek-v4-flash'\n const baseUrl = process.env.ROUTER_BASE ?? 'https://router.tangle.tools/v1'\n return { baseUrl, key, model }\n}\n\n/**\n * The judge emits a JSON object with an `answer_score`. In this dataset it is a\n * flat integer ({\"answer_score\": 1}); we also accept the nested-array form\n * ([[1]] → read [0][0]) the upstream scorer can produce. 1/positive = resolved.\n * A \"null\" sentinel (judge could not obtain ground truth) is NOT a pass.\n */\nfunction readAnswerScore(value: unknown): { resolved: boolean; score: number; raw: unknown } {\n let v: unknown = value\n // unwrap nested-array form: [[s]] / [s]\n while (Array.isArray(v)) v = v[0]\n if (v === null || v === undefined || v === 'null') {\n return { resolved: false, score: 0, raw: value }\n }\n const n = typeof v === 'number' ? v : typeof v === 'string' ? Number(v) : NaN\n if (!Number.isFinite(n)) {\n throw new Error(`FinSearchComp judge answer_score not numeric: ${JSON.stringify(value)}`)\n }\n // Their scale: 1 = correct, 0 = wrong. Treat any positive as resolved; clamp to 0..1.\n const resolved = n >= 1\n const score = n <= 0 ? 0 : n >= 1 ? 1 : n\n return { resolved, score, raw: value }\n}\n\n/** Extract the first JSON object carrying `answer_score` from judge output; throw if none. */\nfunction parseJudgeOutput(content: string): { resolved: boolean; score: number; raw: unknown } {\n // Prefer a fenced block, then fall back to scanning for a {...} with answer_score.\n const candidates: string[] = []\n for (const m of content.matchAll(/```(?:json)?\\s*([\\s\\S]*?)```/g)) candidates.push(m[1].trim())\n for (const m of content.matchAll(/\\{[^{}]*\"answer_score\"[\\s\\S]*?\\}/g)) candidates.push(m[0])\n candidates.push(content.trim())\n for (const c of candidates) {\n let parsed: { answer_score?: unknown }\n try {\n parsed = JSON.parse(c) as { answer_score?: unknown }\n } catch {\n continue\n }\n if ('answer_score' in parsed) return readAnswerScore(parsed.answer_score)\n }\n throw new Error(\n `FinSearchComp judge produced no parseable {\"answer_score\": …}: ${content.slice(0, 400)}`,\n )\n}\n\n/** Run the record's own judge via the router. Fail loud on transport/parse errors. */\nasync function runRecordJudge(meta: FinSearchMeta, response: string, router: JudgeRouter): Promise<BenchScore> {\n const turn = await runBenchRouterTurn(\n {\n routerBaseUrl: router.baseUrl,\n routerKey: router.key,\n profile: {\n name: 'finsearchcomp-judge',\n harness: 'cli-base',\n model: {\n provider: 'tangle-router',\n default: router.model,\n metadata: { temperature: 0 },\n },\n prompt: { systemPrompt: meta.judgeSystemPrompt },\n },\n },\n fillJudgePrompt(meta, response),\n )\n const content = turn.finalText\n if (!content) throw new Error('FinSearchComp judge returned no message content')\n const { resolved, score, raw } = parseJudgeOutput(content)\n return {\n resolved,\n score,\n detail: JSON.stringify({\n taskType: meta.taskType,\n region: meta.region,\n answerScore: raw,\n judgeModel: router.model,\n }),\n }\n}\n\nfunction selectRecords(records: FinSearchRecord[], opts: LoadOptions): BenchTask[] {\n let tasks = records\n .filter((r) => SUPPORTED_TYPES.has(parseTaskType(r.prompt_id)))\n .map(recordToTask)\n if (opts.split) tasks = tasks.filter((t) => t.split === opts.split)\n if (opts.ids) {\n const want = new Set(opts.ids)\n tasks = tasks.filter((t) => want.has(t.id))\n } else if (opts.limit !== undefined) {\n tasks = balanceByType(tasks, opts.limit)\n }\n return tasks\n}\n\n/** Round-robin across task types (T2/T3) so a `limit` pulls a balanced mix\n * rather than slicing the type-ordered dataset's first N (which yields all\n * T2). Deterministic — preserves dataset order within each type. */\nfunction balanceByType(tasks: BenchTask[], limit: number): BenchTask[] {\n const queues = new Map<TaskType, BenchTask[]>()\n for (const t of tasks) {\n const k = parseTaskType(t.id)\n const q = queues.get(k)\n if (q) q.push(t)\n else queues.set(k, [t])\n }\n const lanes = [...queues.values()]\n const out: BenchTask[] = []\n for (let i = 0; out.length < limit; i++) {\n const before = out.length\n for (const lane of lanes) {\n if (i < lane.length) out.push(lane[i])\n if (out.length >= limit) break\n }\n if (out.length === before) break // all lanes exhausted\n }\n return out\n}\n\nasync function loadFixtures(opts: LoadOptions): Promise<BenchTask[]> {\n const records = JSON.parse(await readFile(FIXTURES, 'utf8')) as FinSearchRecord[]\n return selectRecords(records, opts)\n}\n\nasync function fetchDataset(): Promise<FinSearchRecord[]> {\n const res = await fetch(DATASET_URL)\n if (!res.ok) throw new Error(`FinSearchComp dataset HTTP ${res.status} fetching ${DATASET_URL}`)\n const data = (await res.json()) as FinSearchRecord[]\n if (!Array.isArray(data) || data.length === 0) {\n throw new Error(`FinSearchComp dataset empty or not an array: ${DATASET_URL}`)\n }\n return data\n}\n\nexport function createFinsearchcompAdapter(): BenchmarkAdapter {\n const fixturesMode = process.env.FINSEARCHCOMP_FIXTURES === '1'\n\n return {\n name: 'finsearchcomp',\n\n async preflight() {\n // The per-record LLM judge is the arbiter in both modes — its router\n // config must exist or no score can be produced.\n judgeRouter()\n console.warn(\n '[finsearchcomp] T1 (Time_Sensitive_Data_Fetching) is NOT scored: it needs a live ' +\n 'market snapshot / akshare ground truth for the judge {ground_truth} slot. ' +\n 'loadTasks supports T2 + T3 only; wire T1Seam to add T1.',\n )\n if (fixturesMode) {\n await readFile(FIXTURES, 'utf8').catch((err) => {\n throw new Error(\n `FINSEARCHCOMP_FIXTURES=1 but ${FIXTURES} unreadable: ${err instanceof Error ? err.message : err}`,\n )\n })\n return\n }\n const res = await fetch(DATASET_URL, { method: 'HEAD' }).catch((err) => {\n throw new Error(\n `finsearchcomp preflight failed reaching ${DATASET_URL}: ${err instanceof Error ? err.message : err}\\n` +\n `Fix: ensure network access to raw.githubusercontent.com, or set FINSEARCHCOMP_FIXTURES=1 ` +\n `to run against the committed fixtures offline.`,\n )\n })\n if (!res.ok) {\n throw new Error(\n `finsearchcomp preflight: dataset HEAD ${res.status} for ${DATASET_URL}. ` +\n `Set FINSEARCHCOMP_FIXTURES=1 to run against the committed fixtures offline.`,\n )\n }\n },\n\n async loadTasks(opts: LoadOptions = {}) {\n if (fixturesMode) return loadFixtures(opts)\n let records: FinSearchRecord[]\n try {\n records = await fetchDataset()\n } catch (err) {\n console.warn(\n `[finsearchcomp] live dataset fetch failed (${err instanceof Error ? err.message : err}); ` +\n `falling back to committed fixtures at ${FIXTURES}`,\n )\n return loadFixtures(opts)\n }\n return selectRecords(records, opts)\n },\n\n async goldArtifact(task: BenchTask) {\n // Gold artifact = the record's response_reference fed back as the student\n // answer, so verify-judge proves gold→resolved through the SAME per-record\n // judge the real artifact takes. The reference may carry tolerance/criteria\n // prose; the judge is built to read the value out of it.\n const meta = readMeta(task)\n return meta.responseReference\n },\n\n async judge(task: BenchTask, artifact: string): Promise<BenchScore> {\n const meta = readMeta(task)\n const response = artifact.trim()\n if (response.length === 0) {\n // Fail-closed — the benchmark's own judges score an empty answer 0.\n return {\n resolved: false,\n score: 0,\n detail: JSON.stringify({ taskType: meta.taskType, region: meta.region, reason: 'empty answer' }),\n }\n }\n return runRecordJudge(meta, response, judgeRouter())\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA,MA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,IAAI,IACP,MAAM,IAAI,MACR,yCAAyC,IAAI,OAAO,OAAO,YAAY,8EAEzE;EAEJ;EAEA,MAAM,UAAU,OAAoB,CAAC,GAAG;GACtC,IAAI,cAAc,OAAO,aAAa,IAAI;GAC1C,IAAI;GACJ,IAAI;IACF,UAAU,MAAM,aAAa;GAC/B,SAAS,KAAK;IACZ,QAAQ,KACN,8CAA8C,eAAe,QAAQ,IAAI,UAAU,IAAI,2CAC5C,UAC7C;IACA,OAAO,aAAa,IAAI;GAC1B;GACA,OAAO,cAAc,SAAS,IAAI;EACpC;EAEA,MAAM,aAAa,MAAiB;GAMlC,OADa,SAAS,IACZ,CAAC,CAAC;EACd;EAEA,MAAM,MAAM,MAAiB,UAAuC;GAClE,MAAM,OAAO,SAAS,IAAI;GAC1B,MAAM,WAAW,SAAS,KAAK;GAC/B,IAAI,SAAS,WAAW,GAEtB,OAAO;IACL,UAAU;IACV,OAAO;IACP,QAAQ,KAAK,UAAU;KAAE,UAAU,KAAK;KAAU,QAAQ,KAAK;KAAQ,QAAQ;IAAe,CAAC;GACjG;GAEF,OAAO,eAAe,MAAM,UAAU,YAAY,CAAC;EACrD;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"finsearchcomp.js","names":[],"sources":["../../src/benchmarks/finsearchcomp.ts"],"sourcesContent":["/**\n * FinSearchComp adapter (randomtutu/FinSearchComp). Agentic financial search +\n * reasoning. Worker artifact = the agent's free-form final answer text (zh/en).\n *\n * Each record is SELF-CONTAINED and carries its OWN judge: a per-record\n * `judge_system_prompt` + a `judge_prompt_template` with {prompt},\n * {response_reference} (gold answer WITH embedded tolerance/scoring-criteria),\n * and {response} (the student answer) placeholders. We faithfully REPLICATE the\n * benchmark's judge — fill the template, run it under the record's system prompt\n * via the pinned router (temperature 0), and parse the JSON the judge emits. The\n * judge returns an `answer_score` field; 1/positive = resolved, else not.\n * This matches the FinSearchComp leaderboard (Grok-4-web 68.9%).\n *\n * There is NO deterministic Tier-1 path here: the gold answer is prose with\n * region-specific units, embedded tolerances (\"允许1%的误差\"), and multi-point\n * scoring criteria. The benchmark intends its own LLM judge to be the arbiter,\n * so the judge IS the score — fail loud on unparseable judge output (never\n * default to resolved).\n *\n * SCOPE: T2 (Simple_Historical_Lookup) + T3 (Complex_Historical_Investigation)\n * are fully self-contained and supported. T1 (Time_Sensitive_Data_Fetching)\n * needs a live market snapshot / akshare ground truth to fill the judge's\n * {ground_truth} slot — it is SKIPPED in loadTasks and flagged in preflight.\n * See {@link T1Seam}.\n *\n * Requires for a live run: network access to the GitHub-hosted dataset JSON and\n * a TANGLE_API_KEY for the judge. For offline/CI verification, loadTasks falls back\n * to the committed fixtures (bench/fixtures/finsearchcomp.json) with an explicit\n * console.warn — never a silent fallback.\n */\n\nimport { readFile } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport { runBenchRouterTurn } from '../router-turn'\nimport type { BenchmarkAdapter, BenchScore, BenchTask, LoadOptions } from './types'\n\nconst BENCH_ROOT = fileURLToPath(new URL('../..', import.meta.url))\nconst FIXTURES = join(BENCH_ROOT, 'fixtures', 'finsearchcomp.json')\n\nconst DATASET_URL =\n 'https://raw.githubusercontent.com/randomtutu/FinSearchComp/main/data/finsearchcomp_data.json'\n\n/** Task-type prefix on prompt_id, e.g. \"(T2)Simple_Historical_Lookup_001\". */\ntype TaskType = 'T1' | 'T2' | 'T3'\n/** Only these are self-contained (gold + own judge, no external ground truth). */\nconst SUPPORTED_TYPES: ReadonlySet<TaskType> = new Set<TaskType>(['T2', 'T3'])\n\n/**\n * Worker contract appended to every task prompt. The judge is paraphrase- and\n * keyword-aware (\"答案为\", \"the answer is\"), so we do not impose a sentinel; we\n * pass the whole artifact through as {response}. We DO ask the worker to lead\n * with its final value so a truncated artifact still carries the answer.\n */\nconst WORKER_CONTRACT = [\n '',\n 'Research this financial question using live web/market sources and answer it.',\n 'State your final answer explicitly, with the exact units and precision the question requests.',\n 'Respect any tolerance the question implies; show the value you settled on, not just intermediate work.',\n].join('\\n')\n\n/**\n * Typed seam for T1 (Time_Sensitive_Data_Fetching). T1 records score against a\n * live market snapshot the judge consumes via a {ground_truth} template slot;\n * the adapter does NOT fabricate that snapshot. Wiring T1 means supplying a\n * resolver that fetches the akshare/market value for the record at judge time\n * and filling {ground_truth}. Until then T1 is excluded from loadTasks.\n */\nexport interface T1Seam {\n promptId: string\n /** Resolver that returns the real-time ground-truth block for the {ground_truth} slot. */\n resolveGroundTruth(promptId: string): Promise<string>\n}\n\ninterface FinSearchRecord {\n prompt_id: string\n prompt: string\n response_reference: string\n judge_prompt_template: string\n judge_system_prompt: string\n label: string\n}\n\ninterface FinSearchMeta {\n promptId: string\n label: string\n taskType: TaskType\n region: string\n responseReference: string\n judgePromptTemplate: string\n judgeSystemPrompt: string\n rawPrompt: string\n}\n\n/** \"(T2)Simple_Historical_Lookup_001\" → \"T2\"; throws on an unknown/missing prefix. */\nfunction parseTaskType(promptId: string): TaskType {\n const m = promptId.match(/^\\((T[123])\\)/)\n if (!m) throw new Error(`FinSearchComp prompt_id has no (T1|T2|T3) prefix: ${JSON.stringify(promptId)}`)\n return m[1] as TaskType\n}\n\n/** \"Simple_Historical_Lookup(Greater China)\" → \"Greater China\"; '' when absent. */\nfunction parseRegion(label: string): string {\n const m = label.match(/\\(([^()]+)\\)\\s*$/)\n return m ? m[1].trim() : ''\n}\n\nfunction recordToTask(rec: FinSearchRecord): BenchTask {\n const taskType = parseTaskType(rec.prompt_id)\n const meta: FinSearchMeta = {\n promptId: rec.prompt_id,\n label: rec.label,\n taskType,\n region: parseRegion(rec.label),\n responseReference: rec.response_reference,\n judgePromptTemplate: rec.judge_prompt_template,\n judgeSystemPrompt: rec.judge_system_prompt,\n rawPrompt: rec.prompt,\n }\n return {\n id: rec.prompt_id,\n split: taskType,\n prompt: rec.prompt + WORKER_CONTRACT,\n metadata: meta as unknown as Record<string, unknown>,\n }\n}\n\nfunction readMeta(task: BenchTask): FinSearchMeta {\n const md = task.metadata\n if (\n !md ||\n typeof md.responseReference !== 'string' ||\n typeof md.judgePromptTemplate !== 'string' ||\n typeof md.judgeSystemPrompt !== 'string' ||\n typeof md.rawPrompt !== 'string'\n ) {\n throw new Error(`FinSearchComp task ${task.id} missing judge metadata — loadTasks did not populate it`)\n }\n return md as unknown as FinSearchMeta\n}\n\n/** Fill the per-record judge_prompt_template. {ground_truth} is T1-only and unused for T2/T3. */\nfunction fillJudgePrompt(meta: FinSearchMeta, response: string): string {\n return meta.judgePromptTemplate\n .replaceAll('{prompt}', meta.rawPrompt)\n .replaceAll('{response_reference}', meta.responseReference)\n .replaceAll('{response}', response)\n}\n\ninterface JudgeRouter {\n baseUrl: string\n key: string\n model: string\n}\n\nfunction judgeRouter(): JudgeRouter {\n const key = process.env.TANGLE_API_KEY\n if (!key) throw new Error('TANGLE_API_KEY is required for the FinSearchComp per-record LLM judge')\n const model = process.env.JUDGE_MODEL ?? 'deepseek/deepseek-v4.1-flash'\n const baseUrl = process.env.ROUTER_BASE ?? 'https://router.tangle.tools/v1'\n return { baseUrl, key, model }\n}\n\n/**\n * The judge emits a JSON object with an `answer_score`. In this dataset it is a\n * flat integer ({\"answer_score\": 1}); we also accept the nested-array form\n * ([[1]] → read [0][0]) the upstream scorer can produce. 1/positive = resolved.\n * A \"null\" sentinel (judge could not obtain ground truth) is NOT a pass.\n */\nfunction readAnswerScore(value: unknown): { resolved: boolean; score: number; raw: unknown } {\n let v: unknown = value\n // unwrap nested-array form: [[s]] / [s]\n while (Array.isArray(v)) v = v[0]\n if (v === null || v === undefined || v === 'null') {\n return { resolved: false, score: 0, raw: value }\n }\n const n = typeof v === 'number' ? v : typeof v === 'string' ? Number(v) : NaN\n if (!Number.isFinite(n)) {\n throw new Error(`FinSearchComp judge answer_score not numeric: ${JSON.stringify(value)}`)\n }\n // Their scale: 1 = correct, 0 = wrong. Treat any positive as resolved; clamp to 0..1.\n const resolved = n >= 1\n const score = n <= 0 ? 0 : n >= 1 ? 1 : n\n return { resolved, score, raw: value }\n}\n\n/** Extract the first JSON object carrying `answer_score` from judge output; throw if none. */\nfunction parseJudgeOutput(content: string): { resolved: boolean; score: number; raw: unknown } {\n // Prefer a fenced block, then fall back to scanning for a {...} with answer_score.\n const candidates: string[] = []\n for (const m of content.matchAll(/```(?:json)?\\s*([\\s\\S]*?)```/g)) candidates.push(m[1].trim())\n for (const m of content.matchAll(/\\{[^{}]*\"answer_score\"[\\s\\S]*?\\}/g)) candidates.push(m[0])\n candidates.push(content.trim())\n for (const c of candidates) {\n let parsed: { answer_score?: unknown }\n try {\n parsed = JSON.parse(c) as { answer_score?: unknown }\n } catch {\n continue\n }\n if ('answer_score' in parsed) return readAnswerScore(parsed.answer_score)\n }\n throw new Error(\n `FinSearchComp judge produced no parseable {\"answer_score\": …}: ${content.slice(0, 400)}`,\n )\n}\n\n/** Run the record's own judge via the router. Fail loud on transport/parse errors. */\nasync function runRecordJudge(meta: FinSearchMeta, response: string, router: JudgeRouter): Promise<BenchScore> {\n const turn = await runBenchRouterTurn(\n {\n routerBaseUrl: router.baseUrl,\n routerKey: router.key,\n profile: {\n name: 'finsearchcomp-judge',\n harness: 'cli-base',\n model: {\n provider: 'tangle-router',\n default: router.model,\n metadata: { temperature: 0 },\n },\n prompt: { systemPrompt: meta.judgeSystemPrompt },\n },\n },\n fillJudgePrompt(meta, response),\n )\n const content = turn.finalText\n if (!content) throw new Error('FinSearchComp judge returned no message content')\n const { resolved, score, raw } = parseJudgeOutput(content)\n return {\n resolved,\n score,\n detail: JSON.stringify({\n taskType: meta.taskType,\n region: meta.region,\n answerScore: raw,\n judgeModel: router.model,\n }),\n }\n}\n\nfunction selectRecords(records: FinSearchRecord[], opts: LoadOptions): BenchTask[] {\n let tasks = records\n .filter((r) => SUPPORTED_TYPES.has(parseTaskType(r.prompt_id)))\n .map(recordToTask)\n if (opts.split) tasks = tasks.filter((t) => t.split === opts.split)\n if (opts.ids) {\n const want = new Set(opts.ids)\n tasks = tasks.filter((t) => want.has(t.id))\n } else if (opts.limit !== undefined) {\n tasks = balanceByType(tasks, opts.limit)\n }\n return tasks\n}\n\n/** Round-robin across task types (T2/T3) so a `limit` pulls a balanced mix\n * rather than slicing the type-ordered dataset's first N (which yields all\n * T2). Deterministic — preserves dataset order within each type. */\nfunction balanceByType(tasks: BenchTask[], limit: number): BenchTask[] {\n const queues = new Map<TaskType, BenchTask[]>()\n for (const t of tasks) {\n const k = parseTaskType(t.id)\n const q = queues.get(k)\n if (q) q.push(t)\n else queues.set(k, [t])\n }\n const lanes = [...queues.values()]\n const out: BenchTask[] = []\n for (let i = 0; out.length < limit; i++) {\n const before = out.length\n for (const lane of lanes) {\n if (i < lane.length) out.push(lane[i])\n if (out.length >= limit) break\n }\n if (out.length === before) break // all lanes exhausted\n }\n return out\n}\n\nasync function loadFixtures(opts: LoadOptions): Promise<BenchTask[]> {\n const records = JSON.parse(await readFile(FIXTURES, 'utf8')) as FinSearchRecord[]\n return selectRecords(records, opts)\n}\n\nasync function fetchDataset(): Promise<FinSearchRecord[]> {\n const res = await fetch(DATASET_URL)\n if (!res.ok) throw new Error(`FinSearchComp dataset HTTP ${res.status} fetching ${DATASET_URL}`)\n const data = (await res.json()) as FinSearchRecord[]\n if (!Array.isArray(data) || data.length === 0) {\n throw new Error(`FinSearchComp dataset empty or not an array: ${DATASET_URL}`)\n }\n return data\n}\n\nexport function createFinsearchcompAdapter(): BenchmarkAdapter {\n const fixturesMode = process.env.FINSEARCHCOMP_FIXTURES === '1'\n\n return {\n name: 'finsearchcomp',\n\n async preflight() {\n // The per-record LLM judge is the arbiter in both modes — its router\n // config must exist or no score can be produced.\n judgeRouter()\n console.warn(\n '[finsearchcomp] T1 (Time_Sensitive_Data_Fetching) is NOT scored: it needs a live ' +\n 'market snapshot / akshare ground truth for the judge {ground_truth} slot. ' +\n 'loadTasks supports T2 + T3 only; wire T1Seam to add T1.',\n )\n if (fixturesMode) {\n await readFile(FIXTURES, 'utf8').catch((err) => {\n throw new Error(\n `FINSEARCHCOMP_FIXTURES=1 but ${FIXTURES} unreadable: ${err instanceof Error ? err.message : err}`,\n )\n })\n return\n }\n const res = await fetch(DATASET_URL, { method: 'HEAD' }).catch((err) => {\n throw new Error(\n `finsearchcomp preflight failed reaching ${DATASET_URL}: ${err instanceof Error ? err.message : err}\\n` +\n `Fix: ensure network access to raw.githubusercontent.com, or set FINSEARCHCOMP_FIXTURES=1 ` +\n `to run against the committed fixtures offline.`,\n )\n })\n if (!res.ok) {\n throw new Error(\n `finsearchcomp preflight: dataset HEAD ${res.status} for ${DATASET_URL}. ` +\n `Set FINSEARCHCOMP_FIXTURES=1 to run against the committed fixtures offline.`,\n )\n }\n },\n\n async loadTasks(opts: LoadOptions = {}) {\n if (fixturesMode) return loadFixtures(opts)\n let records: FinSearchRecord[]\n try {\n records = await fetchDataset()\n } catch (err) {\n console.warn(\n `[finsearchcomp] live dataset fetch failed (${err instanceof Error ? err.message : err}); ` +\n `falling back to committed fixtures at ${FIXTURES}`,\n )\n return loadFixtures(opts)\n }\n return selectRecords(records, opts)\n },\n\n async goldArtifact(task: BenchTask) {\n // Gold artifact = the record's response_reference fed back as the student\n // answer, so verify-judge proves gold→resolved through the SAME per-record\n // judge the real artifact takes. The reference may carry tolerance/criteria\n // prose; the judge is built to read the value out of it.\n const meta = readMeta(task)\n return meta.responseReference\n },\n\n async judge(task: BenchTask, artifact: string): Promise<BenchScore> {\n const meta = readMeta(task)\n const response = artifact.trim()\n if (response.length === 0) {\n // Fail-closed — the benchmark's own judges score an empty answer 0.\n return {\n resolved: false,\n score: 0,\n detail: JSON.stringify({ taskType: meta.taskType, region: meta.region, reason: 'empty answer' }),\n }\n }\n return runRecordJudge(meta, response, judgeRouter())\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA,MAAM,aAAa,cAAc,IAAI,IAAI,SAAS,YAAY,GAAG,CAAC;AAClE,MAAM,WAAW,KAAK,YAAY,YAAY,oBAAoB;AAElE,MAAM,cACJ;;AAK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,IAAI,cAAc,OAAO,aAAa,IAAI;GAC1C,IAAI;GACJ,IAAI;IACF,UAAU,MAAM,aAAa;GAC/B,SAAS,KAAK;IACZ,QAAQ,KACN,8CAA8C,eAAe,QAAQ,IAAI,UAAU,IAAI,2CAC5C,UAC7C;IACA,OAAO,aAAa,IAAI;GAC1B;GACA,OAAO,cAAc,SAAS,IAAI;EACpC;EAEA,MAAM,aAAa,MAAiB;GAMlC,OADa,SAAS,IACZ,CAAC,CAAC;EACd;EAEA,MAAM,MAAM,MAAiB,UAAuC;GAClE,MAAM,OAAO,SAAS,IAAI;GAC1B,MAAM,WAAW,SAAS,KAAK;GAC/B,IAAI,SAAS,WAAW,GAEtB,OAAO;IACL,UAAU;IACV,OAAO;IACP,QAAQ,KAAK,UAAU;KAAE,UAAU,KAAK;KAAU,QAAQ,KAAK;KAAQ,QAAQ;IAAe,CAAC;GACjG;GAEF,OAAO,eAAe,MAAM,UAAU,YAAY,CAAC;EACrD;CACF;AACF"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { BenchmarkAdapter } from "./types.js";
|
|
2
|
-
import { McadTask } from "./mcad-tasks.js";
|
|
3
1
|
import { McadGeometry, McadScoring, Tri } from "./mcad-bench.js";
|
|
2
|
+
import { McadTask } from "./mcad-tasks.js";
|
|
3
|
+
import { BenchmarkAdapter } from "./types.js";
|
|
4
4
|
/** Package-relative venv, resolved through `_harness`'s bench-root lookup. */
|
|
5
5
|
export declare const CADQUERY_VENV = ".venv-cadquery";
|
|
6
6
|
/** Files the worker's script must leave in its working directory. */
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { venvPythonAt } from "./_harness.js";
|
|
2
|
-
import { MCAD_DELIVERABLE, MCAD_DELIVERABLE_MULTIBODY, MCAD_TASKS } from "./mcad-tasks.js";
|
|
3
2
|
import { measureMesh, parseAsciiStl, scoreAgainstSpec, stripCodeFence } from "./mcad-bench.js";
|
|
4
3
|
import { MCAD_CQ_GOLDS, MCAD_CQ_UNCALIBRATED } from "./mcad-cq-golds.js";
|
|
4
|
+
import { MCAD_DELIVERABLE, MCAD_DELIVERABLE_MULTIBODY, MCAD_TASKS } from "./mcad-tasks.js";
|
|
5
5
|
import { mkdtemp, open, readFile, writeFile } from "node:fs/promises";
|
|
6
6
|
import { isAbsolute, join } from "node:path";
|
|
7
7
|
import { execFile } from "node:child_process";
|
|
@@ -98,7 +98,7 @@ const GRADER_PROMPT = (question, gold, predicted) => [
|
|
|
98
98
|
function graderRouter() {
|
|
99
99
|
const key = process.env.TANGLE_API_KEY;
|
|
100
100
|
if (!key) throw new Error("TANGLE_API_KEY is required for the SimpleQA grader (set the Tangle API key)");
|
|
101
|
-
const model = process.env.JUDGE_MODEL ?? "deepseek-v4-flash";
|
|
101
|
+
const model = process.env.JUDGE_MODEL ?? "deepseek/deepseek-v4.1-flash";
|
|
102
102
|
return {
|
|
103
103
|
baseUrl: process.env.ROUTER_BASE ?? "https://router.tangle.tools/v1",
|
|
104
104
|
key,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"simpleqa.js","names":[],"sources":["../../src/benchmarks/simpleqa.ts"],"sourcesContent":["/**\n * SimpleQA adapter (OpenAI simple-evals; short-form factual QA). Worker artifact\n * = a single free-text final answer string (optionally preceded by a CITATIONS:\n * block). Each item ships a short gold `answer` plus metadata (topic,\n * answer_type, source urls).\n *\n * Judge is the official SimpleQA grader — an LLM classifier that maps\n * (question, gold target, predicted answer) to exactly one of:\n * A = CORRECT — fully contains the gold, no contradiction\n * B = INCORRECT — contradicts / contains a different factual value\n * C = NOT_ATTEMPTED — hedged, non-committal, or no value given\n * resolved = (grade == CORRECT). score = 1 for CORRECT else 0. The grade letter\n * (with its label) rides in `detail`; NOT_ATTEMPTED is surfaced distinctly from\n * INCORRECT so the scorecard can separate abstention from error.\n *\n * There is no deterministic tier: SimpleQA's rubric (containment + abstention)\n * is the grader's job by design, so judge() always calls the pinned grader model\n * (temperature 0) and fails loud on unparseable grader output. The final-answer\n * extraction IS deterministic (FINAL ANSWER: sentinel, fail-closed to '').\n *\n * Requires for a live run: the bench `.venv` with `datasets`/`requests` not\n * needed — the test set is a single public CSV fetched over HTTP — plus a\n * grader key (TANGLE_API_KEY). For offline/CI verification set\n * SIMPLEQA_FIXTURES=1 to load the committed fixtures\n * (bench/fixtures/simpleqa.json) — no network.\n */\n\nimport { execFile } from 'node:child_process'\nimport { readFile } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport { promisify } from 'node:util'\nimport { runBenchRouterTurn } from '../router-turn'\nimport { FINAL_ANSWER_SENTINEL, parseCitations, parseFinalAnswer } from './rag-shared'\nimport type { BenchmarkAdapter, BenchScore, BenchTask, LoadOptions } from './types'\n\nconst execFileAsync = promisify(execFile)\nconst BENCH_ROOT = fileURLToPath(new URL('../..', import.meta.url))\nconst PY = join(BENCH_ROOT, '.venv', 'bin', 'python')\nconst FIXTURES = join(BENCH_ROOT, 'fixtures', 'simpleqa.json')\n\nconst DATASET_URL =\n 'https://openaipublic.blob.core.windows.net/simple-evals/simple_qa_test_set.csv'\n\n/** Worker contract appended to every task prompt. Answer extraction keys off the sentinel. */\nconst WORKER_CONTRACT = [\n '',\n 'Research the question using live web sources and answer it with a short, specific factual value.',\n 'Cite the sources you used as full URLs, one per line, in a `CITATIONS:` block.',\n `End your response with a single final line: \\`${FINAL_ANSWER_SENTINEL} <answer>\\``,\n 'The answer after the sentinel must be the bare value only (no explanation on that line).',\n 'If you do not know the answer, state that you do not know rather than guessing.',\n].join('\\n')\n\n/**\n * Typed seam for the research worker. The benchmark adapter scores a plain\n * `string` artifact (the BenchmarkAdapter contract); the loop worker decodes its\n * agent runs into a {@link ResearchAnswer} and serializes `finalAnswer` (+ an\n * optional `CITATIONS:` block) into that string before judging.\n */\nexport interface SimpleQaTask {\n id: string\n question: string\n /** Gold short answer — the grader's target. */\n gold: string\n /** Source URLs cited by the dataset for this item — SOFT provenance signal, never a hard gate. */\n goldSources: string[]\n /** SimpleQA topic, e.g. 'Politics' — slices the scorecard by domain. */\n topic: string\n /** SimpleQA answer_type, e.g. 'Person' | 'Date' | 'Number' | 'Place'. */\n answerType: string\n}\n\n/** Normalized fixture/loader row — the single shape both the CSV loader and fixtures emit. */\ninterface SimpleQaRow {\n problem: string\n answer: string\n topic: string\n answer_type: string\n urls: string[]\n}\n\ninterface SimpleQaMeta {\n gold: string\n goldSources: string[]\n topic: string\n answerType: string\n question: string\n}\n\n/** The three official SimpleQA grades. */\ntype Grade = 'CORRECT' | 'INCORRECT' | 'NOT_ATTEMPTED'\n\n/** Run the bench venv python with a script; return stdout (throws on nonzero). */\nasync function py(script: string, args: string[] = []): Promise<string> {\n const { stdout } = await execFileAsync(PY, ['-c', script, ...args], {\n maxBuffer: 1024 * 1024 * 256,\n })\n return stdout\n}\n\n/**\n * The official SimpleQA grader prompt (faithful paraphrase of OpenAI's\n * simple-evals GRADER_TEMPLATE). Classifies the predicted answer against the\n * gold target into A=CORRECT / B=INCORRECT / C=NOT_ATTEMPTED. The predicted\n * answer must fully contain the gold value with no contradicting statement;\n * hedged or non-committal answers are NOT_ATTEMPTED.\n */\nconst GRADER_PROMPT = (question: string, gold: string, predicted: string): string =>\n [\n 'Your job is to grade a predicted answer to a factual question against the single gold target answer.',\n 'Grade the prediction into exactly one of three categories: CORRECT, INCORRECT, or NOT_ATTEMPTED.',\n 'First, follow these grading rules carefully.',\n '',\n 'CORRECT:',\n ' The predicted answer fully contains the gold target without contradicting it.',\n ' Predictions with more detail than the gold are still CORRECT, as long as no part contradicts the gold.',\n ' Hedging that still commits to the gold value (e.g. \"I think it is X\" where X is the gold) is CORRECT.',\n ' Minor formatting, capitalization, ordering, or obvious-typo differences do not matter.',\n ' For numeric/date targets, the prediction is CORRECT only if it matches the gold to the precision the gold specifies.',\n '',\n 'INCORRECT:',\n ' The predicted answer contradicts the gold target in any way, even if the contradiction is hedged.',\n ' A prediction that states a different factual value than the gold is INCORRECT.',\n '',\n 'NOT_ATTEMPTED:',\n ' The gold target is neither fully given nor contradicted: the prediction declines to answer, says it does not know,',\n ' asks for clarification, or gives a non-committal, vague, or empty response that commits to no specific value.',\n '',\n 'Also note the following rules:',\n ' Do not punish a prediction for omitting information that would not change whether the gold target is contained.',\n ' Grade ONLY whether the gold value is present and uncontradicted — not the overall quality of the response.',\n '',\n `Question: ${question}`,\n `Gold target: ${gold}`,\n `Predicted answer: ${predicted}`,\n '',\n 'Respond with ONLY a fenced JSON block and nothing else:',\n '```json',\n '{\"grade\": \"CORRECT\" | \"INCORRECT\" | \"NOT_ATTEMPTED\"}',\n '```',\n ].join('\\n')\n\ninterface GraderRouter {\n baseUrl: string\n key: string\n model: string\n}\n\nfunction graderRouter(): GraderRouter {\n const key = process.env.TANGLE_API_KEY\n if (!key) throw new Error('TANGLE_API_KEY is required for the SimpleQA grader (set the Tangle API key)')\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/** Call the official grader. Pinned model, temperature 0; fail loud on unparseable output. */\nasync function gradeAnswer(\n question: string,\n gold: string,\n predicted: string,\n router: GraderRouter,\n): Promise<Grade> {\n const turn = await runBenchRouterTurn(\n {\n routerBaseUrl: router.baseUrl,\n routerKey: router.key,\n profile: {\n name: 'simpleqa-grader',\n harness: 'cli-base',\n model: {\n provider: 'tangle-router',\n default: router.model,\n metadata: { temperature: 0 },\n },\n },\n },\n GRADER_PROMPT(question, gold, predicted),\n )\n const content = turn.finalText\n if (!content) throw new Error('SimpleQA grader returned no message content')\n const fenced = content.match(/```(?:json)?\\s*([\\s\\S]*?)```/)\n const raw = (fenced ? fenced[1] : content)?.trim() ?? ''\n let parsed: { grade?: unknown }\n try {\n parsed = JSON.parse(raw) as { grade?: unknown }\n } catch {\n throw new Error(`SimpleQA grader produced unparseable output (no JSON grade): ${content.slice(0, 300)}`)\n }\n if (parsed.grade === 'CORRECT' || parsed.grade === 'INCORRECT' || parsed.grade === 'NOT_ATTEMPTED') {\n return parsed.grade\n }\n throw new Error(\n `SimpleQA grader grade not in {CORRECT,INCORRECT,NOT_ATTEMPTED}: ${JSON.stringify(parsed).slice(0, 200)}`,\n )\n}\n\nfunction rowToTask(row: SimpleQaRow, index: number): BenchTask {\n const meta: SimpleQaMeta = {\n gold: row.answer,\n goldSources: row.urls,\n topic: row.topic,\n answerType: row.answer_type,\n question: row.problem,\n }\n return {\n id: `simpleqa-${index}`,\n split: 'test',\n prompt: row.problem + WORKER_CONTRACT,\n metadata: meta as unknown as Record<string, unknown>,\n }\n}\n\nfunction readMeta(task: BenchTask): SimpleQaMeta {\n const md = task.metadata\n if (!md || typeof md.gold !== 'string' || typeof md.question !== 'string') {\n throw new Error(`SimpleQA task ${task.id} missing metadata.gold/question — loadTasks did not populate it`)\n }\n return md as unknown as SimpleQaMeta\n}\n\nfunction selectTasks(tasks: BenchTask[], opts: LoadOptions): BenchTask[] {\n if (opts.ids) {\n const want = new Set(opts.ids)\n return tasks.filter((t) => want.has(t.id))\n }\n if (opts.limit !== undefined) return tasks.slice(0, opts.limit)\n return tasks\n}\n\nasync function loadFixtures(opts: LoadOptions): Promise<BenchTask[]> {\n const rows = JSON.parse(await readFile(FIXTURES, 'utf8')) as SimpleQaRow[]\n console.warn(`[simpleqa] SIMPLEQA_FIXTURES=1 — loading ${rows.length} committed fixtures (no network)`)\n return selectTasks(rows.map(rowToTask), opts)\n}\n\n/**\n * Load the live test set: fetch the public CSV via the bench venv python, parse\n * with `csv` (handles quoted/embedded-comma fields) and `ast.literal_eval` for\n * the python-repr `metadata` dict. Emits the same normalized SimpleQaRow shape\n * the fixtures use, so loadTasks/judge share one parse path.\n */\nasync function loadLive(opts: LoadOptions): Promise<BenchTask[]> {\n const script = `\nimport csv, ast, json, io, sys\nfrom urllib.request import urlopen\nwith urlopen(${JSON.stringify(DATASET_URL)}, timeout=120) as resp:\n text = resp.read().decode('utf-8')\nrows = list(csv.DictReader(io.StringIO(text)))\nout = []\nfor r in rows:\n meta = ast.literal_eval(r['metadata']) if r.get('metadata') else {}\n out.append({\n 'problem': r.get('problem', ''),\n 'answer': r.get('answer', ''),\n 'topic': str(meta.get('topic', '')),\n 'answer_type': str(meta.get('answer_type', '')),\n 'urls': list(meta.get('urls', [])),\n })\nprint(json.dumps(out))\n`\n const stdout = await py(script)\n const rows = JSON.parse(stdout) as SimpleQaRow[]\n return selectTasks(rows.map(rowToTask), opts)\n}\n\nexport function createSimpleQaAdapter(): BenchmarkAdapter {\n const fixturesMode = process.env.SIMPLEQA_FIXTURES === '1'\n\n return {\n name: 'simpleqa',\n\n async preflight() {\n // The grader router must be configured in both modes — SimpleQA's score is\n // defined by the grader, so a run without it is meaningless.\n graderRouter()\n if (fixturesMode) {\n await readFile(FIXTURES, 'utf8').catch((err) => {\n throw new Error(\n `SIMPLEQA_FIXTURES=1 but ${FIXTURES} unreadable: ${err instanceof Error ? err.message : err}`,\n )\n })\n return\n }\n try {\n await py(\n `from urllib.request import urlopen\nwith urlopen(${JSON.stringify(DATASET_URL)}, timeout=120) as resp:\n head = resp.read(64).decode('utf-8', 'replace')\nassert head.startswith('metadata,problem,answer'), 'unexpected CSV header: ' + head[:40]\nprint('ok')`,\n )\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err)\n throw new Error(\n `simpleqa preflight failed: ${msg}\\n` +\n `Fix: (1) ensure the bench venv exists (python3 -m venv bench/.venv) ; ` +\n `(2) ensure network access to ${DATASET_URL} ; ` +\n `or set SIMPLEQA_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 return loadLive(opts)\n },\n\n async goldArtifact(task: BenchTask) {\n // Gold artifact = the worker-contract serialization of the gold answer, so\n // verify-judge proves gold→CORRECT through the SAME parse path the real\n // artifact takes.\n const meta = readMeta(task)\n return `${FINAL_ANSWER_SENTINEL} ${meta.gold}`\n },\n\n async judge(task: BenchTask, artifact: string): Promise<BenchScore> {\n const meta = readMeta(task)\n const finalAnswer = parseFinalAnswer(artifact)\n const citations = parseCitations(artifact)\n\n if (finalAnswer.length === 0) {\n // No parseable value committed — NOT_ATTEMPTED by construction, no grader call.\n return {\n resolved: false,\n score: 0,\n detail: JSON.stringify({\n grade: 'NOT_ATTEMPTED',\n gradeLetter: 'C',\n reason: 'no parseable answer',\n gold: meta.gold,\n topic: meta.topic,\n answerType: meta.answerType,\n citationCount: citations.length,\n }),\n }\n }\n\n const grade = await gradeAnswer(meta.question, meta.gold, finalAnswer, graderRouter())\n const gradeLetter = grade === 'CORRECT' ? 'A' : grade === 'INCORRECT' ? 'B' : 'C'\n const resolved = grade === 'CORRECT'\n return {\n resolved,\n score: resolved ? 1 : 0,\n detail: JSON.stringify({\n grade,\n gradeLetter,\n gold: meta.gold,\n predicted: finalAnswer,\n topic: meta.topic,\n answerType: meta.answerType,\n citationCount: citations.length,\n }),\n }\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA,MAAM,gBAAgB,UAAU,QAAQ;AACxC,MAAM,aAAa,cAAc,IAAI,IAAI,SAAS,YAAY,GAAG,CAAC;AAClE,MAAM,KAAK,KAAK,YAAY,SAAS,OAAO,QAAQ;AACpD,MAAM,WAAW,KAAK,YAAY,YAAY,eAAe;AAE7D,MAAM,cACJ;;AAGF,MAAM,kBAAkB;CACtB;CACA;CACA;CACA,iDAAiD,sBAAsB;CACvE;CACA;AACF,CAAC,CAAC,KAAK,IAAI;;AA0CX,eAAe,GAAG,QAAgB,OAAiB,CAAC,GAAoB;CACtE,MAAM,EAAE,WAAW,MAAM,cAAc,IAAI;EAAC;EAAM;EAAQ,GAAG;CAAI,GAAG,EAClE,WAAW,UACb,CAAC;CACD,OAAO;AACT;;;;;;;;AASA,MAAM,iBAAiB,UAAkB,MAAc,cACrD;CACE;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;C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eACK,KAAK,UAAU,WAAW,EAAE;;;YAInC;GACF,SAAS,KAAK;IACZ,MAAM,MAAM,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;IAC3D,MAAM,IAAI,MACR,8BAA8B,IAAI,uGAEA,YAAY,6EAEhD;GACF;EACF;EAEA,MAAM,UAAU,OAAoB,CAAC,GAAG;GACtC,IAAI,cAAc,OAAO,aAAa,IAAI;GAC1C,OAAO,SAAS,IAAI;EACtB;EAEA,MAAM,aAAa,MAAiB;GAIlC,MAAM,OAAO,SAAS,IAAI;GAC1B,OAAO,GAAG,sBAAsB,GAAG,KAAK;EAC1C;EAEA,MAAM,MAAM,MAAiB,UAAuC;GAClE,MAAM,OAAO,SAAS,IAAI;GAC1B,MAAM,cAAc,iBAAiB,QAAQ;GAC7C,MAAM,YAAY,eAAe,QAAQ;GAEzC,IAAI,YAAY,WAAW,GAEzB,OAAO;IACL,UAAU;IACV,OAAO;IACP,QAAQ,KAAK,UAAU;KACrB,OAAO;KACP,aAAa;KACb,QAAQ;KACR,MAAM,KAAK;KACX,OAAO,KAAK;KACZ,YAAY,KAAK;KACjB,eAAe,UAAU;IAC3B,CAAC;GACH;GAGF,MAAM,QAAQ,MAAM,YAAY,KAAK,UAAU,KAAK,MAAM,aAAa,aAAa,CAAC;GACrF,MAAM,cAAc,UAAU,YAAY,MAAM,UAAU,cAAc,MAAM;GAC9E,MAAM,WAAW,UAAU;GAC3B,OAAO;IACL;IACA,OAAO,WAAW,IAAI;IACtB,QAAQ,KAAK,UAAU;KACrB;KACA;KACA,MAAM,KAAK;KACX,WAAW;KACX,OAAO,KAAK;KACZ,YAAY,KAAK;KACjB,eAAe,UAAU;IAC3B,CAAC;GACH;EACF;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"simpleqa.js","names":[],"sources":["../../src/benchmarks/simpleqa.ts"],"sourcesContent":["/**\n * SimpleQA adapter (OpenAI simple-evals; short-form factual QA). Worker artifact\n * = a single free-text final answer string (optionally preceded by a CITATIONS:\n * block). Each item ships a short gold `answer` plus metadata (topic,\n * answer_type, source urls).\n *\n * Judge is the official SimpleQA grader — an LLM classifier that maps\n * (question, gold target, predicted answer) to exactly one of:\n * A = CORRECT — fully contains the gold, no contradiction\n * B = INCORRECT — contradicts / contains a different factual value\n * C = NOT_ATTEMPTED — hedged, non-committal, or no value given\n * resolved = (grade == CORRECT). score = 1 for CORRECT else 0. The grade letter\n * (with its label) rides in `detail`; NOT_ATTEMPTED is surfaced distinctly from\n * INCORRECT so the scorecard can separate abstention from error.\n *\n * There is no deterministic tier: SimpleQA's rubric (containment + abstention)\n * is the grader's job by design, so judge() always calls the pinned grader model\n * (temperature 0) and fails loud on unparseable grader output. The final-answer\n * extraction IS deterministic (FINAL ANSWER: sentinel, fail-closed to '').\n *\n * Requires for a live run: the bench `.venv` with `datasets`/`requests` not\n * needed — the test set is a single public CSV fetched over HTTP — plus a\n * grader key (TANGLE_API_KEY). For offline/CI verification set\n * SIMPLEQA_FIXTURES=1 to load the committed fixtures\n * (bench/fixtures/simpleqa.json) — no network.\n */\n\nimport { execFile } from 'node:child_process'\nimport { readFile } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport { promisify } from 'node:util'\nimport { runBenchRouterTurn } from '../router-turn'\nimport { FINAL_ANSWER_SENTINEL, parseCitations, parseFinalAnswer } from './rag-shared'\nimport type { BenchmarkAdapter, BenchScore, BenchTask, LoadOptions } from './types'\n\nconst execFileAsync = promisify(execFile)\nconst BENCH_ROOT = fileURLToPath(new URL('../..', import.meta.url))\nconst PY = join(BENCH_ROOT, '.venv', 'bin', 'python')\nconst FIXTURES = join(BENCH_ROOT, 'fixtures', 'simpleqa.json')\n\nconst DATASET_URL =\n 'https://openaipublic.blob.core.windows.net/simple-evals/simple_qa_test_set.csv'\n\n/** Worker contract appended to every task prompt. Answer extraction keys off the sentinel. */\nconst WORKER_CONTRACT = [\n '',\n 'Research the question using live web sources and answer it with a short, specific factual value.',\n 'Cite the sources you used as full URLs, one per line, in a `CITATIONS:` block.',\n `End your response with a single final line: \\`${FINAL_ANSWER_SENTINEL} <answer>\\``,\n 'The answer after the sentinel must be the bare value only (no explanation on that line).',\n 'If you do not know the answer, state that you do not know rather than guessing.',\n].join('\\n')\n\n/**\n * Typed seam for the research worker. The benchmark adapter scores a plain\n * `string` artifact (the BenchmarkAdapter contract); the loop worker decodes its\n * agent runs into a {@link ResearchAnswer} and serializes `finalAnswer` (+ an\n * optional `CITATIONS:` block) into that string before judging.\n */\nexport interface SimpleQaTask {\n id: string\n question: string\n /** Gold short answer — the grader's target. */\n gold: string\n /** Source URLs cited by the dataset for this item — SOFT provenance signal, never a hard gate. */\n goldSources: string[]\n /** SimpleQA topic, e.g. 'Politics' — slices the scorecard by domain. */\n topic: string\n /** SimpleQA answer_type, e.g. 'Person' | 'Date' | 'Number' | 'Place'. */\n answerType: string\n}\n\n/** Normalized fixture/loader row — the single shape both the CSV loader and fixtures emit. */\ninterface SimpleQaRow {\n problem: string\n answer: string\n topic: string\n answer_type: string\n urls: string[]\n}\n\ninterface SimpleQaMeta {\n gold: string\n goldSources: string[]\n topic: string\n answerType: string\n question: string\n}\n\n/** The three official SimpleQA grades. */\ntype Grade = 'CORRECT' | 'INCORRECT' | 'NOT_ATTEMPTED'\n\n/** Run the bench venv python with a script; return stdout (throws on nonzero). */\nasync function py(script: string, args: string[] = []): Promise<string> {\n const { stdout } = await execFileAsync(PY, ['-c', script, ...args], {\n maxBuffer: 1024 * 1024 * 256,\n })\n return stdout\n}\n\n/**\n * The official SimpleQA grader prompt (faithful paraphrase of OpenAI's\n * simple-evals GRADER_TEMPLATE). Classifies the predicted answer against the\n * gold target into A=CORRECT / B=INCORRECT / C=NOT_ATTEMPTED. The predicted\n * answer must fully contain the gold value with no contradicting statement;\n * hedged or non-committal answers are NOT_ATTEMPTED.\n */\nconst GRADER_PROMPT = (question: string, gold: string, predicted: string): string =>\n [\n 'Your job is to grade a predicted answer to a factual question against the single gold target answer.',\n 'Grade the prediction into exactly one of three categories: CORRECT, INCORRECT, or NOT_ATTEMPTED.',\n 'First, follow these grading rules carefully.',\n '',\n 'CORRECT:',\n ' The predicted answer fully contains the gold target without contradicting it.',\n ' Predictions with more detail than the gold are still CORRECT, as long as no part contradicts the gold.',\n ' Hedging that still commits to the gold value (e.g. \"I think it is X\" where X is the gold) is CORRECT.',\n ' Minor formatting, capitalization, ordering, or obvious-typo differences do not matter.',\n ' For numeric/date targets, the prediction is CORRECT only if it matches the gold to the precision the gold specifies.',\n '',\n 'INCORRECT:',\n ' The predicted answer contradicts the gold target in any way, even if the contradiction is hedged.',\n ' A prediction that states a different factual value than the gold is INCORRECT.',\n '',\n 'NOT_ATTEMPTED:',\n ' The gold target is neither fully given nor contradicted: the prediction declines to answer, says it does not know,',\n ' asks for clarification, or gives a non-committal, vague, or empty response that commits to no specific value.',\n '',\n 'Also note the following rules:',\n ' Do not punish a prediction for omitting information that would not change whether the gold target is contained.',\n ' Grade ONLY whether the gold value is present and uncontradicted — not the overall quality of the response.',\n '',\n `Question: ${question}`,\n `Gold target: ${gold}`,\n `Predicted answer: ${predicted}`,\n '',\n 'Respond with ONLY a fenced JSON block and nothing else:',\n '```json',\n '{\"grade\": \"CORRECT\" | \"INCORRECT\" | \"NOT_ATTEMPTED\"}',\n '```',\n ].join('\\n')\n\ninterface GraderRouter {\n baseUrl: string\n key: string\n model: string\n}\n\nfunction graderRouter(): GraderRouter {\n const key = process.env.TANGLE_API_KEY\n if (!key) throw new Error('TANGLE_API_KEY is required for the SimpleQA grader (set the Tangle API key)')\n const model = process.env.JUDGE_MODEL ?? 'deepseek/deepseek-v4.1-flash'\n const baseUrl = process.env.ROUTER_BASE ?? 'https://router.tangle.tools/v1'\n return { baseUrl, key, model }\n}\n\n/** Call the official grader. Pinned model, temperature 0; fail loud on unparseable output. */\nasync function gradeAnswer(\n question: string,\n gold: string,\n predicted: string,\n router: GraderRouter,\n): Promise<Grade> {\n const turn = await runBenchRouterTurn(\n {\n routerBaseUrl: router.baseUrl,\n routerKey: router.key,\n profile: {\n name: 'simpleqa-grader',\n harness: 'cli-base',\n model: {\n provider: 'tangle-router',\n default: router.model,\n metadata: { temperature: 0 },\n },\n },\n },\n GRADER_PROMPT(question, gold, predicted),\n )\n const content = turn.finalText\n if (!content) throw new Error('SimpleQA grader returned no message content')\n const fenced = content.match(/```(?:json)?\\s*([\\s\\S]*?)```/)\n const raw = (fenced ? fenced[1] : content)?.trim() ?? ''\n let parsed: { grade?: unknown }\n try {\n parsed = JSON.parse(raw) as { grade?: unknown }\n } catch {\n throw new Error(`SimpleQA grader produced unparseable output (no JSON grade): ${content.slice(0, 300)}`)\n }\n if (parsed.grade === 'CORRECT' || parsed.grade === 'INCORRECT' || parsed.grade === 'NOT_ATTEMPTED') {\n return parsed.grade\n }\n throw new Error(\n `SimpleQA grader grade not in {CORRECT,INCORRECT,NOT_ATTEMPTED}: ${JSON.stringify(parsed).slice(0, 200)}`,\n )\n}\n\nfunction rowToTask(row: SimpleQaRow, index: number): BenchTask {\n const meta: SimpleQaMeta = {\n gold: row.answer,\n goldSources: row.urls,\n topic: row.topic,\n answerType: row.answer_type,\n question: row.problem,\n }\n return {\n id: `simpleqa-${index}`,\n split: 'test',\n prompt: row.problem + WORKER_CONTRACT,\n metadata: meta as unknown as Record<string, unknown>,\n }\n}\n\nfunction readMeta(task: BenchTask): SimpleQaMeta {\n const md = task.metadata\n if (!md || typeof md.gold !== 'string' || typeof md.question !== 'string') {\n throw new Error(`SimpleQA task ${task.id} missing metadata.gold/question — loadTasks did not populate it`)\n }\n return md as unknown as SimpleQaMeta\n}\n\nfunction selectTasks(tasks: BenchTask[], opts: LoadOptions): BenchTask[] {\n if (opts.ids) {\n const want = new Set(opts.ids)\n return tasks.filter((t) => want.has(t.id))\n }\n if (opts.limit !== undefined) return tasks.slice(0, opts.limit)\n return tasks\n}\n\nasync function loadFixtures(opts: LoadOptions): Promise<BenchTask[]> {\n const rows = JSON.parse(await readFile(FIXTURES, 'utf8')) as SimpleQaRow[]\n console.warn(`[simpleqa] SIMPLEQA_FIXTURES=1 — loading ${rows.length} committed fixtures (no network)`)\n return selectTasks(rows.map(rowToTask), opts)\n}\n\n/**\n * Load the live test set: fetch the public CSV via the bench venv python, parse\n * with `csv` (handles quoted/embedded-comma fields) and `ast.literal_eval` for\n * the python-repr `metadata` dict. Emits the same normalized SimpleQaRow shape\n * the fixtures use, so loadTasks/judge share one parse path.\n */\nasync function loadLive(opts: LoadOptions): Promise<BenchTask[]> {\n const script = `\nimport csv, ast, json, io, sys\nfrom urllib.request import urlopen\nwith urlopen(${JSON.stringify(DATASET_URL)}, timeout=120) as resp:\n text = resp.read().decode('utf-8')\nrows = list(csv.DictReader(io.StringIO(text)))\nout = []\nfor r in rows:\n meta = ast.literal_eval(r['metadata']) if r.get('metadata') else {}\n out.append({\n 'problem': r.get('problem', ''),\n 'answer': r.get('answer', ''),\n 'topic': str(meta.get('topic', '')),\n 'answer_type': str(meta.get('answer_type', '')),\n 'urls': list(meta.get('urls', [])),\n })\nprint(json.dumps(out))\n`\n const stdout = await py(script)\n const rows = JSON.parse(stdout) as SimpleQaRow[]\n return selectTasks(rows.map(rowToTask), opts)\n}\n\nexport function createSimpleQaAdapter(): BenchmarkAdapter {\n const fixturesMode = process.env.SIMPLEQA_FIXTURES === '1'\n\n return {\n name: 'simpleqa',\n\n async preflight() {\n // The grader router must be configured in both modes — SimpleQA's score is\n // defined by the grader, so a run without it is meaningless.\n graderRouter()\n if (fixturesMode) {\n await readFile(FIXTURES, 'utf8').catch((err) => {\n throw new Error(\n `SIMPLEQA_FIXTURES=1 but ${FIXTURES} unreadable: ${err instanceof Error ? err.message : err}`,\n )\n })\n return\n }\n try {\n await py(\n `from urllib.request import urlopen\nwith urlopen(${JSON.stringify(DATASET_URL)}, timeout=120) as resp:\n head = resp.read(64).decode('utf-8', 'replace')\nassert head.startswith('metadata,problem,answer'), 'unexpected CSV header: ' + head[:40]\nprint('ok')`,\n )\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err)\n throw new Error(\n `simpleqa preflight failed: ${msg}\\n` +\n `Fix: (1) ensure the bench venv exists (python3 -m venv bench/.venv) ; ` +\n `(2) ensure network access to ${DATASET_URL} ; ` +\n `or set SIMPLEQA_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 return loadLive(opts)\n },\n\n async goldArtifact(task: BenchTask) {\n // Gold artifact = the worker-contract serialization of the gold answer, so\n // verify-judge proves gold→CORRECT through the SAME parse path the real\n // artifact takes.\n const meta = readMeta(task)\n return `${FINAL_ANSWER_SENTINEL} ${meta.gold}`\n },\n\n async judge(task: BenchTask, artifact: string): Promise<BenchScore> {\n const meta = readMeta(task)\n const finalAnswer = parseFinalAnswer(artifact)\n const citations = parseCitations(artifact)\n\n if (finalAnswer.length === 0) {\n // No parseable value committed — NOT_ATTEMPTED by construction, no grader call.\n return {\n resolved: false,\n score: 0,\n detail: JSON.stringify({\n grade: 'NOT_ATTEMPTED',\n gradeLetter: 'C',\n reason: 'no parseable answer',\n gold: meta.gold,\n topic: meta.topic,\n answerType: meta.answerType,\n citationCount: citations.length,\n }),\n }\n }\n\n const grade = await gradeAnswer(meta.question, meta.gold, finalAnswer, graderRouter())\n const gradeLetter = grade === 'CORRECT' ? 'A' : grade === 'INCORRECT' ? 'B' : 'C'\n const resolved = grade === 'CORRECT'\n return {\n resolved,\n score: resolved ? 1 : 0,\n detail: JSON.stringify({\n grade,\n gradeLetter,\n gold: meta.gold,\n predicted: finalAnswer,\n topic: meta.topic,\n answerType: meta.answerType,\n citationCount: citations.length,\n }),\n }\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA,MAAM,gBAAgB,UAAU,QAAQ;AACxC,MAAM,aAAa,cAAc,IAAI,IAAI,SAAS,YAAY,GAAG,CAAC;AAClE,MAAM,KAAK,KAAK,YAAY,SAAS,O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Aa,CAAC;GACrF,MAAM,cAAc,UAAU,YAAY,MAAM,UAAU,cAAc,MAAM;GAC9E,MAAM,WAAW,UAAU;GAC3B,OAAO;IACL;IACA,OAAO,WAAW,IAAI;IACtB,QAAQ,KAAK,UAAU;KACrB;KACA;KACA,MAAM,KAAK;KACX,WAAW;KACX,OAAO,KAAK;KACZ,YAAY,KAAK;KACjB,eAAe,UAAU;IAC3B,CAAC;GACH;EACF;CACF;AACF"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { BenchScore, BenchmarkAdapter } from "./types.js";
|
|
2
1
|
import { StagedRunCaptureSpec } from "./_harness.js";
|
|
2
|
+
import { BenchScore, BenchmarkAdapter } from "./types.js";
|
|
3
3
|
import { OutputAdapter } from "@tangle-network/agent-runtime/kernel";
|
|
4
4
|
/**
|
|
5
5
|
* The SWE deliverable's FALLBACK parser, from the agent's event STREAM.
|
|
@@ -36,7 +36,7 @@ const WORKER_SUFFIX = [
|
|
|
36
36
|
"Write your complete analysis to the text block that starts with \"ANALYSIS:\" on a line by itself.",
|
|
37
37
|
"Take a clear position on the topic. Every factual claim must name the file it comes from."
|
|
38
38
|
].join("\n");
|
|
39
|
-
const JUDGE_MODEL = "gemini-
|
|
39
|
+
const JUDGE_MODEL = "gemini-3.1-pro-preview";
|
|
40
40
|
function readText(p, maxBytes = MAX_FILE_BYTES) {
|
|
41
41
|
try {
|
|
42
42
|
const buf = readFileSync(p);
|
|
@@ -155,10 +155,8 @@ async function callJudge(router, prompt, maxAttempts = 2) {
|
|
|
155
155
|
model: {
|
|
156
156
|
provider: "tangle-router",
|
|
157
157
|
default: router.model,
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
maxTokens: Number(process.env.JUDGE_MAX_TOKENS ?? 16384)
|
|
161
|
-
}
|
|
158
|
+
maxVisibleOutputTokens: Number(process.env.JUDGE_MAX_TOKENS ?? 16384),
|
|
159
|
+
metadata: { temperature: 0 }
|
|
162
160
|
}
|
|
163
161
|
}
|
|
164
162
|
}, prompt)).finalText;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"trata-hedge.js","names":[],"sources":["../../src/benchmarks/trata-hedge.ts"],"sourcesContent":["/**\n * Trata Hedge-Bench adapter (Trata-Inc/trata-hedge-bench). 102 financial\n * analysis tasks across 6 domains (private equity, managed care, industrials,\n * vertical SaaS, REITs, insurance). Each task bundles real earnings-call\n * transcripts, financial statements, press releases, and SEC filings under\n * `environment/data/`; the agent must produce a grounded analysis citing those\n * files.\n *\n * Harbor architecture: the original benchmark runs each task in a Docker\n * container with file-read tools. This adapter skips Harbor and embeds the data\n * files directly in the worker prompt so any router backend can score it. Large\n * files (> 30 KB) are truncated to fit within model context limits. The judge\n * reads the actual files from disk for citation verification.\n *\n * Judge: a 3-stage LLM cascade faithful to grade.py —\n * Task 1: hallucination check (cited-file context + agent answer)\n * Task 2: per-move coverage check (ground truth + agent answer + flagged claims)\n * Task 3: synthesis check (ground truth + agent answer)\n * Score 0–4: themes_covered == num_themes && synthesis → 4, all themes → 3,\n * ≥2 themes → 2, ≥1 theme → 1, else → 0. Normalized to 0..1 for BenchScore;\n * resolved = score 4 (sparse reward).\n *\n * Requires TANGLE_API_KEY and TRATA_BENCH_ROOT=/tmp/trata-hedge-bench.\n * Clone: git clone --depth 1 https://github.com/Trata-Inc/trata-hedge-bench /tmp/trata-hedge-bench\n */\n\nimport { readdirSync, readFileSync, statSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { runBenchRouterTurn } from '../router-turn'\nimport type { BenchmarkAdapter, BenchScore, BenchTask, LoadOptions } from './types'\n\nconst DEFAULT_BENCH_ROOT = '/tmp/trata-hedge-bench'\nconst MAX_FILE_BYTES = 8_000\n// Sandbox API rejects messages > 100K chars; instruction + suffix adds ~500 chars overhead.\nconst MAX_DATA_CHARS = 85_000\nconst WORKER_SUFFIX = [\n '',\n 'The data files above are your only source. Cite each claim with the filename that supports it.',\n 'Write your complete analysis to the text block that starts with \"ANALYSIS:\" on a line by itself.',\n 'Take a clear position on the topic. Every factual claim must name the file it comes from.',\n].join('\\n')\n\n// Judge model: Gemini 2.5 Pro via router (matches gemini-3.1-pro-preview tier used by grade.py).\nconst JUDGE_MODEL = 'gemini-2.5-pro'\n\ninterface TrataTaskMeta {\n taskDir: string\n taskId: string\n dataDir: string\n groundTruth: string\n gradingTask1: string\n gradingTask2: string\n gradingTask3: string\n /** [(label, n_moves)] in rubric order. */\n themeMoveCounts: Array<{ label: string; nMoves: number }>\n}\n\n// ── file reading helpers ──────────────────────────────────────────────────────\n\nfunction readText(p: string, maxBytes = MAX_FILE_BYTES): string {\n try {\n const buf = readFileSync(p)\n if (buf.length <= maxBytes) return buf.toString('utf8')\n return buf.subarray(0, maxBytes).toString('utf8') + `\\n[… truncated at ${maxBytes} bytes …]`\n } catch {\n return `[unreadable: ${p}]`\n }\n}\n\nfunction listFilesRec(dir: string): string[] {\n const out: string[] = []\n try {\n for (const name of readdirSync(dir)) {\n const full = join(dir, name)\n try {\n if (statSync(full).isDirectory()) out.push(...listFilesRec(full))\n else out.push(full)\n } catch {\n // skip unreadable entries\n }\n }\n } catch {\n // dir absent\n }\n return out.sort()\n}\n\nfunction buildDataBlock(dataDir: string): string {\n const files = listFilesRec(dataDir)\n if (files.length === 0) return '(no data files found)'\n // Prioritise: company profiles → earnings calls → primary-ticker financials →\n // sec filings → press releases → peers. Stop once total chars hit MAX_DATA_CHARS.\n const priority = (f: string) => {\n if (f.includes('company_profiles')) return 0\n if (f.includes('earnings_call')) return 1\n if (/financials\\/(income|cash_flow|balance)/.test(f) && !/bam_|bx_|kkr_|ares_|cg_|owl_|fsk_|cat_|de_|tdg_|car_/.test(f)) return 2\n if (f.includes('sec_filings')) return 3\n if (f.includes('investor_pres')) return 4\n if (f.includes('press_release')) return 5\n return 6\n }\n const sorted = [...files].sort((a, b) => priority(a) - priority(b) || a.localeCompare(b))\n const blocks: string[] = []\n let total = 0\n for (const f of sorted) {\n const rel = f.slice(dataDir.length + 1)\n const content = readText(f)\n const chunk = `\\n=== FILE: data/${rel} ===\\n${content}`\n if (total + chunk.length > MAX_DATA_CHARS) {\n blocks.push(`\\n[… ${sorted.length - blocks.length} more files omitted to stay within context limit …]`)\n break\n }\n blocks.push(chunk)\n total += chunk.length\n }\n return blocks.join('')\n}\n\nfunction buildCitedDataBlock(answerText: string, dataDir: string): string {\n const files = listFilesRec(dataDir)\n const cited: string[] = []\n for (const f of files) {\n const rel = f.slice(dataDir.length + 1)\n const name = rel.split('/').pop() ?? ''\n if (answerText.includes(rel) || answerText.includes(name)) cited.push(f)\n }\n if (cited.length === 0) {\n return '(The agent did not cite any data files, or no cited file could be located.)'\n }\n const blocks: string[] = []\n for (const f of cited) {\n const rel = f.slice(dataDir.length + 1)\n blocks.push(`\\n=== FILE: data/${rel} ===\\n${readText(f)}`)\n }\n return blocks.join('')\n}\n\n// ── ground-truth parser ───────────────────────────────────────────────────────\n\nfunction parseThemeMoveCounts(groundTruth: string): Array<{ label: string; nMoves: number }> {\n const lines = groundTruth.split('\\n')\n const themeStarts = lines.reduce<number[]>((acc, l, i) => {\n if (/^\\d+\\./.test(l.trim())) acc.push(i)\n return acc\n }, [])\n return themeStarts.map((start, k) => {\n const end = k + 1 < themeStarts.length ? themeStarts[k + 1] : lines.length\n const block = lines.slice(start, end).join('\\n')\n const label = lines[start].replace(/^\\d+\\.\\s*/, '').trim()\n const nMoves = (block.match(/^\\s*\\[[a-z]\\]\\s+/gm) ?? []).length\n return { label, nMoves }\n })\n}\n\nfunction coverageThreshold(nMoves: number): number {\n return Math.max(1, Math.min(nMoves - 1, 3))\n}\n\n// ── router judge calls ────────────────────────────────────────────────────────\n\ninterface JudgeRouter {\n baseUrl: string\n key: string\n model: string\n}\n\nfunction judgeRouter(): JudgeRouter {\n const key = process.env.TANGLE_API_KEY\n if (!key) throw new Error('TANGLE_API_KEY is required for the Trata hedge-bench judge')\n const model = process.env.JUDGE_MODEL ?? JUDGE_MODEL\n const baseUrl = process.env.ROUTER_BASE ?? 'https://router.tangle.tools/v1'\n return { baseUrl, key, model }\n}\n\nfunction parseJsonFallback(raw: string): unknown {\n let s = raw.trim()\n if (s.startsWith('```')) s = s.split('\\n').slice(1).join('\\n')\n if (s.endsWith('```')) s = s.slice(0, s.lastIndexOf('```'))\n s = s.replace(/,(\\s*[}\\]])/g, '$1').trim()\n try {\n return JSON.parse(s)\n } catch {\n try {\n const m = s.match(/\\{[\\s\\S]*\\}/)\n if (m) return JSON.parse(m[0])\n } catch {\n // fallthrough\n }\n }\n return null\n}\n\nasync function callJudge(router: JudgeRouter, prompt: string, maxAttempts = 2): Promise<unknown> {\n for (let i = 0; i < maxAttempts; i++) {\n try {\n const turn = await runBenchRouterTurn(\n {\n routerBaseUrl: router.baseUrl,\n routerKey: router.key,\n profile: {\n name: 'trata-hedge-judge',\n harness: 'cli-base',\n model: {\n provider: 'tangle-router',\n default: router.model,\n metadata: {\n temperature: 0,\n maxTokens: Number(process.env.JUDGE_MAX_TOKENS ?? 16384),\n },\n },\n },\n },\n prompt,\n )\n const content = turn.finalText\n const parsed = parseJsonFallback(content)\n if (parsed !== null) return parsed\n } catch (error) {\n if (i + 1 === maxAttempts) throw error\n }\n }\n return null\n}\n\ninterface Task1Result {\n hallucinations_detected?: boolean | string\n unverifiable_claims?: Array<{ claim: string; cited_file?: string; issue?: string; evidence_check?: string }>\n}\n\ninterface Task2ThemeResult {\n label?: string\n moves_hit?: string[]\n moves_missed?: string[]\n moves_tainted?: string[]\n move_reasoning?: Record<string, string>\n}\n\ninterface Task2Result {\n themes?: Task2ThemeResult[]\n}\n\ninterface Task3Result {\n synthesis_found?: string | null\n}\n\nasync function task1HallucinationCheck(\n meta: TrataTaskMeta,\n answer: string,\n router: JudgeRouter,\n): Promise<Task1Result> {\n const citedBlock = buildCitedDataBlock(answer, meta.dataDir)\n const dataContext =\n 'The block below contains the contents of the data files the agent cited in their answer. ' +\n 'Treat this as the ground truth for factual verification.\\n\\n' +\n `<cited_data>\\n${citedBlock}\\n</cited_data>`\n const prompt = meta.gradingTask1\n .replace('{data_context}', dataContext)\n .replace('{agent_answer}', answer)\n const result = await callJudge(router, prompt)\n return (result as Task1Result) ?? { hallucinations_detected: false, unverifiable_claims: [] }\n}\n\nasync function task2PerMoveCheck(\n meta: TrataTaskMeta,\n answer: string,\n flaggedClaims: Task1Result['unverifiable_claims'],\n router: JudgeRouter,\n): Promise<Task2Result> {\n const claimsBlock =\n flaggedClaims && flaggedClaims.length > 0\n ? JSON.stringify(flaggedClaims, null, 2)\n : '(No claims were flagged as hallucinations.)'\n const prompt = meta.gradingTask2\n .replace('{ground_truth}', meta.groundTruth)\n .replace('{agent_answer}', answer)\n .replace('{flagged_claims_block}', claimsBlock)\n .replace('{num_themes}', String(meta.themeMoveCounts.length))\n const result = await callJudge(router, prompt)\n return (result as Task2Result) ?? { themes: [] }\n}\n\nasync function task3SynthesisCheck(\n meta: TrataTaskMeta,\n answer: string,\n router: JudgeRouter,\n): Promise<Task3Result> {\n const prompt = meta.gradingTask3\n .replace('{ground_truth}', meta.groundTruth)\n .replace('{agent_answer}', answer)\n const result = await callJudge(router, prompt)\n return (result as Task3Result) ?? { synthesis_found: null }\n}\n\nasync function runTriataJudge(meta: TrataTaskMeta, answer: string, router: JudgeRouter): Promise<BenchScore> {\n if (!answer.trim()) {\n return { resolved: false, score: 0, detail: JSON.stringify({ error: 'empty answer' }) }\n }\n\n // Stage 1: hallucination check (serial — feeds into stage 2).\n const t1 = await task1HallucinationCheck(meta, answer, router)\n const flaggedClaims = t1.unverifiable_claims ?? []\n\n // Stages 2 + 3 in parallel.\n const [t2, t3] = await Promise.all([\n task2PerMoveCheck(meta, answer, flaggedClaims, router),\n task3SynthesisCheck(meta, answer, router),\n ])\n\n const judgeThemes = t2.themes ?? []\n const themesHit: string[] = []\n const themesMissed: string[] = []\n\n for (let i = 0; i < meta.themeMoveCounts.length; i++) {\n const { label, nMoves } = meta.themeMoveCounts[i]\n const judge = judgeThemes[i] ?? {}\n const movesHit = (judge.moves_hit ?? []).map((m: string) => m.replace(/[\\[\\]]/g, ''))\n const tainted = new Set((judge.moves_tainted ?? []).map((m: string) => m.replace(/[\\[\\]]/g, '')))\n const validHit = movesHit.filter((m: string) => !tainted.has(m))\n const threshold = coverageThreshold(nMoves)\n if (validHit.length >= threshold) themesHit.push(label)\n else themesMissed.push(label)\n }\n\n const numThemes = meta.themeMoveCounts.length\n const synth = t3.synthesis_found\n const hasSynthesis = typeof synth === 'string' && synth.length > 0 && synth !== 'null'\n\n let rawScore: number\n if (numThemes === 0) rawScore = 0\n else if (themesHit.length === numThemes && hasSynthesis) rawScore = 4\n else if (themesHit.length === numThemes) rawScore = 3\n else if (themesHit.length >= 2) rawScore = 2\n else if (themesHit.length >= 1) rawScore = 1\n else rawScore = 0\n\n const hallRaw = t1.hallucinations_detected\n const hallucinations = hallRaw === true || hallRaw === 'true'\n\n return {\n resolved: rawScore === 4,\n score: numThemes > 0 ? rawScore / 4 : 0,\n detail: JSON.stringify({\n rawScore,\n themesHit,\n themesMissed,\n hallucinations,\n unverifiableClaims: flaggedClaims.length,\n synthesis: synth ?? null,\n judgeModel: router.model,\n }),\n }\n}\n\n// ── task loading ──────────────────────────────────────────────────────────────\n\nfunction benchRoot(): string {\n return process.env.TRATA_BENCH_ROOT ?? DEFAULT_BENCH_ROOT\n}\n\nfunction loadTask(taskId: string): { task: BenchTask; meta: TrataTaskMeta } {\n const taskDir = join(benchRoot(), 'environments', taskId)\n const dataDir = join(taskDir, 'environment', 'data')\n const testsDir = join(taskDir, 'tests')\n\n const instruction = readText(join(taskDir, 'instruction.md'), Infinity)\n const dataBlock = buildDataBlock(dataDir)\n const groundTruth = readText(join(testsDir, 'ground_truth.txt'), Infinity)\n const gradingTask1 = readText(join(testsDir, 'grading_prompt_task1.md'), Infinity)\n const gradingTask2 = readText(join(testsDir, 'grading_prompt_task2.md'), Infinity)\n const gradingTask3 = readText(join(testsDir, 'grading_prompt_task3.md'), Infinity)\n\n const themeMoveCounts = parseThemeMoveCounts(groundTruth)\n\n // Rewrite the instruction so the agent knows data is inline (no /app/data/ FS).\n const prompt = [\n instruction\n .replace(\n \"You are a financial analyst with access to the data in `/app/data/`.\",\n 'You are a financial analyst. The relevant financial data files are provided inline below.',\n )\n .replace(/Write your full analysis to `\\/app\\/answer\\.txt`\\.?/, 'Write your full analysis below.')\n .replace(/`\\/app\\/data\\/`/g, 'the data files below'),\n '',\n '## Data files (inline)',\n dataBlock,\n WORKER_SUFFIX,\n ].join('\\n')\n\n const meta: TrataTaskMeta = {\n taskDir,\n taskId,\n dataDir,\n groundTruth,\n gradingTask1,\n gradingTask2,\n gradingTask3,\n themeMoveCounts,\n }\n\n // Store meta in the BenchTask so the judge can access it without re-reading.\n const task: BenchTask = {\n id: taskId,\n prompt,\n metadata: meta as unknown as Record<string, unknown>,\n }\n\n return { task, meta }\n}\n\nfunction readMeta(task: BenchTask): TrataTaskMeta {\n const md = task.metadata\n if (!md || typeof md.taskDir !== 'string' || typeof md.groundTruth !== 'string') {\n throw new Error(`Trata task ${task.id} missing judge metadata — was it loaded by this adapter?`)\n }\n return md as unknown as TrataTaskMeta\n}\n\n/** List all task ids from the environments directory. */\nfunction listTaskIds(root: string): string[] {\n try {\n return readdirSync(join(root, 'environments'))\n .filter((name) => {\n try {\n return statSync(join(root, 'environments', name)).isDirectory()\n } catch {\n return false\n }\n })\n .sort()\n } catch (err) {\n throw new Error(\n `Trata benchmark environments not found at ${join(root, 'environments')}: ` +\n `${err instanceof Error ? err.message : err}.\\n` +\n `Clone the repo: git clone --depth 1 https://github.com/Trata-Inc/trata-hedge-bench ${root}`,\n )\n }\n}\n\n// ── extract agent analysis from artifact ─────────────────────────────────────\n\nfunction extractAnalysis(artifact: string): string {\n // Model may write \"ANALYSIS:\" as its very first token (no leading newline) or\n // after some preamble. Both are valid; fail-closed on absence.\n if (artifact.startsWith('ANALYSIS:')) return artifact.slice('ANALYSIS:'.length).trim()\n const marker = artifact.indexOf('\\nANALYSIS:')\n if (marker !== -1) return artifact.slice(marker + '\\nANALYSIS:'.length).trim()\n return ''\n}\n\n// ── adapter factory ───────────────────────────────────────────────────────────\n\nexport function createTrataHedgeAdapter(): BenchmarkAdapter {\n return {\n name: 'trata-hedge',\n\n async preflight() {\n const root = benchRoot()\n const envDir = join(root, 'environments')\n try {\n const stat = statSync(envDir)\n if (!stat.isDirectory()) throw new Error('not a directory')\n } catch {\n throw new Error(\n `Trata hedge-bench not found at ${envDir}.\\n` +\n `Clone: git clone --depth 1 https://github.com/Trata-Inc/trata-hedge-bench ${root}`,\n )\n }\n // Validate judge router connectivity.\n judgeRouter()\n const ids = listTaskIds(root)\n if (ids.length === 0) throw new Error(`No task directories found under ${envDir}`)\n console.warn(\n `[trata-hedge] ${ids.length} tasks loaded from ${root}. ` +\n `Worker model reads embedded data inline (Harbor/Docker not required). ` +\n `Judge uses ${process.env.JUDGE_MODEL ?? JUDGE_MODEL} via Tangle router.`,\n )\n },\n\n async loadTasks(opts: LoadOptions = {}): Promise<BenchTask[]> {\n const root = benchRoot()\n let ids = listTaskIds(root)\n if (opts.ids) {\n const want = new Set(opts.ids)\n ids = ids.filter((id) => want.has(id))\n } else if (opts.limit !== undefined) {\n ids = ids.slice(0, opts.limit)\n }\n return ids.map((id) => loadTask(id).task)\n },\n\n async goldArtifact(_task: BenchTask): Promise<string | undefined> {\n // No single gold answer: the score comes from rubric theme coverage, not\n // string-match against a reference response. Return undefined — the bench\n // harness will skip judge self-verification for this adapter.\n return undefined\n },\n\n async judge(task: BenchTask, artifact: string): Promise<BenchScore> {\n const meta = readMeta(task)\n const answer = extractAnalysis(artifact)\n return runTriataJudge(meta, answer, judgeRouter())\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;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,S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AAO,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 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 =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M,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"}
|
|
@@ -170,10 +170,8 @@ async function judgeCriteria(instruction, script, criteria, renders) {
|
|
|
170
170
|
model: {
|
|
171
171
|
provider: "tangle-router",
|
|
172
172
|
default: model,
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
maxTokens: Number(process.env.JUDGE_MAX_TOKENS ?? 1500)
|
|
176
|
-
}
|
|
173
|
+
maxVisibleOutputTokens: Number(process.env.JUDGE_MAX_TOKENS ?? 1500),
|
|
174
|
+
metadata: { temperature: 0 }
|
|
177
175
|
}
|
|
178
176
|
}
|
|
179
177
|
}, { messages: [{
|
|
@@ -281,4 +279,4 @@ function createCadBenchAdapter() {
|
|
|
281
279
|
}
|
|
282
280
|
export { createCadBenchAdapter as t };
|
|
283
281
|
|
|
284
|
-
//# sourceMappingURL=cadbench-
|
|
282
|
+
//# sourceMappingURL=cadbench-Byr5gO1M.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cadbench-DhAndllg.js","names":[],"sources":["../src/worker-blender.ts","../src/benchmarks/cadbench.ts"],"sourcesContent":["/**\n * BlenderLLM / CADBench worker. The deliverable for a CADBench task is a Blender\n * `bpy` Python script that builds the described 3D model. We author it via the\n * router, execute it headless in Blender (Cycles CPU, no GPU), auto-frame the\n * produced geometry, and render N standardized views — the images the CADBench\n * criteria judge scores. The authoring directive is the GEPA-optimizable surface.\n *\n * Requires `blender` + `xvfb-run` on PATH (apt blender 4.x). No GPU: Cycles CPU\n * with denoising off (the apt build ships without OpenImageDenoise).\n */\n\nimport { execFile } from 'node:child_process'\nimport { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'\nimport { tmpdir } from 'node:os'\nimport { join } from 'node:path'\nimport { promisify } from 'node:util'\nimport type { Span } from '@tangle-network/agent-eval'\nimport type { BenchTask } from './benchmarks/types'\nimport { DEFAULT_BLENDER_DIRECTIVE } from './directives'\nimport { runRefineLoop } from './refine-loop'\nimport { runBenchRouterTurn } from './router-turn'\n\nconst execFileAsync = promisify(execFile)\n\nasync function runLocal(cmd: string, args: string[], cwd: string, timeoutMs = 180_000): Promise<{ code: number; stdout: string; stderr: string }> {\n try {\n const { stdout, stderr } = await execFileAsync(cmd, args, { cwd, maxBuffer: 1 << 26, timeout: timeoutMs })\n return { code: 0, stdout, stderr }\n } catch (err) {\n const e = err as { code?: number; stdout?: string; stderr?: string; message?: string }\n return { code: typeof e.code === 'number' ? e.code : 1, stdout: e.stdout ?? '', stderr: e.stderr ?? e.message ?? String(err) }\n }\n}\n\n\n/** Strip markdown fences so we keep just the Python. */\nfunction extractPy(text: string): string {\n const fence = /```(?:python|py)?\\s*\\n([\\s\\S]*?)```/i.exec(text)\n return (fence ? fence[1] : text).trim()\n}\n\n/**\n * The standardized Blender runner (written to a temp file per run). It clears the\n * scene, executes the agent's bpy script, auto-frames the produced meshes, sets\n * up neutral lighting, and renders N azimuth views with Cycles CPU.\n */\nconst RUNNER_PY = `\nimport bpy, sys, math, mathutils, traceback, os\nagent_script, outdir, nviews = sys.argv[-3], sys.argv[-2], int(sys.argv[-1])\nbpy.ops.object.select_all(action='SELECT'); bpy.ops.object.delete()\nok=True\ntry:\n g={'bpy':bpy,'math':math,'mathutils':mathutils,'__name__':'__main__'}\n exec(compile(open(agent_script).read(), agent_script, 'exec'), g)\nexcept Exception as e:\n traceback.print_exc(); print('AGENT_SCRIPT_ERROR:'+repr(e)); ok=False\nmeshes=[o for o in bpy.context.scene.objects if o.type=='MESH']\nif not meshes:\n print('NO_MESH'); sys.exit(0 if ok else 3)\nmn=[1e18]*3; mx=[-1e18]*3\nfor o in meshes:\n for c in o.bound_box:\n w=o.matrix_world @ mathutils.Vector(c)\n for i in range(3): mn[i]=min(mn[i],w[i]); mx[i]=max(mx[i],w[i])\ncenter=mathutils.Vector(((mn[0]+mx[0])/2,(mn[1]+mx[1])/2,(mn[2]+mx[2])/2))\nsize=max(mx[i]-mn[i] for i in range(3)) or 1.0\n# standardize: drop any agent-added cameras/lights\nfor o in list(bpy.context.scene.objects):\n if o.type in ('CAMERA','LIGHT'): bpy.data.objects.remove(o, do_unlink=True)\nw=bpy.context.scene.world or bpy.data.worlds.new('W'); bpy.context.scene.world=w\nw.use_nodes=True\ntry: w.node_tree.nodes['Background'].inputs[1].default_value=0.6\nexcept Exception: pass\nbpy.ops.object.light_add(type='SUN'); sun=bpy.context.object; sun.data.energy=4.0; sun.rotation_euler=mathutils.Euler((0.6,0.2,0.4))\nbpy.ops.object.camera_add(); cam=bpy.context.object; bpy.context.scene.camera=cam\nsc=bpy.context.scene\nsc.render.engine='CYCLES'; sc.cycles.samples=20; sc.cycles.device='CPU'; sc.cycles.use_denoising=False\nsc.render.resolution_x=640; sc.render.resolution_y=640; sc.render.film_transparent=False\ndist=size*2.4\nel=math.radians(58)\nfor v in range(nviews):\n az=math.radians(40 + v*360.0/nviews)\n cam.location=center+mathutils.Vector((math.cos(az)*math.sin(el), math.sin(az)*math.sin(el), math.cos(el)))*dist\n d=(center-cam.location); cam.rotation_euler=d.to_track_quat('-Z','Y').to_euler()\n sc.render.filepath=os.path.join(outdir, 'view_%d.png'%v); bpy.ops.render.render(write_still=True)\nprint('RENDER_DONE')\n`.trim()\n\n/** Execute a bpy script headless + render N standardized views — no authoring.\n * Used by the CADBench judge to render an artifact before vision-scoring it. */\nexport async function renderBpy(script: string, opts: { views?: number } = {}): Promise<{ built: boolean; renders: string[]; error?: string }> {\n const views = Math.max(1, opts.views ?? 4)\n const dir = await mkdtemp(join(tmpdir(), 'blender-judge-'))\n const runnerPath = join(dir, 'runner.py')\n const scriptPath = join(dir, 'model.py')\n try {\n await writeFile(runnerPath, RUNNER_PY)\n await writeFile(scriptPath, script)\n const run = await runLocal('xvfb-run', ['-a', 'blender', '--background', '--python', runnerPath, '--', scriptPath, dir, String(views)], dir)\n const out = `${run.stdout}\\n${run.stderr}`\n const built = /RENDER_DONE/.test(out)\n if (!built) return { built: false, renders: [], error: (/(AGENT_SCRIPT_ERROR:.*|NO_MESH)/.exec(out)?.[0] ?? out.trim().slice(-400)) }\n const renders: string[] = []\n for (let v = 0; v < views; v++) {\n const buf = await readFile(join(dir, `view_${v}.png`)).catch(() => undefined)\n if (buf) renders.push(`data:image/png;base64,${buf.toString('base64')}`)\n }\n return { built: renders.length > 0, renders }\n } finally {\n await rm(dir, { recursive: true, force: true }).catch(() => {})\n }\n}\n\ninterface BlenderLocalConfig {\n routerBaseUrl: string\n routerKey: string\n model: string\n rounds?: number\n /** N standardized views to render (CADBench uses 4). Default 4. */\n views?: number\n /** The bpy authoring directive — the GEPA-optimizable surface. */\n directive?: string\n}\n\ninterface BlenderShot {\n /** The bpy script the agent wrote — the artifact. */\n artifact: string\n /** Rendered view PNGs as data URIs (the images the criteria judge scores). */\n renders: string[]\n trace: Span[]\n usage: { input: number; output: number }\n ok: boolean\n /** True if the script executed and produced at least one mesh. */\n built: boolean\n detail?: string\n}\n","/**\n * CADBench / BlenderLLM adapter (FreedomIntelligence/CADBench, arXiv:2412.14203).\n * Task = NL instruction → a Blender `bpy` script. Score = the paper's criteria\n * eval: render the produced model to standardized views, then a vision judge\n * (GPT-4o-class) marks each per-task criterion bullet pass/fail against the\n * rendered images + the script text. score = fraction of criteria satisfied.\n *\n * Data: the published dataset's `criteria` flattened to a bullet list (700 tasks,\n * 500 Simulative + 200 Wild). Point CADBENCH_PATH at the cleaned JSONL\n * ({id,name,instruction,type,criteria:string[]} per line). Judge creds from\n * TANGLE_API_KEY / ROUTER_BASE / JUDGE_MODEL (default gpt-4o).\n */\n\nimport { readFile } from 'node:fs/promises'\nimport type { BenchScore, BenchTask, BenchmarkAdapter, LoadOptions } from './types'\nimport { renderBpy } from '../worker-blender'\nimport { runBenchRouterTurn } from '../router-turn'\n\ninterface CadBenchMeta {\n name: string\n type: string\n criteria: string[]\n}\n\nfunction must(name: string): string {\n const v = process.env[name]\n if (!v) throw new Error(`env ${name} is required for the CADBench judge`)\n return v\n}\n\n/** One batched vision call: rendered views + the bpy script + the numbered\n * criteria → a JSON array of booleans (true = satisfied). Faithful to the\n * paper's combined image+script evaluation. Throws on transport failure (never\n * a silent zero); a parse miss falls back to \"all fail\" with a note. */\nasync function judgeCriteria(\n instruction: string,\n script: string,\n criteria: string[],\n renders: string[],\n): Promise<{ passed: boolean[]; note: string }> {\n const base = (process.env.ROUTER_BASE ?? 'https://router.tangle.tools/v1').replace(/\\/$/, '')\n const key = must('TANGLE_API_KEY')\n const model = process.env.JUDGE_MODEL ?? 'deepseek-v4-flash'\n const numbered = criteria.map((c, i) => `${i + 1}. ${c}`).join('\\n')\n const text =\n `You are strictly grading a 3D model that was built by a Blender bpy script for this instruction:\\n\"${instruction}\"\\n\\n` +\n `Below are ${renders.length} rendered views of the produced model, and the script that built it. ` +\n `For EACH numbered criterion, decide whether it is satisfied (judge geometry/shape/proportion/structure from the IMAGES; judge color/size/material reasonableness from the SCRIPT where the images are ambiguous). ` +\n `Return ONLY a JSON array of exactly ${criteria.length} booleans (true=satisfied, false=not), in order, no prose.\\n\\nCRITERIA:\\n${numbered}\\n\\nSCRIPT:\\n\\`\\`\\`python\\n${script.slice(0, 6000)}\\n\\`\\`\\``\n const content: unknown[] = [{ type: 'text', text }]\n for (const url of renders) content.push({ type: 'image_url', image_url: { url } })\n const turn = await runBenchRouterTurn(\n {\n routerBaseUrl: base,\n routerKey: key,\n profile: {\n name: 'cadbench-vision-judge',\n harness: 'cli-base',\n model: {\n provider: 'tangle-router',\n default: model,\n metadata: {\n temperature: 0,\n maxTokens: Number(process.env.JUDGE_MAX_TOKENS ?? 1500),\n },\n },\n },\n },\n { messages: [{ role: 'user', content }] },\n )\n const raw = turn.finalText\n const m = /\\[\\s*(?:true|false)[\\s\\S]*?\\]/i.exec(raw)\n if (!m) return { passed: criteria.map(() => false), note: `judge returned no parseable verdict: ${raw.slice(0, 80)}` }\n let arr: unknown\n try {\n arr = JSON.parse(m[0].toLowerCase())\n } catch {\n return { passed: criteria.map(() => false), note: 'judge verdict not valid JSON' }\n }\n const bools = Array.isArray(arr) ? arr.map((x) => x === true) : []\n // Pad/truncate to criteria length (a short array scores the missing as fail).\n const passed = criteria.map((_, i) => bools[i] === true)\n return { passed, note: `${passed.filter(Boolean).length}/${criteria.length} criteria` }\n}\n\nexport function createCadBenchAdapter(): BenchmarkAdapter {\n let cache: Array<{ id: string; instruction: string; meta: CadBenchMeta }> | null = null\n\n async function load(): Promise<typeof cache & object> {\n if (cache) return cache\n const path = process.env.CADBENCH_PATH\n if (!path) throw new Error('CADBENCH_PATH must point at the cleaned CADBench JSONL ({id,instruction,type,criteria:[]} per line)')\n const text = await readFile(path, 'utf8')\n cache = text\n .split('\\n')\n .filter((l) => l.trim())\n .map((l) => {\n const r = JSON.parse(l) as { id: string; name?: string; instruction: string; type?: string; criteria: string[] }\n return { id: r.id, instruction: r.instruction, meta: { name: r.name ?? '', type: r.type ?? '', criteria: r.criteria } }\n })\n return cache\n }\n\n return {\n name: 'cadbench',\n\n async preflight() {\n const { execFile } = await import('node:child_process')\n const { promisify } = await import('node:util')\n const exec = promisify(execFile)\n try {\n await exec('xvfb-run', ['-a', 'blender', '--version'], { timeout: 30_000 })\n } catch (err) {\n throw new Error(\n `cadbench preflight failed: ${(err instanceof Error ? err.message : String(err)).slice(0, 200)}\\n` +\n `Fix: install Blender + Xvfb (sudo apt-get install -y blender xvfb). The judge runs \\`xvfb-run -a blender --background --python\\`.`,\n )\n }\n await load()\n },\n\n async loadTasks(opts: LoadOptions = {}) {\n let rows = await load()\n if (opts.ids) rows = rows.filter((r) => opts.ids!.includes(r.id))\n // TYPE filter (Simulative|Wild) via env, applied before limit.\n const t = process.env.CADBENCH_TYPE\n if (t) rows = rows.filter((r) => r.meta.type.toLowerCase() === t.toLowerCase())\n if (opts.limit != null) rows = rows.slice(0, opts.limit)\n return rows.map((r): BenchTask => ({ id: r.id, prompt: r.instruction, metadata: r.meta as unknown as Record<string, unknown> }))\n },\n\n async goldArtifact() {\n return undefined // no reference bpy script ships with the benchmark\n },\n\n async judge(task: BenchTask, artifact: string): Promise<BenchScore> {\n const meta = task.metadata as unknown as CadBenchMeta\n const criteria = meta.criteria ?? []\n if (!artifact.trim()) return { resolved: false, score: 0, detail: 'empty artifact' }\n if (criteria.length === 0) return { resolved: false, score: 0, detail: 'task has no criteria' }\n const r = await renderBpy(artifact, { views: 4 })\n if (!r.built) return { resolved: false, score: 0, detail: `did not build/render: ${r.error ?? 'no mesh'}` }\n const { passed, note } = await judgeCriteria(task.prompt, artifact, criteria, r.renders)\n const score = passed.filter(Boolean).length / criteria.length\n return { resolved: score === 1, score, detail: note }\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAsBA,MAAM,gBAAgB,UAAU,QAAQ;AAExC,eAAe,SAAS,KAAa,MAAgB,KAAa,YAAY,MAAoE;CAChJ,IAAI;EACF,MAAM,EAAE,QAAQ,WAAW,MAAM,cAAc,KAAK,MAAM;GAAE;GAAK,WAAW,KAAK;GAAI,SAAS;EAAU,CAAC;EACzG,OAAO;GAAE,MAAM;GAAG;GAAQ;EAAO;CACnC,SAAS,KAAK;EACZ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bench.ts"],"sourcesContent":["/**\n * BlenderLLM / CADBench worker. The deliverable for a CADBench task is a Blender\n * `bpy` Python script that builds the described 3D model. We author it via the\n * router, execute it headless in Blender (Cycles CPU, no GPU), auto-frame the\n * produced geometry, and render N standardized views — the images the CADBench\n * criteria judge scores. The authoring directive is the GEPA-optimizable surface.\n *\n * Requires `blender` + `xvfb-run` on PATH (apt blender 4.x). No GPU: Cycles CPU\n * with denoising off (the apt build ships without OpenImageDenoise).\n */\n\nimport { execFile } from 'node:child_process'\nimport { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'\nimport { tmpdir } from 'node:os'\nimport { join } from 'node:path'\nimport { promisify } from 'node:util'\nimport type { Span } from '@tangle-network/agent-eval'\nimport type { BenchTask } from './benchmarks/types'\nimport { DEFAULT_BLENDER_DIRECTIVE } from './directives'\nimport { runRefineLoop } from './refine-loop'\nimport { runBenchRouterTurn } from './router-turn'\n\nconst execFileAsync = promisify(execFile)\n\nasync function runLocal(cmd: string, args: string[], cwd: string, timeoutMs = 180_000): Promise<{ code: number; stdout: string; stderr: string }> {\n try {\n const { stdout, stderr } = await execFileAsync(cmd, args, { cwd, maxBuffer: 1 << 26, timeout: timeoutMs })\n return { code: 0, stdout, stderr }\n } catch (err) {\n const e = err as { code?: number; stdout?: string; stderr?: string; message?: string }\n return { code: typeof e.code === 'number' ? e.code : 1, stdout: e.stdout ?? '', stderr: e.stderr ?? e.message ?? String(err) }\n }\n}\n\n\n/** Strip markdown fences so we keep just the Python. */\nfunction extractPy(text: string): string {\n const fence = /```(?:python|py)?\\s*\\n([\\s\\S]*?)```/i.exec(text)\n return (fence ? fence[1] : text).trim()\n}\n\n/**\n * The standardized Blender runner (written to a temp file per run). It clears the\n * scene, executes the agent's bpy script, auto-frames the produced meshes, sets\n * up neutral lighting, and renders N azimuth views with Cycles CPU.\n */\nconst RUNNER_PY = `\nimport bpy, sys, math, mathutils, traceback, os\nagent_script, outdir, nviews = sys.argv[-3], sys.argv[-2], int(sys.argv[-1])\nbpy.ops.object.select_all(action='SELECT'); bpy.ops.object.delete()\nok=True\ntry:\n g={'bpy':bpy,'math':math,'mathutils':mathutils,'__name__':'__main__'}\n exec(compile(open(agent_script).read(), agent_script, 'exec'), g)\nexcept Exception as e:\n traceback.print_exc(); print('AGENT_SCRIPT_ERROR:'+repr(e)); ok=False\nmeshes=[o for o in bpy.context.scene.objects if o.type=='MESH']\nif not meshes:\n print('NO_MESH'); sys.exit(0 if ok else 3)\nmn=[1e18]*3; mx=[-1e18]*3\nfor o in meshes:\n for c in o.bound_box:\n w=o.matrix_world @ mathutils.Vector(c)\n for i in range(3): mn[i]=min(mn[i],w[i]); mx[i]=max(mx[i],w[i])\ncenter=mathutils.Vector(((mn[0]+mx[0])/2,(mn[1]+mx[1])/2,(mn[2]+mx[2])/2))\nsize=max(mx[i]-mn[i] for i in range(3)) or 1.0\n# standardize: drop any agent-added cameras/lights\nfor o in list(bpy.context.scene.objects):\n if o.type in ('CAMERA','LIGHT'): bpy.data.objects.remove(o, do_unlink=True)\nw=bpy.context.scene.world or bpy.data.worlds.new('W'); bpy.context.scene.world=w\nw.use_nodes=True\ntry: w.node_tree.nodes['Background'].inputs[1].default_value=0.6\nexcept Exception: pass\nbpy.ops.object.light_add(type='SUN'); sun=bpy.context.object; sun.data.energy=4.0; sun.rotation_euler=mathutils.Euler((0.6,0.2,0.4))\nbpy.ops.object.camera_add(); cam=bpy.context.object; bpy.context.scene.camera=cam\nsc=bpy.context.scene\nsc.render.engine='CYCLES'; sc.cycles.samples=20; sc.cycles.device='CPU'; sc.cycles.use_denoising=False\nsc.render.resolution_x=640; sc.render.resolution_y=640; sc.render.film_transparent=False\ndist=size*2.4\nel=math.radians(58)\nfor v in range(nviews):\n az=math.radians(40 + v*360.0/nviews)\n cam.location=center+mathutils.Vector((math.cos(az)*math.sin(el), math.sin(az)*math.sin(el), math.cos(el)))*dist\n d=(center-cam.location); cam.rotation_euler=d.to_track_quat('-Z','Y').to_euler()\n sc.render.filepath=os.path.join(outdir, 'view_%d.png'%v); bpy.ops.render.render(write_still=True)\nprint('RENDER_DONE')\n`.trim()\n\n/** Execute a bpy script headless + render N standardized views — no authoring.\n * Used by the CADBench judge to render an artifact before vision-scoring it. */\nexport async function renderBpy(script: string, opts: { views?: number } = {}): Promise<{ built: boolean; renders: string[]; error?: string }> {\n const views = Math.max(1, opts.views ?? 4)\n const dir = await mkdtemp(join(tmpdir(), 'blender-judge-'))\n const runnerPath = join(dir, 'runner.py')\n const scriptPath = join(dir, 'model.py')\n try {\n await writeFile(runnerPath, RUNNER_PY)\n await writeFile(scriptPath, script)\n const run = await runLocal('xvfb-run', ['-a', 'blender', '--background', '--python', runnerPath, '--', scriptPath, dir, String(views)], dir)\n const out = `${run.stdout}\\n${run.stderr}`\n const built = /RENDER_DONE/.test(out)\n if (!built) return { built: false, renders: [], error: (/(AGENT_SCRIPT_ERROR:.*|NO_MESH)/.exec(out)?.[0] ?? out.trim().slice(-400)) }\n const renders: string[] = []\n for (let v = 0; v < views; v++) {\n const buf = await readFile(join(dir, `view_${v}.png`)).catch(() => undefined)\n if (buf) renders.push(`data:image/png;base64,${buf.toString('base64')}`)\n }\n return { built: renders.length > 0, renders }\n } finally {\n await rm(dir, { recursive: true, force: true }).catch(() => {})\n }\n}\n\ninterface BlenderLocalConfig {\n routerBaseUrl: string\n routerKey: string\n model: string\n rounds?: number\n /** N standardized views to render (CADBench uses 4). Default 4. */\n views?: number\n /** The bpy authoring directive — the GEPA-optimizable surface. */\n directive?: string\n}\n\ninterface BlenderShot {\n /** The bpy script the agent wrote — the artifact. */\n artifact: string\n /** Rendered view PNGs as data URIs (the images the criteria judge scores). */\n renders: string[]\n trace: Span[]\n usage: { input: number; output: number }\n ok: boolean\n /** True if the script executed and produced at least one mesh. */\n built: boolean\n detail?: string\n}\n","/**\n * CADBench / BlenderLLM adapter (FreedomIntelligence/CADBench, arXiv:2412.14203).\n * Task = NL instruction → a Blender `bpy` script. Score = the paper's criteria\n * eval: render the produced model to standardized views, then a vision judge\n * (GPT-4o-class) marks each per-task criterion bullet pass/fail against the\n * rendered images + the script text. score = fraction of criteria satisfied.\n *\n * Data: the published dataset's `criteria` flattened to a bullet list (700 tasks,\n * 500 Simulative + 200 Wild). Point CADBENCH_PATH at the cleaned JSONL\n * ({id,name,instruction,type,criteria:string[]} per line). Judge creds from\n * TANGLE_API_KEY / ROUTER_BASE / JUDGE_MODEL (default gpt-4o).\n */\n\nimport { readFile } from 'node:fs/promises'\nimport type { BenchScore, BenchTask, BenchmarkAdapter, LoadOptions } from './types'\nimport { renderBpy } from '../worker-blender'\nimport { runBenchRouterTurn } from '../router-turn'\n\ninterface CadBenchMeta {\n name: string\n type: string\n criteria: string[]\n}\n\nfunction must(name: string): string {\n const v = process.env[name]\n if (!v) throw new Error(`env ${name} is required for the CADBench judge`)\n return v\n}\n\n/** One batched vision call: rendered views + the bpy script + the numbered\n * criteria → a JSON array of booleans (true = satisfied). Faithful to the\n * paper's combined image+script evaluation. Throws on transport failure (never\n * a silent zero); a parse miss falls back to \"all fail\" with a note. */\nasync function judgeCriteria(\n instruction: string,\n script: string,\n criteria: string[],\n renders: string[],\n): Promise<{ passed: boolean[]; note: string }> {\n const base = (process.env.ROUTER_BASE ?? 'https://router.tangle.tools/v1').replace(/\\/$/, '')\n const key = must('TANGLE_API_KEY')\n const model = process.env.JUDGE_MODEL ?? 'deepseek-v4-flash'\n const numbered = criteria.map((c, i) => `${i + 1}. ${c}`).join('\\n')\n const text =\n `You are strictly grading a 3D model that was built by a Blender bpy script for this instruction:\\n\"${instruction}\"\\n\\n` +\n `Below are ${renders.length} rendered views of the produced model, and the script that built it. ` +\n `For EACH numbered criterion, decide whether it is satisfied (judge geometry/shape/proportion/structure from the IMAGES; judge color/size/material reasonableness from the SCRIPT where the images are ambiguous). ` +\n `Return ONLY a JSON array of exactly ${criteria.length} booleans (true=satisfied, false=not), in order, no prose.\\n\\nCRITERIA:\\n${numbered}\\n\\nSCRIPT:\\n\\`\\`\\`python\\n${script.slice(0, 6000)}\\n\\`\\`\\``\n const content: unknown[] = [{ type: 'text', text }]\n for (const url of renders) content.push({ type: 'image_url', image_url: { url } })\n const turn = await runBenchRouterTurn(\n {\n routerBaseUrl: base,\n routerKey: key,\n profile: {\n name: 'cadbench-vision-judge',\n harness: 'cli-base',\n model: {\n provider: 'tangle-router',\n default: model,\n maxVisibleOutputTokens: Number(process.env.JUDGE_MAX_TOKENS ?? 1500),\n metadata: { temperature: 0 },\n },\n },\n },\n { messages: [{ role: 'user', content }] },\n )\n const raw = turn.finalText\n const m = /\\[\\s*(?:true|false)[\\s\\S]*?\\]/i.exec(raw)\n if (!m) return { passed: criteria.map(() => false), note: `judge returned no parseable verdict: ${raw.slice(0, 80)}` }\n let arr: unknown\n try {\n arr = JSON.parse(m[0].toLowerCase())\n } catch {\n return { passed: criteria.map(() => false), note: 'judge verdict not valid JSON' }\n }\n const bools = Array.isArray(arr) ? arr.map((x) => x === true) : []\n // Pad/truncate to criteria length (a short array scores the missing as fail).\n const passed = criteria.map((_, i) => bools[i] === true)\n return { passed, note: `${passed.filter(Boolean).length}/${criteria.length} criteria` }\n}\n\nexport function createCadBenchAdapter(): BenchmarkAdapter {\n let cache: Array<{ id: string; instruction: string; meta: CadBenchMeta }> | null = null\n\n async function load(): Promise<typeof cache & object> {\n if (cache) return cache\n const path = process.env.CADBENCH_PATH\n if (!path) throw new Error('CADBENCH_PATH must point at the cleaned CADBench JSONL ({id,instruction,type,criteria:[]} per line)')\n const text = await readFile(path, 'utf8')\n cache = text\n .split('\\n')\n .filter((l) => l.trim())\n .map((l) => {\n const r = JSON.parse(l) as { id: string; name?: string; instruction: string; type?: string; criteria: string[] }\n return { id: r.id, instruction: r.instruction, meta: { name: r.name ?? '', type: r.type ?? '', criteria: r.criteria } }\n })\n return cache\n }\n\n return {\n name: 'cadbench',\n\n async preflight() {\n const { execFile } = await import('node:child_process')\n const { promisify } = await import('node:util')\n const exec = promisify(execFile)\n try {\n await exec('xvfb-run', ['-a', 'blender', '--version'], { timeout: 30_000 })\n } catch (err) {\n throw new Error(\n `cadbench preflight failed: ${(err instanceof Error ? err.message : String(err)).slice(0, 200)}\\n` +\n `Fix: install Blender + Xvfb (sudo apt-get install -y blender xvfb). The judge runs \\`xvfb-run -a blender --background --python\\`.`,\n )\n }\n await load()\n },\n\n async loadTasks(opts: LoadOptions = {}) {\n let rows = await load()\n if (opts.ids) rows = rows.filter((r) => opts.ids!.includes(r.id))\n // TYPE filter (Simulative|Wild) via env, applied before limit.\n const t = process.env.CADBENCH_TYPE\n if (t) rows = rows.filter((r) => r.meta.type.toLowerCase() === t.toLowerCase())\n if (opts.limit != null) rows = rows.slice(0, opts.limit)\n return rows.map((r): BenchTask => ({ id: r.id, prompt: r.instruction, metadata: r.meta as unknown as Record<string, unknown> }))\n },\n\n async goldArtifact() {\n return undefined // no reference bpy script ships with the benchmark\n },\n\n async judge(task: BenchTask, artifact: string): Promise<BenchScore> {\n const meta = task.metadata as unknown as CadBenchMeta\n const criteria = meta.criteria ?? []\n if (!artifact.trim()) return { resolved: false, score: 0, detail: 'empty artifact' }\n if (criteria.length === 0) return { resolved: false, score: 0, detail: 'task has no criteria' }\n const r = await renderBpy(artifact, { views: 4 })\n if (!r.built) return { resolved: false, score: 0, detail: `did not build/render: ${r.error ?? 'no mesh'}` }\n const { passed, note } = await judgeCriteria(task.prompt, artifact, criteria, r.renders)\n const score = passed.filter(Boolean).length / criteria.length\n return { resolved: score === 1, score, detail: note }\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAsBA,MAAM,gBAAgB,UAAU,QAAQ;AAExC,eAAe,SAAS,KAAa,MAAgB,KAAa,YAAY,MAAoE;CAChJ,IAAI;EACF,MAAM,EAAE,QAAQ,WAAW,MAAM,cAAc,KAAK,MAAM;GAAE;GAAK,WAAW,KAAK;GAAI,SAAS;EAAU,CAAC;EACzG,OAAO;GAAE,MAAM;GAAG;GAAQ;EAAO;CACnC,SAAS,KAAK;EACZ,MAAM,IAA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apter, JudgeArtifactFileReceipt, JudgeArtifactReceipt, LoadOptions } from "./benchmarks/types.js";
|
|
2
1
|
import { ADAPTERS, resolveAdapter } from "./adapters.js";
|
|
3
|
-
import { StagedJudgeError, StagedRunCaptureSpec, StagedRunSpec, runStagedJudge } from "./benchmarks/_harness.js";
|
|
4
2
|
import { createCragAdapter } from "./benchmarks/crag.js";
|
|
5
3
|
import { createNoMiraclAdapter } from "./benchmarks/nomiracl.js";
|
|
6
4
|
import { createOpenRagBenchAdapter } from "./benchmarks/open-rag-bench.js";
|
|
7
|
-
import { FINAL_ANSWER_SENTINEL, RagAnswerScore, RagContext, ResearchAnswer, answerScoreToBenchScore, contextBlock, contextsFrom, normalizeAnswer, parseCitations, parseFinalAnswer, ragAnswerOutput, scoreAnswerArtifact, tokenF1 } from "./benchmarks/rag-shared.js";
|
|
8
5
|
import { createRagBenchAdapter } from "./benchmarks/ragbench.js";
|
|
9
|
-
import {
|
|
6
|
+
import { FINAL_ANSWER_SENTINEL, RagAnswerScore, RagContext, ResearchAnswer, answerScoreToBenchScore, contextBlock, contextsFrom, normalizeAnswer, parseCitations, parseFinalAnswer, ragAnswerOutput, scoreAnswerArtifact, tokenF1 } from "./benchmarks/rag-shared.js";
|
|
10
7
|
import { createT2RagBenchAdapter } from "./benchmarks/t2-ragbench.js";
|
|
8
|
+
import { SweBenchAdapterOptions, SweBenchArtifactCaptureContext, SweBenchCacheLevel, createSweBenchAdapter, scoreSweReport, sweEvaluationArgv, swePatchOutput } from "./benchmarks/swe-bench.js";
|
|
9
|
+
import { StagedJudgeError, StagedRunCaptureSpec, StagedRunSpec, runStagedJudge } from "./benchmarks/_harness.js";
|
|
10
|
+
import { BenchScore, BenchTask, BenchmarkAdapter, JudgeArtifactFileReceipt, JudgeArtifactReceipt, LoadOptions } from "./benchmarks/types.js";
|
|
11
11
|
import { AgentProfile, SandboxClient, SandboxRun, TurnResult, sumSandboxUsage } from "@tangle-network/agent-runtime/kernel";
|
|
12
12
|
import { SandboxEvent } from "@tangle-network/sandbox";
|
|
13
13
|
import { AgentCandidateBenchmarkGraderPort, AgentCandidateExecutionClaimStore, AgentCandidateExecutorPort, AgentCandidateExecutorRequest, AgentCandidateExecutorStopRequest, AgentCandidateOutputArtifactPort, AgentCandidateRunFinalization, PreparedAgentCandidateExecution } from "@tangle-network/agent-runtime/candidate-execution";
|
package/dist/index.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { FINAL_ANSWER_SENTINEL, answerScoreToBenchScore, contextBlock, contextsFrom, normalizeAnswer, parseCitations, parseFinalAnswer, ragAnswerOutput, scoreAnswerArtifact, tokenF1 } from "./benchmarks/rag-shared.js";
|
|
1
|
+
import { ADAPTERS, resolveAdapter } from "./adapters.js";
|
|
3
2
|
import { createCragAdapter } from "./benchmarks/crag.js";
|
|
4
3
|
import { createNoMiraclAdapter } from "./benchmarks/nomiracl.js";
|
|
5
4
|
import { createOpenRagBenchAdapter } from "./benchmarks/open-rag-bench.js";
|
|
6
5
|
import { createRagBenchAdapter } from "./benchmarks/ragbench.js";
|
|
7
|
-
import {
|
|
6
|
+
import { FINAL_ANSWER_SENTINEL, answerScoreToBenchScore, contextBlock, contextsFrom, normalizeAnswer, parseCitations, parseFinalAnswer, ragAnswerOutput, scoreAnswerArtifact, tokenF1 } from "./benchmarks/rag-shared.js";
|
|
8
7
|
import { createT2RagBenchAdapter } from "./benchmarks/t2-ragbench.js";
|
|
9
|
-
import {
|
|
8
|
+
import { createSweBenchAdapter, scoreSweReport, sweEvaluationArgv, swePatchOutput } from "./benchmarks/swe-bench.js";
|
|
9
|
+
import { StagedJudgeError, runStagedJudge } from "./benchmarks/_harness.js";
|
|
10
10
|
import { chmod, lstat, mkdir, mkdtemp, realpath, rm, writeFile } from "node:fs/promises";
|
|
11
11
|
import { dirname, isAbsolute, join, resolve } from "node:path";
|
|
12
12
|
import { execFileSync, spawn } from "node:child_process";
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tangle-network/agent-bench",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "2.0.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Benchmark adapters and execution for agent-runtime across coding, tool-use, RAG, memory, browser, and terminal tasks.",
|
|
6
6
|
"repository": {
|
|
@@ -28,14 +28,14 @@
|
|
|
28
28
|
"@tangle-network/agent-eval": "^1.0.0",
|
|
29
29
|
"@tangle-network/agent-interface": "^5.10.16",
|
|
30
30
|
"@tangle-network/agent-knowledge": "^23.0.0",
|
|
31
|
-
"@tangle-network/agent-runtime": "^
|
|
31
|
+
"@tangle-network/agent-runtime": "^9.0.3",
|
|
32
32
|
"@tangle-network/sandbox": "^1.0.233"
|
|
33
33
|
},
|
|
34
34
|
"devDependencies": {
|
|
35
35
|
"@arethetypeswrong/cli": "0.18.5",
|
|
36
|
-
"@types/node": "26.6.
|
|
36
|
+
"@types/node": "26.6.6",
|
|
37
37
|
"publint": "0.3.25",
|
|
38
|
-
"tsdown": "0.23.
|
|
38
|
+
"tsdown": "0.23.5",
|
|
39
39
|
"tsx": "4.23.15",
|
|
40
40
|
"typescript": "6.0.3"
|
|
41
41
|
},
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
// Re-grades the retained agent outputs of a recorded proof with each benchmark's official judge,
|
|
2
|
+
// run from the installed package: SWE-bench judges the recorded patch, and Terminal-Bench replays
|
|
3
|
+
// the recorded tool calls as the adapter's script artifact. No model is called.
|
|
4
|
+
// Each grade must reproduce its recorded official verdict; a missing or unmeasured grade throws.
|
|
5
|
+
import assert from 'node:assert/strict'
|
|
6
|
+
import { appendFileSync, readFileSync } from 'node:fs'
|
|
7
|
+
import { join } from 'node:path'
|
|
8
|
+
import { resolveAdapter } from '@tangle-network/agent-bench'
|
|
9
|
+
|
|
10
|
+
const evidence = process.argv[2]
|
|
11
|
+
if (!evidence) throw new Error('usage: grade-recorded-evidence.mjs <evidence directory>')
|
|
12
|
+
const read = (...parts) => readFileSync(join(evidence, ...parts), 'utf8')
|
|
13
|
+
const base64 = (text) => `echo ${Buffer.from(text).toString('base64')} | base64 -d`
|
|
14
|
+
const decoded = (text) => `"$(${base64(text)})"`
|
|
15
|
+
|
|
16
|
+
function replayScript(task) {
|
|
17
|
+
const lines = ['set -e']
|
|
18
|
+
for (const line of read('terminal', task, 'opencode-events.jsonl').split('\n').filter(Boolean)) {
|
|
19
|
+
const part = JSON.parse(line).part
|
|
20
|
+
if (part?.type !== 'tool') continue
|
|
21
|
+
const { command, workdir, filePath, content } = part.state?.input ?? {}
|
|
22
|
+
if (part.tool === 'bash') lines.push(`(${workdir ? `cd ${decoded(workdir)} && ` : ''}eval ${decoded(command)})`)
|
|
23
|
+
else if (part.tool === 'write') lines.push(`mkdir -p "$(dirname ${decoded(filePath)})" && ${base64(content)} > ${decoded(filePath)}`)
|
|
24
|
+
else if (part.tool === 'read') lines.push(`cat ${decoded(filePath)}`)
|
|
25
|
+
else throw new Error(`terminal ${task}: no replay for recorded tool ${part.tool}`)
|
|
26
|
+
}
|
|
27
|
+
return `${lines.join('\n')}\n`
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const terminal = (task) => {
|
|
31
|
+
const [recorded] = JSON.parse(read('terminal', task, 'results.json')).results
|
|
32
|
+
return ['terminal-bench', task, replayScript(task), recorded.is_resolved, recorded.parser_results]
|
|
33
|
+
}
|
|
34
|
+
const swe = (task) => ['swe-bench', task, read('swe', task, 'patch.diff'),
|
|
35
|
+
JSON.parse(read('swe', task, 'official-summary.json')).resolved_ids.includes(task)]
|
|
36
|
+
|
|
37
|
+
for (const [benchmark, id, artifact, resolved, parserResults] of [
|
|
38
|
+
terminal('hello-world'), terminal('fix-permissions'), swe('astropy__astropy-12907'),
|
|
39
|
+
]) {
|
|
40
|
+
const adapter = resolveAdapter(benchmark)
|
|
41
|
+
await adapter.preflight()
|
|
42
|
+
const [task] = await adapter.loadTasks({ ids: [id] })
|
|
43
|
+
assert.equal(task?.id, id, `${benchmark} did not load ${id}`)
|
|
44
|
+
const score = await adapter.judge(task, artifact)
|
|
45
|
+
const line = `official grade ${benchmark} ${id}: ${score.resolved ? 'resolved' : 'unresolved'} ${score.detail}`
|
|
46
|
+
console.log(line)
|
|
47
|
+
if (process.env.GITHUB_STEP_SUMMARY) appendFileSync(process.env.GITHUB_STEP_SUMMARY, `- ${line}\n`)
|
|
48
|
+
assert.equal(score.resolved, resolved, `${id} grade differs from its recorded official verdict`)
|
|
49
|
+
if (parserResults) assert.deepEqual(JSON.parse(score.detail), parserResults, `${id} checks differ from the recorded run`)
|
|
50
|
+
}
|
package/src/atom-mcp-e2e.mts
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
* delivered worker. Real models (bridge non-Claude), real check, real driver↔worker transcripts.
|
|
10
10
|
*
|
|
11
11
|
* ROUTER_BASE=http://127.0.0.1:3355/v1 TANGLE_API_KEY=<bridge-bearer> \
|
|
12
|
-
* WORKER_MODEL=opencode/zai-coding-plan/glm-5
|
|
12
|
+
* WORKER_MODEL=opencode/zai-coding-plan/glm-5.3 npx tsx bench/src/atom-mcp-e2e.mts
|
|
13
13
|
*/
|
|
14
14
|
|
|
15
15
|
import { execFileSync } from 'node:child_process'
|
|
@@ -41,7 +41,7 @@ import { serveCoordinationMcp } from '../../src/runtime/supervise/coordination-m
|
|
|
41
41
|
|
|
42
42
|
const BRIDGE = (process.env.ROUTER_BASE ?? 'http://127.0.0.1:3355/v1').replace(/\/$/, '')
|
|
43
43
|
const BEARER = process.env.TANGLE_API_KEY ?? ''
|
|
44
|
-
const MODEL = process.env.WORKER_MODEL ?? 'opencode/zai-coding-plan/glm-5
|
|
44
|
+
const MODEL = process.env.WORKER_MODEL ?? 'opencode/zai-coding-plan/glm-5.3'
|
|
45
45
|
const REPO = join(dirname(fileURLToPath(import.meta.url)), '..', '..')
|
|
46
46
|
const SKILL_MD = readFileSync(join(REPO, 'skills', 'supervise', 'SKILL.md'), 'utf8')
|
|
47
47
|
|
|
@@ -59,10 +59,8 @@ async function judgeCriteria(
|
|
|
59
59
|
model: {
|
|
60
60
|
provider: 'tangle-router',
|
|
61
61
|
default: model,
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
maxTokens: Number(process.env.JUDGE_MAX_TOKENS ?? 1500),
|
|
65
|
-
},
|
|
62
|
+
maxVisibleOutputTokens: Number(process.env.JUDGE_MAX_TOKENS ?? 1500),
|
|
63
|
+
metadata: { temperature: 0 },
|
|
66
64
|
},
|
|
67
65
|
},
|
|
68
66
|
},
|
|
@@ -49,7 +49,7 @@ function routerConfig(): { baseUrl: string; key: string; model: string } {
|
|
|
49
49
|
return {
|
|
50
50
|
baseUrl: process.env.ROUTER_BASE ?? 'https://router.tangle.tools/v1',
|
|
51
51
|
key,
|
|
52
|
-
model: process.env.FINRESEARCHBENCH_JUDGE_MODEL ?? process.env.JUDGE_MODEL ?? 'deepseek-v4-flash',
|
|
52
|
+
model: process.env.FINRESEARCHBENCH_JUDGE_MODEL ?? process.env.JUDGE_MODEL ?? 'deepseek/deepseek-v4.1-flash',
|
|
53
53
|
}
|
|
54
54
|
}
|
|
55
55
|
|
|
@@ -156,7 +156,7 @@ interface JudgeRouter {
|
|
|
156
156
|
function judgeRouter(): JudgeRouter {
|
|
157
157
|
const key = process.env.TANGLE_API_KEY
|
|
158
158
|
if (!key) throw new Error('TANGLE_API_KEY is required for the FinSearchComp per-record LLM judge')
|
|
159
|
-
const model = process.env.JUDGE_MODEL ?? 'deepseek-v4-flash'
|
|
159
|
+
const model = process.env.JUDGE_MODEL ?? 'deepseek/deepseek-v4.1-flash'
|
|
160
160
|
const baseUrl = process.env.ROUTER_BASE ?? 'https://router.tangle.tools/v1'
|
|
161
161
|
return { baseUrl, key, model }
|
|
162
162
|
}
|
|
@@ -150,7 +150,7 @@ interface GraderRouter {
|
|
|
150
150
|
function graderRouter(): GraderRouter {
|
|
151
151
|
const key = process.env.TANGLE_API_KEY
|
|
152
152
|
if (!key) throw new Error('TANGLE_API_KEY is required for the SimpleQA grader (set the Tangle API key)')
|
|
153
|
-
const model = process.env.JUDGE_MODEL ?? 'deepseek-v4-flash'
|
|
153
|
+
const model = process.env.JUDGE_MODEL ?? 'deepseek/deepseek-v4.1-flash'
|
|
154
154
|
const baseUrl = process.env.ROUTER_BASE ?? 'https://router.tangle.tools/v1'
|
|
155
155
|
return { baseUrl, key, model }
|
|
156
156
|
}
|
|
@@ -40,8 +40,8 @@ const WORKER_SUFFIX = [
|
|
|
40
40
|
'Take a clear position on the topic. Every factual claim must name the file it comes from.',
|
|
41
41
|
].join('\n')
|
|
42
42
|
|
|
43
|
-
// Judge model: Gemini
|
|
44
|
-
const JUDGE_MODEL = 'gemini-
|
|
43
|
+
// Judge model: Gemini 3.1 Pro preview via router, the model grade.py uses.
|
|
44
|
+
const JUDGE_MODEL = 'gemini-3.1-pro-preview'
|
|
45
45
|
|
|
46
46
|
interface TrataTaskMeta {
|
|
47
47
|
taskDir: string
|
|
@@ -203,10 +203,8 @@ async function callJudge(router: JudgeRouter, prompt: string, maxAttempts = 2):
|
|
|
203
203
|
model: {
|
|
204
204
|
provider: 'tangle-router',
|
|
205
205
|
default: router.model,
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
maxTokens: Number(process.env.JUDGE_MAX_TOKENS ?? 16384),
|
|
209
|
-
},
|
|
206
|
+
maxVisibleOutputTokens: Number(process.env.JUDGE_MAX_TOKENS ?? 16384),
|
|
207
|
+
metadata: { temperature: 0 },
|
|
210
208
|
},
|
|
211
209
|
},
|
|
212
210
|
},
|
|
@@ -18,9 +18,9 @@ import { type BenchCell, type BenchShot, printBenchmarksReport, runBenchmarks }
|
|
|
18
18
|
|
|
19
19
|
/** The matrix: three cells spanning harnesses, models, and transports. */
|
|
20
20
|
const cells: BenchCell[] = [
|
|
21
|
-
{ label: 'opencode/glm-
|
|
22
|
-
{ label: 'codex/gpt-
|
|
23
|
-
{ label: 'router/deepseek-v4-flash', model: 'deepseek-v4-flash', backend: 'router' },
|
|
21
|
+
{ label: 'opencode/glm-5.3', harness: 'opencode', model: 'glm-5.3', backend: 'sandbox' },
|
|
22
|
+
{ label: 'codex/gpt-6.1-sol', harness: 'codex', model: 'gpt-6.1-sol', backend: 'sandbox' },
|
|
23
|
+
{ label: 'router/deepseek-v4.1-flash', model: 'deepseek/deepseek-v4.1-flash', backend: 'router' },
|
|
24
24
|
]
|
|
25
25
|
|
|
26
26
|
async function live(): Promise<void> {
|
|
@@ -68,9 +68,9 @@ async function demo(): Promise<void> {
|
|
|
68
68
|
|
|
69
69
|
// Cell ability: opencode/glm solves the most, router the least — deterministic by task index.
|
|
70
70
|
const ability: Record<string, number> = {
|
|
71
|
-
'opencode/glm-
|
|
72
|
-
'codex/gpt-
|
|
73
|
-
'router/deepseek-v4-flash': 0.38,
|
|
71
|
+
'opencode/glm-5.3': 0.88,
|
|
72
|
+
'codex/gpt-6.1-sol': 0.62,
|
|
73
|
+
'router/deepseek-v4.1-flash': 0.38,
|
|
74
74
|
}
|
|
75
75
|
const shot: BenchShot = async ({ task, cell }) => {
|
|
76
76
|
const idx = Number(task.id.split('-').pop())
|
|
@@ -148,7 +148,7 @@ async function main(): Promise<void> {
|
|
|
148
148
|
routerKey,
|
|
149
149
|
workerProfile: benchRouterProfile(
|
|
150
150
|
'lean-proof-worker',
|
|
151
|
-
process.env.WORKER_MODEL ?? 'deepseek-v4-flash',
|
|
151
|
+
process.env.WORKER_MODEL ?? 'deepseek/deepseek-v4.1-flash',
|
|
152
152
|
{
|
|
153
153
|
systemPrompt: 'Construct and verify Lean proofs with the available checker before answering.',
|
|
154
154
|
maxTurns: 8,
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
* sampleThenRefine (both). Swap the `check` and this same file grades a tax return value,
|
|
9
9
|
* a rubric score, anything answer-shaped.
|
|
10
10
|
*
|
|
11
|
-
* Run from bench/ (needs a router key; default model deepseek-v4-flash):
|
|
11
|
+
* Run from bench/ (needs a router key; default model deepseek/deepseek-v4.1-flash):
|
|
12
12
|
* TANGLE_API_KEY=... WORKER_MODEL=gpt-4o-mini BUDGET=3 tsx src/examples/math-demo.mts
|
|
13
13
|
*/
|
|
14
14
|
import {
|
|
@@ -98,7 +98,7 @@ async function main(): Promise<void> {
|
|
|
98
98
|
routerKey,
|
|
99
99
|
workerProfile: benchRouterProfile(
|
|
100
100
|
'math-worker',
|
|
101
|
-
process.env.WORKER_MODEL ?? 'deepseek-v4-flash',
|
|
101
|
+
process.env.WORKER_MODEL ?? 'deepseek/deepseek-v4.1-flash',
|
|
102
102
|
{
|
|
103
103
|
systemPrompt: 'Solve the requested math task with the available tools and verify the result.',
|
|
104
104
|
maxTurns: 6,
|
|
@@ -99,7 +99,7 @@ async function main(): Promise<void> {
|
|
|
99
99
|
routerKey: process.env.TANGLE_API_KEY ?? '',
|
|
100
100
|
workerProfile: benchRouterProfile(
|
|
101
101
|
'strategy-demo-worker',
|
|
102
|
-
process.env.WORKER_MODEL ?? 'deepseek-v4-flash',
|
|
102
|
+
process.env.WORKER_MODEL ?? 'deepseek/deepseek-v4.1-flash',
|
|
103
103
|
{
|
|
104
104
|
systemPrompt: 'Use the available tools to complete and verify the task.',
|
|
105
105
|
maxTurns: 6,
|
package/src/gate-cli.mts
CHANGED
|
@@ -37,7 +37,7 @@ const defaultStrategies: ReadonlyArray<string> = [
|
|
|
37
37
|
async function main(): Promise<void> {
|
|
38
38
|
const benchKey = process.env.BENCH ?? 'enterpriseops-gym'
|
|
39
39
|
const adapter = resolveAdapter(benchKey)
|
|
40
|
-
const model = process.env.WORKER_MODEL ?? 'deepseek-v4-flash'
|
|
40
|
+
const model = process.env.WORKER_MODEL ?? 'deepseek/deepseek-v4.1-flash'
|
|
41
41
|
const routerBaseUrl = process.env.ROUTER_BASE ?? 'https://router.tangle.tools/v1'
|
|
42
42
|
const routerKey = must('TANGLE_API_KEY')
|
|
43
43
|
const k = Number(process.env.K ?? defaultStrategies.length)
|
|
@@ -18,7 +18,7 @@
|
|
|
18
18
|
* exit 0 admitted · 1 rejected · 2 malformed/infra
|
|
19
19
|
* Env: EVAL_GATE_BASE_URL (default https://router.tangle.tools/v1)
|
|
20
20
|
* EVAL_GATE_API_KEY (default $TANGLE_API_KEY)
|
|
21
|
-
* EVAL_GATE_MODEL (default
|
|
21
|
+
* EVAL_GATE_MODEL (default deepseek/deepseek-v4.1-flash)
|
|
22
22
|
*/
|
|
23
23
|
import { execSync } from 'node:child_process'
|
|
24
24
|
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
|
|
@@ -119,14 +119,14 @@ export async function discriminationGate(
|
|
|
119
119
|
): Promise<{ passed: boolean; detail: string }> {
|
|
120
120
|
const baseUrl = opts.gateBaseUrl ?? process.env.EVAL_GATE_BASE_URL ?? 'https://router.tangle.tools/v1'
|
|
121
121
|
const apiKey = opts.gateApiKey ?? process.env.EVAL_GATE_API_KEY ?? process.env.TANGLE_API_KEY
|
|
122
|
-
const model = opts.gateModel ?? process.env.EVAL_GATE_MODEL ?? 'deepseek-v4-flash'
|
|
122
|
+
const model = opts.gateModel ?? process.env.EVAL_GATE_MODEL ?? 'deepseek/deepseek-v4.1-flash'
|
|
123
123
|
if (!apiKey) throw new Error('discrimination gate needs EVAL_GATE_API_KEY (or TANGLE_API_KEY)')
|
|
124
124
|
const res = await runBenchRouterTurn(
|
|
125
125
|
{
|
|
126
126
|
routerBaseUrl: baseUrl,
|
|
127
127
|
routerKey: apiKey,
|
|
128
128
|
profile: {
|
|
129
|
-
name: 'generated-eval-parametric-check',
|
|
129
|
+
name: 'generated-eval-parametric-check', harness: 'cli-base',
|
|
130
130
|
model: { provider: 'tangle-router', default: model },
|
|
131
131
|
},
|
|
132
132
|
},
|
|
@@ -150,7 +150,7 @@ export async function certifyEval(candidate: GeneratedEval, opts: CertifyOpts =
|
|
|
150
150
|
schemaVersion: generatedEvalSchemaVersion,
|
|
151
151
|
groundingPassed: true,
|
|
152
152
|
parametricFailed: true,
|
|
153
|
-
parametricModel: opts.gateModel ?? process.env.EVAL_GATE_MODEL ?? 'deepseek-v4-flash',
|
|
153
|
+
parametricModel: opts.gateModel ?? process.env.EVAL_GATE_MODEL ?? 'deepseek/deepseek-v4.1-flash',
|
|
154
154
|
resolvedTarget: declaredTarget(candidate.setup),
|
|
155
155
|
certifiedAt: new Date().toISOString(),
|
|
156
156
|
certifier: certifierId,
|
|
@@ -39,7 +39,7 @@ function parseCell(spec: string): BenchCell {
|
|
|
39
39
|
async function main(): Promise<void> {
|
|
40
40
|
const benchmarks = (process.env.BENCHMARKS ?? '').split(',').map((s) => s.trim()).filter(Boolean)
|
|
41
41
|
if (benchmarks.length === 0) throw new Error('env BENCHMARKS is required (comma-separated registry keys, e.g. humaneval,swe-bench)')
|
|
42
|
-
const cells = (process.env.CELLS ?? process.env.WORKER_MODEL ?? 'deepseek-v4-flash')
|
|
42
|
+
const cells = (process.env.CELLS ?? process.env.WORKER_MODEL ?? 'deepseek-v4.1-flash')
|
|
43
43
|
.split(',').map((s) => s.trim()).filter(Boolean).map(parseCell)
|
|
44
44
|
|
|
45
45
|
const report = await runBenchmarks({
|
package/src/swe-self-improve.mts
CHANGED
|
@@ -25,8 +25,8 @@ async function main(): Promise<void> {
|
|
|
25
25
|
const routerKey = process.env.TANGLE_API_KEY
|
|
26
26
|
if (!routerKey) throw new Error('TANGLE_API_KEY required (worker + author call the router)')
|
|
27
27
|
const routerBaseUrl = process.env.ROUTER_BASE ?? 'https://router.tangle.tools/v1'
|
|
28
|
-
const workerModel = process.env.WORKER_MODEL ?? 'deepseek-v4-flash'
|
|
29
|
-
const authorModel = process.env.AUTHOR_MODEL ?? 'deepseek-v4-flash'
|
|
28
|
+
const workerModel = process.env.WORKER_MODEL ?? 'deepseek/deepseek-v4.1-flash'
|
|
29
|
+
const authorModel = process.env.AUTHOR_MODEL ?? 'deepseek/deepseek-v4.1-flash'
|
|
30
30
|
const innerTurns = Number(process.env.INNER_TURNS ?? 40)
|
|
31
31
|
const workerProfile: AgentProfile = {
|
|
32
32
|
name: 'swe-worker',
|
|
@@ -101,7 +101,7 @@ async function main(): Promise<void> {
|
|
|
101
101
|
profile: authorProfile(authorModel, 'swe-strategy-author'),
|
|
102
102
|
executor: { backend: 'router', routerBaseUrl, routerKey },
|
|
103
103
|
fallbackProfile: authorProfile(
|
|
104
|
-
process.env.AUTHOR_FALLBACK ?? 'deepseek-v4-flash',
|
|
104
|
+
process.env.AUTHOR_FALLBACK ?? 'deepseek/deepseek-v4.1-flash',
|
|
105
105
|
'swe-strategy-author-fallback',
|
|
106
106
|
),
|
|
107
107
|
},
|
package/src/terminal-compare.ts
CHANGED
|
@@ -48,7 +48,7 @@ const PROFILE_AGENT_IMPORT = 'tb_agents.opencode_router_agent:OpenCodeRouterAgen
|
|
|
48
48
|
const CORPUS = process.env.CORPUS ?? join(BENCH_ROOT, 'corpus', 'terminal.jsonl')
|
|
49
49
|
|
|
50
50
|
const DATASET = process.env.TB_DATASET ?? 'terminal-bench-core==0.1.1'
|
|
51
|
-
const MODEL = process.env.TB_MODEL ?? 'deepseek-v4-flash'
|
|
51
|
+
const MODEL = process.env.TB_MODEL ?? 'deepseek-v4.1-flash'
|
|
52
52
|
const PROVIDER = process.env.TB_PROVIDER ?? 'tangle-router'
|
|
53
53
|
const PROFILE = agentProfileSchema.parse({
|
|
54
54
|
name: 'terminal-compare-worker',
|