tokensafe 2.3.0 → 2.4.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.
- package/README.md +32 -0
- package/hooks/pre_invocation.py +8 -1
- package/hooks/pre_tool_use.py +13 -3
- package/package.json +1 -1
- package/plugin.json +1 -1
- package/server.json +23 -3
- package/src/cli.py +3 -2
- package/src/environment_auditor.py +48 -5
- package/src/history_compactor.py +1 -1
- package/src/loop_detector.py +3 -1
- package/src/mcp_server.py +1 -1
- package/src/skeletonizer.py +2 -1
- package/src/slicer.py +5 -3
- package/src/telemetry_sync.py +1 -1
- package/src/version_checker.py +1 -1
- package/hooks/__pycache__/pre_invocation.cpython-313.pyc +0 -0
- package/hooks/__pycache__/pre_tool_use.cpython-313.pyc +0 -0
- package/hooks/__pycache__/session_start.cpython-313.pyc +0 -0
- package/hooks/__pycache__/stop_hook.cpython-313.pyc +0 -0
package/README.md
CHANGED
|
@@ -130,6 +130,38 @@ Connect TokenSafe to **Claude Desktop** (`claude_desktop_config.json`) or **Curs
|
|
|
130
130
|
}
|
|
131
131
|
```
|
|
132
132
|
|
|
133
|
+
### Cloud MCP — team metrics & managed distillation
|
|
134
|
+
|
|
135
|
+
The stdio server slices your local files. Cloud features (team savings metrics, license status, server-side prompt distillation, shared team cache, billing) live on the remote streamable-HTTP endpoint:
|
|
136
|
+
|
|
137
|
+
```
|
|
138
|
+
https://api.tokensafe.dev/mcp
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
Auth: `Authorization: Bearer <TS1./TS2. license key>` (from [tokensafe.dev](https://tokensafe.dev)). Public tools — `get_public_stats`, `check_latest_version`, `get_setup_instructions`, `search_docs` — work without a key.
|
|
142
|
+
|
|
143
|
+
### ChatGPT (custom connector — nothing to install)
|
|
144
|
+
|
|
145
|
+
1. **Settings → Connectors → Create**, paste `https://api.tokensafe.dev/mcp`
|
|
146
|
+
2. Authentication: **None** — the four public tools work immediately
|
|
147
|
+
3. Ask ChatGPT to "show TokenSafe public stats" or "search TokenSafe docs"
|
|
148
|
+
|
|
149
|
+
License-gated tools (team metrics, distillation) return a clear upgrade hint when called without a key — the funnel is intentional: see the value, then bring the same endpoint into Codex / Claude Code with your Bearer key to unlock the paid tools.
|
|
150
|
+
|
|
151
|
+
### Codex CLI (`~/.codex/config.toml`, shared with the IDE extension)
|
|
152
|
+
|
|
153
|
+
```toml
|
|
154
|
+
[mcp_servers.tokensafe] # local engine: AST slicing, guards
|
|
155
|
+
command = "npx"
|
|
156
|
+
args = ["-y", "tokensafe", "mcp"]
|
|
157
|
+
|
|
158
|
+
[mcp_servers.tokensafe-cloud] # cloud features
|
|
159
|
+
url = "https://api.tokensafe.dev/mcp"
|
|
160
|
+
bearer_token_env_var = "TOKENSAFE_LICENSE"
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
Set `export TOKENSAFE_LICENSE="TS2.…"`, then run `get_setup_instructions` via any connected agent for per-agent snippets (cursor, claude_desktop, claude_code, codex, windsurf, antigravity, gemini_cli, chatgpt).
|
|
164
|
+
|
|
133
165
|
---
|
|
134
166
|
|
|
135
167
|
## Three Outcomes for Engineering Teams
|
package/hooks/pre_invocation.py
CHANGED
|
@@ -190,8 +190,15 @@ def main():
|
|
|
190
190
|
"• To inspect all exported types/interfaces: call 'tokensafe:get_api_surface(project_path)'.\n"
|
|
191
191
|
"• Prefer 'edit_file' over 'write_file' for existing files."
|
|
192
192
|
)
|
|
193
|
+
# systemMessage nested form (hooks.md contract): ephemeralMessage is
|
|
194
|
+
# deprecated and is converted to a hidden system message anyway. This
|
|
195
|
+
# reminder only fires on guard violations / fresh history folds, so
|
|
196
|
+
# persistence here is intentional reinforcement, not per-turn bloat.
|
|
193
197
|
inject_steps.append({
|
|
194
|
-
"
|
|
198
|
+
"systemMessage": {
|
|
199
|
+
"systemMessage": protocol_reminder,
|
|
200
|
+
"metadata": {}
|
|
201
|
+
}
|
|
195
202
|
})
|
|
196
203
|
|
|
197
204
|
# 5. Context Budget HUD warning: inject once per session when the
|
package/hooks/pre_tool_use.py
CHANGED
|
@@ -139,6 +139,13 @@ def main():
|
|
|
139
139
|
path = args.get("Path") or args.get("path") or args.get("FilePath") or ""
|
|
140
140
|
start_line = args.get("StartLine") or args.get("startLine")
|
|
141
141
|
end_line = args.get("EndLine") or args.get("endLine")
|
|
142
|
+
# The overwrite merge is shallow top-level key replacement — we must
|
|
143
|
+
# rewrite the SAME keys the agent actually sent, or a "path"/"FilePath"
|
|
144
|
+
# read would get the optimized content under a brand-new "Path" key
|
|
145
|
+
# while its original argument still points at the full file.
|
|
146
|
+
path_key = next((k for k in ("Path", "path", "FilePath") if k in args), "Path")
|
|
147
|
+
start_key = next((k for k in ("StartLine", "startLine") if k in args), "StartLine")
|
|
148
|
+
end_key = next((k for k in ("EndLine", "endLine") if k in args), "EndLine")
|
|
142
149
|
|
|
143
150
|
if is_quota_exceeded:
|
|
144
151
|
# Free tier quota reached: pass through raw read_file without AST skeletonization
|
|
@@ -167,7 +174,7 @@ def main():
|
|
|
167
174
|
skel_path, orig_t, skel_t = Skeletonizer.get_skeleton_file(path, target_symbol=target_sym)
|
|
168
175
|
if skel_path and orig_t > skel_t:
|
|
169
176
|
saved = orig_t - skel_t
|
|
170
|
-
response["overwrite"] = {
|
|
177
|
+
response["overwrite"] = {path_key: skel_path}
|
|
171
178
|
response["reason"] = f"Token Optimizer: Graph-guided AST view for '{target_sym}' (Saved ~{saved} tokens)"
|
|
172
179
|
tracker.record_event(
|
|
173
180
|
session_id=conversation_id,
|
|
@@ -184,7 +191,10 @@ def main():
|
|
|
184
191
|
return
|
|
185
192
|
|
|
186
193
|
if overwrite_args and metrics.get("saved_tokens", 0) > 0:
|
|
187
|
-
response["overwrite"] =
|
|
194
|
+
response["overwrite"] = {
|
|
195
|
+
start_key: overwrite_args["StartLine"],
|
|
196
|
+
end_key: overwrite_args["EndLine"],
|
|
197
|
+
}
|
|
188
198
|
response["reason"] = (
|
|
189
199
|
f"Token Optimizer: Sliced read window to lines "
|
|
190
200
|
f"{overwrite_args['StartLine']}-{overwrite_args['EndLine']} (Saved ~{metrics['saved_tokens']} tokens)"
|
|
@@ -209,7 +219,7 @@ def main():
|
|
|
209
219
|
skeleton_path, orig_t, skel_t = Skeletonizer.get_skeleton_file(path)
|
|
210
220
|
if skeleton_path and orig_t > skel_t:
|
|
211
221
|
saved = orig_t - skel_t
|
|
212
|
-
response["overwrite"] = {
|
|
222
|
+
response["overwrite"] = {path_key: skeleton_path}
|
|
213
223
|
response["reason"] = (
|
|
214
224
|
f"Token Optimizer: Provided AST skeleton view (Saved ~{saved} tokens). "
|
|
215
225
|
f"Call read_file with StartLine/EndLine to inspect specific method bodies."
|
package/package.json
CHANGED
package/plugin.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tokensafe",
|
|
3
3
|
"displayName": "TokenSafe",
|
|
4
|
-
"version": "2.
|
|
4
|
+
"version": "2.4.0",
|
|
5
5
|
"description": "Zero-Loss Token Economy & Context Optimizer for AI Agents. Compresses prompts, slices AST/tool outputs, and prevents stuck loops.",
|
|
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": "Cut AI coding agent token usage up to 90% via AST slicing, dependency graphs & security guards.",
|
|
6
|
-
"version": "2.
|
|
6
|
+
"version": "2.4.0",
|
|
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.4.0",
|
|
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.4.0",
|
|
50
50
|
"runtimeHint": "uvx",
|
|
51
51
|
"transport": {
|
|
52
52
|
"type": "stdio"
|
|
@@ -58,5 +58,25 @@
|
|
|
58
58
|
}
|
|
59
59
|
]
|
|
60
60
|
}
|
|
61
|
+
],
|
|
62
|
+
"remotes": [
|
|
63
|
+
{
|
|
64
|
+
"type": "streamable-http",
|
|
65
|
+
"url": "https://api.tokensafe.dev/mcp",
|
|
66
|
+
"headers": [
|
|
67
|
+
{
|
|
68
|
+
"name": "Authorization",
|
|
69
|
+
"value": "Bearer {tokensafe_license_key}",
|
|
70
|
+
"isSecret": true,
|
|
71
|
+
"variables": {
|
|
72
|
+
"tokensafe_license_key": {
|
|
73
|
+
"description": "TokenSafe license key (TS1./TS2.) from tokensafe.dev. Optional: public tools (stats, docs, setup) work without it.",
|
|
74
|
+
"isSecret": true,
|
|
75
|
+
"required": false
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
]
|
|
80
|
+
}
|
|
61
81
|
]
|
|
62
82
|
}
|
package/src/cli.py
CHANGED
|
@@ -32,7 +32,8 @@ def summarize_unittest_output(raw: str, full_traceback: bool = False) -> str:
|
|
|
32
32
|
s = ln.strip()
|
|
33
33
|
if s.startswith("Ran ") and " test" in s:
|
|
34
34
|
ran = s
|
|
35
|
-
elif s
|
|
35
|
+
elif s.startswith("OK") or s.startswith("FAILED"):
|
|
36
|
+
# "OK (skipped=N)" must count as success too, not just bare "OK".
|
|
36
37
|
status = s
|
|
37
38
|
# Failure blocks: one '=' * 70 line PER failure, then the title line,
|
|
38
39
|
# a '-' * 70 rule and the traceback — each block is self-contained.
|
|
@@ -80,7 +81,7 @@ def summarize_unittest_output(raw: str, full_traceback: bool = False) -> str:
|
|
|
80
81
|
tail = [l for l in lines if l.strip()][-15:]
|
|
81
82
|
return "\n".join(tail) if tail else "(no unittest output captured)"
|
|
82
83
|
|
|
83
|
-
if status
|
|
84
|
+
if status.startswith("OK"):
|
|
84
85
|
return f"\033[32m✓ {ran} — all tests passed\033[0m"
|
|
85
86
|
|
|
86
87
|
out = [f"\033[31m✗ {ran} — {status}\033[0m"]
|
|
@@ -52,23 +52,66 @@ class EnvironmentAuditor:
|
|
|
52
52
|
]
|
|
53
53
|
return [d for d in dirs if os.path.isdir(d)]
|
|
54
54
|
|
|
55
|
+
@classmethod
|
|
56
|
+
def get_plugins_dir(cls) -> str:
|
|
57
|
+
return os.path.join(os.path.expanduser("~"), ".gemini", "config", "plugins")
|
|
58
|
+
|
|
59
|
+
@classmethod
|
|
60
|
+
def get_enable_state_path(cls) -> str:
|
|
61
|
+
return os.path.join(os.path.expanduser("~"), ".gemini", "config", "config.json")
|
|
62
|
+
|
|
63
|
+
@classmethod
|
|
64
|
+
def _get_disabled_plugin_names(cls) -> set:
|
|
65
|
+
"""Plugin directory names that are switched off. plugins.md: the
|
|
66
|
+
enable-state lives in config.json under a `plugins` map keyed by the
|
|
67
|
+
plugin's directory name; a `plugin.json` `"disabled": true` also ships
|
|
68
|
+
a plugin switched off."""
|
|
69
|
+
disabled = set()
|
|
70
|
+
state_path = cls.get_enable_state_path()
|
|
71
|
+
if os.path.isfile(state_path):
|
|
72
|
+
try:
|
|
73
|
+
with open(state_path, "r", encoding="utf-8") as f:
|
|
74
|
+
plugins_state = json.load(f).get("plugins", {})
|
|
75
|
+
for name, state in plugins_state.items():
|
|
76
|
+
if isinstance(state, dict) and state.get("enabled") is False:
|
|
77
|
+
disabled.add(name)
|
|
78
|
+
except Exception:
|
|
79
|
+
pass
|
|
80
|
+
plugins_dir = cls.get_plugins_dir()
|
|
81
|
+
if os.path.isdir(plugins_dir):
|
|
82
|
+
for entry in os.listdir(plugins_dir):
|
|
83
|
+
manifest = os.path.join(plugins_dir, entry, "plugin.json")
|
|
84
|
+
if os.path.isfile(manifest):
|
|
85
|
+
try:
|
|
86
|
+
with open(manifest, "r", encoding="utf-8") as f:
|
|
87
|
+
if json.load(f).get("disabled") is True:
|
|
88
|
+
disabled.add(entry)
|
|
89
|
+
except Exception:
|
|
90
|
+
pass
|
|
91
|
+
return disabled
|
|
92
|
+
|
|
55
93
|
@classmethod
|
|
56
94
|
def get_configured_mcp_servers(cls) -> Dict[str, Any]:
|
|
57
95
|
configured: Dict[str, Any] = {}
|
|
96
|
+
# Merge EVERY present config file: both ~/.gemini/config and the
|
|
97
|
+
# antigravity dir can legitimately carry servers (they are merged by
|
|
98
|
+
# Antigravity too), so breaking on the first one undercounts.
|
|
58
99
|
for p in cls.get_config_paths():
|
|
59
100
|
if os.path.isfile(p):
|
|
60
101
|
try:
|
|
61
102
|
with open(p, "r", encoding="utf-8") as f:
|
|
62
|
-
|
|
63
|
-
configured.update(data.get("mcpServers", {}))
|
|
64
|
-
break
|
|
103
|
+
configured.update(json.load(f).get("mcpServers", {}))
|
|
65
104
|
except Exception:
|
|
66
105
|
continue
|
|
67
106
|
# Plugin-declared servers (plugins/<name>/mcp_config.json) are loaded
|
|
68
|
-
# by Antigravity together with the plugin — audit them too
|
|
69
|
-
|
|
107
|
+
# by Antigravity together with the plugin — audit them too, unless the
|
|
108
|
+
# plugin itself is disabled.
|
|
109
|
+
disabled = cls._get_disabled_plugin_names()
|
|
110
|
+
plugins_dir = cls.get_plugins_dir()
|
|
70
111
|
if os.path.isdir(plugins_dir):
|
|
71
112
|
for entry in sorted(os.listdir(plugins_dir)):
|
|
113
|
+
if entry in disabled or entry.endswith(".disabled"):
|
|
114
|
+
continue
|
|
72
115
|
plugin_cfg = os.path.join(plugins_dir, entry, "mcp_config.json")
|
|
73
116
|
if not os.path.isfile(plugin_cfg):
|
|
74
117
|
continue
|
package/src/history_compactor.py
CHANGED
|
@@ -61,7 +61,7 @@ class HistoryCompactor:
|
|
|
61
61
|
if p:
|
|
62
62
|
read_files.add(os.path.basename(p))
|
|
63
63
|
elif name in ("edit_file", "write_file"):
|
|
64
|
-
p = args.get("Path"
|
|
64
|
+
p = args.get("Path") or args.get("path") or args.get("FilePath") or ""
|
|
65
65
|
if p:
|
|
66
66
|
edited_files.add(os.path.basename(p))
|
|
67
67
|
elif name == "run_command":
|
package/src/loop_detector.py
CHANGED
|
@@ -10,10 +10,12 @@ import hashlib
|
|
|
10
10
|
from contextlib import contextmanager
|
|
11
11
|
from typing import Dict, Any, Tuple
|
|
12
12
|
|
|
13
|
+
from src.paths import resolve_data_dir
|
|
14
|
+
|
|
13
15
|
class LoopDetector:
|
|
14
16
|
"""Tracks tool invocation signatures to detect hallucination loops."""
|
|
15
17
|
|
|
16
|
-
STATE_FILE = os.path.join(
|
|
18
|
+
STATE_FILE = os.path.join(resolve_data_dir(), "loop_state.json")
|
|
17
19
|
MAX_IDENTICAL_REPEATS = 3
|
|
18
20
|
SESSION_TTL_SECONDS = 48 * 3600 # prune sessions idle for more than 2 days
|
|
19
21
|
|
package/src/mcp_server.py
CHANGED
package/src/skeletonizer.py
CHANGED
|
@@ -11,6 +11,7 @@ import hashlib
|
|
|
11
11
|
import json
|
|
12
12
|
from typing import Optional, Tuple, Set
|
|
13
13
|
from src.tokenizer import count_tokens
|
|
14
|
+
from src.paths import resolve_data_dir
|
|
14
15
|
|
|
15
16
|
CONTROL_KEYWORDS = {
|
|
16
17
|
'if', 'else', 'for', 'while', 'do', 'switch', 'case', 'default',
|
|
@@ -168,7 +169,7 @@ class Skeletonizer:
|
|
|
168
169
|
out.append("".join(res))
|
|
169
170
|
return out
|
|
170
171
|
|
|
171
|
-
CACHE_DIR = os.path.join(
|
|
172
|
+
CACHE_DIR = os.path.join(resolve_data_dir(), "skeletons")
|
|
172
173
|
|
|
173
174
|
@classmethod
|
|
174
175
|
def skeletonize_code(cls, code: str, file_ext: str, keep_symbols: Optional[Set[str]] = None) -> str:
|
package/src/slicer.py
CHANGED
|
@@ -79,9 +79,11 @@ class ToolSlicer:
|
|
|
79
79
|
If a file is large and no bounds are given, locates target symbol or applies windowing.
|
|
80
80
|
Returns: (modified_args_or_none, metrics_dict)
|
|
81
81
|
"""
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
82
|
+
# Tolerant arg keys: hooks keep proto casing ("Path"), but the
|
|
83
|
+
# view_file/lowercase variants may send "path"/"FilePath".
|
|
84
|
+
path = args.get("Path") or args.get("path") or args.get("FilePath") or ""
|
|
85
|
+
start_line = args.get("StartLine") or args.get("startLine")
|
|
86
|
+
end_line = args.get("EndLine") or args.get("endLine")
|
|
85
87
|
|
|
86
88
|
if not path or not os.path.isabs(path) or not os.path.exists(path):
|
|
87
89
|
return {}, {"saved_tokens": 0, "original_tokens": 0, "optimized_tokens": 0}
|
package/src/telemetry_sync.py
CHANGED
|
@@ -266,7 +266,7 @@ class TelemetrySync:
|
|
|
266
266
|
rollup_synced = bool(state.get("lifetime_rollup_synced", False))
|
|
267
267
|
headers = {
|
|
268
268
|
"Content-Type": "application/json",
|
|
269
|
-
"User-Agent": "TokenSafe-Sync/2.
|
|
269
|
+
"User-Agent": "TokenSafe-Sync/2.4.0"
|
|
270
270
|
}
|
|
271
271
|
if active_key:
|
|
272
272
|
headers["Authorization"] = f"Bearer {active_key}"
|
package/src/version_checker.py
CHANGED
|
@@ -16,7 +16,7 @@ import urllib.request
|
|
|
16
16
|
import urllib.error
|
|
17
17
|
from typing import Dict, Any, Optional, Tuple
|
|
18
18
|
|
|
19
|
-
CURRENT_VERSION = "2.
|
|
19
|
+
CURRENT_VERSION = "2.4.0"
|
|
20
20
|
CACHE_TTL = 86400 # 24 hours
|
|
21
21
|
# When the cloud is unreachable we must NOT cache the synthesized "up to date"
|
|
22
22
|
# answer for a full day — otherwise an update released right after an outage
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|