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 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
@@ -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
- "ephemeralMessage": protocol_reminder
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
@@ -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"] = {"Path": skel_path}
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"] = overwrite_args
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"] = {"Path": skeleton_path}
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
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "tokensafe",
3
3
  "mcpName": "dev.tokensafe/tokensafe",
4
- "version": "2.3.0",
4
+ "version": "2.4.0",
5
5
  "description": "Local-first AI coding guardrails, context slicing, and team ROI telemetry for AI coding agents",
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.3.0",
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.3.0",
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.3.0",
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.3.0",
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 == "OK" or s.startswith("FAILED"):
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 == "OK":
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
- data = json.load(f)
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
- plugins_dir = os.path.join(os.path.expanduser("~"), ".gemini", "config", "plugins")
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
@@ -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":
@@ -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(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "data", "loop_state.json")
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
@@ -39,7 +39,7 @@ from src.scoped_search import ScopedSearch
39
39
 
40
40
  SERVER_INFO = {
41
41
  "name": "tokensafe-mcp",
42
- "version": "2.3.0"
42
+ "version": "2.4.0"
43
43
  }
44
44
 
45
45
  # MCP client attribution: the initialize handshake carries clientInfo, which
@@ -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(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "data", "skeletons")
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
- path = args.get("Path", "")
83
- start_line = args.get("StartLine")
84
- end_line = args.get("EndLine")
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}
@@ -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.3.0"
269
+ "User-Agent": "TokenSafe-Sync/2.4.0"
270
270
  }
271
271
  if active_key:
272
272
  headers["Authorization"] = f"Bearer {active_key}"
@@ -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.3.0"
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