tokensafe 1.3.1 → 1.3.2

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tokensafe",
3
- "version": "1.3.1",
3
+ "version": "1.3.2",
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.1",
4
+ "version": "1.3.2",
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/__init__.py CHANGED
@@ -2,5 +2,5 @@
2
2
  TokenSafe: Autonomous Zero-Loss Token Economy & Context Optimizer for AI Coding Agents.
3
3
  """
4
4
 
5
- __version__ = "1.3.1"
5
+ __version__ = "1.3.2"
6
6
  __author__ = "TokenSafe Team"
package/src/compactor.py CHANGED
@@ -4,8 +4,10 @@ into ultra-dense Token-Optimized Communication Protocol (TOCP) S-Expressions.
4
4
  Supports 3-Tier Routing: Pass-through -> Regex Compactor -> DeepSeek-V3 Distiller.
5
5
  """
6
6
 
7
+ import os
8
+ import json
7
9
  import re
8
- from typing import Dict, List, Optional
10
+ from typing import Dict, List, Optional, Any
9
11
  from src.tokenizer import count_tokens
10
12
  from src.distiller import UniversalDistiller
11
13
  from src.secret_redactor import SecretRedactor
@@ -65,13 +67,35 @@ class PromptCompactor:
65
67
  (re.compile(r"\b(unit_test|юнит\w*)\b", re.I), "unit_test"),
66
68
  ]
67
69
 
70
+ DEFAULT_MIN_DISTILL_TOKENS = 100
71
+
72
+ @classmethod
73
+ def _get_min_distill_tokens(cls) -> int:
74
+ """Loads minimum token threshold for LLM distillation from config or returns 100."""
75
+ base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
76
+ config_path = os.path.join(base_dir, "data", "config.json")
77
+ if os.path.exists(config_path):
78
+ try:
79
+ with open(config_path, "r", encoding="utf-8") as f:
80
+ conf = json.load(f)
81
+ if "llm_distill_min_tokens" in conf:
82
+ return int(conf["llm_distill_min_tokens"])
83
+ except Exception:
84
+ pass
85
+ return cls.DEFAULT_MIN_DISTILL_TOKENS
86
+
68
87
  @classmethod
69
- def compact(cls, raw_text: str, enable_deepseek: bool = True) -> Dict[str, any]:
88
+ def compact(
89
+ cls,
90
+ raw_text: str,
91
+ enable_deepseek: bool = True,
92
+ min_distill_tokens: Optional[int] = None
93
+ ) -> Dict[str, Any]:
70
94
  """
71
95
  Compresses input prompt via 3-Tier Architecture:
72
96
  - Tier 0: Pass-through for very short inputs (< 6 tokens)
73
- - Tier 2: DeepSeek-V3 Distiller for complex/long inputs (> 15 tokens)
74
- - Tier 1: Local Regex Compactor (fallback or structured commands)
97
+ - Tier 1: Local Regex Compactor (0ms, 0 external tokens) for inputs < 100 tokens
98
+ - Tier 2: LLM Distiller (DeepSeek / Gemini / OpenAI) for long/complex prompts (>= 100 tokens)
75
99
  """
76
100
  if not raw_text or not raw_text.strip():
77
101
  return {
@@ -112,7 +136,8 @@ class PromptCompactor:
112
136
  }
113
137
 
114
138
  # Tier 2: LLM Intent Distiller (Gemini / OpenAI / DeepSeek)
115
- if enable_deepseek and original_tokens >= 15:
139
+ min_distill = min_distill_tokens if min_distill_tokens is not None else cls._get_min_distill_tokens()
140
+ if enable_deepseek and original_tokens >= min_distill:
116
141
  distilled = UniversalDistiller.distill(raw_text)
117
142
  if distilled:
118
143
  dist_tokens = count_tokens(distilled)
@@ -10,6 +10,7 @@ import re
10
10
  import urllib.request
11
11
  import urllib.error
12
12
  from typing import Optional, Dict, Any
13
+ from src.distiller_cache import DistillationCache
13
14
 
14
15
  class DeepSeekDistiller:
15
16
  """Uses DeepSeek-Flash as a high-density semantic compiler for prompts."""
