tokensafe 2.4.2 → 2.5.0

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/src/proxy.py CHANGED
@@ -183,8 +183,11 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
183
183
  return
184
184
 
185
185
  proxy_tracker = MetricsTracker()
186
+ from src.license_manager import LicenseManager
187
+ quota = LicenseManager.check_quota(proxy_tracker)
188
+ is_quota_exceeded = bool(quota.get("is_quota_exceeded", False))
186
189
 
187
- # 1. Local Secret Redaction: Scrub credentials across all messages before dispatch
190
+ # 1. Local Secret Redaction: Scrub credentials across all messages before dispatch (always active)
188
191
  messages = payload.get("messages", [])
189
192
  if messages:
190
193
  messages, secrets_scrubbed = SecretRedactor.redact_messages(messages)
@@ -192,10 +195,9 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
192
195
  print(f"[TokenSafe] Scrubbed {secrets_scrubbed} sensitive secret(s) from payload before transmission.")
193
196
 
194
197
  # 2. Ingress Optimization: REPLACE the last user message with its TOCP form.
195
- # This is the real replace-mode: the upstream model never sees the verbose
196
- # original, so the delta is literally measured (see METRICS.md).
198
+ # Paused when Community 500k monthly measured quota is exceeded.
197
199
  target_symbol = None
198
- if messages:
200
+ if messages and not is_quota_exceeded:
199
201
  for idx in reversed(range(len(messages))):
200
202
  msg = messages[idx]
201
203
  if msg.get("role") == "user" and isinstance(msg.get("content"), str):
@@ -223,7 +225,7 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
223
225
  break
224
226
 
225
227
  # 3. Automatic Architecture Awareness (God Nodes Injection)
226
- if messages:
228
+ if messages and not is_quota_exceeded:
227
229
  try:
228
230
  graph = GraphEngine.get_instance(os.getcwd())
229
231
  banner = graph.format_topology_banner()
@@ -234,23 +236,10 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
234
236
  except Exception:
235
237
  pass
236
238
 
237
- # 4. Prompt Cache Prefix Normalization (100% Cache Hits)
238
- if messages:
239
- messages, cache_meta = PromptCacheNormalizer.normalize_messages(messages)
240
- payload["messages"] = messages
241
-
242
- # 5. Context Window Governor (Budget Autothrottle)
243
- if messages:
244
- messages, gov_stats = ContextGovernor.govern_messages(messages, session_id="proxy_session")
245
- payload["messages"] = messages
246
- if gov_stats.get("throttled"):
247
- BROADCASTER.publish("governor_throttle", gov_stats)
248
-
249
- # 6. Resolve Multi-Provider Upstream & API Key
239
+ # 4. Resolve Multi-Provider Upstream & API Key (needed before provider-aware cache breakpoints)
250
240
  auth_header = self.headers.get("Authorization", "")
251
241
  custom_url = os.environ.get("TOKENSAFE_UPSTREAM_URL", "")
252
242
 
253
- # Supported keys from environment or config
254
243
  data_dir = resolve_data_dir()
255
244
  conf_keys = {}
256
245
  config_path = os.path.join(data_dir, "config.json")
@@ -261,37 +250,38 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
261
250
  except Exception:
262
251
  pass
263
252
 
264
- deepseek_key = os.environ.get("DEEPSEEK_API_KEY", "") or conf_keys.get("deepseek_api_key", "")
265
- openai_key = os.environ.get("OPENAI_API_KEY", "") or conf_keys.get("openai_api_key", "")
266
- gemini_key = os.environ.get("GEMINI_API_KEY", "") or conf_keys.get("gemini_api_key", "")
267
- anthropic_key = os.environ.get("ANTHROPIC_API_KEY", "") or conf_keys.get("anthropic_api_key", "")
268
- generic_upstream_key = os.environ.get("TOKENSAFE_UPSTREAM_KEY", "")
253
+ upstream_url, resolved_key = self._resolve_upstream(conf_keys, custom_url)
254
+ provider = self._detect_provider(upstream_url)
255
+
256
+ # 5. Epoch-Aware Context Governor (runs BEFORE cache normalization so breakpoints stay valid)
257
+ if messages and not is_quota_exceeded:
258
+ messages, gov_stats = ContextGovernor.govern_messages(
259
+ messages,
260
+ session_id="proxy_session",
261
+ model=str(payload.get("model") or ""),
262
+ append_only=True,
263
+ )
264
+ payload["messages"] = messages
265
+ if gov_stats.get("throttled"):
266
+ BROADCASTER.publish("governor_throttle", gov_stats)
269
267
 
