tokensafe 1.3.3 → 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 CHANGED
@@ -62,7 +62,9 @@ Traditional AI code interactions suffer from massive context bloat:
62
62
  - **Subagent Deduplication Firewall:** Detects repeated file reads across subagents and agent swarms, serving cached AST slices directly from SQLite session memory (`SUBAGENT_DEDUP`) with zero redundant overhead.
63
63
  - **AST Diff Slicer & Lockfile Stripper:** Compresses code review diffs by stripping noisy lockfiles (`package-lock.json`, `pnpm-lock.yaml`, `yarn.lock`, `Cargo.lock`) and minified assets, condensing diffs to 2 lines of context (`git diff -U2`) for up to 96% token savings.
64
64
  - **God Nodes & Architectural Hub Detection:** Calculates Degree Centrality to identify structural project hubs and injects topology awareness into agent sessions without expensive file crawling.
65
- - **TOCP Prompt Distillation:** Intercepts prompts and distills intent into lean S-Expressions via **Google Gemini (2.0 Flash-Lite), OpenAI ChatGPT (gpt-4o-mini), Anthropic Claude, or DeepSeek-Flash** (`-40% to -70%`). Automatically detects `GEMINI_API_KEY`, `OPENAI_API_KEY`, `ANTHROPIC_API_KEY`, or `DEEPSEEK_API_KEY`.
65
+ - **TOCP Prompt Distillation:** Intercepts prompts and distills intent into lean S-Expressions via **Google Gemini (Flash-Lite / 2.0 Flash), DeepSeek, OpenAI ChatGPT (gpt-4o-mini), or Anthropic Claude** (`-40% to -70%`). Automatically prioritizes ultra-cheap / free Google Gemini (`gemini-flash-lite-latest`, $0.075/M input, 1,500 req/day free tier in Google AI Studio).
66
+ - **Token Arbitrage Guard & Output Ceiling:** Eliminates LLM compiler arbitrage loss with a dual defense: inputs $< 100$ tokens route to instant zero-cost local regex heuristics ($0$ LLM tokens), while inputs $\ge 100$ tokens are clamped to a strict $60$-token max output ceiling.
67
+ - **Two-Tier Distillation Cache:** Two-tier In-Memory LRU + Persistent SQLite cache (`metrics.db`) with normalized SHA-256 hashing guarantees sub-millisecond zero-cost replays for recurring developer commands.
66
68
  - **API Surface Map Generator:** Generates high-density `tokensafe-out/API_SURFACE.md` (~1.5k tokens) for instant agent codebase onboarding.
67
69
  - **Predictive Dependency Prefetcher:** Attaches imported symbol signatures to eliminate downstream exploratory `read_file` roundtrips.
68
70
  - **Live SSE Streaming Dashboard:** Real-time reactive Web UI streaming token reductions, live event logs, and USD savings via Server-Sent Events (`/api/events`).
