tokensafe 1.3.6 → 1.3.8

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
@@ -65,6 +65,7 @@ Traditional AI code interactions suffer from massive context bloat:
65
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).
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
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.
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.
68
69
  - **API Surface Map Generator:** Generates high-density `tokensafe-out/API_SURFACE.md` (~1.5k tokens) for instant agent codebase onboarding.
69
70
  - **Predictive Dependency Prefetcher:** Attaches imported symbol signatures to eliminate downstream exploratory `read_file` roundtrips.
70
71
  - **Live SSE Streaming Dashboard:** Real-time reactive Web UI streaming token reductions, live event logs, and USD savings via Server-Sent Events (`/api/events`).
@@ -408,7 +409,7 @@ TokenSafe is built on an **Open-Core** model designed to give every developer im
408
409
  | :--- | :---: | :---: | :--- |
409
410
  | **Community (Free)** | **$0** forever | **500,000 tokens / mo** | Multilingual Local Regex Compactor, AST Slicer, Output Guard, Loop Guard, Local SQLite & HTML Dashboard |
410
411
  | **Solo Developer** | **$9 / mo** | **Unlimited** | Multi-Provider Distillation (Gemini Flash-Lite, DeepSeek), Subagent Swarm Firewall, Cascading Governor, Multi-turn History Fold |
411
- | **Engineering Team** | **$29 / seat / mo** | **Unlimited** | Everything in Solo + Friday Team ROI Digest, Cloud Organization Console, Seat Quota Management, Self-Hosted Docker Proxy |
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 |
412
413
 
413
414
  > [!TIP]
414
415
  > **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.6",
3
+ "version": "1.3.8",
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.6",
4
+ "version": "1.3.8",
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:
@@ -110,13 +110,25 @@ class DistillationCache:
110
110
  except Exception:
111
111
  pass
112
112
 
113
+ # 3. Check L3 Shared Team Cache (TokenSafe Team tier)
114
+ try:
115
+ from src.team_cache import TeamCache
116
+ team_val = TeamCache.get("PROMPT", prompt_text)
117
+ if team_val:
118
+ cls.set(prompt_text, team_val, provider="team_cache", sync_remote=False)
119
+ with cls._lock:
120
+ cls._hits += 1
121
+ return team_val
122
+ except Exception:
123
+ pass
124
+
113
125
  with cls._lock:
114
126
  cls._misses += 1
115
127
  return None
116
128
 
117
129
  @classmethod
118
- def set(cls, prompt_text: str, distilled_text: str, provider: str = "deepseek") -> None:
119
- """Stores a distillation result into memory LRU and SQLite cache."""
130
+ def set(cls, prompt_text: str, distilled_text: str, provider: str = "deepseek", sync_remote: bool = True) -> None:
131
+ """Stores a distillation result into memory LRU, SQLite cache, and Team Cache if applicable."""
120
132
  if not prompt_text or not distilled_text or not distilled_text.strip():
121
133
  return
122
134
 
@@ -152,6 +164,14 @@ class DistillationCache:
152
164
  except Exception:
153
165
  pass
154
166
 
167
+ # 4. Broadcast to L3 Shared Team Cache (Asynchronous)
168
+ if sync_remote:
169
+ try:
170
+ from src.team_cache import TeamCache
171
+ TeamCache.put("PROMPT", prompt_text, distilled_text.strip(), tokens_saved=45)
172
+ except Exception:
173
+ pass
174
+
155
175
  @classmethod
156
176
  def clear(cls) -> None:
157
177
  """Clears both in-memory and persistent SQLite cache."""