270
- # Infer upstream URL if not provided
271
- pref = conf_keys.get("preferred_provider", "").lower()
272
- if not custom_url:
273
- if (pref == "gemini" and gemini_key) or (gemini_key and not deepseek_key and not openai_key):
274
- upstream_url = "https://generativelanguage.googleapis.com/v1beta/openai/chat/completions"
275
- resolved_key = gemini_key
276
- elif openai_key and not deepseek_key:
277
- upstream_url = "https://api.openai.com/v1/chat/completions"
278
- resolved_key = openai_key
279
- elif anthropic_key and not deepseek_key:
280
- upstream_url = "https://api.anthropic.com/v1/messages"
281
- resolved_key = anthropic_key
282
- else:
283
- upstream_url = "https://api.deepseek.com/chat/completions"
284
- resolved_key = deepseek_key or generic_upstream_key
285
- else:
286
- upstream_url = custom_url
287
- if "openai.com" in upstream_url:
288
- resolved_key = openai_key or generic_upstream_key or deepseek_key
289
- elif "anthropic.com" in upstream_url:
290
- resolved_key = anthropic_key or generic_upstream_key
291
- elif "googleapis.com" in upstream_url:
292
- resolved_key = gemini_key or generic_upstream_key
293
- else:
294
- resolved_key = deepseek_key or generic_upstream_key or openai_key
268
+ # 6. Prompt Cache Prefix & Tool Normalization (multi-breakpoint + deterministic ordering)
269
+ if not is_quota_exceeded:
270
+ if "tools" in payload and isinstance(payload["tools"], list):
271
+ payload["tools"] = PromptCacheNormalizer.normalize_tools(
272
+ payload["tools"], provider=provider, inject_cache_control=False
273
+ )
274
+ if messages:
275
+ messages, cache_meta = PromptCacheNormalizer.normalize_messages(
276
+ messages,
277
+ provider=provider,
278
+ tools=payload.get("tools") if isinstance(payload.get("tools"), list) else None,
279
+ )
280
+ payload["messages"] = messages
281
+ if cache_meta.get("normalized_tools") is not None:
282
+ payload["tools"] = cache_meta["normalized_tools"]
283
+ if provider == "openai" and cache_meta.get("prompt_cache_key"):
284
+ payload.setdefault("prompt_cache_key", cache_meta["prompt_cache_key"])
295
285
 
296
286
  headers = {"Content-Type": "application/json"}
297
287
  if auth_header:
@@ -305,7 +295,7 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
305
295
 
306
296
  req = urllib.request.Request(
307
297
  upstream_url,
308
- data=json.dumps(payload).encode("utf-8"),
298
+ data=json.dumps(payload, sort_keys=True, ensure_ascii=False).encode("utf-8"),
309
299
  headers=headers
310
300
  )
311
301
 
@@ -316,9 +306,26 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
316
306
  for k, v in resp.getheaders():
317
307
  if k.lower() in ("content-type", "content-encoding"):
318
308
  self.send_header(k, v)
309
+ if is_quota_exceeded:
310
+ self.send_header("X-TokenSafe-Quota", "exceeded")
311
+ LicenseManager.should_emit_quota_banner(proxy_tracker, session_id="proxy_session", every_n_turns=5)
319
312
  self.end_headers()
320
313
  self.wfile.write(resp_data)
321
314
 
