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.
Files changed (44) hide show
  1. package/.codex-plugin/plugin.json +2 -2
  2. package/LICENSE +202 -21
  3. package/README.md +30 -4
  4. package/hooks/claude_code_hook.py +17 -15
  5. package/hooks/kimi_hook.py +14 -12
  6. package/hooks/pre_invocation.py +7 -12
  7. package/hooks/session_start.py +8 -2
  8. package/kimi.plugin.json +2 -2
  9. package/package.json +2 -2
  10. package/plugin.json +2 -1
  11. package/rules/AGENTS.md +1 -1
  12. package/server.json +3 -3
  13. package/src/acp/__init__.py +15 -0
  14. package/src/acp/server.py +328 -0
  15. package/src/adapter_core.py +2 -1
  16. package/src/agent/__init__.py +11 -0
  17. package/src/agent/context.py +99 -0
  18. package/src/agent/loop.py +385 -0
  19. package/src/agent/pricing.py +77 -0
  20. package/src/agent/providers.py +486 -0
  21. package/src/agent/tools.py +98 -0
  22. package/src/agent_firewall.py +16 -1
  23. package/src/auto_inject.py +93 -7
  24. package/src/batch_editor.py +106 -15
  25. package/src/bench/__init__.py +1 -0
  26. package/src/bench/driver.py +234 -0
  27. package/src/bench/go_target.py +646 -0
  28. package/src/bench/mechanics.py +214 -0
  29. package/src/bench/react_target.py +541 -0
  30. package/src/bench/runner.py +331 -0
  31. package/src/bench/tokensafe_mcp.py +144 -0
  32. package/src/cli.py +156 -0
  33. package/src/history_compactor.py +200 -2
  34. package/src/installer.py +3 -3
  35. package/src/mcp_server.py +510 -237
  36. package/src/paths.py +41 -2
  37. package/src/retrofit.py +27 -5
  38. package/src/scaffold.py +8 -6
  39. package/src/scoped_search.py +67 -5
  40. package/src/session_brief.py +180 -15
  41. package/src/session_context.py +124 -0
  42. package/src/skeletonizer.py +9 -3
  43. package/src/telemetry_sync.py +1 -1
  44. package/src/version_checker.py +1 -1
