tokensafe 4.5.0 → 4.5.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.
Files changed (62) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/bin/agy-tokens +10 -1
  3. package/bin/tokensafe.js +2 -1
  4. package/hooks/claude_code_hook.py +38 -126
  5. package/hooks/cursor_hook.py +45 -1
  6. package/hooks/kimi_hook.py +46 -90
  7. package/hooks/pre_invocation.py +23 -4
  8. package/hooks/pre_tool_use.py +40 -22
  9. package/hooks/session_start.py +28 -10
  10. package/hooks/zcode_hook.py +95 -0
  11. package/hooks.json +1 -1
  12. package/kimi.plugin.json +17 -1
  13. package/mcp_config.json +10 -4
  14. package/package.json +1 -1
  15. package/plugin.json +1 -1
  16. package/rules/AGENTS.md +24 -24
  17. package/server.json +3 -3
  18. package/skills/token-optimizer/SKILL.md +61 -86
  19. package/skills/token-optimizer/references/mcp-tools.md +32 -132
  20. package/src/adapter_core.py +231 -7
  21. package/src/batch_editor.py +73 -22
  22. package/src/batch_search.py +31 -11
  23. package/src/burn_monitor.py +581 -0
  24. package/src/cache_normalizer.py +2 -0
  25. package/src/cli.py +34 -4
  26. package/src/compactor.py +1 -1
  27. package/src/dashboard.py +17 -9
  28. package/src/diff_slicer.py +1 -1
  29. package/src/distiller.py +11 -1
  30. package/src/environment_auditor.py +30 -6
  31. package/src/format_parsers/ansi.py +1 -1
  32. package/src/format_parsers/lockfiles.py +22 -17
  33. package/src/format_parsers/tabular.py +6 -3
  34. package/src/fts_index.py +26 -20
  35. package/src/governor.py +2 -2
  36. package/src/graph_engine.py +31 -9
  37. package/src/guard.py +3 -3
  38. package/src/image_downscale.py +26 -0
  39. package/src/installer.py +61 -48
  40. package/src/license_manager.py +49 -16
  41. package/src/live_relay.py +9 -8
  42. package/src/mcp_server.py +487 -48
  43. package/src/metrics.py +78 -13
  44. package/src/mistakes.py +4 -2
  45. package/src/paths.py +4 -1
  46. package/src/proxy.py +302 -123
  47. package/src/result_ledger.py +39 -1
  48. package/src/schema_slicer.py +40 -18
  49. package/src/scoped_search.py +66 -23
  50. package/src/skeletonizer.py +22 -11
  51. package/src/slicer.py +6 -4
  52. package/src/stash.py +37 -7
  53. package/src/superseded.py +42 -23
  54. package/src/syntax_guard.py +2 -0
  55. package/src/team_cache.py +3 -0
  56. package/src/telemetry_sync.py +96 -54
  57. package/src/thinking_fold.py +50 -12
  58. package/src/transcript_analyzer.py +270 -68
  59. package/src/treesitter_backend.py +2 -0
  60. package/src/type_slicer.py +60 -18
  61. package/src/version_checker.py +1 -1
  62. package/src/web_reader.py +55 -22
@@ -17,6 +17,7 @@ import json
17
17
  import time
18
18
  import secrets
19
19
  import sqlite3
20
+ from contextlib import closing
20
21
  import threading
21
22
  import subprocess
22
23
  import urllib.request
@@ -31,6 +32,7 @@ if PROJECT_ROOT not in sys.path:
31
32
 
32
33
  from src.license_manager import LicenseManager
33
34
  from src.metrics import resolve_measurement
35
+ from src.ssl_context import shared_ssl_context
34
36
 
35
37
  from src.paths import resolve_data_dir
36
38
 
@@ -141,13 +143,12 @@ class TelemetrySync:
141
143
  db_path = _metrics_db_path()
142
144
  if os.path.exists(db_path):
143
145
  try:
144
- conn = sqlite3.connect(db_path)
145
- c = conn.cursor()
146
- row = c.execute("SELECT COUNT(*) FROM events").fetchone()
147
- total_local = row[0] if row else 0
148
- row_pending = c.execute("SELECT COUNT(*) FROM events WHERE id > ?", (last_id,)).fetchone()
149
- pending = row_pending[0] if row_pending else 0
150
- conn.close()
146
+ with closing(sqlite3.connect(db_path, timeout=5.0)) as conn:
147
+ c = conn.cursor()
148
+ row = c.execute("SELECT COUNT(*) FROM events").fetchone()
149
+ total_local = row[0] if row else 0
150
+ row_pending = c.execute("SELECT COUNT(*) FROM events WHERE id > ?", (last_id,)).fetchone()
151
+ pending = row_pending[0] if row_pending else 0
151
152
  except Exception:
