tokensafe 1.3.4 → 1.3.6

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.
@@ -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."""
@@ -19,18 +20,21 @@ class DeepSeekDistiller:
19
20
  DEFAULT_MODEL = "deepseek-flash"
20
21
  DEFAULT_TIMEOUT = 3.5
21
22
 
22
- SYSTEM_PROMPT = """You are a semantic code intent compiler for the Token-Optimized Communication Protocol (TOCP). Your task is to compress verbose, conversational developer requests into an ultra-dense S-Expression with this exact syntax:
23
+ SYSTEM_PROMPT = """You are a multilingual semantic code intent compiler for the Token-Optimized Communication Protocol (TOCP). Your task is to compress verbose, conversational developer requests into an ultra-dense S-Expression with this exact syntax:
23
24
  (ACTION [filepath] [symbol] [[traits...]] ["minimal_intent"])
24
25
 
25
26
  Available ACTIONS: REFACTOR, DEBUG, CREATE, OPTIMIZE, EXPLAIN, AUDIT, TEST, RUN.
26
27
 
27
28
  Examples:
28
- Input: "Слушай, перепиши пожалуйста функцию get_balance в файле wallet.ts, добавь туда redis cache и сделай её асинхронной"
29
+ Input: "Could you please rewrite the get_balance function in wallet.ts, add redis caching to it and make it async?"
29
30
  Output: (REFACTOR wallet.ts get_balance [async redis] "add caching and async")
30
31
 
31
- Input: "У меня в auth.controller.ts при логине через гугл если нет аватарки промис зависает на 30 сек и падает 504"
32
+ Input: "In auth.controller.ts during Google login, if user has no avatar the promise hangs for 30s and throws 504"
32
33
  Output: (DEBUG auth.controller.ts [oauth google timeout_504 missing_avatar] "fix 30s hang on no avatar")
33
34
 
35
+ Input: "Por favor arregla la función validate_token en auth.py para que verifique jwt y devuelva boolean"
36
+ Output: (DEBUG auth.py validate_token [jwt] "verify jwt and return boolean")
37
+
34
38
  Rules:
35
39
  1. Output ONLY the S-Expression starting with ( and ending with ).
36
40
  2. No markdown code blocks, no preamble, no explanations.
@@ -69,7 +73,12 @@ Rules:
69
73
  """
70
74
  Sends raw text to DeepSeek-V3 to compile into an S-Expression.
71
75
  Returns distilled S-Expression or None if unavailable/timed out.
76
+ Requires active TokenSafe Solo or Team subscription.
72
77
  """
78
+ tier, _ = LicenseManager.get_active_license()
79
+ if tier == "free":
80
+ return None
81
+
73
82
  conf = cls._get_config()
74
83
  if not conf["enabled"] or not conf["api_key"] or not raw_text or len(raw_text.strip()) < 10:
75
84
  return None
package/src/distiller.py CHANGED
@@ -12,24 +12,28 @@ 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."""
18
19
 
19
20
  DEFAULT_TIMEOUT = 3.5
20
21
 
21
- SYSTEM_PROMPT = """You are a semantic code intent compiler for the Token-Optimized Communication Protocol (TOCP). Your task is to compress verbose, conversational developer requests into an ultra-dense S-Expression with this exact syntax:
22
+ SYSTEM_PROMPT = """You are a multilingual semantic code intent compiler for the Token-Optimized Communication Protocol (TOCP). Your task is to compress verbose, conversational developer requests into an ultra-dense S-Expression with this exact syntax:
22
23
  (ACTION [filepath] [symbol] [[traits...]] ["minimal_intent"])
23
24
 
24
25
  Available ACTIONS: REFACTOR, DEBUG, CREATE, OPTIMIZE, EXPLAIN, AUDIT, TEST, RUN.
25
26
 
26
27
  Examples:
27
- Input: "Слушай, перепиши пожалуйста функцию get_balance в файле wallet.ts, добавь туда redis cache и сделай её асинхронной"
28
+ Input: "Could you please rewrite the get_balance function in wallet.ts, add redis caching to it and make it async?"
28
29
  Output: (REFACTOR wallet.ts get_balance [async redis] "add caching and async")
29
30
 
30
- Input: "У меня в auth.controller.ts при логине через гугл если нет аватарки промис зависает на 30 сек и падает 504"
31
+ Input: "In auth.controller.ts during Google login, if user has no avatar the promise hangs for 30s and throws 504"
31
32
  Output: (DEBUG auth.controller.ts [oauth google timeout_504 missing_avatar] "fix 30s hang on no avatar")
32
33
 