@@ -130,19 +132,47 @@ How TokenSafe complements or supersedes static graph tools like **Graphify** (`g
130
132
 
131
133
  ---
132
134
 
133
- ## 🤖 Universal LLM Distillation Providers
135
+ ## 🤖 Universal LLM Distillation Providers & Unit Economics Defense
134
136
 
135
- TokenSafe supports any key you already have:
137
+ TokenSafe features an intelligent multi-provider prompt compiler that distills verbose developer prompts into lean TOCP S-Expressions (`-40% to -70% tokens`).
136
138
 
137
- | Provider | Supported Model | Environment Variable | Config Key |
138
- |---|---|---|---|
139
- | **Google Gemini** | `gemini-2.0-flash-lite`, `gemini-2.0-flash` | `GEMINI_API_KEY` | `gemini_api_key` |
140
- | **OpenAI ChatGPT** | `gpt-4o-mini`, `gpt-4o` | `OPENAI_API_KEY` | `openai_api_key` |
141
- | **Anthropic Claude** | `claude-3-5-haiku`, `claude-3-7-sonnet` | `ANTHROPIC_API_KEY` | `anthropic_api_key` |
142
- | **DeepSeek** | `deepseek-flash`, `deepseek-chat` | `DEEPSEEK_API_KEY` | `deepseek_api_key` |
143
- | **Custom / Unified** | Any OpenAI/Anthropic compatible gateway | `TOKENSAFE_UPSTREAM_KEY` | `upstream_key` |
139
+ ### 1. Provider Priority & Economics Matrix
144
140
 
145
- Check active providers anytime with:
141
+ | Provider | Recommended Model | Pricing (Input / Output) | Environment Variable | Priority |
142
+ |---|---|---|---|---|
143
+ | **Google Gemini** ⚡ | `gemini-flash-lite-latest` | **$0.075 / $0.30** / M (Free tier: 1,500 req/day) | `GEMINI_API_KEY` | **1 (Default / Lowest Cost)** |
144
+ | **DeepSeek** | `deepseek-chat` / `deepseek-flash` | $0.14 / $0.60 / M | `DEEPSEEK_API_KEY` | 2 |
145
+ | **OpenAI ChatGPT** | `gpt-4o-mini` | $0.15 / $0.60 / M | `OPENAI_API_KEY` | 3 |
146
+ | **Anthropic Claude** | `claude-3-5-haiku-20241022` | $0.80 / $4.00 / M | `ANTHROPIC_API_KEY` | 4 |
147
+ | **Custom / Unified** | Any OpenAI/Anthropic gateway | Custom | `TOKENSAFE_UPSTREAM_KEY` | 5 |
148
+
149
+ > **Recommendation**: Set `GEMINI_API_KEY` from Google AI Studio. Gemini Flash-Lite provides 1,500 free requests per day, making prompt distillation 100% free for individual developers and small teams.
150
+
151
+ ### 2. Token Arbitrage Guard & Two-Tier Cache Architecture
152
+
153
+ To prevent compiler cost overhead from exceeding token savings, TokenSafe applies a 3-stage defense:
154
+
155
+ 1. **Smart Gating Threshold (`llm_distill_min_tokens: 100`)**: Prompts under 100 tokens bypass LLM calls entirely and use instant zero-cost local regex heuristics ($0$ tokens, $< 1\text{ms}$).
156
+ 2. **Output Token Ceiling (`distill_max_tokens: 60`)**: Caps LLM output at 60 tokens, eliminating verbose chain-of-thought inflation and token arbitrage loss.
157
+ 3. **Two-Tier Distillation Cache**:
158
+ - **Tier 1 (In-Memory LRU)**: Sub-millisecond instant hit for active session loops.
159
+ - **Tier 2 (Persistent SQLite)**: Stores SHA-256 normalized prompt hashes in `data/metrics.db` across agent restarts. Recurring commands (`git commit`, `run tests`, `fix lint`) cost 0 tokens.
160
+
161
+ ### 3. Configuration (`data/config.json`)
162
+
163
+ Configure your provider preferences and models directly:
164
+
165
+ ```json
166
+ {
167
+ "preferred_provider": "gemini",
168
+ "gemini_api_key": "YOUR_GEMINI_API_KEY",
169
+ "gemini_model": "gemini-flash-lite-latest",
170
+ "llm_distill_min_tokens": 100,
171
+ "distill_max_tokens": 60
172
+ }
173
+ ```
174
+
175
+ Check active providers and cache stats anytime:
146
176
  ```bash
147
177
  tokensafe providers
148
178
  ```
@@ -182,32 +212,67 @@ Verified across 8 real-world production software engineering scenarios (131,604
182
212
  ## 🛠️ CLI Quickstart
183
213
 
184
214
  ```bash
185
- # Analyze repository God Nodes and dependency topology
186
- tokensafe graph
215
+ # View live savings dashboard in your terminal
216
+ tokensafe stats
217
+ ```
187
218
 
188
- # Generate compact tokensafe-out/API_SURFACE.md interface snapshot
189
- tokensafe map
219
+ ```text
220
+ ┌────────────────────────────────────────────────────────────────────────┐
221
+ │ ⚡ TOKENSAFE CONTEXT OPTIMIZER DASHBOARD ⚡ │
222
+ └────────────────────────────────────────────────────────────────────────┘
223
+
224
+ Total Tokens Saved: 4,524,156 tokens
225
+ Efficiency Gain: [████████████████████████████░░] 92.5%
226
+ Estimated Savings: $6.7865 USD
227
+ Context Traffic: 4,889,255 raw ➔ 370,574 optimized (2132 events)
228
+
229
+ ── Breakdown by Source ──────────────────────────────────────────────────
230
+ • AST Skeletonizer (Signatures) : 3,509 tokens saved (2 events)
231
+ • Command Sanitizer (CLI) : 727,300 tokens saved (263 events)
232
+ • Context Governor : 5,800 tokens saved (29 events)
233
+ • Graph-Guided Slicer (Call-Graph) : 42,420 tokens saved (14 events)
234
+ • Architecture Graph (God Nodes) : 758,256 tokens saved (13 events)
235
+ • Multi-turn History Fold : 2,897,897 tokens saved (471 events)
236
+ • Output Token Guard (write_file) : 42,466 tokens saved (84 events)
237
+ • Prompt Compactor (TOCP + Cache) : 43,502 tokens saved (1255 events)
238
+ • File Line Slicer (AST) : 3,006 tokens saved (1 events)
239
+
240
+ Run `tokensafe test "<prompt>"` to test compression on custom input.
241
+ Run `tokensafe html` to view interactive browser dashboard.
242
+ ```
190
243
 
191
- # Run environment health check and audit MCP/skill context token tax
244
+ ```bash
245
+ # Open interactive local Apple dark-mode browser dashboard
246
+ tokensafe html
247
+
248
+ # Test prompt compression on custom input in real time
249
+ tokensafe test "please fix the validate_token method in src/auth.py so that it checks jwt expiration and returns boolean"
250
+
251
+ # Audit environment and context token tax (MCP & skills)
192
252
  tokensafe doctor
193
253
 
194
- # View live savings dashboard in your terminal
195
- tokensafe stats
254
+ # List configured LLM distillation providers and models
255
+ tokensafe providers
196
256
 
197
- # Open interactive Apple dark-mode HTML dashboard
198
- tokensafe html
257
+ # Analyze repository God Nodes and dependency topology
258
+ tokensafe graph
199
259
 
200
- # Generate or preview Friday team ROI digest email
201
- tokensafe digest
260
+ # Generate compact tokensafe-out/API_SURFACE.md interface snapshot
261
+ tokensafe map
202
262
 
203
263
  # Manage or disable high-overhead MCP tools
204
264
  tokensafe mcp list
205
265
  tokensafe mcp disable <server>
266
+ tokensafe mcp enable <server>
206
267
 
207
268
  # Optimize SQLite metrics storage
208
269
  tokensafe vacuum
270
+ tokensafe prune
271
+
272
+ # Generate or preview Friday team ROI digest email
273
+ tokensafe digest
209
274
 
210
- # Run the 5-scenario benchmark suite
275
+ # Run the SWE-bench zero-loss verification suite
211
276
  tokensafe benchmark
212
277
 
213
278
  # Run the local transparent AI proxy (0.0.0.0:8765/v1)
@@ -229,10 +294,11 @@ You can configure any or all of your preferred LLM provider keys:
229
294
 
230
295
  | Environment Variable | Provider Supported | Default Model |
231
296
  |---|---|---|
297
+ | `GEMINI_API_KEY` | Google Gemini (Fastest / Lowest Cost) | `gemini-flash-lite-latest` |
298
+ | `PREFERRED_PROVIDER` | Explicit provider priority (`gemini`, `deepseek`, etc.) | `gemini` |
299
+ | `DEEPSEEK_API_KEY` | DeepSeek API | `deepseek-chat` |
232
300
  | `OPENAI_API_KEY` | OpenAI API | `gpt-4o-mini` |
233
301
  | `ANTHROPIC_API_KEY` | Anthropic Claude | `claude-3-5-haiku-20241022` |
234
- | `GEMINI_API_KEY` | Google Gemini | `gemini-2.0-flash-lite` |
235
- | `DEEPSEEK_API_KEY` | DeepSeek API | `deepseek-chat` |
236
302
  | `TOKENSAFE_UPSTREAM_KEY` | Unified / Custom Gateway | Custom Upstream |
237
303
 
238
304
  ### 2. Docker Compose Quickstart
@@ -334,12 +400,27 @@ python3 -m unittest discover tests
334
400
 
335
401
  ---
336
402
 
403
+ ## 💎 Pricing & Plans
404
+
405
+ TokenSafe is built on an **Open-Core** model designed to give every developer immediate zero-friction value while offering unlimited throughput and centralized governance for professionals and teams:
406
+
407
+ | Plan | Price | Monthly Token Savings | Capabilities |
408
+ | :--- | :---: | :---: | :--- |
409
+ | **Community (Free)** | **$0** forever | **500,000 tokens / mo** | Multilingual Local Regex Compactor, AST Slicer, Output Guard, Loop Guard, Local SQLite & HTML Dashboard |
410
+ | **Solo Developer** | **$9 / mo** | **Unlimited** | Multi-Provider Distillation (Gemini Flash-Lite, DeepSeek), Subagent Swarm Firewall, Cascading Governor, Multi-turn History Fold |
411
+ | **Engineering Team** | **$29 / seat / mo** | **Unlimited** | Everything in Solo + Friday Team ROI Digest, Cloud Organization Console, Seat Quota Management, Self-Hosted Docker Proxy |
412
+
413
+ > [!TIP]
414
+ > **500,000 free tokens / month** are included out of the box with zero registration. When your monthly community limit is reached, basic regex compaction continues safely, and you can unlock unlimited Solo optimization anytime at [tokensafe.dev](https://tokensafe.dev/#pricing) or activate via `tokensafe activate <key>`.
415
+
416
+ ---
417
+
337
418
  ## 📄 License
338
419
  MIT License. Commercial enterprise licenses available for on-premise B2B deployments.
339
420
 
340
421
  ### Export Markdown Report
341
422
  ```bash
342
- ./bin/agy-tokens markdown
423
+ tokensafe markdown
343
424
  ```
344
425
 
345
426
  ---
@@ -360,21 +441,28 @@ agy-token-optimizer/
360
441
  ├── proto/
361
442
  │ └── tocp.proto # Protocol Buffers contract
362
443
  ├── src/
444
+ │ ├── cli.py # Unified CLI dispatcher (npm, pip, standalone)
363
445
  │ ├── cache_normalizer.py # Prompt Cache Prefix Normalizer (Anthropic & DeepSeek)
364
446
  │ ├── governor.py # Context Window Governor & Token Ceiling (Cascading reduction)
365
447
  │ ├── agent_firewall.py # Cross-Agent Deduplication Cache (Subagent Firewall)
366
448
  │ ├── diff_slicer.py # AST Diff Slicer & Lockfile Stripper (`git diff -U2`)
367
449
  │ ├── weekly_digest.py # Friday Team ROI Digest & Engineer Leaderboard
368
450
  │ ├── environment_auditor.py # MCP Server & Skill context token tax auditor
451
+ │ ├── command_sanitizer.py # High-output terminal command sanitizer
369
452
  │ ├── proxy.py # Multi-provider transparent AI proxy & SSE broadcaster
370
453
  │ ├── graph_engine.py # Sub-30ms AST parser, call graphs & God Node centrality
371
454
  │ ├── tokenizer.py # Zero-dependency calibrated BPE token counter
372
- │ ├── compactor.py # Semantic compactor (Natural Language -> TOCP S-Expr)
455
+ │ ├── compactor.py # Enhanced semantic compactor (Local Regex + Distillation -> TOCP S-Expr)
456
+ │ ├── distiller.py # Multi-provider LLM distillation engine (Gemini, DeepSeek, OpenAI)
457
+ │ ├── distiller_cache.py # Two-tier LRU + SQLite prompt distillation cache
458
+ │ ├── deepseek_distiller.py # DeepSeek-Flash semantic compiler with token arbitrage guard
373
459
  │ ├── slicer.py # AST & Line windowing tool optimizer
374
460
  │ ├── metrics.py # Persistent SQLite metrics engine
375
461
  │ ├── dashboard.py # Visual ANSI terminal, Markdown & reactive SSE web dashboard
376
462
  │ ├── license_manager.py # Ed25519 cryptographic license verification
377
463
  │ ├── mailer.py # Transactional email & Friday ROI digest dispatcher
464
+ │ ├── mcp_server.py # Native Model Context Protocol (MCP) server
465
+ │ ├── installer.py # Multi-IDE agent auto-installer & config wizard
378
466
  │ └── cloud_backend.py # Cloud REST backend, telemetry sync & Stripe webhooks
379
467
  ├── hooks/
380
468
  │ ├── pre_invocation.py # PreInvocation hook entry point
@@ -382,7 +470,8 @@ agy-token-optimizer/
382
470
  │ └── post_tool_use.py # PostToolUse hook entry point
383
471
  ├── frontend/ # Modern React / Vite / Tailwind Web App & Dashboard
384
472
  ├── bin/
385
- │ └── agy-tokens # Executable CLI (`tokensafe`)
473
+ │ ├── tokensafe.js # Node.js npm launcher (npx tokensafe)
474
+ │ └── tokensafe # Python CLI launcher (pip / standalone)
386
475
  ├── tests/ # Unit test suite (100% passing)
387
476
  ├── install.sh # One-click installer for Antigravity
388
477
  └── README.md
package/bin/agy-tokens CHANGED
@@ -1,305 +1,17 @@
1
1
  #!/usr/bin/env python3
2
2
  """
3
- CLI entry point for Antigravity Token Optimizer.
4
- Usage:
5
- agy-tokens [stats] Show visual metrics dashboard
6
- agy-tokens doctor Audit environment and static context tax (MCP & skills)
7
- agy-tokens mcp [list|disable|enable] Manage MCP servers to prune turn overhead
8
- agy-tokens html Generate and open interactive browser dashboard
9
- agy-tokens test "<prompt>" Test prompt compression and view savings
10
- agy-tokens markdown Output GitHub Markdown report
11
- agy-tokens prune Prune granular events into lifetime rollup
12
- agy-tokens vacuum Compact SQLite metrics database
13
- agy-tokens reset Reset metrics database
3
+ Legacy alias for TokenSafe CLI launcher.
14
4
  """
15
5
 
16
6
  import sys
17
7
  import os
18
- import subprocess
19
8
 
20
9
  SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
21
10
  PROJECT_ROOT = os.path.dirname(SCRIPT_DIR)
22
- sys.path.insert(0, PROJECT_ROOT)
11
+ if PROJECT_ROOT not in sys.path:
12
+ sys.path.insert(0, PROJECT_ROOT)
23
13
 
24
- from src.metrics import MetricsTracker
25
- from src.dashboard import Dashboard, render_bar
26
- from src.compactor import PromptCompactor
27
- from src.tokenizer import count_tokens
28
-
29
- def main():
30
- tracker = MetricsTracker()
31
- dashboard = Dashboard(tracker)
32
-
33
- args = sys.argv[1:]
34
- command = args[0] if args else "stats"
35
-
36
- if command in ("stats", "dashboard"):
37
- print(dashboard.render_terminal())
38
-
39
- elif command in ("html", "web"):
40
- html_content = dashboard.render_html()
41
- out_path = os.path.join(PROJECT_ROOT, "data", "dashboard.html")
42
- os.makedirs(os.path.dirname(out_path), exist_ok=True)
43
- with open(out_path, "w", encoding="utf-8") as f:
44
- f.write(html_content)
45
- print(f"\n⚡ Interactive HTML Dashboard generated at: {out_path}")
46
- try:
47
- subprocess.run(["open", out_path])
48
- print(" Opened in default browser.")
49
- except Exception:
50
- pass
51
-
52
- elif command in ("benchmark", "bench"):
53
- from src.benchmark import BenchmarkSuite
54
- print("\n⚡ Running Zero-Loss SWE-bench Benchmark Suite across 5 real-world scenarios...")
55
- data = BenchmarkSuite.run_all()
56
- print(BenchmarkSuite.render_report(data))
57
- out_md = os.path.join(PROJECT_ROOT, "data", "BENCHMARK_REPORT.md")
58
- BenchmarkSuite.export_markdown_report(data, out_md)
59
- print(f"📊 Publication-ready markdown report saved to: {out_md}\n")
60
-
61
- elif command in ("setup", "install"):
62
- from src.installer import AgentInstaller
63
- if "--all" in args or "-a" in args or "-y" in args or "--auto" in args:
64
- print("\n\033[1m\033[36m⚡ TOKENSAFE UNIVERSAL MULTI-AGENT INSTALLER (--all) ⚡\033[0m\n")
65
- res = AgentInstaller.install_all(force=True)
66
- print("Configured AI agent environments:")
67
- for k, r in res["agents"].items():
68
- status = "\033[32m✔\033[0m" if r["success"] else "\033[31m✖\033[0m"
69
- print(f" {status} \033[1m{r['name']:<28}\033[0m: {r['message']}")
70
- print(f"\n\033[32m✔ Universal project rules injected into: {', '.join(res['project_rules'])}\033[0m\n")
71
- elif "--project" in args:
72
- res = AgentInstaller.install_project(os.getcwd())
73
- print(f"\n\033[32m✔ TokenSafe rules injected into project: {', '.join(res['created_rules'])}\033[0m\n")
74
- else:
75
- AgentInstaller.run_interactive()
76
-
77
- elif command in ("update", "upgrade"):
78
- from src.installer import AgentInstaller
79
- AgentInstaller.self_update()
80
-
81
- elif command == "proxy":
82
- from src.proxy import run_proxy
83
- port = int(args[1]) if len(args) > 1 else 8765
84
- run_proxy(port)
85
-
86
- elif command == "mcp":
87
- subcmd = args[1] if len(args) > 1 else "serve"
88
- if subcmd in ("disable", "off", "rm"):
89
- if len(args) < 3:
90
- print("Usage: agy-tokens mcp disable <server_name>")
91
- sys.exit(1)
92
- target = args[2].strip()
93
- from src.environment_auditor import EnvironmentAuditor
94
- res = EnvironmentAuditor.disable_mcp(target)
95
- if res["success"]:
96
- print(f"\n\033[32m✔ MCP server '{target}' disabled successfully. Removed from active turn overhead.\033[0m\n")
97
- else:
98
- print(f"\n\033[31m✖ Server '{target}' not found or already disabled.\033[0m\n")
99
- elif subcmd in ("enable", "on", "add"):
100
- if len(args) < 3:
101
- print("Usage: agy-tokens mcp enable <server_name>")
102
- sys.exit(1)
103
- target = args[2].strip()
104
- from src.environment_auditor import EnvironmentAuditor
105
- res = EnvironmentAuditor.enable_mcp(target)
106
- if res["success"]:
107
- print(f"\n\033[32m✔ MCP server '{target}' re-enabled successfully.\033[0m\n")
108
- else:
109
- print(f"\n\033[31m✖ Server '{target}' not found in disabled servers.\033[0m\n")
110
- elif subcmd in ("list", "ls", "status"):
111
- from src.environment_auditor import EnvironmentAuditor
112
- print(EnvironmentAuditor.format_cli_report())
113
- else:
114
- from src.mcp_server import run_mcp_server
115
- run_mcp_server()
116
-
117
- elif command in ("doctor", "audit", "tax"):
118
- from src.environment_auditor import EnvironmentAuditor
119
- print(EnvironmentAuditor.format_cli_report())
120
-
121
- elif command == "activate":
122
- from src.license_manager import LicenseManager
123
- if len(args) < 2:
124
- print("Usage: agy-tokens activate <LICENSE_KEY>")
125
- sys.exit(1)
126
- key = args[1].strip()
127
- ok, msg = LicenseManager.save_license(key)
128
- if ok:
129
- print(f"\n\033[32m\033[1m✔ {msg}\033[0m\n")
130
- else:
131
- print(f"\n\033[31m\033[1m✖ {msg}\033[0m\n")
132
- sys.exit(1)
133
-
134
- elif command in ("license", "tier"):
135
- from src.license_manager import LicenseManager
136
- tier, payload = LicenseManager.get_active_license()
137
- print("\n\033[1m\033[36m⚡ TOKENSAFE LICENSE STATUS ⚡\033[0m\n")
138
- print(f" Tier: \033[32m\033[1m{tier.upper()}\033[0m")
139
- if tier != "free":
140
- print(f" Email: {payload.get('email', 'N/A')}")
141
- if payload.get("trial"):
142
- print(f" Mode: \033[33m7-Day Free Trial\033[0m")
143
- exp = payload.get("expires_at", 0)
144
- if exp > 0:
145
- import datetime
146
- dt = datetime.datetime.fromtimestamp(exp).strftime('%Y-%m-%d %H:%M:%S')
147
- print(f" Expires: {dt}")
148
- else:
149
- print(f" Expires: Never (Lifetime)")
150
- else:
151
- print(" Status: Free Tier (up to 100,000 tokens/mo)")
152
- print(" Upgrade: https://tokensafe.dev ($9/mo Solo with 7-Day Free Trial)\n")
153
- print()
154
-
155
- elif command in ("providers", "models", "keys"):
156
- from src.distiller import UniversalDistiller
157
- configured = UniversalDistiller.get_configured_providers()
158
- print("\n\033[1m\033[36m⚡ TOKENSAFE LLM DISTILLATION PROVIDERS ⚡\033[0m\n")
159
- all_p = UniversalDistiller.PROVIDERS
160
- for key, p in all_p.items():
161
- if key in configured:
162
- c = configured[key]
163
- print(f" \033[32m✔\033[0m \033[1m{p['name']:<18}\033[0m [Active: {c['model']}]")
164
- else:
165
- print(f" \033[2m○ {p['name']:<18} [Set {p['env_key']} to activate]\033[0m")
166
- print("\nSet environment variable or add to data/config.json to activate.\n")
167
-
168
- elif command in ("markdown", "md", "export"):
169
- print(dashboard.render_markdown())
170
-
171
- elif command == "test":
172
- if len(args) < 2:
173
- print("Usage: agy-tokens test \"<prompt text>\"")
174
- sys.exit(1)
175
- raw_prompt = " ".join(args[1:])
176
- res = PromptCompactor.compact(raw_prompt)
177
-
178
- print("\n\033[1m\033[36m⚡ TOKEN COMPRESSION TEST ⚡\033[0m\n")
179
- print(f"\033[1mOriginal Input:\033[0m {res['original_text']}")
180
- print(f"\033[1mCompacted DSL:\033[0m \033[32m\033[1m{res['compact_text']}\033[0m\n")
181
- print(f"\033[1mRouting Tier:\033[0m \033[33m{res.get('tier', 'REGEX')}\033[0m")
182
- print(f"\033[1mExtracted Action:\033[0m {res['action']}")
183
- print(f"\033[1mTarget File:\033[0m {res['target_file'] or 'None'}")
184
- print(f"\033[1mScope Symbol:\033[0m {res['symbol'] or 'None'}")
185
- print(f"\033[1mTraits / Tags:\033[0m {res['traits']}\n")
186
- print(f"\033[1mOriginal Tokens:\033[0m {res['original_tokens']}")
187
- print(f"\033[1mCompacted Tokens:\033[0m {res['compact_tokens']}")
188
- print(f"\033[1mTokens Saved:\033[0m \033[32m\033[1m+{res['saved_tokens']} tokens\033[0m ({render_bar(res['reduction_pct'])})\n")
189
-
190
- elif command in ("prune", "cleanup"):
191
- days = None
192
- max_events = None
193
- i = 1
194
- while i < len(args):
195
- if args[i] == "--days" and i + 1 < len(args):
196
- try:
197
- days = int(args[i + 1])
198
- except ValueError:
199
- pass
200
- i += 2
201
- elif args[i] in ("--max", "--max-events") and i + 1 < len(args):
202
- try:
203
- max_events = int(args[i + 1])
204
- except ValueError:
205
- pass
206
- i += 2
207
- else:
208
- i += 1
209
-
210
- if days is None and max_events is None:
211
- days = 30
212
- max_events = 5000
213
-
214
- print(f"\n\033[1m\033[36m⚡ DATA RETENTION PRUNE ⚡\033[0m")
215
- print(f"Policy: retain events < {days or 'any'} days old, max {max_events or 'unlimited'} entries.")
216
- res = tracker.prune(days=days, max_events=max_events, vacuum=True)
217
- b_before = res.get("db_size_before", 0) / 1024.0
218
- b_after = res.get("db_size_after", 0) / 1024.0
219
- print(f"\033[32m✔ Pruned {res['pruned_events']} granular events into lifetime rollup table.\033[0m")
220
- print(f" DB Size: {b_before:.1f} KB ➔ {b_after:.1f} KB\n")
221
-
222
- elif command == "vacuum":
223
- print("\n\033[1m\033[36m⚡ VACUUMING METRICS DATABASE ⚡\033[0m")
224
- b_before = (os.path.getsize(tracker.db_path) if os.path.exists(tracker.db_path) else 0) / 1024.0
225
- tracker.vacuum()
226
- b_after = (os.path.getsize(tracker.db_path) if os.path.exists(tracker.db_path) else 0) / 1024.0
227
- print(f"\033[32m✔ Database compacted. Size: {b_before:.1f} KB ➔ {b_after:.1f} KB\033[0m\n")
228
-
229
- elif command in ("digest", "weekly-digest"):
230
- from src.weekly_digest import WeeklyDigestGenerator
231
- from src.cloud_backend import CloudBackendService
232
- from src.mailer import TokenSafeMailer
233
-
234
- target_email = None
235
- do_send = "--send" in args
236
- force = "--force" in args
237
-
238
- for a in args:
239
- if a.startswith("--email="):
240
- target_email = a.split("=", 1)[1].strip()
241
-
242
- if not target_email:
243
- from src.license_manager import LicenseManager
244
- _, payload = LicenseManager.get_active_license()
245
- target_email = payload.get("email") or "teamlead@example.com"
246
-
247
- print(f"\n\033[1m\033[36m⚡ COMPILING FRIDAY TEAM ROI DIGEST ⚡\033[0m")
248
- print(f"Target Teamlead: {target_email}")
249
-
250
- stats = WeeklyDigestGenerator.get_team_weekly_stats(target_email)
251
- if not stats:
252
- # Fallback mock/synthetic preview if DB has no historical team events
253
- stats = {
254
- "owner_email": target_email,
255
- "tier": "team",
256
- "seats_total": 5,
257
- "active_members_count": 4,
258
- "total_members_count": 5,
259
- "total_original_tokens": 5800000,
260
- "total_saved_tokens": 4200000,
261
- "total_saved_human": "4.2M",
262
- "total_usd_saved": 28.50,
263
- "total_events": 340,
264
- "reduction_pct": 72.4,
265
- "leaderboard": [
266
- {"rank": 1, "email": "alex.dev@corp.com", "saved_tokens": 1650000, "saved_tokens_human": "1.7M", "usd_saved_formatted": "$11.20", "event_count": 120},
267
- {"rank": 2, "email": "maria.arch@corp.com", "saved_tokens": 1200000, "saved_tokens_human": "1.2M", "usd_saved_formatted": "$8.10", "event_count": 94},
268
- {"rank": 3, "email": "sergey.qa@corp.com", "saved_tokens": 850000, "saved_tokens_human": "850K", "usd_saved_formatted": "$5.70", "event_count": 68},
269
- {"rank": 4, "email": target_email, "saved_tokens": 500000, "saved_tokens_human": "500K", "usd_saved_formatted": "$3.50", "event_count": 58}
270
- ]
271
- }
272
-
273
- print(WeeklyDigestGenerator.render_email_text(stats))
274
-
275
- # Save HTML preview
276
- out_html = os.path.join(PROJECT_ROOT, "data", "weekly_digest_preview.html")
277
- os.makedirs(os.path.dirname(out_html), exist_ok=True)
278
- with open(out_html, "w", encoding="utf-8") as f:
279
- f.write(WeeklyDigestGenerator.render_email_html(stats))
280
- print(f"\n📧 Apple-style email HTML preview generated at: {out_html}")
281
-
282
- if do_send:
283
- ok = TokenSafeMailer.send_weekly_digest(target_email, stats, sync=True)
284
- if ok:
285
- print(f"\033[32m✔ Weekly digest successfully dispatched to {target_email}!\033[0m\n")
286
- else:
287
- print(f"\033[33m○ Digest dispatch queued (SMTP_PASS not configured in local environment).\033[0m\n")
288
- else:
289
- print("Tip: Run with --send to dispatch email, or --email=<addr> to target specific team.\n")
290
-
291
- elif command == "reset":
292
- confirm = input("Are you sure you want to reset all token metrics? [y/N]: ").strip().lower()
293
- if confirm == "y":
294
- tracker.reset()
295
- print("Metrics database reset successfully.")
296
- else:
297
- print("Reset cancelled.")
298
-
299
- else:
300
- print(f"Unknown command: {command}")
301
- print("Available commands: stats, doctor, mcp, html, benchmark, setup, proxy, test, markdown, prune, vacuum, reset")
302
- sys.exit(1)
14
+ from src.cli import main
303
15
 
304
16
  if __name__ == "__main__":
305
17
  main()
package/bin/tokensafe ADDED
@@ -0,0 +1,17 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ TokenSafe standalone CLI launcher.
4
+ """
5
+
6
+ import sys
7
+ import os
8
+
9
+ SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
10
+ PROJECT_ROOT = os.path.dirname(SCRIPT_DIR)
11
+ if PROJECT_ROOT not in sys.path:
12
+ sys.path.insert(0, PROJECT_ROOT)
13
+
14
+ from src.cli import main
15
+
16
+ if __name__ == "__main__":
17
+ main()