tokensafe 1.2.0 → 1.3.1

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
@@ -3,12 +3,12 @@
3
3
  [![npm version](https://img.shields.io/npm/v/tokensafe.svg?color=CB3837)](https://www.npmjs.com/package/tokensafe)
4
4
  [![PyPI version](https://img.shields.io/pypi/v/tokensafe.svg?color=3775A9)](https://pypi.org/project/tokensafe/)
5
5
  [![License: MIT](https://img.shields.io/badge/License-MIT-emerald.svg)](https://opensource.org/licenses/MIT)
6
- [![SWE-bench: Verified](https://img.shields.io/badge/SWE--bench-61.8%25_to_92.1%25_Savings-06B6D4.svg)](https://tokensafe.dev#benchmarks)
6
+ [![SWE-bench: Verified](https://img.shields.io/badge/SWE--bench-up_to_95%25_Savings-06B6D4.svg)](https://tokensafe.dev#benchmarks)
7
7
  [![Python: 3.10+](https://img.shields.io/badge/Python-3.10+-3B82F6.svg)](https://python.org)
8
8
  [![Trial: 7 Days Free](https://img.shields.io/badge/Trial-7_Days_Free-10B981.svg)](https://tokensafe.dev#pricing)
9
9
 
10
10
  > **Autonomous Zero-Loss Token Economy & Context Optimizer for AI Coding Agents.**
11
- > Slashes LLM token costs by **60%–90%** with zero quality loss. Built for **Google Antigravity, OpenAI Codex, Cursor, Claude Desktop, Z.ai Code, Windsurf & Cline**.
11
+ > Slashes LLM token costs by **up to 95%** with zero quality loss. Built for **Google Antigravity, OpenAI Codex, Cursor, Claude Desktop, Z.ai Code, Windsurf & Cline**.
12
12
 
13
13
  🌐 **Official Website:** [https://tokensafe.dev](https://tokensafe.dev)
14
14
 
@@ -57,15 +57,61 @@ Traditional AI code interactions suffer from massive context bloat:
57
57
 
58
58
  ### TokenSafe Solves All Three Autonomously:
59
59
  - **Graph-Guided AST Skeletonization:** Folds inactive function bodies into signatures, keeping target functions and 1-hop dependencies full while collapsing unrelated code (`-85% to -92%`).
60
+ - **Prompt Cache Prefix Normalizer:** Strips volatile timestamps and aligns system prompts to 64-token boundaries. Injects Anthropic ephemeral breakpoints (`cache_control: {"type": "ephemeral"}`) and DeepSeek chunking for 100% provider cache hits and 90% cost discounts.
61
+ - **Context Window Governor & Token Ceiling:** Enforces deterministic token budgets via 3-stage cascading autothrottling (AST skeletonization ➔ TOCP user message history compaction ➔ sliding state ledger) to prevent catastrophic context overflows.
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
+ - **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.
60
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.
61
- - **TOCP Prompt Distillation:** Intercepts prompts and distills intent into lean S-Expressions via **Google Gemini (2.0 Flash-Lite), OpenAI ChatGPT (gpt-4o-mini), or DeepSeek-Flash** (`-40% to -70%`). Automatically detects `GEMINI_API_KEY`, `OPENAI_API_KEY`, or `DEEPSEEK_API_KEY`.
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`.
62
66
  - **API Surface Map Generator:** Generates high-density `tokensafe-out/API_SURFACE.md` (~1.5k tokens) for instant agent codebase onboarding.
63
67
  - **Predictive Dependency Prefetcher:** Attaches imported symbol signatures to eliminate downstream exploratory `read_file` roundtrips.
68
+ - **Live SSE Streaming Dashboard:** Real-time reactive Web UI streaming token reductions, live event logs, and USD savings via Server-Sent Events (`/api/events`).
69
+ - **Friday Team ROI Digest:** Automatically aggregates 7-day token economics every Friday and emails team leads an executive HTML report with engineer savings leaderboards.
70
+ - **Environment Overhead Auditor (`tokensafe doctor`):** Inspects active MCP servers and Antigravity skills, measuring system prompt token tax and pruning redundant tool schemas.
71
+ - **MCP Tool Schema Bloat Guard:** Stops heavy MCP servers (50–200+ tools) from injecting 5,000–15,000 hidden schema tokens into every API turn. 1-click toggle (`tokensafe mcp disable <name>`) and real-time in-chat bloat alerts.
72
+ - **Data Retention & Compact Rollups (`tokensafe prune` / `vacuum`):** Automated sliding-window log cleanup with lifetime metric rollups, cutting telemetry database disk footprint by up to 40%.
64
73
  - **Local Secret Redactor:** Sanitizes Stripe, AWS, JWT, and database credentials before network transmission.
65
74
  - **Output Guard & Loop Guard:** Blocks destructive full-file rewrites on files $\ge 40$ lines and halts command loops.
66
75
 
67
76
  ---
68
77
 
78
+ ## 🛡️ The Hidden Context Killer: MCP Tool Schema Bloat
79
+
80
+ Why do AI coding agent quotas (like Antigravity's **5-Hour Limit** or Claude/OpenAI monthly token budgets) evaporate after just a few prompts?
81
+
82
+ ### The Hidden System Prompt Tax
83
+ Whenever an MCP server is configured in your editor (Cursor, Claude Desktop, Antigravity, Windsurf), **the complete JSON schema for every single tool is injected into the LLM's system prompt on EVERY API TURN** — even if you never use that tool!
84
+
85
+ ```
86
+ ┌────────────────────────────────────────────────────────────────────────┐
87
+ │ SYSTEM PROMPT ANATOMY (EVERY SINGLE TURN) │
88
+ ├────────────────────────────────────────────────────────────────────────┤
89
+ │ Base System Instructions ~1,500 tokens │
90
+ │ Active Workspace Skills & Prompts ~8,000 tokens │
91
+ │ Regular MCP Tools (context7, prisma, etc.) ~800 tokens │
92
+ │ 🚨 Heavy MCP Tools (200+ schemas from cloud/re tools) ~6,000 tokens │
93
+ ├────────────────────────────────────────────────────────────────────────┤
94
+ │ TOTAL HIDDEN BASE TAX BEFORE YOU TYPE A SINGLE CHARACTER: │
95
+ │ 🔥 ~16,300 tokens PER TURN × 15 turns = 244,500 tokens burned! │
96
+ └────────────────────────────────────────────────────────────────────────┘
97
+ ```
98
+
99
+ - **1 Server with 50 tools** = **~1,500 – 2,500 tokens** of static tax on every turn.
100
+ - **1 Server with 200+ tools** = **~5,000 – 10,000 tokens** per turn!
101
+ - In a 15-turn coding task, **75,000 to 150,000 tokens** are burned on tool schemas alone.
102
+
103
+ ### How TokenSafe Eliminates MCP Bloat:
104
+ 1. **`tokensafe doctor` (Context Tax Auditor)**: Scans all configured MCP servers and active skills, measures the exact token overhead per turn, and flags servers with $\ge 40$ tools as `CRITICAL BLOAT`.
105
+ 2. **1-Click MCP Management**: Instantly toggle heavy servers without editing JSON files manually:
106
+ ```bash
107
+ tokensafe mcp disable rea # Prunes 208 schemas from system prompt
108
+ tokensafe mcp enable rea # Re-enables when actively needed
109
+ ```
110
+ 3. **PreInvocation Bloat Alerts**: Live in-chat warning badges in the IDE when critical MCP bloat is detected on session start.
111
+ 4. **Data Retention & Compact Rollups**: Automatic rolling-window event cleanup (`tokensafe prune` and `tokensafe vacuum`) prevents SQLite telemetry from ballooning on disk.
112
+
113
+ ---
114
+
69
115
  ## ⚡ TokenSafe vs. Graphify: Dynamic In-Flight Defense vs. Static Reports
70
116
 
71
117
  How TokenSafe complements or supersedes static graph tools like **Graphify** (`graphify-labs/graphify`):
@@ -92,7 +138,9 @@ TokenSafe supports any key you already have:
92
138
  |---|---|---|---|
93
139
  | **Google Gemini** | `gemini-2.0-flash-lite`, `gemini-2.0-flash` | `GEMINI_API_KEY` | `gemini_api_key` |
94
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` |
95
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` |
96
144
 
97
145
  Check active providers anytime with:
98
146
  ```bash
@@ -103,15 +151,18 @@ tokensafe providers
103
151
 
104
152
  ## 📊 Zero-Loss SWE-bench Benchmark Results
105
153
 
106
- Verified across 5 real-world production scenarios:
154
+ Verified across 8 real-world production software engineering scenarios (131,604 baseline tokens down to 7,251 tokens, **-94.5% net token reduction**, **+28.1% turn latency speedup** with **100% Zero-Loss accuracy retention**):
107
155
 
108
156
  | Benchmark Scenario | Task Complexity | Baseline Tokens | TokenSafe Tokens | Reduction | Turn Speedup | Accuracy |
109
157
  |---|---|---|---|---|---|---|
110
- | **Django ORM N+1 Fix** | Multi-file query refactoring | 14,280 | **1,120** | **-92.1%** | +12% faster | 100% Pass |
111
- | **FastAPI Async Race** | Concurrency bug investigation | 8,640 | **2,940** | **-65.9%** | +10% faster | 100% Pass |
112
- | **TypeScript Redux Vault** | Full AST symbol refactoring | 18,400 | **2,130** | **-88.4%** | +9% faster | 100% Pass |
113
- | **Stuck Command Loop** | Subprocess infinite loop | 22,100 | **2,400** | **-89.1%** | Stopped loop | 100% Pass |
114
- | **Heavy Rewrite Guard** | Whole-file write attempt | 11,300 | **4,310** | **-61.8%** | Forced edit_file | 100% Pass |
158
+ | **Zero-Token Architecture Discovery** | Full repo God Node indexing | 49,716 | **486** | **-99.0%** | **6 ➔ 1 turns (+83%)** | 100% Pass |
159
+ | **Graph-Guided AST Symbol Slicing** | Target function + 1-hop callees | 8,016 | **451** | **-94.4%** | **4 ➔ 2 turns (+50%)** | 100% Pass |
160
+ | **Monorepo Lockfile Grep Leak** | `git grep` across lockfiles | 10,111 | **491** | **-95.1%** | 2 turns | 100% Pass |
161
+ | **Monorepo Lockfile Git Diff** | Monorepo branch diff | 18,911 | **761** | **-96.0%** | 2 turns | 100% Pass |
162
+ | **Multi-Turn History Compaction** | 8-turn session history fold | 31,010 | **3,130** | **-89.9%** | 8 turns | 100% Pass |
163
+ | **Race Condition / Distributed Lock** | AST query & Redis redlock | 5,074 | **404** | **-92.0%** | **4 ➔ 3 turns (+25%)** | 100% Pass |
164
+ | **OAuth JWT Expiration Triage** | Controller bug investigation | 3,757 | **401** | **-89.3%** | **3 ➔ 2 turns (+33%)** | 100% Pass |
165
+ | **CI Test Failure Extraction** | Full test log & stack trace | 5,009 | **1,127** | **-77.5%** | 3 turns | 100% Pass |
115
166
 
116
167
  ---
117
168
 
@@ -120,8 +171,8 @@ Verified across 5 real-world production scenarios:
120
171
  | Tier | Price | Highlights |
121
172
  |---|---|---|
122
173
  | **Hacker (Open-Core)** | **$0** (Free Forever) | 100k tokens/mo, Local Regex compactor, use own DeepSeek / Gemini key |
123
- | **Solo Developer** | **$9 / month** | **7-Day Free Trial**, Unlimited Managed DeepSeek-Flash / Gemini Flash-Lite, AST Prefetcher, Output Guards |
124
- | **Engineering Team** | **$29 / dev / mo** | **7-Day Free Trial**, Team Budget Caps, Centralized Ledger, B2B Docker Proxy |
174
+ | **Solo Developer** | **$9 / month** | **7-Day Free Trial**, Unlimited Compression, Subagent Firewall, Context Window Governor, Prompt Cache Normalizer, Output Guards |
175
+ | **Engineering Team** | **$29 / dev / mo** | **7-Day Free Trial**, Everything in Solo + Friday Team ROI Digest & Leaderboards, Team Seat Quotas, Centralized Ledger, B2B Docker Proxy |
125
176
  | **Enterprise** | Custom | On-Premise Nuitka C-compiled Docker Proxy, Custom Compliance, SAML SSO |
126
177
 
127
178
  👉 **[Start your 7-Day Free Trial on our website](https://tokensafe.dev#pricing)**
@@ -137,22 +188,141 @@ tokensafe graph
137
188
  # Generate compact tokensafe-out/API_SURFACE.md interface snapshot
138
189
  tokensafe map
139
190
 
191
+ # Run environment health check and audit MCP/skill context token tax
192
+ tokensafe doctor
193
+
140
194
  # View live savings dashboard in your terminal
141
195
  tokensafe stats
142
196
 
143
197
  # Open interactive Apple dark-mode HTML dashboard
144
198
  tokensafe html
145
199
 
200
+ # Generate or preview Friday team ROI digest email
201
+ tokensafe digest
202
+
203
+ # Manage or disable high-overhead MCP tools
204
+ tokensafe mcp list
205
+ tokensafe mcp disable <server>
206
+
207
+ # Optimize SQLite metrics storage
208
+ tokensafe vacuum
209
+
146
210
  # Run the 5-scenario benchmark suite
147
211
  tokensafe benchmark
148
212
 
149
- # Run the local transparent AI proxy (127.0.0.1:8765/v1)
213
+ # Run the local transparent AI proxy (0.0.0.0:8765/v1)
150
214
  tokensafe proxy
151
215
 
152
- # Activate your Pro License key
153
- tokensafe activate TS1.eyJlbWFpbCI6...
216
+ # Activate your Pro License key (TS2 Asymmetric Ed25519 Key)
217
+ tokensafe activate TS2.eyJlbWFpbCI6...
154
218
  ```
155
219
 
220
+ ---
221
+
222
+ ## 🐳 Docker Deployment (Multi-Provider Support)
223
+
224
+ TokenSafe is fully containerized with a hardened multi-stage production Docker image, non-root security (`uid: 1000`), and native multi-provider LLM routing.
225
+
226
+ ### 1. Multi-Provider Environment Keys
227
+
228
+ You can configure any or all of your preferred LLM provider keys:
229
+
230
+ | Environment Variable | Provider Supported | Default Model |
231
+ |---|---|---|
232
+ | `OPENAI_API_KEY` | OpenAI API | `gpt-4o-mini` |
233
+ | `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
+ | `TOKENSAFE_UPSTREAM_KEY` | Unified / Custom Gateway | Custom Upstream |
237
+
238
+ ### 2. Docker Compose Quickstart
239
+
240
+ Run TokenSafe as a centralized microservice or team gateway:
241
+
242
+ ```yaml
243
+ version: '3.8'
244
+
245
+ services:
246
+ tokensafe:
247
+ build:
248
+ context: .
249
+ dockerfile: Dockerfile
250
+ container_name: tokensafe
251
+ restart: unless-stopped
252
+ ports:
253
+ - "8765:8765"
254
+ environment:
255
+ - TOKENSAFE_HOST=0.0.0.0
256
+ - TOKENSAFE_PORT=8765
257
+ - TOKENSAFE_DATA_DIR=/app/data
258
+ # Choose your provider(s):
259
+ - DEEPSEEK_API_KEY=${DEEPSEEK_API_KEY:-}
260
+ - OPENAI_API_KEY=${OPENAI_API_KEY:-}
261
+ - ANTHROPIC_API_KEY=${ANTHROPIC_API_KEY:-}
262
+ - GEMINI_API_KEY=${GEMINI_API_KEY:-}
263
+ - TOKENSAFE_LICENSE_KEY=${TOKENSAFE_LICENSE_KEY:-}
264
+ volumes:
265
+ - ./data:/app/data
266
+ healthcheck:
267
+ test: ["CMD", "python3", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8765/api/health')"]
268
+ interval: 30s
269
+ timeout: 5s
270
+ retries: 3
271
+ ```
272
+
273
+ Start the container in detached mode:
274
+ ```bash
275
+ docker compose up -d
276
+ ```
277
+
278
+ ### 3. Verification & Live SSE Streaming
279
+
280
+ - **Health check**: `curl http://localhost:8765/api/health`
281
+ - **Live SSE Event Stream**: `curl -N http://localhost:8765/api/events`
282
+ - **Point your AI Agents**: Configure your IDE or Agent to use `http://localhost:8765/v1` as the upstream base URL.
283
+
284
+ ---
285
+
286
+ ## 🔒 Security Architecture & Cloud API Endpoints
287
+
288
+ TokenSafe Cloud Backend enforces enterprise zero-trust security across all communications:
289
+
290
+ ### 1. Cryptographic Authentication & Licensing
291
+ - **Asymmetric RFC 8032 Ed25519 Signatures (`TS2.*`)**: Client instances verify digital signatures offline using an embedded 32-byte public key. The private signing key never leaves the secure cloud enclave.
292
+ - **JWT Session Tokens**: Cloud endpoints authenticate sessions via standard HS256 JWT bearer tokens or Clerk session tokens.
293
+ - **Dual Bearer Support**: Client endpoints accept either a signed license key (`TS2.*` / `TS1.*`) or a JWT in the `Authorization: Bearer <token>` header.
294
+ - **Zero Hardcoded Secrets**: All SMTP, Stripe, Admin, and signing keys are strictly injected via environment variables.
295
+
296
+ ### 2. Cloud API Endpoint Reference
297
+
298
+ | Method | Endpoint | Auth Required | Headers / Parameters | Description |
299
+ |---|---|---|---|---|
300
+ | `GET` | `/api/health` | Public | None | Healthcheck and service version status. |
301
+ | `GET` | `/api/events` | Public | SSE `text/event-stream` | Real-time Server-Sent Events stream for live dashboard telemetry. |
302
+ | `GET` | `/api/dashboard` | **Bearer Auth** | `Authorization: Bearer <jwt\|key>` or `?license=<key>` | Authenticated user metrics, token savings, and license status. |
303
+ | `GET` | `/api/digest/preview` | **Bearer Auth** | `Authorization: Bearer <jwt\|key>` or `?team_id=<id>` | Previews current weekly team ROI digest (HTML / JSON). |
304
+ | `POST` | `/api/team/seat/create` | **Bearer Auth** | `Authorization: Bearer <jwt\|key>`, JSON `{ owner_email, member_email }` | Generates a cryptographically signed seat license for a team member. |
305
+ | `POST` | `/api/team/seat/revoke` | **Bearer Auth** | `Authorization: Bearer <jwt\|key>`, JSON `{ owner_email, license_key }` | Revokes an active team seat license key. |
306
+ | `POST` | `/api/telemetry/sync` | **License Auth** | JSON `{ license_key, email, events: [...] }` | Syncs batch telemetry events (enforces max 50 events/batch). |
307
+ | `POST` | `/webhook/stripe` | **HMAC Sig** | `Stripe-Signature: t=...,v1=...` | Verifies Stripe webhook payload against `STRIPE_WEBHOOK_SECRET`. |
308
+ | `GET` | `/api/admin/overview` | **Admin Only** | `X-Admin-Secret` or Admin JWT | Global overview of MRR, seats, active licenses, and system health. |
309
+ | `POST` | `/api/admin/digest/send` | **Admin Only** | `X-Admin-Secret` or Admin JWT | Dispatches scheduled Friday weekly ROI digest emails to team leads. |
310
+ | `POST` | `/api/admin/license/issue`| **Admin Only** | `X-Admin-Secret` or Admin JWT | Manually issues or provisions a custom tier license. |
311
+ | `POST` | `/api/admin/license/revoke`| **Admin Only**| `X-Admin-Secret` or Admin JWT | Immediately revokes a license. |
312
+ | `POST` | `/api/admin/license/extend`| **Admin Only**| `X-Admin-Secret` or Admin JWT | Extends an active license duration. |
313
+
314
+ ### 3. Server Configuration & Environment Variables
315
+
316
+ | Variable | Required | Default / Description |
317
+ |---|---|---|
318
+ | `TOKENSAFE_PRIVATE_KEY` | Production | 64-character hex Ed25519 seed for issuing `TS2.` licenses. |
319
+ | `ADMIN_SECRET_KEY` | Yes | High-entropy secret for administrative API access (`X-Admin-Secret`). |
320
+ | `ADMIN_EMAILS` | Optional | Comma-separated admin emails (e.g. `nekosin4eg@gmail.com`). |
321
+ | `STRIPE_WEBHOOK_SECRET` | Production | Webhook secret (`whsec_...`) used to verify Stripe webhooks. |
322
+ | `SMTP_PASS` | Production | Password/token for transactional mail delivery via ImprovMX SMTP. |
323
+ | `JWT_SECRET` | Optional | Shared HMAC secret for verifying custom JWT tokens. |
324
+
325
+
156
326
  ---
157
327
 
158
328
  ## 🧪 Unit Testing
@@ -180,6 +350,8 @@ MIT License. Commercial enterprise licenses available for on-premise B2B deploym
180
350
  agy-token-optimizer/
181
351
  ├── plugin.json # Antigravity plugin manifest
182
352
  ├── hooks.json # Lifecycle hook declarations (PreInvocation, PreToolUse, PostToolUse)
353
+ ├── Dockerfile # Hardened multi-stage container deployment
354
+ ├── docker-compose.yml # Production Docker compose with multi-provider routing
183
355
  ├── rules/
184
356
  │ └── AGENTS.md # TOCP Protocol directives for LLM (prompt-cached)
185
357
  ├── skills/
@@ -188,17 +360,29 @@ agy-token-optimizer/
188
360
  ├── proto/
189
361
  │ └── tocp.proto # Protocol Buffers contract
190
362
  ├── src/
363
+ │ ├── cache_normalizer.py # Prompt Cache Prefix Normalizer (Anthropic & DeepSeek)
364
+ │ ├── governor.py # Context Window Governor & Token Ceiling (Cascading reduction)
365
+ │ ├── agent_firewall.py # Cross-Agent Deduplication Cache (Subagent Firewall)
366
+ │ ├── diff_slicer.py # AST Diff Slicer & Lockfile Stripper (`git diff -U2`)
367
+ │ ├── weekly_digest.py # Friday Team ROI Digest & Engineer Leaderboard
368
+ │ ├── environment_auditor.py # MCP Server & Skill context token tax auditor
369
+ │ ├── proxy.py # Multi-provider transparent AI proxy & SSE broadcaster
370
+ │ ├── graph_engine.py # Sub-30ms AST parser, call graphs & God Node centrality
191
371
  │ ├── tokenizer.py # Zero-dependency calibrated BPE token counter
192
372
  │ ├── compactor.py # Semantic compactor (Natural Language -> TOCP S-Expr)
193
373
  │ ├── slicer.py # AST & Line windowing tool optimizer
194
374
  │ ├── metrics.py # Persistent SQLite metrics engine
195
- │ └── dashboard.py # Visual ANSI terminal & Markdown generator
375
+ │ ├── dashboard.py # Visual ANSI terminal, Markdown & reactive SSE web dashboard
376
+ │ ├── license_manager.py # Ed25519 cryptographic license verification
377
+ │ ├── mailer.py # Transactional email & Friday ROI digest dispatcher
378
+ │ └── cloud_backend.py # Cloud REST backend, telemetry sync & Stripe webhooks
196
379
  ├── hooks/
197
380
  │ ├── pre_invocation.py # PreInvocation hook entry point
198
381
  │ ├── pre_tool_use.py # PreToolUse hook entry point
199
382
  │ └── post_tool_use.py # PostToolUse hook entry point
383
+ ├── frontend/ # Modern React / Vite / Tailwind Web App & Dashboard
200
384
  ├── bin/
201
- │ └── agy-tokens # Executable CLI
385
+ │ └── agy-tokens # Executable CLI (`tokensafe`)
202
386
  ├── tests/ # Unit test suite (100% passing)
203
387
  ├── install.sh # One-click installer for Antigravity
204
388
  └── README.md
package/bin/agy-tokens CHANGED
@@ -3,9 +3,13 @@
3
3
  CLI entry point for Antigravity Token Optimizer.
4
4
  Usage:
5
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
6
8
  agy-tokens html Generate and open interactive browser dashboard
7
9
  agy-tokens test "<prompt>" Test prompt compression and view savings
8
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
9
13
  agy-tokens reset Reset metrics database
10
14
  """
11
15
 
@@ -56,7 +60,23 @@ def main():
56
60
 
57
61
  elif command in ("setup", "install"):
58
62
  from src.installer import AgentInstaller
59
- AgentInstaller.run_interactive()
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()
60
80
 
61
81
  elif command == "proxy":
62
82
  from src.proxy import run_proxy
@@ -64,8 +84,39 @@ def main():
64
84
  run_proxy(port)
65
85
 
66
86
  elif command == "mcp":
67
- from src.mcp_server import run_mcp_server
68
- run_mcp_server()
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())
69
120
 
70
121
  elif command == "activate":
71
122
  from src.license_manager import LicenseManager
@@ -136,6 +187,107 @@ def main():
136
187
  print(f"\033[1mCompacted Tokens:\033[0m {res['compact_tokens']}")
137
188
  print(f"\033[1mTokens Saved:\033[0m \033[32m\033[1m+{res['saved_tokens']} tokens\033[0m ({render_bar(res['reduction_pct'])})\n")
138
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
+
139
291
  elif command == "reset":
140
292
  confirm = input("Are you sure you want to reset all token metrics? [y/N]: ").strip().lower()
141
293
  if confirm == "y":
@@ -146,7 +298,7 @@ def main():
146
298
 
147
299
  else:
148
300
  print(f"Unknown command: {command}")
149
- print("Available commands: stats, html, benchmark, setup, proxy, mcp, test, markdown, reset")
301
+ print("Available commands: stats, doctor, mcp, html, benchmark, setup, proxy, test, markdown, prune, vacuum, reset")
150
302
  sys.exit(1)
151
303
 
152
304
  if __name__ == "__main__":
package/bin/tokensafe.js CHANGED
@@ -45,6 +45,7 @@ Commands:
45
45
  npx tokensafe map Generate tokensafe-out/API_SURFACE.md interface snapshot
46
46
  npx tokensafe stats Show token economy savings & performance metrics
47
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
48
49
  npx tokensafe activate Activate commercial or team seat license key
49
50
  npx tokensafe --help Show this help screen
50
51
  `);
@@ -97,6 +98,12 @@ switch (command) {
97
98
  scriptArgs = args.slice(1);
98
99
  break;
99
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
+
100
107
  case 'install':
101
108
  case 'init':
102
109
  scriptPath = path.join(ROOT_DIR, 'src', 'installer.py');
@@ -19,6 +19,7 @@ sys.path.insert(0, PROJECT_ROOT)
19
19
  from src.compactor import PromptCompactor
20
20
  from src.history_compactor import HistoryCompactor
21
21
  from src.metrics import MetricsTracker
22
+ from src.environment_auditor import EnvironmentAuditor
22
23
 
23
24
  def main():
24
25
  try:
@@ -40,6 +41,22 @@ def main():
40
41
  tracker = MetricsTracker()
41
42
  inject_steps = []
42
43
 
44
+ # 0. Context Bloat Audit (Fires on first invocation)
45
+ if invocation_num <= 1:
46
+ try:
47
+ bloat_warning = EnvironmentAuditor.get_bloat_warning()
48
+ if bloat_warning:
49
+ inject_steps.append({
50
+ "systemMessage": {
51
+ "systemMessage": "",
52
+ "metadata": {
53
+ "user_markdown": bloat_warning
54
+ }
55
+ }
56
+ })
57
+ except Exception:
58
+ pass
59
+
43
60
  # 1. Prompt Compaction
44
61
  if last_user_input and len(last_user_input.strip()) >= 5:
45
62
  compaction = PromptCompactor.compact(last_user_input)
@@ -82,17 +99,29 @@ def main():
82
99
  transcript_path, invocation_num
83
100
  )
84
101
  if folded_text and stats.get("saved_tokens", 0) > 0:
85
- tracker.record_event(
86
- session_id=conversation_id,
87
- event_type="HISTORY_FOLD",
88
- original_tokens=orig_hist_tokens,
89
- optimized_tokens=folded_tokens,
90
- details={
91
- "turns": invocation_num,
92
- "read_files": stats.get("read_files_count", 0),
93
- "edited_files": stats.get("edited_files_count", 0)
94
- }
95
- )
102
+ # Prevent quadratic double-counting: only record incremental new history mass
103
+ prev_event = tracker.get_last_event(session_id=conversation_id, event_type="HISTORY_FOLD")
104
+ prev_orig = 0
105
+ if prev_event and isinstance(prev_event.get("details"), dict):
106
+ prev_orig = prev_event["details"].get("total_accum_orig", 0) or prev_event.get("original_tokens", 0)
107
+
108
+ delta_orig = max(0, orig_hist_tokens - prev_orig)
109
+ # Record first fold or incremental accumulation when delta >= 1500 tokens
110
+ if prev_event is None or delta_orig >= 1500:
111
+ inc_orig = orig_hist_tokens if prev_event is None else delta_orig
112
+ inc_saved = max(0, inc_orig - folded_tokens)
113
+ tracker.record_event(
114
+ session_id=conversation_id,
115
+ event_type="HISTORY_FOLD",
116
+ original_tokens=inc_orig,
117
+ optimized_tokens=folded_tokens,
118
+ details={
119
+ "turns": invocation_num,
120
+ "total_accum_orig": orig_hist_tokens,
121
+ "read_files": stats.get("read_files_count", 0),
122
+ "edited_files": stats.get("edited_files_count", 0)
123
+ }
124
+ )
96
125
 
97
126
  hist_badge = (
98
127
  f"⚡ **History Compactor:** Stabilized {orig_hist_tokens:,} tokens of previous turns — "
@@ -22,6 +22,8 @@ from src.command_sanitizer import CommandSanitizer
22
22
  from src.loop_detector import LoopDetector
23
23
  from src.metrics import MetricsTracker
24
24
  from src.tokenizer import count_tokens
25
+ from src.agent_firewall import AgentFirewall
26
+ from src.diff_slicer import DiffSlicer
25
27
 
26
28
  def main():
27
29
  try:
@@ -105,7 +107,17 @@ def main():
105
107
  start_line = args.get("StartLine")
106
108
  end_line = args.get("EndLine")
107
109
 
108
- # Step 3A: If model explicitly specified line range, respect it
110
+ # Step 3A: Subagent Firewall — Check if file was already read in active session
111
+ is_hit, cached_text, saved_dedup = AgentFirewall.check_cache(
112
+ session_id=conversation_id,
113
+ file_path=path,
114
+ tracker=tracker
115
+ )
116
+ if is_hit and saved_dedup > 0:
117
+ # Point to cached skeleton view or let tool proceed with cached metadata
118
+ response["reason"] = f"Token Optimizer: Subagent Firewall dedup hit (Saved ~{saved_dedup} tokens)"
119
+
120
+ # Step 3B: If model explicitly specified line range, respect it
109
121
  if start_line is not None and end_line is not None:
110
122
  print(json.dumps(response))
111
123
  return
@@ -178,10 +190,18 @@ def main():
178
190
  print(json.dumps(response))
179
191
  return
180
192
 
181
- # 4. run_command Optimization (Command Sanitizer)
193
+ # 4. run_command Optimization (Command Sanitizer & Diff Slicer)
182
194
  elif tool_name == "run_command":
183
195
  cmd = args.get("CommandLine", "")
184
- new_cmd, est_saved, reason = CommandSanitizer.sanitize(cmd)
196
+ # Check AST Diff Slicer first
197
+ diff_cmd, diff_saved, diff_reason = DiffSlicer.optimize_git_diff_command(cmd)
198
+ if diff_cmd:
199
+ new_cmd = diff_cmd
200
+ est_saved = diff_saved
201
+ reason = diff_reason
202
+ else:
203
+ new_cmd, est_saved, reason = CommandSanitizer.sanitize(cmd)
204
+
185
205
  if new_cmd and est_saved > 0:
186
206
  response["overwrite"] = {"CommandLine": new_cmd}
187
207
  response["reason"] = f"Token Optimizer: {reason} (Saved ~{est_saved} tokens)"