152
153
  pass
153
154
 
@@ -211,7 +212,7 @@ class TelemetrySync:
211
212
  target_email = str(payload.get("email", "")).strip().lower()
212
213
 
213
214
  # Community fallback: unauthenticated or expired users participate in global community sync
214
- if not target_email:
215
+ if not target_email and not active_key.startswith("ts_live_"):
215
216
  target_email = "community@tokensafe.dev"
216
217
  if not active_key:
217
218
  active_key = "community"
@@ -238,10 +239,17 @@ class TelemetrySync:
238
239
  total_sent = 0
239
240
  cumulative_synced = state.get("total_synced_events", 0)
240
241
  rollup_synced = bool(state.get("lifetime_rollup_synced", False))
242
+ has_rollup_watermark = "last_synced_rollup_tokens" in state
243
+ last_synced_rollup = int(state.get("last_synced_rollup_tokens", 0) or 0)
244
+ last_synced_rollup_orig = int(state.get("last_synced_rollup_orig", 0) or 0)
245
+ last_synced_rollup_usd = float(state.get("last_synced_rollup_usd", 0.0) or 0.0)
246
+ current_rollup_tokens = last_synced_rollup
247
+ current_rollup_orig = last_synced_rollup_orig
248
+ current_rollup_usd = last_synced_rollup_usd
241
249
  current_last_id = last_id
242
250
  headers = {
243
251
  "Content-Type": "application/json",
244
- "User-Agent": "TokenSafe-Sync/4.5.0"
252
+ "User-Agent": "TokenSafe-Sync/4.5.2"
245
253
  }
246
254
  if active_key:
247
255
  headers["Authorization"] = f"Bearer {active_key}"
@@ -254,7 +262,10 @@ class TelemetrySync:
254
262
  "last_quota_sync_at": state.get("last_quota_sync_at", 0),
255
263
  "consecutive_failures": int(state.get("consecutive_failures", 0) or 0) + 1,
256
264
  "total_synced_events": cumulative_synced,
257
- "lifetime_rollup_synced": rollup_synced
265
+ "lifetime_rollup_synced": rollup_synced,
266
+ "last_synced_rollup_tokens": last_synced_rollup,
267
+ "last_synced_rollup_orig": last_synced_rollup_orig,
268
+ "last_synced_rollup_usd": last_synced_rollup_usd,
258
269
  }
259
270
  cls.save_state(fail_state)
