tokensafe 1.3.5 → 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 +2 -1
- package/hooks/__pycache__/pre_tool_use.cpython-313.pyc +0 -0
- package/hooks/pre_tool_use.py +16 -0
- package/package.json +1 -1
- package/plugin.json +1 -1
- package/src/cli.py +20 -10
- package/src/compactor.py +40 -36
- package/src/deepseek_distiller.py +6 -0
- package/src/distiller.py +10 -0
- package/src/distiller_cache.py +22 -2
- package/src/team_cache.py +146 -0
- package/src/version_checker.py +1 -1
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>`.
|
|
Binary file
|
package/hooks/pre_tool_use.py
CHANGED
|
@@ -24,6 +24,7 @@ from src.metrics import MetricsTracker
|
|
|
24
24
|
from src.tokenizer import count_tokens
|
|
25
25
|
from src.agent_firewall import AgentFirewall
|
|
26
26
|
from src.diff_slicer import DiffSlicer
|
|
27
|
+
from src.license_manager import LicenseManager
|
|
27
28
|
|
|
28
29
|
def main():
|
|
29
30
|
try:
|
|
@@ -44,6 +45,8 @@ def main():
|
|
|
44
45
|
last_user_input = payload.get("lastUserInput", "")
|
|
45
46
|
|
|
46
47
|
tracker = MetricsTracker()
|
|
48
|
+
quota = LicenseManager.check_quota(tracker)
|
|
49
|
+
is_quota_exceeded = quota.get("is_quota_exceeded", False)
|
|
47
50
|
|
|
48
51
|
# 1. Loop Detector Guard (Applies to all tools)
|
|
49
52
|
is_loop, repeat_count, loop_msg = LoopDetector.check_loop(conversation_id, tool_name, args)
|
|
@@ -107,6 +110,11 @@ def main():
|
|
|
107
110
|
start_line = args.get("StartLine")
|
|
108
111
|
end_line = args.get("EndLine")
|
|
109
112
|
|
|
113
|
+
if is_quota_exceeded:
|
|
114
|
+
# Free tier quota reached: pass through raw read_file without AST skeletonization
|
|
115
|
+
print(json.dumps(response))
|
|
116
|
+
return
|
|
117
|
+
|
|
110
118
|
# Step 3A: Subagent Firewall — Check if file was already read in active session
|
|
111
119
|
is_hit, cached_text, saved_dedup = AgentFirewall.check_cache(
|
|
112
120
|
session_id=conversation_id,
|
|
@@ -193,6 +201,14 @@ def main():
|
|
|
193
201
|
# 4. run_command Optimization (Command Sanitizer & Diff Slicer)
|
|
194
202
|
elif tool_name == "run_command":
|
|
195
203
|
cmd = args.get("CommandLine", "")
|
|
204
|
+
if is_quota_exceeded:
|
|
205
|
+
# Free tier quota reached: pass through without AST diff slicing or savings tracking
|
|
206
|
+
new_cmd, est_saved, reason = CommandSanitizer.sanitize(cmd)
|
|
207
|
+
if new_cmd and est_saved > 0:
|
|
208
|
+
response["overwrite"] = {"CommandLine": new_cmd}
|
|
209
|
+
print(json.dumps(response))
|
|
210
|
+
return
|
|
211
|
+
|
|
196
212
|
# Check AST Diff Slicer first
|
|
197
213
|
diff_cmd, diff_saved, diff_reason = DiffSlicer.optimize_git_diff_command(cmd)
|
|
198
214
|
if diff_cmd:
|
package/package.json
CHANGED
package/plugin.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "agy-token-optimizer",
|
|
3
3
|
"displayName": "TokenSafe",
|
|
4
|
-
"version": "1.3.
|
|
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": {
|
package/src/cli.py
CHANGED
|
@@ -179,22 +179,32 @@ def main():
|
|
|
179
179
|
else:
|
|
180
180
|
print(f" Expires: Never (Lifetime)")
|
|
181
181
|
else:
|
|
182
|
-
print(" Status: Free Tier (up to
|
|
182
|
+
print(" Status: Free Tier (up to 500,000 tokens/mo)")
|
|
183
183
|
print(" Upgrade: https://tokensafe.dev ($9/mo Solo with 7-Day Free Trial)\n")
|
|
184
184
|
print()
|
|
185
185
|
|
|
186
186
|
elif command in ("providers", "models", "keys"):
|
|
187
|
+
from src.license_manager import LicenseManager
|
|
187
188
|
from src.distiller import UniversalDistiller
|
|
188
|
-
|
|
189
|
+
tier, _ = LicenseManager.get_active_license()
|
|
189
190
|
print("\n\033[1m\033[36m⚡ TOKENSAFE LLM DISTILLATION PROVIDERS ⚡\033[0m\n")
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
191
|
+
if tier == "free":
|
|
192
|
+
print(" \033[33mTier: Free Community Edition\033[0m")
|
|
193
|
+
print(" Neural Semantic Distillation (Gemini / OpenAI / DeepSeek) is reserved for Solo & Team tiers.")
|
|
194
|
+
print(" Free Community Edition operates with the zero-latency, zero-cost Local Regex Compactor.\n")
|
|
195
|
+
print(" \033[1mTo unlock Neural LLM Distillation:\033[0m")
|
|
196
|
+
print(" 1. Start 7-day free trial or upgrade at: \033[36mhttps://tokensafe.dev\033[0m")
|
|
197
|
+
print(" 2. Activate your key: \033[32mtokensafe activate <KEY>\033[0m\n")
|
|
198
|
+
else:
|
|
199
|
+
configured = UniversalDistiller.get_configured_providers()
|
|
200
|
+
all_p = UniversalDistiller.PROVIDERS
|
|
201
|
+
for key, p in all_p.items():
|
|
202
|
+
if key in configured:
|
|
203
|
+
c = configured[key]
|
|
204
|
+
print(f" \033[32m✔\033[0m \033[1m{p['name']:<18}\033[0m [Active: {c['model']}]")
|
|
205
|
+
else:
|
|
206
|
+
print(f" \033[2m○ {p['name']:<18} [Set {p['env_key']} to activate]\033[0m")
|
|
207
|
+
print("\nSet environment variable or add to data/config.json to activate.\n")
|
|
198
208
|
|
|
199
209
|
elif command in ("markdown", "md", "export"):
|
|
200
210
|
print(dashboard.render_markdown())
|
package/src/compactor.py
CHANGED
|
@@ -12,6 +12,7 @@ from typing import Dict, List, Optional, Any
|
|
|
12
12
|
from src.tokenizer import count_tokens
|
|
13
13
|
from src.distiller import UniversalDistiller
|
|
14
14
|
from src.secret_redactor import SecretRedactor
|
|
15
|
+
from src.license_manager import LicenseManager
|
|
15
16
|
|
|
16
17
|
class PromptCompactor:
|
|
17
18
|
"""Transforms verbose natural language requests into compact Intent IR across major world languages."""
|
|
@@ -405,44 +406,47 @@ class PromptCompactor:
|
|
|
405
406
|
"tier": "PASS_THROUGH"
|
|
406
407
|
}
|
|
407
408
|
|
|
408
|
-
# Tier 2: LLM Intent Distiller (Gemini / OpenAI / DeepSeek)
|
|
409
|
+
# Tier 2: Neural LLM Intent Distiller (Gemini / OpenAI / DeepSeek)
|
|
410
|
+
# Exclusive to TokenSafe Solo, Team, and Enterprise (or active trials)
|
|
409
411
|
min_distill = min_distill_tokens if min_distill_tokens is not None else cls._get_min_distill_tokens()
|
|
410
412
|
if enable_deepseek and original_tokens >= min_distill:
|
|
411
|
-
|
|
412
|
-
if
|
|
413
|
-
|
|
414
|
-
if
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
413
|
+
active_tier, _ = LicenseManager.get_active_license()
|
|
414
|
+
if active_tier != "free":
|
|
415
|
+
distilled = UniversalDistiller.distill(raw_text)
|
|
416
|
+
if distilled:
|
|
417
|
+
dist_tokens = count_tokens(distilled)
|
|
418
|
+
if dist_tokens < original_tokens:
|
|
419
|
+
saved = original_tokens - dist_tokens
|
|
420
|
+
pct = (saved / original_tokens * 100.0)
|
|
421
|
+
|
|
422
|
+
# Extract action from S-Expression: e.g. "(DEBUG ..."
|
|
423
|
+
act_match = re.match(r"^\(([A-Z]+)", distilled)
|
|
424
|
+
action = act_match.group(1) if act_match else "TASK"
|
|
425
|
+
|
|
426
|
+
# Extract file if present
|
|
427
|
+
files = cls.FILE_REGEX.findall(distilled)
|
|
428
|
+
target_file = files[0] if files else ""
|
|
429
|
+
|
|
430
|
+
# Extract symbol
|
|
431
|
+
symbol = cls.extract_symbol(raw_text, target_file)
|
|
432
|
+
|
|
433
|
+
# Extract traits if present in distilled S-Expression: e.g. [async redis ...]
|
|
434
|
+
trait_match = re.search(r"\[(.*?)\]", distilled)
|
|
435
|
+
traits = trait_match.group(1).split() if trait_match else []
|
|
436
|
+
|
|
437
|
+
return {
|
|
438
|
+
"original_text": raw_text,
|
|
439
|
+
"compact_text": distilled,
|
|
440
|
+
"original_tokens": original_tokens,
|
|
441
|
+
"compact_tokens": dist_tokens,
|
|
442
|
+
"saved_tokens": saved,
|
|
443
|
+
"reduction_pct": round(pct, 1),
|
|
444
|
+
"action": action,
|
|
445
|
+
"target_file": target_file,
|
|
446
|
+
"symbol": symbol,
|
|
447
|
+
"traits": traits,
|
|
448
|
+
"tier": "DEEPSEEK_V3"
|
|
449
|
+
}
|
|
446
450
|
|
|
447
451
|
# Tier 1: Multilingual Local Regex Compactor
|
|
448
452
|
files = cls.FILE_REGEX.findall(raw_text)
|
|
@@ -11,6 +11,7 @@ import urllib.request
|
|
|
11
11
|
import urllib.error
|
|
12
12
|
from typing import Optional, Dict, Any
|
|
13
13
|
from src.distiller_cache import DistillationCache
|
|
14
|
+
from src.license_manager import LicenseManager
|
|
14
15
|
|
|
15
16
|
class DeepSeekDistiller:
|
|
16
17
|
"""Uses DeepSeek-Flash as a high-density semantic compiler for prompts."""
|
|
@@ -72,7 +73,12 @@ Rules:
|
|
|
72
73
|
"""
|
|
73
74
|
Sends raw text to DeepSeek-V3 to compile into an S-Expression.
|
|
74
75
|
Returns distilled S-Expression or None if unavailable/timed out.
|
|
76
|
+
Requires active TokenSafe Solo or Team subscription.
|
|
75
77
|
"""
|
|
78
|
+
tier, _ = LicenseManager.get_active_license()
|
|
79
|
+
if tier == "free":
|
|
80
|
+
return None
|
|
81
|
+
|
|
76
82
|
conf = cls._get_config()
|
|
77
83
|
if not conf["enabled"] or not conf["api_key"] or not raw_text or len(raw_text.strip()) < 10:
|
|
78
84
|
return None
|
package/src/distiller.py
CHANGED
|
@@ -12,6 +12,7 @@ import urllib.request
|
|
|
12
12
|
import urllib.error
|
|
13
13
|
from typing import Optional, Dict, Any, Tuple
|
|
14
14
|
from src.distiller_cache import DistillationCache
|
|
15
|
+
from src.license_manager import LicenseManager
|
|
15
16
|
|
|
16
17
|
class UniversalDistiller:
|
|
17
18
|
"""Multi-provider semantic intent compiler supporting DeepSeek, OpenAI, and Google Gemini."""
|
|
@@ -65,6 +66,10 @@ Rules:
|
|
|
65
66
|
@classmethod
|
|
66
67
|
def get_configured_providers(cls) -> Dict[str, Dict[str, Any]]:
|
|
67
68
|
"""Scans environment and data/config.json for configured LLM distillation keys."""
|
|
69
|
+
tier, _ = LicenseManager.get_active_license()
|
|
70
|
+
if tier == "free":
|
|
71
|
+
return {}
|
|
72
|
+
|
|
68
73
|
config_file_data = {}
|
|
69
74
|
base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
70
75
|
config_path = os.path.join(base_dir, "data", "config.json")
|
|
@@ -104,7 +109,12 @@ Rules:
|
|
|
104
109
|
"""
|
|
105
110
|
Distills raw conversational text into an S-Expression using the best available provider.
|
|
106
111
|
Priority: Explicit preferred -> Gemini -> OpenAI -> DeepSeek.
|
|
112
|
+
Requires active TokenSafe Solo or Team subscription.
|
|
107
113
|
"""
|
|
114
|
+
tier, _ = LicenseManager.get_active_license()
|
|
115
|
+
if tier == "free":
|
|
116
|
+
return None
|
|
117
|
+
|
|
108
118
|
if not raw_text or len(raw_text.strip()) < 10:
|
|
109
119
|
return None
|
|
110
120
|
|
package/src/distiller_cache.py
CHANGED
|
@@ -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
|
|
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}
|
package/src/version_checker.py
CHANGED
|
@@ -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.
|
|
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__)))
|