tokensafe 1.3.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 +148 -6
- package/bin/agy-tokens +152 -4
- package/hooks/pre_invocation.py +17 -0
- package/hooks/pre_tool_use.py +23 -3
- package/package.json +2 -2
- package/plugin.json +1 -1
- package/rules/AGENTS.md +6 -0
- package/skills/token-optimizer/SKILL.md +1 -0
- package/src/__init__.py +1 -1
- package/src/agent_firewall.py +146 -0
- package/src/cache_normalizer.py +105 -0
- package/src/dashboard.py +41 -6
- package/src/diff_slicer.py +120 -0
- package/src/environment_auditor.py +259 -0
- package/src/governor.py +166 -0
- package/src/installer.py +104 -33
- package/src/mcp_server.py +35 -1
- package/src/metrics.py +216 -21
- package/src/proxy.py +142 -19
- package/src/version_checker.py +1 -1
- package/src/weekly_digest.py +305 -0
package/README.md
CHANGED
|
@@ -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
|
|
@@ -123,8 +171,8 @@ Verified across 8 real-world production software engineering scenarios (131,604
|
|
|
123
171
|
| Tier | Price | Highlights |
|
|
124
172
|
|---|---|---|
|
|
125
173
|
| **Hacker (Open-Core)** | **$0** (Free Forever) | 100k tokens/mo, Local Regex compactor, use own DeepSeek / Gemini key |
|
|
126
|
-
| **Solo Developer** | **$9 / month** | **7-Day Free Trial**, Unlimited
|
|
127
|
-
| **Engineering Team** | **$29 / dev / mo** | **7-Day Free Trial**, Team
|
|
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 |
|
|
128
176
|
| **Enterprise** | Custom | On-Premise Nuitka C-compiled Docker Proxy, Custom Compliance, SAML SSO |
|
|
129
177
|
|
|
130
178
|
👉 **[Start your 7-Day Free Trial on our website](https://tokensafe.dev#pricing)**
|
|
@@ -140,16 +188,29 @@ tokensafe graph
|
|
|
140
188
|
# Generate compact tokensafe-out/API_SURFACE.md interface snapshot
|
|
141
189
|
tokensafe map
|
|
142
190
|
|
|
191
|
+
# Run environment health check and audit MCP/skill context token tax
|
|
192
|
+
tokensafe doctor
|
|
193
|
+
|
|
143
194
|
# View live savings dashboard in your terminal
|
|
144
195
|
tokensafe stats
|
|
145
196
|
|
|
146
197
|
# Open interactive Apple dark-mode HTML dashboard
|
|
147
198
|
tokensafe html
|
|
148
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
|
+
|
|
149
210
|
# Run the 5-scenario benchmark suite
|
|
150
211
|
tokensafe benchmark
|
|
151
212
|
|
|
152
|
-
# Run the local transparent AI proxy (
|
|
213
|
+
# Run the local transparent AI proxy (0.0.0.0:8765/v1)
|
|
153
214
|
tokensafe proxy
|
|
154
215
|
|
|
155
216
|
# Activate your Pro License key (TS2 Asymmetric Ed25519 Key)
|
|
@@ -158,6 +219,70 @@ tokensafe activate TS2.eyJlbWFpbCI6...
|
|
|
158
219
|
|
|
159
220
|
---
|
|
160
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
|
+
|
|
161
286
|
## 🔒 Security Architecture & Cloud API Endpoints
|
|
162
287
|
|
|
163
288
|
TokenSafe Cloud Backend enforces enterprise zero-trust security across all communications:
|
|
@@ -173,12 +298,15 @@ TokenSafe Cloud Backend enforces enterprise zero-trust security across all commu
|
|
|
173
298
|
| Method | Endpoint | Auth Required | Headers / Parameters | Description |
|
|
174
299
|
|---|---|---|---|---|
|
|
175
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. |
|
|
176
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). |
|
|
177
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. |
|
|
178
305
|
| `POST` | `/api/team/seat/revoke` | **Bearer Auth** | `Authorization: Bearer <jwt\|key>`, JSON `{ owner_email, license_key }` | Revokes an active team seat license key. |
|
|
179
306
|
| `POST` | `/api/telemetry/sync` | **License Auth** | JSON `{ license_key, email, events: [...] }` | Syncs batch telemetry events (enforces max 50 events/batch). |
|
|
180
307
|
| `POST` | `/webhook/stripe` | **HMAC Sig** | `Stripe-Signature: t=...,v1=...` | Verifies Stripe webhook payload against `STRIPE_WEBHOOK_SECRET`. |
|
|
181
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. |
|
|
182
310
|
| `POST` | `/api/admin/license/issue`| **Admin Only** | `X-Admin-Secret` or Admin JWT | Manually issues or provisions a custom tier license. |
|
|
183
311
|
| `POST` | `/api/admin/license/revoke`| **Admin Only**| `X-Admin-Secret` or Admin JWT | Immediately revokes a license. |
|
|
184
312
|
| `POST` | `/api/admin/license/extend`| **Admin Only**| `X-Admin-Secret` or Admin JWT | Extends an active license duration. |
|
|
@@ -222,6 +350,8 @@ MIT License. Commercial enterprise licenses available for on-premise B2B deploym
|
|
|
222
350
|
agy-token-optimizer/
|
|
223
351
|
├── plugin.json # Antigravity plugin manifest
|
|
224
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
|
|
225
355
|
├── rules/
|
|
226
356
|
│ └── AGENTS.md # TOCP Protocol directives for LLM (prompt-cached)
|
|
227
357
|
├── skills/
|
|
@@ -230,17 +360,29 @@ agy-token-optimizer/
|
|
|
230
360
|
├── proto/
|
|
231
361
|
│ └── tocp.proto # Protocol Buffers contract
|
|
232
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
|
|
233
371
|
│ ├── tokenizer.py # Zero-dependency calibrated BPE token counter
|
|
234
372
|
│ ├── compactor.py # Semantic compactor (Natural Language -> TOCP S-Expr)
|
|
235
373
|
│ ├── slicer.py # AST & Line windowing tool optimizer
|
|
236
374
|
│ ├── metrics.py # Persistent SQLite metrics engine
|
|
237
|
-
│
|
|
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
|
|
238
379
|
├── hooks/
|
|
239
380
|
│ ├── pre_invocation.py # PreInvocation hook entry point
|
|
240
381
|
│ ├── pre_tool_use.py # PreToolUse hook entry point
|
|
241
382
|
│ └── post_tool_use.py # PostToolUse hook entry point
|
|
383
|
+
├── frontend/ # Modern React / Vite / Tailwind Web App & Dashboard
|
|
242
384
|
├── bin/
|
|
243
|
-
│ └── agy-tokens # Executable CLI
|
|
385
|
+
│ └── agy-tokens # Executable CLI (`tokensafe`)
|
|
244
386
|
├── tests/ # Unit test suite (100% passing)
|
|
245
387
|
├── install.sh # One-click installer for Antigravity
|
|
246
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,19 @@ def main():
|
|
|
56
60
|
|
|
57
61
|
elif command in ("setup", "install"):
|
|
58
62
|
from src.installer import AgentInstaller
|
|
59
|
-
|
|
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()
|
|
60
76
|
|
|
61
77
|
elif command in ("update", "upgrade"):
|
|
62
78
|
from src.installer import AgentInstaller
|
|
@@ -68,8 +84,39 @@ def main():
|
|
|
68
84
|
run_proxy(port)
|
|
69
85
|
|
|
70
86
|
elif command == "mcp":
|
|
71
|
-
|
|
72
|
-
|
|
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())
|
|
73
120
|
|
|
74
121
|
elif command == "activate":
|
|
75
122
|
from src.license_manager import LicenseManager
|
|
@@ -140,6 +187,107 @@ def main():
|
|
|
140
187
|
print(f"\033[1mCompacted Tokens:\033[0m {res['compact_tokens']}")
|
|
141
188
|
print(f"\033[1mTokens Saved:\033[0m \033[32m\033[1m+{res['saved_tokens']} tokens\033[0m ({render_bar(res['reduction_pct'])})\n")
|
|
142
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
|
+
|
|
143
291
|
elif command == "reset":
|
|
144
292
|
confirm = input("Are you sure you want to reset all token metrics? [y/N]: ").strip().lower()
|
|
145
293
|
if confirm == "y":
|
|
@@ -150,7 +298,7 @@ def main():
|
|
|
150
298
|
|
|
151
299
|
else:
|
|
152
300
|
print(f"Unknown command: {command}")
|
|
153
|
-
print("Available commands: stats, html, benchmark, setup, proxy,
|
|
301
|
+
print("Available commands: stats, doctor, mcp, html, benchmark, setup, proxy, test, markdown, prune, vacuum, reset")
|
|
154
302
|
sys.exit(1)
|
|
155
303
|
|
|
156
304
|
if __name__ == "__main__":
|
package/hooks/pre_invocation.py
CHANGED
|
@@ -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)
|
package/hooks/pre_tool_use.py
CHANGED
|
@@ -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:
|
|
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
|
-
|
|
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)"
|
package/package.json
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tokensafe",
|
|
3
|
-
"version": "1.3.
|
|
3
|
+
"version": "1.3.1",
|
|
4
4
|
"description": "Autonomous Zero-Loss Token Economy & Context Optimizer for AI Coding Agents",
|
|
5
5
|
"main": "bin/tokensafe.js",
|
|
6
6
|
"bin": {
|
|
7
|
-
"tokensafe": "
|
|
7
|
+
"tokensafe": "bin/tokensafe.js"
|
|
8
8
|
},
|
|
9
9
|
"files": [
|
|
10
10
|
"bin/tokensafe.js",
|
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.1",
|
|
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": {
|
package/rules/AGENTS.md
CHANGED
|
@@ -29,3 +29,9 @@ Execute the specified action directly based on these extracted parameters.
|
|
|
29
29
|
1. **Never Crawl with Raw Grep/Find**: Before executing exploratory searches or answering architecture questions, inspect `tokensafe:get_architecture_graph` or `tokensafe-out/API_SURFACE.md`. It provides project God Nodes and dependencies in < 250 tokens without file crawling.
|
|
30
30
|
2. **Graph-Guided File Reading**: When inspecting code implementations, call `tokensafe:smart_read_file` with the targeted `symbol`. It preserves full executable bodies for the target function and its 1-hop callees while folding inert code into signatures (-85% to -92% tokens).
|
|
31
31
|
3. **Bounded Reads**: Never call `read_file` without `StartLine`/`EndLine` on files > 100 lines unless inspecting a skeleton.
|
|
32
|
+
|
|
33
|
+
### 4. Turn Token Savings Footer (Proof-of-Savings)
|
|
34
|
+
At the end of your response for any turn where tools were executed, files were inspected, commands were sanitized, or prompts were compacted, append a compact 1-line footer:
|
|
35
|
+
`⚡ **TokenSafe Turn Savings**: +<tokens> tokens saved on this turn (<breakdown>) | Cumulative Total: <total> tokens`
|
|
36
|
+
Example:
|
|
37
|
+
`⚡ **TokenSafe Turn Savings**: +3,520 tokens (~88%) | Cumulative Total: 3.04M tokens ($4.56)`
|
|
@@ -23,6 +23,7 @@ This skill provides autonomous AI coding assistants with deterministic, zero-tok
|
|
|
23
23
|
| `tokensafe:get_api_surface` | Exports public signatures and types for the entire project. | ~300-600 tokens |
|
|
24
24
|
| `tokensafe:smart_read_file` | Reads `path` focusing on `symbol` + 1-hop dependencies; folds inert code into signatures. | -85% to -92% vs raw read |
|
|
25
25
|
| `tokensafe:sanitize_command` | Strips lockfiles, limits test/build output, and prevents context poisoning. | Saves 10k-50k tokens |
|
|
26
|
+
| `tokensafe:slice_diff` | Slices unified git diffs, eliminates lockfiles, and minimizes hunk context lines. | -50% to -80% |
|
|
26
27
|
| `tokensafe:compress_prompt` | Compresses verbose user instructions into lean TOCP S-expressions. | -40% to -65% |
|
|
27
28
|
| `tokensafe:get_token_savings_metrics` | Returns total tokens saved, USD value, and breakdown by source. | ~100 tokens |
|
|
28
29
|
|
package/src/__init__.py
CHANGED