tokensafe 4.4.9 → 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 (65) 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 +44 -15
  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 +24 -1
  14. package/package.json +1 -1
  15. package/plugin.json +1 -1
  16. package/rules/AGENTS.md +24 -21
  17. package/server.json +3 -3
  18. package/skills/token-optimizer/SKILL.md +61 -76
  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 +403 -0
  22. package/src/batch_search.py +428 -0
  23. package/src/burn_monitor.py +581 -0
  24. package/src/cache_normalizer.py +2 -0
  25. package/src/cli.py +85 -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 +232 -52
  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_proxy.py +13 -7
  43. package/src/mcp_server.py +758 -26
  44. package/src/metrics.py +10 -1
  45. package/src/mistakes.py +4 -2
  46. package/src/oumv_gateway.py +81 -7
  47. package/src/paths.py +4 -1
  48. package/src/proxy.py +302 -123
  49. package/src/result_ledger.py +39 -1
  50. package/src/schema_slicer.py +40 -18
  51. package/src/scoped_search.py +66 -23
  52. package/src/skeletonizer.py +22 -11
  53. package/src/slicer.py +6 -4
  54. package/src/snapshot.py +249 -0
  55. package/src/stash.py +37 -7
  56. package/src/superseded.py +42 -23
  57. package/src/syntax_guard.py +86 -0
  58. package/src/team_cache.py +3 -0
  59. package/src/telemetry_sync.py +66 -53
  60. package/src/thinking_fold.py +50 -12
  61. package/src/transcript_analyzer.py +483 -0
  62. package/src/treesitter_backend.py +2 -0
  63. package/src/type_slicer.py +60 -18
  64. package/src/version_checker.py +1 -1
  65. package/src/web_reader.py +55 -22
package/src/stash.py CHANGED
@@ -15,6 +15,7 @@ import re
15
15
  import json
16
16
  import time
17
17
  import hashlib
18
+ import threading
18
19
  from typing import Tuple, Optional, Dict, Any
19
20
 
20
21
  from src.paths import resolve_data_dir
@@ -23,7 +24,7 @@ STASH_DIRNAME = "stash"
23
24
  MAX_STASH_CHARS = 5 * 1024 * 1024 # Cap single artifact at 5 MB
24
25
  DEFAULT_MAX_AGE_DAYS = 7
25
26
  DEFAULT_MAX_TOTAL_MB = 50
26
- _HASH_PATTERN = re.compile(r"#?([0-9a-fA-F]{8})\b")
27
+ _HASH_PATTERN = re.compile(r"#?([0-9a-fA-F]{8,32})\b")
27
28
  _LAST_CLEANUP_TS = 0.0
28
29
 
29
30
 
@@ -69,10 +70,21 @@ def stash_block(content: str, source: str = "tool") -> Tuple[str, str]:
69
70
 
70
71
  try:
71
72
  stash_dir = get_stash_dir()
72
- path = os.path.join(stash_dir, f"{hash8}.json")
73
+ hash_key = hash8
74
+ path = os.path.join(stash_dir, f"{hash_key}.json")
75
+ if os.path.exists(path):
76
+ try:
77
+ with open(path, "r", encoding="utf-8") as ef:
78
+ existing = json.load(ef)
79
+ if isinstance(existing, dict) and existing.get("sha256") and existing["sha256"] != full_sha:
80
+ hash_key = full_sha[:16]
81
+ path = os.path.join(stash_dir, f"{hash_key}.json")
82
+ except Exception:
83
+ pass
84
+
73
85
  if not os.path.exists(path):
74
86
  payload = {
75
- "hash": hash8,
87
+ "hash": hash_key,
76
88
  "sha256": full_sha,
77
89
  "timestamp": int(time.time()),
78
90
  "source": source,
@@ -80,20 +92,29 @@ def stash_block(content: str, source: str = "tool") -> Tuple[str, str]:
80
92
  "chars": chars_count,
81
93
  "content": content,
82
94
  }
83
- tmp_path = f"{path}.tmp.{os.getpid()}"
95
+ tmp_path = f"{path}.tmp.{os.getpid()}.{threading.get_ident()}"
84
96
  with open(tmp_path, "w", encoding="utf-8") as f:
85
97
  json.dump(payload, f, ensure_ascii=False)
86
98
  os.replace(tmp_path, path)
87
99
 
100
+ if hash_key != hash8:
101
+ marker = (
102
+ f"[TokenSafe folded: #{hash_key} ({lines_count} lines / {chars_count} chars omitted) "
103
+ f"— call tokensafe:expand_ref('{hash_key}') to restore raw content]"
104
+ )
105
+
88
106
  # Trigger passive cleanup once per hour
89
107
  now = time.time()
90
108
  if now - _LAST_CLEANUP_TS > 3600.0:
91
109
  _LAST_CLEANUP_TS = now
92
110
  cleanup_old_stashes()
111
+ return hash_key, marker
93
112
  except Exception:
