@tangle-network/agent-bench 0.14.2 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (218) hide show
  1. package/CHANGELOG.md +48 -0
  2. package/README.md +2 -3
  3. package/dist/adapters.d.ts +2 -5
  4. package/dist/adapters.js +3 -4
  5. package/dist/benchmarks/_harness.d.ts +17 -20
  6. package/dist/benchmarks/_harness.js +4 -4
  7. package/dist/benchmarks/_harness.js.map +1 -1
  8. package/dist/benchmarks/aec-bench.d.ts +1 -4
  9. package/dist/benchmarks/aec-bench.js +1 -2
  10. package/dist/benchmarks/agentbench.d.ts +2 -5
  11. package/dist/benchmarks/agentbench.js +1 -2
  12. package/dist/benchmarks/appworld.d.ts +8 -10
  13. package/dist/benchmarks/appworld.js +23 -23
  14. package/dist/benchmarks/appworld.js.map +1 -1
  15. package/dist/benchmarks/bfcl.d.ts +2 -5
  16. package/dist/benchmarks/bfcl.js +1 -2
  17. package/dist/benchmarks/cad-design.d.ts +2 -5
  18. package/dist/benchmarks/cad-design.js +2 -3
  19. package/dist/benchmarks/cad-design.js.map +1 -1
  20. package/dist/benchmarks/cadbench.d.ts +1 -4
  21. package/dist/benchmarks/cadbench.js +1 -2
  22. package/dist/benchmarks/cadgenbench.d.ts +1 -4
  23. package/dist/benchmarks/cadgenbench.js +1 -2
  24. package/dist/benchmarks/commit0.d.ts +2 -5
  25. package/dist/benchmarks/commit0.js +1 -2
  26. package/dist/benchmarks/crag.d.ts +1 -4
  27. package/dist/benchmarks/crag.js +3 -3
  28. package/dist/benchmarks/crag.js.map +1 -1
  29. package/dist/benchmarks/dabstep.d.ts +2 -5
  30. package/dist/benchmarks/dabstep.js +2 -3
  31. package/dist/benchmarks/dabstep.js.map +1 -1
  32. package/dist/benchmarks/enterpriseops-gym.d.ts +2 -5
  33. package/dist/benchmarks/enterpriseops-gym.js +1 -2
  34. package/dist/benchmarks/finresearchbench.d.ts +2 -5
  35. package/dist/benchmarks/finresearchbench.js +2 -3
  36. package/dist/benchmarks/finsearchcomp.d.ts +2 -5
  37. package/dist/benchmarks/finsearchcomp.js +4 -4
  38. package/dist/benchmarks/finsearchcomp.js.map +1 -1
  39. package/dist/benchmarks/frames.d.ts +3 -19
  40. package/dist/benchmarks/frames.js +13 -39
  41. package/dist/benchmarks/frames.js.map +1 -1
  42. package/dist/benchmarks/hotpotqa.d.ts +4 -14
  43. package/dist/benchmarks/hotpotqa.js +12 -32
  44. package/dist/benchmarks/hotpotqa.js.map +1 -1
  45. package/dist/benchmarks/humaneval.d.ts +9 -12
  46. package/dist/benchmarks/humaneval.js +2 -3
  47. package/dist/benchmarks/humaneval.js.map +1 -1
  48. package/dist/benchmarks/mcad-bench.d.ts +13 -16
  49. package/dist/benchmarks/mcad-bench.js +2 -3
  50. package/dist/benchmarks/mcad-bench.js.map +1 -1
  51. package/dist/benchmarks/mcad-cq-bench.d.ts +17 -20
  52. package/dist/benchmarks/mcad-cq-bench.js +2 -3
  53. package/dist/benchmarks/mcad-cq-bench.js.map +1 -1
  54. package/dist/benchmarks/mcad-cq-golds.d.ts +2 -5
  55. package/dist/benchmarks/mcad-cq-golds.js +1 -2
  56. package/dist/benchmarks/mcad-golds.d.ts +1 -4
  57. package/dist/benchmarks/mcad-golds.js +0 -1
  58. package/dist/benchmarks/mcad-tasks.d.ts +5 -8
  59. package/dist/benchmarks/mcad-tasks.js +7 -8
  60. package/dist/benchmarks/mcad-tasks.js.map +1 -1
  61. package/dist/benchmarks/mind2web.d.ts +3 -5
  62. package/dist/benchmarks/mind2web.js +2 -3
  63. package/dist/benchmarks/mind2web.js.map +1 -1
  64. package/dist/benchmarks/nomiracl.d.ts +1 -4
  65. package/dist/benchmarks/nomiracl.js +1 -2
  66. package/dist/benchmarks/open-rag-bench.d.ts +1 -4
  67. package/dist/benchmarks/open-rag-bench.js +3 -3
  68. package/dist/benchmarks/open-rag-bench.js.map +1 -1
  69. package/dist/benchmarks/programbench.d.ts +2 -5
  70. package/dist/benchmarks/programbench.js +1 -2
  71. package/dist/benchmarks/rag-shared.d.ts +30 -22
  72. package/dist/benchmarks/rag-shared.js +8 -2
  73. package/dist/benchmarks/rag-shared.js.map +1 -1
  74. package/dist/benchmarks/ragbench.d.ts +1 -4
  75. package/dist/benchmarks/ragbench.js +3 -3
  76. package/dist/benchmarks/ragbench.js.map +1 -1
  77. package/dist/benchmarks/simpleqa.d.ts +2 -18
  78. package/dist/benchmarks/simpleqa.js +5 -31
  79. package/dist/benchmarks/simpleqa.js.map +1 -1
  80. package/dist/benchmarks/swe-bench.d.ts +7 -10
  81. package/dist/benchmarks/swe-bench.js +4 -4
  82. package/dist/benchmarks/swe-bench.js.map +1 -1
  83. package/dist/benchmarks/t2-ragbench.d.ts +1 -4
  84. package/dist/benchmarks/t2-ragbench.js +3 -3
  85. package/dist/benchmarks/t2-ragbench.js.map +1 -1
  86. package/dist/benchmarks/tau-bench-shared.d.ts +5 -8
  87. package/dist/benchmarks/tau-bench-shared.js +4 -4
  88. package/dist/benchmarks/tau-bench-shared.js.map +1 -1
  89. package/dist/benchmarks/tau2-bench.d.ts +2 -5
  90. package/dist/benchmarks/tau2-bench.js +1 -2
  91. package/dist/benchmarks/tau3-banking.d.ts +1 -4
  92. package/dist/benchmarks/tau3-banking.js +1 -2
  93. package/dist/benchmarks/terminal-bench.d.ts +1 -4
  94. package/dist/benchmarks/terminal-bench.js +4 -4
  95. package/dist/benchmarks/terminal-bench.js.map +1 -1
  96. package/dist/benchmarks/toollm.d.ts +2 -5
  97. package/dist/benchmarks/toollm.js +1 -2
  98. package/dist/benchmarks/trata-hedge.d.ts +1 -4
  99. package/dist/benchmarks/trata-hedge.js +2 -3
  100. package/dist/benchmarks/types.d.ts +6 -9
  101. package/dist/benchmarks/webarena-verified.d.ts +2 -5
  102. package/dist/benchmarks/webarena-verified.js +1 -2
  103. package/dist/{cadbench-BRF-59Mt.js → cadbench-DhAndllg.js} +4 -6
  104. package/dist/cadbench-DhAndllg.js.map +1 -0
  105. package/dist/{cadgenbench-DXtGkuW3.js → cadgenbench-Tvk16YKT.js} +15 -5
  106. package/dist/cadgenbench-Tvk16YKT.js.map +1 -0
  107. package/dist/index.d.ts +8 -18
  108. package/dist/index.js +16 -24
  109. package/dist/index.js.map +1 -1
  110. package/dist/{router-turn-uTYO6KQ1.js → router-turn-DNbQ_GjQ.js} +2 -3
  111. package/dist/router-turn-DNbQ_GjQ.js.map +1 -0
  112. package/fixtures/pier-agent/no-model-task/pre_artifacts.sh +0 -0
  113. package/fixtures/pier-agent/no-model-task/tests/test.sh +0 -0
  114. package/package.json +10 -10
  115. package/pier_agents/tangle_candidate.py +15 -23
  116. package/scripts/run-package-tests.mjs +8 -15
  117. package/scripts/verify-packed-consumer.mjs +0 -1
  118. package/src/atom-mcp-e2e.mts +16 -4
  119. package/src/benchmarks/frames.ts +10 -44
  120. package/src/benchmarks/hotpotqa.ts +9 -29
  121. package/src/benchmarks/rag-shared.ts +12 -0
  122. package/src/benchmarks/simpleqa.ts +2 -36
  123. package/src/commit0-prereqs.sh +0 -0
  124. package/src/corpus-replay.mts +8 -8
  125. package/src/corpus-report.mts +21 -21
  126. package/src/corpus.test.mts +5 -5
  127. package/src/corpus.ts +16 -16
  128. package/src/directives.ts +0 -38
  129. package/src/examples/lean-verify.ts +1 -1
  130. package/src/gate.ts +8 -8
  131. package/src/generate-eval/certify.ts +2 -2
  132. package/src/index.ts +1 -0
  133. package/src/refine-loop.ts +5 -5
  134. package/src/resolve-client.ts +1 -1
  135. package/src/router-turn.ts +3 -11
  136. package/src/run-benchmarks.test.mts +0 -4
  137. package/src/run-pool.ts +1 -1
  138. package/src/runtime-hook-recorder.ts +2 -2
  139. package/src/search-bench/tasks.ts +1 -1
  140. package/src/selector.test.mts +13 -13
  141. package/src/selector.ts +19 -19
  142. package/src/swe-bench-env.ts +4 -12
  143. package/src/swe-jail.ts +5 -156
  144. package/src/swe-structural-judge-policy.ts +3 -3
  145. package/src/swe-structural-policy.ts +3 -3
  146. package/src/swe-structural-provenance.ts +4 -4
  147. package/src/terminal-compare.ts +10 -10
  148. package/src/worker-blender.ts +2 -106
  149. package/src/worker-build123d.ts +2 -81
  150. package/tb_agents/opencode_router_agent.py +1 -1
  151. package/dist/cadbench-BRF-59Mt.js.map +0 -1
  152. package/dist/cadgenbench-DXtGkuW3.js.map +0 -1
  153. package/dist/router-turn-uTYO6KQ1.js.map +0 -1
  154. package/scripts/cadbench_prepare.py +0 -22
  155. package/scripts/cadgenbench_hard_parts.py +0 -48
  156. package/scripts/clbench_codebase_judge.py +0 -73
  157. package/scripts/render-gate-chart.mjs +0 -176
  158. package/scripts/trata-hedge/README.md +0 -57
  159. package/scripts/trata-hedge/run.sh +0 -64
  160. package/src/browser/adapters/bad-design-audit.ts +0 -153
  161. package/src/browser/adapters/bad-design-audit.verify.ts +0 -85
  162. package/src/browser/adapters/bad.ts +0 -165
  163. package/src/browser/agent-adapter.ts +0 -145
  164. package/src/browser/process-adapter.ts +0 -146
  165. package/src/browser/run-to-spans.ts +0 -105
  166. package/src/browser/run-to-spans.verify.ts +0 -89
  167. package/src/browser/ui-reviewer.ts +0 -200
  168. package/src/browser/ui-reviewer.verify.ts +0 -94
  169. package/src/browser/verify.ts +0 -96
  170. package/src/clbench-codebase-gate.mts +0 -314
  171. package/src/clbench-context-gate.mts +0 -341
  172. package/src/cloud-loop.mts +0 -156
  173. package/src/commit0-env-run.mts +0 -62
  174. package/src/commit0-env.ts +0 -172
  175. package/src/commit0-gate.mts +0 -558
  176. package/src/coordination-mcp-container-reach.mts +0 -182
  177. package/src/egress-probe.mts +0 -26
  178. package/src/fleet.mts +0 -143
  179. package/src/hev-structural.mts +0 -697
  180. package/src/humaneval-gate.mts +0 -220
  181. package/src/humaneval-repair-gate.mts +0 -182
  182. package/src/mbpp-structural.mts +0 -676
  183. package/src/mcp-mount-probe.mts +0 -139
  184. package/src/profile-coordinates.ts +0 -134
  185. package/src/profiles.ts +0 -128
  186. package/src/research-gate.mts +0 -132
  187. package/src/research-shot.ts +0 -144
  188. package/src/router-executor.ts +0 -51
  189. package/src/run-benchmarks-report.ts +0 -66
  190. package/src/sandbox-run.ts +0 -108
  191. package/src/search-bench/bridge.ts +0 -182
  192. package/src/search-bench/export.mts +0 -0
  193. package/src/search-bench/parametric-check.mts +0 -78
  194. package/src/search-bench/profiles.ts +0 -113
  195. package/src/search-bench/run.mts +0 -286
  196. package/src/search-bench/tasks-fresh.ts +0 -688
  197. package/src/skill-sandbox-smoke.mts +0 -101
  198. package/src/smoke-structural-rollout.mts +0 -415
  199. package/src/stats.mts +0 -90
  200. package/src/supervisor-arena.mts +0 -825
  201. package/src/swe-code-improve.mts +0 -306
  202. package/src/swe-emit-patch.mts +0 -125
  203. package/src/swe-improve.mts +0 -284
  204. package/src/swe-local-proof.mts +0 -265
  205. package/src/swe-repro-calibrate.mts +0 -451
  206. package/src/swe-stream.mts +0 -1561
  207. package/src/swe-structural.mts +0 -707
  208. package/src/tb-container-executor.mts +0 -266
  209. package/src/tb-container-executor.test.mts +0 -134
  210. package/src/tb-supervisor-sidecar.mts +0 -208
  211. package/src/trajectory-assemble.mjs +0 -130
  212. package/src/trata-gepa.mts +0 -381
  213. package/src/trata-hedge-solve.mts +0 -81
  214. package/src/worker-browser.ts +0 -115
  215. package/src/worker-cad.ts +0 -470
  216. package/src/workspace-loop.mts +0 -133
  217. package/tb_agents/opencode_refine_agent.py +0 -117
  218. package/tb_agents/opencode_supervisor_agent.py +0 -239
