tokensafe 2.2.1 → 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 +38 -5
- package/hooks/claude_code_hook.py +13 -1
- package/hooks/pre_invocation.py +39 -59
- package/hooks/pre_tool_use.py +25 -10
- 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 +2 -1
- package/plugin.json +2 -2
- package/server.json +23 -3
- 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 +15 -6
- 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 +191 -23
- package/src/history_compactor.py +5 -3
- package/src/installer.py +107 -12
- package/src/license_manager.py +3 -1
- package/src/loop_detector.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/skeletonizer.py +2 -1
- package/src/slicer.py +5 -3
- 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
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/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
|
@@ -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.4.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
|
package/src/proxy.py
CHANGED
|
@@ -26,6 +26,7 @@ from src.secret_redactor import SecretRedactor
|
|
|
26
26
|
from src.graph_engine import GraphEngine
|
|
27
27
|
from src.cache_normalizer import PromptCacheNormalizer
|
|
28
28
|
from src.governor import ContextGovernor
|
|
29
|
+
from src.paths import resolve_data_dir
|
|
29
30
|
|
|
30
31
|
DEFAULT_PORT = 8765
|
|
31
32
|
DEFAULT_HOST = os.environ.get("HOST", os.environ.get("TOKENSAFE_HOST", "0.0.0.0"))
|
|
@@ -164,10 +165,7 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
|
|
|
164
165
|
when the proxy is in the loop it REPLACES the last user message with the
|
|
165
166
|
TOCP form, so hook-side injection would double-count the same prompt."""
|
|
166
167
|
try:
|
|
167
|
-
marker = os.path.join(
|
|
168
|
-
os.environ.get("TOKENSAFE_DATA_DIR", os.path.join(BASE_DIR, "data")),
|
|
169
|
-
".proxy_active",
|
|
170
|
-
)
|
|
168
|
+
marker = os.path.join(resolve_data_dir(), ".proxy_active")
|
|
171
169
|
with open(marker, "w", encoding="utf-8") as f:
|
|
172
170
|
f.write(str(int(__import__("time").time())))
|
|
173
171
|
except Exception:
|
|
@@ -253,7 +251,7 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
|
|
|
253
251
|
custom_url = os.environ.get("TOKENSAFE_UPSTREAM_URL", "")
|
|
254
252
|
|
|
255
253
|
# Supported keys from environment or config
|
|
256
|
-
data_dir =
|
|
254
|
+
data_dir = resolve_data_dir()
|
|
257
255
|
conf_keys = {}
|
|
258
256
|
config_path = os.path.join(data_dir, "config.json")
|
|
259
257
|
if os.path.exists(config_path):
|
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/team_cache.py
CHANGED
|
@@ -28,8 +28,9 @@ class TeamCache:
|
|
|
28
28
|
"""Checks if current active license belongs to a Team tier subscription."""
|
|
29
29
|
key = os.environ.get("TOKENSAFE_LICENSE_KEY", "").strip()
|
|
30
30
|
if not key:
|
|
31
|
+
from src.paths import resolve_data_dir
|
|
31
32
|
candidate_paths = [
|
|
32
|
-
os.path.join(
|
|
33
|
+
os.path.join(resolve_data_dir(), "license.json"),
|
|
33
34
|
os.path.join(os.getcwd(), "data", "license.json"),
|
|
34
35
|
os.path.expanduser("~/.tokensafe/license.json")
|
|
35
36
|
]
|
package/src/telemetry_sync.py
CHANGED
|
@@ -31,7 +31,9 @@ if PROJECT_ROOT not in sys.path:
|
|
|
31
31
|
from src.license_manager import LicenseManager
|
|
32
32
|
from src.metrics import resolve_measurement
|
|
33
33
|
|
|
34
|
-
|
|
34
|
+
from src.paths import resolve_data_dir
|
|
35
|
+
|
|
36
|
+
DATA_DIR = resolve_data_dir()
|
|
35
37
|
METRICS_DB_PATH = os.path.join(DATA_DIR, "metrics.db")
|
|
36
38
|
SYNC_STATE_PATH = os.path.join(DATA_DIR, "sync_state.json")
|
|
37
39
|
SYNC_LOCK_PATH = os.path.join(DATA_DIR, ".sync.lock")
|
|
@@ -264,7 +266,7 @@ class TelemetrySync:
|
|
|
264
266
|
rollup_synced = bool(state.get("lifetime_rollup_synced", False))
|
|
265
267
|
headers = {
|
|
266
268
|
"Content-Type": "application/json",
|
|
267
|
-
"User-Agent": "TokenSafe-Sync/2.
|
|
269
|
+
"User-Agent": "TokenSafe-Sync/2.4.0"
|
|
268
270
|
}
|
|
269
271
|
if active_key:
|
|
270
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
|
|
@@ -24,8 +24,10 @@ CACHE_TTL = 86400 # 24 hours
|
|
|
24
24
|
# "broken" while the backend was redeploying).
|
|
25
25
|
FALLBACK_CACHE_TTL = 900 # 15 minutes
|
|
26
26
|
|
|
27
|
+
from src.paths import resolve_data_dir
|
|
28
|
+
|
|
27
29
|
PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
28
|
-
DATA_DIR =
|
|
30
|
+
DATA_DIR = resolve_data_dir()
|
|
29
31
|
CACHE_FILE = os.path.join(DATA_DIR, "version_cache.json")
|
|
30
32
|
CLOUD_CHECK_URL = os.environ.get("TOKENSAFE_VERSION_URL", "https://api.tokensafe.dev/api/version/check")
|
|
31
33
|
|
package/src/weekly_digest.py
CHANGED
|
@@ -17,20 +17,22 @@ import sqlite3
|
|
|
17
17
|
from contextlib import contextmanager
|
|
18
18
|
from typing import Dict, List, Any, Optional, Tuple
|
|
19
19
|
|
|
20
|
+
from src.paths import resolve_data_dir
|
|
21
|
+
|
|
20
22
|
PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
21
|
-
DATA_DIR =
|
|
23
|
+
DATA_DIR = resolve_data_dir()
|
|
22
24
|
CLOUD_DB_PATH = os.environ.get("TOKENSAFE_CLOUD_DB_PATH", os.path.join(DATA_DIR, "cloud.db"))
|
|
23
25
|
|
|
24
26
|
|
|
25
27
|
@contextmanager
|
|
26
28
|
def _open_digest_db(db_path: str):
|
|
27
|
-
"""Yields
|
|
29
|
+
"""Yields Cloud DB/cloud connection for default DB path, or local sqlite3 for custom paths."""
|
|
28
30
|
if db_path == CLOUD_DB_PATH:
|
|
29
31
|
try:
|
|
30
32
|
from src.cloud.db import get_db_connection
|
|
31
|
-
from src.cloud.config import
|
|
33
|
+
from src.cloud.config import CLOUD_DB_URL, CLOUD_DB_TOKEN, CLOUD_DB_PATH as CLOUD_CFG_DB_PATH
|
|
32
34
|
|
|
33
|
-
if (
|
|
35
|
+
if (CLOUD_DB_URL and CLOUD_DB_TOKEN) or os.path.exists(CLOUD_CFG_DB_PATH):
|
|
34
36
|
with get_db_connection() as conn:
|
|
35
37
|
yield conn
|
|
36
38
|
return
|
|
@@ -71,7 +73,7 @@ class WeeklyDigestGenerator:
|
|
|
71
73
|
) -> Optional[Dict[str, Any]]:
|
|
72
74
|
"""
|
|
73
75
|
Retrieves 7-day telemetry for team owned by owner_email.
|
|
74
|
-
Supports both
|
|
76
|
+
Supports both Cloud DB (cloud) and local SQLite databases.
|
|
75
77
|
Returns aggregated digest data or None if no eligible records found.
|
|
76
78
|
"""
|
|
77
79
|
clean_email = (owner_email or "").strip().lower()
|