315
+ try:
316
+ resp_json = json.loads(resp_data.decode("utf-8"))
317
+ usage = resp_json.get("usage") or {}
318
+ cached = (
319
+ (usage.get("prompt_tokens_details") or {}).get("cached_tokens")
320
+ or usage.get("cache_read_input_tokens")
321
+ or usage.get("prompt_cache_hit_tokens")
322
+ or 0
323
+ )
324
+ if cached:
325
+ BROADCASTER.publish("cache_stats", {"provider": provider, "cached_tokens": int(cached)})
326
+ except Exception:
327
+ pass
328
+
322
329
  # Broadcast live telemetry update to SSE dashboard subscribers
323
330
  try:
324
331
  tracker = MetricsTracker()
@@ -335,6 +342,45 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
335
342
  self.end_headers()
336
343
  self.wfile.write(json.dumps({"error": f"Upstream proxy error: {str(e)}"}).encode("utf-8"))
337
344
 
345
+ @staticmethod
346
+ def _detect_provider(upstream_url: str) -> str:
347
+ url = (upstream_url or "").lower()
348
+ if "anthropic.com" in url:
349
+ return "anthropic"
350
+ if "openai.com" in url:
351
+ return "openai"
352
+ if "googleapis.com" in url or "generativelanguage" in url:
353
+ return "gemini"
354
+ if "deepseek.com" in url:
355
+ return "deepseek"
356
+ return "generic"
357
+
358
+ @staticmethod
359
+ def _resolve_upstream(conf_keys: Dict[str, Any], custom_url: str):
360
+ deepseek_key = os.environ.get("DEEPSEEK_API_KEY", "") or conf_keys.get("deepseek_api_key", "")
361
+ openai_key = os.environ.get("OPENAI_API_KEY", "") or conf_keys.get("openai_api_key", "")
362
+ gemini_key = os.environ.get("GEMINI_API_KEY", "") or conf_keys.get("gemini_api_key", "")
363
+ anthropic_key = os.environ.get("ANTHROPIC_API_KEY", "") or conf_keys.get("anthropic_api_key", "")
364
+ generic_upstream_key = os.environ.get("TOKENSAFE_UPSTREAM_KEY", "")
365
+
366
+ pref = str(conf_keys.get("preferred_provider", "")).lower()
367
+ if not custom_url:
368
+ if (pref == "gemini" and gemini_key) or (gemini_key and not deepseek_key and not openai_key):
369
+ return "https://generativelanguage.googleapis.com/v1beta/openai/chat/completions", gemini_key
370
+ if openai_key and not deepseek_key:
371
+ return "https://api.openai.com/v1/chat/completions", openai_key
372
+ if anthropic_key and not deepseek_key:
373
+ return "https://api.anthropic.com/v1/messages", anthropic_key
374
+ return "https://api.deepseek.com/chat/completions", (deepseek_key or generic_upstream_key)
375
+
376
+ if "openai.com" in custom_url:
377
+ return custom_url, (openai_key or generic_upstream_key or deepseek_key)
378
+ if "anthropic.com" in custom_url:
379
+ return custom_url, (anthropic_key or generic_upstream_key)
380
+ if "googleapis.com" in custom_url:
381
+ return custom_url, (gemini_key or generic_upstream_key)
382
+ return custom_url, (deepseek_key or generic_upstream_key or openai_key)
383
+
338
384
  def run_proxy(port: int = DEFAULT_PORT, host: str = DEFAULT_HOST):
339
385
  # Auto-initialize Knowledge Graph & API Surface on startup
340
386
  hubs_summary = "active"
@@ -172,17 +172,84 @@ class Skeletonizer:
172
172
  CACHE_DIR = os.path.join(resolve_data_dir(), "skeletons")
173
173
 
174
174
  @classmethod