@@ -1,133 +0,0 @@
1
- /**
2
- * The decisive de-risk: does a git-backed shared workspace make accumulating,
3
- * resumable, multi-worker loops REAL on a share-nothing substrate?
4
- *
5
- * The red-team's fatal finding: each cloud worker is a fresh box with no shared
6
- * filesystem, so "worker N+1 builds on worker N's code" is impossible and resume
7
- * restores decisions, not the mutated workspace. The proposed fix: a git-backed
8
- * contract. This proves or kills it on 3 dependency-ordered modules (a←b←c).
9
- *
10
- * - The DURABLE WORKSPACE = a bare git repo (models a GitHub branch in cloud).
11
- * - Each WORKER = a FRESH temp clone (models a fresh box's empty FS), torn down
12
- * after it commits+pushes. State survives ONLY because git persisted it.
13
- * - THE PROOF: a worker asserts its dependency's file is on disk in its fresh
14
- * clone. Fails on share-nothing (names-in-a-string); passes on the git seam.
15
- *
16
- * Test (a) — does it link? full run → integration test imports a←b←c, must pass.
17
- * Test (b) — resume? KILL_AFTER=b, then RESUME=1: c clones a repo that
18
- * HAS a+b committed (durable), re-runs ONLY c, links.
19
- *
20
- * pnpm exec tsx src/workspace-loop.mts # (a) happy path
21
- * KILL_AFTER=b pnpm exec tsx src/workspace-loop.mts # die after b
22
- * RESUME=1 pnpm exec tsx src/workspace-loop.mts # (b) resume → finish c
23
- */
24
- import { execFileSync } from 'node:child_process'
25
- import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
26
- import { appendFileSync } from 'node:fs'
27
- import { tmpdir } from 'node:os'
28
- import { join } from 'node:path'
29
-
30
- const BARE = '/tmp/workspace-loop.git' // the durable shared workspace (≈ a remote branch)
31
- const JOURNAL = '/tmp/workspace-loop.journal' // the decision record (which modules are committed)
32
-
33
- const sh = (cmd: string, args: string[], cwd?: string): string =>
34
- execFileSync(cmd, args, { cwd, stdio: 'pipe', encoding: 'utf-8' })
35
- const git = (args: string[], cwd?: string): string =>
36
- // hooksPath=/dev/null: these are throwaway test clones, not project repos — the
37
- // operator's global ai-agent-hooks must not run on them.
38
- sh('git', ['-c', 'core.hooksPath=/dev/null', '-c', 'user.email=loop@tangle', '-c', 'user.name=loop', ...args], cwd)
39
-
40
- /** a←b←c: c.top(1) = ((1+1)*2)+3 = 7. The integration test imports the whole chain,
41
- * so it passes ONLY if all three files accumulated in the workspace. */
42
- const modules = [
43
- { id: 'a', file: 'a.py', dep: null as string | null, code: 'def base(x):\n return x + 1\n' },
44
- { id: 'b', file: 'b.py', dep: 'a', code: 'from a import base\n\ndef mid(x):\n return base(x) * 2\n' },
45
- { id: 'c', file: 'c.py', dep: 'b', code: 'from b import mid\n\ndef top(x):\n return mid(x) + 3\n' },
46
- ]
47
- const depFile = (id: string): string => modules.find((m) => m.id === id)!.file
48
-
49
- function initWorkspace(): void {
50
- rmSync(BARE, { recursive: true, force: true })
51
- rmSync(JOURNAL, { force: true })
52
- git(['init', '--bare', '-b', 'main', BARE])
53
- // seed: the integration test, on the branch from commit 0.
54
- const seed = mkdtempSync(join(tmpdir(), 'wl-seed-'))
55
- git(['clone', BARE, seed])
56
- writeFileSync(join(seed, 'test_all.py'), 'from c import top\n\nassert top(1) == 7, top(1)\nprint("INTEGRATION OK")\n')
57
- git(['add', '-A'], seed)
58
- git(['commit', '-m', 'seed: integration test'], seed)
59
- git(['push', 'origin', 'main'], seed)
60
- rmSync(seed, { recursive: true, force: true })
61
- }
62
-
63
- function loadJournal(): Set<string> {
64
- if (!existsSync(JOURNAL)) return new Set()
65
- return new Set(readFileSync(JOURNAL, 'utf-8').split('\n').filter(Boolean))
66
- }
67
-
68
- /** One worker: fresh clone (empty box FS) → verify dep is ON DISK → port → push → torn down. */
69
- function runWorker(m: (typeof modules)[number]): void {
70
- const work = mkdtempSync(join(tmpdir(), `wl-${m.id}-`))
71
- try {
72
- git(['clone', BARE, work]) // a brand-new, otherwise-empty box
73
- // THE PROOF: did the durable workspace carry my dependency's code to this fresh box?
74
- if (m.dep) {
75
- const present = existsSync(join(work, depFile(m.dep)))
76
- console.error(` [${m.id}] fresh clone — dependency ${depFile(m.dep)} on disk? ${present ? 'YES ✓ (git carried it)' : 'NO ✗ (share-nothing)'}`)
77
- if (!present) throw new Error(`SHARE-NOTHING: ${m.id} cannot see ${m.dep} — the seam is broken`)
78
- } else {
79
- console.error(` [${m.id}] fresh clone — root module, no dependency`)
80
- }
81
- writeFileSync(join(work, m.file), m.code) // port the module
82
- git(['add', '-A'], work)
83
- git(['commit', '-m', `port ${m.id}`], work)
84
- git(['push', 'origin', 'main'], work) // accumulate into the durable workspace
85
- appendFileSync(JOURNAL, `${m.id}\n`) // record the decision durably
86
- console.error(` [${m.id}] ported + committed + pushed → torn down`)
87
- } finally {
88
- rmSync(work, { recursive: true, force: true }) // teardown — the box dies, git survives
89
- }
90
- }
91
-
92
- /** Test (a): a fresh clone of the durable workspace must pass the integration test. */
93
- function integrationLinks(): boolean {
94
- const check = mkdtempSync(join(tmpdir(), 'wl-check-'))
95
- try {
96
- git(['clone', BARE, check])
97
- const out = sh('python3', ['test_all.py'], check)
98
- console.error(` integration: ${out.trim()}`)
99
- return out.includes('INTEGRATION OK')
100
- } catch (e) {
101
- console.error(` integration FAILED: ${e instanceof Error ? e.message.split('\n').slice(-3).join(' ') : e}`)
102
- return false
103
- } finally {
104
- rmSync(check, { recursive: true, force: true })
105
- }
106
- }
107
-
108
- function main(): void {
109
- const resume = process.env.RESUME === '1'
110
- const killAfter = process.env.KILL_AFTER
111
- if (!resume) initWorkspace()
112
- const done = loadJournal()
113
- console.error(`\n=== git-backed workspace loop · ${resume ? 'RESUME' : 'fresh'}${done.size ? ` (done: ${[...done].join(',')})` : ''} ===`)
114
-
115
- for (const m of modules) {
116
- if (done.has(m.id)) {
117
- console.error(` [${m.id}] skip — already committed (resumed from durable git)`)
118
- continue
119
- }
120
- if (m.dep && !loadJournal().has(m.dep)) throw new Error(`${m.id} blocked: dependency ${m.dep} not done (topo order)`)
121
- runWorker(m)
122
- if (killAfter === m.id) {
123
- console.error(`\n💥 KILLED after ${m.id} (orchestrator death). Durable git has: ${[...loadJournal()].join(',')}. Re-run with RESUME=1.\n`)
124
- process.exit(1)
125
- }
126
- }
127
-
128
- const links = integrationLinks()
129
- console.error(`\n=== ${links ? '✅ LINKS — git-backed workspace + resume is REAL' : '❌ does not link'} ===`)
130
- process.exit(links ? 0 : 1)
131
- }
132
-
133
- main()
@@ -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)
@@ -1,239 +0,0 @@
1
- """Terminal-Bench opencode agent with a coordination MCP mounted into the task container."""
2
-
3
- import json
4
- import os
5
- import shlex
6
- import subprocess
7
- import time
8
- from pathlib import Path
9
-
10
- from terminal_bench.agents.base_agent import AgentResult
11
- from terminal_bench.agents.failure_mode import FailureMode
12
- from terminal_bench.terminal.tmux_session import TmuxSession
13
-
14
- from tb_agents.opencode_router_agent import (
15
- _CONTAINER_DIR,
16
- OpenCodeRouterAgent,
17
- )
18
-
19
- DOCKER_BRIDGE_GATEWAY = os.environ.get("DOCKER_BRIDGE_GATEWAY", "172.17.0.1")
20
- _WORKER_CONFIG_PATH = f"{_CONTAINER_DIR}/opencode-worker.json"
21
- # The sidecar entrypoint, resolved relative to the bench dir (this file is bench/tb_agents/...).
22
- _BENCH_DIR = Path(__file__).resolve().parent.parent
23
- _REPO_DIR = _BENCH_DIR.parent
24
- _SIDECAR_TS = _BENCH_DIR / "src" / "tb-supervisor-sidecar.mts"
25
-
26
-
27
- def _resolve_tsx() -> list[str]:
28
- """Prefer the pinned local tsx binary (no npx download / no shell hook rewrite)."""
29
- for cand in (
30
- _BENCH_DIR / "node_modules" / ".bin" / "tsx",
31
- _REPO_DIR / "node_modules" / ".bin" / "tsx",
32
- ):
33
- if cand.exists():
34
- return [str(cand)]
35
- return ["npx", "tsx"]
36
-
37
-
38
- class OpenCodeSupervisorAgent(OpenCodeRouterAgent):
39
- """`OpenCodeRouterAgent` + a coordination MCP mounted into the in-container opencode.
40
-
41
- Adds a host orchestration sidecar and the `mcp.coordination` config block; otherwise
42
- identical to Arm A. Worker model defaults to the same model as the supervisor.
43
- """
44
-
45
- def __init__(self, model_name: str, *args, **kwargs):
46
- super().__init__(model_name, *args, **kwargs)
47
- self._mcp_port: int | None = None
48
- self._sidecar: subprocess.Popen | None = None
49
- self._sidecar_stdout = None
50
- self._sidecar_port_file: Path | None = None
51
- self._sidecar_log_file: Path | None = None
52
-
53
- @staticmethod
54
- def name() -> str:
55
- return "agent-runtime-opencode-supervisor"
56
-
57
- def _mcp_url(self) -> str:
58
- return f"http://{DOCKER_BRIDGE_GATEWAY}:{self._mcp_port}/mcp"
59
-
60
- def _build_router_config(self) -> str:
61
- """Base router config plus the coordination MCP block."""
62
- config = json.loads(super()._build_router_config())
63
- if self._mcp_port is not None:
64
- config["mcp"] = {
65
- "coordination": {
66
- "type": "remote",
67
- "url": self._mcp_url(),
68
- "enabled": True,
69
- }
70
- }
71
- return json.dumps(config)
72
-
73
- def _write_config_to_container(self, session: TmuxSession) -> None:
74
- super()._write_config_to_container(session)
75
- worker_config = OpenCodeRouterAgent._build_router_config(self)
76
- session.container.exec_run(
77
- [
78
- "sh",
79
- "-c",
80
- f"printf '%s' {shlex.quote(worker_config)} > {_WORKER_CONFIG_PATH}",
81
- ]
82
- )
83
-
84
- def _resolve_container_id(self, session: TmuxSession) -> str | None:
85
- return getattr(session.container, "id", None) or getattr(
86
- session.container, "short_id", None
87
- )
88
-
89
- def _start_sidecar(self, container_id: str, logging_dir: Path | None) -> None:
90
- base = logging_dir if logging_dir is not None else Path.cwd()
91
- base.mkdir(parents=True, exist_ok=True)
92
- self._sidecar_port_file = base / ".tb-sidecar-port"
93
- self._sidecar_log_file = base / "tb-sidecar-events.jsonl"
94
- self._sidecar_port_file.unlink(missing_ok=True)
95
-
96
- env = dict(os.environ)
97
- env.update(
98
- {
99
- "TB_TARGET_CONTAINER": container_id,
100
- "OPENAI_API_KEY": self._router_api_key,
101
- "OPENAI_BASE_URL": self._router_base_url,
102
- "WORKER_MODEL": self._model_name,
103
- "TB_SIDECAR_PORT_FILE": str(self._sidecar_port_file),
104
- "TB_SIDECAR_LOG": str(self._sidecar_log_file),
105
- "DOCKER_BRIDGE_GATEWAY": DOCKER_BRIDGE_GATEWAY,
106
- }
107
- )
108
- self._sidecar_stdout = open(base / "tb-sidecar.stdout.log", "w")
109
- self._logger.info("Starting orchestration sidecar for container %s", container_id)
110
- self._sidecar = subprocess.Popen(
111
- [*_resolve_tsx(), str(_SIDECAR_TS)],
112
- cwd=str(_BENCH_DIR),
113
- env=env,
114
- stdout=self._sidecar_stdout,
115
- stderr=subprocess.STDOUT,
116
- )
117
- deadline = time.time() + 60.0
118
- while time.time() < deadline:
119
- if self._sidecar.poll() is not None:
120
- raise RuntimeError(
121
- f"orchestration sidecar exited early with code {self._sidecar.returncode} "
122
- f"(see {base / 'tb-sidecar.stdout.log'})"
123
- )
124
- if self._sidecar_port_file.exists():
125
- txt = self._sidecar_port_file.read_text().strip()
126
- if txt.isdigit():
127
- self._mcp_port = int(txt)
128
- self._logger.info(
129
- "Sidecar ready: mcp port=%d url=%s", self._mcp_port, self._mcp_url()
130
- )
131
- return
132
- time.sleep(0.5)
133
- raise RuntimeError("orchestration sidecar did not publish a port within 60s")
134
-
135
- def _stop_sidecar(self) -> None:
136
- if self._sidecar is None:
137
- return
138
- try:
139
- self._sidecar.terminate()
140
- try:
141
- self._sidecar.wait(timeout=30)
142
- except subprocess.TimeoutExpired:
143
- self._sidecar.kill()
144
- except Exception as e: # noqa: BLE001 - teardown is never fatal
145
- self._logger.warning("Could not stop sidecar cleanly: %s", e)
146
- finally:
147
- if self._sidecar_stdout is not None:
148
- try:
149
- self._sidecar_stdout.close()
150
- except Exception: # noqa: BLE001
151
- pass
152
-
153
- def _orchestration_summary(self) -> dict:
154
- summary: dict = {
155
- "settled": [],
156
- "worker_outputs": [],
157
- "history_len": 0,
158
- "worker_ran": False,
159
- "worker_tokens": {"input": 0, "output": 0},
160
- }
161
- if self._sidecar_log_file is None:
162
- return summary
163
- final = Path(str(self._sidecar_log_file) + ".final.json")
164
- try:
165
- if final.exists():
166
- data = json.loads(final.read_text())
167
- settled = data.get("settled", []) or []
168
- summary["settled"] = settled
169
- summary["worker_outputs"] = data.get("workerOutputs", []) or []
170
- summary["history_len"] = len(data.get("history", []) or [])
171
- summary["worker_tokens"] = data.get(
172
- "workerTokens", {"input": 0, "output": 0}
173
- )
174
- summary["worker_ran"] = any(
175
- isinstance(w, dict) and w.get("containerId")
176
- for w in summary["worker_outputs"]
177
- ) or len(settled) > 0
178
- except Exception as e: # noqa: BLE001
179
- self._logger.warning("Could not read orchestration summary: %s", e)
180
- return summary
181
-
182
- def perform_task(
183
- self,
184
- instruction: str,
185
- session: TmuxSession,
186
- logging_dir: Path | None = None,
187
- ) -> AgentResult:
188
- container_id = self._resolve_container_id(session)
189
- if not container_id:
190
- self._logger.error("Could not resolve container id for supervisor sidecar.")
191
- return AgentResult(failure_mode=FailureMode.UNKNOWN_AGENT_ERROR)
192
-
193
- try:
194
- self._start_sidecar(container_id, logging_dir)
195
- except Exception as e: # noqa: BLE001
196
- self._logger.error("Sidecar failed to start: %s", e)
197
- self._mcp_port = None
198
- return AgentResult(failure_mode=FailureMode.UNKNOWN_AGENT_ERROR)
199
-
200
- try:
201
- supervised_instruction = (
202
- "You are the supervisor. You have an MCP server named \"coordination\" with "
203
- "tools including spawn_worker(profile, task), observe_agent(workerId), "
204
- "await_event(), and stop(). A spawned worker runs a full coding agent INSIDE "
205
- "THIS SAME container and its file changes persist here, so you may delegate "
206
- "concrete sub-tasks (e.g. \"install perl and 7z\", \"crack the hash with john\") "
207
- "to workers via spawn_worker, then observe_agent/await_event for their results. "
208
- "Delegate independent or heavy sub-tasks to workers when useful; do the rest "
209
- "yourself. Complete the task fully.\n\n"
210
- f"TASK:\n{instruction}"
211
- )
212
- result = super().perform_task(supervised_instruction, session, logging_dir)
213
- finally:
214
- self._stop_sidecar()
215
-
216
- summary = self._orchestration_summary()
217
- if logging_dir is not None:
218
- try:
219
- (logging_dir / "orchestration-summary.json").write_text(
220
- json.dumps(summary, indent=2)
221
- )
222
- except Exception: # noqa: BLE001
223
- pass
224
- self._logger.info(
225
- "Arm B orchestration: workers_settled=%d history_len=%d worker_ran=%s",
226
- len(summary.get("settled", [])),
227
- summary.get("history_len", 0),
228
- summary.get("worker_ran"),
229
- )
230
- wt = summary.get("worker_tokens") or {}
231
- worker_in = int(wt.get("input") or 0)
232
- worker_out = int(wt.get("output") or 0)
233
- if result.failure_mode == FailureMode.AGENT_INSTALLATION_FAILED:
234
- return result
235
- return AgentResult(
236
- total_input_tokens=result.total_input_tokens + worker_in,
237
- total_output_tokens=result.total_output_tokens + worker_out,
238
- failure_mode=result.failure_mode,
239
- )