260
271
  return {
@@ -265,47 +276,67 @@ class TelemetrySync:
265
276
 
266
277
  page_limit = 2000
267
278
  max_pages = 25
279
+ batch_size = min(max(1, int(batch_size or 50)), 200)
268
280
  for page_idx in range(max_pages):
269
281
  try:
270
- conn = sqlite3.connect(db_path)
271
- conn.row_factory = sqlite3.Row
272
- cur = conn.cursor()
282
+ with closing(sqlite3.connect(db_path, timeout=5.0)) as conn:
283
+ conn.row_factory = sqlite3.Row
284
+ cur = conn.cursor()
273
285
 
274
- synthetic_events: List[Dict[str, Any]] = []
275
- if page_idx == 0 and not rollup_synced:
276
- try:
277
- life_row = cur.execute("SELECT * FROM lifetime_aggregates WHERE id = 1").fetchone()
278
- if life_row and life_row["total_saved_tokens"] > 0:
279
- synthetic_events.append({
280
- "event_type": "ROLLUP_LIFETIME",
281
- "original_tokens": int(life_row["total_original_tokens"]),
282
- "saved_tokens": int(life_row["total_saved_tokens"]),
283
- "usd_saved": float(life_row["total_usd_saved"]),
284
- "model": "aggregate",
285
- "timestamp": int(time.time()),
286
- # Rolled-up historical mass of mixed provenance: conservatively estimated.
287
- "measurement": "estimated"
288
- })
289
- except Exception:
290
- pass
286
+ synthetic_events: List[Dict[str, Any]] = []
287
+ if page_idx == 0:
288
+ try:
289
+ life_row = cur.execute("SELECT * FROM lifetime_aggregates WHERE id = 1").fetchone()
290
+ if life_row:
291
+ life_dict = dict(life_row)
292
+ syncable_orig = max(0, int(life_dict.get("total_original_tokens") or 0) - int(life_dict.get("pruned_synced_orig_tokens") or 0))
293
+ syncable_saved = max(0, int(life_dict.get("total_saved_tokens") or 0) - int(life_dict.get("pruned_synced_saved_tokens") or 0))
294
+ syncable_usd = max(0.0, float(life_dict.get("total_usd_saved") or 0.0) - float(life_dict.get("pruned_synced_usd") or 0.0))
295
+ # Upgrade migration from pre-watermark sync_state.json: do not re-emit already synced rollup
296
+ if rollup_synced and not has_rollup_watermark:
297
+ last_synced_rollup = syncable_saved
298
+ last_synced_rollup_orig = syncable_orig
299
+ last_synced_rollup_usd = syncable_usd
300
+ current_rollup_tokens = syncable_saved
301
+ current_rollup_orig = syncable_orig
302
+ current_rollup_usd = syncable_usd
303
+ has_rollup_watermark = True
304
+ elif syncable_saved > last_synced_rollup:
305
+ current_rollup_tokens = syncable_saved
306
+ current_rollup_orig = syncable_orig
307
+ current_rollup_usd = syncable_usd
308
+ delta_orig = max(0, syncable_orig - last_synced_rollup_orig)
309
+ delta_saved = syncable_saved - last_synced_rollup
310
+ delta_usd = max(0.0, syncable_usd - last_synced_rollup_usd)
311
+ synthetic_events.append({
312
+ "event_type": "ROLLUP_LIFETIME",
313
+ "original_tokens": delta_orig or delta_saved,
314
+ "saved_tokens": delta_saved,
315
+ "usd_saved": delta_usd,
316
+ "model": "aggregate",
317
+ "timestamp": int(time.time()),
318
+ # Rolled-up historical mass of mixed provenance: conservatively estimated.
319
+ "measurement": "estimated"
320
+ })
321
+ except Exception:
322
+ pass
291
323
 
292
- # The measurement column may be absent on legacy databases that have
293
- # not yet been migrated by MetricsTracker._init_db; fall back to the
294
- # event-type map so sync never blocks on schema drift.
295
- try:
296
- rows = cur.execute(
297
- "SELECT id, timestamp, event_type, original_tokens, saved_tokens, est_usd_saved, session_id, details, measurement "
298
- "FROM events WHERE id > ? ORDER BY id ASC LIMIT ?",
299
- (current_last_id, page_limit)
300
- ).fetchall()
301
- except sqlite3.OperationalError:
302
- rows = cur.execute(
303
- "SELECT id, timestamp, event_type, original_tokens, saved_tokens, est_usd_saved, session_id, details, "
304
- "NULL as measurement "
305
- "FROM events WHERE id > ? ORDER BY id ASC LIMIT ?",
306
- (current_last_id, page_limit)
307
- ).fetchall()
308
- conn.close()
324
+ # The measurement column may be absent on legacy databases that have
325
+ # not yet been migrated by MetricsTracker._init_db; fall back to the
326
+ # event-type map so sync never blocks on schema drift.
327
+ try:
328
+ rows = cur.execute(
329
+ "SELECT id, timestamp, event_type, original_tokens, saved_tokens, est_usd_saved, session_id, details, measurement "
330
+ "FROM events WHERE id > ? ORDER BY id ASC LIMIT ?",
331
+ (current_last_id, page_limit)
332
+ ).fetchall()
333
+ except sqlite3.OperationalError:
334
+ rows = cur.execute(
335
+ "SELECT id, timestamp, event_type, original_tokens, saved_tokens, est_usd_saved, session_id, details, "
336
+ "NULL as measurement "
337
+ "FROM events WHERE id > ? ORDER BY id ASC LIMIT ?",
338
+ (current_last_id, page_limit)
339
+ ).fetchall()
309
340
  except Exception as e:
310
341
  if total_sent > 0:
311
342
  return _record_failure(f"Failed to read local metrics database: {str(e)}")
@@ -401,6 +432,8 @@ class TelemetrySync:
401
432
  "license_key": active_key,
402
433
  "events": chunk,
403
434
  }
435
+ if machine_fp:
436
+ body_dict["machine_fp"] = machine_fp
404
437
  if machine_fp and active_key == "community":