175
- def skeletonize_code(cls, code: str, file_ext: str, keep_symbols: Optional[Set[str]] = None) -> str:
175
+ def _collapse_import_lines(cls, skeleton: str, ext: str) -> str:
176
+ """Collapses runs of >5 top-level import lines into a 1-line summary for surgical reads."""
177
+ lines = skeleton.splitlines()
178
+ out = []
179
+ import_mods = []
180
+ import_lines_buf = []
181
+ in_import_block = False
182
+
183
+ def flush_imports():
184
+ non_blank_count = sum(1 for l in import_lines_buf if l.strip())
185
+ if non_blank_count > 5:
186
+ preview = ", ".join(import_mods[:8])
187
+ if len(import_mods) > 8:
188
+ preview += f", +{len(import_mods) - 8}"
189
+ comment_prefix = "#" if ext == ".py" else "//"
190
+ out.append(f"{comment_prefix} [Collapsed {non_blank_count} imports: {preview}]")
191
+ else:
192
+ out.extend(import_lines_buf)
193
+ import_mods.clear()
194
+ import_lines_buf.clear()
195
+
196
+ for line in lines:
197
+ stripped = line.strip()
198
+ is_imp = False
199
+ mod = ""
200
+ if ext == ".py":
201
+ m1 = re.match(r"^import\s+([A-Za-z0-9_.,\s]+)", stripped)
202
+ m2 = re.match(r"^from\s+([A-Za-z0-9_.]+)\s+import\b", stripped)
203
+ if m1:
204
+ is_imp = True
205
+ mod = m1.group(1).split(",")[0].split(" as ")[0].strip()
206
+ elif m2:
207
+ is_imp = True
208
+ mod = m2.group(1).strip()
209
+ else:
210
+ m3 = re.match(r"""^import\s+.*?\s+from\s+['"]([^'"]+)['"]""", stripped)
211
+ if m3:
212
+ is_imp = True
213
+ mod = m3.group(1).strip()
214
+
215
+ if is_imp:
216
+ in_import_block = True
217
+ import_lines_buf.append(line)
218
+ if mod and mod not in import_mods:
219
+ import_mods.append(mod)
220
+ else:
221
+ if in_import_block:
222
+ if not stripped:
223
+ import_lines_buf.append(line)
224
+ continue
225
+ flush_imports()
226
+ in_import_block = False
227
+ out.append(line)
228
+
229
+ if import_lines_buf:
230
+ flush_imports()
231
+ return "\n".join(out)
232
+
233
+ @classmethod
234
+ def skeletonize_code(
235
+ cls,
236
+ code: str,
237
+ file_ext: str,
238
+ keep_symbols: Optional[Set[str]] = None,
239
+ collapse_imports: bool = False,
240
+ ) -> str:
176
241
  """Skeletons source code based on file extension, optionally preserving keep_symbols."""
177
242
  ext = file_ext.lower().lstrip(".")
178
243
  ext = f".{ext}" if ext else ""
179
244
  if ext == ".py":
180
- return cls._skeletonize_python(code, keep_symbols=keep_symbols)
245
+ res = cls._skeletonize_python(code, keep_symbols=keep_symbols)
246
+ return cls._collapse_import_lines(res, ext) if (collapse_imports and keep_symbols) else res
181
247
  elif ext in (
182
248
  ".ts", ".js", ".tsx", ".jsx", ".mjs", ".cjs",
183
249
  ".go", ".java", ".rs", ".cpp", ".cc", ".cxx", ".c", ".h", ".hpp", ".cs", ".php", ".kt", ".swift"
184
250
  ):
185
- return cls._skeletonize_braces(code, ext, keep_symbols=keep_symbols)
251
+ res = cls._skeletonize_braces(code, ext, keep_symbols=keep_symbols)
252
+ return cls._collapse_import_lines(res, ext) if (collapse_imports and keep_symbols) else res
186
253
  elif ext in (".css", ".scss", ".sass", ".less"):
187
254
  return cls._skeletonize_css(code, ext, keep_symbols=keep_symbols)
188
255
  return code
package/src/team_cache.py CHANGED
@@ -26,25 +26,7 @@ class TeamCache:
26
26
  @classmethod
27
27
  def _is_team_tier(cls) -> Tuple[bool, str]:
28
28
  """Checks if current active license belongs to a Team tier subscription."""
