tokensafe 2.6.1 → 2.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/bin/tokensafe +1 -1
- package/extensions/cursor-tokensafe/extension.js +21 -8
- package/hooks/claude_code_hook.py +13 -5
- package/hooks/cursor_hook.py +7 -4
- package/hooks/post_tool_use.py +24 -6
- package/hooks/pre_invocation.py +40 -27
- package/hooks/pre_tool_use.py +85 -83
- package/hooks/session_start.py +8 -4
- package/hooks/stop_hook.py +7 -4
- package/package.json +1 -1
- package/plugin.json +1 -1
- package/server.json +3 -3
- package/src/agent_firewall.py +38 -21
- package/src/cache_normalizer.py +39 -10
- package/src/cli.py +144 -91
- package/src/command_sanitizer.py +248 -136
- package/src/compactor.py +55 -25
- package/src/dashboard.py +17 -10
- package/src/deepseek_distiller.py +26 -17
- package/src/dependency_prefetcher.py +66 -41
- package/src/diff_slicer.py +23 -17
- package/src/distiller.py +45 -17
- package/src/distiller_cache.py +74 -47
- package/src/environment_auditor.py +34 -12
- package/src/governor.py +83 -26
- package/src/graph_engine.py +653 -140
- package/src/guard.py +316 -132
- package/src/history_compactor.py +57 -26
- package/src/installer.py +174 -131
- package/src/license_manager.py +12 -9
- package/src/loop_detector.py +68 -29
- package/src/mcp_server.py +200 -60
- package/src/metrics.py +141 -54
- package/src/paths.py +32 -6
- package/src/proxy.py +121 -52
- package/src/scoped_search.py +18 -6
- package/src/secret_redactor.py +78 -59
- package/src/skeletonizer.py +68 -13
- package/src/slicer.py +25 -7
- package/src/team_cache.py +10 -3
- package/src/telemetry_sync.py +110 -39
- package/src/tokenizer.py +24 -13
- package/src/treesitter_backend.py +539 -0
- package/src/version_checker.py +67 -32
- package/src/weekly_digest.py +6 -3
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tokensafe",
|
|
3
3
|
"mcpName": "dev.tokensafe/tokensafe",
|
|
4
|
-
"version": "2.
|
|
4
|
+
"version": "2.7.1",
|
|
5
5
|
"description": "Reduce your AI bills by up to 99% locally. Your agents read only needed code, keep prompt caches intact across turns, and keep secrets out of git.",
|
|
6
6
|
"main": "bin/tokensafe.js",
|
|
7
7
|
"bin": {
|
package/plugin.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tokensafe",
|
|
3
3
|
"displayName": "TokenSafe",
|
|
4
|
-
"version": "2.
|
|
4
|
+
"version": "2.7.1",
|
|
5
5
|
"description": "Reduce your AI bills by up to 99% locally. Your agents read only needed code, keep prompt caches intact across turns, and keep secrets out of git.",
|
|
6
6
|
"logo": "assets/logo.svg",
|
|
7
7
|
"author": {
|
package/server.json
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"name": "dev.tokensafe/tokensafe",
|
|
4
4
|
"title": "TokenSafe",
|
|
5
5
|
"description": "Reduce your AI bills by up to 99% locally: focused code, warm prompt caches & zero secret leaks.",
|
|
6
|
-
"version": "2.
|
|
6
|
+
"version": "2.7.1",
|
|
7
7
|
"websiteUrl": "https://tokensafe.dev",
|
|
8
8
|
"repository": {
|
|
9
9
|
"url": "https://github.com/tokensafe-dev/tokensafe",
|
|
@@ -30,7 +30,7 @@
|
|
|
30
30
|
"registryType": "npm",
|
|
31
31
|
"registryBaseUrl": "https://registry.npmjs.org",
|
|
32
32
|
"identifier": "tokensafe",
|
|
33
|
-
"version": "2.
|
|
33
|
+
"version": "2.7.1",
|
|
34
34
|
"runtimeHint": "npx",
|
|
35
35
|
"transport": {
|
|
36
36
|
"type": "stdio"
|
|
@@ -46,7 +46,7 @@
|
|
|
46
46
|
"registryType": "pypi",
|
|
47
47
|
"registryBaseUrl": "https://pypi.org",
|
|
48
48
|
"identifier": "tokensafe",
|
|
49
|
-
"version": "2.
|
|
49
|
+
"version": "2.7.1",
|
|
50
50
|
"runtimeHint": "uvx",
|
|
51
51
|
"transport": {
|
|
52
52
|
"type": "stdio"
|
package/src/agent_firewall.py
CHANGED
|
@@ -58,11 +58,16 @@ class AgentFirewall:
|
|
|
58
58
|
|
|
59
59
|
@staticmethod
|
|
60
60
|
def _file_content_hash(file_path: str) -> str:
|
|
61
|
-
"""sha256 of the file's RAW bytes —
|
|
62
|
-
git checkout mtime resets."""
|
|
61
|
+
"""sha256 of the file's RAW bytes — streamed in 64KB chunks."""
|
|
63
62
|
try:
|
|
63
|
+
h = hashlib.sha256()
|
|
64
64
|
with open(file_path, "rb") as f:
|
|
65
|
-
|
|
65
|
+
while True:
|
|
66
|
+
chunk = f.read(65536)
|
|
67
|
+
if not chunk:
|
|
68
|
+
break
|
|
69
|
+
h.update(chunk)
|
|
70
|
+
return h.hexdigest()
|
|
66
71
|
except OSError:
|
|
67
72
|
return ""
|
|
68
73
|
|
|
@@ -117,34 +122,45 @@ class AgentFirewall:
|
|
|
117
122
|
|
|
118
123
|
abs_path = os.path.abspath(file_path)
|
|
119
124
|
symbol_key = (symbol or "").strip()
|
|
120
|
-
current_hash =
|
|
125
|
+
current_hash = ""
|
|
121
126
|
|
|
122
127
|
hit_data = None
|
|
123
128
|
hit_scope = "session"
|
|
124
129
|
|
|
125
130
|
def _query():
|
|
126
|
-
nonlocal hit_data, hit_scope
|
|
131
|
+
nonlocal hit_data, hit_scope, current_hash
|
|
127
132
|
with tracker._get_connection() as conn:
|
|
128
|
-
# Stage 1: in-session
|
|
133
|
+
# Stage 1: in-session lookup; verify content_hash when present so same-second edits never serve stale content
|
|
129
134
|
row = conn.execute("""
|
|
130
|
-
SELECT id, content, tokens, mtime, hit_count
|
|
135
|
+
SELECT id, content, tokens, mtime, hit_count, content_hash
|
|
131
136
|
FROM subagent_file_cache
|
|
132
137
|
WHERE session_id = ? AND file_path = ? AND symbol = ?;
|
|
133
138
|
""", (session_id, abs_path, symbol_key)).fetchone()
|
|
134
139
|
|
|
135
140
|
if row and row["mtime"] >= current_mtime:
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
141
|
+
stored_hash = row["content_hash"] or ""
|
|
142
|
+
if stored_hash:
|
|
143
|
+
if not current_hash:
|
|
144
|
+
current_hash = cls._file_content_hash(abs_path)
|
|
145
|
+
if not current_hash or stored_hash == current_hash:
|
|
146
|
+
hit_data = (row["id"], row["content"], row["tokens"], row["hit_count"] + 1)
|
|
147
|
+
else:
|
|
148
|
+
hit_data = (row["id"], row["content"], row["tokens"], row["hit_count"] + 1)
|
|
149
|
+
if hit_data is None:
|
|
150
|
+
# Only hash the file when we actually need Stage 2 persistent fallback
|
|
151
|
+
if not current_hash:
|
|
152
|
+
current_hash = cls._file_content_hash(abs_path)
|
|
153
|
+
if current_hash:
|
|
154
|
+
# Stage 2: cross-session, content-hash-validated
|
|
155
|
+
row2 = conn.execute("""
|
|
156
|
+
SELECT id, content, tokens, hit_count
|
|
157
|
+
FROM subagent_file_cache
|
|
158
|
+
WHERE file_path = ? AND symbol = ? AND content_hash = ?
|
|
159
|
+
ORDER BY created_at DESC LIMIT 1;
|
|
160
|
+
""", (abs_path, symbol_key, current_hash)).fetchone()
|
|
161
|
+
if row2:
|
|
162
|
+
hit_data = (row2["id"], row2["content"], row2["tokens"], row2["hit_count"] + 1)
|
|
163
|
+
hit_scope = "persistent"
|
|
148
164
|
|
|
149
165
|
try:
|
|
150
166
|
_query()
|
|
@@ -157,7 +173,7 @@ class AgentFirewall:
|
|
|
157
173
|
cache_id, content, tokens, hit_count = hit_data
|
|
158
174
|
try:
|
|
159
175
|
with tracker._get_connection() as conn:
|
|
160
|
-
conn.execute("UPDATE subagent_file_cache SET hit_count =
|
|
176
|
+
conn.execute("UPDATE subagent_file_cache SET hit_count = hit_count + 1 WHERE id = ?;", (cache_id,))
|
|
161
177
|
except Exception:
|
|
162
178
|
pass
|
|
163
179
|
|
|
@@ -181,7 +197,8 @@ class AgentFirewall:
|
|
|
181
197
|
f"'{os.path.basename(abs_path)}{sym_label}' (sha256:{short_hash})]\n"
|
|
182
198
|
)
|
|
183
199
|
payload = header + content
|
|
184
|
-
|
|
200
|
+
# Honest accounting: full-content return saves 0 tokens vs raw cached text
|
|
201
|
+
opt_tokens = count_tokens(payload)
|
|
185
202
|
|
|
186
203
|
saved = max(0, tokens - opt_tokens)
|
|
187
204
|
try:
|
package/src/cache_normalizer.py
CHANGED
|
@@ -50,7 +50,10 @@ def _inject_cache_control_on_msg(msg: Dict[str, Any]) -> bool:
|
|
|
50
50
|
copied = [dict(b) if isinstance(b, dict) else b for b in content_val]
|
|
51
51
|
for block in reversed(copied):
|
|
52
52
|
if isinstance(block, dict):
|
|
53
|
-
|
|
53
|
+
btype = block.get("type")
|
|
54
|
+
if btype in ("thinking", "redacted_thinking"):
|
|
55
|
+
continue
|
|
56
|
+
if btype == "text" and not str(block.get("text", "")).strip():
|
|
54
57
|
continue
|
|
55
58
|
block["cache_control"] = {"type": "ephemeral"}
|
|
56
59
|
msg["content"] = copied
|
|
@@ -58,16 +61,41 @@ def _inject_cache_control_on_msg(msg: Dict[str, Any]) -> bool:
|
|
|
58
61
|
return False
|
|
59
62
|
|
|
60
63
|
|
|
64
|
+
def _count_existing_cache_controls(tools: Optional[List[Any]], messages: List[Dict[str, Any]]) -> int:
|
|
65
|
+
count = 0
|
|
66
|
+
if isinstance(tools, list):
|
|
67
|
+
for t in tools:
|
|
68
|
+
if isinstance(t, dict) and "cache_control" in t:
|
|
69
|
+
count += 1
|
|
70
|
+
for m in messages:
|
|
71
|
+
c = m.get("content") if isinstance(m, dict) else None
|
|
72
|
+
if isinstance(c, list):
|
|
73
|
+
for b in c:
|
|
74
|
+
if isinstance(b, dict) and "cache_control" in b:
|
|
75
|
+
count += 1
|
|
76
|
+
return count
|
|
77
|
+
|
|
78
|
+
|
|
61
79
|
def _message_text(msg: Dict[str, Any]) -> str:
|
|
62
80
|
content = msg.get("content", "")
|
|
63
81
|
if isinstance(content, str):
|
|
64
82
|
return content
|
|
65
83
|
if isinstance(content, list):
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
84
|
+
parts: List[str] = []
|
|
85
|
+
for b in content:
|
|
86
|
+
if not isinstance(b, dict):
|
|
87
|
+
continue
|
|
88
|
+
if isinstance(b.get("text"), str):
|
|
89
|
+
parts.append(b["text"])
|
|
90
|
+
elif b.get("type") == "tool_use" and b.get("input") is not None:
|
|
91
|
+
parts.append(json.dumps(b["input"], ensure_ascii=False))
|
|
92
|
+
elif b.get("type") == "tool_result":
|
|
93
|
+
tc = b.get("content")
|
|
94
|
+
if isinstance(tc, str):
|
|
95
|
+
parts.append(tc)
|
|
96
|
+
elif tc is not None:
|
|
97
|
+
parts.append(json.dumps(tc, ensure_ascii=False))
|
|
98
|
+
return "\n".join(parts)
|
|
71
99
|
return ""
|
|
72
100
|
|
|
73
101
|
|
|
@@ -76,7 +104,7 @@ class PromptCacheNormalizer:
|
|
|
76
104
|
|
|
77
105
|
VOLATILE_PATTERNS = [
|
|
78
106
|
re.compile(r"The current local time is:.*?(?=\n|$)", re.IGNORECASE),
|
|
79
|
-
re.compile(r"timestamp=\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z?", re.IGNORECASE),
|
|
107
|
+
re.compile(r"timestamp=\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:[.,]\d+)?(?:Z|[+-]\d{2}:?\d{2})?", re.IGNORECASE),
|
|
80
108
|
re.compile(r"request_id=['\"][a-zA-Z0-9_-]+['\"]", re.IGNORECASE),
|
|
81
109
|
re.compile(r"uuid=['\"][a-f0-9-]{36}['\"]", re.IGNORECASE),
|
|
82
110
|
re.compile(r"turn_count=\d+", re.IGNORECASE),
|
|
@@ -184,21 +212,22 @@ class PromptCacheNormalizer:
|
|
|
184
212
|
cache_eligible = prefix_tokens >= 64
|
|
185
213
|
breakpoints_injected = 0
|
|
186
214
|
supports_cc = provider in ("generic", "anthropic")
|
|
215
|
+
existing_cc = _count_existing_cache_controls(norm_tools, normalized)
|
|
187
216
|
|
|
188
217
|
if inject_cache_control and supports_cc:
|
|
189
218
|
# Breakpoint #1: Tools schema tail (for Anthropic when tools are supplied)
|
|
190
219
|
if provider == "anthropic" and norm_tools and len(norm_tools) > 0 and isinstance(norm_tools[-1], dict):
|
|
191
|
-
if prefix_tokens >= 1024:
|
|
220
|
+
if prefix_tokens >= 1024 and (existing_cc + breakpoints_injected) < 4 and "cache_control" not in norm_tools[-1]:
|
|
192
221
|
norm_tools[-1]["cache_control"] = {"type": "ephemeral"}
|
|
193
222
|
breakpoints_injected += 1
|
|
194
223
|
|
|
195
224
|
# Breakpoint #2: Static system/developer prefix tail
|
|
196
|
-
if last_static_idx >= 0 and prefix_tokens >= 1024:
|
|
225
|
+
if last_static_idx >= 0 and prefix_tokens >= 1024 and (existing_cc + breakpoints_injected) < 4:
|
|
197
226
|
if _inject_cache_control_on_msg(normalized[last_static_idx]):
|
|
198
227
|
breakpoints_injected += 1
|
|
199
228
|
|
|
200
229
|
# Breakpoint #3: Rolling history checkpoint (penultimate turn before new user input)
|
|
201
|
-
if provider == "anthropic" and len(normalized) >= 3 and breakpoints_injected < 4:
|
|
230
|
+
if provider == "anthropic" and len(normalized) >= 3 and (existing_cc + breakpoints_injected) < 4:
|
|
202
231
|
penultimate_idx = len(normalized) - 2
|
|
203
232
|
if penultimate_idx > last_static_idx:
|
|
204
233
|
upto_tokens = prefix_tokens + sum(
|
package/src/cli.py
CHANGED
|
@@ -11,7 +11,7 @@ import sys
|
|
|
11
11
|
import os
|
|
12
12
|
import subprocess
|
|
13
13
|
|
|
14
|
-
SCRIPT_DIR = os.path.dirname(os.path.
|
|
14
|
+
SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__))
|
|
15
15
|
PROJECT_ROOT = os.path.dirname(SCRIPT_DIR)
|
|
16
16
|
if PROJECT_ROOT not in sys.path:
|
|
17
17
|
sys.path.insert(0, PROJECT_ROOT)
|
|
@@ -93,10 +93,37 @@ def summarize_unittest_output(raw: str, full_traceback: bool = False) -> str:
|
|
|
93
93
|
return "\n".join(out)
|
|
94
94
|
|
|
95
95
|
|
|
96
|
+
def _print_help():
|
|
97
|
+
print("TokenSafe CLI — usage: tokensafe <command> [args]\n")
|
|
98
|
+
print("Commands:")
|
|
99
|
+
print(" stats / markdown / html Savings analytics (terminal / .md report / dashboard)")
|
|
100
|
+
print(" benchmark Zero-context-loss benchmark suite (simulated SWE-bench harness)")
|
|
101
|
+
print(" graph / map / skeleton Architecture graph / API surface / AST skeleton of a file")
|
|
102
|
+
print(" test <prompt> Preview TOCP S-expression prompt compaction")
|
|
103
|
+
print(" digest [--send] [--email=...] Compile (and optionally dispatch) the weekly team digest")
|
|
104
|
+
print(" guard <command> Pre-flight safety check for a shell command")
|
|
105
|
+
print(" doctor Audit MCP tool overhead and token tax")
|
|
106
|
+
print(" tests [pytest] [--traceback] Run the unit test suite (compact failure report)")
|
|
107
|
+
print(" prune [--days N | --max N] Compact metrics database (roll old events)")
|
|
108
|
+
print(" vacuum Reclaim SQLite disk space")
|
|
109
|
+
print(" reset Reset all local token metrics")
|
|
110
|
+
print(" install | setup [--all] Configure detected agent environments")
|
|
111
|
+
print(" update | upgrade Self-update npm/PyPI package and re-sync agents")
|
|
112
|
+
print(" check-update Check for a newer published version")
|
|
113
|
+
print(" activate / license License activation and status")
|
|
114
|
+
print(" sync Sync telemetry with the cloud backend")
|
|
115
|
+
print(" providers / proxy / mcp Providers info / proxy server / MCP stdio server")
|
|
116
|
+
print(" --version Print version and exit")
|
|
117
|
+
|
|
118
|
+
|
|
96
119
|
def main():
|
|
97
120
|
args = sys.argv[1:]
|
|
98
121
|
command = args[0] if args else "stats"
|
|
99
122
|
|
|
123
|
+
if command in ("--help", "-h", "help"):
|
|
124
|
+
_print_help()
|
|
125
|
+
return
|
|
126
|
+
|
|
100
127
|
# Fast path: version queries must not construct MetricsTracker (which creates
|
|
101
128
|
# the data dir and SQLite database). `tokensafe --version` may run in read-only
|
|
102
129
|
# or foreign directories and must stay side-effect free.
|
|
@@ -113,28 +140,20 @@ def main():
|
|
|
113
140
|
VersionChecker.notify_os_update(force=True)
|
|
114
141
|
return
|
|
115
142
|
|
|
116
|
-
tracker = MetricsTracker()
|
|
117
|
-
dashboard = Dashboard(tracker)
|
|
118
|
-
|
|
119
143
|
if command in ("stats", "dashboard"):
|
|
144
|
+
tracker = MetricsTracker()
|
|
145
|
+
dashboard = Dashboard(tracker)
|
|
120
146
|
try:
|
|
121
147
|
from src.telemetry_sync import TelemetrySync
|
|
122
148
|
TelemetrySync.sync_background()
|
|
123
149
|
except Exception:
|
|
124
150
|
pass
|
|
125
151
|
print(dashboard.render_terminal())
|
|
126
|
-
# Update banner in the most-reliable visibility channel: the stats
|
|
127
|
-
# output itself. Best-effort — never break the dashboard render.
|
|
128
|
-
try:
|
|
129
|
-
from src.version_checker import VersionChecker
|
|
130
|
-
banner = VersionChecker.get_banner()
|
|
131
|
-
if banner:
|
|
132
|
-
print(banner)
|
|
133
|
-
except Exception:
|
|
134
|
-
pass
|
|
135
152
|
|
|
136
153
|
elif command in ("html", "web"):
|
|
137
154
|
from src.paths import resolve_data_dir
|
|
155
|
+
tracker = MetricsTracker()
|
|
156
|
+
dashboard = Dashboard(tracker)
|
|
138
157
|
html_content = dashboard.render_html()
|
|
139
158
|
out_path = os.path.join(resolve_data_dir(), "dashboard.html")
|
|
140
159
|
os.makedirs(os.path.dirname(out_path), exist_ok=True)
|
|
@@ -142,10 +161,19 @@ def main():
|
|
|
142
161
|
f.write(html_content)
|
|
143
162
|
print(f"\n⚡ Interactive HTML Dashboard generated at: {out_path}")
|
|
144
163
|
try:
|
|
145
|
-
|
|
164
|
+
if sys.platform == "darwin":
|
|
165
|
+
subprocess.run(["open", out_path], check=False)
|
|
166
|
+
elif os.name == "nt":
|
|
167
|
+
os.startfile(out_path) # type: ignore[attr-defined]
|
|
168
|
+
else:
|
|
169
|
+
subprocess.run(["xdg-open", out_path], check=False)
|
|
146
170
|
print(" Opened in default browser.")
|
|
147
171
|
except Exception:
|
|
148
|
-
|
|
172
|
+
try:
|
|
173
|
+
import webbrowser
|
|
174
|
+
webbrowser.open(f"file://{os.path.abspath(out_path)}")
|
|
175
|
+
except Exception:
|
|
176
|
+
pass
|
|
149
177
|
|
|
150
178
|
elif command in ("benchmark", "bench"):
|
|
151
179
|
from src.benchmark import BenchmarkSuite
|
|
@@ -204,26 +232,40 @@ def main():
|
|
|
204
232
|
sub = args[1] if len(args) > 1 else "help"
|
|
205
233
|
if sub in ("audit", "scan"):
|
|
206
234
|
target_path = args[2] if len(args) > 2 else os.getcwd()
|
|
235
|
+
if not os.path.exists(target_path):
|
|
236
|
+
print(f"\n\033[31m✖ Target path not found: {target_path}\033[0m\n")
|
|
237
|
+
sys.exit(1)
|
|
207
238
|
print(f"\n\033[1m\033[36m🛡️ TOKENSAFE SECURITY & HYGIENE AUDIT 🛡️\033[0m")
|
|
208
239
|
print(f" Target: {target_path}\n")
|
|
209
240
|
violations = []
|
|
210
241
|
files_scanned = 0
|
|
211
242
|
code_exts = (".py", ".ts", ".tsx", ".js", ".jsx", ".go", ".rs", ".java")
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
243
|
+
if os.path.isfile(target_path):
|
|
244
|
+
files_scanned = 1
|
|
245
|
+
try:
|
|
246
|
+
with open(target_path, "r", encoding="utf-8", errors="replace") as fp:
|
|
247
|
+
content = fp.read()
|
|
248
|
+
res = TokenSafeGuard.inspect_file_write(target_path, content)
|
|
249
|
+
if res.blocked:
|
|
250
|
+
violations.append((os.path.basename(target_path), res.check_name, res.reason))
|
|
251
|
+
except Exception:
|
|
252
|
+
pass
|
|
253
|
+
else:
|
|
254
|
+
for root, dirs, files in os.walk(target_path):
|
|
255
|
+
dirs[:] = [d for d in dirs if d not in (".git", "node_modules", "dist", "build", ".next", ".venv", "venv", "__pycache__")]
|
|
256
|
+
for f in files:
|
|
257
|
+
if f.endswith(code_exts):
|
|
258
|
+
files_scanned += 1
|
|
259
|
+
full_p = os.path.join(root, f)
|
|
260
|
+
try:
|
|
261
|
+
with open(full_p, "r", encoding="utf-8", errors="replace") as fp:
|
|
262
|
+
content = fp.read()
|
|
263
|
+
res = TokenSafeGuard.inspect_file_write(full_p, content)
|
|
264
|
+
if res.blocked:
|
|
265
|
+
rel_p = os.path.relpath(full_p, target_path)
|
|
266
|
+
violations.append((rel_p, res.check_name, res.reason))
|
|
267
|
+
except Exception:
|
|
268
|
+
pass
|
|
227
269
|
if not violations:
|
|
228
270
|
print(f" \033[32m✔ All {files_scanned} files passed TokenSafe Guard audit cleanly! Zero secret fallbacks or SQLi.\033[0m\n")
|
|
229
271
|
else:
|
|
@@ -231,8 +273,21 @@ def main():
|
|
|
231
273
|
for rel_p, check, reason in violations:
|
|
232
274
|
print(f" \033[31m• [{check}]\033[0m {rel_p}: {reason}")
|
|
233
275
|
print()
|
|
234
|
-
elif sub in ("check", "test")
|
|
235
|
-
cmd_to_test = " ".join(args[2:])
|
|
276
|
+
elif sub in ("check", "test") and len(args) > 2:
|
|
277
|
+
cmd_to_test = " ".join(args[2:])
|
|
278
|
+
print(f"\n\033[1m\033[36m🛡️ TOKENSAFE COMMAND GUARD CHECK 🛡️\033[0m\n")
|
|
279
|
+
print(f" Command: \033[1m{cmd_to_test}\033[0m")
|
|
280
|
+
res = TokenSafeGuard.inspect_command(cmd_to_test)
|
|
281
|
+
if res.blocked:
|
|
282
|
+
print(f" Status: \033[31m\033[1mBLOCKED\033[0m [{res.check_name}]")
|
|
283
|
+
print(f" Reason: {res.reason}\n")
|
|
284
|
+
elif res.warning_only:
|
|
285
|
+
print(f" Status: \033[33m\033[1mWARNING\033[0m [{res.check_name}]")
|
|
286
|
+
print(f" Notice: {res.reason}\n")
|
|
287
|
+
else:
|
|
288
|
+
print(f" Status: \033[32m\033[1mALLOWED\033[0m (Command is safe and policy-compliant)\n")
|
|
289
|
+
elif sub not in ("help", "--help", "-h", "check", "test") and len(args) > 1:
|
|
290
|
+
cmd_to_test = " ".join(args[1:])
|
|
236
291
|
print(f"\n\033[1m\033[36m🛡️ TOKENSAFE COMMAND GUARD CHECK 🛡️\033[0m\n")
|
|
237
292
|
print(f" Command: \033[1m{cmd_to_test}\033[0m")
|
|
238
293
|
res = TokenSafeGuard.inspect_command(cmd_to_test)
|
|
@@ -247,11 +302,23 @@ def main():
|
|
|
247
302
|
else:
|
|
248
303
|
print("\nUsage:")
|
|
249
304
|
print(" tokensafe guard \"<command>\" Audit a terminal command line")
|
|
305
|
+
print(" tokensafe guard check \"<command>\" Audit a terminal command line")
|
|
250
306
|
print(" tokensafe guard audit [path] Recursively audit source files for secrets & vulnerabilities\n")
|
|
251
307
|
|
|
252
308
|
elif command == "proxy":
|
|
253
309
|
from src.proxy import run_proxy
|
|
254
|
-
|
|
310
|
+
if len(args) > 1 and args[1] in ("--help", "-h", "help"):
|
|
311
|
+
print("Usage: tokensafe proxy [port] (default: 8765)")
|
|
312
|
+
return
|
|
313
|
+
port = 8765
|
|
314
|
+
if len(args) > 1:
|
|
315
|
+
try:
|
|
316
|
+
port = int(args[1])
|
|
317
|
+
if not (1 <= port <= 65535):
|
|
318
|
+
raise ValueError("port out of range")
|
|
319
|
+
except ValueError:
|
|
320
|
+
print(f"Invalid port '{args[1]}'. Expected integer 1..65535 (default: 8765).")
|
|
321
|
+
sys.exit(1)
|
|
255
322
|
run_proxy(port)
|
|
256
323
|
|
|
257
324
|
elif command == "mcp":
|
|
@@ -292,8 +359,7 @@ def main():
|
|
|
292
359
|
elif command in ("graph", "nodes"):
|
|
293
360
|
from src.graph_engine import GraphEngine
|
|
294
361
|
target_dir = args[1] if len(args) > 1 else os.getcwd()
|
|
295
|
-
graph = GraphEngine(target_dir)
|
|
296
|
-
graph.index_workspace()
|
|
362
|
+
graph = GraphEngine.get_instance(target_dir)
|
|
297
363
|
print(f"\n🔍 TokenSafe Graph Engine — Knowledge Graph & Centrality Analysis")
|
|
298
364
|
print(f" Indexed: {len(graph.file_symbols)} code files, {len(graph.symbols)} symbols\n")
|
|
299
365
|
god_nodes = graph.get_god_nodes(top_n=7)
|
|
@@ -306,10 +372,15 @@ def main():
|
|
|
306
372
|
elif command in ("map", "surface"):
|
|
307
373
|
from src.graph_engine import GraphEngine
|
|
308
374
|
target_dir = args[1] if len(args) > 1 else os.getcwd()
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
375
|
+
if not os.path.isdir(target_dir):
|
|
376
|
+
print(f"\n\033[31m✖ Directory not found: {target_dir}\033[0m\n")
|
|
377
|
+
sys.exit(1)
|
|
378
|
+
graph = GraphEngine.get_instance(target_dir)
|
|
379
|
+
out_file = os.path.join(os.path.abspath(target_dir), "tokensafe-out", "API_SURFACE.md")
|
|
312
380
|
graph.generate_api_surface(out_file)
|
|
381
|
+
if not os.path.exists(out_file):
|
|
382
|
+
print(f"\n\033[31m✖ Could not write API Surface Map to: {out_file}\033[0m\n")
|
|
383
|
+
sys.exit(1)
|
|
313
384
|
print(f"\n✓ Generated API Surface Map: {out_file} ({os.path.getsize(out_file):,} bytes)")
|
|
314
385
|
print(f" AI agents can read this file in ~1.5k tokens instead of reading the entire repo.\n")
|
|
315
386
|
|
|
@@ -318,10 +389,9 @@ def main():
|
|
|
318
389
|
if len(args) < 2:
|
|
319
390
|
print("Usage: tokensafe skeleton <file_path> [target_symbol]")
|
|
320
391
|
sys.exit(1)
|
|
321
|
-
file_path = args[1]
|
|
392
|
+
file_path = os.path.abspath(args[1])
|
|
322
393
|
target_symbol = args[2] if len(args) > 2 else None
|
|
323
|
-
|
|
324
|
-
graph = GraphEngine(target_dir)
|
|
394
|
+
graph, _ = GraphEngine.for_file(file_path)
|
|
325
395
|
res = graph.graph_guided_skeletonize(file_path, target_symbol)
|
|
326
396
|
print(res)
|
|
327
397
|
|
|
@@ -423,7 +493,7 @@ def main():
|
|
|
423
493
|
print("\nSet environment variable or add to data/config.json to activate.\n")
|
|
424
494
|
|
|
425
495
|
elif command in ("markdown", "md", "export"):
|
|
426
|
-
print(
|
|
496
|
+
print(Dashboard(MetricsTracker()).render_markdown())
|
|
427
497
|
|
|
428
498
|
elif command == "test":
|
|
429
499
|
if len(args) < 2:
|
|
@@ -503,7 +573,7 @@ def main():
|
|
|
503
573
|
|
|
504
574
|
print(f"\n\033[1m\033[36m⚡ DATA RETENTION PRUNE ⚡\033[0m")
|
|
505
575
|
print(f"Policy: retain events < {days or 'any'} days old, max {max_events or 'unlimited'} entries.")
|
|
506
|
-
res =
|
|
576
|
+
res = MetricsTracker().prune(days=days, max_events=max_events, vacuum=True)
|
|
507
577
|
b_before = res.get("db_size_before", 0) / 1024.0
|
|
508
578
|
b_after = res.get("db_size_after", 0) / 1024.0
|
|
509
579
|
print(f"\033[32m✔ Pruned {res['pruned_events']} granular events into lifetime rollup table.\033[0m")
|
|
@@ -511,21 +581,27 @@ def main():
|
|
|
511
581
|
|
|
512
582
|
elif command == "vacuum":
|
|
513
583
|
print("\n\033[1m\033[36m⚡ VACUUMING METRICS DATABASE ⚡\033[0m")
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
584
|
+
t = MetricsTracker()
|
|
585
|
+
b_before = (os.path.getsize(t.db_path) if os.path.exists(t.db_path) else 0) / 1024.0
|
|
586
|
+
t.vacuum()
|
|
587
|
+
b_after = (os.path.getsize(t.db_path) if os.path.exists(t.db_path) else 0) / 1024.0
|
|
517
588
|
print(f"\033[32m✔ Database compacted. Size: {b_before:.1f} KB ➔ {b_after:.1f} KB\033[0m\n")
|
|
518
589
|
|
|
519
590
|
elif command in ("digest", "weekly-digest"):
|
|
520
591
|
from src.weekly_digest import WeeklyDigestGenerator
|
|
521
|
-
from src.mailer import TokenSafeMailer
|
|
522
592
|
|
|
523
593
|
target_email = None
|
|
524
594
|
do_send = "--send" in args
|
|
525
595
|
|
|
526
|
-
|
|
596
|
+
idx = 1
|
|
597
|
+
while idx < len(args):
|
|
598
|
+
a = args[idx]
|
|
527
599
|
if a.startswith("--email="):
|
|
528
600
|
target_email = a.split("=", 1)[1].strip()
|
|
601
|
+
elif a == "--email" and idx + 1 < len(args):
|
|
602
|
+
target_email = args[idx + 1].strip()
|
|
603
|
+
idx += 1
|
|
604
|
+
idx += 1
|
|
529
605
|
|
|
530
606
|
if not target_email:
|
|
531
607
|
from src.license_manager import LicenseManager
|
|
@@ -540,21 +616,16 @@ def main():
|
|
|
540
616
|
stats = {
|
|
541
617
|
"owner_email": target_email,
|
|
542
618
|
"tier": "team",
|
|
543
|
-
"seats_total":
|
|
544
|
-
"active_members_count":
|
|
545
|
-
"total_members_count":
|
|
546
|
-
"total_original_tokens":
|
|
547
|
-
"total_saved_tokens":
|
|
548
|
-
"total_saved_human": "
|
|
549
|
-
"total_usd_saved":
|
|
550
|
-
"total_events":
|
|
551
|
-
"reduction_pct":
|
|
552
|
-
"leaderboard": [
|
|
553
|
-
{"rank": 1, "email": "alex.dev@corp.com", "saved_tokens": 1650000, "saved_tokens_human": "1.7M", "usd_saved_formatted": "$11.20", "event_count": 120},
|
|
554
|
-
{"rank": 2, "email": "maria.arch@corp.com", "saved_tokens": 1200000, "saved_tokens_human": "1.2M", "usd_saved_formatted": "$8.10", "event_count": 94},
|
|
555
|
-
{"rank": 3, "email": "sergey.qa@corp.com", "saved_tokens": 850000, "saved_tokens_human": "850K", "usd_saved_formatted": "$5.70", "event_count": 68},
|
|
556
|
-
{"rank": 4, "email": target_email, "saved_tokens": 500000, "saved_tokens_human": "500K", "usd_saved_formatted": "$3.50", "event_count": 58}
|
|
557
|
-
]
|
|
619
|
+
"seats_total": 1,
|
|
620
|
+
"active_members_count": 0,
|
|
621
|
+
"total_members_count": 0,
|
|
622
|
+
"total_original_tokens": 0,
|
|
623
|
+
"total_saved_tokens": 0,
|
|
624
|
+
"total_saved_human": "0",
|
|
625
|
+
"total_usd_saved": 0.0,
|
|
626
|
+
"total_events": 0,
|
|
627
|
+
"reduction_pct": 0.0,
|
|
628
|
+
"leaderboard": [],
|
|
558
629
|
}
|
|
559
630
|
|
|
560
631
|
print(WeeklyDigestGenerator.render_email_text(stats))
|
|
@@ -567,45 +638,27 @@ def main():
|
|
|
567
638
|
print(f"\n📧 Apple-style email HTML preview generated at: {out_html}")
|
|
568
639
|
|
|
569
640
|
if do_send:
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
641
|
+
try:
|
|
642
|
+
from src.mailer import TokenSafeMailer
|
|
643
|
+
ok = TokenSafeMailer.send_weekly_digest(target_email, stats, sync=True)
|
|
644
|
+
if ok:
|
|
645
|
+
print(f"\033[32m✔ Weekly digest successfully dispatched to {target_email}!\033[0m\n")
|
|
646
|
+
else:
|
|
647
|
+
print(f"\033[33m○ Digest dispatch queued (SMTP_PASS not configured in local environment).\033[0m\n")
|
|
648
|
+
except ImportError:
|
|
649
|
+
print("\n\033[33m○ Email delivery is handled by TokenSafe Cloud; preview HTML saved locally.\033[0m\n")
|
|
575
650
|
else:
|
|
576
651
|
print("Tip: Run with --send to dispatch email, or --email=<addr> to target specific team.\n")
|
|
577
652
|
|
|
578
653
|
elif command == "reset":
|
|
579
654
|
confirm = input("Are you sure you want to reset all token metrics? [y/N]: ").strip().lower()
|
|
580
655
|
if confirm == "y":
|
|
581
|
-
|
|
656
|
+
MetricsTracker().reset()
|
|
582
657
|
print("Metrics database reset successfully.")
|
|
583
658
|
else:
|
|
584
659
|
print("Reset cancelled.")
|
|
585
660
|
|
|
586
661
|
else:
|
|
587
|
-
if command in ("--help", "-h", "help"):
|
|
588
|
-
print("TokenSafe CLI — usage: tokensafe <command> [args]\n")
|
|
589
|
-
print("Commands:")
|
|
590
|
-
print(" stats / markdown / html Savings analytics (terminal / .md report / dashboard)")
|
|
591
|
-
print(" benchmark Zero-context-loss benchmark suite (simulated SWE-bench harness)")
|
|
592
|
-
print(" graph / map / skeleton Architecture graph / API surface / AST skeleton of a file")
|
|
593
|
-
print(" test <prompt> Preview TOCP S-expression prompt compaction")
|
|
594
|
-
print(" digest [--send] [--email=...] Compile (and optionally dispatch) the weekly team digest")
|
|
595
|
-
print(" guard <command> Pre-flight safety check for a shell command")
|
|
596
|
-
print(" doctor Audit MCP tool overhead and token tax")
|
|
597
|
-
print(" tests [pytest] [--traceback] Run the unit test suite (compact failure report)")
|
|
598
|
-
print(" prune [--days N | --max N] Compact metrics database (roll old events)")
|
|
599
|
-
print(" vacuum Reclaim SQLite disk space")
|
|
600
|
-
print(" reset Reset all local token metrics")
|
|
601
|
-
print(" install | setup [--all] Configure detected agent environments")
|
|
602
|
-
print(" update | upgrade Self-update npm/PyPI package and re-sync agents")
|
|
603
|
-
print(" check-update Check for a newer published version")
|
|
604
|
-
print(" activate / license License activation and status")
|
|
605
|
-
print(" sync Sync telemetry with the cloud backend")
|
|
606
|
-
print(" providers / proxy / mcp Providers info / proxy server / MCP stdio server")
|
|
607
|
-
print(" --version Print version and exit")
|
|
608
|
-
sys.exit(0)
|
|
609
662
|
print(f"Unknown command: {command}")
|
|
610
663
|
print("Available commands: stats, sync, html, test, tests, doctor, providers, mcp, benchmark, proxy, graph, map, skeleton, guard, vacuum, prune, digest, activate, license, markdown, install, setup, update, check-update, reset. Run 'tokensafe help' for details.")
|
|
611
664
|
sys.exit(1)
|