tokensafe 2.7.1 → 2.7.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,7 +1,7 @@
1
1
  {
2
2
  "name": "tokensafe",
3
3
  "mcpName": "dev.tokensafe/tokensafe",
4
- "version": "2.7.1",
4
+ "version": "2.7.2",
5
5
  "description": "Reduce your AI bills by up to 99% locally. Your agents read only needed code, keep prompt caches intact across turns, and keep secrets out of git.",
6
6
  "main": "bin/tokensafe.js",
7
7
  "bin": {
package/plugin.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "tokensafe",
3
3
  "displayName": "TokenSafe",
4
- "version": "2.7.1",
4
+ "version": "2.7.2",
5
5
  "description": "Reduce your AI bills by up to 99% locally. Your agents read only needed code, keep prompt caches intact across turns, and keep secrets out of git.",
6
6
  "logo": "assets/logo.svg",
7
7
  "author": {
package/server.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "name": "dev.tokensafe/tokensafe",
4
4
  "title": "TokenSafe",
5
5
  "description": "Reduce your AI bills by up to 99% locally: focused code, warm prompt caches & zero secret leaks.",
6
- "version": "2.7.1",
6
+ "version": "2.7.2",
7
7
  "websiteUrl": "https://tokensafe.dev",
8
8
  "repository": {
9
9
  "url": "https://github.com/tokensafe-dev/tokensafe",
@@ -30,7 +30,7 @@
30
30
  "registryType": "npm",
31
31
  "registryBaseUrl": "https://registry.npmjs.org",
32
32
  "identifier": "tokensafe",
33
- "version": "2.7.1",
33
+ "version": "2.7.2",
34
34
  "runtimeHint": "npx",
35
35
  "transport": {
36
36
  "type": "stdio"
@@ -46,7 +46,7 @@
46
46
  "registryType": "pypi",
47
47
  "registryBaseUrl": "https://pypi.org",
48
48
  "identifier": "tokensafe",
49
- "version": "2.7.1",
49
+ "version": "2.7.2",
50
50
  "runtimeHint": "uvx",
51
51
  "transport": {
52
52
  "type": "stdio"
@@ -278,7 +278,12 @@ class DistillationCache:
278
278
  team_tmpl = TeamCache.get("PROMPT_TMPL", tmpl_prompt)
279
279
  instantiated = cls._instantiate_template(team_tmpl, slots) if team_tmpl else None
280
280
  if instantiated:
281
- cls.set(prompt_text, instantiated, provider="team_template_cache", sync_remote=False)
281
+ with cls._lock:
282
+ cls._template_memory_cache[tmpl_hash] = team_tmpl
283
+ cls._template_memory_cache.move_to_end(tmpl_hash)
284
+ if len(cls._template_memory_cache) > cls._MAX_MEMORY_ENTRIES:
285
+ cls._template_memory_cache.popitem(last=False)
286
+ cls.set(prompt_text, instantiated, provider="team_template_cache", sync_remote=False, store_template=False)
282
287
  with cls._lock:
283
288
  cls._hits += 1
284
289
  return instantiated
package/src/mcp_server.py CHANGED
@@ -40,7 +40,7 @@ from src.license_manager import LicenseManager
40
40
 
41
41
  SERVER_INFO = {
42
42
  "name": "tokensafe-mcp",
43
- "version": "2.7.1"
43
+ "version": "2.7.2"
44
44
  }
45
45
 
46
46
  # MCP client attribution: the initialize handshake carries clientInfo, which
@@ -508,10 +508,11 @@ def _team_cache_key(path: str, symbol: str, dep_mode: str = "signature") -> str:
508
508
  def _team_skeleton_lookup(path: str, symbol: str, dep_mode: str = "signature") -> Optional[str]:
509
509
  """Team cache pre-warm lookup: returns a teammate's cached skeleton or None.
510
510
 
511
- Never blocks the caller for more than ~250ms: the network fetch runs in a
512
- daemon thread with a short join. Non-team installs skip the network entirely."""
511
+ Never blocks the caller for more than ~450ms: the HTTP timeout matches
512
+ the thread join so discarded timeouts don't inflate cloud hit_count.
513
+ Non-team installs skip the network entirely."""
513
514
  try:
514
- is_team, _ = TeamCache._is_team_tier()
515
+ is_team, lic_key = TeamCache._is_team_tier()
515
516
  if not is_team:
516
517
  return None
517
518
  cache_key = _team_cache_key(path, symbol, dep_mode=dep_mode)
@@ -519,13 +520,13 @@ def _team_skeleton_lookup(path: str, symbol: str, dep_mode: str = "signature") -
519
520
 
520
521
  def _fetch():
521
522
  try:
522
- box["value"] = TeamCache.get("SKELETON", cache_key)
523
+ box["value"] = TeamCache.get("SKELETON", cache_key, timeout=0.45, lic_key=lic_key)
523
524
  except Exception:
524
525
  pass
525
526
 
526
527
  t = threading.Thread(target=_fetch, daemon=True)
527
528
  t.start()
528
- t.join(0.25)
529
+ t.join(0.45)
529
530
  return box.get("value")
530
531
  except Exception:
531
532
  return None
package/src/team_cache.py CHANGED
@@ -21,6 +21,31 @@ class TeamCache:
21
21
  DEFAULT_TIMEOUT = float(os.environ.get("TOKENSAFE_CACHE_TIMEOUT", "1.2")) # Fast 1.2s timeout to prevent blocking agent turns
22
22
  FAILURE_COOLDOWN_SECONDS = 120.0
23
23
  _cooldown_until: float = 0.0
24
+ _cooldowns: Dict[str, float] = {}
25
+ _cooldown_lock = threading.Lock()
26
+
27
+ @classmethod
28
+ def _is_in_cooldown(cls, cloud_url: Optional[str] = None) -> bool:
29
+ now = time.monotonic()
30
+ url = cloud_url or cls._get_cloud_url()
31
+ with cls._cooldown_lock:
32
+ if cls._cooldown_until > now:
33
+ return True
34
+ return cls._cooldowns.get(url, 0.0) > now
35
+
36
+ @classmethod
37
+ def _trip_cooldown(cls, cloud_url: Optional[str] = None) -> None:
38
+ url = cloud_url or cls._get_cloud_url()
39
+ until = time.monotonic() + cls.FAILURE_COOLDOWN_SECONDS
40
+ with cls._cooldown_lock:
41
+ cls._cooldowns[url] = until
42
+
43
+ @classmethod
44
+ def _clear_cooldown(cls, cloud_url: Optional[str] = None) -> None:
45
+ url = cloud_url or cls._get_cloud_url()
46
+ with cls._cooldown_lock:
47
+ cls._cooldown_until = 0.0
48
+ cls._cooldowns.pop(url, None)
24
49
 
25
50
  @classmethod
26
51
  def _get_cloud_url(cls) -> str:
@@ -45,19 +70,30 @@ class TeamCache:
45
70
  return hashlib.sha256(norm.encode("utf-8")).hexdigest()
46
71
 
47
72
  @classmethod
48
- def get(cls, cache_type: str, key_text: str) -> Optional[str]:
73
+ def get(
74
+ cls,
75
+ cache_type: str,
76
+ key_text: str,
77
+ timeout: Optional[float] = None,
78
+ lic_key: Optional[str] = None,
79
+ ) -> Optional[str]:
49
80
  """
50
81
  Queries Shared Team Cache for compiled S-Expression or AST Skeleton.
51
82
  Returns cached value string or None if miss/disabled/timed out/in cooldown.
52
83
  """
53
- if time.monotonic() < cls._cooldown_until:
84
+ cloud_url = cls._get_cloud_url()
85
+ if cls._is_in_cooldown(cloud_url):
54
86
  return None
55
- is_team, lic_key = cls._is_team_tier()
56
- if not is_team or not key_text:
87
+ if not lic_key:
88
+ is_team, resolved_key = cls._is_team_tier()
89
+ if not is_team:
90
+ return None
91
+ lic_key = resolved_key
92
+ if not cache_type or not key_text:
57
93
  return None
58
94
 
59
95
  h = cls.hash_key(key_text)
60
- endpoint = f"{cls._get_cloud_url()}/api/team/cache?type={urllib.parse.quote(cache_type)}&hash={h}"
96
+ endpoint = f"{cloud_url}/api/team/cache?type={urllib.parse.quote(cache_type)}&hash={h}"
61
97
 
62
98
  req = urllib.request.Request(
63
99
  endpoint,
@@ -67,42 +103,69 @@ class TeamCache:
67
103
  }
68
104
  )
69
105
 
106
+ eff_timeout = cls.DEFAULT_TIMEOUT if timeout is None else max(0.05, float(timeout))
70
107
  try:
71
- with urllib.request.urlopen(req, timeout=cls.DEFAULT_TIMEOUT) as resp:
108
+ with urllib.request.urlopen(req, timeout=eff_timeout) as resp:
72
109
  if resp.status == 200:
73
110
  data = json.loads(resp.read().decode("utf-8"))
74
111
  val = data.get("value") or data.get("cached_value")
112
+ cls._clear_cooldown(cloud_url)
75
113
  if data.get("hit") and val:
76
- cls._cooldown_until = 0.0
77
114
  return val
115
+ except urllib.error.HTTPError as he:
116
+ # Trip circuit breaker on auth rejection or server 5xx outage
117
+ if he.code in (401, 403) or he.code >= 500:
118
+ cls._trip_cooldown(cloud_url)
119
+ return None
78
120
  except Exception:
79
- # Circuit-break offline/unreachable cloud calls for 120s so misses don't stall repeated prompts
80
- cls._cooldown_until = time.monotonic() + cls.FAILURE_COOLDOWN_SECONDS
121
+ # Circuit-break offline/unreachable cloud calls so misses don't stall repeated prompts
122
+ cls._trip_cooldown(cloud_url)
81
123
  return None
82
124
 
83
125
  return None
84
126
 
85
127
  @classmethod
86
- def put(cls, cache_type: str, key_text: str, value: str, tokens_saved: int = 0) -> None:
128
+ def put(
129
+ cls,
130
+ cache_type: str,
131
+ key_text: str,
132
+ value: str,
133
+ tokens_saved: int = 0,
134
+ lic_key: Optional[str] = None,
135
+ ) -> None:
87
136
  """
88
137
  Asynchronously broadcasts a freshly compiled distillation or skeleton to the Team Cache.
89
138
  Runs in a detached daemon thread so developer workflows never wait on network I/O.
90
139
  """
91
- is_team, lic_key = cls._is_team_tier()
92
- if not is_team or not key_text or not value:
140
+ cloud_url = cls._get_cloud_url()
141
+ if cls._is_in_cooldown(cloud_url):
142
+ return
143
+ if not lic_key:
144
+ is_team, resolved_key = cls._is_team_tier()
145
+ if not is_team:
146
+ return
147
+ lic_key = resolved_key
148
+ if not cache_type or not key_text or not value:
93
149
  return
94
150
 
151
+ safe_value = value
152
+ try:
153
+ from src.secret_redactor import SecretRedactor
154
+ safe_value, _, _ = SecretRedactor.redact_text(value)
155
+ except Exception:
156
+ pass
157
+
95
158
  h = cls.hash_key(key_text)
96
159
 
97
160
  def _worker():
98
161
  payload = {
99
162
  "type": cache_type,
100
163
  "hash": h,
101
- "value": value,
102
- "tokens_saved": max(0, tokens_saved),
164
+ "value": safe_value,
165
+ "tokens_saved": max(0, int(tokens_saved or 0)),
103
166
  "license_key": lic_key
104
167
  }
105
- endpoint = f"{cls._get_cloud_url()}/api/team/cache"
168
+ endpoint = f"{cloud_url}/api/team/cache"
106
169
  req = urllib.request.Request(
107
170
  endpoint,
108
171
  data=json.dumps(payload).encode("utf-8"),
@@ -114,9 +177,12 @@ class TeamCache:
114
177
  )
115
178
  try:
116
179
  with urllib.request.urlopen(req, timeout=1.5):
117
- pass
180
+ cls._clear_cooldown(cloud_url)
181
+ except urllib.error.HTTPError as he:
182
+ if he.code in (401, 403) or he.code >= 500:
183
+ cls._trip_cooldown(cloud_url)
118
184
  except Exception:
119
- pass
185
+ cls._trip_cooldown(cloud_url)
120
186
 
121
187
  t = threading.Thread(target=_worker, daemon=True)
122
188
  t.start()
@@ -228,7 +228,7 @@ class TelemetrySync:
228
228
  current_last_id = last_id
229
229
  headers = {
230
230
  "Content-Type": "application/json",
231
- "User-Agent": "TokenSafe-Sync/2.7.1"
231
+ "User-Agent": "TokenSafe-Sync/2.7.2"
232
232
  }
233
233
  if active_key:
234
234
  headers["Authorization"] = f"Bearer {active_key}"
@@ -17,7 +17,7 @@ import urllib.request
17
17
  import urllib.error
18
18
  from typing import Dict, Any, Optional, Tuple
19
19
 
20
- CURRENT_VERSION = "2.7.1"
20
+ CURRENT_VERSION = "2.7.2"
21
21
  CACHE_TTL = 86400 # 24 hours
22
22
  # When the cloud is unreachable we must NOT cache the synthesized "up to date"
23
23
  # answer for a full day — otherwise an update released right after an outage