29
- key = os.environ.get("TOKENSAFE_LICENSE_KEY", "").strip()
30
- if not key:
31
- from src.paths import resolve_data_dir
32
- candidate_paths = [
33
- os.path.join(resolve_data_dir(), "license.json"),
34
- os.path.join(os.getcwd(), "data", "license.json"),
35
- os.path.expanduser("~/.tokensafe/license.json")
36
- ]
37
- for lic_file in candidate_paths:
38
- if os.path.exists(lic_file):
39
- try:
40
- with open(lic_file, "r", encoding="utf-8") as f:
41
- data = json.load(f)
42
- key = data.get("license_key", "").strip()
43
- if key:
44
- break
45
- except Exception:
46
- pass
47
-
29
+ key = LicenseManager.get_active_license_key()
48
30
  if not key:
49
31
  return False, ""
50
32
 
@@ -212,17 +212,27 @@ class TelemetrySync:
212
212
  "error": f"Failed to read local metrics database: {str(e)}"
213
213
  }
214
214
 
215
- if not rows and not synthetic_events:
216
- return {
217
- "success": True,
218
- "synced_events": 0,
219
- "total_synced": state.get("total_synced_events", 0),
220
- "message": "All metrics are already up to date."
221
- }
215
+ try:
216
+ from src.metrics import MetricsTracker
217
+ local_monthly_measured = MetricsTracker(db_path=METRICS_DB_PATH).get_monthly_saved_tokens(measured_only=True)
218
+ except Exception:
219
+ local_monthly_measured = 0
220
+ machine_fp = "" if os.environ.get("TOKENSAFE_TELEMETRY_DISABLED") in ("1", "true", "yes") else LicenseManager.get_machine_fingerprint()
222
221
 
223
- formatted_items: List[Tuple[Optional[int], Dict[str, Any]]] = [
224
- (None, ev) for ev in synthetic_events
225
- ]
222
+ if not rows and not synthetic_events:
223
+ last_q_sync = float(state.get("last_quota_sync_at", 0) or 0)
224
+ if not (machine_fp and active_key == "community" and (time.time() - last_q_sync > 3600)):
225
+ return {
226
+ "success": True,
227
+ "synced_events": 0,
228
+ "total_synced": state.get("total_synced_events", 0),
229
+ "message": "All metrics are already up to date."
230
+ }
231
+ formatted_items = [(None, None)] # quota-only probe for community tier
232
+ else:
233
+ formatted_items = [
234
+ (None, ev) for ev in synthetic_events
235
+ ]
226
236
  current_last_id = last_id
227
237
 
228
238
  for r in rows:
@@ -266,7 +276,7 @@ class TelemetrySync:
266
276
  rollup_synced = bool(state.get("lifetime_rollup_synced", False))
267
277
  headers = {
268
278
  "Content-Type": "application/json",
269
- "User-Agent": "TokenSafe-Sync/2.4.2"
279
+ "User-Agent": "TokenSafe-Sync/2.5.0"
270
280
  }
271
281
  if active_key:
272
282
  headers["Authorization"] = f"Bearer {active_key}"
@@ -288,24 +298,35 @@ class TelemetrySync:
288
298
 
289
299
  for i in range(0, len(formatted_items), batch_size):
290
300
  batch_items = formatted_items[i:i + batch_size]
291
- chunk = [item[1] for item in batch_items]
301
+ chunk = [item[1] for item in batch_items if item[1] is not None]
292
302
  body_dict = {
293
303
  "email": target_email,
294
304
  "license_key": active_key,
295
- "events": chunk
305
+ "events": chunk,
296
306
  }
307
+ if machine_fp and active_key == "community":
308
+ body_dict["machine_id"] = machine_fp
309
+ body_dict["monthly_measured_saved"] = local_monthly_measured
297
310
  body_bytes = json.dumps(body_dict).encode("utf-8")
298
311
 
299
312
  req = urllib.request.Request(target_url, data=body_bytes, headers=headers, method="POST")
300
313
  try:
301
314
  with urllib.request.urlopen(req, timeout=timeout) as resp:
302
315
  if resp.status == 200:
316
+ try:
317
+ resp_body = json.loads(resp.read().decode("utf-8") or "{}")
318
+ srv_measured = int(resp_body.get("server_monthly_measured_saved") or 0)
319
+ if srv_measured > 0:
320
+ from src.metrics import MetricsTracker
321
+ MetricsTracker(db_path=METRICS_DB_PATH).record_server_quota_floor(srv_measured)
322
+ except Exception:
323
+ pass
303
324
  total_sent += len(chunk)
