tokensafe 4.6.4 → 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.
@@ -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)}
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,43 @@ 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
+ target = _flag("--target", "go")
925
+ catalogue = react_target.TASKS if target == "react" else go_target.TASKS
926
+ tasks_arg = _flag("--tasks", "all")
927
+ task_ids = list(catalogue) if tasks_arg == "all" else [t.strip() for t in tasks_arg.split(",") if t.strip()]
928
+ arms = [a.strip() for a in _flag("--arms", "baseline,oumv").split(",") if a.strip()]
929
+ runs = int(_flag("--runs", "1"))
930
+ budget = float(_flag("--budget", "1.0"))
931
+ model = _flag("--model", "deepseek-chat")
932
+ max_steps = int(_flag("--max-steps", "14"))
933
+
934
+ print(f"\n⚡ OUMV bench ({target}): tasks={task_ids} runs={runs} model={model} budget=${budget}\n")
935
+ if target == "react":
936
+ report = run_react_matrix(task_ids, runs=runs, model=model, max_steps=max_steps, budget_usd=budget)
937
+ else:
938
+ report = run_matrix(task_ids, arms, runs=runs, model=model, max_steps=max_steps, budget_usd=budget)
939
+ paths = write_artifacts(report)
940
+ if "--json" in args:
941
+ import json as _json
942
+ print(_json.dumps(report, indent=2, ensure_ascii=False))
943
+ else:
944
+ print(render_markdown(report))
945
+ print(f"artifacts: {paths['markdown']}\n {paths['json']}\n")
946
+
907
947
  elif command in ("burn", "burn-monitor"):
908
948
  from src.burn_monitor import collect_live_burn_snapshot, evaluate_burn_warnings, is_zai_peak_hour
909
949
  from src.transcript_analyzer import discover_transcript_paths, analyze_transcript, render_transcripts_report
@@ -1092,6 +1132,91 @@ def main(argv: Optional[List[str]] = None):
1092
1132
  from src.mcp_server import run_mcp_server
1093
1133
  run_mcp_server()
1094
1134
 
1135
+ elif command in ("acp",):
1136
+ from src.acp.server import run_acp_server
1137
+ run_acp_server()
1138
+
1139
+ elif command in ("agent", "run-agent", "run_agent"):
1140
+ opts = {"model": "", "provider": "", "base_url": "", "root": "", "max_steps": 16, "budget": 1.0}
1141
+ prompt_parts: List[str] = []
1142
+ index = 1
1143
+ while index < len(args):
1144
+ arg = args[index]
1145
+ if arg in ("--model", "-m") and index + 1 < len(args):
1146
+ opts["model"] = args[index + 1]
1147
+ index += 2
1148
+ elif arg == "--provider" and index + 1 < len(args):
1149
+ opts["provider"] = args[index + 1]
1150
+ index += 2
1151
+ elif arg in ("--base-url", "--base_url") and index + 1 < len(args):
1152
+ opts["base_url"] = args[index + 1]
1153
+ index += 2
1154
+ elif arg in ("--root", "-C") and index + 1 < len(args):
1155
+ opts["root"] = args[index + 1]
1156
+ index += 2
1157
+ elif arg == "--max-steps" and index + 1 < len(args):
1158
+ try:
1159
+ opts["max_steps"] = int(args[index + 1])
1160
+ except ValueError:
1161
+ pass
1162
+ index += 2
1163
+ elif arg == "--budget" and index + 1 < len(args):
1164
+ try:
1165
+ opts["budget"] = float(args[index + 1])
1166
+ except ValueError:
1167
+ pass
1168
+ index += 2
1169
+ else:
1170
+ prompt_parts.append(arg)
1171
+ index += 1
1172
+ prompt = " ".join(prompt_parts).strip()
1173
+ if not prompt:
1174
+ print("Usage: tokensafe agent [--model M] [--provider P] [--base-url U] [-C dir] "
1175
+ "[--max-steps N] [--budget USD] <prompt>")
1176
+ sys.exit(1)
1177
+ from src.agent.loop import AgentConfig, AgentLoop
1178
+ from src.agent.providers import ProviderError
1179
+ import json as _json
1180
+
1181
+ def _sink(event):
1182
+ kind = event.get("type")
1183
+ if kind == "text":
1184
+ sys.stdout.write(event.get("text") or "")
1185
+ sys.stdout.flush()
1186
+ elif kind == "tool_call":
1187
+ rendered = _json.dumps(event.get("arguments"), ensure_ascii=False)[:160]
1188
+ print(f"\n\033[2m→ {event.get('name')} {rendered}\033[0m")
1189
+ elif kind == "tool_result":
1190
+ state = "ok" if event.get("ok") else "error"
1191
+ print(f"\033[2m← {event.get('name')}: {state} ({len(event.get('text') or '')} chars)\033[0m")
1192
+ elif kind == "compaction":
1193
+ print(f"\033[2m[context compacted: {event.get('before')} → {event.get('after')} tokens]\033[0m")
1194
+
1195
+ loop = AgentLoop(
1196
+ root=opts["root"] or None,
1197
+ session_id="cli:agent",
1198
+ config=AgentConfig(
1199
+ model=opts["model"],
1200
+ provider=opts["provider"],
1201
+ base_url=opts["base_url"],
1202
+ max_steps=opts["max_steps"],
1203
+ budget_usd=opts["budget"],
1204
+ ),
1205
+ event_sink=_sink,
1206
+ )
1207
+ try:
1208
+ result = loop.run(prompt)
1209
+ except ProviderError as exc:
1210
+ print(f"\n\033[31mError:\033[0m {exc}")
1211
+ sys.exit(2)
1212
+ usage = result.usage
1213
+ priced = "" if usage.get("priced") else " · unpriced model"
1214
+ print(
1215
+ f"\n\033[2m[{result.stop_reason} · {result.steps} step(s) · "
1216
+ f"{usage.get('input_tokens', 0)} in / {usage.get('output_tokens', 0)} out · "
1217
+ f"${usage.get('usd', 0.0):.4f}{priced}]\033[0m"
1218
+ )
1219
+
1095
1220
  elif command in ("mcp-proxy", "mcp_proxy"):
1096
1221
  target_args = list(args[1:])
1097
1222
  if target_args and target_args[0] == "--":