tokensafe 4.6.4 → 4.7.1
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 +30 -4
- package/hooks/claude_code_hook.py +17 -15
- package/hooks/kimi_hook.py +14 -12
- package/hooks/pre_invocation.py +7 -12
- package/hooks/session_start.py +8 -2
- package/kimi.plugin.json +2 -2
- package/package.json +2 -2
- package/plugin.json +2 -1
- package/rules/AGENTS.md +1 -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 +2 -1
- 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/agent_firewall.py +16 -1
- package/src/auto_inject.py +93 -7
- package/src/batch_editor.py +106 -15
- package/src/bench/__init__.py +1 -0
- package/src/bench/driver.py +234 -0
- package/src/bench/go_target.py +646 -0
- package/src/bench/mechanics.py +214 -0
- package/src/bench/react_target.py +541 -0
- package/src/bench/runner.py +331 -0
- package/src/bench/tokensafe_mcp.py +144 -0
- package/src/cli.py +156 -0
- package/src/history_compactor.py +200 -2
- package/src/installer.py +3 -3
- package/src/mcp_server.py +510 -237
- package/src/paths.py +41 -2
- package/src/retrofit.py +27 -5
- package/src/scaffold.py +8 -6
- package/src/scoped_search.py +67 -5
- package/src/session_brief.py +180 -15
- package/src/session_context.py +124 -0
- package/src/skeletonizer.py +9 -3
- package/src/telemetry_sync.py +1 -1
- package/src/version_checker.py +1 -1
|
@@ -0,0 +1,331 @@
|
|
|
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
|
+
model: str = "deepseek-chat",
|
|
19
|
+
max_steps: int = 14,
|
|
20
|
+
budget_usd: float = 1.0,
|
|
21
|
+
) -> Dict[str, Any]:
|
|
22
|
+
ws = go_target.GoWorkspace(task_id)
|
|
23
|
+
started = time.time()
|
|
24
|
+
try:
|
|
25
|
+
before = ws.oracle()
|
|
26
|
+
client = DeepSeekClient(model=model, temperature=0.0)
|
|
27
|
+
# one place decides prompt + schemas + dispatcher, so a schema the model sees is
|
|
28
|
+
# always a tool the dispatcher can run
|
|
29
|
+
system, tools, registry = go_target.build_arm(ws, arm)
|
|
30
|
+
|
|
31
|
+
result = run_agent(
|
|
32
|
+
client=client,
|
|
33
|
+
system_prompt=system,
|
|
34
|
+
task_prompt=go_target.task_prompt(task_id),
|
|
35
|
+
tools=tools,
|
|
36
|
+
registry=registry,
|
|
37
|
+
max_steps=max_steps,
|
|
38
|
+
budget_usd=budget_usd,
|
|
39
|
+
after_step=lambda _i: ws.oracle(),
|
|
40
|
+
)
|
|
41
|
+
after = ws.oracle()
|
|
42
|
+
return {
|
|
43
|
+
"arm": arm,
|
|
44
|
+
"task": task_id,
|
|
45
|
+
"oracle_before": {"passed": before[0], "failed": before[1]},
|
|
46
|
+
"oracle_after": {"passed": after[0], "failed": after[1]},
|
|
47
|
+
"solved": after[0] == 12,
|
|
48
|
+
"wall_clock_s": round(time.time() - started, 1),
|
|
49
|
+
**result,
|
|
50
|
+
}
|
|
51
|
+
except BudgetExceeded as exc:
|
|
52
|
+
return {
|
|
53
|
+
"arm": arm,
|
|
54
|
+
"task": task_id,
|
|
55
|
+
"solved": False,
|
|
56
|
+
"stop_reason": "budget_exceeded",
|
|
57
|
+
"error": str(exc),
|
|
58
|
+
"usage": getattr(exc, "usage", {}),
|
|
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
|
+
results: List[Dict[str, Any]] = []
|
|
74
|
+
spent = 0.0
|
|
75
|
+
aborted: Optional[str] = None
|
|
76
|
+
for run_idx in range(1, runs + 1):
|
|
77
|
+
for task_id in tasks:
|
|
78
|
+
for arm in arms:
|
|
79
|
+
if spent >= budget_usd:
|
|
80
|
+
aborted = f"global budget ${budget_usd} exhausted after ${spent:.4f}"
|
|
81
|
+
break
|
|
82
|
+
per_run_budget = max(budget_usd - spent, 0.01)
|
|
83
|
+
row = run_one(arm, task_id, model=model, max_steps=max_steps, budget_usd=per_run_budget)
|
|
84
|
+
row["run"] = run_idx
|
|
85
|
+
results.append(row)
|
|
86
|
+
spent += float((row.get("usage") or {}).get("usd") or 0.0)
|
|
87
|
+
if aborted:
|
|
88
|
+
break
|
|
89
|
+
if aborted:
|
|
90
|
+
break
|
|
91
|
+
return {
|
|
92
|
+
"target": "go",
|
|
93
|
+
"tasks": tasks,
|
|
94
|
+
"arms": arms,
|
|
95
|
+
"runs": runs,
|
|
96
|
+
"model": model,
|
|
97
|
+
"budget_usd": budget_usd,
|
|
98
|
+
"spent_usd": round(spent, 6),
|
|
99
|
+
"aborted": aborted,
|
|
100
|
+
"results": results,
|
|
101
|
+
"provenance": _provenance("go", tasks, arms),
|
|
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
|
+
arm: str = "baseline",
|
|
110
|
+
model: str = "deepseek-chat",
|
|
111
|
+
max_steps: int = 14,
|
|
112
|
+
budget_usd: float = 1.0,
|
|
113
|
+
) -> Dict[str, Any]:
|
|
114
|
+
ws = react_target.ReactWorkspace(task_id)
|
|
115
|
+
started = time.time()
|
|
116
|
+
try:
|
|
117
|
+
before = ws.oracle()
|
|
118
|
+
client = DeepSeekClient(model=model, temperature=0.0)
|
|
119
|
+
if arm == "oumv":
|
|
120
|
+
system, tools = react_target.SYSTEM_OUMV, react_target.OUMV_TOOLS
|
|
121
|
+
elif arm == "tokensafe":
|
|
122
|
+
system, tools = react_target.SYSTEM_TOKENSAFE, react_target.TOKENSAFE_TOOLS
|
|
123
|
+
else:
|
|
124
|
+
system, tools = react_target.SYSTEM, react_target.TOOLS
|
|
125
|
+
result = run_agent(
|
|
126
|
+
client=client,
|
|
127
|
+
system_prompt=system,
|
|
128
|
+
task_prompt=react_target.task_prompt(task_id),
|
|
129
|
+
tools=tools,
|
|
130
|
+
registry=react_target.registry(ws, arm),
|
|
131
|
+
max_steps=max_steps,
|
|
132
|
+
budget_usd=budget_usd,
|
|
133
|
+
after_step=lambda _i: ws.oracle(),
|
|
134
|
+
)
|
|
135
|
+
after = ws.oracle()
|
|
136
|
+
return {
|
|
137
|
+
"arm": arm,
|
|
138
|
+
"task": task_id,
|
|
139
|
+
"oracle_before": {"passed": before[0], "failed": before[1]},
|
|
140
|
+
"oracle_after": {"passed": after[0], "failed": after[1]},
|
|
141
|
+
"solved": after[0] == 12,
|
|
142
|
+
"wall_clock_s": round(time.time() - started, 1),
|
|
143
|
+
**result,
|
|
144
|
+
}
|
|
145
|
+
except BudgetExceeded as exc:
|
|
146
|
+
return {"arm": arm, "task": task_id, "solved": False,
|
|
147
|
+
"stop_reason": "budget_exceeded", "error": str(exc),
|
|
148
|
+
"usage": getattr(exc, "usage", {}),
|
|
149
|
+
"wall_clock_s": round(time.time() - started, 1)}
|
|
150
|
+
finally:
|
|
151
|
+
ws.cleanup()
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def run_react_matrix(
|
|
155
|
+
tasks: List[str],
|
|
156
|
+
arms: List[str],
|
|
157
|
+
runs: int = 1,
|
|
158
|
+
model: str = "deepseek-chat",
|
|
159
|
+
max_steps: int = 14,
|
|
160
|
+
budget_usd: float = 1.0,
|
|
161
|
+
) -> Dict[str, Any]:
|
|
162
|
+
results: List[Dict[str, Any]] = []
|
|
163
|
+
spent = 0.0
|
|
164
|
+
aborted: Optional[str] = None
|
|
165
|
+
for run_idx in range(1, runs + 1):
|
|
166
|
+
for task_id in tasks:
|
|
167
|
+
for arm in arms:
|
|
168
|
+
if spent >= budget_usd:
|
|
169
|
+
aborted = f"global budget ${budget_usd} exhausted after ${spent:.4f}"
|
|
170
|
+
break
|
|
171
|
+
row = run_react_one(task_id, arm, model=model, max_steps=max_steps,
|
|
172
|
+
budget_usd=max(budget_usd - spent, 0.01))
|
|
173
|
+
row["run"] = run_idx
|
|
174
|
+
results.append(row)
|
|
175
|
+
spent += float((row.get("usage") or {}).get("usd") or 0.0)
|
|
176
|
+
if aborted:
|
|
177
|
+
break
|
|
178
|
+
if aborted:
|
|
179
|
+
break
|
|
180
|
+
return {
|
|
181
|
+
"target": "react",
|
|
182
|
+
"tasks": tasks,
|
|
183
|
+
"arms": arms,
|
|
184
|
+
"runs": runs,
|
|
185
|
+
"model": model,
|
|
186
|
+
"budget_usd": budget_usd,
|
|
187
|
+
"spent_usd": round(spent, 6),
|
|
188
|
+
"aborted": aborted,
|
|
189
|
+
"results": results,
|
|
190
|
+
"note": "React arm runs the shipped static controller over stdio (no browser tab).",
|
|
191
|
+
"provenance": _provenance("react", tasks, arms),
|
|
192
|
+
"generated_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def _provenance(target: str, tasks: List[str], arms: List[str]) -> Dict[str, Any]:
|
|
197
|
+
"""Frozen prompts + harness revision, so a report can be audited later."""
|
|
198
|
+
import hashlib
|
|
199
|
+
import subprocess
|
|
200
|
+
|
|
201
|
+
module = react_target if target == "react" else go_target
|
|
202
|
+
harness_repo = Path(__file__).resolve().parents[2]
|
|
203
|
+
systems = {
|
|
204
|
+
"baseline": getattr(module, "SYSTEM_BASELINE", getattr(module, "SYSTEM", "")),
|
|
205
|
+
"tokensafe": getattr(module, "SYSTEM_TOKENSAFE", ""),
|
|
206
|
+
"oumv": getattr(module, "SYSTEM_OUMV", ""),
|
|
207
|
+
}
|
|
208
|
+
prompts = {task: module.task_prompt(task) for task in tasks}
|
|
209
|
+
try:
|
|
210
|
+
commit = subprocess.run(
|
|
211
|
+
["git", "rev-parse", "HEAD"], cwd=str(harness_repo), capture_output=True, text=True, timeout=10
|
|
212
|
+
).stdout.strip()
|
|
213
|
+
dirty = bool(
|
|
214
|
+
subprocess.run(
|
|
215
|
+
["git", "status", "--porcelain"], cwd=str(harness_repo), capture_output=True, text=True, timeout=10
|
|
216
|
+
).stdout.strip()
|
|
217
|
+
)
|
|
218
|
+
except Exception:
|
|
219
|
+
commit, dirty = "", False
|
|
220
|
+
return {
|
|
221
|
+
"prompt_sha256": {task: hashlib.sha256(prompt.encode()).hexdigest() for task, prompt in prompts.items()},
|
|
222
|
+
"system_sha256": {
|
|
223
|
+
arm: hashlib.sha256(systems.get(arm, "").encode()).hexdigest() for arm in arms
|
|
224
|
+
},
|
|
225
|
+
"harness_commit": commit,
|
|
226
|
+
"harness_dirty": dirty,
|
|
227
|
+
"price_snapshot": "2026-11-26",
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def summarize(report: Dict[str, Any]) -> List[Dict[str, Any]]:
|
|
232
|
+
rows: Dict[str, Dict[str, Any]] = {}
|
|
233
|
+
for result in report["results"]:
|
|
234
|
+
key = result["arm"]
|
|
235
|
+
row = rows.setdefault(
|
|
236
|
+
key,
|
|
237
|
+
{"arm": key, "runs": 0, "solved": 0, "input": 0, "output": 0, "usd": 0.0, "steps": 0, "seconds": 0.0},
|
|
238
|
+
)
|
|
239
|
+
row["runs"] += 1
|
|
240
|
+
row["solved"] += 1 if result.get("solved") else 0
|
|
241
|
+
usage = result.get("usage") or {}
|
|
242
|
+
row["input"] += int(usage.get("input_tokens") or 0)
|
|
243
|
+
row["output"] += int(usage.get("output_tokens") or 0)
|
|
244
|
+
row["usd"] += float(usage.get("usd") or 0.0)
|
|
245
|
+
row["steps"] += len(result.get("steps") or [])
|
|
246
|
+
row["seconds"] += float(result.get("wall_clock_s") or 0.0)
|
|
247
|
+
for row in rows.values():
|
|
248
|
+
row["mean_steps"] = round(row["steps"] / row["runs"], 1) if row["runs"] else 0.0
|
|
249
|
+
row["mean_seconds"] = round(row["seconds"] / row["runs"], 1) if row["runs"] else 0.0
|
|
250
|
+
row["mean_input"] = round(row["input"] / row["runs"]) if row["runs"] else 0
|
|
251
|
+
row["mean_output"] = round(row["output"] / row["runs"]) if row["runs"] else 0
|
|
252
|
+
return sorted(rows.values(), key=lambda r: r["arm"])
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def render_markdown(report: Dict[str, Any]) -> str:
|
|
256
|
+
target = report.get("target", "go")
|
|
257
|
+
oracle = (
|
|
258
|
+
"the 12-assertion TaskManagerOracle (`npx tsx src/bin/oracle-runner.ts`)"
|
|
259
|
+
if target == "react"
|
|
260
|
+
else "the real 12-assertion oracle (`go test ./benchmark -run TestGroundTruthOracleVanilla`)"
|
|
261
|
+
)
|
|
262
|
+
sandbox = "the `agent-dom` React benchmark sandbox" if target == "react" else "the `tokensafe-backend/go` module"
|
|
263
|
+
lines = [
|
|
264
|
+
f"# OUMV benchmark — {target} sandbox (measured)",
|
|
265
|
+
"",
|
|
266
|
+
f"> Model: `{report['model']}` · runs: {report['runs']} · budget: ${report['budget_usd']} · "
|
|
267
|
+
f"spent: ${report['spent_usd']} · {report['generated_at']}",
|
|
268
|
+
"",
|
|
269
|
+
"## Methodology",
|
|
270
|
+
"",
|
|
271
|
+
f"- Each arm starts from a throwaway copy of {sandbox} with one deliberate regression.",
|
|
272
|
+
f"- Correctness is {oracle}, re-run after every agent step.",
|
|
273
|
+
"- Token and cost numbers come from the provider `usage` payload; prices are a pinned snapshot printed in the JSON artifact.",
|
|
274
|
+
"- `baseline` uses file/command tools only; `oumv` gets the same tools plus observe/getSource/applyEdit/understand served by the shipped OUMV adapter.",
|
|
275
|
+
"",
|
|
276
|
+
"## Results",
|
|
277
|
+
"",
|
|
278
|
+
"| Arm | Runs | Solved | Mean steps | Mean wall clock | Mean input tokens | Mean output tokens | Cost |",
|
|
279
|
+
"| :--- | ---: | ---: | ---: | ---: | ---: | ---: | ---: |",
|
|
280
|
+
]
|
|
281
|
+
for row in summarize(report):
|
|
282
|
+
lines.append(
|
|
283
|
+
f"| `{row['arm']}` | {row['runs']} | {row['solved']}/{row['runs']} | {row['mean_steps']} | "
|
|
284
|
+
f"{row['mean_seconds']}s | {row['mean_input']:,} | {row['mean_output']:,} | ${row['usd']:.4f} |"
|
|
285
|
+
)
|
|
286
|
+
if report.get("aborted"):
|
|
287
|
+
lines += ["", f"> Stopped early: {report['aborted']}"]
|
|
288
|
+
rows = {row["arm"]: row for row in summarize(report)}
|
|
289
|
+
if "baseline" in rows and "oumv" in rows:
|
|
290
|
+
baseline, oumv = rows["baseline"], rows["oumv"]
|
|
291
|
+
def delta(before: float, after: float) -> str:
|
|
292
|
+
if not before:
|
|
293
|
+
return "—"
|
|
294
|
+
return f"{(after - before) / before * 100:+.1f}%"
|
|
295
|
+
lines += [
|
|
296
|
+
"",
|
|
297
|
+
"## OUMV vs baseline",
|
|
298
|
+
"",
|
|
299
|
+
"| Metric | Baseline | OUMV | Delta |",
|
|
300
|
+
"| :--- | ---: | ---: | ---: |",
|
|
301
|
+
f"| Solved | {baseline['solved']}/{baseline['runs']} | {oumv['solved']}/{oumv['runs']} | — |",
|
|
302
|
+
f"| Mean input tokens | {baseline['mean_input']:,} | {oumv['mean_input']:,} | {delta(baseline['mean_input'], oumv['mean_input'])} |",
|
|
303
|
+
f"| Mean output tokens | {baseline['mean_output']:,} | {oumv['mean_output']:,} | {delta(baseline['mean_output'], oumv['mean_output'])} |",
|
|
304
|
+
f"| Mean steps | {baseline['mean_steps']} | {oumv['mean_steps']} | {delta(baseline['mean_steps'], oumv['mean_steps'])} |",
|
|
305
|
+
f"| Mean wall clock | {baseline['mean_seconds']}s | {oumv['mean_seconds']}s | {delta(baseline['mean_seconds'], oumv['mean_seconds'])} |",
|
|
306
|
+
f"| Cost | ${baseline['usd']:.4f} | ${oumv['usd']:.4f} | {delta(baseline['usd'], oumv['usd'])} |",
|
|
307
|
+
]
|
|
308
|
+
lines += ["", "## Per-run detail", "", "| Run | Arm | Task | Oracle before | Oracle after | Stop | Steps |", "| ---: | :--- | :--- | :--- | :--- | :--- | ---: |"]
|
|
309
|
+
for result in report["results"]:
|
|
310
|
+
before = result.get("oracle_before") or {}
|
|
311
|
+
after = result.get("oracle_after") or {}
|
|
312
|
+
lines.append(
|
|
313
|
+
f"| {result.get('run')} | `{result['arm']}` | {result['task']} | "
|
|
314
|
+
f"{before.get('passed', '—')}/12 | {after.get('passed', '—')}/12 | "
|
|
315
|
+
f"{result.get('stop_reason', '—')} | {len(result.get('steps') or [])} |"
|
|
316
|
+
)
|
|
317
|
+
return "\n".join(lines) + "\n"
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
def write_artifacts(report: Dict[str, Any], out_dir: Optional[Path] = None) -> Dict[str, str]:
|
|
321
|
+
from src.paths import resolve_data_dir
|
|
322
|
+
|
|
323
|
+
base = Path(out_dir) if out_dir else Path(resolve_data_dir()) / "bench"
|
|
324
|
+
base.mkdir(parents=True, exist_ok=True)
|
|
325
|
+
stamp = time.strftime("%Y%m%d-%H%M%S", time.gmtime())
|
|
326
|
+
target = report.get("target", "go")
|
|
327
|
+
json_path = base / f"{target}-{stamp}.json"
|
|
328
|
+
md_path = base / f"{target}-{stamp}.md"
|
|
329
|
+
json_path.write_text(json.dumps(report, indent=2, ensure_ascii=False), encoding="utf-8")
|
|
330
|
+
md_path.write_text(render_markdown(report), encoding="utf-8")
|
|
331
|
+
return {"json": str(json_path), "markdown": str(md_path)}
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
"""TokenSafe MCP client for the `tokensafe` benchmark arm.
|
|
2
|
+
|
|
3
|
+
The third arm measures the product's own tools (AST skeleton reader, scoped
|
|
4
|
+
search, architecture map) without OUMV. It speaks the real MCP server over stdio —
|
|
5
|
+
the same process `tokensafe mcp` starts for an agent — so the arm is not a
|
|
6
|
+
strawman reimplementation.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import hashlib
|
|
12
|
+
import json
|
|
13
|
+
import os
|
|
14
|
+
import subprocess
|
|
15
|
+
import sys
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
from typing import Any, Dict, List, Optional
|
|
18
|
+
|
|
19
|
+
TOKENSAFE_BIN = Path(__file__).resolve().parents[2] / "bin" / "tokensafe"
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class TokenSafeMcp:
|
|
23
|
+
def __init__(self, workspace: Path, timeout: float = 120.0, client_name: str = "oumv-bench",
|
|
24
|
+
profile: str = ""):
|
|
25
|
+
self.timeout = timeout
|
|
26
|
+
env = dict(os.environ)
|
|
27
|
+
if profile:
|
|
28
|
+
env["TOKENSAFE_MCP_PROFILE"] = profile
|
|
29
|
+
self.proc = subprocess.Popen(
|
|
30
|
+
[sys.executable, str(TOKENSAFE_BIN), "mcp"],
|
|
31
|
+
cwd=str(workspace),
|
|
32
|
+
env=env,
|
|
33
|
+
stdin=subprocess.PIPE,
|
|
34
|
+
stdout=subprocess.PIPE,
|
|
35
|
+
stderr=subprocess.DEVNULL,
|
|
36
|
+
text=True,
|
|
37
|
+
)
|
|
38
|
+
self._id = 0
|
|
39
|
+
self._rpc(
|
|
40
|
+
"initialize",
|
|
41
|
+
{
|
|
42
|
+
"protocolVersion": "2024-11-05",
|
|
43
|
+
"capabilities": {},
|
|
44
|
+
"clientInfo": {"name": client_name, "version": "0"},
|
|
45
|
+
},
|
|
46
|
+
)
|
|
47
|
+
self._notify("notifications/initialized", {})
|
|
48
|
+
|
|
49
|
+
def _send(self, payload: Dict[str, Any]) -> None:
|
|
50
|
+
assert self.proc.stdin is not None
|
|
51
|
+
self.proc.stdin.write(json.dumps(payload) + "\n")
|
|
52
|
+
self.proc.stdin.flush()
|
|
53
|
+
|
|
54
|
+
def _notify(self, method: str, params: Dict[str, Any]) -> None:
|
|
55
|
+
self._send({"jsonrpc": "2.0", "method": method, "params": params})
|
|
56
|
+
|
|
57
|
+
def _rpc(self, method: str, params: Dict[str, Any]) -> Dict[str, Any]:
|
|
58
|
+
self._id += 1
|
|
59
|
+
request_id = self._id
|
|
60
|
+
self._send({"jsonrpc": "2.0", "id": request_id, "method": method, "params": params})
|
|
61
|
+
assert self.proc.stdout is not None
|
|
62
|
+
while True:
|
|
63
|
+
line = self.proc.stdout.readline()
|
|
64
|
+
if not line:
|
|
65
|
+
return {"error": "MCP server closed the stream"}
|
|
66
|
+
try:
|
|
67
|
+
body = json.loads(line)
|
|
68
|
+
except json.JSONDecodeError:
|
|
69
|
+
continue
|
|
70
|
+
if body.get("id") != request_id:
|
|
71
|
+
continue
|
|
72
|
+
return body
|
|
73
|
+
|
|
74
|
+
def tool_schemas(self, exclude: Optional[set] = None) -> List[Dict[str, Any]]:
|
|
75
|
+
"""The tools the server actually advertises, in OpenAI function-calling shape.
|
|
76
|
+
|
|
77
|
+
The arm must show the model the *shipped* schema: its size and wording are part
|
|
78
|
+
of the product's cost (re-sent on every request), and a hand-written stand-in
|
|
79
|
+
both hides that cost and measures a configuration no user runs.
|
|
80
|
+
"""
|
|
81
|
+
body = self._rpc("tools/list", {})
|
|
82
|
+
tools = (body.get("result") or {}).get("tools") or []
|
|
83
|
+
out: List[Dict[str, Any]] = []
|
|
84
|
+
for tool in tools:
|
|
85
|
+
name = str(tool.get("name") or "")
|
|
86
|
+
if not name or (exclude and name in exclude):
|
|
87
|
+
continue
|
|
88
|
+
out.append({
|
|
89
|
+
"type": "function",
|
|
90
|
+
"function": {
|
|
91
|
+
"name": name,
|
|
92
|
+
"description": str(tool.get("description") or ""),
|
|
93
|
+
"parameters": tool.get("inputSchema") or {"type": "object", "properties": {}},
|
|
94
|
+
},
|
|
95
|
+
})
|
|
96
|
+
return out
|
|
97
|
+
|
|
98
|
+
def call(self, name: str, arguments: Dict[str, Any]) -> Any:
|
|
99
|
+
body = self._rpc("tools/call", {"name": name, "arguments": arguments})
|
|
100
|
+
if body.get("error"):
|
|
101
|
+
return {"error": body["error"]}
|
|
102
|
+
result = body.get("result") or {}
|
|
103
|
+
if result.get("isError"):
|
|
104
|
+
content = result.get("content") or []
|
|
105
|
+
text = content[0].get("text") if content else "MCP tool failed"
|
|
106
|
+
return {"error": text}
|
|
107
|
+
content = result.get("content") or []
|
|
108
|
+
return content[0].get("text") if content else ""
|
|
109
|
+
|
|
110
|
+
def close(self) -> None:
|
|
111
|
+
try:
|
|
112
|
+
self.proc.terminate()
|
|
113
|
+
self.proc.wait(timeout=5)
|
|
114
|
+
except Exception:
|
|
115
|
+
try:
|
|
116
|
+
self.proc.kill()
|
|
117
|
+
except Exception:
|
|
118
|
+
pass
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _client_name(workspace: Path) -> str:
|
|
122
|
+
"""One MCP session per benchmark run.
|
|
123
|
+
|
|
124
|
+
The server keys its dedup cache, loop guard and pointer state by session, and the
|
|
125
|
+
session id is derived from `clientInfo.name`. A constant name would make run 2 of
|
|
126
|
+
the same task inherit run 1's "you already read this" state — the agent would get
|
|
127
|
+
a pointer to content it never saw.
|
|
128
|
+
"""
|
|
129
|
+
digest = hashlib.sha1(str(workspace).encode("utf-8")).hexdigest()[:10]
|
|
130
|
+
return f"oumv-bench-{digest}"
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def open_client(workspace: Path) -> Optional[TokenSafeMcp]:
|
|
134
|
+
"""Best-effort: a missing CLI means the arm cannot run, not that the bench crashes."""
|
|
135
|
+
if not TOKENSAFE_BIN.exists():
|
|
136
|
+
return None
|
|
137
|
+
try:
|
|
138
|
+
# The arm runs the profile the docs recommend for a coding session: four core
|
|
139
|
+
# tools (+oumv) instead of seven, because every advertised tool is re-sent in
|
|
140
|
+
# every request. `oumv` is dropped from the arm's surface by build_arm.
|
|
141
|
+
return TokenSafeMcp(workspace, client_name=_client_name(workspace),
|
|
142
|
+
profile=os.environ.get("TOKENSAFE_BENCH_PROFILE", "lean"))
|
|
143
|
+
except Exception:
|
|
144
|
+
return None
|
package/src/cli.py
CHANGED
|
@@ -107,6 +107,7 @@ def _print_help():
|
|
|
107
107
|
print(" init [--template ...] Initialize TokenSafe stack in current directory")
|
|
108
108
|
print(" stats / markdown / html Savings analytics (terminal / .md report / dashboard)")
|
|
109
109
|
print(" savings [--json] Canonical totals + last event (cite these numbers, never guess)")
|
|
110
|
+
print(" bench-oumv [--target go|react] [--tasks all] [--arms baseline,oumv] [--runs N] [--budget USD] Measured agent benchmark")
|
|
110
111
|
print(" status One-screen health check: hooks, weekly savings, tier, sync")
|
|
111
112
|
print(" budget [--transcript=...] Context Window Budget HUD & Context Quality Score (Grade S-F)")
|
|
112
113
|
print(" compact <transcript.jsonl> Fold conversation transcript into Consolidated State Ledger")
|
|
@@ -136,6 +137,8 @@ def _print_help():
|
|
|
136
137
|
print(" logout / unlink Unlink this device and remove local license")
|
|
137
138
|
print(" sync Sync telemetry with the cloud backend")
|
|
138
139
|
print(" providers / proxy / mcp Providers info / proxy server / MCP stdio server")
|
|
140
|
+
print(" agent [--model M] [-C dir] <prompt> One agent turn in this workspace (streaming tool use)")
|
|
141
|
+
print(" acp ACP agent server over stdio (Zed, JetBrains, Neovim, Emacs)")
|
|
139
142
|
print(" --version Print version and exit")
|
|
140
143
|
|
|
141
144
|
|
|
@@ -904,6 +907,74 @@ def main(argv: Optional[List[str]] = None):
|
|
|
904
907
|
proc = subprocess.run(cmd, cwd=target_dir)
|
|
905
908
|
sys.exit(proc.returncode)
|
|
906
909
|
|
|
910
|
+
elif command in ("bench-oumv", "bench_oumv"):
|
|
911
|
+
# Measured, agent-driven benchmark (DeepSeek by default): real oracle,
|
|
912
|
+
# provider-side token accounting, hard budget cap.
|
|
913
|
+
from src.bench import go_target, react_target
|
|
914
|
+
from src.bench.runner import render_markdown, run_matrix, run_react_matrix, write_artifacts
|
|
915
|
+
|
|
916
|
+
def _flag(name: str, default: str) -> str:
|
|
917
|
+
for i, arg in enumerate(args):
|
|
918
|
+
if arg == name and i + 1 < len(args):
|
|
919
|
+
return args[i + 1]
|
|
920
|
+
if arg.startswith(name + "="):
|
|
921
|
+
return arg.split("=", 1)[1]
|
|
922
|
+
return default
|
|
923
|
+
|
|
924
|
+
if "--help" in args or "-h" in args:
|
|
925
|
+
print(
|
|
926
|
+
"\n tokensafe bench-oumv [--target go|react] [--tasks all|id,id] [--arms baseline,oumv] "
|
|
927
|
+
"[--runs N] [--budget USD] [--model NAME] [--max-steps N] [--dry-run] [--mechanics] [--json]\n"
|
|
928
|
+
"\n Measured agent run against DeepSeek with a hard USD cap. --dry-run prints the\n"
|
|
929
|
+
" matrix and the pricing without calling the provider. --mechanics measures the\n"
|
|
930
|
+
" runtime itself (payload sizes, verification latency, guard rejections), no model.\n"
|
|
931
|
+
)
|
|
932
|
+
return
|
|
933
|
+
|
|
934
|
+
if "--mechanics" in args:
|
|
935
|
+
# Deterministic runtime measurements: no provider call, no API key.
|
|
936
|
+
from src.bench import mechanics
|
|
937
|
+
|
|
938
|
+
results = mechanics.run()
|
|
939
|
+
if "--json" in args:
|
|
940
|
+
import json as _json
|
|
941
|
+
print(_json.dumps(results, indent=2, ensure_ascii=False))
|
|
942
|
+
else:
|
|
943
|
+
print(mechanics.render_markdown(results))
|
|
944
|
+
return
|
|
945
|
+
|
|
946
|
+
target = _flag("--target", "go")
|
|
947
|
+
catalogue = react_target.TASKS if target == "react" else go_target.TASKS
|
|
948
|
+
tasks_arg = _flag("--tasks", "all")
|
|
949
|
+
task_ids = list(catalogue) if tasks_arg == "all" else [t.strip() for t in tasks_arg.split(",") if t.strip()]
|
|
950
|
+
arms = [a.strip() for a in _flag("--arms", "baseline,oumv").split(",") if a.strip()]
|
|
951
|
+
runs = int(_flag("--runs", "1"))
|
|
952
|
+
budget = float(_flag("--budget", "1.0"))
|
|
953
|
+
model = _flag("--model", "deepseek-chat")
|
|
954
|
+
max_steps = int(_flag("--max-steps", "14"))
|
|
955
|
+
|
|
956
|
+
if "--dry-run" in args:
|
|
957
|
+
from src.bench.driver import PRICES
|
|
958
|
+
|
|
959
|
+
sessions = len(task_ids) * len(arms) * runs
|
|
960
|
+
print(f"\n dry run: {target} · tasks={task_ids} · arms={arms} · runs={runs} → {sessions} sessions")
|
|
961
|
+
print(f" model={model} prices={PRICES.get(model)} budget=${budget}")
|
|
962
|
+
print(" no provider call was made\n")
|
|
963
|
+
return
|
|
964
|
+
|
|
965
|
+
print(f"\n⚡ OUMV bench ({target}): tasks={task_ids} runs={runs} model={model} budget=${budget}\n")
|
|
966
|
+
if target == "react":
|
|
967
|
+
report = run_react_matrix(task_ids, arms, runs=runs, model=model, max_steps=max_steps, budget_usd=budget)
|
|
968
|
+
else:
|
|
969
|
+
report = run_matrix(task_ids, arms, runs=runs, model=model, max_steps=max_steps, budget_usd=budget)
|
|
970
|
+
paths = write_artifacts(report)
|
|
971
|
+
if "--json" in args:
|
|
972
|
+
import json as _json
|
|
973
|
+
print(_json.dumps(report, indent=2, ensure_ascii=False))
|
|
974
|
+
else:
|
|
975
|
+
print(render_markdown(report))
|
|
976
|
+
print(f"artifacts: {paths['markdown']}\n {paths['json']}\n")
|
|
977
|
+
|
|
907
978
|
elif command in ("burn", "burn-monitor"):
|
|
908
979
|
from src.burn_monitor import collect_live_burn_snapshot, evaluate_burn_warnings, is_zai_peak_hour
|
|
909
980
|
from src.transcript_analyzer import discover_transcript_paths, analyze_transcript, render_transcripts_report
|
|
@@ -1092,6 +1163,91 @@ def main(argv: Optional[List[str]] = None):
|
|
|
1092
1163
|
from src.mcp_server import run_mcp_server
|
|
1093
1164
|
run_mcp_server()
|
|
1094
1165
|
|
|
1166
|
+
elif command in ("acp",):
|
|
1167
|
+
from src.acp.server import run_acp_server
|
|
1168
|
+
run_acp_server()
|
|
1169
|
+
|
|
1170
|
+
elif command in ("agent", "run-agent", "run_agent"):
|
|
1171
|
+
opts = {"model": "", "provider": "", "base_url": "", "root": "", "max_steps": 16, "budget": 1.0}
|
|
1172
|
+
prompt_parts: List[str] = []
|
|
1173
|
+
index = 1
|
|
1174
|
+
while index < len(args):
|
|
1175
|
+
arg = args[index]
|
|
1176
|
+
if arg in ("--model", "-m") and index + 1 < len(args):
|
|
1177
|
+
opts["model"] = args[index + 1]
|
|
1178
|
+
index += 2
|
|
1179
|
+
elif arg == "--provider" and index + 1 < len(args):
|
|
1180
|
+
opts["provider"] = args[index + 1]
|
|
1181
|
+
index += 2
|
|
1182
|
+
elif arg in ("--base-url", "--base_url") and index + 1 < len(args):
|
|
1183
|
+
opts["base_url"] = args[index + 1]
|
|
1184
|
+
index += 2
|
|
1185
|
+
elif arg in ("--root", "-C") and index + 1 < len(args):
|
|
1186
|
+
opts["root"] = args[index + 1]
|
|
1187
|
+
index += 2
|
|
1188
|
+
elif arg == "--max-steps" and index + 1 < len(args):
|
|
1189
|
+
try:
|
|
1190
|
+
opts["max_steps"] = int(args[index + 1])
|
|
1191
|
+
except ValueError:
|
|
1192
|
+
pass
|
|
1193
|
+
index += 2
|
|
1194
|
+
elif arg == "--budget" and index + 1 < len(args):
|
|
1195
|
+
try:
|
|
1196
|
+
opts["budget"] = float(args[index + 1])
|
|
1197
|
+
except ValueError:
|
|
1198
|
+
pass
|
|
1199
|
+
index += 2
|
|
1200
|
+
else:
|
|
1201
|
+
prompt_parts.append(arg)
|
|
1202
|
+
index += 1
|
|
1203
|
+
prompt = " ".join(prompt_parts).strip()
|
|
1204
|
+
if not prompt:
|
|
1205
|
+
print("Usage: tokensafe agent [--model M] [--provider P] [--base-url U] [-C dir] "
|
|
1206
|
+
"[--max-steps N] [--budget USD] <prompt>")
|
|
1207
|
+
sys.exit(1)
|
|
1208
|
+
from src.agent.loop import AgentConfig, AgentLoop
|
|
1209
|
+
from src.agent.providers import ProviderError
|
|
1210
|
+
import json as _json
|
|
1211
|
+
|
|
1212
|
+
def _sink(event):
|
|
1213
|
+
kind = event.get("type")
|
|
1214
|
+
if kind == "text":
|
|
1215
|
+
sys.stdout.write(event.get("text") or "")
|
|
1216
|
+
sys.stdout.flush()
|
|
1217
|
+
elif kind == "tool_call":
|
|
1218
|
+
rendered = _json.dumps(event.get("arguments"), ensure_ascii=False)[:160]
|
|
1219
|
+
print(f"\n\033[2m→ {event.get('name')} {rendered}\033[0m")
|
|
1220
|
+
elif kind == "tool_result":
|
|
1221
|
+
state = "ok" if event.get("ok") else "error"
|
|
1222
|
+
print(f"\033[2m← {event.get('name')}: {state} ({len(event.get('text') or '')} chars)\033[0m")
|
|
1223
|
+
elif kind == "compaction":
|
|
1224
|
+
print(f"\033[2m[context compacted: {event.get('before')} → {event.get('after')} tokens]\033[0m")
|
|
1225
|
+
|
|
1226
|
+
loop = AgentLoop(
|
|
1227
|
+
root=opts["root"] or None,
|
|
1228
|
+
session_id="cli:agent",
|
|
1229
|
+
config=AgentConfig(
|
|
1230
|
+
model=opts["model"],
|
|
1231
|
+
provider=opts["provider"],
|
|
1232
|
+
base_url=opts["base_url"],
|
|
1233
|
+
max_steps=opts["max_steps"],
|
|
1234
|
+
budget_usd=opts["budget"],
|
|
1235
|
+
),
|
|
1236
|
+
event_sink=_sink,
|
|
1237
|
+
)
|
|
1238
|
+
try:
|
|
1239
|
+
result = loop.run(prompt)
|
|
1240
|
+
except ProviderError as exc:
|
|
1241
|
+
print(f"\n\033[31mError:\033[0m {exc}")
|
|
1242
|
+
sys.exit(2)
|
|
1243
|
+
usage = result.usage
|
|
1244
|
+
priced = "" if usage.get("priced") else " · unpriced model"
|
|
1245
|
+
print(
|
|
1246
|
+
f"\n\033[2m[{result.stop_reason} · {result.steps} step(s) · "
|
|
1247
|
+
f"{usage.get('input_tokens', 0)} in / {usage.get('output_tokens', 0)} out · "
|
|
1248
|
+
f"${usage.get('usd', 0.0):.4f}{priced}]\033[0m"
|
|
1249
|
+
)
|
|
1250
|
+
|
|
1095
1251
|
elif command in ("mcp-proxy", "mcp_proxy"):
|
|
1096
1252
|
target_args = list(args[1:])
|
|
1097
1253
|
if target_args and target_args[0] == "--":
|