304
325
  cumulative_synced += len(chunk)
305
326
  for ev_id, ev_payload in batch_items:
306
327
  if ev_id is not None and ev_id > current_last_id:
307
328
  current_last_id = ev_id
308
- if ev_payload.get("event_type") == "ROLLUP_LIFETIME":
329
+ if ev_payload and ev_payload.get("event_type") == "ROLLUP_LIFETIME":
309
330
  rollup_synced = True
310
331
  if not synthetic_events:
311
332
  rollup_synced = True
@@ -313,6 +334,7 @@ class TelemetrySync:
313
334
  "last_synced_event_id": current_last_id,
314
335
  "last_synced_at": int(time.time()),
315
336
  "last_attempt_at": int(time.time()),
337
+ "last_quota_sync_at": int(time.time()),
316
338
  "total_synced_events": cumulative_synced,
317
339
  "lifetime_rollup_synced": rollup_synced
318
340
  })
@@ -16,7 +16,7 @@ import urllib.request
16
16
  import urllib.error
17
17
  from typing import Dict, Any, Optional, Tuple
18
18
 
19
- CURRENT_VERSION = "2.4.2"
19
+ CURRENT_VERSION = "2.5.0"
20
20
  CACHE_TTL = 86400 # 24 hours
21
21
  # When the cloud is unreachable we must NOT cache the synthesized "up to date"
22
22
  # answer for a full day — otherwise an update released right after an outage
@@ -91,6 +91,15 @@ class VersionChecker:
91
91
  except Exception:
92
92
  pass
93
93
 
94
+ @staticmethod
95
+ def _cache_matches_version(cached: Optional[Dict[str, Any]], current_version: str) -> bool:
96
+ """True when cached payload was recorded for `current_version` (invalidates cache on upgrade)."""
97
+ if not cached:
98
+ return False
99
+ cached_ver = str(cached.get("client_version") or "").strip().lstrip("v")
100
+ curr_ver = str(current_version or "").strip().lstrip("v")
101
+ return bool(cached_ver) and cached_ver == curr_ver
102
+
94
103
  @classmethod
95
104
  def check_version(
96
105
  cls,
@@ -100,8 +109,8 @@ class VersionChecker:
100
109
  timeout: float = 1.5
101
110
  ) -> Dict[str, Any]:
102
111
  """
103
- Retrieves version status. Returns cached result if within TTL,
104
- otherwise makes a fast network request (< 1.5s timeout).
112
+ Retrieves version status. Returns cached result if within TTL and matching
113
+ `current_version`, otherwise makes a fast network request (< 1.5s timeout).
105
114
  Falls back gracefully on network or offline scenarios.
106
115
  """
107
116
  now = int(time.time())
@@ -113,8 +122,9 @@ class VersionChecker:
113
122
  license_key = ""
114
123
 
115
124
  cached = cls.load_cache()
125
+ cache_matches = cls._cache_matches_version(cached, current_version)
116
126
 
117
- if not force_fetch and cached:
127
+ if not force_fetch and cache_matches:
118
128
  checked_at = cached.get("checked_at", 0)
119
129
  ttl = int(cached.get("ttl", CACHE_TTL))
120
130
  if now - checked_at < ttl:
@@ -161,8 +171,8 @@ class VersionChecker:
161
171
  except Exception:
162
172
  pass
163
173
 
164
- # Stale cache fallback if available
165
- if cached:
174
+ # Stale cache fallback if available for the same installed version
175
+ if cache_matches:
166
176
  return cached
167
177
  cls.save_cache(payload)
168
178
  return payload
@@ -397,7 +407,7 @@ class VersionChecker:
397
407
  """
398
408
  now = int(time.time())
399
409
  cached = cls.load_cache()
400
- if not force and cached:
410
+ if not force and cls._cache_matches_version(cached, current_version):
401
411
  checked_at = cached.get("checked_at", 0)
402
412
  update_available = cached.get("update_available", False)
403
413
  latest = cached.get("latest_version", current_version)