34
+ Input: "Por favor arregla la función validate_token en auth.py para que verifique jwt y devuelva boolean"
35
+ Output: (DEBUG auth.py validate_token [jwt] "verify jwt and return boolean")
36
+
33
37
  Rules:
34
38
  1. Output ONLY the S-Expression starting with ( and ending with ).
35
39
  2. No markdown code blocks, no preamble, no explanations.
@@ -62,6 +66,10 @@ Rules:
62
66
  @classmethod
63
67
  def get_configured_providers(cls) -> Dict[str, Dict[str, Any]]:
64
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
+
65
73
  config_file_data = {}
66
74
  base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
67
75
  config_path = os.path.join(base_dir, "data", "config.json")
@@ -101,7 +109,12 @@ Rules:
101
109
  """
102
110
  Distills raw conversational text into an S-Expression using the best available provider.
103
111
  Priority: Explicit preferred -> Gemini -> OpenAI -> DeepSeek.
112
+ Requires active TokenSafe Solo or Team subscription.
104
113
  """
114
+ tier, _ = LicenseManager.get_active_license()
115
+ if tier == "free":
116
+ return None
117
+
105
118
  if not raw_text or len(raw_text.strip()) < 10:
106
119
  return None
107
120
 
@@ -129,11 +129,11 @@ class EnvironmentAuditor:
129
129
  return None
130
130
 
131
131
  bloated = report["bloated_servers"]
132
- names = ", ".join([f"`{b['name']}` ({b['tool_count']} инструментов, ~{b['est_tokens_per_turn']:,} токенов/шаг)" for b in bloated])
132
+ names = ", ".join([f"`{b['name']}` ({b['tool_count']} tools, ~{b['est_tokens_per_turn']:,} tokens/turn)" for b in bloated])
133
133
  return (
134
- f"⚠️ **TokenSafe Bloat Alert**: Обнаружен тяжелый MCP сервер: {names}. "
135
- f"Суммарный налог на каждый запрос: **~{report['total_static_tokens_per_turn']:,} токенов**. "
136
- f"Отключите неиспользуемые серверы через `./bin/agy-tokens mcp disable <name>`."
134
+ f"⚠️ **TokenSafe Bloat Alert**: Heavy MCP server detected: {names}. "
135
+ f"Static context overhead per turn: **~{report['total_static_tokens_per_turn']:,} tokens**. "
136
+ f"Disable unused servers via `tokensafe mcp disable <name>`."
137
137
  )
138
138
 
139
139
  @classmethod
@@ -228,7 +228,7 @@ class EnvironmentAuditor:
228
228
 
229
229
  @classmethod
230
230
  def format_cli_report(cls) -> str:
231
- """Formats visual CLI report for agy-tokens doctor."""
231
+ """Formats visual CLI report for tokensafe doctor."""
232
232
  report = cls.audit()