@@ -33,7 +34,7 @@ Output: (DEBUG auth.controller.ts [oauth google timeout_504 missing_avatar] "fix
33
34
  Rules:
34
35
  1. Output ONLY the S-Expression starting with ( and ending with ).
35
36
  2. No markdown code blocks, no preamble, no explanations.
36
- 3. Keep minimal_intent ultra-compact (under 10 words, English preferred for BPE token economy)."""
37
+ 3. Keep minimal_intent ultra-compact (under 10 words, English preferred for BPE token economy). Total response MUST be under 50 tokens."""
37
38
 
38
39
  @classmethod
39
40
  def _get_config(cls) -> Dict[str, Any]:
@@ -56,6 +57,7 @@ Rules:
56
57
  config["api_key"] = file_conf["deepseek_api_key"]
57
58
  config["model"] = file_conf.get("deepseek_model", config["model"])
58
59
  config["timeout"] = file_conf.get("deepseek_timeout", config["timeout"])
60
+ config["max_tokens"] = int(file_conf.get("distill_max_tokens", 60))
59
61
  config["enabled"] = file_conf.get("enable_deepseek_tier", True)
60
62
  except Exception:
61
63
  pass
@@ -72,6 +74,11 @@ Rules:
72
74
  if not conf["enabled"] or not conf["api_key"] or not raw_text or len(raw_text.strip()) < 10:
73
75
  return None
74
76
 
77
+ # Check distillation cache before remote roundtrips
78
+ cached = DistillationCache.get(raw_text)
79
+ if cached:
80
+ return cached
81
+
75
82
  payload = {
76
83
  "model": conf["model"],
77
84
  "messages": [
@@ -79,7 +86,7 @@ Rules:
79
86
  {"role": "user", "content": raw_text.strip()}
80
87
  ],
81
88
  "temperature": 0.0,
82
- "max_tokens": 300,
89
+ "max_tokens": conf.get("max_tokens", 60),
83
90
  "effort": "low"
84
91
  }
85
92
 
@@ -102,6 +109,7 @@ Rules:
102
109
  # Clean backticks if any
103
110
  content = re.sub(r"^```[a-zA-Z]*\n?|```$", "", content).strip()
104
111
  if content.startswith("(") and content.endswith(")"):
112
+ DistillationCache.set(raw_text, content, provider="deepseek")
105
113
  return content
106
114
  except Exception:
107
115
  # Network issue, timeout, or rate limit: fallback gracefully
package/src/distiller.py CHANGED
@@ -11,6 +11,7 @@ import re
11
11
  import urllib.request
12
12
  import urllib.error
13
13
  from typing import Optional, Dict, Any, Tuple
14
+ from src.distiller_cache import DistillationCache
14
15
 
15
16
  class UniversalDistiller:
16
17
  """Multi-provider semantic intent compiler supporting DeepSeek, OpenAI, and Google Gemini."""
@@ -32,7 +33,7 @@ Output: (DEBUG auth.controller.ts [oauth google timeout_504 missing_avatar] "fix
32
33
  Rules:
33
34
  1. Output ONLY the S-Expression starting with ( and ending with ).
34
35
  2. No markdown code blocks, no preamble, no explanations.
35
- 3. Keep minimal_intent ultra-compact (under 10 words, English preferred for BPE token economy)."""
36
+ 3. Keep minimal_intent ultra-compact (under 10 words, English preferred for BPE token economy). Total response MUST be under 50 tokens."""
36
37
 
37
38
  PROVIDERS = {
38
39
  "deepseek": {
@@ -82,12 +83,14 @@ Rules:
82
83
  if api_key:
83
84
  model = config_file_data.get(f"{key}_model", p_info["default_model"])
84
85
  timeout = float(config_file_data.get(f"{key}_timeout", cls.DEFAULT_TIMEOUT))
86
+ max_tokens = int(config_file_data.get("distill_max_tokens", 60))
85
87
  available[key] = {
86
88
  "provider": key,
87
89
  "name": p_info["name"],
88
90
  "api_key": api_key,
89
91
  "model": model,
90
92
  "timeout": timeout,
93
+ "max_tokens": max_tokens,
91
94
  "endpoint": p_info["endpoint"]
92
95
  }
93
96
 
@@ -102,6 +105,11 @@ Rules:
102
105
  if not raw_text or len(raw_text.strip()) < 10:
103
106
  return None
104
107
 
108
+ # Check distillation cache before remote API roundtrips
109
+ cached = DistillationCache.get(raw_text)
110
+ if cached:
111
+ return cached
112
+
105
113
  providers = cls.get_configured_providers()
106
114
  if not providers:
107
115
  return None
@@ -127,6 +135,7 @@ Rules:
127
135
  if result:
128
136
  clean = cls._sanitize_s_expression(result)
129
137
  if clean:
138
+ DistillationCache.set(raw_text, clean, provider=p_key)
130
139
  return clean
131
140
  except Exception:
132
141
  continue
@@ -142,7 +151,7 @@ Rules:
142
151
  {"role": "user", "content": raw_text.strip()}
143
152
  ],
144
153
  "temperature": 0.0,
145
- "max_tokens": 300
154
+ "max_tokens": conf.get("max_tokens", 60)
146
155
  }
147
156
  if conf.get("provider") == "deepseek" or "deepseek" in str(conf.get("endpoint", "")).lower():
148
157
  payload["effort"] = "low"
@@ -177,7 +186,7 @@ Rules:
177
186
  ],
178
187
  "generationConfig": {
179
188
  "temperature": 0.0,
180
- "maxOutputTokens": 100
189
+ "maxOutputTokens": conf.get("max_tokens", 60)
181
190
  }
182
191
  }
