tokensafe 1.3.4 → 1.3.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/tokensafe.js CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  /**
4
4
  * TokenSafe - Universal Node.js CLI & MCP Launcher
5
- * Works with `npx tokensafe [mcp|proxy|stats|benchmark|install]`
5
+ * Works with `npx tokensafe [command]` or global `tokensafe [command]`
6
6
  */
7
7
 
8
8
  const { spawn, spawnSync } = require('child_process');
@@ -27,27 +27,35 @@ function findPython() {
27
27
  return null;
28
28
  }
29
29
 
30
- const command = args[0] || 'install';
30
+ const firstArg = args[0] || '';
31
31
 
32
- if (command === 'help' || command === '--help' || command === '-h') {
32
+ if (firstArg === 'help' || firstArg === '--help' || firstArg === '-h') {
33
33
  console.log(`
34
34
  ⚡ TokenSafe - Autonomous Zero-Loss Token Optimizer for AI Coding Agents
35
35
  Website: https://tokensafe.dev
36
36
 
37
37
  Usage:
38
- npx tokensafe [command]
38
+ tokensafe [command] [options]
39
39
 
40
40
  Commands:
41
- npx tokensafe Interactive setup for Cursor, Antigravity, Claude & Codex
42
- npx tokensafe mcp Start Universal MCP Server (for Claude Desktop / Cursor)
43
- npx tokensafe proxy [port] Start Transparent Local AI Proxy (default: 8765)
44
- npx tokensafe graph Analyze repository God Nodes & dependency topology
45
- npx tokensafe map Generate tokensafe-out/API_SURFACE.md interface snapshot
46
- npx tokensafe stats Show token economy savings & performance metrics
47
- npx tokensafe benchmark Run zero-loss verification benchmark suite
48
- npx tokensafe update One-click self-update for npm, pip & all AI agent rules
49
- npx tokensafe activate Activate commercial or team seat license key
50
- npx tokensafe --help Show this help screen
41
+ tokensafe stats Show token economy savings & performance metrics
42
+ tokensafe html Generate and open interactive browser dashboard
43
+ tokensafe test "<prompt>" Test prompt compression on custom input
44
+ tokensafe doctor Audit MCP servers & skills context token tax
45
+ tokensafe providers List active LLM distillation models & keys
46
+ tokensafe benchmark Run zero-loss verification benchmark suite
47
+ tokensafe mcp Manage MCP servers (list, disable <name>, enable <name>)
48
+ tokensafe proxy [port] Start Transparent Local AI Proxy (default: 8765)
49
+ tokensafe graph Analyze repository God Nodes & dependency topology
50
+ tokensafe map Generate tokensafe-out/API_SURFACE.md interface snapshot
51
+ tokensafe vacuum Compact SQLite metrics database storage
52
+ tokensafe prune Prune granular telemetry events into lifetime rollup
53
+ tokensafe digest Preview or send weekly team ROI digest email
54
+ tokensafe activate <key> Activate commercial Solo or Team seat license key
55
+ tokensafe license Show current license status and active tier
56
+ tokensafe update One-click self-update for npm, pip & all AI agent rules
57
+ tokensafe install Interactive installer for Cursor, Antigravity, Claude, etc.
58
+ tokensafe --help Show this help screen
51
59
  `);
52
60
  process.exit(0);
53
61
  }
@@ -61,66 +69,16 @@ if (!python) {
61
69
  process.exit(1);
62
70
  }
63
71
 
64
- let scriptPath = '';
65
- let scriptArgs = [];
66
-
67
- switch (command) {
68
- case 'mcp':
69
- scriptPath = path.join(ROOT_DIR, 'src', 'mcp_server.py');
70
- scriptArgs = args.slice(1);
71
- break;
72
-
73
- case 'proxy':
74
- scriptPath = path.join(ROOT_DIR, 'src', 'proxy.py');
75
- scriptArgs = args.slice(1);
76
- break;
77
-
78
- case 'graph':
79
- case 'map':
80
- case 'skeleton':
81
- scriptPath = path.join(ROOT_DIR, 'src', 'graph_engine.py');
82
- scriptArgs = args;
83
- break;
84
-
85
- case 'stats':
86
- case 'dashboard':
87
- scriptPath = path.join(ROOT_DIR, 'src', 'dashboard.py');
88
- scriptArgs = ['--cli', ...args.slice(1)];
89
- break;
90
-
91
- case 'benchmark':
92
- scriptPath = path.join(ROOT_DIR, 'src', 'benchmark.py');
93
- scriptArgs = args.slice(1);
94
- break;
95
-
96
- case 'activate':
97
- scriptPath = path.join(ROOT_DIR, 'src', 'license_manager.py');
98
- scriptArgs = args.slice(1);
99
- break;
100
-
101
- case 'update':
102
- case 'upgrade':
103
- scriptPath = path.join(ROOT_DIR, 'src', 'installer.py');
104
- scriptArgs = ['update', ...args.slice(1)];
105
- break;
106
-
107
- case 'install':
108
- case 'init':
109
- scriptPath = path.join(ROOT_DIR, 'src', 'installer.py');
110
- scriptArgs = args.slice(1);
111
- break;
112
-
113
- default:
114
- scriptPath = path.join(ROOT_DIR, 'src', 'installer.py');
115
- scriptArgs = args;
116
- break;
117
- }
118
-
72
+ const candidateTokensafe = path.join(ROOT_DIR, 'bin', 'tokensafe');
73
+ const candidateAgy = path.join(ROOT_DIR, 'bin', 'agy-tokens');
74
+ const scriptPath = fs.existsSync(candidateTokensafe) ? candidateTokensafe : candidateAgy;
119
75
  if (!fs.existsSync(scriptPath)) {
120
76
  console.error(`Error: TokenSafe script not found at ${scriptPath}`);
121
77
  process.exit(1);
122
78
  }
123
79
 
80
+ const scriptArgs = args.length === 0 ? ['install'] : args;
81
+
124
82
  const child = spawn(python, [scriptPath, ...scriptArgs], {
125
83
  stdio: 'inherit',
126
84
  cwd: process.cwd(),
@@ -12,7 +12,8 @@ function activate(context) {
12
12
  context.subscriptions.push(statusBarItem);
13
13
 
14
14
  const projectRoot = path.dirname(path.dirname(__dirname));
15
- const cliPath = path.join(projectRoot, "bin", "agy-tokens");
15
+ const candidateTokensafe = path.join(projectRoot, "bin", "tokensafe");
16
+ const cliPath = fs.existsSync(candidateTokensafe) ? candidateTokensafe : path.join(projectRoot, "bin", "agy-tokens");
16
17
  const dashboardHtml = path.join(projectRoot, "data", "dashboard.html");
17
18
 
18
19
  const disposableStats = vscode.commands.registerCommand('tokensafe.showStats', () => {
@@ -20,6 +20,7 @@ from src.compactor import PromptCompactor
20
20
  from src.history_compactor import HistoryCompactor
21
21
  from src.metrics import MetricsTracker
22
22
  from src.environment_auditor import EnvironmentAuditor
23
+ from src.license_manager import LicenseManager
23
24
 
24
25
  def main():
25
26
  try:
@@ -41,8 +42,18 @@ def main():
41
42
  tracker = MetricsTracker()
42
43
  inject_steps = []
43
44
 
44
- # 0. Context Bloat Audit (Fires on first invocation)
45
+ # 0. Quota and Environment Audits (Fires on first invocation)
46
+ quota = LicenseManager.check_quota(tracker)
45
47
  if invocation_num <= 1:
48
+ if quota.get("warning"):
49
+ inject_steps.append({
50
+ "systemMessage": {
51
+ "systemMessage": "",
52
+ "metadata": {
53
+ "user_markdown": quota["warning"]
54
+ }
55
+ }
56
+ })
46
57
  try:
47
58
  bloat_warning = EnvironmentAuditor.get_bloat_warning()
48
59
  if bloat_warning:
@@ -57,9 +68,10 @@ def main():
57
68
  except Exception:
58
69
  pass
59
70
 
60
- # 1. Prompt Compaction
71
+ # 1. Prompt Compaction (Tier 2 LLM Distillation paused if community quota exceeded)
61
72
  if last_user_input and len(last_user_input.strip()) >= 5:
62
- compaction = PromptCompactor.compact(last_user_input)
73
+ enable_distill = not quota.get("is_quota_exceeded", False)
74
+ compaction = PromptCompactor.compact(last_user_input, enable_deepseek=enable_distill)
63
75
  saved_tokens = compaction["saved_tokens"]
64
76
  reduction_pct = compaction["reduction_pct"]
65
77
 
@@ -79,10 +91,16 @@ def main():
79
91
  }
80
92
  )
81
93
 
82
- badge_markdown = (
83
- f"⚡ **Token Optimizer:** Compaction active ({tier}) — saved **{saved_tokens} tokens** "
84
- f"(-{reduction_pct}%) on this prompt."
85
- )
94
+ if quota.get("is_quota_exceeded"):
95
+ badge_markdown = (
96
+ f"⚡ **TokenSafe:** Saved **{saved_tokens} tokens** via local regex "
97
+ f"(Community 500k quota reached — [Upgrade to Solo](https://tokensafe.dev/#pricing) for unlimited deep distillation & history folding)."
98
+ )
99
+ else:
100
+ badge_markdown = (
101
+ f"⚡ **Token Optimizer:** Compaction active ({tier}) — saved **{saved_tokens} tokens** "
102
+ f"(-{reduction_pct}%) on this prompt."
103
+ )
86
104
 
87
105
  inject_steps.append({
88
106
  "systemMessage": {
@@ -93,8 +111,8 @@ def main():
93
111
  }
94
112
  })
95
113
 
96
- # 2. Multi-turn History Compaction
97
- if invocation_num >= 3 and transcript_path:
114
+ # 2. Multi-turn History Compaction (Paused when community quota is exceeded)
115
+ if not quota.get("is_quota_exceeded", False) and invocation_num >= 3 and transcript_path:
98
116
  folded_text, orig_hist_tokens, folded_tokens, stats = HistoryCompactor.fold_transcript(
99
117
  transcript_path, invocation_num
100
118
  )
@@ -24,6 +24,7 @@ from src.metrics import MetricsTracker
24
24
  from src.tokenizer import count_tokens
25
25
  from src.agent_firewall import AgentFirewall
26
26
  from src.diff_slicer import DiffSlicer
27
+ from src.license_manager import LicenseManager
27
28
 
28
29
  def main():
29
30
  try:
@@ -44,6 +45,8 @@ def main():
44
45
  last_user_input = payload.get("lastUserInput", "")
45
46
 
46
47
  tracker = MetricsTracker()
48
+ quota = LicenseManager.check_quota(tracker)
49
+ is_quota_exceeded = quota.get("is_quota_exceeded", False)
47
50
 
48
51
  # 1. Loop Detector Guard (Applies to all tools)
49
52
  is_loop, repeat_count, loop_msg = LoopDetector.check_loop(conversation_id, tool_name, args)
@@ -107,6 +110,11 @@ def main():
107
110
  start_line = args.get("StartLine")
108
111
  end_line = args.get("EndLine")
109
112
 
113
+ if is_quota_exceeded:
114
+ # Free tier quota reached: pass through raw read_file without AST skeletonization
115
+ print(json.dumps(response))
116
+ return
117
+
110
118
  # Step 3A: Subagent Firewall — Check if file was already read in active session
111
119
  is_hit, cached_text, saved_dedup = AgentFirewall.check_cache(
112
120
  session_id=conversation_id,
@@ -193,6 +201,14 @@ def main():
193
201
  # 4. run_command Optimization (Command Sanitizer & Diff Slicer)
194
202
  elif tool_name == "run_command":
195
203
  cmd = args.get("CommandLine", "")
204
+ if is_quota_exceeded:
205
+ # Free tier quota reached: pass through without AST diff slicing or savings tracking
206
+ new_cmd, est_saved, reason = CommandSanitizer.sanitize(cmd)
207
+ if new_cmd and est_saved > 0:
208
+ response["overwrite"] = {"CommandLine": new_cmd}
209
+ print(json.dumps(response))
210
+ return
211
+
196
212
  # Check AST Diff Slicer first
197
213
  diff_cmd, diff_saved, diff_reason = DiffSlicer.optimize_git_diff_command(cmd)
198
214
  if diff_cmd:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tokensafe",
3
- "version": "1.3.4",
3
+ "version": "1.3.6",
4
4
  "description": "Autonomous Zero-Loss Token Economy & Context Optimizer for AI Coding Agents",
5
5
  "main": "bin/tokensafe.js",
6
6
  "bin": {
@@ -8,6 +8,7 @@
8
8
  },
9
9
  "files": [
10
10
  "bin/tokensafe.js",
11
+ "bin/tokensafe",
11
12
  "bin/agy-tokens",
12
13
  "src/*.py",
13
14
  "!src/cloud_backend.py",
package/plugin.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "agy-token-optimizer",
3
3
  "displayName": "TokenSafe",
4
- "version": "1.3.4",
4
+ "version": "1.3.6",
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": {
@@ -70,7 +70,7 @@ Before executing potentially verbose terminal commands (`git diff`, `git grep`,
70
70
 
71
71
  ## CLI Usage
72
72
 
73
- Developers and agents can run `tokensafe` (or `./bin/agy-tokens`) directly from the terminal:
73
+ Developers and agents can run `tokensafe` directly from the terminal:
74
74
 
75
75
  ```bash
76
76
  # View terminal breakdown & recent optimizations
package/src/benchmark.py CHANGED
@@ -29,7 +29,7 @@ BENCHMARK_TASKS = [
29
29
  {
30
30
  "id": "SWE-01",
31
31
  "name": "Race Condition / Distributed Lock (order_service.py)",
32
- "prompt": "Привет! В файле order_service.py функция checkout иногда зависает при повторной оплате картой, потому что нет транзакционной блокировки через mutex. Добавь туда распределенную блокировку через Redis redlock и сделай метод идемпотентным.",
32
+ "prompt": "Hello! In order_service.py the checkout function occasionally hangs during duplicate card payments because there is no transaction mutex lock. Please add a distributed lock using Redis redlock and make the method idempotent.",
33
33
  "file_lines": 350,
34
34
  "is_edit": True,
35
35
  "raw_tool_tokens": 2800,
@@ -40,7 +40,7 @@ BENCHMARK_TASKS = [
40
40
  {
41
41
  "id": "SWE-02",
42
42
  "name": "OAuth JWT Expiration Triage (auth.controller.ts)",
43
- "prompt": "Слушай, у меня в сервисе auth.controller.ts при логине через Google, если у юзера нет аватарки, промис зависает на 30 секунд и падает 504. Почини эту ерунду пожалуйста.",
43
+ "prompt": "In auth.controller.ts during Google login, if the user has no avatar the promise hangs for 30 seconds and fails with 504. Please fix this bug.",
44
44
  "file_lines": 280,
45
45
  "is_edit": True,
46
46
  "raw_tool_tokens": 2100,
package/src/cli.py ADDED
@@ -0,0 +1,342 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ TokenSafe Unified CLI Dispatcher.
4
+ Used by:
5
+ - npm CLI (`bin/tokensafe.js`)
6
+ - standalone executable (`bin/tokensafe`)
7
+ - PyPI console script entrypoint (`tokensafe` via `pyproject.toml`)
8
+ """
9
+
10
+ import sys
11
+ import os
12
+ import subprocess
13
+
14
+ SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
15
+ PROJECT_ROOT = os.path.dirname(SCRIPT_DIR)
16
+ if PROJECT_ROOT not in sys.path:
17
+ sys.path.insert(0, PROJECT_ROOT)
18
+
19
+ from src.metrics import MetricsTracker
20
+ from src.dashboard import Dashboard, render_bar
21
+ from src.compactor import PromptCompactor
22
+ from src.tokenizer import count_tokens
23
+
24
+ def main():
25
+ tracker = MetricsTracker()
26
+ dashboard = Dashboard(tracker)
27
+
28
+ args = sys.argv[1:]
29
+ command = args[0] if args else "stats"
30
+
31
+ if command in ("stats", "dashboard"):
32
+ print(dashboard.render_terminal())
33
+
34
+ elif command in ("html", "web"):
35
+ html_content = dashboard.render_html()
36
+ out_path = os.path.join(PROJECT_ROOT, "data", "dashboard.html")
37
+ os.makedirs(os.path.dirname(out_path), exist_ok=True)
38
+ with open(out_path, "w", encoding="utf-8") as f:
39
+ f.write(html_content)
40
+ print(f"\n⚡ Interactive HTML Dashboard generated at: {out_path}")
41
+ try:
42
+ subprocess.run(["open", out_path])
43
+ print(" Opened in default browser.")
44
+ except Exception:
45
+ pass
46
+
47
+ elif command in ("benchmark", "bench"):
48
+ from src.benchmark import BenchmarkSuite
49
+ print("\n⚡ Running Zero-Loss SWE-bench Benchmark Suite across real-world scenarios...")
50
+ data = BenchmarkSuite.run_all()
51
+ print(BenchmarkSuite.render_report(data))
52
+ out_md = os.path.join(PROJECT_ROOT, "data", "BENCHMARK_REPORT.md")
53
+ BenchmarkSuite.export_markdown_report(data, out_md)
54
+ print(f"📊 Publication-ready markdown report saved to: {out_md}\n")
55
+
56
+ elif command in ("setup", "install"):
57
+ from src.installer import AgentInstaller
58
+ if "--all" in args or "-a" in args or "-y" in args or "--auto" in args:
59
+ print("\n\033[1m\033[36m⚡ TOKENSAFE UNIVERSAL MULTI-AGENT INSTALLER (--all) ⚡\033[0m\n")
60
+ res = AgentInstaller.install_all(force=True)
61
+ print("Configured AI agent environments:")
62
+ for k, r in res["agents"].items():
63
+ status = "\033[32m✔\033[0m" if r["success"] else "\033[31m✖\033[0m"
64
+ print(f" {status} \033[1m{r['name']:<28}\033[0m: {r['message']}")
65
+ print(f"\n\033[32m✔ Universal project rules injected into: {', '.join(res['project_rules'])}\033[0m\n")
66
+ elif "--project" in args:
67
+ res = AgentInstaller.install_project(os.getcwd())
68
+ print(f"\n\033[32m✔ TokenSafe rules injected into project: {', '.join(res['created_rules'])}\033[0m\n")
69
+ else:
70
+ AgentInstaller.run_interactive()
71
+
72
+ elif command in ("update", "upgrade"):
73
+ from src.installer import AgentInstaller
74
+ AgentInstaller.self_update()
75
+
76
+ elif command == "proxy":
77
+ from src.proxy import run_proxy
78
+ port = int(args[1]) if len(args) > 1 else 8765
79
+ run_proxy(port)
80
+
81
+ elif command == "mcp":
82
+ subcmd = args[1] if len(args) > 1 else "serve"
83
+ if subcmd in ("disable", "off", "rm"):
84
+ if len(args) < 3:
85
+ print("Usage: tokensafe mcp disable <server_name>")
86
+ sys.exit(1)
87
+ target = args[2].strip()
88
+ from src.environment_auditor import EnvironmentAuditor
89
+ res = EnvironmentAuditor.disable_mcp(target)
90
+ if res["success"]:
91
+ print(f"\n\033[32m✔ MCP server '{target}' disabled successfully. Removed from active turn overhead.\033[0m\n")
92
+ else:
93
+ print(f"\n\033[31m✖ Server '{target}' not found or already disabled.\033[0m\n")
94
+ elif subcmd in ("enable", "on", "add"):
95
+ if len(args) < 3:
96
+ print("Usage: tokensafe mcp enable <server_name>")
97
+ sys.exit(1)
98
+ target = args[2].strip()
99
+ from src.environment_auditor import EnvironmentAuditor
100
+ res = EnvironmentAuditor.enable_mcp(target)
101
+ if res["success"]:
102
+ print(f"\n\033[32m✔ MCP server '{target}' re-enabled successfully.\033[0m\n")
103
+ else:
104
+ print(f"\n\033[31m✖ Server '{target}' not found in disabled servers.\033[0m\n")
105
+ elif subcmd in ("list", "ls", "status"):
106
+ from src.environment_auditor import EnvironmentAuditor
107
+ print(EnvironmentAuditor.format_cli_report())
108
+ else:
109
+ from src.mcp_server import run_mcp_server
110
+ run_mcp_server()
111
+
112
+ elif command in ("doctor", "audit", "tax"):
113
+ from src.environment_auditor import EnvironmentAuditor
114
+ print(EnvironmentAuditor.format_cli_report())
115
+
116
+ elif command in ("graph", "nodes"):
117
+ from src.graph_engine import GraphEngine
118
+ target_dir = args[1] if len(args) > 1 else os.getcwd()
119
+ graph = GraphEngine(target_dir)
120
+ graph.index_workspace()
121
+ print(f"\n🔍 TokenSafe Graph Engine — Knowledge Graph & Centrality Analysis")
122
+ print(f" Indexed: {len(graph.file_symbols)} code files, {len(graph.symbols)} symbols\n")
123
+ god_nodes = graph.get_god_nodes(top_n=7)
124
+ print("⚡ Architectural Hubs (God Nodes):")
125
+ for idx, g in enumerate(god_nodes, 1):
126
+ print(f" {idx}. {g['file']}")
127
+ print(f" Degree Centrality: {g['centrality']} | Dependents: {g['dependents']} | Dependencies: {g['dependencies']} | Symbols: {g['symbols_count']}")
128
+ print(f"\n💡 Tip: Run 'tokensafe map' to generate tokensafe-out/API_SURFACE.md\n")
129
+
130
+ elif command in ("map", "surface"):
131
+ from src.graph_engine import GraphEngine
132
+ target_dir = args[1] if len(args) > 1 else os.getcwd()
133
+ graph = GraphEngine(target_dir)
134
+ graph.index_workspace()
135
+ out_file = os.path.join(target_dir, "tokensafe-out", "API_SURFACE.md")
136
+ graph.generate_api_surface(out_file)
137
+ print(f"\n✓ Generated API Surface Map: {out_file} ({os.path.getsize(out_file):,} bytes)")
138
+ print(f" AI agents can read this file in ~1.5k tokens instead of reading the entire repo.\n")
139
+
140
+ elif command == "skeleton":
141
+ from src.graph_engine import GraphEngine
142
+ if len(args) < 2:
143
+ print("Usage: tokensafe skeleton <file_path> [target_symbol]")
144
+ sys.exit(1)
145
+ file_path = args[1]
146
+ target_symbol = args[2] if len(args) > 2 else None
147
+ target_dir = os.path.dirname(os.path.abspath(file_path)) or os.getcwd()
148
+ graph = GraphEngine(target_dir)
149
+ res = graph.graph_guided_skeletonize(file_path, target_symbol)
150
+ print(res)
151
+
152
+ elif command == "activate":
153
+ from src.license_manager import LicenseManager
154
+ if len(args) < 2:
155
+ print("Usage: tokensafe activate <LICENSE_KEY>")
156
+ sys.exit(1)
157
+ key = args[1].strip()
158
+ ok, msg = LicenseManager.save_license(key)
159
+ if ok:
160
+ print(f"\n\033[32m\033[1m✔ {msg}\033[0m\n")
161
+ else:
162
+ print(f"\n\033[31m\033[1m✖ {msg}\033[0m\n")
163
+ sys.exit(1)
164
+
165
+ elif command in ("license", "tier"):
166
+ from src.license_manager import LicenseManager
167
+ tier, payload = LicenseManager.get_active_license()
168
+ print("\n\033[1m\033[36m⚡ TOKENSAFE LICENSE STATUS ⚡\033[0m\n")
169
+ print(f" Tier: \033[32m\033[1m{tier.upper()}\033[0m")
170
+ if tier != "free":
171
+ print(f" Email: {payload.get('email', 'N/A')}")
172
+ if payload.get("trial"):
173
+ print(f" Mode: \033[33m7-Day Free Trial\033[0m")
174
+ exp = payload.get("expires_at", 0)
175
+ if exp > 0:
176
+ import datetime
177
+ dt = datetime.datetime.fromtimestamp(exp).strftime('%Y-%m-%d %H:%M:%S')
178
+ print(f" Expires: {dt}")
179
+ else:
180
+ print(f" Expires: Never (Lifetime)")
181
+ else:
182
+ print(" Status: Free Tier (up to 500,000 tokens/mo)")
183
+ print(" Upgrade: https://tokensafe.dev ($9/mo Solo with 7-Day Free Trial)\n")
184
+ print()
185
+
186
+ elif command in ("providers", "models", "keys"):
187
+ from src.license_manager import LicenseManager
188
+ from src.distiller import UniversalDistiller
189
+ tier, _ = LicenseManager.get_active_license()
190
+ print("\n\033[1m\033[36m⚡ TOKENSAFE LLM DISTILLATION PROVIDERS ⚡\033[0m\n")
191
+ if tier == "free":
192
+ print(" \033[33mTier: Free Community Edition\033[0m")
193
+ print(" Neural Semantic Distillation (Gemini / OpenAI / DeepSeek) is reserved for Solo & Team tiers.")
194
+ print(" Free Community Edition operates with the zero-latency, zero-cost Local Regex Compactor.\n")
195
+ print(" \033[1mTo unlock Neural LLM Distillation:\033[0m")
196
+ print(" 1. Start 7-day free trial or upgrade at: \033[36mhttps://tokensafe.dev\033[0m")
197
+ print(" 2. Activate your key: \033[32mtokensafe activate <KEY>\033[0m\n")
198
+ else:
199
+ configured = UniversalDistiller.get_configured_providers()
200
+ all_p = UniversalDistiller.PROVIDERS
201
+ for key, p in all_p.items():
202
+ if key in configured:
203
+ c = configured[key]
204
+ print(f" \033[32m✔\033[0m \033[1m{p['name']:<18}\033[0m [Active: {c['model']}]")
205
+ else:
206
+ print(f" \033[2m○ {p['name']:<18} [Set {p['env_key']} to activate]\033[0m")
207
+ print("\nSet environment variable or add to data/config.json to activate.\n")
208
+
209
+ elif command in ("markdown", "md", "export"):
210
+ print(dashboard.render_markdown())
211
+
212
+ elif command == "test":
213
+ if len(args) < 2:
214
+ print("Usage: tokensafe test \"<prompt text>\"")
215
+ sys.exit(1)
216
+ raw_prompt = " ".join(args[1:])
217
+ res = PromptCompactor.compact(raw_prompt)
218
+
219
+ print("\n\033[1m\033[36m⚡ TOKEN COMPRESSION TEST ⚡\033[0m\n")
220
+ print(f"\033[1mOriginal Input:\033[0m {res['original_text']}")
221
+ print(f"\033[1mCompacted DSL:\033[0m \033[32m\033[1m{res['compact_text']}\033[0m\n")
222
+ print(f"\033[1mRouting Tier:\033[0m \033[33m{res.get('tier', 'REGEX')}\033[0m")
223
+ print(f"\033[1mExtracted Action:\033[0m {res['action']}")
224
+ print(f"\033[1mTarget File:\033[0m {res['target_file'] or 'None'}")
225
+ print(f"\033[1mScope Symbol:\033[0m {res['symbol'] or 'None'}")
226
+ print(f"\033[1mTraits / Tags:\033[0m {res['traits']}\n")
227
+ print(f"\033[1mOriginal Tokens:\033[0m {res['original_tokens']}")
228
+ print(f"\033[1mCompacted Tokens:\033[0m {res['compact_tokens']}")
229
+ print(f"\033[1mTokens Saved:\033[0m \033[32m\033[1m+{res['saved_tokens']} tokens\033[0m ({render_bar(res['reduction_pct'])})\n")
230
+
231
+ elif command in ("prune", "cleanup"):
232
+ days = None
233
+ max_events = None
234
+ i = 1
235
+ while i < len(args):
236
+ if args[i] == "--days" and i + 1 < len(args):
237
+ try:
238
+ days = int(args[i + 1])
239
+ except ValueError:
240
+ pass
241
+ i += 2
242
+ elif args[i] in ("--max", "--max-events") and i + 1 < len(args):
243
+ try:
244
+ max_events = int(args[i + 1])
245
+ except ValueError:
246
+ pass
247
+ i += 2
248
+ else:
249
+ i += 1
250
+
251
+ if days is None and max_events is None:
252
+ days = 30
253
+ max_events = 5000
254
+
255
+ print(f"\n\033[1m\033[36m⚡ DATA RETENTION PRUNE ⚡\033[0m")
256
+ print(f"Policy: retain events < {days or 'any'} days old, max {max_events or 'unlimited'} entries.")
257
+ res = tracker.prune(days=days, max_events=max_events, vacuum=True)
258
+ b_before = res.get("db_size_before", 0) / 1024.0
259
+ b_after = res.get("db_size_after", 0) / 1024.0
260
+ print(f"\033[32m✔ Pruned {res['pruned_events']} granular events into lifetime rollup table.\033[0m")
261
+ print(f" DB Size: {b_before:.1f} KB ➔ {b_after:.1f} KB\n")
262
+
263
+ elif command == "vacuum":
264
+ print("\n\033[1m\033[36m⚡ VACUUMING METRICS DATABASE ⚡\033[0m")
265
+ b_before = (os.path.getsize(tracker.db_path) if os.path.exists(tracker.db_path) else 0) / 1024.0
266
+ tracker.vacuum()
267
+ b_after = (os.path.getsize(tracker.db_path) if os.path.exists(tracker.db_path) else 0) / 1024.0
268
+ print(f"\033[32m✔ Database compacted. Size: {b_before:.1f} KB ➔ {b_after:.1f} KB\033[0m\n")
269
+
270
+ elif command in ("digest", "weekly-digest"):
271
+ from src.weekly_digest import WeeklyDigestGenerator
272
+ from src.mailer import TokenSafeMailer
273
+
274
+ target_email = None
275
+ do_send = "--send" in args
276
+
277
+ for a in args:
278
+ if a.startswith("--email="):
279
+ target_email = a.split("=", 1)[1].strip()
280
+
281
+ if not target_email:
282
+ from src.license_manager import LicenseManager
283
+ _, payload = LicenseManager.get_active_license()
284
+ target_email = payload.get("email") or "teamlead@example.com"
285
+
286
+ print(f"\n\033[1m\033[36m⚡ COMPILING FRIDAY TEAM ROI DIGEST ⚡\033[0m")
287
+ print(f"Target Teamlead: {target_email}")
288
+
289
+ stats = WeeklyDigestGenerator.get_team_weekly_stats(target_email)
290
+ if not stats:
291
+ stats = {
292
+ "owner_email": target_email,
293
+ "tier": "team",
294
+ "seats_total": 5,
295
+ "active_members_count": 4,
296
+ "total_members_count": 5,
297
+ "total_original_tokens": 5800000,
298
+ "total_saved_tokens": 4200000,
299
+ "total_saved_human": "4.2M",
300
+ "total_usd_saved": 28.50,
301
+ "total_events": 340,
302
+ "reduction_pct": 72.4,
303
+ "leaderboard": [
304
+ {"rank": 1, "email": "alex.dev@corp.com", "saved_tokens": 1650000, "saved_tokens_human": "1.7M", "usd_saved_formatted": "$11.20", "event_count": 120},
305
+ {"rank": 2, "email": "maria.arch@corp.com", "saved_tokens": 1200000, "saved_tokens_human": "1.2M", "usd_saved_formatted": "$8.10", "event_count": 94},
306
+ {"rank": 3, "email": "sergey.qa@corp.com", "saved_tokens": 850000, "saved_tokens_human": "850K", "usd_saved_formatted": "$5.70", "event_count": 68},
307
+ {"rank": 4, "email": target_email, "saved_tokens": 500000, "saved_tokens_human": "500K", "usd_saved_formatted": "$3.50", "event_count": 58}
308
+ ]
309
+ }
310
+
311
+ print(WeeklyDigestGenerator.render_email_text(stats))
312
+
313
+ out_html = os.path.join(PROJECT_ROOT, "data", "weekly_digest_preview.html")
314
+ os.makedirs(os.path.dirname(out_html), exist_ok=True)
315
+ with open(out_html, "w", encoding="utf-8") as f:
316
+ f.write(WeeklyDigestGenerator.render_email_html(stats))
317
+ print(f"\n📧 Apple-style email HTML preview generated at: {out_html}")
318
+
319
+ if do_send:
320
+ ok = TokenSafeMailer.send_weekly_digest(target_email, stats, sync=True)
321
+ if ok:
322
+ print(f"\033[32m✔ Weekly digest successfully dispatched to {target_email}!\033[0m\n")
323
+ else:
324
+ print(f"\033[33m○ Digest dispatch queued (SMTP_PASS not configured in local environment).\033[0m\n")
325
+ else:
326
+ print("Tip: Run with --send to dispatch email, or --email=<addr> to target specific team.\n")
327
+
328
+ elif command == "reset":
329
+ confirm = input("Are you sure you want to reset all token metrics? [y/N]: ").strip().lower()
330
+ if confirm == "y":
331
+ tracker.reset()
332
+ print("Metrics database reset successfully.")
333
+ else:
334
+ print("Reset cancelled.")
335
+
336
+ else:
337
+ print(f"Unknown command: {command}")
338
+ print("Available commands: stats, html, test, doctor, providers, mcp, benchmark, proxy, graph, map, vacuum, prune, digest, activate, license, markdown, setup, reset")
339
+ sys.exit(1)
340
+
341
+ if __name__ == "__main__":
342
+ main()