@@ -0,0 +1,214 @@
1
+ """Deterministic protocol-mechanics measurements (no provider calls).
2
+
3
+ The agent matrix measures what a model chooses to do. These numbers measure the
4
+ runtime itself, so a reader can separate "the protocol is cheap" from "the model
5
+ happened to take few steps":
6
+
7
+ * discovery payload — observe L2 vs the same fact obtained by search + read;
8
+ * slicing — full-file getSource vs one-symbol getSource;
9
+ * verification — one in-process probe vs one oracle/test-suite run;
10
+ * safety — a stale OCC version and a broken edit are rejected.
11
+
12
+ Everything runs against a throwaway copy of the benchmark sandbox, so the numbers
13
+ are reproducible on a laptop without an API key.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import json
19
+ import statistics
20
+ import time
21
+ from pathlib import Path
22
+ from typing import Any, Dict, List, Optional
23
+
24
+ from src.bench import go_target, react_target
25
+
26
+
27
+ def _ms(fn, repeats: int) -> Dict[str, float]:
28
+ samples: List[float] = []
29
+ for _ in range(repeats):
30
+ started = time.perf_counter()
31
+ fn()
32
+ samples.append((time.perf_counter() - started) * 1000)
33
+ return {
34
+ "median_ms": round(statistics.median(samples), 2),
35
+ "min_ms": round(min(samples), 2),
36
+ "max_ms": round(max(samples), 2),
37
+ "samples": repeats,
38
+ }
39
+
40
+
41
+ def _chars(payload: Any) -> int:
42
+ return len(json.dumps(payload, ensure_ascii=False))
43
+
44
+
45
+ def measure_go(task_id: str = "product-create-status", repeats: int = 15) -> Dict[str, Any]:
46
+ ws = go_target.GoWorkspace(task_id)
47
+ probe = {"target": "POST /api/products", "action": "probe", "payload": {"title": "probe", "price": 1}}
48
+ source_path = go_target.SANDBOX_FILE
49
+ try:
50
+ ws.oumv("oumv/verify", probe) # warm the helper and the Go build cache
51
+ full = ws.oumv("oumv/getSource", {"path": source_path})
52
+ sliced = ws.oumv("oumv/getSource", {"path": source_path, "symbol": "NewVanillaApp"})
53
+ l2 = ws.oumv("oumv/observe", {"level": "L2", "target": "POST /api/products"})
54
+ l3 = ws.oumv("oumv/observe", {"level": "L3", "target": "POST /api/products"})
55
+ hits = ws.search_files("StatusOK")
56
+ hit_line = 0
57
+ if hits.get("hits"):
58
+ hit_line = int(hits["hits"][0].split(":")[1])
59
+ window = ws.read_file(source_path, max(1, hit_line - 10), hit_line + 40)
60
+
61
+ # A stale version must be rejected before anything is written.
62
+ stale = ws.oumv(
63
+ "oumv/applyEdit",
64
+ {
65
+ "path": source_path,
66
+ "replacement": full.get("source") or "",
67
+ "expectedVersion": "sha256:" + "0" * 64,
68
+ },
69
+ )
70
+ # A syntactically broken replacement must be rejected by the pre-flight.
71
+ broken = ws.oumv(
72
+ "oumv/applyEdit",
73
+ {
74
+ "path": source_path,
75
+ "replacement": "package vanilla_gin\nfunc broken( {\n",
76
+ "expectedVersion": full.get("version") or "",
77
+ },
78
+ )
79
+
80
+ verify = _ms(lambda: ws.oumv("oumv/verify", probe), repeats)
81
+ verify_sample = ws.oumv("oumv/verify", probe)
82
+ test_run = _ms(
83
+ lambda: ws.run_command("go test ./benchmark -run TestGroundTruthOracleVanilla -count=1"),
84
+ 3,
85
+ )
86
+ return {
87
+ "target": "go",
88
+ "task": task_id,
89
+ "discovery": {
90
+ "oumv_l2_chars": _chars(l2),
91
+ "oumv_l3_chars": _chars(l3),
92
+ "oumv_handler_chars": len(str((l3.get("data") or {}).get("source") or "")),
93
+ "baseline_search_chars": _chars(hits),
94
+ "baseline_read_window_chars": _chars(window),
95
+ "baseline_total_chars": _chars(hits) + _chars(window),
96
+ },
97
+ "slicing": {
98
+ "full_file_chars": _chars(full),
99
+ "symbol_chars": _chars(sliced),
100
+ "symbol": sliced.get("symbol"),
101
+ "start_line": sliced.get("startLine"),
102
+ "end_line": sliced.get("endLine"),
103
+ },
104
+ "verification": {
105
+ "oumv_verify_end_to_end": verify,
106
+ "oumv_verify_reported_in_process_ms": verify_sample.get("durationMs"),
107
+ "oracle_run": test_run,
108
+ "speedup": round(test_run["median_ms"] / verify["median_ms"], 1) if verify["median_ms"] else None,
109
+ },
110
+ "safety": {
111
+ "stale_version_rejected": bool((stale.get("error") or {}).get("code") == -32001),
112
+ "broken_edit_rejected": bool((broken.get("error") or {}).get("code") == -32002),
113
+ "stale_error": (stale.get("error") or {}).get("code"),
114
+ "broken_error": (broken.get("error") or {}).get("code"),
115
+ },
116
+ }
117
+ finally:
118
+ ws.cleanup()
119
+
120
+
121
+ def measure_react(task_id: str = "search-filter", repeats: int = 15) -> Dict[str, Any]:
122
+ ws = react_target.ReactWorkspace(task_id)
123
+ store = "sandboxes/react-task-manager/src/store.ts"
124
+ try:
125
+ full = ws.oumv("oumv/getSource", {"path": store})
126
+ sliced = ws.oumv("oumv/getSource", {"path": store, "symbol": "selectFilteredTasks"})
127
+ l1 = ws.oumv("oumv/observe", {"level": "L1"})
128
+ hits = ws.search_files("searchQuery")
129
+ hit_line = 0
130
+ if hits.get("hits"):
131
+ hit_line = int(hits["hits"][0].split(":")[1].split(":")[0]) if ":" in hits["hits"][0] else 0
132
+ window = ws.read_file(store, max(1, hit_line - 10), hit_line + 40)
133
+ stale = ws.oumv(
134
+ "oumv/applyEdit",
135
+ {"path": store, "replacement": full.get("source") or "", "expectedVersion": "sha256:" + "0" * 64},
136
+ )
137
+ oracle = _ms(lambda: ws.run_command("npx tsx src/bin/oracle-runner.ts"), 3)
138
+ read = _ms(lambda: ws.oumv("oumv/getSource", {"path": store, "symbol": "selectFilteredTasks"}), repeats)
139
+ return {
140
+ "target": "react",
141
+ "task": task_id,
142
+ "discovery": {
143
+ "oumv_l1_chars": _chars(l1),
144
+ "baseline_search_chars": _chars(hits),
145
+ "baseline_read_window_chars": _chars(window),
146
+ "baseline_total_chars": _chars(hits) + _chars(window),
147
+ },
148
+ "slicing": {
149
+ "full_file_chars": _chars(full),
150
+ "symbol_chars": _chars(sliced),
151
+ "symbol": sliced.get("symbol"),
152
+ "start_line": sliced.get("startLine"),
153
+ "end_line": sliced.get("endLine"),
154
+ },
155
+ "verification": {
156
+ "oumv_get_source": read,
157
+ "oracle_run": oracle,
158
+ "speedup": round(oracle["median_ms"] / read["median_ms"], 1) if read["median_ms"] else None,
159
+ },
160
+ "safety": {
161
+ "stale_version_rejected": bool((stale.get("error") or {}).get("code") == -32001),
162
+ "stale_error": (stale.get("error") or {}).get("code"),
163
+ },
164
+ }
165
+ finally:
166
+ ws.cleanup()
167
+
168
+
169
+ def render_markdown(results: List[Dict[str, Any]]) -> str:
170
+ lines = ["# OUMV protocol mechanics (deterministic, no model)", ""]
171
+ for row in results:
172
+ lines += [f"## {row['target']} (`{row['task']}`)", ""]
173
+ discovery = row["discovery"]
174
+ slicing = row["slicing"]
175
+ lines += [
176
+ "| Measurement | Value |",
177
+ "| :--- | ---: |",
178
+ f"| OUMV observe payload | {discovery.get('oumv_l3_chars') or discovery.get('oumv_l2_chars') or discovery.get('oumv_l1_chars')} chars |",
179
+ *(
180
+ [f"| …of which the handler body | {discovery['oumv_handler_chars']} chars |"]
181
+ if discovery.get("oumv_handler_chars")
182
+ else []
183
+ ),
184
+ f"| Baseline search + read window | {discovery['baseline_total_chars']} chars |",
185
+ f"| `getSource` full file | {slicing['full_file_chars']} chars |",
186
+ f"| `getSource` one symbol | {slicing['symbol_chars']} chars |",
187
+ "",
188
+ ]
189
+ verification = row["verification"]
190
+ timing_label = (
191
+ "OUMV probe (end-to-end, one process)"
192
+ if verification.get("oumv_verify_end_to_end")
193
+ else "getSource, one symbol (end-to-end)"
194
+ )
195
+ timing_value = verification.get("oumv_verify_end_to_end") or verification.get("oumv_get_source") or {}
196
+ lines += [
197
+ "| Verification | Median |",
198
+ "| :--- | ---: |",
199
+ f"| {timing_label} | {timing_value.get('median_ms')} ms |",
200
+ f"| Oracle / test suite run | {verification['oracle_run']['median_ms']} ms |",
201
+ "",
202
+ ]
203
+ safety = row["safety"]
204
+ lines += [
205
+ f"Safety: stale `expectedVersion` rejected: **{safety['stale_version_rejected']}**"
206
+ + (f"; broken edit rejected: **{safety['broken_edit_rejected']}**" if "broken_edit_rejected" in safety else "")
207
+ + ".",
208
+ "",
209
+ ]
210
+ return "\n".join(lines)
211
+
212
+
213
+ def run(repeats: int = 15) -> List[Dict[str, Any]]:
214
+ return [measure_go(repeats=repeats), measure_react(repeats=repeats)]