tokensafe 4.6.3 → 4.7.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/.codex-plugin/plugin.json +2 -2
- package/LICENSE +202 -21
- package/README.md +44 -7
- package/hooks/claude_code_hook.py +24 -2
- package/hooks/kimi_hook.py +20 -0
- package/hooks/pre_invocation.py +7 -12
- package/hooks/session_start.py +8 -0
- package/kimi.plugin.json +2 -2
- package/package.json +2 -2
- package/plugin.json +2 -1
- package/server.json +3 -3
- package/src/acp/__init__.py +15 -0
- package/src/acp/server.py +328 -0
- package/src/adapter_core.py +22 -3
- package/src/agent/__init__.py +11 -0
- package/src/agent/context.py +99 -0
- package/src/agent/loop.py +385 -0
- package/src/agent/pricing.py +77 -0
- package/src/agent/providers.py +486 -0
- package/src/agent/tools.py +98 -0
- package/src/auto_inject.py +517 -0
- package/src/bench/__init__.py +1 -0
- package/src/bench/driver.py +219 -0
- package/src/bench/go_target.py +360 -0
- package/src/bench/react_target.py +234 -0
- package/src/bench/runner.py +247 -0
- package/src/cli.py +244 -5
- package/src/command_sanitizer.py +54 -0
- package/src/guard.py +63 -10
- package/src/history_compactor.py +200 -2
- package/src/mcp_server.py +65 -13
- package/src/paths.py +99 -2
- package/src/retrofit.py +91 -4
- package/src/savings.py +81 -0
- package/src/scaffold.py +190 -8
- package/src/session_brief.py +154 -0
- package/src/session_context.py +124 -0
- package/src/telemetry_sync.py +93 -25
- package/src/version_checker.py +1 -1
- package/hooks/__pycache__/claude_code_hook.cpython-312.pyc +0 -0
- package/hooks/__pycache__/cursor_hook.cpython-312.pyc +0 -0
- package/hooks/__pycache__/kimi_hook.cpython-312.pyc +0 -0
- package/hooks/__pycache__/pre_invocation.cpython-312.pyc +0 -0
- package/hooks/__pycache__/pre_tool_use.cpython-312.pyc +0 -0
- package/hooks/__pycache__/session_start.cpython-312.pyc +0 -0
- package/hooks/__pycache__/stop_hook.cpython-312.pyc +0 -0
- package/hooks/__pycache__/zcode_hook.cpython-312.pyc +0 -0
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
"""React sandbox target for the measured benchmark.
|
|
2
|
+
|
|
3
|
+
Workspace: a throwaway copy of `agent-dom/packages/benchmark` placed *inside* the
|
|
4
|
+
repo (`agent-dom/.bench-tmp-*`) so Node resolves react/tsx from the monorepo's
|
|
5
|
+
node_modules. The agent edits the real React sandbox sources; correctness is the
|
|
6
|
+
12-assertion TaskManagerOracle executed by `src/bin/oracle-runner.ts` after every
|
|
7
|
+
step.
|
|
8
|
+
|
|
9
|
+
The OUMV arm for this target needs the Vite bridge (`tokensafe dev`), so the first
|
|
10
|
+
React pilot measures the `baseline` arm only — the Go pilot already compares both.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import json
|
|
16
|
+
import os
|
|
17
|
+
import shutil
|
|
18
|
+
import subprocess
|
|
19
|
+
import tempfile
|
|
20
|
+
import time
|
|
21
|
+
from pathlib import Path
|
|
22
|
+
from typing import Any, Dict, List, Optional, Tuple
|
|
23
|
+
|
|
24
|
+
REPO_ROOT = Path(__file__).resolve().parents[3]
|
|
25
|
+
AGENT_DOM = REPO_ROOT / "agent-dom"
|
|
26
|
+
PACKAGE = AGENT_DOM / "packages" / "benchmark"
|
|
27
|
+
WRITE_PREFIX = "sandboxes/react-task-manager/src/"
|
|
28
|
+
STORE = f"{WRITE_PREFIX}store.ts"
|
|
29
|
+
|
|
30
|
+
TASKS: Dict[str, Dict[str, Any]] = {
|
|
31
|
+
"search-filter": {
|
|
32
|
+
"symptom": "typing in the search box no longer filters the task list (the query is ignored).",
|
|
33
|
+
"breaks": [(
|
|
34
|
+
STORE,
|
|
35
|
+
" if (state.searchQuery.trim()) {\n const q = state.searchQuery.toLowerCase();\n const inTitle = task.title.toLowerCase().includes(q);\n const inTags = task.tags?.some((tag) => tag.toLowerCase().includes(q)) ?? false;\n if (!inTitle && !inTags) return false;\n }\n",
|
|
36
|
+
"",
|
|
37
|
+
)],
|
|
38
|
+
},
|
|
39
|
+
"optimistic-rollback": {
|
|
40
|
+
"symptom": "when the background sync fails, the toggled task keeps the optimistic status instead of rolling back.",
|
|
41
|
+
"breaks": [(
|
|
42
|
+
STORE,
|
|
43
|
+
""" } catch (err: any) {
|
|
44
|
+
this.set({
|
|
45
|
+
tasks: this.state.tasks.map((t) => (t.id === id ? { ...t, status: prior.status } : t)),
|
|
46
|
+
errorMessage: err?.message || 'Optimistic sync failed',
|
|
47
|
+
});
|
|
48
|
+
throw err;
|
|
49
|
+
}""",
|
|
50
|
+
""" } catch (err: any) {
|
|
51
|
+
this.set({ errorMessage: err?.message || 'Optimistic sync failed' });
|
|
52
|
+
throw err;
|
|
53
|
+
}""",
|
|
54
|
+
)],
|
|
55
|
+
},
|
|
56
|
+
"saving-indicator": {
|
|
57
|
+
"symptom": "the save button is never disabled while the request is in flight, so users double-submit.",
|
|
58
|
+
"breaks": [(
|
|
59
|
+
STORE,
|
|
60
|
+
" this.set({ isSaving: true, errorMessage: null, successMessage: null });",
|
|
61
|
+
" this.set({ errorMessage: null, successMessage: null });",
|
|
62
|
+
)],
|
|
63
|
+
},
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class ReactWorkspace:
|
|
68
|
+
def __init__(self, task_id: str):
|
|
69
|
+
if task_id not in TASKS:
|
|
70
|
+
raise ValueError(f"unknown task {task_id}; valid: {', '.join(TASKS)}")
|
|
71
|
+
self.task_id = task_id
|
|
72
|
+
base = AGENT_DOM / f".bench-tmp-{next(tempfile._get_candidate_names())}"
|
|
73
|
+
self.dir = base / "benchmark"
|
|
74
|
+
base.mkdir(parents=True)
|
|
75
|
+
shutil.copytree(
|
|
76
|
+
PACKAGE,
|
|
77
|
+
self.dir,
|
|
78
|
+
ignore=shutil.ignore_patterns("node_modules", "dist", ".turbo", "*.log"),
|
|
79
|
+
)
|
|
80
|
+
# Reuse the package's installed deps (react, happy-dom, tsx) instead of
|
|
81
|
+
# copying them: the temp dir lives inside the repo, so a symlink is enough.
|
|
82
|
+
if (PACKAGE / "node_modules").is_dir():
|
|
83
|
+
os.symlink(PACKAGE / "node_modules", self.dir / "node_modules")
|
|
84
|
+
for rel, old, new in TASKS[task_id]["breaks"]:
|
|
85
|
+
path = self.dir / rel
|
|
86
|
+
text = path.read_text(encoding="utf-8")
|
|
87
|
+
if old not in text:
|
|
88
|
+
raise RuntimeError(f"break target not found in {rel}")
|
|
89
|
+
path.write_text(text.replace(old, new, 1), encoding="utf-8")
|
|
90
|
+
|
|
91
|
+
# ---- oracle -----------------------------------------------------------
|
|
92
|
+
def oracle(self) -> Tuple[int, List[str], str]:
|
|
93
|
+
proc = subprocess.run(
|
|
94
|
+
["npx", "tsx", "src/bin/oracle-runner.ts"],
|
|
95
|
+
cwd=str(self.dir),
|
|
96
|
+
capture_output=True,
|
|
97
|
+
text=True,
|
|
98
|
+
timeout=300,
|
|
99
|
+
)
|
|
100
|
+
out = (proc.stdout or "").strip().splitlines()
|
|
101
|
+
for line in reversed(out):
|
|
102
|
+
try:
|
|
103
|
+
payload = json.loads(line)
|
|
104
|
+
except json.JSONDecodeError:
|
|
105
|
+
continue
|
|
106
|
+
return int(payload.get("passed", 0)), list(payload.get("failed", [])), "PASS" if payload.get("passed") == 12 else "FAIL"
|
|
107
|
+
tail = ((proc.stderr or "") + (proc.stdout or "")).strip().splitlines()
|
|
108
|
+
detail = " | ".join(tail[-3:])[:400] if tail else "no output"
|
|
109
|
+
return 0, [], f"RUNNER ERROR: {detail}"
|
|
110
|
+
|
|
111
|
+
# ---- tools ------------------------------------------------------------
|
|
112
|
+
def _resolve(self, rel: str) -> Path:
|
|
113
|
+
candidate = (self.dir / rel).resolve()
|
|
114
|
+
root = self.dir.resolve()
|
|
115
|
+
if candidate != root and root not in candidate.parents:
|
|
116
|
+
raise ValueError(f"path escapes the workspace: {rel}")
|
|
117
|
+
return candidate
|
|
118
|
+
|
|
119
|
+
def list_files(self, path: str = "sandboxes", depth: int = 3) -> Any:
|
|
120
|
+
base = self._resolve(path)
|
|
121
|
+
if not base.exists():
|
|
122
|
+
return {"error": f"no such path: {path}"}
|
|
123
|
+
lines: List[str] = []
|
|
124
|
+
for entry in sorted(base.rglob("*")):
|
|
125
|
+
rel = entry.relative_to(base)
|
|
126
|
+
if len(rel.parts) > max(0, min(int(depth), 4)):
|
|
127
|
+
continue
|
|
128
|
+
lines.append(f"{rel}{'/' if entry.is_dir() else ''}")
|
|
129
|
+
if len(lines) >= 120:
|
|
130
|
+
lines.append("… truncated")
|
|
131
|
+
break
|
|
132
|
+
return {"path": path, "entries": lines}
|
|
133
|
+
|
|
134
|
+
def read_file(self, path: str, start: int = 1, end: int = 180) -> Any:
|
|
135
|
+
target = self._resolve(path)
|
|
136
|
+
if not target.is_file():
|
|
137
|
+
return {"error": f"not a file: {path}"}
|
|
138
|
+
lines = target.read_text(encoding="utf-8", errors="replace").splitlines()
|
|
139
|
+
start = max(1, int(start))
|
|
140
|
+
end = min(len(lines), max(start, int(end)))
|
|
141
|
+
return {
|
|
142
|
+
"path": path,
|
|
143
|
+
"total_lines": len(lines),
|
|
144
|
+
"content": "\n".join(f"{i:>4}: {lines[i-1]}" for i in range(start, end + 1)),
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
def write_file(self, path: str, content: str) -> Any:
|
|
148
|
+
if not path.startswith(WRITE_PREFIX) or not path.endswith((".ts", ".tsx")):
|
|
149
|
+
return {"error": f"writes are limited to {WRITE_PREFIX}**/*.ts(x)"}
|
|
150
|
+
if path.endswith("adapter.ts"):
|
|
151
|
+
return {"error": "the adapter is read-only; edit the component/store"}
|
|
152
|
+
target = self._resolve(path)
|
|
153
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
154
|
+
target.write_text(content, encoding="utf-8")
|
|
155
|
+
return {"ok": True, "path": path, "bytes": len(content.encode())}
|
|
156
|
+
|
|
157
|
+
def run_command(self, cmd: str) -> Any:
|
|
158
|
+
if not cmd.strip().startswith("npx tsx src/bin/oracle-runner.ts"):
|
|
159
|
+
return {"error": "only `npx tsx src/bin/oracle-runner.ts` is allowed"}
|
|
160
|
+
proc = subprocess.run(cmd.split(), cwd=str(self.dir), capture_output=True, text=True, timeout=300)
|
|
161
|
+
return {"exit_code": proc.returncode, "output": ((proc.stdout or "") + (proc.stderr or "")).strip()[-2000:]}
|
|
162
|
+
|
|
163
|
+
def cleanup(self) -> None:
|
|
164
|
+
shutil.rmtree(self.dir.parent, ignore_errors=True)
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
TOOLS: List[Dict[str, Any]] = [
|
|
168
|
+
{
|
|
169
|
+
"type": "function",
|
|
170
|
+
"function": {
|
|
171
|
+
"name": "list_files",
|
|
172
|
+
"description": "List sandbox files (start from 'sandboxes').",
|
|
173
|
+
"parameters": {"type": "object", "properties": {"path": {"type": "string"}, "depth": {"type": "integer"}}},
|
|
174
|
+
},
|
|
175
|
+
},
|
|
176
|
+
{
|
|
177
|
+
"type": "function",
|
|
178
|
+
"function": {
|
|
179
|
+
"name": "read_file",
|
|
180
|
+
"description": "Read a line range of a sandbox file.",
|
|
181
|
+
"parameters": {
|
|
182
|
+
"type": "object",
|
|
183
|
+
"properties": {"path": {"type": "string"}, "start": {"type": "integer"}, "end": {"type": "integer"}},
|
|
184
|
+
"required": ["path"],
|
|
185
|
+
},
|
|
186
|
+
},
|
|
187
|
+
},
|
|
188
|
+
{
|
|
189
|
+
"type": "function",
|
|
190
|
+
"function": {
|
|
191
|
+
"name": "write_file",
|
|
192
|
+
"description": "Replace a sandbox source file (sandboxes/react-task-manager/src/**, not adapter.ts).",
|
|
193
|
+
"parameters": {
|
|
194
|
+
"type": "object",
|
|
195
|
+
"properties": {"path": {"type": "string"}, "content": {"type": "string"}},
|
|
196
|
+
"required": ["path", "content"],
|
|
197
|
+
},
|
|
198
|
+
},
|
|
199
|
+
},
|
|
200
|
+
{
|
|
201
|
+
"type": "function",
|
|
202
|
+
"function": {
|
|
203
|
+
"name": "run_command",
|
|
204
|
+
"description": "Run the 12-assertion oracle (`npx tsx src/bin/oracle-runner.ts`).",
|
|
205
|
+
"parameters": {"type": "object", "properties": {"cmd": {"type": "string"}}, "required": ["cmd"]},
|
|
206
|
+
},
|
|
207
|
+
},
|
|
208
|
+
]
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def registry(ws: ReactWorkspace) -> Dict[str, Any]:
|
|
212
|
+
return {
|
|
213
|
+
"list_files": ws.list_files,
|
|
214
|
+
"read_file": ws.read_file,
|
|
215
|
+
"write_file": ws.write_file,
|
|
216
|
+
"run_command": ws.run_command,
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
SYSTEM = (
|
|
221
|
+
"You are a senior React engineer working in a small sandbox. Use list_files/read_file to inspect the "
|
|
222
|
+
"component, store and adapters; write_file to fix the bug; run_command to run the 12-assertion oracle. "
|
|
223
|
+
"The oracle output is JSON with `passed` and `failed` assertion ids. Tests and adapter.ts are read-only. "
|
|
224
|
+
"Make the smallest correct change and stop as soon as the oracle reports 12."
|
|
225
|
+
)
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def task_prompt(task_id: str) -> str:
|
|
229
|
+
return (
|
|
230
|
+
f"The task manager has a regression: {TASKS[task_id]['symptom']}\n"
|
|
231
|
+
"Find the cause and fix the sandbox source. "
|
|
232
|
+
"Verification: `npx tsx src/bin/oracle-runner.ts` must print {\"passed\":12,\"failed\":[]}. "
|
|
233
|
+
"Do not modify the oracle, adapter.ts, or the test harness."
|
|
234
|
+
)
|
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
"""Runs benchmark arms and writes the measured report."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import tempfile
|
|
7
|
+
import time
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Any, Dict, List, Optional
|
|
10
|
+
|
|
11
|
+
from src.bench import go_target, react_target
|
|
12
|
+
from src.bench.driver import BudgetExceeded, DeepSeekClient, run_agent
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def run_one(
|
|
16
|
+
arm: str,
|
|
17
|
+
task_id: str,
|
|
18
|
+
helper: Path,
|
|
19
|
+
model: str = "deepseek-chat",
|
|
20
|
+
max_steps: int = 14,
|
|
21
|
+
budget_usd: float = 1.0,
|
|
22
|
+
) -> Dict[str, Any]:
|
|
23
|
+
ws = go_target.GoWorkspace(task_id, helper)
|
|
24
|
+
started = time.time()
|
|
25
|
+
try:
|
|
26
|
+
before = ws.oracle()
|
|
27
|
+
client = DeepSeekClient(model=model, temperature=0.0)
|
|
28
|
+
system = go_target.SYSTEM_OUMV if arm == "oumv" else go_target.SYSTEM_BASELINE
|
|
29
|
+
tools = go_target.OUMV_TOOLS if arm == "oumv" else go_target.BASE_TOOLS
|
|
30
|
+
registry = go_target.registry(ws, arm)
|
|
31
|
+
|
|
32
|
+
result = run_agent(
|
|
33
|
+
client=client,
|
|
34
|
+
system_prompt=system,
|
|
35
|
+
task_prompt=go_target.task_prompt(task_id),
|
|
36
|
+
tools=tools,
|
|
37
|
+
registry=registry,
|
|
38
|
+
max_steps=max_steps,
|
|
39
|
+
budget_usd=budget_usd,
|
|
40
|
+
after_step=lambda _i: ws.oracle(),
|
|
41
|
+
)
|
|
42
|
+
after = ws.oracle()
|
|
43
|
+
return {
|
|
44
|
+
"arm": arm,
|
|
45
|
+
"task": task_id,
|
|
46
|
+
"oracle_before": {"passed": before[0], "failed": before[1]},
|
|
47
|
+
"oracle_after": {"passed": after[0], "failed": after[1]},
|
|
48
|
+
"solved": after[0] == 12,
|
|
49
|
+
"wall_clock_s": round(time.time() - started, 1),
|
|
50
|
+
**result,
|
|
51
|
+
}
|
|
52
|
+
except BudgetExceeded as exc:
|
|
53
|
+
return {
|
|
54
|
+
"arm": arm,
|
|
55
|
+
"task": task_id,
|
|
56
|
+
"solved": False,
|
|
57
|
+
"stop_reason": "budget_exceeded",
|
|
58
|
+
"error": str(exc),
|
|
59
|
+
"wall_clock_s": round(time.time() - started, 1),
|
|
60
|
+
}
|
|
61
|
+
finally:
|
|
62
|
+
ws.cleanup()
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def run_matrix(
|
|
66
|
+
tasks: List[str],
|
|
67
|
+
arms: List[str],
|
|
68
|
+
runs: int = 1,
|
|
69
|
+
model: str = "deepseek-chat",
|
|
70
|
+
max_steps: int = 14,
|
|
71
|
+
budget_usd: float = 1.0,
|
|
72
|
+
) -> Dict[str, Any]:
|
|
73
|
+
helper = go_target.build_helper()
|
|
74
|
+
results: List[Dict[str, Any]] = []
|
|
75
|
+
spent = 0.0
|
|
76
|
+
aborted: Optional[str] = None
|
|
77
|
+
for run_idx in range(1, runs + 1):
|
|
78
|
+
for task_id in tasks:
|
|
79
|
+
for arm in arms:
|
|
80
|
+
if spent >= budget_usd:
|
|
81
|
+
aborted = f"global budget ${budget_usd} exhausted after ${spent:.4f}"
|
|
82
|
+
break
|
|
83
|
+
per_run_budget = max(budget_usd - spent, 0.01)
|
|
84
|
+
row = run_one(arm, task_id, helper, model=model, max_steps=max_steps, budget_usd=per_run_budget)
|
|
85
|
+
row["run"] = run_idx
|
|
86
|
+
results.append(row)
|
|
87
|
+
spent += float((row.get("usage") or {}).get("usd") or 0.0)
|
|
88
|
+
if aborted:
|
|
89
|
+
break
|
|
90
|
+
if aborted:
|
|
91
|
+
break
|
|
92
|
+
return {
|
|
93
|
+
"target": "go",
|
|
94
|
+
"tasks": tasks,
|
|
95
|
+
"arms": arms,
|
|
96
|
+
"runs": runs,
|
|
97
|
+
"model": model,
|
|
98
|
+
"budget_usd": budget_usd,
|
|
99
|
+
"spent_usd": round(spent, 6),
|
|
100
|
+
"aborted": aborted,
|
|
101
|
+
"results": results,
|
|
102
|
+
"generated_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def run_react_one(
|
|
108
|
+
task_id: str,
|
|
109
|
+
model: str = "deepseek-chat",
|
|
110
|
+
max_steps: int = 14,
|
|
111
|
+
budget_usd: float = 1.0,
|
|
112
|
+
) -> Dict[str, Any]:
|
|
113
|
+
ws = react_target.ReactWorkspace(task_id)
|
|
114
|
+
started = time.time()
|
|
115
|
+
try:
|
|
116
|
+
before = ws.oracle()
|
|
117
|
+
client = DeepSeekClient(model=model, temperature=0.0)
|
|
118
|
+
result = run_agent(
|
|
119
|
+
client=client,
|
|
120
|
+
system_prompt=react_target.SYSTEM,
|
|
121
|
+
task_prompt=react_target.task_prompt(task_id),
|
|
122
|
+
tools=react_target.TOOLS,
|
|
123
|
+
registry=react_target.registry(ws),
|
|
124
|
+
max_steps=max_steps,
|
|
125
|
+
budget_usd=budget_usd,
|
|
126
|
+
after_step=lambda _i: ws.oracle(),
|
|
127
|
+
)
|
|
128
|
+
after = ws.oracle()
|
|
129
|
+
return {
|
|
130
|
+
"arm": "baseline",
|
|
131
|
+
"task": task_id,
|
|
132
|
+
"oracle_before": {"passed": before[0], "failed": before[1]},
|
|
133
|
+
"oracle_after": {"passed": after[0], "failed": after[1]},
|
|
134
|
+
"solved": after[0] == 12,
|
|
135
|
+
"wall_clock_s": round(time.time() - started, 1),
|
|
136
|
+
**result,
|
|
137
|
+
}
|
|
138
|
+
except BudgetExceeded as exc:
|
|
139
|
+
return {"arm": "baseline", "task": task_id, "solved": False,
|
|
140
|
+
"stop_reason": "budget_exceeded", "error": str(exc),
|
|
141
|
+
"wall_clock_s": round(time.time() - started, 1)}
|
|
142
|
+
finally:
|
|
143
|
+
ws.cleanup()
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def run_react_matrix(
|
|
147
|
+
tasks: List[str],
|
|
148
|
+
runs: int = 1,
|
|
149
|
+
model: str = "deepseek-chat",
|
|
150
|
+
max_steps: int = 14,
|
|
151
|
+
budget_usd: float = 1.0,
|
|
152
|
+
) -> Dict[str, Any]:
|
|
153
|
+
results: List[Dict[str, Any]] = []
|
|
154
|
+
spent = 0.0
|
|
155
|
+
aborted: Optional[str] = None
|
|
156
|
+
for run_idx in range(1, runs + 1):
|
|
157
|
+
for task_id in tasks:
|
|
158
|
+
if spent >= budget_usd:
|
|
159
|
+
aborted = f"global budget ${budget_usd} exhausted after ${spent:.4f}"
|
|
160
|
+
break
|
|
161
|
+
row = run_react_one(task_id, model=model, max_steps=max_steps,
|
|
162
|
+
budget_usd=max(budget_usd - spent, 0.01))
|
|
163
|
+
row["run"] = run_idx
|
|
164
|
+
results.append(row)
|
|
165
|
+
spent += float((row.get("usage") or {}).get("usd") or 0.0)
|
|
166
|
+
if aborted:
|
|
167
|
+
break
|
|
168
|
+
return {
|
|
169
|
+
"target": "react",
|
|
170
|
+
"tasks": tasks,
|
|
171
|
+
"arms": ["baseline"],
|
|
172
|
+
"runs": runs,
|
|
173
|
+
"model": model,
|
|
174
|
+
"budget_usd": budget_usd,
|
|
175
|
+
"spent_usd": round(spent, 6),
|
|
176
|
+
"aborted": aborted,
|
|
177
|
+
"results": results,
|
|
178
|
+
"note": "React arm runs baseline only: the OUMV arm needs the Vite bridge (`tokensafe dev`).",
|
|
179
|
+
"generated_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def summarize(report: Dict[str, Any]) -> List[Dict[str, Any]]:
|
|
184
|
+
rows: Dict[str, Dict[str, Any]] = {}
|
|
185
|
+
for result in report["results"]:
|
|
186
|
+
key = result["arm"]
|
|
187
|
+
row = rows.setdefault(key, {"arm": key, "runs": 0, "solved": 0, "input": 0, "output": 0, "usd": 0.0, "steps": 0})
|
|
188
|
+
row["runs"] += 1
|
|
189
|
+
row["solved"] += 1 if result.get("solved") else 0
|
|
190
|
+
usage = result.get("usage") or {}
|
|
191
|
+
row["input"] += int(usage.get("input_tokens") or 0)
|
|
192
|
+
row["output"] += int(usage.get("output_tokens") or 0)
|
|
193
|
+
row["usd"] += float(usage.get("usd") or 0.0)
|
|
194
|
+
row["steps"] += len(result.get("steps") or [])
|
|
195
|
+
return sorted(rows.values(), key=lambda r: r["arm"])
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def render_markdown(report: Dict[str, Any]) -> str:
|
|
199
|
+
lines = [
|
|
200
|
+
f"# OUMV benchmark — {report.get('target', 'go')} sandbox (measured)",
|
|
201
|
+
"",
|
|
202
|
+
f"> Model: `{report['model']}` · runs: {report['runs']} · budget: ${report['budget_usd']} · "
|
|
203
|
+
f"spent: ${report['spent_usd']} · {report['generated_at']}",
|
|
204
|
+
"",
|
|
205
|
+
"## Methodology",
|
|
206
|
+
"",
|
|
207
|
+
"- Each arm starts from a throwaway copy of the `tokensafe-backend/go` module with one deliberate regression.",
|
|
208
|
+
"- Correctness is the real 12-assertion oracle (`go test ./benchmark -run TestGroundTruthOracleVanilla`), re-run after every agent step.",
|
|
209
|
+
"- Token and cost numbers come from the provider `usage` payload; prices are a pinned snapshot printed in the JSON artifact.",
|
|
210
|
+
"- `baseline` uses file/command tools only; `oumv` gets the same tools plus observe/getSource/verify/impact served by the OUMV runtime.",
|
|
211
|
+
"",
|
|
212
|
+
"## Results",
|
|
213
|
+
"",
|
|
214
|
+
"| Arm | Runs | Solved | Steps | Input tokens | Output tokens | Cost |",
|
|
215
|
+
"| :--- | ---: | ---: | ---: | ---: | ---: | ---: |",
|
|
216
|
+
]
|
|
217
|
+
for row in summarize(report):
|
|
218
|
+
lines.append(
|
|
219
|
+
f"| `{row['arm']}` | {row['runs']} | {row['solved']}/{row['runs']} | {row['steps']} | "
|
|
220
|
+
f"{row['input']:,} | {row['output']:,} | ${row['usd']:.4f} |"
|
|
221
|
+
)
|
|
222
|
+
if report.get("aborted"):
|
|
223
|
+
lines += ["", f"> Stopped early: {report['aborted']}"]
|
|
224
|
+
lines += ["", "## Per-run detail", "", "| Run | Arm | Task | Oracle before | Oracle after | Stop | Steps |", "| ---: | :--- | :--- | :--- | :--- | :--- | ---: |"]
|
|
225
|
+
for result in report["results"]:
|
|
226
|
+
before = result.get("oracle_before") or {}
|
|
227
|
+
after = result.get("oracle_after") or {}
|
|
228
|
+
lines.append(
|
|
229
|
+
f"| {result.get('run')} | `{result['arm']}` | {result['task']} | "
|
|
230
|
+
f"{before.get('passed', '—')}/12 | {after.get('passed', '—')}/12 | "
|
|
231
|
+
f"{result.get('stop_reason', '—')} | {len(result.get('steps') or [])} |"
|
|
232
|
+
)
|
|
233
|
+
return "\n".join(lines) + "\n"
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def write_artifacts(report: Dict[str, Any], out_dir: Optional[Path] = None) -> Dict[str, str]:
|
|
237
|
+
from src.paths import resolve_data_dir
|
|
238
|
+
|
|
239
|
+
base = Path(out_dir) if out_dir else Path(resolve_data_dir()) / "bench"
|
|
240
|
+
base.mkdir(parents=True, exist_ok=True)
|
|
241
|
+
stamp = time.strftime("%Y%m%d-%H%M%S", time.gmtime())
|
|
242
|
+
target = report.get("target", "go")
|
|
243
|
+
json_path = base / f"{target}-{stamp}.json"
|
|
244
|
+
md_path = base / f"{target}-{stamp}.md"
|
|
245
|
+
json_path.write_text(json.dumps(report, indent=2, ensure_ascii=False), encoding="utf-8")
|
|
246
|
+
md_path.write_text(render_markdown(report), encoding="utf-8")
|
|
247
|
+
return {"json": str(json_path), "markdown": str(md_path)}
|