tokensafe 4.7.0 → 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 +1 -1
- package/README.md +22 -0
- package/hooks/claude_code_hook.py +15 -13
- package/hooks/kimi_hook.py +14 -12
- package/hooks/session_start.py +8 -2
- package/kimi.plugin.json +1 -1
- package/package.json +1 -1
- package/plugin.json +1 -1
- package/rules/AGENTS.md +1 -1
- package/server.json +3 -3
- package/src/adapter_core.py +2 -1
- package/src/agent_firewall.py +16 -1
- package/src/auto_inject.py +93 -7
- package/src/batch_editor.py +106 -15
- package/src/bench/driver.py +18 -3
- package/src/bench/go_target.py +308 -22
- package/src/bench/mechanics.py +214 -0
- package/src/bench/react_target.py +312 -5
- package/src/bench/runner.py +114 -30
- package/src/bench/tokensafe_mcp.py +144 -0
- package/src/cli.py +32 -1
- package/src/installer.py +3 -3
- package/src/mcp_server.py +457 -227
- 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/skeletonizer.py +9 -3
- package/src/telemetry_sync.py +1 -1
- package/src/version_checker.py +1 -1
|
@@ -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
|
@@ -921,6 +921,28 @@ def main(argv: Optional[List[str]] = None):
|
|
|
921
921
|
return arg.split("=", 1)[1]
|
|
922
922
|
return default
|
|
923
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
|
+
|
|
924
946
|
target = _flag("--target", "go")
|
|
925
947
|
catalogue = react_target.TASKS if target == "react" else go_target.TASKS
|
|
926
948
|
tasks_arg = _flag("--tasks", "all")
|
|
@@ -931,9 +953,18 @@ def main(argv: Optional[List[str]] = None):
|
|
|
931
953
|
model = _flag("--model", "deepseek-chat")
|
|
932
954
|
max_steps = int(_flag("--max-steps", "14"))
|
|
933
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
|
+
|
|
934
965
|
print(f"\n⚡ OUMV bench ({target}): tasks={task_ids} runs={runs} model={model} budget=${budget}\n")
|
|
935
966
|
if target == "react":
|
|
936
|
-
report = run_react_matrix(task_ids, runs=runs, model=model, max_steps=max_steps, budget_usd=budget)
|
|
967
|
+
report = run_react_matrix(task_ids, arms, runs=runs, model=model, max_steps=max_steps, budget_usd=budget)
|
|
937
968
|
else:
|
|
938
969
|
report = run_matrix(task_ids, arms, runs=runs, model=model, max_steps=max_steps, budget_usd=budget)
|
|
939
970
|
paths = write_artifacts(report)
|
package/src/installer.py
CHANGED
|
@@ -48,10 +48,10 @@ UNIFIED_TOKENSAFE_RULE = (
|
|
|
48
48
|
"## TOKENSAFE GRAPH-FIRST OPTIMIZATION PROTOCOL\n"
|
|
49
49
|
"Always use `tokensafe` MCP tools (`smart_read_file`, `scoped_search`, `apply_edits`, `repo_map`, `session_context`, `oumv`, `run_helper`) over default raw file reads or high-output terminal executions.\n\n"
|
|
50
50
|
"1. **Zero Raw Grep/Find (Blocked & Replaced by `scoped_search`)**: Strictly NEVER execute terminal `grep`, `egrep`, `ripgrep`, or `find` on source code files or directories (`src/`, `views/`, `components/`, `.ts`, `.tsx`, `.py`, `.js`). Use `tokensafe:scoped_search(query, path='.', scope='code')` for single searches (`mode='auto'|'text'|'regex'|'glob'|'fuzzy'|'git'`) or `queries=[...]` for up to 20 concurrent queries in one call.\n"
|
|
51
|
-
"2. **Mandatory Symbol, Bundle & External Type Inspection (`smart_read_file`)**: Always call `tokensafe:smart_read_file(path, symbol)` (default `dep_mode='signature'` folds inert code -95%+ tokens; pass `dep_mode='full'` only when needed, or `force_full=true` if a pointer hit references missing context). Pass `targets=[{path, symbol}]` to bundle 2-8 symbols across files in one call, or `package_name`+`symbol` for 3rd-party `.d.ts` interfaces. OpenAPI/Prisma/GraphQL/SQL schemas auto-slice via `symbol`.\n"
|
|
51
|
+
"2. **Mandatory Symbol, Bundle & External Type Inspection (`smart_read_file`)**: Always call `tokensafe:smart_read_file(path, symbol)` (default `dep_mode='signature'` folds inert code -95%+ tokens; pass `dep_mode='full'` only when needed, or `force_full=true` if a pointer hit references missing context). `symbol` accepts an identifier, a qualified member (`Type.Method`) or an endpoint target (`'POST /api/orders'`): when the target is not a declaration in that file you get the enclosing handler body (or a tight ±window around the hit) with line numbers — that is the slice you edit, never a folded skeleton you have to re-read. Pass `targets=[{path, symbol}]` to bundle 2-8 symbols across files in one call, or `package_name`+`symbol` for 3rd-party `.d.ts` interfaces. OpenAPI/Prisma/GraphQL/SQL schemas auto-slice via `symbol`.\n"
|
|
52
52
|
"3. **Repeat Read Deduplication**: Never re-read unchanged files or symbols within the same session. Reuse the earlier skeleton or pointer hit (`// [TokenSafe: Pointer Hit ...]`).\n"
|
|
53
|
-
"4. **Zero-Fluff Egress & Surgical Diffs**: Omit conversational filler. Reference line ranges (`file.ts#L10-L25`) and use `tokensafe:apply_edits` for multi-hunk/multi-file edits with optional inline `verify
|
|
54
|
-
"5. **Architecture Graph, API Surface & Directory Tree (`repo_map`)**: For
|
|
53
|
+
"4. **Zero-Fluff Egress & Surgical Diffs**: Omit conversational filler. Reference line ranges (`file.ts#L10-L25`) and use `tokensafe:apply_edits` for multi-hunk/multi-file edits with optional inline `verify`. For a failing test, one hunk + `verify='auto'` (the project's own declared test command) per attempt: the edit and the verdict come back in one call, so read the reported line and apply the next hunk instead of rewriting whole files.\n"
|
|
54
|
+
"5. **Architecture Graph, API Surface & Directory Tree (`repo_map`)**: For an unfamiliar repository or a broad refactor, FIRST call `tokensafe:repo_map(view='graph', project_path=...)` for God Nodes (<250 tokens). Use `view='api'` for exported types/interfaces and `view='tree'` instead of `ls -la`. Skip the map when the task already names the failing endpoint, symbol or file — go straight to `scoped_search` + `smart_read_file`.\n"
|
|
55
55
|
"6. **Utilities (`run_helper`)**: Use `tokensafe:run_helper(action=...)` for rare/auxiliary operations: `'sanitize'` (rewrite shell/test commands), `'guard'` (pre-flight secret/safety audit), `'diff'` (slice diff), `'deps'` (lockfile point lookup), `'web'` (fetch clean Markdown), `'expand'` (restore `#hash`), `'image'` (downscale >1024px), and `'compress'` (TOCP prompt).\n"
|
|
56
56
|
"7. **Compact Tests & Build Output**: Run noisy commands, builds, and test suites via `tokensafe wrap '<cmd>'` or `tokensafe tests [cmd]` (clean 1-line summary on pass, full trace on failure; never leave `vitest`/`jest`/`bun` in watch mode).\n"
|
|
57
57
|
"8. **Styles & Design Tokens**: When inspecting CSS/SCSS/LESS/Tailwind, `smart_read_file` preserves design tokens (`:root`, `@theme`, CSS variables) in full.\n"
|