233
233
  lines = [
234
234
  "\n\033[1m\033[36m⚡ TOKENSAFE ENVIRONMENT AUDIT (CONTEXT TAX DOCTOR) ⚡\033[0m\n",
@@ -251,7 +251,7 @@ class EnvironmentAuditor:
251
251
  if report["has_critical_bloat"]:
252
252
  lines.append("\n \033[33m\033[1mDiagnostic Recommendation:\033[0m")
253
253
  for b in report["bloated_servers"]:
254
- lines.append(f" ➜ Run: \033[36m./bin/agy-tokens mcp disable {b['name']}\033[0m to save ~{b['est_tokens_per_turn']:,} tokens per turn!")
254
+ lines.append(f" ➜ Run: \033[36mtokensafe mcp disable {b['name']}\033[0m to save ~{b['est_tokens_per_turn']:,} tokens per turn!")
255
255
  else:
256
256
  lines.append("\n \033[32m✔ Environment healthy: No critical MCP bloat detected.\033[0m")
257
257
 
@@ -129,7 +129,7 @@ class LicenseManager:
129
129
  """Manages TokenSafe subscription tiers, offline signature verification, and 7-day trials."""
130
130
 
131
131
  TIERS = {
132
- "free": {"max_tokens_monthly": 100_000, "deepseek_cloud": False, "team_analytics": False},
132
+ "free": {"max_tokens_monthly": 500_000, "deepseek_cloud": False, "team_analytics": False},
133
133
  "solo": {"max_tokens_monthly": None, "deepseek_cloud": True, "team_analytics": False},
134
134
  "team": {"max_tokens_monthly": None, "deepseek_cloud": True, "team_analytics": True},
135
135
  "enterprise": {"max_tokens_monthly": None, "deepseek_cloud": True, "team_analytics": True, "self_hosted": True}
@@ -257,7 +257,7 @@ class LicenseManager:
257
257
  if valid:
258
258
  return payload.get("tier", "solo"), payload
259
259
 
260
- return "free", {"tier": "free", "max_tokens_monthly": 100_000}
260
+ return "free", {"tier": "free", "max_tokens_monthly": 500_000}
261
261
 
262
262
  @classmethod
263
263
  def save_license(cls, license_key: str) -> Tuple[bool, str]:
@@ -280,3 +280,63 @@ class LicenseManager:
280
280
  tier_name = payload.get("tier", "").upper()
281
281
  trial_note = " (7-Day Trial)" if payload.get("trial") else ""
282
282
  return True, f"Successfully activated TokenSafe {tier_name}{trial_note}!"
283
+
284
+ @classmethod
285
+ def check_quota(cls, tracker: Optional[Any] = None) -> Dict[str, Any]:
286
+ """
287
+ Evaluates whether the current active license quota is exceeded.
288
+ Returns:
289
+ {
290
+ "tier": str,
291
+ "is_quota_exceeded": bool,
292
+ "monthly_limit": Optional[int],
293
+ "monthly_saved": int,
294
+ "warning": Optional[str]
295
+ }
296
+ """
297
+ tier, payload = cls.get_active_license()
298
+ tier_cfg = cls.TIERS.get(tier, cls.TIERS["free"])
299
+ max_tokens = tier_cfg.get("max_tokens_monthly")
300
+
301
+ # Paid tiers (solo, team, enterprise) have unlimited local optimization
302
+ if max_tokens is None:
303
+ return {
304
+ "tier": tier,
305
+ "is_quota_exceeded": False,
306
+ "monthly_limit": None,
307
+ "monthly_saved": 0,
308
+ "warning": None
309
+ }
310
+
311
+ # For free tier, calculate trailing 30 days saved tokens
312
+ if tracker is None:
313
+ try:
314
+ from src.metrics import MetricsTracker
315
+ tracker = MetricsTracker()
316
+ except Exception:
317
+ tracker = None
318
+
319
+ monthly_saved = tracker.get_monthly_saved_tokens() if tracker else 0
320
+ exceeded = monthly_saved >= max_tokens
321
+
322
+ warning = None
323
+ if exceeded:
324
+ warning = (
325
+ f"⚡ **TokenSafe Quota Alert**: Community Edition limit reached "
326
+ f"({monthly_saved:,}/{max_tokens:,} tokens saved this month). "
327
+ f"Advanced optimization is throttled. Upgrade to Solo for unlimited optimization: `tokensafe activate <key>` or visit https://tokensafe.dev."
328
+ )
329
+ elif monthly_saved >= int(max_tokens * 0.85):
330
+ warning = (
331
+ f"⚡ **TokenSafe Quota Notice**: Community Edition is at {int(monthly_saved / max_tokens * 100)}% of monthly limit "
332
+ f"({monthly_saved:,}/{max_tokens:,} tokens). "
333
+ f"Upgrade to Solo for unlimited optimization: `tokensafe activate <key>` or https://tokensafe.dev."
334
+ )
335
+
336
+ return {
337
+ "tier": tier,
338
+ "is_quota_exceeded": exceeded,
339
+ "monthly_limit": max_tokens,
340
+ "monthly_saved": monthly_saved,
341
+ "warning": warning
342
+ }
package/src/metrics.py CHANGED
@@ -211,6 +211,19 @@ class MetricsTracker:
211
211
  "breakdown": combined_breakdown
212
212
  }
213
213
 
214
+ def get_monthly_saved_tokens(self) -> int:
215
+ """Returns total tokens saved in the trailing 30 days for quota calculations."""
216
+ thirty_days_ago = (datetime.utcnow() - timedelta(days=30)).isoformat()
217
+ with self._get_connection() as conn:
218
+ cursor = conn.cursor()
219
+ cursor.execute("""
220
+ SELECT COALESCE(SUM(saved_tokens), 0) as monthly_saved
221
+ FROM events
222
+ WHERE timestamp >= ?
223
+ """, (thirty_days_ago,))
224
+ row = cursor.fetchone()
225
+ return int(row["monthly_saved"]) if row else 0
226
+
214
227
  def get_recent_events(self, limit: int = 10) -> List[Dict[str, Any]]:
215
228
  """Returns the most recent optimization events."""
216
229
  with self._get_connection() as conn:
@@ -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.4"
17
+ CURRENT_VERSION = "1.3.6"
18
18
  CACHE_TTL = 86400 # 24 hours
19
19
 
20
20
  PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))