405
438
  body_dict["machine_id"] = machine_fp
406
439
  body_dict["monthly_measured_saved"] = local_monthly_measured
@@ -410,25 +443,31 @@ class TelemetrySync:
410
443
  try:
411
444
  from src.egress_counter import increment as _egress_increment
412
445
  _egress_increment("telemetry")
413
- with urllib.request.urlopen(req, timeout=timeout) as resp:
446
+ with urllib.request.urlopen(req, timeout=timeout, context=shared_ssl_context()) as resp:
414
447
  if resp.status == 200:
448
+ processed_n = len(chunk)
415
449
  try:
416
450
  resp_body = json.loads(resp.read().decode("utf-8") or "{}")
451
+ if "processed" in resp_body and resp_body["processed"] is not None:
452
+ processed_n = max(0, min(len(chunk), int(resp_body["processed"])))
417
453
  srv_measured = int(resp_body.get("server_monthly_measured_saved") or 0)
418
454
  if srv_measured > 0:
419
455
  from src.metrics import MetricsTracker
420
456
  MetricsTracker(db_path=db_path).record_server_quota_floor(srv_measured)
421
457
  except Exception:
422
458
  pass
423
- total_sent += len(chunk)
424
- cumulative_synced += len(chunk)
425
- for ev_id, ev_payload in batch_items:
459
+ acked_count = processed_n if chunk else 0
460
+ total_sent += acked_count
461
+ cumulative_synced += acked_count
462
+ committed_items = batch_items[:processed_n] if chunk else batch_items
463
+ for ev_id, ev_payload in committed_items:
426
464
  if ev_id is not None and ev_id > current_last_id:
427
465
  current_last_id = ev_id
428
466
  if ev_payload and ev_payload.get("event_type") == "ROLLUP_LIFETIME":
429
467
  rollup_synced = True
430
- if not synthetic_events:
431
- rollup_synced = True
468
+ last_synced_rollup = current_rollup_tokens
469
+ last_synced_rollup_orig = current_rollup_orig
470
+ last_synced_rollup_usd = current_rollup_usd
432
471
  cls.save_state({
433
472
  "last_synced_event_id": current_last_id,
434
473
  "last_synced_at": int(time.time()),
@@ -436,7 +475,10 @@ class TelemetrySync:
436
475
  "last_quota_sync_at": int(time.time()),
437
476
  "consecutive_failures": 0,
438
477
  "total_synced_events": cumulative_synced,
439
- "lifetime_rollup_synced": rollup_synced
478
+ "lifetime_rollup_synced": rollup_synced,
479
+ "last_synced_rollup_tokens": last_synced_rollup,
480
+ "last_synced_rollup_orig": last_synced_rollup_orig,
481
+ "last_synced_rollup_usd": last_synced_rollup_usd,
440
482
  })
441
483
  else:
442
484
  return _record_failure(f"Server returned HTTP {resp.status}")
@@ -1,5 +1,5 @@
1
1
  """
2
- TokenSafe Aged Thinking Fold (proxy stage 1.6, OPT-IN, DEFAULT OFF).
2
+ TokenSafe Aged Thinking Fold (proxy stage 1.6, enabled by default; opt-out via TOKENSAFE_FOLD_THINKING=0).
3
3
 
4
4
  Collapses extended-thinking payloads of AGED assistant turns into one-line
5
5
  stubs inside the proxy pipeline. The ``_tokensafe_thinking`` side-channel key
@@ -8,12 +8,12 @@ z.ai 1214 class) keep accepting the rebuilt tool_use turns — only the mass
8
8
  shrinks. Recent turns (last ``keep_recent`` messages) are never touched, and
9
9
  the fold is idempotent via an in-content marker (KV-cache stable re-runs).
10
10
 
11
- DEFAULT OFF on purpose: enable with TOKENSAFE_FOLD_THINKING=1 only after the
12
- upstream shape probe matrix passes (z.ai weekly quota resets 2026-11-24).
11
+ Cache-aware ROI gate: when the prefix is warm-cached, refuses to mutate
12
+ history if ``suffix_tokens * (M_in - M_cache) >= expected_savings``.
13
13
  """
14
14
 
15
15
  import os
16
- from typing import Any, Dict, List, Tuple
16
+ from typing import Any, Dict, List, Optional, Tuple
17
17
 
18
18
  from src.tokenizer import count_tokens
19
19
 
