tokensafe 1.3.8 → 1.3.10

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
@@ -1,16 +1,31 @@
1
- # ⚡ TokenSafe (`tokensafe`)
2
-
3
- [![npm version](https://img.shields.io/npm/v/tokensafe.svg?color=CB3837)](https://www.npmjs.com/package/tokensafe)
4
- [![PyPI version](https://img.shields.io/pypi/v/tokensafe.svg?color=3775A9)](https://pypi.org/project/tokensafe/)
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-up_to_95%25_Savings-06B6D4.svg)](https://tokensafe.dev#benchmarks)
7
- [![Python: 3.10+](https://img.shields.io/badge/Python-3.10+-3B82F6.svg)](https://python.org)
8
- [![Trial: 7 Days Free](https://img.shields.io/badge/Trial-7_Days_Free-10B981.svg)](https://tokensafe.dev#pricing)
9
-
10
- > **Autonomous Zero-Loss Token Economy & Context Optimizer for AI Coding Agents.**
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
-
13
- 🌐 **Official Website:** [https://tokensafe.dev](https://tokensafe.dev)
1
+ <p align="center">
2
+ <img src="assets/logo.svg" alt="TokenSafe Logo" width="100" height="100" />
3
+ </p>
4
+
5
+ <h1 align="center">⚡ TokenSafe</h1>
6
+
7
+ <p align="center">
8
+ <b>Autonomous Zero-Loss Token Economy & Context Optimizer for AI Coding Agents</b><br>
9
+ Slashes LLM token costs by <b>up to 90%</b> with zero quality loss.<br>
10
+ Built for <b>Cursor, Claude Desktop, Google Antigravity, Windsurf & Cline</b>.
11
+ </p>
12
+
13
+ <p align="center">
14
+ <a href="https://github.com/NekoSin4eG/tokensafe/actions/workflows/test.yml"><img src="https://img.shields.io/github/actions/workflow/status/NekoSin4eG/tokensafe/test.yml?branch=main&label=tests&style=flat-square" alt="Tests"></a>
15
+ <a href="https://www.npmjs.com/package/tokensafe"><img src="https://img.shields.io/npm/v/tokensafe.svg?color=CB3837&style=flat-square" alt="npm"></a>
16
+ <a href="https://pypi.org/project/tokensafe/"><img src="https://img.shields.io/pypi/v/tokensafe.svg?color=3775A9&style=flat-square" alt="PyPI"></a>
17
+ <a href="https://github.com/NekoSin4eG/tokensafe/stargazers"><img src="https://img.shields.io/github/stars/NekoSin4eG/tokensafe?style=flat-square&color=yellow" alt="Stars"></a>
18
+ <a href="https://opensource.org/licenses/MIT"><img src="https://img.shields.io/badge/License-MIT-emerald.svg?style=flat-square" alt="License"></a>
19
+ <a href="https://tokensafe.dev#pricing"><img src="https://img.shields.io/badge/Trial-7_Days_Free-10B981.svg?style=flat-square" alt="Trial"></a>
20
+ </p>
21
+
22
+ <p align="center">
23
+ <a href="#-1-click-universal-install">Install</a> •
24
+ <a href="#-universal-mcp-server-configuration">MCP Setup</a> •
25
+ <a href="#-the-breakthrough-how-it-saves-6090-tokens">How It Works</a> •
26
+ <a href="#-pricing--plans">Pricing</a> •
27
+ <a href="https://tokensafe.dev">Official Website & Docs</a>
28
+ </p>
14
29
 
15
30
  ---
16
31
 
@@ -62,9 +77,9 @@ Traditional AI code interactions suffer from massive context bloat:
62
77
  - **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
78
  - **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
79
  - **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 (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).
80
+ - **TOCP Prompt Distillation:** Intercepts prompts and distills intent into lean S-Expressions (`-40% to -70%`). Solo & Team tiers include **Managed Cloud Distillation** out of the box via TokenSafe Cloud (`gemini-flash-lite-latest`) with **zero API keys required**. Free tier includes a zero-overhead 9-language Local Regex Compactor. Enterprise on-premise Docker deployments support custom private BYOK keys.
66
81
  - **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.
82
+ - **Three-Tier Distillation Cache:** Three-tier L1 In-Memory LRU + L2 Persistent SQLite cache (`metrics.db`) + L3 Shared Team Cloud Cache with normalized SHA-256 hashing guarantees sub-millisecond zero-cost replays for recurring developer commands.
68
83
  - **Shared Team Cache (L3 Cloud Monorepo Cache):** Synchronizes compiled prompt intents and AST skeletons across all developers and CI agents on an engineering team. Teammates querying the same files or command patterns get instant 0ms warm cache hits with zero LLM API calls.
69
84
  - **API Surface Map Generator:** Generates high-density `tokensafe-out/API_SURFACE.md` (~1.5k tokens) for instant agent codebase onboarding.
70
85
  - **Predictive Dependency Prefetcher:** Attaches imported symbol signatures to eliminate downstream exploratory `read_file` roundtrips.
@@ -133,36 +148,39 @@ How TokenSafe complements or supersedes static graph tools like **Graphify** (`g
133
148
 
134
149
  ---
135
150
 
136
- ## 🤖 Universal LLM Distillation Providers & Unit Economics Defense
151
+ ## 🤖 Prompt Distillation: Managed Cloud & Three-Tier Cache Architecture
137
152
 
138
- TokenSafe features an intelligent multi-provider prompt compiler that distills verbose developer prompts into lean TOCP S-Expressions (`-40% to -70% tokens`).
153
+ TokenSafe features an intelligent prompt compiler that distills verbose developer prompts into lean TOCP S-Expressions (`-40% to -70% tokens`).
139
154
 
140
- ### 1. Provider Priority & Economics Matrix
155
+ ### 1. Zero-Config Managed Cloud vs. Self-Hosted Docker BYOK
141
156
 
142
- | Provider | Recommended Model | Pricing (Input / Output) | Environment Variable | Priority |
157
+ | Deployment Mode | Supported Tier | Distillation Engine | Required API Keys | Cost & Setup |
143
158
  |---|---|---|---|---|
144
- | **Google Gemini** ⚡ | `gemini-flash-lite-latest` | **$0.075 / $0.30** / M (Free tier: 1,500 req/day) | `GEMINI_API_KEY` | **1 (Default / Lowest Cost)** |
145
- | **DeepSeek** | `deepseek-chat` / `deepseek-flash` | $0.14 / $0.60 / M | `DEEPSEEK_API_KEY` | 2 |
146
- | **OpenAI ChatGPT** | `gpt-4o-mini` | $0.15 / $0.60 / M | `OPENAI_API_KEY` | 3 |
147
- | **Anthropic Claude** | `claude-3-5-haiku-20241022` | $0.80 / $4.00 / M | `ANTHROPIC_API_KEY` | 4 |
148
- | **Custom / Unified** | Any OpenAI/Anthropic gateway | Custom | `TOKENSAFE_UPSTREAM_KEY` | 5 |
159
+ | **TokenSafe Cloud (SaaS)** ⚡ | **Solo Developer & Team** | **Google Gemini Flash-Lite** (`gemini-flash-lite-latest`) | **None (Zero Keys Required)** | **Included in subscription** (0ms config, unlimited neural distillation) |
160
+ | **Local Regex Compactor** | **Community (Free)** | **Deterministic Multilingual Regex** (9 languages) | **None** | **100% Free** (0ms latency, 0 external tokens, 500k tokens/mo) |
161
+ | **Self-Hosted Docker** 🐳 | **Enterprise / Team** | **BYOK Multi-Provider** (Gemini, DeepSeek, OpenAI, Claude) | `GEMINI_API_KEY`, `DEEPSEEK_API_KEY`, etc. | Private VPC on-premise container deployment |
149
162
 
150
- > **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.
163
+ > **Zero Configuration for Solo & Team**: You do not need to register for Google AI Studio, OpenAI, or DeepSeek API accounts. TokenSafe Cloud handles high-throughput neural distillation automatically with enterprise-grade sub-second turnaround.
151
164
 
152
- ### 2. Token Arbitrage Guard & Two-Tier Cache Architecture
165
+ ### 2. Token Arbitrage Guard & Three-Tier Cache Architecture
153
166
 
154
167
  To prevent compiler cost overhead from exceeding token savings, TokenSafe applies a 3-stage defense:
155
168
 
156
- 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}$).
157
- 2. **Output Token Ceiling (`distill_max_tokens: 60`)**: Caps LLM output at 60 tokens, eliminating verbose chain-of-thought inflation and token arbitrage loss.
158
- 3. **Two-Tier Distillation Cache**:
159
- - **Tier 1 (In-Memory LRU)**: Sub-millisecond instant hit for active session loops.
160
- - **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.
169
+ 1. **Smart Gating Threshold (`llm_distill_min_tokens: 100`)**: Prompts under 100 tokens bypass cloud calls entirely and use instant zero-cost local regex heuristics ($0$ tokens, $< 1\text{ms}$).
170
+ 2. **Output Token Ceiling (`distill_max_tokens: 60`)**: Caps distillation output at 60 tokens, eliminating verbose chain-of-thought inflation and token arbitrage loss.
171
+ 3. **Three-Tier Distillation Cache Hierarchy**:
172
+ - **L1 (In-Memory LRU)**: Sub-millisecond instant hit for active developer session loops.
173
+ - **L2 (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.
174
+ - **L3 (Shared Team Cache)**: *Team Tier.* Synchronizes compiled prompt intents and AST skeletons to TokenSafe Cloud (`/api/team/cache`). When one engineer or CI runner executes a prompt or reads a file, all teammates immediately hit warm 0ms cache.
161
175
 
162
- ### 3. Configuration (`data/config.json`)
176
+ ### 3. Configuration & Provider Inspection
163
177
 
164
- Configure your provider preferences and models directly:
178
+ Check your license status, active distillation mode, and cache stats anytime:
179
+ ```bash
180
+ tokensafe providers
181
+ ```
165
182
 
183
+ For custom self-hosted environments (`TOKENSAFE_SELF_HOSTED=1`), configure your preferred provider in `data/config.json`:
166
184
  ```json
167
185
  {
168
186
  "preferred_provider": "gemini",
@@ -199,12 +217,12 @@ Verified across 8 real-world production software engineering scenarios (131,604
199
217
 
200
218
  ## 💎 Pricing & 7-Day Free Trial
201
219
 
202
- | Tier | Price | Highlights |
203
- |---|---|---|
204
- | **Hacker (Open-Core)** | **$0** (Free Forever) | 100k tokens/mo, Local Regex compactor, use own DeepSeek / Gemini key |
205
- | **Solo Developer** | **$9 / month** | **7-Day Free Trial**, Unlimited Compression, Subagent Firewall, Context Window Governor, Prompt Cache Normalizer, Output Guards |
206
- | **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 |
207
- | **Enterprise** | Custom | On-Premise Nuitka C-compiled Docker Proxy, Custom Compliance, SAML SSO |
220
+ | Tier | Price | Monthly Token Savings | Highlights |
221
+ |---|---|---|---|
222
+ | **Community (Free)** | **$0** (Free Forever) | **500,000 tokens / mo** | 9-Language Local Regex Compactor, Local AST Skeletonizer CLI, Secret Redactor, Local HTML & SQLite Dashboard |
223
+ | **Solo Developer** | **$9 / month** | **Unlimited** | **7-Day Free Trial**, **Managed Cloud Distillation (Gemini Flash-Lite, Zero Keys Required)**, Subagent Swarm Firewall, Cascading Window Governor, Prompt Cache Normalizer |
224
+ | **Engineering Team** | **$29 / seat / mo** | **Unlimited** | **7-Day Free Trial**, Everything in Solo + **Shared Team Cache (L3 Monorepo Cloud Cache)**, Friday Team ROI Digest & Leaderboards, Team Seat Quota Console, Self-Hosted Docker Proxy |
225
+ | **Enterprise** | Custom | **Unlimited** | On-Premise Nuitka C-compiled Docker Proxy (Private BYOK), Custom Compliance, SAML SSO |
208
226
 
209
227
  👉 **[Start your 7-Day Free Trial on our website](https://tokensafe.dev#pricing)**
210
228
 
@@ -407,9 +425,9 @@ TokenSafe is built on an **Open-Core** model designed to give every developer im
407
425
 
408
426
  | Plan | Price | Monthly Token Savings | Capabilities |
409
427
  | :--- | :---: | :---: | :--- |
410
- | **Community (Free)** | **$0** forever | **500,000 tokens / mo** | Multilingual Local Regex Compactor, AST Slicer, Output Guard, Loop Guard, Local SQLite & HTML Dashboard |
411
- | **Solo Developer** | **$9 / mo** | **Unlimited** | Multi-Provider Distillation (Gemini Flash-Lite, DeepSeek), Subagent Swarm Firewall, Cascading Governor, Multi-turn History Fold |
412
- | **Engineering Team** | **$29 / seat / mo** | **Unlimited** | Everything in Solo + **Shared Team Cache (Cloud Prompt & AST Cache)**, Friday Team ROI Digest, Cloud Organization Console, Seat Quota Management, Self-Hosted Docker Proxy |
428
+ | **Community (Free)** | **$0** forever | **500,000 tokens / mo** | Multilingual Local Regex Compactor (9 languages), AST Slicer, Output Guard, Loop Guard, Local SQLite & HTML Dashboard |
429
+ | **Solo Developer** | **$9 / mo** | **Unlimited** | **Managed Cloud Distillation (Gemini Flash-Lite, Zero Keys Required)**, Subagent Swarm Firewall, Cascading Governor, Multi-turn History Fold |
430
+ | **Engineering Team** | **$29 / seat / mo** | **Unlimited** | Everything in Solo + **Shared Team Cache (L3 Monorepo Cloud Cache)**, Friday Team ROI Digest, Cloud Organization Console, Seat Quota Management, Self-Hosted Docker Proxy |
413
431
 
414
432
  > [!TIP]
415
433
  > **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>`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tokensafe",
3
- "version": "1.3.8",
3
+ "version": "1.3.10",
4
4
  "description": "Autonomous Zero-Loss Token Economy & Context Optimizer for AI Coding Agents",
5
5
  "main": "bin/tokensafe.js",
6
6
  "bin": {
package/plugin.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "agy-token-optimizer",
3
3
  "displayName": "TokenSafe",
4
- "version": "1.3.8",
4
+ "version": "1.3.10",
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/src/__init__.py CHANGED
@@ -2,5 +2,5 @@
2
2
  TokenSafe: Autonomous Zero-Loss Token Economy & Context Optimizer for AI Coding Agents.
3
3
  """
4
4
 
5
- __version__ = "1.3.4"
5
+ __version__ = "1.3.10"
6
6
  __author__ = "TokenSafe Team"
@@ -18,9 +18,9 @@ DATA_DIR = os.path.join(PROJECT_ROOT, "data")
18
18
  LICENSE_FILE = os.path.join(DATA_DIR, "license.json")
19
19
 
20
20
  # Master Public Key for client-side offline verification (RFC 8032 Ed25519)
21
- DEFAULT_ED25519_PUBLIC_KEY = "244ea9d4a20e697578b7b7b31db71613c659678d221300dea1c5a03083bc90e9"
22
- # Private key for cloud server signing (never distributed to untrusted clients)
23
- DEFAULT_ED25519_PRIVATE_KEY = os.environ.get("TOKENSAFE_PRIVATE_KEY", "6785d298e2df4c2c305bd4956f124f038d2da5cbda7f4146513645f1733064c0")
21
+ DEFAULT_ED25519_PUBLIC_KEY = "beb27bc42a723943822ea1ba5d50b7abb55e430cb691518b0b05edef889d0132"
22
+ # Private key for cloud server signing (never distributed to client, loaded strictly from environment)
23
+ DEFAULT_ED25519_PRIVATE_KEY = os.environ.get("TOKENSAFE_PRIVATE_KEY", "")
24
24
  # Rotated HMAC salt for backward compatibility with TS1 legacy licenses
25
25
  ROTATED_HMAC_SALT = os.environ.get("TOKENSAFE_HMAC_SALT", "ts-sec-rotated-7b3f9c2d1e0a4f5b6829e1c3a70428e5")
26
26
  DEFAULT_SIGNING_SALT = ROTATED_HMAC_SALT
@@ -166,7 +166,9 @@ class LicenseManager:
166
166
  payload_b64 = base64.urlsafe_b64encode(payload_bytes).decode("ascii").rstrip("=")
167
167
 
168
168
  if version == 2:
169
- priv_hex = signing_key or DEFAULT_ED25519_PRIVATE_KEY
169
+ priv_hex = signing_key or os.environ.get("TOKENSAFE_PRIVATE_KEY") or DEFAULT_ED25519_PRIVATE_KEY
170
+ if not priv_hex:
171
+ raise ValueError("TOKENSAFE_PRIVATE_KEY environment variable is required to generate license signatures.")
170
172
  priv_bytes = bytes.fromhex(priv_hex)
171
173
  pub_bytes = bytes.fromhex(DEFAULT_ED25519_PUBLIC_KEY)
172
174
  sig_raw = _ed25519_sign_bytes(payload_bytes, priv_bytes, pub_bytes)
package/src/team_cache.py CHANGED
@@ -27,14 +27,22 @@ class TeamCache:
27
27
  def _is_team_tier(cls) -> Tuple[bool, str]:
28
28
  """Checks if current active license belongs to a Team tier subscription."""
29
29
  key = os.environ.get("TOKENSAFE_LICENSE_KEY", "").strip()
30
- base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
31
- lic_file = os.path.join(base_dir, "data", "license.json")
32
- if not key and os.path.exists(lic_file):
33
- try:
34
- with open(lic_file, "r", encoding="utf-8") as f:
35
- key = json.load(f).get("license_key", "").strip()
36
- except Exception:
37
- pass
30
+ if not key:
31
+ candidate_paths = [
32
+ os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "data", "license.json"),
33
+ os.path.join(os.getcwd(), "data", "license.json"),
34
+ os.path.expanduser("~/.tokensafe/license.json")
35
+ ]
36
+ for lic_file in candidate_paths:
37
+ if os.path.exists(lic_file):
38
+ try:
39
+ with open(lic_file, "r", encoding="utf-8") as f:
40
+ data = json.load(f)
41
+ key = data.get("license_key", "").strip()
42
+ if key:
43
+ break
44
+ except Exception:
45
+ pass
38
46
 
39
47
  if not key:
40
48
  return False, ""
@@ -75,8 +83,9 @@ class TeamCache:
75
83
  with urllib.request.urlopen(req, timeout=cls.DEFAULT_TIMEOUT) as resp:
76
84
  if resp.status == 200:
77
85
  data = json.loads(resp.read().decode("utf-8"))
78
- if data.get("hit") and data.get("value"):
79
- return data["value"]
86
+ val = data.get("value") or data.get("cached_value")
87
+ if data.get("hit") and val:
88
+ return val
80
89
  except Exception:
81
90
  # Graceful network degradation: fall back to local computation without error
82
91
  return None
@@ -14,7 +14,7 @@ import urllib.request
14
14
  import urllib.error
15
15
  from typing import Dict, Any, Optional, Tuple
16
16
 
17
- CURRENT_VERSION = "1.3.8"
17
+ CURRENT_VERSION = "1.3.10"
18
18
  CACHE_TTL = 86400 # 24 hours
19
19
 
20
20
  PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))