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,219 @@
|
|
|
1
|
+
"""Minimal, measured agent loop for OUMV benchmarks.
|
|
2
|
+
|
|
3
|
+
Deliberately small: one OpenAI-compatible endpoint (DeepSeek by default), explicit
|
|
4
|
+
tool schemas, a hard step cap and a hard USD budget. Every token number comes from
|
|
5
|
+
the provider's own `usage` payload — nothing is estimated from bytes, and no
|
|
6
|
+
fixture traces are involved.
|
|
7
|
+
|
|
8
|
+
Prices are a pinned snapshot; the report prints them so a reader can recompute the
|
|
9
|
+
cost. Update the table when the provider changes prices (and bump `PRICE_SNAPSHOT`).
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import json
|
|
15
|
+
import os
|
|
16
|
+
import urllib.error
|
|
17
|
+
import urllib.request
|
|
18
|
+
from dataclasses import dataclass, field
|
|
19
|
+
from typing import Any, Callable, Dict, List, Optional, Tuple
|
|
20
|
+
|
|
21
|
+
PRICE_SNAPSHOT = "2026-11-26"
|
|
22
|
+
# USD per 1M tokens: cache-miss input, cache-hit input, output.
|
|
23
|
+
PRICES: Dict[str, Dict[str, float]] = {
|
|
24
|
+
"deepseek-chat": {"input_miss": 0.27, "input_hit": 0.07, "output": 1.10},
|
|
25
|
+
"deepseek-flash": {"input_miss": 0.27, "input_hit": 0.07, "output": 1.10},
|
|
26
|
+
}
|
|
27
|
+
DEFAULT_BASE_URL = "https://api.deepseek.com"
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def resolve_api_key() -> str:
|
|
31
|
+
key = os.environ.get("DEEPSEEK_API_KEY", "").strip()
|
|
32
|
+
if key:
|
|
33
|
+
return key
|
|
34
|
+
path = os.path.expanduser("~/.tokensafe/data/config.json")
|
|
35
|
+
try:
|
|
36
|
+
with open(path, "r", encoding="utf-8") as f:
|
|
37
|
+
return str(json.load(f).get("deepseek_api_key") or "").strip()
|
|
38
|
+
except Exception:
|
|
39
|
+
return ""
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass
|
|
43
|
+
class Usage:
|
|
44
|
+
input_tokens: int = 0
|
|
45
|
+
cache_hit_tokens: int = 0
|
|
46
|
+
output_tokens: int = 0
|
|
47
|
+
calls: int = 0
|
|
48
|
+
|
|
49
|
+
def add(self, payload: Dict[str, Any]) -> None:
|
|
50
|
+
self.calls += 1
|
|
51
|
+
self.input_tokens += int(payload.get("prompt_tokens") or 0)
|
|
52
|
+
self.cache_hit_tokens += int(payload.get("prompt_cache_hit_tokens") or 0)
|
|
53
|
+
self.output_tokens += int(payload.get("completion_tokens") or 0)
|
|
54
|
+
|
|
55
|
+
@property
|
|
56
|
+
def cache_miss_tokens(self) -> int:
|
|
57
|
+
return max(self.input_tokens - self.cache_hit_tokens, 0)
|
|
58
|
+
|
|
59
|
+
def usd(self, model: str) -> float:
|
|
60
|
+
price = PRICES.get(model, PRICES["deepseek-chat"])
|
|
61
|
+
return round(
|
|
62
|
+
(self.cache_miss_tokens / 1_000_000) * price["input_miss"]
|
|
63
|
+
+ (self.cache_hit_tokens / 1_000_000) * price["input_hit"]
|
|
64
|
+
+ (self.output_tokens / 1_000_000) * price["output"],
|
|
65
|
+
6,
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
def as_dict(self, model: str) -> Dict[str, Any]:
|
|
69
|
+
return {
|
|
70
|
+
"calls": self.calls,
|
|
71
|
+
"input_tokens": self.input_tokens,
|
|
72
|
+
"cache_hit_tokens": self.cache_hit_tokens,
|
|
73
|
+
"cache_miss_tokens": self.cache_miss_tokens,
|
|
74
|
+
"output_tokens": self.output_tokens,
|
|
75
|
+
"usd": self.usd(model),
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
class BudgetExceeded(RuntimeError):
|
|
80
|
+
pass
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
class DeepSeekClient:
|
|
84
|
+
def __init__(
|
|
85
|
+
self,
|
|
86
|
+
model: str = "deepseek-chat",
|
|
87
|
+
temperature: float = 0.0,
|
|
88
|
+
base_url: Optional[str] = None,
|
|
89
|
+
timeout: float = 120.0,
|
|
90
|
+
):
|
|
91
|
+
self.model = model
|
|
92
|
+
self.temperature = temperature
|
|
93
|
+
self.base_url = (base_url or os.environ.get("DEEPSEEK_BASE_URL") or DEFAULT_BASE_URL).rstrip("/")
|
|
94
|
+
self.timeout = timeout
|
|
95
|
+
self.api_key = resolve_api_key()
|
|
96
|
+
if not self.api_key:
|
|
97
|
+
raise RuntimeError(
|
|
98
|
+
"no DeepSeek API key: set DEEPSEEK_API_KEY or write deepseek_api_key "
|
|
99
|
+
"into ~/.tokensafe/data/config.json"
|
|
100
|
+
)
|
|
101
|
+
|
|
102
|
+
def chat(self, messages: List[Dict[str, Any]], tools: Optional[List[Dict[str, Any]]] = None) -> Tuple[Dict[str, Any], Dict[str, Any]]:
|
|
103
|
+
body: Dict[str, Any] = {
|
|
104
|
+
"model": self.model,
|
|
105
|
+
"messages": messages,
|
|
106
|
+
"temperature": self.temperature,
|
|
107
|
+
}
|
|
108
|
+
if tools:
|
|
109
|
+
body["tools"] = tools
|
|
110
|
+
body["tool_choice"] = "auto"
|
|
111
|
+
req = urllib.request.Request(
|
|
112
|
+
f"{self.base_url}/chat/completions",
|
|
113
|
+
data=json.dumps(body).encode(),
|
|
114
|
+
headers={"Content-Type": "application/json", "Authorization": f"Bearer {self.api_key}"},
|
|
115
|
+
method="POST",
|
|
116
|
+
)
|
|
117
|
+
try:
|
|
118
|
+
with urllib.request.urlopen(req, timeout=self.timeout) as resp:
|
|
119
|
+
payload = json.loads(resp.read().decode())
|
|
120
|
+
except urllib.error.HTTPError as exc:
|
|
121
|
+
raise RuntimeError(f"provider HTTP {exc.code}: {exc.read().decode()[:300]}") from exc
|
|
122
|
+
return payload["choices"][0]["message"], payload.get("usage") or {}
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
ToolFn = Callable[..., Any]
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
@dataclass
|
|
129
|
+
class StepRecord:
|
|
130
|
+
index: int
|
|
131
|
+
tool_calls: List[str] = field(default_factory=list)
|
|
132
|
+
duration_ms: float = 0.0
|
|
133
|
+
oracle_passed: Optional[int] = None
|
|
134
|
+
oracle_failed: List[str] = field(default_factory=list)
|
|
135
|
+
note: str = ""
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def run_agent(
|
|
139
|
+
client: DeepSeekClient,
|
|
140
|
+
system_prompt: str,
|
|
141
|
+
task_prompt: str,
|
|
142
|
+
tools: List[Dict[str, Any]],
|
|
143
|
+
registry: Dict[str, ToolFn],
|
|
144
|
+
max_steps: int = 14,
|
|
145
|
+
budget_usd: float = 1.0,
|
|
146
|
+
after_step: Optional[Callable[[int], Tuple[Optional[int], List[str], str]]] = None,
|
|
147
|
+
stop_when_solved: bool = True,
|
|
148
|
+
) -> Dict[str, Any]:
|
|
149
|
+
"""Runs one tool loop. Returns messages-independent accounting + step log."""
|
|
150
|
+
usage = Usage()
|
|
151
|
+
steps: List[StepRecord] = []
|
|
152
|
+
messages: List[Dict[str, Any]] = [
|
|
153
|
+
{"role": "system", "content": system_prompt},
|
|
154
|
+
{"role": "user", "content": task_prompt},
|
|
155
|
+
]
|
|
156
|
+
stop_reason = "step_limit"
|
|
157
|
+
|
|
158
|
+
for index in range(1, max_steps + 1):
|
|
159
|
+
message, raw_usage = client.chat(messages, tools)
|
|
160
|
+
usage.add(raw_usage)
|
|
161
|
+
|
|
162
|
+
calls = message.get("tool_calls") or []
|
|
163
|
+
messages.append(message)
|
|
164
|
+
|
|
165
|
+
record = StepRecord(index=index, tool_calls=[c["function"]["name"] for c in calls])
|
|
166
|
+
if not calls:
|
|
167
|
+
stop_reason = "agent_finished"
|
|
168
|
+
steps.append(record)
|
|
169
|
+
break
|
|
170
|
+
|
|
171
|
+
for call in calls:
|
|
172
|
+
name = call["function"]["name"]
|
|
173
|
+
try:
|
|
174
|
+
args = json.loads(call["function"].get("arguments") or "{}")
|
|
175
|
+
except json.JSONDecodeError:
|
|
176
|
+
args = {}
|
|
177
|
+
fn = registry.get(name)
|
|
178
|
+
try:
|
|
179
|
+
result = fn(**args) if fn else {"error": f"unknown tool {name}"}
|
|
180
|
+
except Exception as exc: # tool errors are observations, not crashes
|
|
181
|
+
result = {"error": f"{type(exc).__name__}: {exc}"}
|
|
182
|
+
messages.append({
|
|
183
|
+
"role": "tool",
|
|
184
|
+
"tool_call_id": call.get("id", ""),
|
|
185
|
+
"content": json.dumps(result, ensure_ascii=False)[:6000],
|
|
186
|
+
})
|
|
187
|
+
|
|
188
|
+
if after_step:
|
|
189
|
+
passed, failed, note = after_step(index)
|
|
190
|
+
record.oracle_passed, record.oracle_failed, record.note = passed, failed, note
|
|
191
|
+
steps.append(record)
|
|
192
|
+
|
|
193
|
+
if stop_when_solved and record.oracle_passed == 12:
|
|
194
|
+
stop_reason = "solved"
|
|
195
|
+
break
|
|
196
|
+
|
|
197
|
+
if usage.usd(client.model) > budget_usd:
|
|
198
|
+
raise BudgetExceeded(f"budget ${budget_usd} exceeded at step {index} (${usage.usd(client.model)})")
|
|
199
|
+
else:
|
|
200
|
+
stop_reason = "max_steps"
|
|
201
|
+
|
|
202
|
+
return {
|
|
203
|
+
"model": client.model,
|
|
204
|
+
"temperature": client.temperature,
|
|
205
|
+
"price_snapshot": PRICE_SNAPSHOT,
|
|
206
|
+
"prices_usd_per_mtok": PRICES.get(client.model),
|
|
207
|
+
"stop_reason": stop_reason,
|
|
208
|
+
"usage": usage.as_dict(client.model),
|
|
209
|
+
"steps": [
|
|
210
|
+
{
|
|
211
|
+
"index": s.index,
|
|
212
|
+
"tools": s.tool_calls,
|
|
213
|
+
"oracle_passed": s.oracle_passed,
|
|
214
|
+
"oracle_failed": s.oracle_failed,
|
|
215
|
+
"note": s.note,
|
|
216
|
+
}
|
|
217
|
+
for s in steps
|
|
218
|
+
],
|
|
219
|
+
}
|
|
@@ -0,0 +1,360 @@
|
|
|
1
|
+
"""Go sandbox target for the OUMV benchmark.
|
|
2
|
+
|
|
3
|
+
The workstation copy is a throwaway module containing only what is needed to build
|
|
4
|
+
and evaluate the AUB sandbox. Two arms edit the *same* file:
|
|
5
|
+
|
|
6
|
+
* baseline — the agent gets file/command tools only;
|
|
7
|
+
* oumv — the same tools plus observe/getSource/verify/impact, served by a
|
|
8
|
+
helper binary that mounts the OUMV runtime over the same handler.
|
|
9
|
+
|
|
10
|
+
The 12-assertion oracle (`go test ./benchmark -run TestGroundTruthOracleVanilla`)
|
|
11
|
+
is the single source of truth for correctness; it runs after every agent step.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import json
|
|
17
|
+
import os
|
|
18
|
+
import re
|
|
19
|
+
import shutil
|
|
20
|
+
import subprocess
|
|
21
|
+
import tempfile
|
|
22
|
+
from pathlib import Path
|
|
23
|
+
from typing import Any, Dict, List, Optional, Tuple
|
|
24
|
+
|
|
25
|
+
REPO_ROOT = Path(__file__).resolve().parents[3]
|
|
26
|
+
GO_ROOT = REPO_ROOT / "tokensafe-backend" / "go"
|
|
27
|
+
COPY_ITEMS = ("go.mod", "go.sum", "tokensafe.go", "pkg", "benchmark", "cmd")
|
|
28
|
+
SANDBOX_FILE = "benchmark/sandboxes/vanilla_gin/app.go"
|
|
29
|
+
ALLOWED_WRITE_PREFIX = "benchmark/sandboxes/"
|
|
30
|
+
MAX_TOOL_OUTPUT = 4000
|
|
31
|
+
|
|
32
|
+
TASKS: Dict[str, Dict[str, Any]] = {
|
|
33
|
+
"product-create-status": {
|
|
34
|
+
"symptom": "creating a product returns HTTP 200 instead of 201, so the contract test fails.",
|
|
35
|
+
"breaks": [(f"{SANDBOX_FILE}", "c.JSON(http.StatusCreated, p)", "c.JSON(http.StatusOK, p)")],
|
|
36
|
+
},
|
|
37
|
+
"order-conflict-status": {
|
|
38
|
+
"symptom": "a duplicate idempotency key returns HTTP 400 instead of 409, so clients retry blindly.",
|
|
39
|
+
"breaks": [(
|
|
40
|
+
SANDBOX_FILE,
|
|
41
|
+
'c.JSON(http.StatusConflict, gin.H{"error": errMsg})',
|
|
42
|
+
'c.JSON(http.StatusBadRequest, gin.H{"error": errMsg})',
|
|
43
|
+
)],
|
|
44
|
+
},
|
|
45
|
+
"product-validation-status": {
|
|
46
|
+
"symptom": "an invalid product payload is accepted with HTTP 200 instead of being rejected with 422.",
|
|
47
|
+
"breaks": [(
|
|
48
|
+
SANDBOX_FILE,
|
|
49
|
+
# the CreateProduct validation branch (the binding branch alone is not
|
|
50
|
+
# exercised by TC03, which sends a well-formed but invalid payload)
|
|
51
|
+
'p, err := db.CreateProduct(req)\n\t\tif err != nil {\n\t\t\tc.JSON(http.StatusUnprocessableEntity, gin.H{"error": err.Error()})',
|
|
52
|
+
'p, err := db.CreateProduct(req)\n\t\tif err != nil {\n\t\t\tc.JSON(http.StatusOK, gin.H{"error": err.Error()})',
|
|
53
|
+
)],
|
|
54
|
+
},
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _run(cmd: List[str], cwd: Path, timeout: float = 240.0, env: Optional[Dict[str, str]] = None) -> subprocess.CompletedProcess:
|
|
59
|
+
return subprocess.run(cmd, cwd=str(cwd), capture_output=True, text=True, timeout=timeout, env=env)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class GoWorkspace:
|
|
63
|
+
def __init__(self, task_id: str, helper: Path):
|
|
64
|
+
if task_id not in TASKS:
|
|
65
|
+
raise ValueError(f"unknown task {task_id}; valid: {', '.join(TASKS)}")
|
|
66
|
+
self.task_id = task_id
|
|
67
|
+
self.helper = helper
|
|
68
|
+
self.dir = Path(tempfile.mkdtemp(prefix=f"oumv-bench-{task_id}-")) / "go"
|
|
69
|
+
self.dir.mkdir(parents=True)
|
|
70
|
+
for item in COPY_ITEMS:
|
|
71
|
+
src = GO_ROOT / item
|
|
72
|
+
dst = self.dir / item
|
|
73
|
+
if src.is_dir():
|
|
74
|
+
shutil.copytree(src, dst)
|
|
75
|
+
else:
|
|
76
|
+
shutil.copy2(src, dst)
|
|
77
|
+
self.break_build()
|
|
78
|
+
|
|
79
|
+
# ---- task setup -------------------------------------------------------
|
|
80
|
+
def break_build(self) -> None:
|
|
81
|
+
for rel, old, new in TASKS[self.task_id]["breaks"]:
|
|
82
|
+
path = self.dir / rel
|
|
83
|
+
text = path.read_text(encoding="utf-8")
|
|
84
|
+
if old not in text:
|
|
85
|
+
raise RuntimeError(f"break target not found in {rel}: {old[:60]}")
|
|
86
|
+
path.write_text(text.replace(old, new, 1), encoding="utf-8")
|
|
87
|
+
|
|
88
|
+
# ---- oracle -----------------------------------------------------------
|
|
89
|
+
def oracle(self) -> Tuple[int, List[str], str]:
|
|
90
|
+
proc = _run(
|
|
91
|
+
["go", "test", "./benchmark", "-run", "TestGroundTruthOracleVanilla", "-count=1", "-v"],
|
|
92
|
+
cwd=self.dir,
|
|
93
|
+
env={**os.environ, "APP_ENV": "development"},
|
|
94
|
+
)
|
|
95
|
+
output = (proc.stdout or "") + (proc.stderr or "")
|
|
96
|
+
failed = sorted(set(re.findall(r"Assertion (TC\d+_\w+) failed", output)))
|
|
97
|
+
if proc.returncode == 0:
|
|
98
|
+
return 12, [], "PASS"
|
|
99
|
+
if not failed:
|
|
100
|
+
return 0, [], f"BUILD/TEST ERROR: {output.strip().splitlines()[-1][:200] if output.strip() else 'no output'}"
|
|
101
|
+
return 12 - len(failed), failed, "FAIL"
|
|
102
|
+
|
|
103
|
+
# ---- tools ------------------------------------------------------------
|
|
104
|
+
def _resolve(self, rel: str) -> Path:
|
|
105
|
+
candidate = (self.dir / rel).resolve()
|
|
106
|
+
root = self.dir.resolve()
|
|
107
|
+
if candidate != root and root not in candidate.parents:
|
|
108
|
+
raise ValueError(f"path escapes the workspace: {rel}")
|
|
109
|
+
return candidate
|
|
110
|
+
|
|
111
|
+
def list_files(self, path: str = ".", depth: int = 2) -> Any:
|
|
112
|
+
base = self._resolve(path)
|
|
113
|
+
if not base.exists():
|
|
114
|
+
return {"error": f"no such path: {path}"}
|
|
115
|
+
depth = max(0, min(int(depth), 4))
|
|
116
|
+
lines: List[str] = []
|
|
117
|
+
for entry in sorted(base.rglob("*")):
|
|
118
|
+
rel = entry.relative_to(base)
|
|
119
|
+
if len(rel.parts) > depth:
|
|
120
|
+
continue
|
|
121
|
+
if any(part in {".git", "node_modules"} for part in rel.parts):
|
|
122
|
+
continue
|
|
123
|
+
suffix = "/" if entry.is_dir() else ""
|
|
124
|
+
lines.append(f"{rel}{suffix}")
|
|
125
|
+
if len(lines) >= 120:
|
|
126
|
+
lines.append("… truncated")
|
|
127
|
+
break
|
|
128
|
+
return {"path": path, "entries": lines}
|
|
129
|
+
|
|
130
|
+
def read_file(self, path: str, start: int = 1, end: int = 160) -> Any:
|
|
131
|
+
target = self._resolve(path)
|
|
132
|
+
if not target.is_file():
|
|
133
|
+
return {"error": f"not a file: {path}"}
|
|
134
|
+
lines = target.read_text(encoding="utf-8", errors="replace").splitlines()
|
|
135
|
+
start = max(1, int(start))
|
|
136
|
+
end = min(len(lines), max(start, int(end)))
|
|
137
|
+
return {
|
|
138
|
+
"path": path,
|
|
139
|
+
"total_lines": len(lines),
|
|
140
|
+
"start": start,
|
|
141
|
+
"end": end,
|
|
142
|
+
"content": "\n".join(f"{i:>4}: {lines[i - 1]}" for i in range(start, end + 1)),
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
def write_file(self, path: str, content: str) -> Any:
|
|
146
|
+
if not path.startswith(ALLOWED_WRITE_PREFIX) or not path.endswith(".go"):
|
|
147
|
+
return {"error": f"writes are limited to {ALLOWED_WRITE_PREFIX}**/*.go"}
|
|
148
|
+
if path.endswith("_test.go"):
|
|
149
|
+
return {"error": "the oracle tests are read-only"}
|
|
150
|
+
target = self._resolve(path)
|
|
151
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
152
|
+
target.write_text(content, encoding="utf-8")
|
|
153
|
+
return {"ok": True, "path": path, "bytes": len(content.encode())}
|
|
154
|
+
|
|
155
|
+
def run_command(self, cmd: str) -> Any:
|
|
156
|
+
allowed_prefixes = ("go test ./benchmark", "go build ./", "go vet ./benchmark", "go test ./benchmark/")
|
|
157
|
+
if not cmd.strip().startswith(allowed_prefixes):
|
|
158
|
+
return {"error": "only `go test ./benchmark…`, `go build ./…` and `go vet ./benchmark…` are allowed"}
|
|
159
|
+
proc = _run(cmd.split(), cwd=self.dir, env={**os.environ, "APP_ENV": "development"})
|
|
160
|
+
out = ((proc.stdout or "") + (proc.stderr or "")).strip()
|
|
161
|
+
return {"exit_code": proc.returncode, "output": out[-MAX_TOOL_OUTPUT:]}
|
|
162
|
+
|
|
163
|
+
# ---- OUMV -------------------------------------------------------------
|
|
164
|
+
def oumv(self, method: str, params: Dict[str, Any]) -> Any:
|
|
165
|
+
request = {"jsonrpc": "2.0", "id": 1, "method": method, "params": params}
|
|
166
|
+
proc = subprocess.run(
|
|
167
|
+
[str(self.helper)],
|
|
168
|
+
input=json.dumps(request) + "\n",
|
|
169
|
+
capture_output=True,
|
|
170
|
+
text=True,
|
|
171
|
+
timeout=120,
|
|
172
|
+
cwd=str(self.dir),
|
|
173
|
+
env={**os.environ, "APP_ENV": "development"},
|
|
174
|
+
)
|
|
175
|
+
line = (proc.stdout or "").strip().splitlines()
|
|
176
|
+
if not line:
|
|
177
|
+
return {"error": f"oumv helper produced no output: {(proc.stderr or '')[:200]}"}
|
|
178
|
+
try:
|
|
179
|
+
payload = json.loads(line[-1])
|
|
180
|
+
except json.JSONDecodeError:
|
|
181
|
+
return {"error": f"invalid JSON from helper: {line[-1][:200]}"}
|
|
182
|
+
if payload.get("error"):
|
|
183
|
+
return {"error": payload["error"]}
|
|
184
|
+
return payload.get("result")
|
|
185
|
+
|
|
186
|
+
def cleanup(self) -> None:
|
|
187
|
+
shutil.rmtree(self.dir.parent, ignore_errors=True)
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def build_helper() -> Path:
|
|
191
|
+
"""Builds `cmd/benchoumv` once from the pristine module."""
|
|
192
|
+
out_dir = Path(tempfile.mkdtemp(prefix="oumv-bench-helper-"))
|
|
193
|
+
helper = out_dir / "benchoumv"
|
|
194
|
+
proc = _run(["go", "build", "-o", str(helper), "./cmd/benchoumv"], cwd=GO_ROOT)
|
|
195
|
+
if proc.returncode != 0:
|
|
196
|
+
raise RuntimeError(f"failed to build benchoumv: {(proc.stderr or proc.stdout)[-800:]}")
|
|
197
|
+
return helper
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
# ---- tool schemas ---------------------------------------------------------
|
|
201
|
+
|
|
202
|
+
BASE_TOOLS: List[Dict[str, Any]] = [
|
|
203
|
+
{
|
|
204
|
+
"type": "function",
|
|
205
|
+
"function": {
|
|
206
|
+
"name": "list_files",
|
|
207
|
+
"description": "List files under a workspace-relative path.",
|
|
208
|
+
"parameters": {
|
|
209
|
+
"type": "object",
|
|
210
|
+
"properties": {
|
|
211
|
+
"path": {"type": "string", "description": "Relative directory, default '.'"},
|
|
212
|
+
"depth": {"type": "integer", "description": "Max depth 0-4"},
|
|
213
|
+
},
|
|
214
|
+
},
|
|
215
|
+
},
|
|
216
|
+
},
|
|
217
|
+
{
|
|
218
|
+
"type": "function",
|
|
219
|
+
"function": {
|
|
220
|
+
"name": "read_file",
|
|
221
|
+
"description": "Read a line range of a workspace file.",
|
|
222
|
+
"parameters": {
|
|
223
|
+
"type": "object",
|
|
224
|
+
"properties": {
|
|
225
|
+
"path": {"type": "string"},
|
|
226
|
+
"start": {"type": "integer"},
|
|
227
|
+
"end": {"type": "integer"},
|
|
228
|
+
},
|
|
229
|
+
"required": ["path"],
|
|
230
|
+
},
|
|
231
|
+
},
|
|
232
|
+
},
|
|
233
|
+
{
|
|
234
|
+
"type": "function",
|
|
235
|
+
"function": {
|
|
236
|
+
"name": "write_file",
|
|
237
|
+
"description": "Replace a sandbox Go file (benchmark/sandboxes/**/*.go only).",
|
|
238
|
+
"parameters": {
|
|
239
|
+
"type": "object",
|
|
240
|
+
"properties": {"path": {"type": "string"}, "content": {"type": "string"}},
|
|
241
|
+
"required": ["path", "content"],
|
|
242
|
+
},
|
|
243
|
+
},
|
|
244
|
+
},
|
|
245
|
+
{
|
|
246
|
+
"type": "function",
|
|
247
|
+
"function": {
|
|
248
|
+
"name": "run_command",
|
|
249
|
+
"description": "Run an allowlisted Go command (go test ./benchmark…, go build ./…, go vet ./benchmark…).",
|
|
250
|
+
"parameters": {
|
|
251
|
+
"type": "object",
|
|
252
|
+
"properties": {"cmd": {"type": "string"}},
|
|
253
|
+
"required": ["cmd"],
|
|
254
|
+
},
|
|
255
|
+
},
|
|
256
|
+
},
|
|
257
|
+
]
|
|
258
|
+
|
|
259
|
+
OUMV_TOOLS: List[Dict[str, Any]] = BASE_TOOLS + [
|
|
260
|
+
{
|
|
261
|
+
"type": "function",
|
|
262
|
+
"function": {
|
|
263
|
+
"name": "oumv_observe",
|
|
264
|
+
"description": "OUMV observe: L0 pulse, L1 endpoint surface, L2 endpoint contract, L3 source, L4 traces.",
|
|
265
|
+
"parameters": {
|
|
266
|
+
"type": "object",
|
|
267
|
+
"properties": {
|
|
268
|
+
"level": {"type": "string", "enum": ["L0", "L1", "L2", "L3", "L4"]},
|
|
269
|
+
"target": {"type": "string", "description": "e.g. 'GET /api/products' or 'path#symbol'"},
|
|
270
|
+
},
|
|
271
|
+
"required": ["level"],
|
|
272
|
+
},
|
|
273
|
+
},
|
|
274
|
+
},
|
|
275
|
+
{
|
|
276
|
+
"type": "function",
|
|
277
|
+
"function": {
|
|
278
|
+
"name": "oumv_getSource",
|
|
279
|
+
"description": "OUMV source read with the sha256 OCC version token.",
|
|
280
|
+
"parameters": {
|
|
281
|
+
"type": "object",
|
|
282
|
+
"properties": {"path": {"type": "string"}, "symbol": {"type": "string"}},
|
|
283
|
+
"required": ["path"],
|
|
284
|
+
},
|
|
285
|
+
},
|
|
286
|
+
},
|
|
287
|
+
{
|
|
288
|
+
"type": "function",
|
|
289
|
+
"function": {
|
|
290
|
+
"name": "oumv_verify",
|
|
291
|
+
"description": "OUMV verify: dispatch a request (optionally with a JSON body) in-process and see status/body without starting a server.",
|
|
292
|
+
"parameters": {
|
|
293
|
+
"type": "object",
|
|
294
|
+
"properties": {
|
|
295
|
+
"target": {"type": "string", "description": "e.g. 'GET /api/products' or 'POST /api/orders'"},
|
|
296
|
+
"payload": {"type": "object", "description": "JSON body for POST/PUT targets"},
|
|
297
|
+
},
|
|
298
|
+
"required": ["target"],
|
|
299
|
+
},
|
|
300
|
+
},
|
|
301
|
+
},
|
|
302
|
+
{
|
|
303
|
+
"type": "function",
|
|
304
|
+
"function": {
|
|
305
|
+
"name": "oumv_understand",
|
|
306
|
+
"description": "OUMV understand: impact analysis for an endpoint target.",
|
|
307
|
+
"parameters": {
|
|
308
|
+
"type": "object",
|
|
309
|
+
"properties": {
|
|
310
|
+
"query": {"type": "string", "enum": ["impact", "causality"]},
|
|
311
|
+
"target": {"type": "string"},
|
|
312
|
+
},
|
|
313
|
+
"required": ["query", "target"],
|
|
314
|
+
},
|
|
315
|
+
},
|
|
316
|
+
},
|
|
317
|
+
]
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
def registry(ws: GoWorkspace, arm: str) -> Dict[str, Any]:
|
|
321
|
+
tools: Dict[str, Any] = {
|
|
322
|
+
"list_files": ws.list_files,
|
|
323
|
+
"read_file": ws.read_file,
|
|
324
|
+
"write_file": ws.write_file,
|
|
325
|
+
"run_command": ws.run_command,
|
|
326
|
+
}
|
|
327
|
+
if arm == "oumv":
|
|
328
|
+
tools.update({
|
|
329
|
+
"oumv_observe": lambda level, target="": ws.oumv("oumv/observe", {"level": level, "target": target}),
|
|
330
|
+
"oumv_getSource": lambda path, symbol="": ws.oumv("oumv/getSource", {"path": path, "symbol": symbol}),
|
|
331
|
+
"oumv_verify": lambda target, payload=None: ws.oumv(
|
|
332
|
+
"oumv/verify", {"target": target, "action": "probe", "payload": payload}
|
|
333
|
+
),
|
|
334
|
+
"oumv_understand": lambda query, target: ws.oumv("oumv/understand", {"query": query, "target": target}),
|
|
335
|
+
})
|
|
336
|
+
return tools
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
SYSTEM_BASELINE = (
|
|
340
|
+
"You are a senior Go engineer working in a small Go module. Use list_files/read_file to inspect code, "
|
|
341
|
+
"write_file to fix it, and run_command to verify. Tests and the oracle are read-only. "
|
|
342
|
+
"Make the smallest correct change; stop as soon as the oracle passes."
|
|
343
|
+
)
|
|
344
|
+
SYSTEM_OUMV = (
|
|
345
|
+
"You are a senior Go engineer working in a small Go module that exposes the OUMV runtime. "
|
|
346
|
+
"Prefer the OUMV tools before reading whole files: oumv_observe L1 lists endpoints, L2 gives an endpoint "
|
|
347
|
+
"contract, oumv_getSource returns source with an OCC version token, oumv_verify dispatches a request "
|
|
348
|
+
"in-process, oumv_understand gives impact analysis. Fix the code with write_file, confirm with "
|
|
349
|
+
"oumv_verify or run_command, and stop as soon as the oracle passes. Tests are read-only."
|
|
350
|
+
)
|
|
351
|
+
|
|
352
|
+
|
|
353
|
+
def task_prompt(task_id: str) -> str:
|
|
354
|
+
symptom = TASKS[task_id]["symptom"]
|
|
355
|
+
return (
|
|
356
|
+
f"The order API has a regression: {symptom}\n"
|
|
357
|
+
"Reproduce it, find the cause, and fix the handler code. "
|
|
358
|
+
"Verification: `go test ./benchmark -run TestGroundTruthOracleVanilla -count=1` must pass all 12 assertions. "
|
|
359
|
+
"Do not modify tests, the oracle, or the database package."
|
|
360
|
+
)
|