@@ -22,8 +22,9 @@ DEFAULT_KEEP_RECENT = 6
22
22
  DEFAULT_MIN_CHARS = 2000
23
23
 
24
24
 
25
- def _env_flag(name: str) -> bool:
26
- return os.environ.get(name, "").strip().lower() in ("1", "true", "yes")
25
+ def _env_flag(name: str, default: str = "1") -> bool:
26
+ raw = os.environ.get(name, default)
27
+ return str(raw).strip().lower() not in ("0", "false", "no", "off")
27
28
 
28
29
 
29
30
  def _thinking_text_len(blocks: Any) -> int:
@@ -54,17 +55,30 @@ def fold_aged_thinking(
54
55
  min_chars: int = DEFAULT_MIN_CHARS,
55
56
  record: bool = True,
56
57
  session_id: str = "proxy_session",
58
+ model: str = "",
59
+ provider: str = "",
60
+ cache_warm: Optional[bool] = None,
61
+ remaining_turns: int = 8,
62
+ force_fold: bool = False,
57
63
  ) -> Tuple[List[Dict[str, Any]], Dict[str, Any]]:
58
64
  """Folds aged ``_tokensafe_thinking`` payloads in place. Returns (messages, stats).
59
65
 
60
- Gates: TOKENSAFE_FOLD_THINKING=1 required (DEFAULT OFF); thinking inside
61
- the last ``keep_recent`` messages is never folded; payloads under
62
- ``min_chars`` stay verbatim; already-folded turns are never re-folded."""
63
- stats: Dict[str, Any] = {"folded": 0, "orig_tokens": 0, "new_tokens": 0, "saved_tokens": 0}
64
- if not messages or not _env_flag("TOKENSAFE_FOLD_THINKING"):
66
+ Gates: TOKENSAFE_FOLD_THINKING=0 disables; thinking inside the last
67
+ ``keep_recent`` messages is never folded; payloads under ``min_chars`` stay
68
+ verbatim; already-folded turns are never re-folded; warm-cache prefixes
69
+ are protected by the cache-break ROI gate."""
70
+ stats: Dict[str, Any] = {
71
+ "folded": 0,
72
+ "orig_tokens": 0,
73
+ "new_tokens": 0,
74
+ "saved_tokens": 0,
75
+ "deferred_roi": False,
76
+ }
77
+ if not messages or not _env_flag("TOKENSAFE_FOLD_THINKING", "1"):
65
78
  return messages, stats
66
79
 
67
80
  protected_from = max(0, len(messages) - keep_recent)
81
+ pending: List[Tuple[int, Dict[str, Any], int, str, int]] = []
68
82
  for idx, msg in enumerate(messages):
69
83
  if idx >= protected_from or not isinstance(msg, dict) or msg.get("role") != "assistant":
70
84
  continue
@@ -81,8 +95,32 @@ def fold_aged_thinking(
81
95
  )
82
96
  )
83
97
  stub_text = f"{THINKING_FOLD_MARKER} (~{orig_tokens} tok) — current turn's thinking was consumed; history prefix kept for shape validity]"
84
- msg["_tokensafe_thinking"] = [{"type": "text", "text": stub_text}]
85
98
  new_tokens = count_tokens(stub_text)
99
+ pending.append((idx, msg, orig_tokens, stub_text, new_tokens))
100
+
101
+ if not pending:
102
+ return messages, stats
103
+
104
+ total_saved = sum(max(0, orig_t - new_t) for _, _, orig_t, _, new_t in pending)
105
+ earliest_idx = pending[0][0]
106
+ from src.burn_monitor import evaluate_fold_roi
107
+ roi = evaluate_fold_roi(
108
+ messages,
109
+ earliest_fold_idx=earliest_idx,
110
+ saved_tokens=total_saved,
111
+ model=model,
112
+ provider=provider,
113
+ cache_warm=cache_warm,
114
+ remaining_turns=remaining_turns,
115
+ force_fold=force_fold,
116
+ )
117
+ stats["roi"] = roi
118
+ if not roi["should_fold"]:
119
+ stats["deferred_roi"] = True
120
+ return messages, stats
121
+
122
+ for _, msg, orig_tokens, stub_text, new_tokens in pending:
123
+ msg["_tokensafe_thinking"] = [{"type": "text", "text": stub_text}]
86
124
  stats["folded"] += 1
87
125
  stats["orig_tokens"] += orig_tokens
88
126
  stats["new_tokens"] += new_tokens