tokensafe 1.3.7 → 1.3.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -62,9 +62,9 @@ Traditional AI code interactions suffer from massive context bloat:
62
62
  - **Subagent Deduplication Firewall:** Detects repeated file reads across subagents and agent swarms, serving cached AST slices directly from SQLite session memory (`SUBAGENT_DEDUP`) with zero redundant overhead.
63
63
  - **AST Diff Slicer & Lockfile Stripper:** Compresses code review diffs by stripping noisy lockfiles (`package-lock.json`, `pnpm-lock.yaml`, `yarn.lock`, `Cargo.lock`) and minified assets, condensing diffs to 2 lines of context (`git diff -U2`) for up to 96% token savings.
64
64
  - **God Nodes & Architectural Hub Detection:** Calculates Degree Centrality to identify structural project hubs and injects topology awareness into agent sessions without expensive file crawling.
65
- - **TOCP Prompt Distillation:** Intercepts prompts and distills intent into lean S-Expressions via **Google Gemini (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).
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`).
66
66
  - **Token Arbitrage Guard & Output Ceiling:** Eliminates LLM compiler arbitrage loss with a dual defense: inputs $< 100$ tokens route to instant zero-cost local regex heuristics ($0$ LLM tokens), while inputs $\ge 100$ tokens are clamped to a strict $60$-token max output ceiling.
67
- - **Two-Tier Distillation Cache:** Two-tier In-Memory LRU + Persistent SQLite cache (`metrics.db`) with normalized SHA-256 hashing guarantees sub-millisecond zero-cost replays for recurring developer commands.
67
+ - **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
68
  - **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
69
  - **API Surface Map Generator:** Generates high-density `tokensafe-out/API_SURFACE.md` (~1.5k tokens) for instant agent codebase onboarding.
70
70
  - **Predictive Dependency Prefetcher:** Attaches imported symbol signatures to eliminate downstream exploratory `read_file` roundtrips.
@@ -133,36 +133,39 @@ How TokenSafe complements or supersedes static graph tools like **Graphify** (`g
133
133
 
134
134
  ---
135
135
 
136
- ## 🤖 Universal LLM Distillation Providers & Unit Economics Defense
136
+ ## 🤖 Prompt Distillation: Managed Cloud & Three-Tier Cache Architecture
137
137
 
138
- TokenSafe features an intelligent multi-provider prompt compiler that distills verbose developer prompts into lean TOCP S-Expressions (`-40% to -70% tokens`).
138
+ TokenSafe features an intelligent prompt compiler that distills verbose developer prompts into lean TOCP S-Expressions (`-40% to -70% tokens`).
139
139
 
140
- ### 1. Provider Priority & Economics Matrix
140
+ ### 1. Zero-Config Managed Cloud vs. Self-Hosted Docker BYOK
141
141
 
142
- | Provider | Recommended Model | Pricing (Input / Output) | Environment Variable | Priority |
142
+ | Deployment Mode | Supported Tier | Distillation Engine | Required API Keys | Cost & Setup |
143
143
  |---|---|---|---|---|
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 |
144
+ | **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
+ | **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 |
149
147
 
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.
148
+ > **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
149
 
152
- ### 2. Token Arbitrage Guard & Two-Tier Cache Architecture
150
+ ### 2. Token Arbitrage Guard & Three-Tier Cache Architecture
153
151
 
154
152
  To prevent compiler cost overhead from exceeding token savings, TokenSafe applies a 3-stage defense:
155
153
 
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.
154
+ 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}$).
155
+ 2. **Output Token Ceiling (`distill_max_tokens: 60`)**: Caps distillation output at 60 tokens, eliminating verbose chain-of-thought inflation and token arbitrage loss.
156
+ 3. **Three-Tier Distillation Cache Hierarchy**:
157
+ - **L1 (In-Memory LRU)**: Sub-millisecond instant hit for active developer session loops.
158
+ - **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.
159
+ - **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
160
 