183
192
 
@@ -0,0 +1,216 @@
1
+ """
2
+ Distillation Cache: Two-tier (In-Memory LRU + SQLite) cache for semantic prompt distillations.
3
+ Prevents duplicate LLM provider API roundtrips (DeepSeek / Gemini / OpenAI).
4
+ Zero external runtime dependencies.
5
+ """
6
+
7
+ import os
8
+ import hashlib
9
+ import sqlite3
10
+ import threading
11
+ from collections import OrderedDict
12
+ from datetime import datetime
13
+ from typing import Optional, Dict, Any
14
+
15
+ class DistillationCache:
16
+ """Thread-safe two-tier cache (In-Memory LRU + Persistent SQLite)."""
17
+
18
+ _lock = threading.Lock()
19
+ _memory_cache: OrderedDict = OrderedDict()
20
+ _MAX_MEMORY_ENTRIES = 1000
21
+ _db_path: Optional[str] = None
22
+ _hits: int = 0
23
+ _misses: int = 0
24
+
25
+ @classmethod
26
+ def _normalize_prompt(cls, prompt_text: str) -> str:
27
+ """Strips and normalizes whitespace."""
28
+ return " ".join((prompt_text or "").strip().split())
29
+
30
+ @classmethod
31
+ def _hash_prompt(cls, prompt_text: str) -> str:
32
+ """Returns SHA-256 hash of normalized prompt text."""
33
+ norm = cls._normalize_prompt(prompt_text)
34
+ return hashlib.sha256(norm.encode("utf-8")).hexdigest()
35
+
36
+ @classmethod
37
+ def _get_db_path(cls) -> str:
38
+ if cls._db_path:
39
+ return cls._db_path
40
+
41
+ base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
42
+ data_dir = os.environ.get("TOKENSAFE_DATA_DIR", os.path.join(base_dir, "data"))
43
+ os.makedirs(data_dir, exist_ok=True)
44
+ cls._db_path = os.path.join(data_dir, "metrics.db")
45
+ return cls._db_path
46
+
47
+ @classmethod
48
+ def _init_db(cls, conn: sqlite3.Connection):
49
+ conn.execute("""
50
+ CREATE TABLE IF NOT EXISTS distillation_cache (
51
+ prompt_hash TEXT PRIMARY KEY,
52
+ prompt_text TEXT,
53
+ distilled_text TEXT NOT NULL,
54
+ provider TEXT NOT NULL,
55
+ created_at TEXT NOT NULL,
56
+ hit_count INTEGER DEFAULT 0
57
+ );
58
+ """)
59
+ conn.execute("CREATE INDEX IF NOT EXISTS idx_distill_hash ON distillation_cache(prompt_hash);")
60
+
61
+ @classmethod
62
+ def get(cls, prompt_text: str) -> Optional[str]:
63
+ """Retrieves cached distillation S-Expression if present."""
64
+ if not prompt_text or not prompt_text.strip():
65
+ return None
66
+
67
+ h = cls._hash_prompt(prompt_text)
68
+
69
+ with cls._lock:
70
+ # 1. Check in-memory LRU
71
+ if h in cls._memory_cache:
72
+ cls._hits += 1
73
+ distilled = cls._memory_cache.pop(h)
74
+ cls._memory_cache[h] = distilled # Move to end (most recently used)
75
+ return distilled
76
+
77
+ # 2. Check SQLite persistent cache
78
+ db_path = cls._get_db_path()
79
+ conn = None
80
+ try:
81
+ conn = sqlite3.connect(db_path, timeout=5.0)
82
+ cls._init_db(conn)
83
+ cursor = conn.cursor()
84
+ cursor.execute(
85
+ "SELECT distilled_text, hit_count FROM distillation_cache WHERE prompt_hash = ?",
86
+ (h,)
87
+ )
88
+ row = cursor.fetchone()
89
+ if row:
90
+ distilled_text, hit_count = row[0], row[1]
91
+ cursor.execute(
92
+ "UPDATE distillation_cache SET hit_count = ? WHERE prompt_hash = ?",
93
+ (hit_count + 1, h)
94
+ )
95
+ conn.commit()
96
+
97
+ with cls._lock:
98
+ cls._hits += 1
99
+ cls._memory_cache[h] = distilled_text
100
+ if len(cls._memory_cache) > cls._MAX_MEMORY_ENTRIES:
101
+ cls._memory_cache.popitem(last=False) # Evict oldest
102
+
103
+ return distilled_text
104
+ except Exception:
105
+ pass
106
+ finally:
107
+ if conn:
108
+ try:
109
+ conn.close()
110
+ except Exception:
111
+ pass
112
+
113
+ with cls._lock:
114
+ cls._misses += 1
115
+ return None
116
+
117
+ @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."""
120
+ if not prompt_text or not distilled_text or not distilled_text.strip():
121
+ return
122
+
123
+ h = cls._hash_prompt(prompt_text)
124
+ norm_prompt = cls._normalize_prompt(prompt_text)
125
+ now_iso = datetime.now().isoformat()
126
+
127
+ with cls._lock:
128
+ cls._memory_cache[h] = distilled_text.strip()
129
+ if len(cls._memory_cache) > cls._MAX_MEMORY_ENTRIES:
130
+ cls._memory_cache.popitem(last=False)
131
+
132
+ db_path = cls._get_db_path()
133
+ conn = None
134
+ try:
135
+ conn = sqlite3.connect(db_path, timeout=5.0)
136
+ cls._init_db(conn)
137
+ cursor = conn.cursor()
138
+ cursor.execute("""
139
+ INSERT INTO distillation_cache (prompt_hash, prompt_text, distilled_text, provider, created_at, hit_count)
140
+ VALUES (?, ?, ?, ?, ?, 0)
141
+ ON CONFLICT(prompt_hash) DO UPDATE SET
142
+ distilled_text = excluded.distilled_text,
143
+ provider = excluded.provider
144
+ """, (h, norm_prompt[:500], distilled_text.strip(), provider, now_iso))
145
+ conn.commit()
146
+ except Exception:
147
+ pass
148
+ finally:
149
+ if conn:
150
+ try:
151
+ conn.close()
152
+ except Exception:
153
+ pass
154
+
155
+ @classmethod
156
+ def clear(cls) -> None:
157
+ """Clears both in-memory and persistent SQLite cache."""
158
+ with cls._lock:
159
+ cls._memory_cache.clear()
160
+ cls._hits = 0
161
+ cls._misses = 0
162
+
163
+ db_path = cls._get_db_path()
164
+ conn = None
165
+ try:
166
+ conn = sqlite3.connect(db_path, timeout=5.0)
167
+ cls._init_db(conn)
168
+ conn.execute("DELETE FROM distillation_cache;")
169
+ conn.commit()
170
+ except Exception:
171
+ pass
172
+ finally:
173
+ if conn:
174
+ try:
175
+ conn.close()
176
+ except Exception:
177
+ pass
178
+
179
+ @classmethod
180
+ def get_stats(cls) -> Dict[str, Any]:
181
+ """Returns runtime cache statistics."""
182
+ with cls._lock:
183
+ mem_size = len(cls._memory_cache)
184
+ hits = cls._hits
185
+ misses = cls._misses
186
+
187
+ total_db_entries = 0
188
+ db_path = cls._get_db_path()
189
+ conn = None
190
+ try:
191
+ conn = sqlite3.connect(db_path, timeout=5.0)
192
+ cls._init_db(conn)
193
+ cursor = conn.cursor()
194
+ cursor.execute("SELECT count(*) FROM distillation_cache")
195
+ row = cursor.fetchone()
196
+ if row:
197
+ total_db_entries = row[0]
198
+ except Exception:
199
+ pass
200
+ finally:
201
+ if conn:
202
+ try:
203
+ conn.close()
204
+ except Exception:
205
+ pass
206
+
207
+ total_lookups = hits + misses
208
+ hit_ratio = (hits / total_lookups * 100.0) if total_lookups > 0 else 0.0
209
+
210
+ return {
211
+ "memory_entries": mem_size,
212
+ "persistent_entries": total_db_entries,
213
+ "hits": hits,
214
+ "misses": misses,
215
+ "hit_ratio_pct": round(hit_ratio, 1)
216
+ }
package/src/mcp_server.py CHANGED
@@ -28,7 +28,7 @@ from src.diff_slicer import DiffSlicer
28
28
 
29
29
  SERVER_INFO = {
30
30
  "name": "tokensafe-mcp",
31
- "version": "1.3.1"
31
+ "version": "1.3.2"
32
32
  }
33
33
 
34
34
  TOOLS = [
@@ -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.1"
17
+ CURRENT_VERSION = "1.3.2"
18
18
  CACHE_TTL = 86400 # 24 hours
19
19
 
20
20
  PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))