tokensafe 2.2.0 → 2.3.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 +8 -7
- 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/hooks/claude_code_hook.py +13 -1
- package/hooks/pre_invocation.py +31 -58
- package/hooks/pre_tool_use.py +12 -7
- package/hooks/session_start.py +88 -0
- package/hooks/stop_hook.py +86 -0
- package/hooks.json +15 -1
- package/mcp_config.json +11 -0
- package/package.json +4 -3
- package/plugin.json +4 -4
- package/server.json +4 -4
- package/skills/token-optimizer/SKILL.md +9 -151
- package/skills/token-optimizer/references/cli-reference.md +31 -0
- package/skills/token-optimizer/references/guard-checks.md +17 -0
- package/skills/token-optimizer/references/mcp-tools.md +101 -0
- package/src/adapter_core.py +13 -0
- package/src/cli.py +12 -4
- package/src/command_sanitizer.py +155 -3
- package/src/compactor.py +0 -1
- package/src/distiller_cache.py +3 -2
- package/src/environment_auditor.py +147 -22
- package/src/history_compactor.py +4 -2
- package/src/installer.py +107 -12
- package/src/license_manager.py +3 -1
- package/src/mcp_server.py +16 -7
- package/src/metrics.py +3 -4
- package/src/paths.py +86 -0
- package/src/proxy.py +3 -5
- package/src/team_cache.py +2 -1
- package/src/telemetry_sync.py +4 -2
- package/src/version_checker.py +4 -2
- package/src/weekly_digest.py +7 -5
|
@@ -2,19 +2,30 @@
|
|
|
2
2
|
Environment Auditor & Context Bloat Guard for Antigravity Token Optimizer.
|
|
3
3
|
Detects heavy MCP servers, redundant tool schemas, and excessive skills that bloat
|
|
4
4
|
the system prompt on every API turn. Provides one-click enable/disable toggles.
|
|
5
|
+
Also audits always-on rule files against the Antigravity limits (rules.md):
|
|
6
|
+
24 KB per file after @[label](path) expansion, 20,000-token shared budget.
|
|
5
7
|
"""
|
|
6
8
|
|
|
7
9
|
import os
|
|
10
|
+
import re
|
|
8
11
|
import json
|
|
9
12
|
from typing import Dict, List, Any, Optional
|
|
10
13
|
|
|
14
|
+
from src.tokenizer import count_tokens
|
|
15
|
+
|
|
11
16
|
EST_TOKENS_PER_TOOL = 25
|
|
12
17
|
EST_TOKENS_PER_SKILL = 180
|
|
13
18
|
CRITICAL_TOOL_COUNT_THRESHOLD = 40
|
|
14
19
|
|
|
20
|
+
# rules.md contract limits
|
|
21
|
+
RULE_FILE_LIMIT_BYTES = 24000 # per rule file, after @[label](path) expansion
|
|
22
|
+
RULES_BUDGET_TOKENS = 20000 # shared always-on/global rules budget
|
|
23
|
+
|
|
24
|
+
_RULE_INCLUDE_RE = re.compile(r"@\[[^\]]*\]\(([^)]+)\)")
|
|
25
|
+
|
|
15
26
|
|
|
16
27
|
class EnvironmentAuditor:
|
|
17
|
-
"""Scans and audits static context overhead (MCP servers
|
|
28
|
+
"""Scans and audits static context overhead (MCP servers, skills, rules)."""
|
|
18
29
|
|
|
19
30
|
@classmethod
|
|
20
31
|
def get_config_paths(cls) -> List[str]:
|
|
@@ -29,30 +40,115 @@ class EnvironmentAuditor:
|
|
|
29
40
|
return os.path.join(os.path.expanduser("~"), ".gemini", "antigravity", "mcp")
|
|
30
41
|
|
|
31
42
|
@classmethod
|
|
32
|
-
def get_skills_dirs(cls) -> List[str]:
|
|
43
|
+
def get_skills_dirs(cls, workspace_root: Optional[str] = None) -> List[str]:
|
|
44
|
+
"""Global skill roots plus the workspace `.agents/` customization dir
|
|
45
|
+
(json_configs.md: one level deep, entries scanned for SKILL.md)."""
|
|
33
46
|
home = os.path.expanduser("~")
|
|
34
47
|
dirs = [
|
|
35
48
|
os.path.join(home, ".gemini", "config", "skills"),
|
|
36
49
|
os.path.join(home, ".gemini", "config", "plugins"),
|
|
37
50
|
os.path.join(home, ".gemini", "antigravity", "builtin", "skills"),
|
|
51
|
+
os.path.join(workspace_root or os.getcwd(), ".agents"),
|
|
38
52
|
]
|
|
39
53
|
return [d for d in dirs if os.path.isdir(d)]
|
|
40
54
|
|
|
41
55
|
@classmethod
|
|
42
56
|
def get_configured_mcp_servers(cls) -> Dict[str, Any]:
|
|
57
|
+
configured: Dict[str, Any] = {}
|
|
43
58
|
for p in cls.get_config_paths():
|
|
44
59
|
if os.path.isfile(p):
|
|
45
60
|
try:
|
|
46
61
|
with open(p, "r", encoding="utf-8") as f:
|
|
47
62
|
data = json.load(f)
|
|
48
|
-
|
|
63
|
+
configured.update(data.get("mcpServers", {}))
|
|
64
|
+
break
|
|
65
|
+
except Exception:
|
|
66
|
+
continue
|
|
67
|
+
# 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")
|
|
70
|
+
if os.path.isdir(plugins_dir):
|
|
71
|
+
for entry in sorted(os.listdir(plugins_dir)):
|
|
72
|
+
plugin_cfg = os.path.join(plugins_dir, entry, "mcp_config.json")
|
|
73
|
+
if not os.path.isfile(plugin_cfg):
|
|
74
|
+
continue
|
|
75
|
+
try:
|
|
76
|
+
with open(plugin_cfg, "r", encoding="utf-8") as f:
|
|
77
|
+
configured.update(json.load(f).get("mcpServers", {}))
|
|
49
78
|
except Exception:
|
|
50
79
|
continue
|
|
51
|
-
return
|
|
80
|
+
return configured
|
|
81
|
+
|
|
82
|
+
@classmethod
|
|
83
|
+
def _load_rule_text(cls, path: str, depth: int = 1) -> str:
|
|
84
|
+
"""Reads a rule file with one level of @[label](path) include expansion."""
|
|
85
|
+
try:
|
|
86
|
+
with open(path, "r", encoding="utf-8", errors="replace") as f:
|
|
87
|
+
text = f.read()
|
|
88
|
+
except Exception:
|
|
89
|
+
return ""
|
|
90
|
+
|
|
91
|
+
if depth <= 0:
|
|
92
|
+
return text
|
|
93
|
+
|
|
94
|
+
def _sub(match: "re.Match[str]") -> str:
|
|
95
|
+
inc = match.group(1)
|
|
96
|
+
if not os.path.isabs(inc):
|
|
97
|
+
inc = os.path.join(os.path.dirname(path), inc)
|
|
98
|
+
try:
|
|
99
|
+
with open(inc, "r", encoding="utf-8", errors="replace") as f:
|
|
100
|
+
return f.read()
|
|
101
|
+
except Exception:
|
|
102
|
+
return ""
|
|
103
|
+
|
|
104
|
+
return _RULE_INCLUDE_RE.sub(_sub, text)
|
|
52
105
|
|
|
53
106
|
@classmethod
|
|
54
|
-
def
|
|
55
|
-
"""Audits
|
|
107
|
+
def audit_rules(cls, workspace_root: Optional[str] = None) -> Dict[str, Any]:
|
|
108
|
+
"""Audits workspace rule files against the rules.md limits.
|
|
109
|
+
|
|
110
|
+
Scans AGENTS.md / GEMINI.md at the workspace root and .agents/rules/*.md.
|
|
111
|
+
Per-file: effective byte size after include expansion vs the 24 KB cap.
|
|
112
|
+
Aggregate: token count vs the 20,000-token always-on rules budget
|
|
113
|
+
(exceeding it demotes rules to file-path pointers)."""
|
|
114
|
+
root = workspace_root or os.getcwd()
|
|
115
|
+
candidates = [
|
|
116
|
+
os.path.join(root, "AGENTS.md"),
|
|
117
|
+
os.path.join(root, "GEMINI.md"),
|
|
118
|
+
]
|
|
119
|
+
rules_dir = os.path.join(root, ".agents", "rules")
|
|
120
|
+
if os.path.isdir(rules_dir):
|
|
121
|
+
for entry in sorted(os.listdir(rules_dir)):
|
|
122
|
+
if entry.endswith(".md"):
|
|
123
|
+
candidates.append(os.path.join(rules_dir, entry))
|
|
124
|
+
|
|
125
|
+
violations: List[Dict[str, Any]] = []
|
|
126
|
+
total_tokens = 0
|
|
127
|
+
files_count = 0
|
|
128
|
+
for path in candidates:
|
|
129
|
+
if not os.path.isfile(path):
|
|
130
|
+
continue
|
|
131
|
+
files_count += 1
|
|
132
|
+
text = cls._load_rule_text(path)
|
|
133
|
+
effective_bytes = len(text.encode("utf-8", errors="replace"))
|
|
134
|
+
total_tokens += count_tokens(text)
|
|
135
|
+
if effective_bytes > RULE_FILE_LIMIT_BYTES:
|
|
136
|
+
violations.append({
|
|
137
|
+
"path": os.path.relpath(path, root),
|
|
138
|
+
"effective_bytes": effective_bytes,
|
|
139
|
+
"limit_bytes": RULE_FILE_LIMIT_BYTES,
|
|
140
|
+
})
|
|
141
|
+
|
|
142
|
+
return {
|
|
143
|
+
"files": files_count,
|
|
144
|
+
"total_tokens": total_tokens,
|
|
145
|
+
"budget_exceeded": total_tokens > RULES_BUDGET_TOKENS,
|
|
146
|
+
"violations": violations,
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
@classmethod
|
|
150
|
+
def audit(cls, workspace_root: Optional[str] = None) -> Dict[str, Any]:
|
|
151
|
+
"""Audits all active MCP servers, skills and rules for context footprint."""
|
|
56
152
|
configured = cls.get_configured_mcp_servers()
|
|
57
153
|
schemas_dir = cls.get_mcp_schemas_dir()
|
|
58
154
|
|
|
@@ -97,11 +193,14 @@ class EnvironmentAuditor:
|
|
|
97
193
|
|
|
98
194
|
# 2. Count skills
|
|
99
195
|
skills_count = 0
|
|
100
|
-
for sdir in cls.get_skills_dirs():
|
|
196
|
+
for sdir in cls.get_skills_dirs(workspace_root):
|
|
101
197
|
for root, dirs, files in os.walk(sdir):
|
|
102
198
|
if "SKILL.md" in files:
|
|
103
199
|
skills_count += 1
|
|
104
200
|
|
|
201
|
+
# 3. Rule files (rules.md limits)
|
|
202
|
+
rules = cls.audit_rules(workspace_root)
|
|
203
|
+
|
|
105
204
|
total_mcp_tools = sum(s["tool_count"] for s in servers.values() if s["active"])
|
|
106
205
|
total_mcp_tokens = sum(s["est_tokens_per_turn"] for s in servers.values() if s["active"])
|
|
107
206
|
total_skills_tokens = skills_count * EST_TOKENS_PER_SKILL
|
|
@@ -118,23 +217,42 @@ class EnvironmentAuditor:
|
|
|
118
217
|
"skills_tokens_per_turn": total_skills_tokens,
|
|
119
218
|
"total_static_tokens_per_turn": total_static_tokens,
|
|
120
219
|
"bloated_servers": bloated_servers,
|
|
121
|
-
"has_critical_bloat": len(bloated_servers) > 0
|
|
220
|
+
"has_critical_bloat": len(bloated_servers) > 0,
|
|
221
|
+
"rules": rules
|
|
122
222
|
}
|
|
123
223
|
|
|
124
224
|
@classmethod
|
|
125
|
-
def get_bloat_warning(cls) -> Optional[str]:
|
|
126
|
-
"""Returns a formatted warning string if critical context bloat
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
225
|
+
def get_bloat_warning(cls, workspace_root: Optional[str] = None) -> Optional[str]:
|
|
226
|
+
"""Returns a formatted warning string if critical context bloat or
|
|
227
|
+
rule-file overruns are detected."""
|
|
228
|
+
report = cls.audit(workspace_root)
|
|
229
|
+
parts: List[str] = []
|
|
130
230
|
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
231
|
+
if report["has_critical_bloat"]:
|
|
232
|
+
bloated = report["bloated_servers"]
|
|
233
|
+
names = ", ".join([f"`{b['name']}` ({b['tool_count']} tools, ~{b['est_tokens_per_turn']:,} tokens/turn)" for b in bloated])
|
|
234
|
+
parts.append(
|
|
235
|
+
f"Heavy MCP server detected: {names}. "
|
|
236
|
+
f"Static context overhead per turn: **~{report['total_static_tokens_per_turn']:,} tokens**. "
|
|
237
|
+
f"Disable unused servers via `tokensafe mcp disable <name>`."
|
|
238
|
+
)
|
|
239
|
+
|
|
240
|
+
rules = report.get("rules") or {}
|
|
241
|
+
if rules.get("budget_exceeded"):
|
|
242
|
+
parts.append(
|
|
243
|
+
f"Always-on rule files total ~{rules['total_tokens']:,} tokens — over the "
|
|
244
|
+
f"{RULES_BUDGET_TOKENS:,}-token rules budget; over-budget rules degrade to file-path pointers. "
|
|
245
|
+
f"Trim AGENTS.md / .agents/rules/*.md."
|
|
246
|
+
)
|
|
247
|
+
for v in rules.get("violations", []):
|
|
248
|
+
parts.append(
|
|
249
|
+
f"Rule file `{v['path']}` is {v['effective_bytes']:,} bytes after @[label](path) expansion — "
|
|
250
|
+
f"over the {RULE_FILE_LIMIT_BYTES:,}-byte per-file cap; it will be truncated."
|
|
251
|
+
)
|
|
252
|
+
|
|
253
|
+
if not parts:
|
|
254
|
+
return None
|
|
255
|
+
return "⚠️ **TokenSafe Bloat Alert**: " + " ".join(parts)
|
|
138
256
|
|
|
139
257
|
@classmethod
|
|
140
258
|
def disable_mcp(cls, server_name: str) -> Dict[str, Any]:
|
|
@@ -227,9 +345,9 @@ class EnvironmentAuditor:
|
|
|
227
345
|
}
|
|
228
346
|
|
|
229
347
|
@classmethod
|
|
230
|
-
def format_cli_report(cls) -> str:
|
|
348
|
+
def format_cli_report(cls, workspace_root: Optional[str] = None) -> str:
|
|
231
349
|
"""Formats visual CLI report for tokensafe doctor."""
|
|
232
|
-
report = cls.audit()
|
|
350
|
+
report = cls.audit(workspace_root)
|
|
233
351
|
lines = [
|
|
234
352
|
"\n\033[1m\033[36m⚡ TOKENSAFE ENVIRONMENT AUDIT (CONTEXT TAX DOCTOR) ⚡\033[0m\n",
|
|
235
353
|
f" \033[1mTotal Base Context Tax:\033[0m ~{report['total_static_tokens_per_turn']:,} tokens on EVERY API turn\n",
|
|
@@ -248,6 +366,13 @@ class EnvironmentAuditor:
|
|
|
248
366
|
|
|
249
367
|
lines.append(f"\n \033[1mInstalled Skills:\033[0m {report['total_skills']} skills (~{report['skills_tokens_per_turn']:,} tokens/turn)")
|
|
250
368
|
|
|
369
|
+
rules = report.get("rules") or {}
|
|
370
|
+
if rules.get("files"):
|
|
371
|
+
budget_flag = "\033[33mover budget\033[0m" if rules.get("budget_exceeded") else "\033[32mwithin budget\033[0m"
|
|
372
|
+
lines.append(f" \033[1mRule Files:\033[0m {rules['files']} files, ~{rules['total_tokens']:,}/20,000 tokens [{budget_flag}]")
|
|
373
|
+
for v in rules.get("violations", []):
|
|
374
|
+
lines.append(f" \033[31m✖ {v['path']}: {v['effective_bytes']:,} bytes > {RULE_FILE_LIMIT_BYTES:,} cap\033[0m")
|
|
375
|
+
|
|
251
376
|
if report["has_critical_bloat"]:
|
|
252
377
|
lines.append("\n \033[33m\033[1mDiagnostic Recommendation:\033[0m")
|
|
253
378
|
for b in report["bloated_servers"]:
|
package/src/history_compactor.py
CHANGED
|
@@ -54,8 +54,10 @@ class HistoryCompactor:
|
|
|
54
54
|
for tc in tool_calls:
|
|
55
55
|
name = tc.get("name", "")
|
|
56
56
|
args = tc.get("args", {})
|
|
57
|
-
if name
|
|
58
|
-
|
|
57
|
+
if name in ("read_file", "view_file"):
|
|
58
|
+
# 'view_file' is the IDE-surface name for read_file;
|
|
59
|
+
# arg keys keep proto casing but tolerate lowercase.
|
|
60
|
+
p = args.get("Path") or args.get("path") or args.get("FilePath") or ""
|
|
59
61
|
if p:
|
|
60
62
|
read_files.add(os.path.basename(p))
|
|
61
63
|
elif name in ("edit_file", "write_file"):
|
package/src/installer.py
CHANGED
|
@@ -40,7 +40,7 @@ UNIFIED_TOKENSAFE_RULE = (
|
|
|
40
40
|
"2. **Mandatory Symbol & Component Inspection**: Whenever locating or reading a function, class, component, or method, ALWAYS call `tokensafe:smart_read_file` with `path` and `symbol`. It preserves the full executable target and 1-hop dependencies while folding inert code into signatures (-85% to -92% tokens).\n"
|
|
41
41
|
"3. **Architecture Discovery**: Always call `tokensafe:get_architecture_graph(project_path)` before exploratory multi-file reading. Returns project God Nodes and key dependency hubs in < 250 tokens without file crawling.\n"
|
|
42
42
|
"4. **API Surface Map**: Use `tokensafe:get_api_surface(project_path)` to get all exported classes, types, and interfaces in a single markdown map.\n"
|
|
43
|
-
"5. **Command Sanitization**: Use `sanitize_command` on high-output terminal commands (`git diff/log/show/blame`, `rg`, `find`, `grep`, `docker`/`kubectl logs`, `npm`/`pip install`, `cat` of lockfiles, `curl`) — compound commands (`a && b ; c`) are rewritten per stage. Run unit tests via the `tokensafe tests [pytest]` CLI (compact failure report) instead of raw `python3 -m unittest discover`; never leave `vitest`/`jest` in watch mode.\n"
|
|
43
|
+
"5. **Command Sanitization**: Use `sanitize_command` on high-output terminal commands (`git diff/log/show/blame`, `rg`, `find`, `grep`, `docker`/`kubectl logs`, `npm`/`pip install`, `cat` of lockfiles, `curl`) — compound commands (`a && b ; c`) are rewritten per stage. Run unit tests via the `tokensafe tests [pytest]` CLI (compact failure report) instead of raw `python3 -m unittest discover`; never leave `vitest`/`jest` in watch mode — pass the optional `cwd` to `sanitize_command` for test commands so the package.json peek can identify the runner behind opaque `yarn/npm test` scripts.\n"
|
|
44
44
|
"6. **Proof-of-Savings Turn Footer (always in English)**:\n"
|
|
45
45
|
"At the end of your response for any turn where tools were executed, files were inspected, commands were sanitized, or prompts were compacted, append a compact 1-line footer in English:\n"
|
|
46
46
|
"`⚡ **TokenSafe Turn Savings**: +<tokens> tokens saved on this turn (<breakdown>) | Cumulative Total: <total> tokens (≈$<usd> approx)`\n"
|
|
@@ -144,7 +144,8 @@ class AgentInstaller:
|
|
|
144
144
|
@classmethod
|
|
145
145
|
def install_hooks_config(cls, agent_key: str) -> Tuple[bool, str]:
|
|
146
146
|
"""Registers TokenSafe lifecycle-hook adapters with agents that support them.
|
|
147
|
-
Claude Code:
|
|
147
|
+
Claude Code: SessionStart (one-shot directives) + UserPromptSubmit (TOCP
|
|
148
|
+
injection) + PreToolUse (shell guard).
|
|
148
149
|
Cursor: beforeShellExecution / beforeReadFile guards.
|
|
149
150
|
Codex has no lifecycle hooks (MCP + AGENTS.md remain the integration)."""
|
|
150
151
|
if agent_key == "codex":
|
|
@@ -173,11 +174,14 @@ class AgentInstaller:
|
|
|
173
174
|
return True, "TokenSafe Claude Code hooks already registered"
|
|
174
175
|
prompt_entry = {"hooks": [{"type": "command", "command": claude_cmd, "timeout": 10}]}
|
|
175
176
|
bash_entry = {"matcher": "Bash", "hooks": [{"type": "command", "command": claude_cmd, "timeout": 10}]}
|
|
177
|
+
# SessionStart: no matcher = all sources (startup/resume/clear/compact).
|
|
178
|
+
session_entry = {"hooks": [{"type": "command", "command": claude_cmd, "timeout": 10}]}
|
|
179
|
+
hooks.setdefault("SessionStart", []).append(session_entry)
|
|
176
180
|
hooks.setdefault("UserPromptSubmit", []).append(prompt_entry)
|
|
177
181
|
hooks.setdefault("PreToolUse", []).append(bash_entry)
|
|
178
182
|
data["hooks"] = hooks
|
|
179
183
|
cls._write_file_safely(config_file, json.dumps(data, indent=2))
|
|
180
|
-
return True, "hooks registered (UserPromptSubmit + PreToolUse guard)"
|
|
184
|
+
return True, "hooks registered (SessionStart + UserPromptSubmit + PreToolUse guard)"
|
|
181
185
|
|
|
182
186
|
# cursor
|
|
183
187
|
config_file = os.path.join(HOME, ".cursor", "hooks.json")
|
|
@@ -209,12 +213,31 @@ class AgentInstaller:
|
|
|
209
213
|
return False, f"Unknown agent: {agent_key}"
|
|
210
214
|
|
|
211
215
|
if info["type"] == "plugin":
|
|
212
|
-
# Symlink plugin
|
|
216
|
+
# Symlink the plugin under its canonical name only. Antigravity keys
|
|
217
|
+
# plugin enable-state by directory name (plugins.md), so a second
|
|
218
|
+
# legacy-named symlink registers the plugin twice and runs every
|
|
219
|
+
# hook twice per turn. Remove only stale legacy SYMLINKS — a real
|
|
220
|
+
# directory there is user data and must not be touched.
|
|
213
221
|
target = info["target_path"]
|
|
214
222
|
cls._symlink_dir(PROJECT_ROOT, target)
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
223
|
+
legacy = info.get("legacy_path")
|
|
224
|
+
if legacy:
|
|
225
|
+
try:
|
|
226
|
+
if os.path.islink(legacy):
|
|
227
|
+
os.unlink(legacy)
|
|
228
|
+
except Exception:
|
|
229
|
+
pass
|
|
230
|
+
# Once the plugin declares its own mcp_config.json (loaded by
|
|
231
|
+
# Antigravity together with the plugin), a leftover user-level
|
|
232
|
+
# tokensafe entry would register the MCP server twice. Migrate it
|
|
233
|
+
# away — Unix only, the plugin-root sh shim is not cmd-compatible.
|
|
234
|
+
migrated = False
|
|
235
|
+
if os.name != "nt" and os.path.isfile(os.path.join(PROJECT_ROOT, "mcp_config.json")):
|
|
236
|
+
migrated = cls._remove_user_level_tokensafe_mcp()
|
|
237
|
+
msg = f"Symlinked plugin into {target}"
|
|
238
|
+
if migrated:
|
|
239
|
+
msg += "; migrated user-level MCP entry to the plugin-declared server"
|
|
240
|
+
return True, msg
|
|
218
241
|
|
|
219
242
|
elif info["type"] == "cursor_env":
|
|
220
243
|
config_file = info["config_path"]
|
|
@@ -428,6 +451,33 @@ class AgentInstaller:
|
|
|
428
451
|
|
|
429
452
|
return False, "Unsupported type"
|
|
430
453
|
|
|
454
|
+
@staticmethod
|
|
455
|
+
def _remove_user_level_tokensafe_mcp() -> bool:
|
|
456
|
+
"""Removes the tokensafe MCP entry from Antigravity's user-level
|
|
457
|
+
mcp_config.json files (backup first). Returns True if any entry was
|
|
458
|
+
removed. Entries under disabledMcpServers are left alone: the user
|
|
459
|
+
explicitly disabled the server there."""
|
|
460
|
+
removed = False
|
|
461
|
+
for config_path in (
|
|
462
|
+
os.path.join(HOME, ".gemini", "config", "mcp_config.json"),
|
|
463
|
+
os.path.join(HOME, ".gemini", "antigravity", "mcp_config.json"),
|
|
464
|
+
):
|
|
465
|
+
if not os.path.isfile(config_path):
|
|
466
|
+
continue
|
|
467
|
+
try:
|
|
468
|
+
with open(config_path, "r", encoding="utf-8") as f:
|
|
469
|
+
data = json.load(f)
|
|
470
|
+
servers = data.get("mcpServers")
|
|
471
|
+
if isinstance(servers, dict) and "tokensafe" in servers:
|
|
472
|
+
shutil.copy2(config_path, f"{config_path}.backup")
|
|
473
|
+
servers.pop("tokensafe")
|
|
474
|
+
with open(config_path, "w", encoding="utf-8") as f:
|
|
475
|
+
json.dump(data, f, indent=2)
|
|
476
|
+
removed = True
|
|
477
|
+
except Exception:
|
|
478
|
+
continue
|
|
479
|
+
return removed
|
|
480
|
+
|
|
431
481
|
@classmethod
|
|
432
482
|
def _symlink_dir(cls, source_path: str, target_path: str):
|
|
433
483
|
"""Safely creates or replaces a symlink to a directory."""
|
|
@@ -483,8 +533,17 @@ class AgentInstaller:
|
|
|
483
533
|
cls._symlink_dir(skill_src, target_path)
|
|
484
534
|
|
|
485
535
|
@classmethod
|
|
486
|
-
def install_project(
|
|
487
|
-
|
|
536
|
+
def install_project(
|
|
537
|
+
cls,
|
|
538
|
+
project_dir: Optional[str] = None,
|
|
539
|
+
agents_plugin_path: Optional[str] = None,
|
|
540
|
+
) -> Dict[str, Any]:
|
|
541
|
+
"""Injects TokenSafe rules and MCP configs directly into a target project workspace.
|
|
542
|
+
|
|
543
|
+
agents_plugin_path (opt-in): declares the tokensafe plugin directory in
|
|
544
|
+
the project's .agents/plugins.json (json_configs.md) so teammates on
|
|
545
|
+
Antigravity load the plugin from the shared repo without running the
|
|
546
|
+
installer themselves."""
|
|
488
547
|
if not project_dir:
|
|
489
548
|
project_dir = os.getcwd()
|
|
490
549
|
project_dir = os.path.abspath(project_dir)
|
|
@@ -541,12 +600,44 @@ class AgentInstaller:
|
|
|
541
600
|
except Exception:
|
|
542
601
|
pass
|
|
543
602
|
|
|
603
|
+
if agents_plugin_path:
|
|
604
|
+
cls._write_agents_plugins_config(project_dir, agents_plugin_path)
|
|
605
|
+
created.append(".agents/plugins.json")
|
|
606
|
+
|
|
544
607
|
return {
|
|
545
608
|
"success": True,
|
|
546
609
|
"project_dir": project_dir,
|
|
547
610
|
"created_rules": created
|
|
548
611
|
}
|
|
549
612
|
|
|
613
|
+
@classmethod
|
|
614
|
+
def _write_agents_plugins_config(cls, project_dir: str, plugin_path: str) -> None:
|
|
615
|
+
"""Writes/merges .agents/plugins.json declaring the tokensafe plugin
|
|
616
|
+
directory. Stored relative to the project root when the plugin lives
|
|
617
|
+
inside it (team-shareable), otherwise as an absolute path."""
|
|
618
|
+
config_path = os.path.join(project_dir, ".agents", "plugins.json")
|
|
619
|
+
config: Dict[str, Any] = {}
|
|
620
|
+
if os.path.isfile(config_path):
|
|
621
|
+
try:
|
|
622
|
+
with open(config_path, "r", encoding="utf-8") as f:
|
|
623
|
+
config = json.load(f)
|
|
624
|
+
except Exception:
|
|
625
|
+
config = {}
|
|
626
|
+
|
|
627
|
+
abs_path = os.path.abspath(plugin_path if os.path.isabs(plugin_path) else os.path.join(os.getcwd(), plugin_path))
|
|
628
|
+
if abs_path == project_dir or abs_path.startswith(project_dir + os.sep):
|
|
629
|
+
stored = os.path.relpath(abs_path, project_dir).replace(os.sep, "/")
|
|
630
|
+
else:
|
|
631
|
+
stored = abs_path
|
|
632
|
+
|
|
633
|
+
entries = config.get("entries")
|
|
634
|
+
if not isinstance(entries, list):
|
|
635
|
+
entries = []
|
|
636
|
+
if not any(isinstance(e, dict) and e.get("path") == stored for e in entries):
|
|
637
|
+
entries.append({"path": stored})
|
|
638
|
+
config["entries"] = entries
|
|
639
|
+
cls._write_file_safely(config_path, json.dumps(config, indent=2))
|
|
640
|
+
|
|
550
641
|
@classmethod
|
|
551
642
|
def install_all(cls, force: bool = False) -> Dict[str, Any]:
|
|
552
643
|
"""Automatically installs TokenSafe to all detected (or all registered) AI agents."""
|
|
@@ -657,7 +748,11 @@ class AgentInstaller:
|
|
|
657
748
|
so auto-reconnecting IDEs (Antigravity, Cursor, Claude Code) spawn the updated version.
|
|
658
749
|
"""
|
|
659
750
|
try:
|
|
660
|
-
|
|
751
|
+
# Data-dir resolution is context-independent (canonical
|
|
752
|
+
# ~/.tokensafe/data unless TOKENSAFE_DATA_DIR overrides), so one
|
|
753
|
+
# marker location covers every launch context.
|
|
754
|
+
from src.paths import resolve_data_dir
|
|
755
|
+
data_dir = resolve_data_dir()
|
|
661
756
|
os.makedirs(data_dir, exist_ok=True)
|
|
662
757
|
reload_marker = os.path.join(data_dir, ".mcp_reload")
|
|
663
758
|
with open(reload_marker, "w", encoding="utf-8") as f:
|
|
@@ -829,8 +924,8 @@ class AgentInstaller:
|
|
|
829
924
|
|
|
830
925
|
# 5. Refresh local version cache
|
|
831
926
|
try:
|
|
832
|
-
|
|
833
|
-
cache_file = os.path.join(
|
|
927
|
+
from src.paths import resolve_data_dir
|
|
928
|
+
cache_file = os.path.join(resolve_data_dir(), "version_cache.json")
|
|
834
929
|
if os.path.exists(cache_file):
|
|
835
930
|
os.remove(cache_file)
|
|
836
931
|
except Exception:
|
package/src/license_manager.py
CHANGED
|
@@ -14,8 +14,10 @@ import base64
|
|
|
14
14
|
import threading
|
|
15
15
|
from typing import Dict, Any, Tuple, Optional
|
|
16
16
|
|
|
17
|
+
from src.paths import resolve_data_dir
|
|
18
|
+
|
|
17
19
|
PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
18
|
-
DATA_DIR =
|
|
20
|
+
DATA_DIR = resolve_data_dir()
|
|
19
21
|
LICENSE_FILE = os.path.join(DATA_DIR, "license.json")
|
|
20
22
|
GLOBAL_DATA_DIR = os.path.expanduser("~/.tokensafe")
|
|
21
23
|
GLOBAL_LICENSE_FILE = os.path.join(GLOBAL_DATA_DIR, "license.json")
|
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.
|
|
42
|
+
"version": "2.3.0"
|
|
43
43
|
}
|
|
44
44
|
|
|
45
45
|
# MCP client attribution: the initialize handshake carries clientInfo, which
|
|
@@ -131,11 +131,14 @@ TOOLS = [
|
|
|
131
131
|
"description": "Per-stage shell command rewrites: prunes lockfiles, caps unbounded git log/show/blame/rg "
|
|
132
132
|
"and docker/kubectl logs, quiets npm/pip installs, bounds cat/curl output. Compound commands "
|
|
133
133
|
"(a && b ; c) are optimized per stage without breaking operators. For unit-test runs prefer "
|
|
134
|
-
"the `tests` CLI wrapper (tokensafe tests [pytest]) over raw `python3 -m unittest discover`."
|
|
134
|
+
"the `tests` CLI wrapper (tokensafe tests [pytest]) over raw `python3 -m unittest discover`. "
|
|
135
|
+
"Pass cwd for test-runner commands: the guard reads <cwd>/package.json to force jest/vitest "
|
|
136
|
+
"into run-once mode (CI=true, --watch=false, --forceExit) so agents never hang on watch mode.",
|
|
135
137
|
"inputSchema": {
|
|
136
138
|
"type": "object",
|
|
137
139
|
"properties": {
|
|
138
|
-
"command": {"type": "string", "description": "Raw bash command line"}
|
|
140
|
+
"command": {"type": "string", "description": "Raw bash command line"},
|
|
141
|
+
"cwd": {"type": "string", "description": "Optional working directory the command will run in; enables the package.json peek that identifies the runner behind opaque yarn/npm test scripts"}
|
|
139
142
|
},
|
|
140
143
|
"required": ["command"]
|
|
141
144
|
}
|
|
@@ -241,7 +244,7 @@ def build_dir_tree(dir_path: str, max_depth: int = 2, max_entries: int = 80) ->
|
|
|
241
244
|
"""
|
|
242
245
|
IGNORE_DIRS = {
|
|
243
246
|
'node_modules', '.git', 'dist', 'build', '.next', 'coverage',
|
|
244
|
-
'__pycache__', '.turbo', '.vite', '.output', '
|
|
247
|
+
'__pycache__', '.turbo', '.vite', '.output', 'data',
|
|
245
248
|
'.venv', 'venv', '.cache', '.idea', '.vscode',
|
|
246
249
|
'Library', 'Applications', 'Movies', 'Music', 'Pictures'
|
|
247
250
|
}
|
|
@@ -668,8 +671,9 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
|
|
|
668
671
|
}
|
|
669
672
|
return {"content": [{"type": "text", "text": json.dumps(result, indent=2)}]}
|
|
670
673
|
|
|
671
|
-
# Step 2: Command sanitization
|
|
672
|
-
|
|
674
|
+
# Step 2: Command sanitization (cwd unlocks the package.json peek for
|
|
675
|
+
# opaque yarn/npm test scripts; None keeps the conservative fallback)
|
|
676
|
+
new_cmd, saved, reason = CommandSanitizer.sanitize(cmd, cwd=args.get("cwd") or None)
|
|
673
677
|
result = {
|
|
674
678
|
"original_command": cmd,
|
|
675
679
|
"sanitized_command": new_cmd or cmd,
|
|
@@ -971,10 +975,15 @@ def _execute_with_timeout(tool_name: str, tool_args: dict, timeout: float = MCP_
|
|
|
971
975
|
|
|
972
976
|
def _get_watched_mtimes() -> Tuple[Optional[float], ...]:
|
|
973
977
|
"""Returns mtimes for core server/package files and the update reload marker."""
|
|
978
|
+
try:
|
|
979
|
+
from src.paths import resolve_data_dir
|
|
980
|
+
reload_markers = [os.path.join(resolve_data_dir(), ".mcp_reload")]
|
|
981
|
+
except Exception:
|
|
982
|
+
reload_markers = [os.path.join(BASE_DIR, "data", ".mcp_reload")]
|
|
974
983
|
watched_paths = (
|
|
975
984
|
os.path.abspath(__file__),
|
|
976
985
|
os.path.join(BASE_DIR, "package.json"),
|
|
977
|
-
|
|
986
|
+
*reload_markers,
|
|
978
987
|
)
|
|
979
988
|
mtimes: List[Optional[float]] = []
|
|
980
989
|
for p in watched_paths:
|
package/src/metrics.py
CHANGED
|
@@ -13,6 +13,8 @@ from contextlib import contextmanager
|
|
|
13
13
|
from datetime import datetime, timedelta
|
|
14
14
|
from typing import Dict, List, Optional, Any, Generator
|
|
15
15
|
|
|
16
|
+
from src.paths import resolve_data_dir
|
|
17
|
+
|
|
16
18
|
USD_PER_TOKEN = 1.50 / 1_000_000.0
|
|
17
19
|
|
|
18
20
|
# Event types whose `original_tokens` baseline is a counterfactual estimate rather
|
|
@@ -62,10 +64,7 @@ class MetricsTracker:
|
|
|
62
64
|
|
|
63
65
|
def __init__(self, db_path: Optional[str] = None):
|
|
64
66
|
if db_path is None:
|
|
65
|
-
data_dir =
|
|
66
|
-
if not data_dir:
|
|
67
|
-
base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
68
|
-
data_dir = os.path.join(base_dir, "data")
|
|
67
|
+
data_dir = resolve_data_dir()
|
|
69
68
|
os.makedirs(data_dir, exist_ok=True)
|
|
70
69
|
db_path = os.environ.get("TOKENSAFE_DB_PATH", os.path.join(data_dir, "metrics.db"))
|
|
71
70
|
|
package/src/paths.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
"""Central data-directory resolution for TokenSafe.
|
|
2
|
+
|
|
3
|
+
Priority order:
|
|
4
|
+
1. ``TOKENSAFE_DATA_DIR`` — explicit override (tests, Docker ``/app/data``).
|
|
5
|
+
Honored verbatim, no migration: the caller controls the environment.
|
|
6
|
+
2. ``~/.tokensafe/data`` — the canonical, user-level directory shared by ALL
|
|
7
|
+
agents (Antigravity, Claude Code, Cursor, Codex, ...). Metrics, caches and
|
|
8
|
+
telemetry state live in one SQLite/JSON set regardless of how TokenSafe was
|
|
9
|
+
installed (git clone, npm, pip) or which agent runs the hook.
|
|
10
|
+
|
|
11
|
+
Migration (only when resolving the canonical dir): well-known state files are
|
|
12
|
+
carried over copy-if-absent from the legacy ``<repo>/data`` directory first
|
|
13
|
+
(the historical authoritative location), then from ``PLUGIN_DATA`` (the
|
|
14
|
+
per-plugin dir Antigravity exposes, which earlier builds migrated into).
|
|
15
|
+
``PLUGIN_DATA`` is a migration source only — it never wins resolution, so the
|
|
16
|
+
active directory is identical for every agent on the machine.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
import os
|
|
20
|
+
import shutil
|
|
21
|
+
|
|
22
|
+
PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
23
|
+
|
|
24
|
+
# Well-known state files carried over into the canonical directory.
|
|
25
|
+
_MIGRATION_FILES = (
|
|
26
|
+
"metrics.db",
|
|
27
|
+
"version_cache.json",
|
|
28
|
+
"sync_state.json",
|
|
29
|
+
"license.json",
|
|
30
|
+
"config.json",
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def user_data_dir() -> str:
|
|
35
|
+
"""The canonical per-user data directory shared across all agents."""
|
|
36
|
+
return os.path.join(os.path.expanduser("~"), ".tokensafe", "data")
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def legacy_data_dir() -> str:
|
|
40
|
+
"""The historical data directory inside the plugin repo (migration source)."""
|
|
41
|
+
return os.path.join(PROJECT_ROOT, "data")
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def plugin_data_dir() -> str:
|
|
45
|
+
"""Antigravity's per-plugin persistent directory (migration source)."""
|
|
46
|
+
return os.environ.get("PLUGIN_DATA") or ""
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def resolve_data_dir() -> str:
|
|
50
|
+
"""Returns the active data directory according to the priority order above."""
|
|
51
|
+
explicit = os.environ.get("TOKENSAFE_DATA_DIR")
|
|
52
|
+
if explicit:
|
|
53
|
+
return explicit
|
|
54
|
+
canonical = user_data_dir()
|
|
55
|
+
_migrate_into(canonical)
|
|
56
|
+
return canonical
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _migrate_into(target: str) -> None:
|
|
60
|
+
"""One-time copy-if-absent carry-over from legacy and plugin directories.
|
|
61
|
+
|
|
62
|
+
Copy-if-absent (never overwrite) keeps the target authoritative: source
|
|
63
|
+
dirs then hold stale files, and re-copying them would roll state back.
|
|
64
|
+
The tmp+os.replace dance keeps concurrent hook processes from observing a
|
|
65
|
+
half-written file. Legacy <repo>/data is migrated first (historically
|
|
66
|
+
authoritative); PLUGIN_DATA fills only the files it still lacks."""
|
|
67
|
+
sources = [legacy_data_dir()]
|
|
68
|
+
if plugin_data_dir():
|
|
69
|
+
sources.append(plugin_data_dir())
|
|
70
|
+
sources = [s for s in sources if os.path.isdir(s)]
|
|
71
|
+
if not sources:
|
|
72
|
+
return
|
|
73
|
+
try:
|
|
74
|
+
os.makedirs(target, exist_ok=True)
|
|
75
|
+
for source in sources:
|
|
76
|
+
if os.path.abspath(source) == os.path.abspath(target):
|
|
77
|
+
continue
|
|
78
|
+
for name in _MIGRATION_FILES:
|
|
79
|
+
src_file = os.path.join(source, name)
|
|
80
|
+
dst_file = os.path.join(target, name)
|
|
81
|
+
if os.path.isfile(src_file) and not os.path.exists(dst_file):
|
|
82
|
+
tmp_file = dst_file + ".migrating"
|
|
83
|
+
shutil.copy2(src_file, tmp_file)
|
|
84
|
+
os.replace(tmp_file, dst_file)
|
|
85
|
+
except Exception:
|
|
86
|
+
pass
|