tokensafe 1.3.9 → 1.3.11

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,7 +77,7 @@ 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 (`-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 BYOK keys (`TOKENSAFE_SELF_HOSTED=1`).
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
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.
@@ -78,6 +93,28 @@ Traditional AI code interactions suffer from massive context bloat:
78
93
 
79
94
  ---
80
95
 
96
+ ## 🤯 The Accidental Side Effect: Your AI Stops Hallucinating
97
+
98
+ We originally built TokenSafe for a purely selfish reason: **to stop getting $400 monthly LLM API bills** from running autonomous coding agents.
99
+
100
+ Then something unexpected happened during real-world dogfooding.
101
+
102
+ Our agents didn't just get cheaper — **they wrote noticeably better code, stopped inventing imaginary methods, and eliminated cyclic regression bugs.**
103
+
104
+ Turns out, there's a simple reason for this:
105
+ > **Transformer models don't write bad code because they're stupid. They write bad code because we drown them in 15,000 lines of garbage.**
106
+
107
+ ### How stripping 90% of token noise fixes AI code quality:
108
+
109
+ | What Usually Breaks the AI | How TokenSafe Fixes It | The Result |
110
+ | :--- | :--- | :--- |
111
+ | **"Lost in the Middle" Attention Fade**<br>Agent reads a 2,000-line file just to tweak a 10-line helper. The model loses track of imports and invents fictional methods. | **AST Skeletonizer** (`src/slicer.py`) collapses dead code into typed interfaces, keeping only target functions and 1-hop callees full. | **High-Density Signal.** The model sees 100% of the type contracts without drowning in unrelated loops. |
112
+ | **Terminal Log Poisoning**<br>`npm test` or `pytest` fails and dumps 4,000 lines of stack traces and lockfile diffs. The model panics and rewrites unrelated code. | **Command Sanitizer** (`src/command_sanitizer.py`) snips the matrix down to the exact failing assertion line and call frame. | **Laser Focus.** The agent fixes the actual bug instead of hallucinating workarounds for log noise. |
113
+ | **The 5-Attempt Doom Loop**<br>Agent tries a broken fix, fails, tries the exact same broken fix again, and oscillates until your session context limit catches fire. | **Anti-Stuck Loop Guard** (`src/loop_detector.py`) intercepts repeated tool calls and cyclic edits in flight. | **No Cascading Regressions.** The loop is halted before the agent can butcher working modules. |
114
+ | **Vague Human Prompts**<br>*"Hey, fix the auth bug but don't break the cache or whatever."* The model takes creative liberties and breaks three other files. | **TOCP Intent Compactor** (`src/compactor.py`) distills messy instructions into explicit S-Expressions with hard constraint boundaries. | **Zero Ambiguity.** The model executes `(DEBUG auth.ts [jwt] "fix 401 token expiry")` with strict parameter bounds. |
115
+
116
+ ---
117
+
81
118
  ## 🛡️ The Hidden Context Killer: MCP Tool Schema Bloat
82
119
 
83
120
  Why do AI coding agent quotas (like Antigravity's **5-Hour Limit** or Claude/OpenAI monthly token budgets) evaporate after just a few prompts?
@@ -143,7 +180,7 @@ TokenSafe features an intelligent prompt compiler that distills verbose develope
143
180
  |---|---|---|---|---|
144
181
  | **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) |
145
182
  | **Local Regex Compactor** | **Community (Free)** | **Deterministic Multilingual Regex** (9 languages) | **None** | **100% Free** (0ms latency, 0 external tokens, 500k tokens/mo) |
146
- | **Self-Hosted Docker** 🐳 | **Enterprise / Team** | **BYOK Multi-Provider** (Gemini, DeepSeek, OpenAI, Claude) | `GEMINI_API_KEY`, `DEEPSEEK_API_KEY`, etc. | Requires `TOKENSAFE_SELF_HOSTED=1` in private VPC container |
183
+ | **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 |
147
184
 
148
185
  > **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.
149
186
 
@@ -207,7 +244,7 @@ Verified across 8 real-world production software engineering scenarios (131,604
207
244
  | **Community (Free)** | **$0** (Free Forever) | **500,000 tokens / mo** | 9-Language Local Regex Compactor, Local AST Skeletonizer CLI, Secret Redactor, Local HTML & SQLite Dashboard |
208
245
  | **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 |
209
246
  | **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 |
210
- | **Enterprise** | Custom | **Unlimited** | On-Premise Nuitka C-compiled Docker Proxy (`TOKENSAFE_SELF_HOSTED=1` BYOK), Custom Compliance, SAML SSO |
247
+ | **Enterprise** | Custom | **Unlimited** | On-Premise Nuitka C-compiled Docker Proxy (Private BYOK), Custom Compliance, SAML SSO |
211
248
 
212
249
  👉 **[Start your 7-Day Free Trial on our website](https://tokensafe.dev#pricing)**
213
250
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tokensafe",
3
- "version": "1.3.9",
3
+ "version": "1.3.11",
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.9",
4
+ "version": "1.3.11",
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.11"
6
6
  __author__ = "TokenSafe Team"
@@ -19,6 +19,7 @@ class DistillationCache:
19
19
  _memory_cache: OrderedDict = OrderedDict()
20
20
  _MAX_MEMORY_ENTRIES = 1000
21
21
  _db_path: Optional[str] = None
22
+ _initialized_dbs: set = set()
22
23
  _hits: int = 0
23
24
  _misses: int = 0
24
25
 
@@ -46,6 +47,9 @@ class DistillationCache:
46
47
 
47
48
  @classmethod
48
49
  def _init_db(cls, conn: sqlite3.Connection):
50
+ db_path = cls._get_db_path()
51
+ if db_path in cls._initialized_dbs:
52
+ return
49
53
  conn.execute("""
50
54
  CREATE TABLE IF NOT EXISTS distillation_cache (
51
55
  prompt_hash TEXT PRIMARY KEY,
@@ -57,6 +61,8 @@ class DistillationCache:
57
61
  );
58
62
  """)
59
63
  conn.execute("CREATE INDEX IF NOT EXISTS idx_distill_hash ON distillation_cache(prompt_hash);")
64
+ conn.commit()
65
+ cls._initialized_dbs.add(db_path)
60
66
 
61
67
  @classmethod
62
68
  def get(cls, prompt_text: str) -> Optional[str]:
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.9"
17
+ CURRENT_VERSION = "1.3.11"
18
18
  CACHE_TTL = 86400 # 24 hours
19
19
 
20
20
  PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))