162
- ### 3. Configuration (`data/config.json`)
161
+ ### 3. Configuration & Provider Inspection
163
162
 
164
- Configure your provider preferences and models directly:
163
+ Check your license status, active distillation mode, and cache stats anytime:
164
+ ```bash
165
+ tokensafe providers
166
+ ```
165
167
 
168
+ For custom self-hosted environments (`TOKENSAFE_SELF_HOSTED=1`), configure your preferred provider in `data/config.json`:
166
169
  ```json
167
170
  {
168
171
  "preferred_provider": "gemini",
@@ -199,12 +202,12 @@ Verified across 8 real-world production software engineering scenarios (131,604
199
202
 
200
203
  ## 💎 Pricing & 7-Day Free Trial
201
204
 
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 |
205
+ | Tier | Price | Monthly Token Savings | Highlights |
206
+ |---|---|---|---|
207
+ | **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
+ | **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
+ | **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 |
208
211
 
209
212
  👉 **[Start your 7-Day Free Trial on our website](https://tokensafe.dev#pricing)**
210
213
 
@@ -407,9 +410,9 @@ TokenSafe is built on an **Open-Core** model designed to give every developer im
407
410
 
408
411
  | Plan | Price | Monthly Token Savings | Capabilities |
409
412
  | :--- | :---: | :---: | :--- |
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 |
413
+ | **Community (Free)** | **$0** forever | **500,000 tokens / mo** | Multilingual Local Regex Compactor (9 languages), AST Slicer, Output Guard, Loop Guard, Local SQLite & HTML Dashboard |
414
+ | **Solo Developer** | **$9 / mo** | **Unlimited** | **Managed Cloud Distillation (Gemini Flash-Lite, Zero Keys Required)**, Subagent Swarm Firewall, Cascading Governor, Multi-turn History Fold |
415
+ | **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
416
 
414
417
  > [!TIP]
415
418
  > **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.7",
3
+ "version": "1.3.9",
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.7",
4
+ "version": "1.3.9",
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/cli.py CHANGED
@@ -195,7 +195,13 @@ def main():
195
195
  print(" \033[1mTo unlock Neural LLM Distillation:\033[0m")
196
196
  print(" 1. Start 7-day free trial or upgrade at: \033[36mhttps://tokensafe.dev\033[0m")
197
197
  print(" 2. Activate your key: \033[32mtokensafe activate <KEY>\033[0m\n")
198
+ elif not UniversalDistiller.is_self_hosted():
199
+ print(f" \033[32m✔\033[0m \033[1mTokenSafe Cloud Distiller\033[0m [Active: gemini-flash-lite-latest via Managed Cloud]")
200
+ print(" Zero API keys required — managed centrally by your TokenSafe subscription.")
201
+ print(" Shared Team Cache & sub-millisecond cloud cache active.\n")
202
+ print(" \033[2m💡 Tip: To run self-hosted with custom BYOK keys in Docker, export TOKENSAFE_SELF_HOSTED=1.\033[0m\n")
198
203
  else:
204
+ print(" \033[36mMode: Self-Hosted Docker (Custom BYOK Keys)\033[0m\n")
199
205
  configured = UniversalDistiller.get_configured_providers()
200
206
  all_p = UniversalDistiller.PROVIDERS
201
207
  for key, p in all_p.items():
@@ -79,6 +79,11 @@ Rules:
79
79
  if tier == "free":
80
80
  return None
81
81
 
82
+ # In standard SaaS mode, delegate to UniversalDistiller's Managed Cloud Distillation
83
+ if os.environ.get("TOKENSAFE_SELF_HOSTED", "").lower() not in ("1", "true", "yes"):
84
+ from src.distiller import UniversalDistiller
85
+ return UniversalDistiller.distill(raw_text)
86
+
82
87
  conf = cls._get_config()
83
88
  if not conf["enabled"] or not conf["api_key"] or not raw_text or len(raw_text.strip()) < 10:
84
89
  return None
package/src/distiller.py CHANGED
@@ -63,6 +63,35 @@ Rules:
63
63
  }
64
64
  }
65
65
 
66
+ @classmethod
67
+ def is_self_hosted(cls) -> bool:
68
+ """Determines if running in Docker self-hosted mode with custom BYOK keys."""
69
+ return os.environ.get("TOKENSAFE_SELF_HOSTED", "").lower() in ("1", "true", "yes")
70
+
71
+ @classmethod
72
+ def _call_cloud_distill(cls, raw_text: str, lic_key: str) -> Optional[str]:
73
+ cloud_url = os.environ.get("TOKENSAFE_CLOUD_URL", "https://api.tokensafe.dev").rstrip("/")
74
+ endpoint = f"{cloud_url}/api/distill"
75
+ payload = {"prompt": raw_text.strip()}
76
+ req = urllib.request.Request(
77
+ endpoint,
78
+ data=json.dumps(payload).encode("utf-8"),
79
+ headers={
80
+ "Authorization": f"Bearer {lic_key}",
81
+ "Content-Type": "application/json",
82
+ "User-Agent": "TokenSafe/1.3.7"
83
+ }
84
+ )
85
+ try:
86
+ with urllib.request.urlopen(req, timeout=cls.DEFAULT_TIMEOUT) as resp:
87
+ if resp.status == 200:
88
+ data = json.loads(resp.read().decode("utf-8"))
89
+ if data.get("success") and data.get("distilled"):
90
+ return data["distilled"].strip()
91
+ except Exception:
92
+ return None
93
+ return None
94
+
66
95
  @classmethod
67
96
  def get_configured_providers(cls) -> Dict[str, Dict[str, Any]]:
68
97
  """Scans environment and data/config.json for configured LLM distillation keys."""
@@ -70,6 +99,16 @@ Rules:
70
99
  if tier == "free":
71
100
  return {}
72
101
 
102
+ if not cls.is_self_hosted():
103
+ return {
104
+ "cloud": {
105
+ "provider": "cloud",
106
+ "name": "TokenSafe Cloud Distiller",
107
+ "model": "gemini-flash-lite-latest",
108
+ "status": "managed"
109
+ }
110
+ }
111
+
73
112
  config_file_data = {}
74
113
  base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
75
114
  config_path = os.path.join(base_dir, "data", "config.json")
@@ -127,6 +166,29 @@ Rules:
127
166
  if not providers:
128
167
  return None
129
168
 
169
+ # 1. Managed Cloud Distillation (Default for Solo/Team SaaS)
170
+ if "cloud" in providers:
171
+ lic_key = os.environ.get("TOKENSAFE_LICENSE_KEY", "").strip()
172
+ if not lic_key:
173
+ base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
174
+ lic_file = os.path.join(base_dir, "data", "license.json")
175
+ if os.path.exists(lic_file):
176
+ try:
177
+ with open(lic_file, "r", encoding="utf-8") as f:
178
+ lic_key = json.load(f).get("license_key", "").strip()
179
+ except Exception:
180
+ pass
181
+
182
+ if lic_key:
183
+ cloud_res = cls._call_cloud_distill(raw_text, lic_key)
184
+ if cloud_res:
185
+ clean = cls._sanitize_s_expression(cloud_res)
186
+ if clean:
187
+ DistillationCache.set(raw_text, clean, provider="cloud-managed")
188
+ return clean
189
+ return None
190
+
191
+ # 2. Self-Hosted Docker Mode (BYOK local providers)
130
192
  # Determine order
131
193
  pref = preferred_provider
132
194
  if not pref:
@@ -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)
@@ -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.7"
17
+ CURRENT_VERSION = "1.3.9"
18
18
  CACHE_TTL = 86400 # 24 hours
19
19
 
20
20
  PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))