tokensafe 1.3.6 → 1.3.7

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.7",
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.7",
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": {
@@ -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.7"
18
18
  CACHE_TTL = 86400 # 24 hours
19
19
 
20
20
  PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))