94
- pass
95
-
96
- return hash8, marker
113
+ err_marker = (
114
+ f"[TokenSafe folded: #{hash8} ({lines_count} lines / {chars_count} chars omitted) "
115
+ f"— stash write failed; raw content unavailable for restore]"
116
+ )
117
+ return hash8, err_marker
97
118
 
98
119
 
99
120
  def retrieve_block(hash_or_marker: str) -> Optional[str]:
@@ -162,6 +183,15 @@ def cleanup_old_stashes(
162
183
  total_size = 0
163
184
 
164
185
  for fname in os.listdir(stash_dir):
186
+ if ".tmp." in fname:
187
+ fpath = os.path.join(stash_dir, fname)
188
+ try:
189
+ if (now - os.path.getmtime(fpath)) > 300:
190
+ os.remove(fpath)
191
+ pruned += 1
192
+ except OSError:
193
+ pass
194
+ continue
165
195
  if not fname.endswith(".json"):
166
196
  continue
167
197
  fpath = os.path.join(stash_dir, fname)
package/src/superseded.py CHANGED
@@ -17,19 +17,36 @@ _READ_TOOLS = {
17
17
  "read_file", "view_file", "Read", "smart_read_file",
18
18
  }
19
19
  _EDIT_TOOLS = {
20
- "edit_file", "write_file", "Edit", "Write", "MultiEdit", "NotebookEdit", "replace_file_content"
20
+ "edit_file", "write_file", "Edit", "Write", "MultiEdit", "NotebookEdit",
21
+ "replace_file_content", "multi_replace_file_content", "write_to_file", "apply_edits",
21
22
  }
22
- _PATH_KEYS = ("Path", "path", "FilePath", "file_path", "notebook_path")
23
+ _PATH_KEYS = ("Path", "path", "FilePath", "file_path", "TargetFile", "notebook_path")
23
24
 
24
25
 
25
- def _extract_path_from_args(args: Any) -> Optional[str]:
26
+ def _extract_paths_from_args(args: Any) -> List[str]:
26
27
  if not isinstance(args, dict):
27
- return None
28
+ return []
29
+ found: List[str] = []
28
30
  for k in _PATH_KEYS:
29
31
  val = args.get(k)
30
32
  if isinstance(val, str) and val.strip():
31
- return os.path.abspath(val.strip())
32
- return None
33
+ found.append(os.path.abspath(val.strip()))
34
+ for list_key in ("edits", "targets"):
35
+ items = args.get(list_key)
36
+ if isinstance(items, list):
37
+ for item in items:
38
+ if isinstance(item, dict):
39
+ for k in _PATH_KEYS:
40
+ val = item.get(k)
41
+ if isinstance(val, str) and val.strip():
42
+ found.append(os.path.abspath(val.strip()))
43
+ break
44
+ return list(dict.fromkeys(found))
45
+
46
+
47
+ def _extract_path_from_args(args: Any) -> Optional[str]:
48
+ paths = _extract_paths_from_args(args)
49
+ return paths[0] if paths else None
33
50
 
34
51
 
35
52
  class SupersededPruner:
@@ -65,14 +82,15 @@ class SupersededPruner:
65
82
  continue
66
83
  tname = tc.get("name", "")
67
84
  args = tc.get("args")
68
- fpath = _extract_path_from_args(args)
69
- if not fpath:
85
+ fpaths = _extract_paths_from_args(args)
86
+ if not fpaths:
70
87
  continue
71
- if tname in _READ_TOOLS:
72
- file_actions.setdefault(fpath, []).append((idx, "READ"))
73
- step_read_files[idx] = fpath
74
- elif tname in _EDIT_TOOLS:
75
- file_actions.setdefault(fpath, []).append((idx, "EDIT"))
88
+ for fpath in fpaths:
89
+ if tname in _READ_TOOLS:
90
+ file_actions.setdefault(fpath, []).append((idx, "READ"))
91
+ step_read_files[idx] = fpath
92
+ elif tname in _EDIT_TOOLS:
93
+ file_actions.setdefault(fpath, []).append((idx, "EDIT"))
76
94
 
77
95
  # Claude Code format: message.content blocks
78
96
  msg = step.get("message")
@@ -83,17 +101,18 @@ class SupersededPruner:
83
101
  if isinstance(b, dict) and b.get("type") == "tool_use":
84
102
  tname = b.get("name", "")
85
103
  inp = b.get("input")
86
- fpath = _extract_path_from_args(inp)
87
- if not fpath:
104
+ fpaths = _extract_paths_from_args(inp)
105
+ if not fpaths:
88
106
  continue
89
- if tname in _READ_TOOLS:
90
- file_actions.setdefault(fpath, []).append((idx, "READ"))
91
- step_read_files[idx] = fpath
92
- tool_use_id = str(b.get("id") or "")
93
- if tool_use_id:
94
- read_tool_ids[tool_use_id] = idx
95
- elif tname in _EDIT_TOOLS:
96
- file_actions.setdefault(fpath, []).append((idx, "EDIT"))
107
+ for fpath in fpaths:
108
+ if tname in _READ_TOOLS:
109
+ file_actions.setdefault(fpath, []).append((idx, "READ"))
110
+ step_read_files[idx] = fpath
111
+ tool_use_id = str(b.get("id") or "")
112
+ if tool_use_id:
113
+ read_tool_ids[tool_use_id] = idx
114
+ elif tname in _EDIT_TOOLS:
115
+ file_actions.setdefault(fpath, []).append((idx, "EDIT"))
97
116
 
98
117
  # Identify superseded read step indices:
99
118
  # A read at step i is superseded if there is an EDIT at step j > i,
@@ -0,0 +1,86 @@
1
+ """
2
+ Out-of-the-box syntax guard for OUMV direct workspace edits.
3
+
4
+ Validates replacement content BEFORE it is persisted so the agent can never
5
+ write syntactically broken code through the `oumv/mutate` offline fallback.
6
+ Runs strictly on the Python standard library; JavaScript checks shell out to
7
+ `node --check` when Node.js is available (best-effort, bounded timeout).
8
+
9
+ Languages without a checker are reported as "skipped" — honest reporting per
10
+ the OUMV spec §8 Mutation Policy (never imply a validation that did not run).
11
+ """
12
+
13
+ import ast
14
+ import os
15
+ import shutil
16
+ import subprocess
17
+ import tempfile
18
+ from typing import Dict
19
+
20
+ _NODE_TIMEOUT_SEC = 3.0
21
+
22
+ _EXT_STRATEGY = {
23
+ ".py": "python-ast",
24
+ ".js": "node-check",
25
+ ".mjs": "node-check",
26
+ ".cjs": "node-check",
27
+ }
28
+
29
+
30
+ def check_syntax(abs_path: str, content: str) -> Dict[str, str]:
31
+ """
32
+ Pre-flight syntax validation for a direct workspace edit.
33
+
34
+ Returns {"status": "passed"|"failed"|"skipped", "tool": str, "error": str}.
35
+ Never raises: a language we cannot validate is reported as "skipped".
36
+ """
37
+ ext = os.path.splitext(abs_path)[1].lower()
38
+ strategy = _EXT_STRATEGY.get(ext)
39
+
40
+ if strategy == "python-ast":
41
+ try:
42
+ ast.parse(content)
43
+ return {"status": "passed", "tool": "python-ast"}
44
+ except SyntaxError as e:
45
+ return {"status": "failed", "tool": "python-ast", "error": f"line {e.lineno}: {e.msg}"}
46
+ except Exception as e:
47
+ return {"status": "failed", "tool": "python-ast", "error": str(e)}
48
+
49
+ if strategy == "node-check":
50
+ node_bin = shutil.which("node")
51
+ if not node_bin:
52
+ return {"status": "skipped", "tool": "node-check", "error": "node not found on PATH"}
53
+ # `node --check` requires a file: validate a temp copy so the target stays untouched.
54
+ tmp_fd, tmp_path = tempfile.mkstemp(suffix=ext, prefix="tokensafe_syntax_")
55
+ try:
56
+ with os.fdopen(tmp_fd, "w", encoding="utf-8") as f:
57
+ f.write(content)
58
+ proc = subprocess.run(
59
+ [node_bin, "--check", tmp_path],
60
+ capture_output=True,
61
+ text=True,
62
+ timeout=_NODE_TIMEOUT_SEC,
63
+ )
64
+ if proc.returncode == 0:
65
+ return {"status": "passed", "tool": "node --check"}
66
+ err_lines = (proc.stderr or proc.stdout or "").strip().splitlines()
67
+ return {
68
+ "status": "failed",
69
+ "tool": "node --check",
70
+ "error": err_lines[0] if err_lines else "syntax check failed",
71
+ }
72
+ except subprocess.TimeoutExpired:
73
+ return {"status": "skipped", "tool": "node-check", "error": "timeout"}
74
+ except Exception as e: # noqa: BLE001 - guard must never raise
75
+ return {"status": "skipped", "tool": "node-check", "error": str(e)}
76
+ finally:
77
+ try:
78
+ os.unlink(tmp_path)
79
+ except OSError:
80
+ pass
81
+
82
+ return {
83
+ "status": "skipped",
84
+ "tool": "none",
85
+ "error": f"no syntax checker for {ext or 'unknown extension'}",
86
+ }
package/src/team_cache.py CHANGED
@@ -252,6 +252,7 @@ class TeamCache:
252
252
  cls._trip_cooldown(cloud_url)
253
253
  return []
254
254
  except Exception:
255
+ cls._trip_cooldown(cloud_url)
255
256
  return []
256
257
  return []
257
258
 
@@ -271,6 +272,8 @@ class TeamCache:
271
272
  with urllib.request.urlopen(req, timeout=max(2.5, cls.DEFAULT_TIMEOUT), context=shared_ssl_context()) as resp:
272
273
  if resp.status == 200:
273
274
  res = json.loads(resp.read().decode("utf-8"))
275
+ res.setdefault("total_entries", res.get("entries", 0))
276
+ res.setdefault("total_hits", res.get("hits", 0))
274
277
  res["active"] = True
275
278
  return res
276
279
  except Exception as e:
@@ -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.4.9"
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