@tangle-network/agent-bench 0.14.4 → 1.0.2
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 +46 -0
- package/README.md +2 -3
- package/dist/adapters.d.ts +2 -5
- package/dist/adapters.js +3 -4
- package/dist/benchmarks/_harness.d.ts +17 -20
- package/dist/benchmarks/_harness.js +4 -4
- package/dist/benchmarks/_harness.js.map +1 -1
- package/dist/benchmarks/aec-bench.d.ts +1 -4
- package/dist/benchmarks/aec-bench.js +1 -2
- package/dist/benchmarks/agentbench.d.ts +2 -5
- package/dist/benchmarks/agentbench.js +1 -2
- package/dist/benchmarks/appworld.d.ts +8 -10
- package/dist/benchmarks/appworld.js +23 -23
- package/dist/benchmarks/appworld.js.map +1 -1
- package/dist/benchmarks/bfcl.d.ts +2 -5
- package/dist/benchmarks/bfcl.js +1 -2
- package/dist/benchmarks/cad-design.d.ts +2 -5
- package/dist/benchmarks/cad-design.js +2 -3
- package/dist/benchmarks/cad-design.js.map +1 -1
- package/dist/benchmarks/cadbench.d.ts +1 -4
- package/dist/benchmarks/cadbench.js +1 -2
- package/dist/benchmarks/cadgenbench.d.ts +1 -4
- package/dist/benchmarks/cadgenbench.js +1 -2
- package/dist/benchmarks/commit0.d.ts +2 -5
- package/dist/benchmarks/commit0.js +1 -2
- package/dist/benchmarks/crag.d.ts +1 -4
- package/dist/benchmarks/crag.js +3 -3
- package/dist/benchmarks/crag.js.map +1 -1
- package/dist/benchmarks/dabstep.d.ts +2 -5
- package/dist/benchmarks/dabstep.js +2 -3
- package/dist/benchmarks/dabstep.js.map +1 -1
- package/dist/benchmarks/enterpriseops-gym.d.ts +2 -5
- package/dist/benchmarks/enterpriseops-gym.js +1 -2
- package/dist/benchmarks/finresearchbench.d.ts +2 -5
- package/dist/benchmarks/finresearchbench.js +2 -3
- package/dist/benchmarks/finsearchcomp.d.ts +2 -5
- package/dist/benchmarks/finsearchcomp.js +4 -4
- package/dist/benchmarks/finsearchcomp.js.map +1 -1
- package/dist/benchmarks/frames.d.ts +3 -19
- package/dist/benchmarks/frames.js +13 -39
- package/dist/benchmarks/frames.js.map +1 -1
- package/dist/benchmarks/hotpotqa.d.ts +4 -14
- package/dist/benchmarks/hotpotqa.js +12 -32
- package/dist/benchmarks/hotpotqa.js.map +1 -1
- package/dist/benchmarks/humaneval.d.ts +9 -12
- package/dist/benchmarks/humaneval.js +2 -3
- package/dist/benchmarks/humaneval.js.map +1 -1
- package/dist/benchmarks/mcad-bench.d.ts +13 -16
- package/dist/benchmarks/mcad-bench.js +2 -3
- package/dist/benchmarks/mcad-bench.js.map +1 -1
- package/dist/benchmarks/mcad-cq-bench.d.ts +17 -20
- package/dist/benchmarks/mcad-cq-bench.js +2 -3
- package/dist/benchmarks/mcad-cq-bench.js.map +1 -1
- package/dist/benchmarks/mcad-cq-golds.d.ts +2 -5
- package/dist/benchmarks/mcad-cq-golds.js +1 -2
- package/dist/benchmarks/mcad-golds.d.ts +1 -4
- package/dist/benchmarks/mcad-golds.js +0 -1
- package/dist/benchmarks/mcad-tasks.d.ts +5 -8
- package/dist/benchmarks/mcad-tasks.js +7 -8
- package/dist/benchmarks/mcad-tasks.js.map +1 -1
- package/dist/benchmarks/mind2web.d.ts +3 -5
- package/dist/benchmarks/mind2web.js +2 -3
- package/dist/benchmarks/mind2web.js.map +1 -1
- package/dist/benchmarks/nomiracl.d.ts +1 -4
- package/dist/benchmarks/nomiracl.js +1 -2
- package/dist/benchmarks/open-rag-bench.d.ts +1 -4
- package/dist/benchmarks/open-rag-bench.js +3 -3
- package/dist/benchmarks/open-rag-bench.js.map +1 -1
- package/dist/benchmarks/programbench.d.ts +2 -5
- package/dist/benchmarks/programbench.js +1 -2
- package/dist/benchmarks/rag-shared.d.ts +30 -22
- package/dist/benchmarks/rag-shared.js +8 -2
- package/dist/benchmarks/rag-shared.js.map +1 -1
- package/dist/benchmarks/ragbench.d.ts +1 -4
- package/dist/benchmarks/ragbench.js +3 -3
- package/dist/benchmarks/ragbench.js.map +1 -1
- package/dist/benchmarks/simpleqa.d.ts +2 -18
- package/dist/benchmarks/simpleqa.js +5 -31
- package/dist/benchmarks/simpleqa.js.map +1 -1
- package/dist/benchmarks/swe-bench.d.ts +7 -10
- package/dist/benchmarks/swe-bench.js +4 -4
- package/dist/benchmarks/swe-bench.js.map +1 -1
- package/dist/benchmarks/t2-ragbench.d.ts +1 -4
- package/dist/benchmarks/t2-ragbench.js +3 -3
- package/dist/benchmarks/t2-ragbench.js.map +1 -1
- package/dist/benchmarks/tau-bench-shared.d.ts +5 -8
- package/dist/benchmarks/tau-bench-shared.js +4 -4
- package/dist/benchmarks/tau-bench-shared.js.map +1 -1
- package/dist/benchmarks/tau2-bench.d.ts +2 -5
- package/dist/benchmarks/tau2-bench.js +1 -2
- package/dist/benchmarks/tau3-banking.d.ts +1 -4
- package/dist/benchmarks/tau3-banking.js +1 -2
- package/dist/benchmarks/terminal-bench.d.ts +1 -4
- package/dist/benchmarks/terminal-bench.js +4 -4
- package/dist/benchmarks/terminal-bench.js.map +1 -1
- package/dist/benchmarks/toollm.d.ts +2 -5
- package/dist/benchmarks/toollm.js +1 -2
- package/dist/benchmarks/trata-hedge.d.ts +1 -4
- package/dist/benchmarks/trata-hedge.js +2 -3
- package/dist/benchmarks/types.d.ts +6 -9
- package/dist/benchmarks/webarena-verified.d.ts +2 -5
- package/dist/benchmarks/webarena-verified.js +1 -2
- package/dist/{cadbench-BRF-59Mt.js → cadbench-DhAndllg.js} +4 -6
- package/dist/cadbench-DhAndllg.js.map +1 -0
- package/dist/{cadgenbench-DXtGkuW3.js → cadgenbench-Tvk16YKT.js} +15 -5
- package/dist/cadgenbench-Tvk16YKT.js.map +1 -0
- package/dist/index.d.ts +8 -18
- package/dist/index.js +16 -24
- package/dist/index.js.map +1 -1
- package/dist/{router-turn-uTYO6KQ1.js → router-turn-DNbQ_GjQ.js} +2 -3
- package/dist/router-turn-DNbQ_GjQ.js.map +1 -0
- package/fixtures/pier-agent/no-model-task/pre_artifacts.sh +0 -0
- package/fixtures/pier-agent/no-model-task/tests/test.sh +0 -0
- package/package.json +10 -10
- package/pier_agents/tangle_candidate.py +15 -23
- package/scripts/run-package-tests.mjs +8 -15
- package/src/atom-mcp-e2e.mts +2 -2
- package/src/benchmarks/frames.ts +10 -44
- package/src/benchmarks/hotpotqa.ts +9 -29
- package/src/benchmarks/rag-shared.ts +12 -0
- package/src/benchmarks/simpleqa.ts +2 -36
- package/src/commit0-prereqs.sh +0 -0
- package/src/corpus-replay.mts +8 -8
- package/src/corpus-report.mts +21 -21
- package/src/corpus.test.mts +5 -5
- package/src/corpus.ts +16 -16
- package/src/directives.ts +0 -38
- package/src/examples/lean-verify.ts +1 -1
- package/src/gate.ts +7 -7
- package/src/generate-eval/certify.ts +2 -2
- package/src/index.ts +1 -0
- package/src/refine-loop.ts +5 -5
- package/src/resolve-client.ts +1 -1
- package/src/router-turn.ts +3 -11
- package/src/run-pool.ts +1 -1
- package/src/runtime-hook-recorder.ts +2 -2
- package/src/search-bench/tasks.ts +1 -1
- package/src/selector.test.mts +13 -13
- package/src/selector.ts +19 -19
- package/src/swe-bench-env.ts +4 -12
- package/src/swe-jail.ts +5 -156
- package/src/swe-structural-judge-policy.ts +3 -3
- package/src/swe-structural-policy.ts +3 -3
- package/src/swe-structural-provenance.ts +4 -4
- package/src/terminal-compare.ts +10 -10
- package/src/worker-blender.ts +2 -106
- package/src/worker-build123d.ts +2 -81
- package/tb_agents/opencode_router_agent.py +1 -1
- package/dist/cadbench-BRF-59Mt.js.map +0 -1
- package/dist/cadgenbench-DXtGkuW3.js.map +0 -1
- package/dist/router-turn-uTYO6KQ1.js.map +0 -1
- package/scripts/cadbench_prepare.py +0 -22
- package/scripts/cadgenbench_hard_parts.py +0 -48
- package/scripts/clbench_codebase_judge.py +0 -73
- package/scripts/render-gate-chart.mjs +0 -176
- package/scripts/trata-hedge/README.md +0 -57
- package/scripts/trata-hedge/run.sh +0 -64
- package/src/cloud-loop.mts +0 -156
- package/src/coordination-mcp-container-reach.mts +0 -182
- package/src/fleet.mts +0 -143
- package/src/hev-structural.mts +0 -697
- package/src/humaneval-gate.mts +0 -220
- package/src/mbpp-structural.mts +0 -676
- package/src/mcp-mount-probe.mts +0 -141
- package/src/profiles.ts +0 -128
- package/src/research-gate.mts +0 -132
- package/src/research-shot.ts +0 -144
- package/src/router-executor.ts +0 -51
- package/src/sandbox-run.ts +0 -108
- package/src/search-bench/bridge.ts +0 -182
- package/src/search-bench/export.mts +0 -0
- package/src/search-bench/parametric-check.mts +0 -78
- package/src/search-bench/profiles.ts +0 -113
- package/src/search-bench/run.mts +0 -286
- package/src/search-bench/tasks-fresh.ts +0 -688
- package/src/smoke-structural-rollout.mts +0 -415
- package/src/stats.mts +0 -90
- package/src/swe-code-improve.mts +0 -306
- package/src/swe-improve.mts +0 -284
- package/src/swe-structural.mts +0 -707
- package/src/tb-container-executor.mts +0 -266
- package/src/tb-container-executor.test.mts +0 -134
- package/src/tb-supervisor-sidecar.mts +0 -208
- package/src/trata-gepa.mts +0 -381
- package/src/trata-hedge-solve.mts +0 -81
- package/tb_agents/opencode_refine_agent.py +0 -117
- package/tb_agents/opencode_supervisor_agent.py +0 -239
package/src/trata-gepa.mts
DELETED
|
@@ -1,381 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Official GEPA prompt optimization for Trata hedge-bench.
|
|
3
|
-
*
|
|
4
|
-
* The optimization surface is the system prompt given to the financial analyst
|
|
5
|
-
* worker. GEPA reflects on which rubric themes were missed across training tasks
|
|
6
|
-
* and proposes improved system prompts, learning to instruct the model to
|
|
7
|
-
* extract specific quantitative claims, cover multiple analytical themes, and
|
|
8
|
-
* cite named evidence. Candidate selection and final testing use disjoint data.
|
|
9
|
-
*
|
|
10
|
-
* The surface evolves beyond a bare system instruction: GEPA naturally discovers
|
|
11
|
-
* that it can add few-shot analytical patterns, calculation templates, and
|
|
12
|
-
* structured coverage checklists, effectively skill-creating without
|
|
13
|
-
* hand-engineering. Set K_ROUNDS=2 to add a self-critique refine pass.
|
|
14
|
-
*
|
|
15
|
-
* Usage:
|
|
16
|
-
* TRATA_BENCH_ROOT=/tmp/trata-hedge-bench \
|
|
17
|
-
* JUDGE_MODEL=gemini-2.5-flash WORKER_MODEL=deepseek-v4-flash \
|
|
18
|
-
* REFLECT_MODEL=gemini-2.5-pro \
|
|
19
|
-
* TRAIN_N=70 SELECTION_N=16 TEST_N=16 MAX_EVALUATIONS=12 CONCURRENCY=8 \
|
|
20
|
-
* dotenvx run -f ~/company/devops/secrets/agent-state.env -- \
|
|
21
|
-
* pnpm exec tsx bench/src/trata-gepa.mts
|
|
22
|
-
*
|
|
23
|
-
* Key env vars:
|
|
24
|
-
* TRATA_BENCH_ROOT cloned trata-hedge-bench (default /tmp/trata-hedge-bench)
|
|
25
|
-
* WORKER_MODEL analyst model (default deepseek-v4-flash)
|
|
26
|
-
* JUDGE_MODEL judge model in trata adapter (default gemini-2.5-flash)
|
|
27
|
-
* REFLECT_MODEL GEPA reflection model (default gemini-2.5-pro)
|
|
28
|
-
* TRAIN_N training tasks (default 70)
|
|
29
|
-
* SELECTION_N optimizer selection tasks (default 16)
|
|
30
|
-
* TEST_N untouched final comparison tasks (default 16)
|
|
31
|
-
* MAX_EVALUATIONS GEPA callback evaluations (default 12)
|
|
32
|
-
* MAX_PROPOSER_COST_USD GEPA proposal budget (default 5)
|
|
33
|
-
* REPS reps per scenario (default 1)
|
|
34
|
-
* CONCURRENCY parallel worker slots (default 8)
|
|
35
|
-
* K_ROUNDS 1=single-shot, 2=analysis+self-critique (default 1)
|
|
36
|
-
* BASELINE_DIRECTIVE override the starting system prompt
|
|
37
|
-
* CORPUS path to write JSONL run records (optional)
|
|
38
|
-
*/
|
|
39
|
-
|
|
40
|
-
import {
|
|
41
|
-
canonicalCandidateDigest,
|
|
42
|
-
type AgentProfile,
|
|
43
|
-
} from '@tangle-network/agent-interface'
|
|
44
|
-
import type {
|
|
45
|
-
DispatchContext,
|
|
46
|
-
JudgeConfig,
|
|
47
|
-
JudgeScore,
|
|
48
|
-
Scenario,
|
|
49
|
-
} from '@tangle-network/agent-eval/campaign'
|
|
50
|
-
import {
|
|
51
|
-
improve,
|
|
52
|
-
officialGepa,
|
|
53
|
-
type ReadonlyAgentProfile,
|
|
54
|
-
} from '@tangle-network/agent-runtime'
|
|
55
|
-
import { appendFileSync, writeFileSync } from 'node:fs'
|
|
56
|
-
import { createTrataHedgeAdapter } from './benchmarks/trata-hedge'
|
|
57
|
-
import type { BenchTask } from './benchmarks/types'
|
|
58
|
-
import {
|
|
59
|
-
assertCompleteCost,
|
|
60
|
-
officialOptimizerModel,
|
|
61
|
-
requiredTokenPricing,
|
|
62
|
-
} from './official-optimizer-config.mjs'
|
|
63
|
-
import { runBenchRouterTurn } from './router-turn'
|
|
64
|
-
|
|
65
|
-
interface TrataScenario extends Scenario {
|
|
66
|
-
task: BenchTask
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
function must(name: string): string {
|
|
70
|
-
const v = process.env[name]
|
|
71
|
-
if (!v) throw new Error(`env ${name} is required`)
|
|
72
|
-
return v
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
function positiveInteger(name: string, fallback: number): number {
|
|
76
|
-
const value = Number(process.env[name] ?? fallback)
|
|
77
|
-
if (!Number.isSafeInteger(value) || value <= 0) {
|
|
78
|
-
throw new Error(`env ${name} must be a positive integer`)
|
|
79
|
-
}
|
|
80
|
-
return value
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
function positiveNumber(name: string, fallback: number): number {
|
|
84
|
-
const value = Number(process.env[name] ?? fallback)
|
|
85
|
-
if (!Number.isFinite(value) || value <= 0) {
|
|
86
|
-
throw new Error(`env ${name} must be a positive number`)
|
|
87
|
-
}
|
|
88
|
-
return value
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
// GEPA-optimised baseline — the best surface found across 9 runs (+8.6pp on holdout, 2 independent
|
|
92
|
-
// confirmations). Future GEPA runs start from here; BASELINE_DIRECTIVE overrides if you want to
|
|
93
|
-
// experiment from a different starting point.
|
|
94
|
-
const DEFAULT_TRATA_SYSTEM = [
|
|
95
|
-
'You are a senior financial analyst producing a structured investment memo.',
|
|
96
|
-
'Begin your response with exactly "ANALYSIS:" on its own line (nothing before it), then write your full analysis.',
|
|
97
|
-
'Structure your analysis with clearly labeled sections for each distinct analytical theme',
|
|
98
|
-
'(e.g., valuation, capital allocation, competitive dynamics, risk factors)',
|
|
99
|
-
'so that no major investment consideration is merged or omitted.',
|
|
100
|
-
'Benchmark the company explicitly against named sector peers, citing specific metrics such as',
|
|
101
|
-
'EV/EBITDA, P/E ratios, margin differentials, and growth premiums from the peer financial files.',
|
|
102
|
-
'Every factual claim must cite the filename (e.g., "per earnings_call/apo_q4_2025_earnings_call.txt").',
|
|
103
|
-
'Identify and verbatim-cite specific numerical targets from management guidance such as',
|
|
104
|
-
'earnings per share targets, margin percentages, growth rates, or AUM figures rather than paraphrasing approximately.',
|
|
105
|
-
'When evaluating capital allocation options, explicitly compute implied returns or internal rates of return (IRRs),',
|
|
106
|
-
'showing the arithmetic using price levels and targets from the source data.',
|
|
107
|
-
'Take a clear, decisive position — do not hedge with "it depends". Reconcile conflicting data points explicitly.',
|
|
108
|
-
].join(' ')
|
|
109
|
-
|
|
110
|
-
// Refine round instruction — used only when K_ROUNDS >= 2.
|
|
111
|
-
const REFINE_INSTRUCTION = [
|
|
112
|
-
'Review your analysis above. For each distinct analytical theme in the investment brief,',
|
|
113
|
-
'verify you have a dedicated section with at least one specific quantitative claim (a named figure,',
|
|
114
|
-
'percentage, ratio, or calculation) from the cited data files. Add any missing themes.',
|
|
115
|
-
'Rewrite any section that only gestures at a theme without a specific supporting data point.',
|
|
116
|
-
].join(' ')
|
|
117
|
-
|
|
118
|
-
async function chatComplete(
|
|
119
|
-
baseUrl: string,
|
|
120
|
-
key: string,
|
|
121
|
-
model: string,
|
|
122
|
-
maxTokens: number,
|
|
123
|
-
messages: Array<{ role: string; content: string }>,
|
|
124
|
-
signal: AbortSignal,
|
|
125
|
-
): Promise<{ content: string; usage?: { input: number; output: number } }> {
|
|
126
|
-
const system = messages.find((message) => message.role === 'system')?.content
|
|
127
|
-
const result = await runBenchRouterTurn(
|
|
128
|
-
{
|
|
129
|
-
routerBaseUrl: baseUrl,
|
|
130
|
-
routerKey: key,
|
|
131
|
-
profile: {
|
|
132
|
-
name: 'trata-gepa-worker',
|
|
133
|
-
harness: 'cli-base',
|
|
134
|
-
model: {
|
|
135
|
-
provider: 'tangle-router',
|
|
136
|
-
default: model,
|
|
137
|
-
metadata: { temperature: 0 },
|
|
138
|
-
maxVisibleOutputTokens: maxTokens,
|
|
139
|
-
},
|
|
140
|
-
...(system ? { prompt: { systemPrompt: system } } : {}),
|
|
141
|
-
},
|
|
142
|
-
signal,
|
|
143
|
-
},
|
|
144
|
-
{ messages: messages.filter((message) => message.role !== 'system') },
|
|
145
|
-
)
|
|
146
|
-
return {
|
|
147
|
-
content: result.finalText,
|
|
148
|
-
...(result.usage.tokensKnown === false
|
|
149
|
-
? {}
|
|
150
|
-
: { usage: { input: result.usage.input, output: result.usage.output } }),
|
|
151
|
-
}
|
|
152
|
-
}
|
|
153
|
-
|
|
154
|
-
async function main(): Promise<void> {
|
|
155
|
-
if (process.env.DRYRUN) {
|
|
156
|
-
console.log(
|
|
157
|
-
`DRYRUN: imports OK (improve=${typeof improve}, officialGepa=${typeof officialGepa})`,
|
|
158
|
-
)
|
|
159
|
-
return
|
|
160
|
-
}
|
|
161
|
-
|
|
162
|
-
const adapter = createTrataHedgeAdapter()
|
|
163
|
-
await adapter.preflight()
|
|
164
|
-
|
|
165
|
-
const model = process.env.WORKER_MODEL ?? 'deepseek-v4-flash'
|
|
166
|
-
const reflectModel = process.env.REFLECT_MODEL ?? 'deepseek-v4-flash'
|
|
167
|
-
const routerBaseUrl = process.env.ROUTER_BASE ?? 'https://router.tangle.tools/v1'
|
|
168
|
-
const routerKey = must('TANGLE_API_KEY')
|
|
169
|
-
const reflectBaseUrl = process.env.REFLECT_BASE ?? routerBaseUrl
|
|
170
|
-
const reflectKey = process.env.REFLECT_KEY ?? routerKey
|
|
171
|
-
const trainN = positiveInteger('TRAIN_N', 70)
|
|
172
|
-
const selectionN = positiveInteger('SELECTION_N', 16)
|
|
173
|
-
const testN = positiveInteger('TEST_N', 16)
|
|
174
|
-
const kRounds = positiveInteger('K_ROUNDS', 1)
|
|
175
|
-
const maxEvaluations = positiveInteger('MAX_EVALUATIONS', 12)
|
|
176
|
-
const maxProposerCostUsd = positiveNumber('MAX_PROPOSER_COST_USD', 5)
|
|
177
|
-
const maxConcurrency = positiveInteger('CONCURRENCY', 8)
|
|
178
|
-
const reps = positiveInteger('REPS', 1)
|
|
179
|
-
const workerMaxTokens = positiveInteger('MAX_TOKENS', 4096)
|
|
180
|
-
const reflectMaxTokens = positiveInteger('REFLECT_MAX_TOKENS', 8192)
|
|
181
|
-
const corpusPath = process.env.CORPUS
|
|
182
|
-
const baselineSurface = process.env.BASELINE_DIRECTIVE ?? DEFAULT_TRATA_SYSTEM
|
|
183
|
-
const runDir = process.env.RUN_DIR ?? '.runs/trata-official-gepa'
|
|
184
|
-
const workerPricing = requiredTokenPricing(process.env, 'WORKER')
|
|
185
|
-
const optimizer = officialOptimizerModel({
|
|
186
|
-
env: process.env,
|
|
187
|
-
model: reflectModel,
|
|
188
|
-
baseUrl: reflectBaseUrl,
|
|
189
|
-
apiKey: reflectKey,
|
|
190
|
-
maxCostUsd: maxProposerCostUsd,
|
|
191
|
-
maxOutputTokensPerRequest: reflectMaxTokens,
|
|
192
|
-
})
|
|
193
|
-
|
|
194
|
-
// Hash-shuffle by task id so all three partitions carry the same difficulty mix.
|
|
195
|
-
const requestedTasks = trainN + selectionN + testN
|
|
196
|
-
const tasks = await adapter.loadTasks({ limit: requestedTasks })
|
|
197
|
-
if (tasks.length !== requestedTasks) {
|
|
198
|
-
throw new Error(
|
|
199
|
-
`Trata returned ${tasks.length} tasks; ${requestedTasks} are required for exact train/selection/test partitions`,
|
|
200
|
-
)
|
|
201
|
-
}
|
|
202
|
-
const idHash = (s: string): number => {
|
|
203
|
-
let h = 2166136261
|
|
204
|
-
for (let i = 0; i < s.length; i += 1) {
|
|
205
|
-
h ^= s.charCodeAt(i)
|
|
206
|
-
h = Math.imul(h, 16777619)
|
|
207
|
-
}
|
|
208
|
-
return h >>> 0
|
|
209
|
-
}
|
|
210
|
-
tasks.sort((a, b) => idHash(a.id) - idHash(b.id) || a.id.localeCompare(b.id))
|
|
211
|
-
const train = tasks.slice(0, trainN)
|
|
212
|
-
const selection = tasks.slice(trainN, trainN + selectionN)
|
|
213
|
-
const test = tasks.slice(trainN + selectionN)
|
|
214
|
-
const toScenario = (t: BenchTask): TrataScenario => ({ id: t.id, kind: 'trata-hedge', task: t })
|
|
215
|
-
|
|
216
|
-
console.log(
|
|
217
|
-
`[trata-gepa] worker=${model} reflect=${reflectModel} rounds=${kRounds} train=${train.length} selection=${selection.length} test=${test.length}`,
|
|
218
|
-
)
|
|
219
|
-
|
|
220
|
-
// Run the financial analyst worker under the candidate surface.
|
|
221
|
-
// For K_ROUNDS=2, a second round asks the model to review its own coverage.
|
|
222
|
-
// Every provider call reports its returned usage through the campaign ledger.
|
|
223
|
-
const runPaidCompletion = async (
|
|
224
|
-
ctx: DispatchContext,
|
|
225
|
-
actor: string,
|
|
226
|
-
messages: Array<{ role: string; content: string }>,
|
|
227
|
-
): Promise<{ content: string; usage?: { input: number; output: number } }> => {
|
|
228
|
-
const paid = await ctx.cost.runPaidCall({
|
|
229
|
-
actor,
|
|
230
|
-
model,
|
|
231
|
-
execute: (signal) =>
|
|
232
|
-
chatComplete(routerBaseUrl, routerKey, model, workerMaxTokens, messages, signal),
|
|
233
|
-
receipt: (result) => ({
|
|
234
|
-
model,
|
|
235
|
-
inputTokens: result.usage?.input ?? 0,
|
|
236
|
-
outputTokens: result.usage?.output ?? 0,
|
|
237
|
-
customTokenPricing: workerPricing,
|
|
238
|
-
...(result.usage ? {} : { usageUnknown: true }),
|
|
239
|
-
}),
|
|
240
|
-
})
|
|
241
|
-
if (!paid.succeeded) throw paid.error
|
|
242
|
-
return paid.value
|
|
243
|
-
}
|
|
244
|
-
|
|
245
|
-
const runWithSurface = async (
|
|
246
|
-
candidate: ReadonlyAgentProfile,
|
|
247
|
-
scenario: TrataScenario,
|
|
248
|
-
ctx: DispatchContext,
|
|
249
|
-
): Promise<string> => {
|
|
250
|
-
const systemPrompt = candidate.prompt?.systemPrompt
|
|
251
|
-
if (systemPrompt === undefined) throw new Error('Trata candidate profile has no system prompt')
|
|
252
|
-
// Round 1: initial analysis under the candidate system prompt.
|
|
253
|
-
const r1 = await runPaidCompletion(ctx, 'trata-worker-round-1', [
|
|
254
|
-
{ role: 'system', content: systemPrompt },
|
|
255
|
-
{ role: 'user', content: scenario.task.prompt },
|
|
256
|
-
])
|
|
257
|
-
let answer = r1.content
|
|
258
|
-
|
|
259
|
-
// Round 2 (optional): self-critique for rubric coverage.
|
|
260
|
-
if (kRounds >= 2 && answer.trim()) {
|
|
261
|
-
const r2 = await runPaidCompletion(ctx, 'trata-worker-round-2', [
|
|
262
|
-
{ role: 'system', content: systemPrompt },
|
|
263
|
-
{ role: 'user', content: scenario.task.prompt },
|
|
264
|
-
{ role: 'assistant', content: answer },
|
|
265
|
-
{ role: 'user', content: REFINE_INSTRUCTION },
|
|
266
|
-
])
|
|
267
|
-
if (r2.content.trim()) answer = r2.content
|
|
268
|
-
}
|
|
269
|
-
|
|
270
|
-
if (corpusPath) {
|
|
271
|
-
appendFileSync(
|
|
272
|
-
corpusPath,
|
|
273
|
-
JSON.stringify({ benchmark: 'trata-gepa', instanceId: scenario.task.id, model, answer: answer.slice(0, 500) }) +
|
|
274
|
-
'\n',
|
|
275
|
-
)
|
|
276
|
-
}
|
|
277
|
-
return answer
|
|
278
|
-
}
|
|
279
|
-
|
|
280
|
-
// Judge: wraps the Trata 3-stage judge. Returns partial-credit score (0/0.25/0.5/0.75/1.0).
|
|
281
|
-
const judge: JudgeConfig<string, TrataScenario> = {
|
|
282
|
-
name: 'trata-hedge-judge',
|
|
283
|
-
dimensions: [
|
|
284
|
-
{ key: 'score', description: 'rubric theme coverage fraction (rawScore/4)' },
|
|
285
|
-
{ key: 'resolved', description: 'all themes hit + synthesis (rawScore=4)' },
|
|
286
|
-
],
|
|
287
|
-
async score({ artifact, scenario }): Promise<JudgeScore> {
|
|
288
|
-
if (!artifact.trim()) {
|
|
289
|
-
return { dimensions: { score: 0, resolved: 0 }, composite: 0, notes: 'empty artifact' }
|
|
290
|
-
}
|
|
291
|
-
const verdict = await adapter.judge(scenario.task, artifact)
|
|
292
|
-
const sc = typeof verdict.score === 'number' ? verdict.score : verdict.resolved ? 1 : 0
|
|
293
|
-
return {
|
|
294
|
-
dimensions: { score: sc, resolved: verdict.resolved ? 1 : 0 },
|
|
295
|
-
composite: sc,
|
|
296
|
-
notes: verdict.detail ?? '',
|
|
297
|
-
}
|
|
298
|
-
},
|
|
299
|
-
}
|
|
300
|
-
|
|
301
|
-
const profile: AgentProfile = {
|
|
302
|
-
name: 'trata-financial-analyst',
|
|
303
|
-
prompt: { systemPrompt: baselineSurface },
|
|
304
|
-
}
|
|
305
|
-
const result = await improve(profile, {
|
|
306
|
-
surface: 'prompt',
|
|
307
|
-
executionRef: canonicalCandidateDigest({
|
|
308
|
-
callback: 'bench/trata-gepa',
|
|
309
|
-
model,
|
|
310
|
-
endpoint: new URL(routerBaseUrl).origin,
|
|
311
|
-
maxTokens: workerMaxTokens,
|
|
312
|
-
rounds: kRounds,
|
|
313
|
-
judgeModel: process.env.JUDGE_MODEL ?? 'adapter-default',
|
|
314
|
-
}),
|
|
315
|
-
method: officialGepa<TrataScenario, string>({
|
|
316
|
-
objective:
|
|
317
|
-
'Improve the complete system instruction for a financial analyst that writes evidence-backed investment memos.',
|
|
318
|
-
background:
|
|
319
|
-
'The judge awards partial credit for covering every requested analytical theme with specific quantitative claims, named peer comparisons, explicit calculations, source citations, and a decisive synthesis. Preserve the required ANALYSIS: prefix.',
|
|
320
|
-
recipe: {
|
|
321
|
-
kind: 'engine',
|
|
322
|
-
run: {
|
|
323
|
-
engine: 'gepa',
|
|
324
|
-
maxEvaluations,
|
|
325
|
-
maxProposerCostUsd,
|
|
326
|
-
},
|
|
327
|
-
},
|
|
328
|
-
optimizer,
|
|
329
|
-
resume: 'if-compatible',
|
|
330
|
-
trustResumeState: true,
|
|
331
|
-
describeScenario: (scenario) => ({
|
|
332
|
-
id: scenario.id,
|
|
333
|
-
prompt: scenario.task.prompt,
|
|
334
|
-
}),
|
|
335
|
-
describeArtifact: (artifact) => ({ answer: artifact.slice(-4000) }),
|
|
336
|
-
}),
|
|
337
|
-
trainScenarios: train.map(toScenario),
|
|
338
|
-
selectionScenarios: selection.map(toScenario),
|
|
339
|
-
testScenarios: test.map(toScenario),
|
|
340
|
-
judges: [judge],
|
|
341
|
-
agent: runWithSurface,
|
|
342
|
-
expectUsage: 'warn',
|
|
343
|
-
maxConcurrency,
|
|
344
|
-
reps,
|
|
345
|
-
runDir,
|
|
346
|
-
optimizationRunOptions: {
|
|
347
|
-
expectUsage: 'warn',
|
|
348
|
-
maxConcurrency,
|
|
349
|
-
reps,
|
|
350
|
-
},
|
|
351
|
-
})
|
|
352
|
-
|
|
353
|
-
assertCompleteCost('Trata official GEPA run', result.cost)
|
|
354
|
-
console.log('\n=== trata-gepa RESULT ===')
|
|
355
|
-
const improved = result.decision === 'ship'
|
|
356
|
-
console.log(` baseline test mean: ${(result.raw.best.baselineComposite * 100).toFixed(1)}%`)
|
|
357
|
-
console.log(` winner test mean: ${(result.raw.best.winnerComposite * 100).toFixed(1)}%`)
|
|
358
|
-
console.log(` test delta: ${(result.lift * 100).toFixed(1)} pp`)
|
|
359
|
-
console.log(
|
|
360
|
-
` 95% interval: [${(result.liftInterval.low * 100).toFixed(1)}, ${(result.liftInterval.high * 100).toFixed(1)}] pp`,
|
|
361
|
-
)
|
|
362
|
-
console.log(` decision: ${result.decision}`)
|
|
363
|
-
console.log(` cost: ${JSON.stringify(result.cost)}`)
|
|
364
|
-
|
|
365
|
-
const winnerSurface = String(result.candidate.value)
|
|
366
|
-
if (improved) {
|
|
367
|
-
console.log(`\n PROMOTED SYSTEM PROMPT:\n${winnerSurface}`)
|
|
368
|
-
} else {
|
|
369
|
-
console.log(' kept baseline (the final-test interval did not clear zero)')
|
|
370
|
-
console.log(`\n BEST CANDIDATE SURFACE (set as BASELINE_DIRECTIVE to seed next run):\n${winnerSurface}`)
|
|
371
|
-
}
|
|
372
|
-
try {
|
|
373
|
-
writeFileSync('/tmp/trata-gepa-winner-surface.txt', winnerSurface)
|
|
374
|
-
console.log('\n (winner surface written to /tmp/trata-gepa-winner-surface.txt)')
|
|
375
|
-
} catch { /* non-fatal */ }
|
|
376
|
-
}
|
|
377
|
-
|
|
378
|
-
main().catch((err) => {
|
|
379
|
-
console.error(err instanceof Error ? (err.stack ?? err.message) : String(err))
|
|
380
|
-
process.exit(1)
|
|
381
|
-
})
|
|
@@ -1,81 +0,0 @@
|
|
|
1
|
-
/** Single-shot lower-bound solver for trata-hedge-bench. */
|
|
2
|
-
import { readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'
|
|
3
|
-
import { join, relative, resolve } from 'node:path'
|
|
4
|
-
import { runBenchRouterTurn } from './router-turn'
|
|
5
|
-
|
|
6
|
-
const environment = process.argv[2]
|
|
7
|
-
if (!environment) throw new Error('usage: solve.mts <env-dir> [out.txt]')
|
|
8
|
-
const output = process.argv[3] ?? '/tmp/thb-answer.txt'
|
|
9
|
-
const model = process.env.WORKER_MODEL
|
|
10
|
-
if (!model) throw new Error('WORKER_MODEL is required')
|
|
11
|
-
const dataBudget = Number(process.env.DATA_BUDGET ?? 160_000)
|
|
12
|
-
const maxTokens = Number(process.env.MAX_TOKENS ?? 6_000)
|
|
13
|
-
const temperature = Number(process.env.TEMPERATURE ?? 0.5)
|
|
14
|
-
const routerKey = process.env.TANGLE_API_KEY
|
|
15
|
-
if (!routerKey) throw new Error('TANGLE_API_KEY is required')
|
|
16
|
-
const routerBaseUrl = process.env.ROUTER_BASE ?? 'https://router.tangle.tools/v1'
|
|
17
|
-
|
|
18
|
-
for (const [name, value] of [
|
|
19
|
-
['DATA_BUDGET', dataBudget],
|
|
20
|
-
['MAX_TOKENS', maxTokens],
|
|
21
|
-
] as const) {
|
|
22
|
-
if (!Number.isSafeInteger(value) || value <= 0) throw new Error(`${name} must be a positive integer`)
|
|
23
|
-
}
|
|
24
|
-
if (!Number.isFinite(temperature)) throw new Error('TEMPERATURE must be finite')
|
|
25
|
-
|
|
26
|
-
const root = resolve(environment)
|
|
27
|
-
const dataDir = join(root, 'environment', 'data')
|
|
28
|
-
const instruction = readFileSync(join(root, 'instruction.md'), 'utf8')
|
|
29
|
-
|
|
30
|
-
function filesUnder(dir: string): string[] {
|
|
31
|
-
return readdirSync(dir)
|
|
32
|
-
.flatMap((name) => {
|
|
33
|
-
const path = join(dir, name)
|
|
34
|
-
return statSync(path).isDirectory() ? filesUnder(path) : [path]
|
|
35
|
-
})
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
function rank(path: string): number {
|
|
39
|
-
if (path.includes('earnings_call')) return 0
|
|
40
|
-
if (path.includes('financials')) return 1
|
|
41
|
-
if (path.includes('company_profiles')) return 2
|
|
42
|
-
if (path.includes('press_releases')) return 3
|
|
43
|
-
return 4
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
let used = 0
|
|
47
|
-
const blocks: string[] = []
|
|
48
|
-
const files = filesUnder(dataDir).sort((a, b) => rank(a) - rank(b) || a.localeCompare(b))
|
|
49
|
-
for (const path of files) {
|
|
50
|
-
const content = readFileSync(path, 'utf8')
|
|
51
|
-
if (used + content.length > dataBudget) continue
|
|
52
|
-
used += content.length
|
|
53
|
-
blocks.push(`\n=== FILE: data/${relative(dataDir, path)} ===\n${content}`)
|
|
54
|
-
}
|
|
55
|
-
process.stderr.write(`[solve] ${blocks.length}/${files.length} files in context (${used} chars)\n`)
|
|
56
|
-
|
|
57
|
-
const prompt =
|
|
58
|
-
'--- AVAILABLE DATA (cite files by their `data/<path>` name inline) ---\n' +
|
|
59
|
-
blocks.join('') +
|
|
60
|
-
'\n\n--- END DATA ---\nWrite ONLY the full analysis (no preamble). Inline-cite every claim with its `data/<path>`.'
|
|
61
|
-
|
|
62
|
-
const result = await runBenchRouterTurn(
|
|
63
|
-
{
|
|
64
|
-
routerBaseUrl,
|
|
65
|
-
routerKey,
|
|
66
|
-
profile: {
|
|
67
|
-
name: 'trata-hedge-solver',
|
|
68
|
-
harness: 'cli-base',
|
|
69
|
-
model: {
|
|
70
|
-
provider: 'tangle-router',
|
|
71
|
-
default: model,
|
|
72
|
-
metadata: { temperature },
|
|
73
|
-
maxVisibleOutputTokens: maxTokens,
|
|
74
|
-
},
|
|
75
|
-
prompt: { systemPrompt: instruction },
|
|
76
|
-
},
|
|
77
|
-
},
|
|
78
|
-
prompt,
|
|
79
|
-
)
|
|
80
|
-
writeFileSync(output, result.finalText)
|
|
81
|
-
process.stderr.write(`[solve] wrote ${result.finalText.length} chars -> ${output} (model=${model})\n`)
|
|
@@ -1,117 +0,0 @@
|
|
|
1
|
-
"""Refine-aware Terminal-Bench agent.
|
|
2
|
-
|
|
3
|
-
Subclasses Terminal-Bench's native `OpenCodeAgent` so the agent, the in-container
|
|
4
|
-
install, the router auth, and the task's own verifier are all the published
|
|
5
|
-
open-source path — unchanged. The ONLY added behavior is an evidence-gated refine
|
|
6
|
-
directive prepended to the task instruction when a prior attempt is present.
|
|
7
|
-
|
|
8
|
-
Round 1 of the runner passes no prior attempt (or an empty one), so this agent is
|
|
9
|
-
byte-for-byte the plain opencode agent and round 1 == a real blind tb run. On a
|
|
10
|
-
refine round the runner passes the prior attempt (a summary of the failed round +
|
|
11
|
-
the failing tests); this class injects the directive and otherwise runs opencode
|
|
12
|
-
exactly as the base agent does (same `_run_agent_commands`, same env).
|
|
13
|
-
|
|
14
|
-
The prior attempt is passed as `prior_attempt_hex` — a hex-encoded UTF-8 string
|
|
15
|
-
with a leading 'h' sentinel. tb's CLI parses `--agent-kwarg key=value` with a
|
|
16
|
-
naive `key, value = kwarg.split("=")` and then runs `ast.literal_eval(value)`, so
|
|
17
|
-
the value must contain no '=' and must not look like a Python literal. Hex with an
|
|
18
|
-
'h' prefix satisfies both: no '=', and `literal_eval('h46...')` raises, so tb keeps
|
|
19
|
-
it as a string. The agent strips 'h' and decodes back to the original text.
|
|
20
|
-
|
|
21
|
-
Usage:
|
|
22
|
-
tb run -d terminal-bench-core==0.1.1 \
|
|
23
|
-
--agent-import-path tb_agents.opencode_refine_agent:OpenCodeRefineAgent \
|
|
24
|
-
-m deepseek/deepseek-v4-pro --task-id <id> \
|
|
25
|
-
--agent-kwarg prior_attempt_hex=h<hex-of-utf8-text>
|
|
26
|
-
"""
|
|
27
|
-
|
|
28
|
-
import inspect
|
|
29
|
-
import os
|
|
30
|
-
import tempfile
|
|
31
|
-
from pathlib import Path
|
|
32
|
-
|
|
33
|
-
from terminal_bench.agents.base_agent import AgentResult
|
|
34
|
-
from terminal_bench.agents.installed_agents.opencode.opencode_agent import (
|
|
35
|
-
OpenCodeAgent,
|
|
36
|
-
)
|
|
37
|
-
from terminal_bench.terminal.tmux_session import TmuxSession
|
|
38
|
-
from terminal_bench.utils.template_utils import render_setup_script
|
|
39
|
-
|
|
40
|
-
REFINE_DIRECTIVE = (
|
|
41
|
-
"REFINE PASS — your PREVIOUS attempt at this exact task FAILED the task's "
|
|
42
|
-
"automated tests. Evidence from that attempt is below.\n\n"
|
|
43
|
-
"<previous_attempt>\n{prior}\n</previous_attempt>\n\n"
|
|
44
|
-
"Re-examine the task from scratch in this fresh container. Keep whatever the "
|
|
45
|
-
"previous attempt got right, and fix the CONCRETE failure shown in the "
|
|
46
|
-
"evidence — do not repeat the same mistake. Do NOT rewrite or discard a part "
|
|
47
|
-
"that already worked. When done, verify your work against the task's stated "
|
|
48
|
-
"success criteria before finishing.\n\n"
|
|
49
|
-
"--- ORIGINAL TASK ---\n{instruction}"
|
|
50
|
-
)
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
class OpenCodeRefineAgent(OpenCodeAgent):
|
|
54
|
-
"""OpenCodeAgent + an evidence-gated refine-instruction injection.
|
|
55
|
-
|
|
56
|
-
`prior_attempt_hex` is decoded + consumed here and never forwarded to the base
|
|
57
|
-
agent, which only knows `model_name` / `version`. An empty/absent value degrades
|
|
58
|
-
the agent exactly to the plain opencode agent.
|
|
59
|
-
"""
|
|
60
|
-
|
|
61
|
-
def __init__(
|
|
62
|
-
self,
|
|
63
|
-
model_name: str,
|
|
64
|
-
prior_attempt_hex: str | None = None,
|
|
65
|
-
**kwargs,
|
|
66
|
-
):
|
|
67
|
-
super().__init__(model_name, **kwargs)
|
|
68
|
-
self._prior_attempt = self._decode_prior(prior_attempt_hex)
|
|
69
|
-
|
|
70
|
-
@staticmethod
|
|
71
|
-
def _decode_prior(prior_attempt_hex: str | None) -> str:
|
|
72
|
-
if not prior_attempt_hex:
|
|
73
|
-
return ""
|
|
74
|
-
raw = str(prior_attempt_hex).strip()
|
|
75
|
-
if raw.startswith("h"):
|
|
76
|
-
raw = raw[1:]
|
|
77
|
-
if not raw:
|
|
78
|
-
return ""
|
|
79
|
-
try:
|
|
80
|
-
return bytes.fromhex(raw).decode("utf-8").strip()
|
|
81
|
-
except ValueError as e:
|
|
82
|
-
raise ValueError(
|
|
83
|
-
f"prior_attempt_hex must be 'h' + hex-encoded UTF-8; got {raw[:40]!r}"
|
|
84
|
-
) from e
|
|
85
|
-
|
|
86
|
-
@staticmethod
|
|
87
|
-
def name() -> str:
|
|
88
|
-
return "agent-runtime-opencode-refine"
|
|
89
|
-
|
|
90
|
-
@property
|
|
91
|
-
def _install_agent_script_path(self) -> os.PathLike:
|
|
92
|
-
# The base method resolves the setup template via inspect.getfile(self.__class__),
|
|
93
|
-
# which points at THIS subclass's dir (tb_agents/) where the template does not
|
|
94
|
-
# live. Render opencode-setup.sh.j2 from the base OpenCodeAgent's own directory.
|
|
95
|
-
template_path = (
|
|
96
|
-
Path(inspect.getfile(OpenCodeAgent)).parent / "opencode-setup.sh.j2"
|
|
97
|
-
)
|
|
98
|
-
script_content = render_setup_script(
|
|
99
|
-
template_path, self._get_template_variables()
|
|
100
|
-
)
|
|
101
|
-
temp_file = tempfile.NamedTemporaryFile(mode="w", suffix=".sh", delete=False)
|
|
102
|
-
temp_file.write(script_content)
|
|
103
|
-
temp_file.close()
|
|
104
|
-
os.chmod(temp_file.name, 0o755)
|
|
105
|
-
return Path(temp_file.name)
|
|
106
|
-
|
|
107
|
-
def perform_task(
|
|
108
|
-
self,
|
|
109
|
-
instruction: str,
|
|
110
|
-
session: TmuxSession,
|
|
111
|
-
logging_dir: Path | None = None,
|
|
112
|
-
) -> AgentResult:
|
|
113
|
-
if self._prior_attempt:
|
|
114
|
-
instruction = REFINE_DIRECTIVE.format(
|
|
115
|
-
prior=self._prior_attempt, instruction=instruction
|
|
116
|
-
)
|
|
117
|
-
return super().perform_task(instruction, session, logging_dir)
|