tokensafe 4.5.0 → 4.5.1

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 +10 -1
  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 +66 -53
  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"
@@ -241,7 +242,7 @@ class TelemetrySync:
241
242
  current_last_id = last_id
242
243
  headers = {
243
244
  "Content-Type": "application/json",
244
- "User-Agent": "TokenSafe-Sync/4.5.0"
245
+ "User-Agent": "TokenSafe-Sync/4.5.1"
245
246
  }
246
247
  if active_key:
247
248
  headers["Authorization"] = f"Bearer {active_key}"
@@ -265,47 +266,52 @@ class TelemetrySync:
265
266
 
266
267
  page_limit = 2000
267
268
  max_pages = 25
269
+ batch_size = min(max(1, int(batch_size or 50)), 200)
270
+ last_synced_rollup = int(state.get("last_synced_rollup_tokens", 0) or 0)
271
+ current_rollup_tokens = last_synced_rollup
268
272
  for page_idx in range(max_pages):
269
273
  try:
270
- conn = sqlite3.connect(db_path)
271
- conn.row_factory = sqlite3.Row
272
- cur = conn.cursor()
274
+ with closing(sqlite3.connect(db_path, timeout=5.0)) as conn:
275
+ conn.row_factory = sqlite3.Row
276
+ cur = conn.cursor()
273
277
 
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
278
+ synthetic_events: List[Dict[str, Any]] = []
279
+ if page_idx == 0:
280
+ try:
281
+ life_row = cur.execute("SELECT * FROM lifetime_aggregates WHERE id = 1").fetchone()
282
+ if life_row and int(life_row["total_saved_tokens"] or 0) > last_synced_rollup:
283
+ current_rollup_tokens = int(life_row["total_saved_tokens"])
284
+ delta_orig = max(0, int(life_row["total_original_tokens"]) - int(state.get("last_synced_rollup_orig", 0) or 0))
285
+ delta_saved = current_rollup_tokens - last_synced_rollup
286
+ synthetic_events.append({
287
+ "event_type": "ROLLUP_LIFETIME",
288
+ "original_tokens": delta_orig or int(life_row["total_original_tokens"]),
289
+ "saved_tokens": delta_saved,
290
+ "usd_saved": max(0.0, float(life_row["total_usd_saved"]) - float(state.get("last_synced_rollup_usd", 0.0) or 0.0)),
291
+ "model": "aggregate",
292
+ "timestamp": int(time.time()),
293
+ # Rolled-up historical mass of mixed provenance: conservatively estimated.
294
+ "measurement": "estimated"
295
+ })
296
+ except Exception:
297
+ pass
291
298
 
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()
299
+ # The measurement column may be absent on legacy databases that have
300
+ # not yet been migrated by MetricsTracker._init_db; fall back to the
301
+ # event-type map so sync never blocks on schema drift.
302
+ try:
303
+ rows = cur.execute(
304
+ "SELECT id, timestamp, event_type, original_tokens, saved_tokens, est_usd_saved, session_id, details, measurement "
305
+ "FROM events WHERE id > ? ORDER BY id ASC LIMIT ?",
306
+ (current_last_id, page_limit)
307
+ ).fetchall()
308
+ except sqlite3.OperationalError:
309
+ rows = cur.execute(
310
+ "SELECT id, timestamp, event_type, original_tokens, saved_tokens, est_usd_saved, session_id, details, "
311
+ "NULL as measurement "
312
+ "FROM events WHERE id > ? ORDER BY id ASC LIMIT ?",
313
+ (current_last_id, page_limit)
314
+ ).fetchall()
309
315
  except Exception as e:
310
316
  if total_sent > 0:
311
317
  return _record_failure(f"Failed to read local metrics database: {str(e)}")
@@ -401,6 +407,8 @@ class TelemetrySync:
401
407
  "license_key": active_key,
402
408
  "events": chunk,
403
409
  }
410
+ if machine_fp:
411
+ body_dict["machine_fp"] = machine_fp
404
412
  if machine_fp and active_key == "community":
405
413
  body_dict["machine_id"] = machine_fp
406
414
  body_dict["monthly_measured_saved"] = local_monthly_measured
@@ -410,25 +418,29 @@ class TelemetrySync:
410
418
  try:
411
419
  from src.egress_counter import increment as _egress_increment
412
420
  _egress_increment("telemetry")
413
- with urllib.request.urlopen(req, timeout=timeout) as resp:
421
+ with urllib.request.urlopen(req, timeout=timeout, context=shared_ssl_context()) as resp:
414
422
  if resp.status == 200:
423
+ processed_n = len(chunk)
415
424
  try:
416
425
  resp_body = json.loads(resp.read().decode("utf-8") or "{}")
426
+ if "processed" in resp_body and resp_body["processed"] is not None:
427
+ processed_n = max(0, min(len(chunk), int(resp_body["processed"])))
417
428
  srv_measured = int(resp_body.get("server_monthly_measured_saved") or 0)
418
429
  if srv_measured > 0:
419
430
  from src.metrics import MetricsTracker
420
431
  MetricsTracker(db_path=db_path).record_server_quota_floor(srv_measured)
421
432
  except Exception:
422
433
  pass
423
- total_sent += len(chunk)
424
- cumulative_synced += len(chunk)
425
- for ev_id, ev_payload in batch_items:
434
+ acked_count = processed_n if chunk else 0
435
+ total_sent += acked_count
436
+ cumulative_synced += acked_count
437
+ committed_items = batch_items[:processed_n] if chunk else batch_items
438
+ for ev_id, ev_payload in committed_items:
426
439
  if ev_id is not None and ev_id > current_last_id:
427
440
  current_last_id = ev_id
428
441
  if ev_payload and ev_payload.get("event_type") == "ROLLUP_LIFETIME":
429
442
  rollup_synced = True
430
- if not synthetic_events:
431
- rollup_synced = True
443
+ last_synced_rollup = current_rollup_tokens
432
444
  cls.save_state({
433
445
  "last_synced_event_id": current_last_id,
434
446
  "last_synced_at": int(time.time()),
@@ -436,7 +448,8 @@ class TelemetrySync:
436
448
  "last_quota_sync_at": int(time.time()),
437
449
  "consecutive_failures": 0,
438
450
  "total_synced_events": cumulative_synced,
439
- "lifetime_rollup_synced": rollup_synced
451
+ "lifetime_rollup_synced": rollup_synced,
452
+ "last_synced_rollup_tokens": last_synced_rollup,
440
453
  })
441
454
  else:
442
455
  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