tokensafe 1.3.4 → 1.3.5
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 +117 -28
- package/bin/agy-tokens +4 -292
- package/bin/tokensafe +17 -0
- package/bin/tokensafe.js +27 -69
- package/extensions/cursor-tokensafe/extension.js +2 -1
- package/hooks/pre_invocation.py +27 -9
- package/package.json +2 -1
- package/plugin.json +1 -1
- package/skills/token-optimizer/SKILL.md +1 -1
- package/src/benchmark.py +2 -2
- package/src/cli.py +332 -0
- package/src/compactor.py +318 -60
- package/src/dashboard.py +46 -2
- package/src/deepseek_distiller.py +6 -3
- package/src/distiller.py +6 -3
- package/src/environment_auditor.py +6 -6
- package/src/license_manager.py +62 -2
- package/src/metrics.py +13 -0
- package/src/version_checker.py +1 -1
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 [
|
|
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
|
|
30
|
+
const firstArg = args[0] || '';
|
|
31
31
|
|
|
32
|
-
if (
|
|
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
|
-
|
|
38
|
+
tokensafe [command] [options]
|
|
39
39
|
|
|
40
40
|
Commands:
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
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
|
-
|
|
65
|
-
|
|
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
|
|
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', () => {
|
package/hooks/pre_invocation.py
CHANGED
|
@@ -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.
|
|
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
|
-
|
|
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
|
-
|
|
83
|
-
|
|
84
|
-
|
|
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
|
)
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tokensafe",
|
|
3
|
-
"version": "1.3.
|
|
3
|
+
"version": "1.3.5",
|
|
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
|
+
"version": "1.3.5",
|
|
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`
|
|
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": "
|
|
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": "
|
|
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,332 @@
|
|
|
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 100,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.distiller import UniversalDistiller
|
|
188
|
+
configured = UniversalDistiller.get_configured_providers()
|
|
189
|
+
print("\n\033[1m\033[36m⚡ TOKENSAFE LLM DISTILLATION PROVIDERS ⚡\033[0m\n")
|
|
190
|
+
all_p = UniversalDistiller.PROVIDERS
|
|
191
|
+
for key, p in all_p.items():
|
|
192
|
+
if key in configured:
|
|
193
|
+
c = configured[key]
|
|
194
|
+
print(f" \033[32m✔\033[0m \033[1m{p['name']:<18}\033[0m [Active: {c['model']}]")
|
|
195
|
+
else:
|
|
196
|
+
print(f" \033[2m○ {p['name']:<18} [Set {p['env_key']} to activate]\033[0m")
|
|
197
|
+
print("\nSet environment variable or add to data/config.json to activate.\n")
|
|
198
|
+
|
|
199
|
+
elif command in ("markdown", "md", "export"):
|
|
200
|
+
print(dashboard.render_markdown())
|
|
201
|
+
|
|
202
|
+
elif command == "test":
|
|
203
|
+
if len(args) < 2:
|
|
204
|
+
print("Usage: tokensafe test \"<prompt text>\"")
|
|
205
|
+
sys.exit(1)
|
|
206
|
+
raw_prompt = " ".join(args[1:])
|
|
207
|
+
res = PromptCompactor.compact(raw_prompt)
|
|
208
|
+
|
|
209
|
+
print("\n\033[1m\033[36m⚡ TOKEN COMPRESSION TEST ⚡\033[0m\n")
|
|
210
|
+
print(f"\033[1mOriginal Input:\033[0m {res['original_text']}")
|
|
211
|
+
print(f"\033[1mCompacted DSL:\033[0m \033[32m\033[1m{res['compact_text']}\033[0m\n")
|
|
212
|
+
print(f"\033[1mRouting Tier:\033[0m \033[33m{res.get('tier', 'REGEX')}\033[0m")
|
|
213
|
+
print(f"\033[1mExtracted Action:\033[0m {res['action']}")
|
|
214
|
+
print(f"\033[1mTarget File:\033[0m {res['target_file'] or 'None'}")
|
|
215
|
+
print(f"\033[1mScope Symbol:\033[0m {res['symbol'] or 'None'}")
|
|
216
|
+
print(f"\033[1mTraits / Tags:\033[0m {res['traits']}\n")
|
|
217
|
+
print(f"\033[1mOriginal Tokens:\033[0m {res['original_tokens']}")
|
|
218
|
+
print(f"\033[1mCompacted Tokens:\033[0m {res['compact_tokens']}")
|
|
219
|
+
print(f"\033[1mTokens Saved:\033[0m \033[32m\033[1m+{res['saved_tokens']} tokens\033[0m ({render_bar(res['reduction_pct'])})\n")
|
|
220
|
+
|
|
221
|
+
elif command in ("prune", "cleanup"):
|
|
222
|
+
days = None
|
|
223
|
+
max_events = None
|
|
224
|
+
i = 1
|
|
225
|
+
while i < len(args):
|
|
226
|
+
if args[i] == "--days" and i + 1 < len(args):
|
|
227
|
+
try:
|
|
228
|
+
days = int(args[i + 1])
|
|
229
|
+
except ValueError:
|
|
230
|
+
pass
|
|
231
|
+
i += 2
|
|
232
|
+
elif args[i] in ("--max", "--max-events") and i + 1 < len(args):
|
|
233
|
+
try:
|
|
234
|
+
max_events = int(args[i + 1])
|
|
235
|
+
except ValueError:
|
|
236
|
+
pass
|
|
237
|
+
i += 2
|
|
238
|
+
else:
|
|
239
|
+
i += 1
|
|
240
|
+
|
|
241
|
+
if days is None and max_events is None:
|
|
242
|
+
days = 30
|
|
243
|
+
max_events = 5000
|
|
244
|
+
|
|
245
|
+
print(f"\n\033[1m\033[36m⚡ DATA RETENTION PRUNE ⚡\033[0m")
|
|
246
|
+
print(f"Policy: retain events < {days or 'any'} days old, max {max_events or 'unlimited'} entries.")
|
|
247
|
+
res = tracker.prune(days=days, max_events=max_events, vacuum=True)
|
|
248
|
+
b_before = res.get("db_size_before", 0) / 1024.0
|
|
249
|
+
b_after = res.get("db_size_after", 0) / 1024.0
|
|
250
|
+
print(f"\033[32m✔ Pruned {res['pruned_events']} granular events into lifetime rollup table.\033[0m")
|
|
251
|
+
print(f" DB Size: {b_before:.1f} KB ➔ {b_after:.1f} KB\n")
|
|
252
|
+
|
|
253
|
+
elif command == "vacuum":
|
|
254
|
+
print("\n\033[1m\033[36m⚡ VACUUMING METRICS DATABASE ⚡\033[0m")
|
|
255
|
+
b_before = (os.path.getsize(tracker.db_path) if os.path.exists(tracker.db_path) else 0) / 1024.0
|
|
256
|
+
tracker.vacuum()
|
|
257
|
+
b_after = (os.path.getsize(tracker.db_path) if os.path.exists(tracker.db_path) else 0) / 1024.0
|
|
258
|
+
print(f"\033[32m✔ Database compacted. Size: {b_before:.1f} KB ➔ {b_after:.1f} KB\033[0m\n")
|
|
259
|
+
|
|
260
|
+
elif command in ("digest", "weekly-digest"):
|
|
261
|
+
from src.weekly_digest import WeeklyDigestGenerator
|
|
262
|
+
from src.mailer import TokenSafeMailer
|
|
263
|
+
|
|
264
|
+
target_email = None
|
|
265
|
+
do_send = "--send" in args
|
|
266
|
+
|
|
267
|
+
for a in args:
|
|
268
|
+
if a.startswith("--email="):
|
|
269
|
+
target_email = a.split("=", 1)[1].strip()
|
|
270
|
+
|
|
271
|
+
if not target_email:
|
|
272
|
+
from src.license_manager import LicenseManager
|
|
273
|
+
_, payload = LicenseManager.get_active_license()
|
|
274
|
+
target_email = payload.get("email") or "teamlead@example.com"
|
|
275
|
+
|
|
276
|
+
print(f"\n\033[1m\033[36m⚡ COMPILING FRIDAY TEAM ROI DIGEST ⚡\033[0m")
|
|
277
|
+
print(f"Target Teamlead: {target_email}")
|
|
278
|
+
|
|
279
|
+
stats = WeeklyDigestGenerator.get_team_weekly_stats(target_email)
|
|
280
|
+
if not stats:
|
|
281
|
+
stats = {
|
|
282
|
+
"owner_email": target_email,
|
|
283
|
+
"tier": "team",
|
|
284
|
+
"seats_total": 5,
|
|
285
|
+
"active_members_count": 4,
|
|
286
|
+
"total_members_count": 5,
|
|
287
|
+
"total_original_tokens": 5800000,
|
|
288
|
+
"total_saved_tokens": 4200000,
|
|
289
|
+
"total_saved_human": "4.2M",
|
|
290
|
+
"total_usd_saved": 28.50,
|
|
291
|
+
"total_events": 340,
|
|
292
|
+
"reduction_pct": 72.4,
|
|
293
|
+
"leaderboard": [
|
|
294
|
+
{"rank": 1, "email": "alex.dev@corp.com", "saved_tokens": 1650000, "saved_tokens_human": "1.7M", "usd_saved_formatted": "$11.20", "event_count": 120},
|
|
295
|
+
{"rank": 2, "email": "maria.arch@corp.com", "saved_tokens": 1200000, "saved_tokens_human": "1.2M", "usd_saved_formatted": "$8.10", "event_count": 94},
|
|
296
|
+
{"rank": 3, "email": "sergey.qa@corp.com", "saved_tokens": 850000, "saved_tokens_human": "850K", "usd_saved_formatted": "$5.70", "event_count": 68},
|
|
297
|
+
{"rank": 4, "email": target_email, "saved_tokens": 500000, "saved_tokens_human": "500K", "usd_saved_formatted": "$3.50", "event_count": 58}
|
|
298
|
+
]
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
print(WeeklyDigestGenerator.render_email_text(stats))
|
|
302
|
+
|
|
303
|
+
out_html = os.path.join(PROJECT_ROOT, "data", "weekly_digest_preview.html")
|
|
304
|
+
os.makedirs(os.path.dirname(out_html), exist_ok=True)
|
|
305
|
+
with open(out_html, "w", encoding="utf-8") as f:
|
|
306
|
+
f.write(WeeklyDigestGenerator.render_email_html(stats))
|
|
307
|
+
print(f"\n📧 Apple-style email HTML preview generated at: {out_html}")
|
|
308
|
+
|
|
309
|
+
if do_send:
|
|
310
|
+
ok = TokenSafeMailer.send_weekly_digest(target_email, stats, sync=True)
|
|
311
|
+
if ok:
|
|
312
|
+
print(f"\033[32m✔ Weekly digest successfully dispatched to {target_email}!\033[0m\n")
|
|
313
|
+
else:
|
|
314
|
+
print(f"\033[33m○ Digest dispatch queued (SMTP_PASS not configured in local environment).\033[0m\n")
|
|
315
|
+
else:
|
|
316
|
+
print("Tip: Run with --send to dispatch email, or --email=<addr> to target specific team.\n")
|
|
317
|
+
|
|
318
|
+
elif command == "reset":
|
|
319
|
+
confirm = input("Are you sure you want to reset all token metrics? [y/N]: ").strip().lower()
|
|
320
|
+
if confirm == "y":
|
|
321
|
+
tracker.reset()
|
|
322
|
+
print("Metrics database reset successfully.")
|
|
323
|
+
else:
|
|
324
|
+
print("Reset cancelled.")
|
|
325
|
+
|
|
326
|
+
else:
|
|
327
|
+
print(f"Unknown command: {command}")
|
|
328
|
+
print("Available commands: stats, html, test, doctor, providers, mcp, benchmark, proxy, graph, map, vacuum, prune, digest, activate, license, markdown, setup, reset")
|
|
329
|
+
sys.exit(1)
|
|
330
|
+
|
|
331
|
+
if __name__ == "__main__":
|
|
332
|
+
main()
|