@@ -0,0 +1,146 @@
1
+ """
2
+ TokenSafe Shared Team Cache Client.
3
+ Provides cross-developer prompt distillation and AST skeleton caching for Team tier.
4
+ Zero external runtime dependencies (standard library urllib + hashlib).
5
+ """
6
+
7
+ import os
8
+ import json
9
+ import hashlib
10
+ import threading
11
+ import urllib.request
12
+ import urllib.error
13
+ import urllib.parse
14
+ from typing import Optional, Dict, Any, Tuple
15
+ from src.license_manager import LicenseManager
16
+
17
+ class TeamCache:
18
+ """Distributed cross-developer cache client for TokenSafe Team tier."""
19
+
20
+ DEFAULT_TIMEOUT = 0.4 # Strict 400ms timeout to prevent blocking agent turns
21
+
22
+ @classmethod
23
+ def _get_cloud_url(cls) -> str:
24
+ return os.environ.get("TOKENSAFE_CLOUD_URL", "https://api.tokensafe.dev").rstrip("/")
25
+
26
+ @classmethod
27
+ def _is_team_tier(cls) -> Tuple[bool, str]:
28
+ """Checks if current active license belongs to a Team tier subscription."""
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
38
+
39
+ if not key:
40
+ return False, ""
41
+
42
+ valid, payload, _ = LicenseManager.validate_license(key)
43
+ if valid and payload.get("tier") == "team":
44
+ return True, key
45
+ return False, ""
46
+
47
+ @classmethod
48
+ def hash_key(cls, key_text: str) -> str:
49
+ """Returns lowercase SHA-256 hash of normalized text."""
50
+ norm = " ".join((key_text or "").strip().split())
51
+ return hashlib.sha256(norm.encode("utf-8")).hexdigest()
52
+
53
+ @classmethod
54
+ def get(cls, cache_type: str, key_text: str) -> Optional[str]:
55
+ """
56
+ Queries Shared Team Cache for compiled S-Expression or AST Skeleton.
57
+ Returns cached value string or None if miss/disabled/timed out.
58
+ """
59
+ is_team, lic_key = cls._is_team_tier()
60
+ if not is_team or not key_text:
61
+ return None
62
+
63
+ h = cls.hash_key(key_text)
64
+ endpoint = f"{cls._get_cloud_url()}/api/team/cache?type={urllib.parse.quote(cache_type)}&hash={h}"
65
+
66
+ req = urllib.request.Request(
67
+ endpoint,
68
+ headers={
69
+ "Authorization": f"Bearer {lic_key}",
70
+ "User-Agent": "TokenSafe-TeamCache/1.0"
71
+ }
72
+ )
73
+
74
+ try:
75
+ with urllib.request.urlopen(req, timeout=cls.DEFAULT_TIMEOUT) as resp:
76
+ if resp.status == 200:
77
+ data = json.loads(resp.read().decode("utf-8"))
78
+ if data.get("hit") and data.get("value"):
79
+ return data["value"]
80
+ except Exception:
81
+ # Graceful network degradation: fall back to local computation without error
82
+ return None
83
+
84
+ return None
85
+
86
+ @classmethod
87
+ def put(cls, cache_type: str, key_text: str, value: str, tokens_saved: int = 0) -> None:
88
+ """
89
+ Asynchronously broadcasts a freshly compiled distillation or skeleton to the Team Cache.
90
+ Runs in a detached daemon thread so developer workflows never wait on network I/O.
91
+ """
92
+ is_team, lic_key = cls._is_team_tier()
93
+ if not is_team or not key_text or not value:
94
+ return
95
+
96
+ h = cls.hash_key(key_text)
97
+
98
+ def _worker():
99
+ payload = {
100
+ "type": cache_type,
101
+ "hash": h,
102
+ "value": value,
103
+ "tokens_saved": max(0, tokens_saved),
104
+ "license_key": lic_key
105
+ }
106
+ endpoint = f"{cls._get_cloud_url()}/api/team/cache"
107
+ req = urllib.request.Request(
108
+ endpoint,
109
+ data=json.dumps(payload).encode("utf-8"),
110
+ headers={
111
+ "Authorization": f"Bearer {lic_key}",
112
+ "Content-Type": "application/json",
113
+ "User-Agent": "TokenSafe-TeamCache/1.0"
114
+ }
115
+ )
116
+ try:
117
+ with urllib.request.urlopen(req, timeout=1.5):
118
+ pass
119
+ except Exception:
120
+ pass
121
+
122
+ t = threading.Thread(target=_worker, daemon=True)
123
+ t.start()
124
+
125
+ @classmethod
126
+ def get_stats(cls) -> Dict[str, Any]:
127
+ """Retrieves team cache hit rates and token savings metrics."""
128
+ is_team, lic_key = cls._is_team_tier()
129
+ if not is_team:
130
+ return {"active": False, "reason": "Requires active TokenSafe Team subscription"}
131
+
132
+ endpoint = f"{cls._get_cloud_url()}/api/team/cache/stats"
133
+ req = urllib.request.Request(
134
+ endpoint,
135
+ headers={"Authorization": f"Bearer {lic_key}", "User-Agent": "TokenSafe-TeamCache/1.0"}
136
+ )
137
+ try:
138
+ with urllib.request.urlopen(req, timeout=1.0) as resp:
139
+ if resp.status == 200:
140
+ res = json.loads(resp.read().decode("utf-8"))
141
+ res["active"] = True
142
+ return res
143
+ except Exception as e:
144
+ return {"active": True, "error": str(e)}
145
+
146
+ return {"active": True, "total_entries": 0, "total_hits": 0}
@@ -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.6"
17
+ CURRENT_VERSION = "1.3.8"
18
18
  CACHE_TTL = 86400 # 24 hours
19
19
 
20
20
  PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))