tokensafe 4.2.13 → 4.3.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.
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "4.2.13",
2
+ "version": "4.3.0",
3
3
  "name": "tokensafe",
4
4
  "description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
5
5
  "author": {
@@ -56,6 +56,23 @@ def handle(event: str, payload: dict) -> dict:
56
56
  extra = f"{extra}\n\n{guard}"
57
57
  except Exception:
58
58
  pass
59
+ # Cold-start brief (project-gated): one-shot God Nodes topology banner,
60
+ # parity with the Antigravity SessionStart hook. Non-project cwd
61
+ # (plain chats, plugin/system dirs) stays banner-free.
62
+ try:
63
+ from src.paths import is_project_root
64
+ start_cwd = str(payload.get("cwd") or os.getcwd())
65
+ if is_project_root(start_cwd):
66
+ from src.graph_engine import GraphEngine
67
+ banner = GraphEngine.get_instance(start_cwd).format_topology_banner()
68
+ if banner:
69
+ extra = (
70
+ f"{extra}\n\n{banner}\n"
71
+ "⚡ Core God Nodes and dependency hubs mapped above. "
72
+ "Call 'tokensafe:get_architecture_graph(project_path)' for full dependency trees."
73
+ )
74
+ except Exception:
75
+ pass
59
76
  return {
60
77
  "hookSpecificOutput": {
61
78
  "hookEventName": "SessionStart",
@@ -200,6 +217,47 @@ def handle(event: str, payload: dict) -> dict:
200
217
  "permissionDecisionReason": verdict["reason"],
201
218
  }
202
219
  }
220
+ elif tool in ("Edit", "MultiEdit", "edit_file", "replace_file_content"):
221
+ # Stale-file edit guard: when the target changed on disk since the
222
+ # model last saw it (build output, linters, another session), the
223
+ # edit either corrupts content or fails and forces a costly full
224
+ # re-read. Surface it BEFORE the edit lands — ask, never deny.
225
+ # Kill switch: TOKENSAFE_STALE_GUARD=0.
226
+ try:
227
+ from src.file_state import FileState
228
+ stale_fp = str(tool_input.get("file_path") or tool_input.get("Path") or tool_input.get("path") or "")
229
+ if stale_fp and FileState.guard_enabled():
230
+ stale = FileState.check_stale(stale_fp)
231
+ if stale:
232
+ try:
233
+ from src.metrics import MetricsTracker
234
+ MetricsTracker().record_event(
235
+ session_id=session_id,
236
+ event_type="STALE_EDIT_ASK",
237
+ original_tokens=FileState.estimate_reread_tokens(stale_fp),
238
+ optimized_tokens=0,
239
+ details={
240
+ "agent": AGENT,
241
+ "target_file": os.path.basename(stale_fp),
242
+ "age_s": stale.get("age_s", 0),
243
+ },
244
+ measurement="estimated",
245
+ )
246
+ except Exception:
247
+ pass
248
+ return {
249
+ "hookSpecificOutput": {
250
+ "hookEventName": "PreToolUse",
251
+ "permissionDecision": "ask",
252
+ "permissionDecisionReason": (
253
+ f"[TokenSafe] {os.path.basename(stale_fp)} changed on disk since it was last read "
254
+ f"(external edit: build/linter/another session?). Your edit may target outdated content. "
255
+ f"Approve if you have verified the current file state."
256
+ ),
257
+ }
258
+ }
259
+ except Exception:
260
+ pass
203
261
  return {}
204
262
 
205
263
  if event == "PostToolUse":
@@ -235,6 +293,49 @@ def handle(event: str, payload: dict) -> dict:
235
293
  f"({orig:,} → {new:,} chars). Output summary:\n{compacted}"
236
294
  ),
237
295
  }
296
+ # File-state tracking for the stale-edit guard: snapshot the on-disk
297
+ # hash of every file the model has just seen (Read) or rewritten
298
+ # (Write/Edit) so PreToolUse can detect external changes later.
299
+ try:
300
+ if tool in ("Read", "view_file", "read_file", "Write", "write_file",
301
+ "Edit", "MultiEdit", "edit_file", "replace_file_content"):
302
+ ti = payload.get("tool_input")
303
+ if isinstance(ti, dict):
304
+ track_fp = str(ti.get("file_path") or ti.get("Path") or ti.get("path") or ti.get("FilePath") or "")
305
+ if track_fp:
306
+ from src.file_state import FileState
307
+ FileState.record_seen(track_fp)
308
+ except Exception:
309
+ pass
310
+ return {}
311
+
312
+ if event == "Stop":
313
+ # Fold-at-rest (opt-in TOKENSAFE_FOLD_AT_REST=1): when the session goes
314
+ # idle, prune superseded intermediate read results from the transcript
315
+ # IN PLACE (structure/UUID-preserving tombstones + one-file backup), so
316
+ # the next resume starts light without any proxy involvement.
317
+ if os.environ.get("TOKENSAFE_FOLD_AT_REST", "").strip().lower() in ("1", "true", "yes"):
318
+ try:
319
+ rest_tp = str(payload.get("transcript_path") or "")
320
+ if rest_tp:
321
+ from src.superseded import SupersededPruner
322
+ res = SupersededPruner.fold_at_rest(rest_tp)
323
+ if res.get("success") and res.get("pruned_count", 0) > 0:
324
+ from src.metrics import MetricsTracker
325
+ MetricsTracker().record_event(
326
+ session_id=session_id,
327
+ event_type="FOLD_AT_REST",
328
+ original_tokens=res.get("orig_tokens", 0),
329
+ optimized_tokens=res.get("pruned_tokens", 0),
330
+ details={
331
+ "agent": AGENT,
332
+ "pruned": res.get("pruned_count", 0),
333
+ "transcript": os.path.basename(rest_tp),
334
+ },
335
+ measurement="measured",
336
+ )
337
+ except Exception:
338
+ pass
238
339
  return {}
239
340
 
240
341
  return {}
@@ -33,9 +33,36 @@ def _should_skip_fast() -> bool:
33
33
  return False
34
34
 
35
35
  def main():
36
+ raw = ""
36
37
  try:
37
- # Drain stdin to keep pipes clean
38
- _ = sys.stdin.read()
38
+ raw = sys.stdin.read()
39
+ except Exception:
40
+ raw = ""
41
+
42
+ # Stale-edit guard tracking: snapshot the on-disk hash of files the model
43
+ # has just seen (read) or rewritten (write/edit). Tolerant payload parsing
44
+ # — this one script serves Antigravity/ZCode (toolCall shape) and stays
45
+ # harmless under CC-shaped payloads. Output contract is untouched: {}.
46
+ try:
47
+ payload = json.loads(raw) if raw.strip() else {}
48
+ if isinstance(payload, dict):
49
+ tool_call = payload.get("toolCall") if isinstance(payload.get("toolCall"), dict) else {}
50
+ tool_name = str(tool_call.get("name") or payload.get("tool_name") or "")
51
+ args = tool_call.get("args") if isinstance(tool_call.get("args"), dict) else (
52
+ payload.get("tool_input") if isinstance(payload.get("tool_input"), dict) else {}
53
+ )
54
+ if tool_name in ("read_file", "view_file", "Read", "smart_read_file", "write_file",
55
+ "edit_file", "Write", "Edit", "MultiEdit", "replace_file_content",
56
+ "NotebookEdit"):
57
+ tracked_path = ""
58
+ for key in ("Path", "TargetFile", "path", "FilePath", "file_path", "notebook_path"):
59
+ val = args.get(key)
60
+ if isinstance(val, str) and val.strip():
61
+ tracked_path = val
62
+ break
63
+ if tracked_path:
64
+ from src.file_state import FileState
65
+ FileState.record_seen(tracked_path)
39
66
  except Exception:
40
67
  pass
41
68
 
@@ -82,6 +82,42 @@ def _handle(payload: dict) -> dict:
82
82
 
83
83
  response: dict = {"decision": "allow"}
84
84
 
85
+ # 1.5 Stale-file edit guard: when the target changed on disk since the
86
+ # model last saw it (build output, linters, another session), the edit
87
+ # either corrupts content or fails and forces a costly full re-read.
88
+ # Surface it BEFORE the edit lands — force_ask, never deny.
89
+ # Kill switch: TOKENSAFE_STALE_GUARD=0.
90
+ if tool_name in ("edit_file", "replace_file_content"):
91
+ try:
92
+ from src.file_state import FileState
93
+ if FileState.guard_enabled():
94
+ raw_path = str(args.get("Path") or args.get("TargetFile") or args.get("path") or "")
95
+ stale = FileState.check_stale(_resolve_hook_path(raw_path, hook_cwd)) if raw_path else None
96
+ if stale:
97
+ tracker.record_event(
98
+ session_id=conversation_id,
99
+ event_type="STALE_EDIT_ASK",
100
+ original_tokens=FileState.estimate_reread_tokens(_resolve_hook_path(raw_path, hook_cwd)),
101
+ optimized_tokens=0,
102
+ details={
103
+ "tool": tool_name,
104
+ "target_file": os.path.basename(raw_path),
105
+ "age_s": stale.get("age_s", 0),
106
+ },
107
+ measurement="estimated",
108
+ )
109
+ _trigger_bg_sync()
110
+ return {
111
+ "decision": "force_ask",
112
+ "reason": (
113
+ f"[TokenSafe] {os.path.basename(raw_path)} changed on disk since it was last read "
114
+ f"(external edit: build/linter/another session?). Your edit may target outdated content. "
115
+ f"Verify the current file state (read_file the target region) before re-applying the edit."
116
+ ),
117
+ }
118
+ except Exception:
119
+ pass
120
+
85
121
  # 2. TokenSafe Guard: Inspect file writes and edits for security violations
86
122
  if tool_name in ("write_file", "edit_file"):
87
123
  from src.guard import TokenSafeGuard
@@ -42,6 +42,33 @@ def _user_markdown(markdown: str) -> dict:
42
42
  }
43
43
 
44
44
 
45
+ def _guest_pitch_step(quota: dict):
46
+ """One-shot Guest-mode pitch: fires on the first session of a machine that
47
+ runs below the 500K free tier (offline guest or a fresh anonymous 50K
48
+ community license), then never again (marker file in the data dir). The
49
+ 80%/100% quota banners cover every later nudge, so this must not become
50
+ per-turn nagging. Anonymous guest machines never see the interactive
51
+ installer prompt, so this is their only 500K-for-login touchpoint."""
52
+ try:
53
+ limit = quota.get("monthly_limit")
54
+ if limit is None or int(limit) >= 500000:
55
+ return None
56
+ from src.paths import resolve_data_dir
57
+ marker_path = os.path.join(resolve_data_dir(), ".guest_pitch_shown")
58
+ if os.path.exists(marker_path):
59
+ return None
60
+ os.makedirs(os.path.dirname(marker_path), exist_ok=True)
61
+ with open(marker_path, "w", encoding="utf-8") as marker:
62
+ marker.write("1")
63
+ return _user_markdown(
64
+ "⚡ **TokenSafe Guest mode**: savings pause at 50,000 tokens/month. "
65
+ "Run `tokensafe login` in your terminal to unlock 500,000 free tokens/month (10x) "
66
+ "plus your personal savings dashboard. Takes about a minute."
67
+ )
68
+ except Exception:
69
+ return None
70
+
71
+
45
72
  def main():
46
73
  try:
47
74
  raw_input = sys.stdin.read()
@@ -68,17 +95,24 @@ def main():
68
95
  pass
69
96
 
70
97
  directives = PROTOCOL_DIRECTIVES
98
+ # Cold-start brief (project-gated): the God Nodes banner is mapped only
99
+ # when the host actually opened a workspace folder. Plain chats (no
100
+ # workspacePaths) previously scanned the hook CWD (plugin/system dir) —
101
+ # junk topology + wasted scan time; they now skip the banner entirely.
102
+ # Opened-folder sessions behave exactly as before (regression-minimal
103
+ # gate: folder-opened is the ONLY condition — no project-marker sniffing).
71
104
  try:
72
- from src.graph_engine import GraphEngine
73
- graph = GraphEngine.get_instance(workspace_root)
74
- banner = graph.format_topology_banner()
75
- if banner:
76
- directives = (
77
- f"{directives}\n\n"
78
- f"{banner}\n"
79
- "⚡ Core God Nodes and dependency hubs mapped above. "
80
- "Call 'tokensafe:get_architecture_graph(project_path)' for full dependency trees."
81
- )
105
+ if workspace_paths:
106
+ from src.graph_engine import GraphEngine
107
+ graph = GraphEngine.get_instance(workspace_root)
108
+ banner = graph.format_topology_banner()
109
+ if banner:
110
+ directives = (
111
+ f"{directives}\n\n"
112
+ f"{banner}\n"
113
+ "⚡ Core God Nodes and dependency hubs mapped above. "
114
+ "Call 'tokensafe:get_architecture_graph(project_path)' for full dependency trees."
115
+ )
82
116
  except Exception:
83
117
  pass
84
118
 
@@ -91,6 +125,9 @@ def main():
91
125
  quota = LicenseManager.check_quota(tracker)
92
126
  if quota.get("warning"):
93
127
  inject_steps.append(_user_markdown(quota["warning"]))
128
+ pitch = _guest_pitch_step(quota)
129
+ if pitch:
130
+ inject_steps.append(pitch)
94
131
  except Exception:
95
132
  pass
96
133
 
package/kimi.plugin.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tokensafe",
3
- "version": "4.2.13",
3
+ "version": "4.3.0",
4
4
  "description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
5
5
  "homepage": "https://tokensafe.dev",
6
6
  "license": "MIT",
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "tokensafe",
3
3
  "mcpName": "dev.tokensafe/tokensafe",
4
- "version": "4.2.13",
4
+ "version": "4.3.0",
5
5
  "description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
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": "4.2.13",
4
+ "version": "4.3.0",
5
5
  "description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
6
6
  "logo": "assets/logo.png",
7
7
  "developerName": "TokenSafe",
package/server.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "name": "dev.tokensafe/tokensafe",
4
4
  "title": "TokenSafe",
5
5
  "description": "Your AI agent is smart enough to code all day. Local firewall & zero-loss runtime.",
6
- "version": "4.2.13",
6
+ "version": "4.3.0",
7
7
  "websiteUrl": "https://tokensafe.dev",
8
8
  "repository": {
9
9
  "url": "https://github.com/tokensafe-dev/tokensafe",
@@ -23,7 +23,7 @@
23
23
  "registryType": "npm",
24
24
  "registryBaseUrl": "https://registry.npmjs.org",
25
25
  "identifier": "tokensafe",
26
- "version": "4.2.13",
26
+ "version": "4.3.0",
27
27
  "runtimeHint": "npx",
28
28
  "transport": {
29
29
  "type": "stdio"
@@ -39,7 +39,7 @@
39
39
  "registryType": "pypi",
40
40
  "registryBaseUrl": "https://pypi.org",
41
41
  "identifier": "tokensafe",
42
- "version": "4.2.13",
42
+ "version": "4.3.0",
43
43
  "runtimeHint": "uvx",
44
44
  "transport": {
45
45
  "type": "stdio"
package/src/dashboard.py CHANGED
@@ -54,7 +54,11 @@ EVENT_NAMES = {
54
54
  "TOOL_LEDGER": "Tool Result Ledger (proxy)",
55
55
  "TOOL_PRUNE": "Cold Tool Pruning (proxy)",
56
56
  "TOOL_PRUNE_MISS": "Tool Prune Miss (quality watch)",
57
- "EPOCH_ROLLOVER": "Epoch Rollover (80% window)"
57
+ "EPOCH_ROLLOVER": "Epoch Rollover (80% window)",
58
+ "FOLD_AT_REST": "Fold-at-Rest (Stop hook)",
59
+ "THINKING_FOLD": "Aged Thinking Fold (proxy)",
60
+ "STALE_EDIT_ASK": "Stale-File Edit Guard",
61
+ "CACHE_OBS": "Cache Stability (proxy)"
58
62
  }
59
63
 
60
64
  class Dashboard:
@@ -142,6 +146,22 @@ class Dashboard:
142
146
  out.append(f" • {BOLD}{'Cold MCP tools pruned (proxy)':<34}{RESET} : {GREEN}{tp['saved']:,} floor tokens{RESET} ({tp['count']} events)")
143
147
  out.append("")
144
148
 
149
+ # Cache stability (proxy): does history mutation erode KV-cache hits?
150
+ try:
151
+ cache_obs = self.tracker.get_cache_obs()
152
+ except Exception:
153
+ cache_obs = None
154
+ if cache_obs and cache_obs.get("total"):
155
+ mut_c = cache_obs.get("mutated") or {}
156
+ clean_c = cache_obs.get("clean") or {}
157
+ out.append(f"{BOLD}── Cache Stability (proxy KV-cache) ────────────────────────────────{RESET}")
158
+ if clean_c.get("hit_pct") is not None:
159
+ out.append(f" • {BOLD}{'Clean requests':<34}{RESET} : {GREEN}{clean_c['hit_pct']:.1f}% avg cache-hit{RESET} ({clean_c['n']} samples)")
160
+ if mut_c.get("hit_pct") is not None:
161
+ out.append(f" • {BOLD}{'Mutated (folded) requests':<34}{RESET} : {YELLOW}{mut_c['hit_pct']:.1f}% avg cache-hit{RESET} ({mut_c['n']} samples)")
162
+ out.append(f" {DIM}Mutation stages should not erode hits — a persistent gap means a fold is cache-breaking.{RESET}")
163
+ out.append("")
164
+
145
165
  # Breakdown by category
146
166
  out.append(f"{BOLD}── Breakdown by Source ──────────────────────────────────────────────{RESET}")
147
167
  breakdown = summary.get("breakdown", {})
@@ -149,6 +169,8 @@ class Dashboard:
149
169
  out.append(f" {DIM}No events recorded yet. Run a prompt to see live optimization.{RESET}\n")
150
170
  else:
151
171
  for source, data in breakdown.items():
172
+ if source == "CACHE_OBS":
173
+ continue # zero-savings observability event — has its own panel above
152
174
  s_name = EVENT_NAMES.get(source, source)
153
175
  out.append(f" • {BOLD}{s_name:<32}{RESET} : {GREEN}{data['saved']:,} tokens saved{RESET} ({data['count']} events)")
154
176
  out.append("")
@@ -215,9 +237,26 @@ class Dashboard:
215
237
  md.append("| Pipeline Stage | Events | Tokens Saved |")
216
238
  md.append("| :--- | :--- | :--- |")
217
239
  for source, data in summary.get("breakdown", {}).items():
240
+ if source == "CACHE_OBS":
241
+ continue # zero-savings observability event — has its own panel below
218
242
  s_name = EVENT_NAMES.get(source, source)
219
243
  md.append(f"| **{s_name}** | {data['count']} | `{data['saved']:,}` |")
220
244
 
245
+ try:
246
+ cache_obs = self.tracker.get_cache_obs()
247
+ except Exception:
248
+ cache_obs = None
249
+ if cache_obs and cache_obs.get("total"):
250
+ mut_c = cache_obs.get("mutated") or {}
251
+ clean_c = cache_obs.get("clean") or {}
252
+ md.append("\n### Cache Stability (proxy KV-cache)\n")
253
+ md.append("| Request Kind | Samples | Avg Cache-Hit |")
254
+ md.append("| :--- | :--- | :--- |")
255
+ clean_pct = clean_c.get("hit_pct")
256
+ mut_pct = mut_c.get("hit_pct")
257
+ md.append(f"| Clean | {clean_c.get('n', 0)} | {f'{clean_pct:.1f}%' if clean_pct is not None else '—'} |")
258
+ md.append(f"| Mutated (folded) | {mut_c.get('n', 0)} | {f'{mut_pct:.1f}%' if mut_pct is not None else '—'} |")
259
+
221
260
  md.append("\n### Recent Optimization Events\n")
222
261
  md.append("| Timestamp | Event Type | Scope | Tokens Before ➔ After | Saved |")
223
262
  md.append("| :--- | :--- | :--- | :--- | :--- |")
@@ -244,6 +283,8 @@ class Dashboard:
244
283
 
245
284
  breakdown_rows = ""
246
285
  for source, data in summary.get("breakdown", {}).items():
286
+ if source == "CACHE_OBS":
287
+ continue # zero-savings observability event — kept out of the savings cards
247
288
  s_name = html_lib.escape(str(EVENT_NAMES.get(source, source)))
248
289
  s_pct = round((data['saved'] / total_saved * 100.0), 1) if total_saved > 0 else 0
249
290
  breakdown_rows += f"""
@@ -0,0 +1,198 @@
1
+ """
2
+ TokenSafe File-State Tracker (stale-edit guard).
3
+
4
+ Records a content-hash snapshot of every file the model has just SEEN (Read)
5
+ or just REWRITTEN (Write/Edit) — machine-level state shared by all agents —
6
+ so PreToolUse hooks can detect externally-changed edit targets (build output,
7
+ linters/formatters, another concurrent session) BEFORE the edit lands.
8
+
9
+ Why: an edit against a stale file either corrupts content (hosts without
10
+ native protection) or fails and forces the model to re-read the whole file,
11
+ burning a full file-worth of context on every occurrence.
12
+
13
+ Design rules:
14
+ - Fail-open everywhere: any internal error returns None/False so the guard
15
+ degrades to "no opinion" and never blocks a tool call by itself.
16
+ - ``ask``/``force_ask`` only, never deny (same philosophy as guard_write).
17
+ - Kill switch: TOKENSAFE_STALE_GUARD=0 disables the PreToolUse checks;
18
+ tracking (PostToolUse hashing) stays harmless and keeps running.
19
+ - State lives in <data_dir>/file_state.json, atomic writes, LRU-capped.
20
+ """
21
+
22
+ import os
23
+ import json
24
+ import time
25
+ import hashlib
26
+ import tempfile
27
+ from typing import Any, Dict, Optional
28
+
29
+ from src.paths import resolve_data_dir
30
+
31
+ STATE_FILENAME = "file_state.json"
32
+ _MAX_ENTRIES = 512
33
+ _MAX_FILE_BYTES = 1_000_000
34
+ _ENTRY_TTL_S = 7 * 86400
35
+
36
+ # Files that are never tracked: binaries, generated bundles, lockfiles and
37
+ # anything under TokenSafe's own data dir (self-edits would poison the map).
38
+ _SKIP_SUFFIXES = (
39
+ ".png", ".jpg", ".jpeg", ".gif", ".webp", ".ico", ".pdf", ".zip", ".tar",
40
+ ".gz", ".bz2", ".7z", ".rar", ".mp4", ".mov", ".mp3", ".wav", ".woff",
41
+ ".woff2", ".ttf", ".otf", ".eot", ".db", ".sqlite", ".sqlite3", ".pyc",
42
+ ".pyo", ".class", ".jar", ".so", ".dylib", ".node", ".wasm", ".exe",
43
+ ".dll", ".bin", ".iso", ".dmg", ".min.js", ".min.css", ".map", ".lock",
44
+ )
45
+ _SKIP_PARTS = (
46
+ ".git", "node_modules", "dist", "build", "out", "__pycache__",
47
+ ".venv", "venv", ".tox", ".mypy_cache", ".pytest_cache", "vendor",
48
+ )
49
+
50
+
51
+ def guard_enabled() -> bool:
52
+ """Kill switch for the PreToolUse stale checks (tracking is always safe)."""
53
+ return os.environ.get("TOKENSAFE_STALE_GUARD", "").strip().lower() not in ("0", "false", "no")
54
+
55
+
56
+ def _state_path() -> str:
57
+ return os.path.join(resolve_data_dir(), STATE_FILENAME)
58
+
59
+
60
+ def _skip_path(path: str) -> bool:
61
+ try:
62
+ real = os.path.realpath(path)
63
+ data_root = os.path.realpath(resolve_data_dir())
64
+ if real == data_root or real.startswith(data_root + os.sep):
65
+ return True
66
+ home = os.path.realpath(os.path.expanduser("~"))
67
+ if real.startswith(os.path.join(home, ".tokensafe")):
68
+ return True
69
+ lowered = real.lower()
70
+ if lowered.endswith(_SKIP_SUFFIXES):
71
+ return True
72
+ parts = {p.lower() for p in os.path.normpath(real).split(os.sep)}
73
+ if parts & set(_SKIP_PARTS):
74
+ return True
75
+ return os.path.getsize(real) > _MAX_FILE_BYTES
76
+ except OSError:
77
+ return True
78
+
79
+
80
+ def _load_state() -> Dict[str, Any]:
81
+ try:
82
+ with open(_state_path(), "r", encoding="utf-8") as f:
83
+ data = json.load(f)
84
+ return data if isinstance(data, dict) else {}
85
+ except Exception:
86
+ return {}
87
+
88
+
89
+ def _save_state(state: Dict[str, Any]) -> None:
90
+ try:
91
+ target = _state_path()
92
+ os.makedirs(os.path.dirname(target), exist_ok=True)
93
+ fd, tmp = tempfile.mkstemp(prefix=".file_state_", dir=os.path.dirname(target))
94
+ try:
95
+ with os.fdopen(fd, "w", encoding="utf-8") as f:
96
+ json.dump(state, f)
97
+ os.replace(tmp, target)
98
+ except Exception:
99
+ try:
100
+ if os.path.exists(tmp):
101
+ os.unlink(tmp)
102
+ except OSError:
103
+ pass
104
+ except Exception:
105
+ pass
106
+
107
+
108
+ def _prune_state(state: Dict[str, Any]) -> Dict[str, Any]:
109
+ now = time.time()
110
+ live = {
111
+ k: v for k, v in state.items()
112
+ if isinstance(v, dict) and (now - float(v.get("ts") or 0)) < _ENTRY_TTL_S
113
+ }
114
+ if len(live) > _MAX_ENTRIES:
115
+ ranked = sorted(live.items(), key=lambda kv: float(kv[1].get("ts") or 0), reverse=True)
116
+ live = dict(ranked[:_MAX_ENTRIES])
117
+ return live
118
+
119
+
120
+ def record_seen(path: str) -> bool:
121
+ """Snapshots the current on-disk hash of ``path`` (post-Read/post-Write).
122
+
123
+ Returns True when a snapshot was recorded. A missing file drops its entry
124
+ (deleted targets can never be stale)."""
125
+ if not path:
126
+ return False
127
+ abs_path = os.path.abspath(path)
128
+ try:
129
+ with open(abs_path, "rb") as f:
130
+ blob = f.read()
131
+ except FileNotFoundError:
132
+ try:
133
+ state = _prune_state(_load_state())
134
+ if abs_path in state:
135
+ state.pop(abs_path, None)
136
+ _save_state(state)
137
+ except Exception:
138
+ pass
139
+ return False
140
+ except Exception:
141
+ return False
142
+ if _skip_path(abs_path):
143
+ return False
144
+ try:
145
+ sha = hashlib.sha256(blob).hexdigest()
146
+ state = _prune_state(_load_state())
147
+ state[abs_path] = {"sha": sha, "ts": time.time(), "size": len(blob)}
148
+ # Trim AFTER insertion so the cap holds on the saved snapshot too.
149
+ state = _prune_state(state)
150
+ _save_state(state)
151
+ return True
152
+ except Exception:
153
+ return False
154
+
155
+
156
+ def check_stale(path: str) -> Optional[Dict[str, Any]]:
157
+ """Returns staleness info when ``path`` changed on disk since the last
158
+ snapshot, else None (never seen, unchanged, deleted, or untrackable)."""
159
+ if not path:
160
+ return None
161
+ try:
162
+ abs_path = os.path.abspath(path)
163
+ if _skip_path(abs_path):
164
+ return None
165
+ entry = _load_state().get(abs_path)
166
+ if not isinstance(entry, dict):
167
+ return None
168
+ with open(abs_path, "rb") as f:
169
+ blob = f.read()
170
+ sha = hashlib.sha256(blob).hexdigest()
171
+ if sha == entry.get("sha"):
172
+ return None
173
+ return {
174
+ "age_s": round(time.time() - float(entry.get("ts") or 0)),
175
+ "size_seen": int(entry.get("size") or 0),
176
+ "size_now": len(blob),
177
+ }
178
+ except Exception:
179
+ return None
180
+
181
+
182
+ def estimate_reread_tokens(path: str, cap: int = 50_000) -> int:
183
+ """Cheap counterfactual for the wasted re-read mass (bytes/4 heuristic)."""
184
+ try:
185
+ return min(cap, os.path.getsize(os.path.abspath(path)) // 4)
186
+ except Exception:
187
+ return 0
188
+
189
+
190
+ class FileState:
191
+ """Namespace facade so hook call sites read naturally
192
+ (``FileState.record_seen(path)``) while the module-level functions above
193
+ stay directly importable for tests."""
194
+
195
+ guard_enabled = staticmethod(guard_enabled)
196
+ record_seen = staticmethod(record_seen)
197
+ check_stale = staticmethod(check_stale)
198
+ estimate_reread_tokens = staticmethod(estimate_reread_tokens)
package/src/installer.py CHANGED
@@ -292,6 +292,14 @@ class AgentInstaller:
292
292
  write_entry = {"matcher": "Write", "hooks": [{"type": "command", "command": claude_cmd, "timeout": 10}]}
293
293
  session_entry = {"hooks": [{"type": "command", "command": claude_cmd, "timeout": 10}]}
294
294
  post_bash_entry = {"matcher": "Bash", "hooks": [{"type": "command", "command": claude_cmd, "timeout": 10}]}
295
+ # Stale-edit guard: PreToolUse asks on externally-changed targets;
296
+ # PostToolUse snapshots the on-disk hash after every read/write.
297
+ stale_edit_entry = {"matcher": "Edit|MultiEdit", "hooks": [{"type": "command", "command": claude_cmd, "timeout": 10}]}
298
+ post_track_entry = {"matcher": "Read|Edit|MultiEdit|Write", "hooks": [{"type": "command", "command": claude_cmd, "timeout": 10}]}
299
+ # Fold-at-rest: Stop hook prunes superseded reads from the idle
300
+ # transcript (opt-in via TOKENSAFE_FOLD_AT_REST=1; the hook itself
301
+ # is a no-op while the flag is off).
302
+ stop_entry = {"hooks": [{"type": "command", "command": claude_cmd, "timeout": 15}]}
295
303
 
296
304
  def _sync_claude_event(event_name: str, default_entry: dict) -> bool:
297
305
  entries = hooks.get(event_name)
@@ -318,13 +326,16 @@ class AgentInstaller:
318
326
  _sync_claude_event("UserPromptSubmit", prompt_entry),
319
327
  _sync_claude_event("PreToolUse", bash_entry),
320
328
  _sync_claude_event("PreToolUse", write_entry),
329
+ _sync_claude_event("PreToolUse", stale_edit_entry),
321
330
  _sync_claude_event("PostToolUse", post_bash_entry),
331
+ _sync_claude_event("PostToolUse", post_track_entry),
332
+ _sync_claude_event("Stop", stop_entry),
322
333
  ])
323
334
  if not changed:
324
335
  return True, "TokenSafe Claude Code hooks already registered"
325
336
  data["hooks"] = hooks
326
337
  cls._atomic_write_json(config_file, data)
327
- return True, "hooks registered (SessionStart + UserPromptSubmit + PreToolUse guard/write + PostToolUse stdout compact)"
338
+ return True, "hooks registered (SessionStart + UserPromptSubmit + PreToolUse guard/write/stale + PostToolUse compact/tracking + Stop fold-at-rest)"
328
339
 
329
340
  if agent_key == "zcode":
330
341
  config_file = os.path.join(HOME, ".zcode", "cli", "config.json")
package/src/mcp_server.py CHANGED
@@ -42,7 +42,7 @@ from src.paths import get_active_workspace, is_plugin_or_system_dir
42
42
 
43
43
  SERVER_INFO = {
44
44
  "name": "tokensafe-mcp",
45
- "version": "4.2.13"
45
+ "version": "4.3.0"
46
46
  }
47
47
 
48
48
  # MCP client attribution: the initialize handshake carries clientInfo, which
package/src/metrics.py CHANGED
@@ -541,6 +541,58 @@ class MetricsTracker:
541
541
  except Exception:
542
542
  return {"events": 0, "saved_tokens": 0, "usd_saved": 0.0}
543
543
 
544
+ def get_cache_obs(self, limit: int = 300) -> Dict[str, Any]:
545
+ """Aggregates CACHE_OBS proxy events into clean-vs-mutated cache-hit
546
+ ratios — the evidence for the cache-stability claim: history-mutation
547
+ stages (ledger/thinking/prompt/governor) should NOT erode KV-cache
548
+ hits versus clean requests.
549
+
550
+ Hit definition per provider shape:
551
+ - anthropic: cache_read / (input + cache_read + cache_write)
552
+ - openai: cached_tokens / prompt_tokens (prompt already includes cache)
553
+ Zero-denominator samples are skipped."""
554
+ samples: List[Dict[str, Any]] = []
555
+ with self._get_connection() as conn:
556
+ cursor = conn.cursor()
557
+ cursor.execute(
558
+ "SELECT details FROM events WHERE event_type = 'CACHE_OBS' ORDER BY id DESC LIMIT ?",
559
+ (int(limit),),
560
+ )
561
+ for row in cursor.fetchall():
562
+ try:
563
+ d = json.loads(row["details"] or "{}")
564
+ if isinstance(d, dict):
565
+ samples.append(d)
566
+ except Exception:
567
+ continue
568
+
569
+ def _hit(d: Dict[str, Any]) -> Optional[float]:
570
+ cache_read = float(d.get("cache_read") or 0)
571
+ if str(d.get("provider") or "") == "anthropic":
572
+ denom = float(d.get("input") or 0) + cache_read + float(d.get("cache_write") or 0)
573
+ else:
574
+ denom = float(d.get("input") or 0)
575
+ return (cache_read / denom) if denom > 0 else None
576
+
577
+ buckets: Dict[str, List[float]] = {"mutated": [], "clean": []}
578
+ for d in samples:
579
+ hit = _hit(d)
580
+ if hit is None:
581
+ continue
582
+ buckets["mutated" if d.get("mutations") else "clean"].append(hit)
583
+
584
+ def _agg(hits: List[float]) -> Dict[str, Any]:
585
+ return {
586
+ "n": len(hits),
587
+ "hit_pct": round(sum(hits) / len(hits) * 100.0, 1) if hits else None,
588
+ }
589
+
590
+ return {
591
+ "mutated": _agg(buckets["mutated"]),
592
+ "clean": _agg(buckets["clean"]),
593
+ "total": len(samples),
594
+ }
595
+
544
596
  def get_summary(self) -> Dict[str, Any]:
545
597
  """Returns cumulative statistics across all sessions, including lifetime rollups."""
546
598
  with self._get_connection() as conn:
package/src/paths.py CHANGED
@@ -201,3 +201,37 @@ def ensure_tokensafe_gitignore(project_root: Optional[str]) -> bool:
201
201
 
202
202
  return updated
203
203
 
204
+
205
+ _PROJECT_MARKER_FILES = (
206
+ "package.json", "pyproject.toml", "setup.py", "setup.cfg", "requirements.txt",
207
+ "go.mod", "Cargo.toml", "pom.xml", "build.gradle", "build.gradle.kts",
208
+ "composer.json", "Gemfile", "mix.exs", "Makefile", "CMakeLists.txt",
209
+ )
210
+
211
+
212
+ def is_project_root(path: str) -> bool:
213
+ """True when ``path`` looks like a real working project the agent can code in.
214
+
215
+ Used to gate project-scoped SessionStart injections (cold-start brief /
216
+ God Nodes banner): plain chats and plugin/system directories must stay
217
+ banner-free. A directory qualifies when it carries a VCS root or any
218
+ well-known project manifest, and is neither the home directory, a hidden
219
+ home subdirectory, nor a plugin/system dir per ``is_plugin_or_system_dir``.
220
+ Fail-open is deliberately NOT used here: an unrecognized directory simply
221
+ gets no brief (additive-only behavior, never breaks existing sessions).
222
+ """
223
+ try:
224
+ if not path or not os.path.isdir(path):
225
+ return False
226
+ if is_plugin_or_system_dir(path):
227
+ return False
228
+ real = os.path.realpath(path)
229
+ home = os.path.expanduser("~")
230
+ if real == home or real.startswith(home + os.sep + "."):
231
+ return False
232
+ if os.path.isdir(os.path.join(real, ".git")) or os.path.isfile(os.path.join(real, ".git")):
233
+ return True
234
+ return any(os.path.exists(os.path.join(real, marker)) for marker in _PROJECT_MARKER_FILES)
235
+ except Exception:
236
+ return False
237
+
package/src/proxy.py CHANGED
@@ -29,6 +29,7 @@ from src.graph_engine import GraphEngine
29
29
  from src.cache_normalizer import PromptCacheNormalizer
30
30
  from src.governor import ContextGovernor
31
31
  from src.result_ledger import fold_tool_results
32
+ from src.thinking_fold import fold_aged_thinking
32
33
  from src.tool_pruner import _tool_name, apply_subset, detect_prune_miss
33
34
  from src.paths import resolve_data_dir
34
35
 
@@ -73,6 +74,42 @@ class EventBroadcaster:
73
74
 
74
75
  BROADCASTER = EventBroadcaster()
75
76
 
77
+ _CACHE_OBS_MIN_INTERVAL_S = 30.0
78
+ _last_cache_obs_ts = 0.0
79
+
80
+
81
+ def _record_cache_obs(tracker, provider: str, mutation_kinds: List[str],
82
+ input_tokens: int, cache_read: int, cache_write: int) -> None:
83
+ """CACHE_OBS: per-response KV-cache observation (zero-savings telemetry).
84
+
85
+ Lets the dashboard PROVE cache stability: average cache-hit ratio on
86
+ requests where history-mutation stages fired vs clean requests. Clean
87
+ samples are throttled; every mutated request is recorded — that is the
88
+ signal this metric exists for."""
89
+ global _last_cache_obs_ts
90
+ mutated = bool(mutation_kinds)
91
+ now = time.time()
92
+ if not mutated and (now - _last_cache_obs_ts) < _CACHE_OBS_MIN_INTERVAL_S:
93
+ return
94
+ _last_cache_obs_ts = now
95
+ try:
96
+ tracker.record_event(
97
+ session_id="proxy_session",
98
+ event_type="CACHE_OBS",
99
+ original_tokens=0,
100
+ optimized_tokens=0,
101
+ details={
102
+ "provider": str(provider),
103
+ "input": int(input_tokens or 0),
104
+ "cache_read": int(cache_read or 0),
105
+ "cache_write": int(cache_write or 0),
106
+ "mutations": list(mutation_kinds or []),
107
+ },
108
+ measurement="measured",
109
+ )
110
+ except Exception:
111
+ pass
112
+
76
113
 
77
114
  # ---------------------------------------------------------------------------
78
115
  # OpenAI <-> Anthropic payload translation.
@@ -991,6 +1028,13 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
991
1028
  if secrets_scrubbed > 0:
992
1029
  print(f"[TokenSafe] Scrubbed {secrets_scrubbed} sensitive secret(s) from payload before transmission.")
993
1030
 
1031
+ # Stage-local stats init: kept defined even when the quota gate skips
1032
+ # the stages below (the CACHE_OBS signature reads them afterwards).
1033
+ ledger_stats: Dict[str, Any] = {}
1034
+ think_stats: Dict[str, Any] = {}
1035
+ gov_stats: Dict[str, Any] = {}
1036
+ prompt_mutated = False
1037
+
994
1038
  # 1.5 Tool Result Ledger: fold aged, oversized tool results into compact
995
1039
  # anchors + local archive (idempotent via marker; cache-aware). Runs
996
1040
  # before the governor so the governor sees the lightened mass.
@@ -1006,6 +1050,23 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
1006
1050
  except Exception:
1007
1051
  pass
1008
1052
 
1053
+ # 1.6 Aged Thinking Fold (OPT-IN, DEFAULT OFF via TOKENSAFE_FOLD_THINKING):
1054
+ # collapse extended-thinking payloads of aged assistant turns into
1055
+ # one-line stubs. The _tokensafe_thinking side-channel key stays a
1056
+ # valid text block for shape-sensitive mirrors (the 1214 class).
1057
+ # Enable only after the upstream shape probe matrix passes.
1058
+ if messages and not is_quota_exceeded:
1059
+ try:
1060
+ messages, think_stats = fold_aged_thinking(messages)
1061
+ payload["messages"] = messages
1062
+ if think_stats.get("folded"):
1063
+ print(
1064
+ f"[TokenSafe] Aged thinking folded: {think_stats['folded']} turn(s), "
1065
+ f"~{think_stats['saved_tokens']} input tokens lighter."
1066
+ )
1067
+ except Exception:
1068
+ pass
1069
+
1009
1070
  # 2. Ingress Optimization: REPLACE the last user message with its TOCP form.
1010
1071
  # Paused when Community 500k monthly measured quota is exceeded.
1011
1072
  target_symbol = None
@@ -1017,6 +1078,7 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
1017
1078
  compaction = PromptCompactor.compact(raw_user, enable_distill=False)
1018
1079
  if compaction["saved_tokens"] > 5:
1019
1080
  msg["content"] = compaction["compact_text"]
1081
+ prompt_mutated = True
1020
1082
  try:
1021
1083
  proxy_tracker.record_event(
1022
1084
  session_id="proxy_session",
@@ -1140,6 +1202,18 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
1140
1202
  payload["tools"], provider=provider, inject_cache_control=False
1141
1203
  )
1142
1204
 
1205
+ # Request mutation signature for cache-stability telemetry: which
1206
+ # history-mutation stages fired on THIS request (the CACHE_OBS panel
1207
+ # splits the cache-hit ratio into mutated vs clean by this list).
1208
+ mutation_kinds = [
1209
+ kind for kind, fired in (
1210
+ ("ledger", bool(ledger_stats.get("folded"))),
1211
+ ("thinking", bool(think_stats.get("folded"))),
1212
+ ("prompt", prompt_mutated),
1213
+ ("governor", bool(gov_stats.get("saved_tokens"))),
1214
+ ) if fired
1215
+ ]
1216
+
1143
1217
  if provider == "anthropic":
1144
1218
  # Outbound OpenAI->Anthropic translation is skipped when the CLIENT
1145
1219
  # itself speaks Anthropic (ingest): the pipeline ran on the internal
@@ -1239,6 +1313,20 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
1239
1313
  BROADCASTER.publish("cache_stats", {"provider": provider, "cached_tokens": int(m_cached.group(1))})
1240
1314
  elif m_usage:
1241
1315
  BROADCASTER.publish("cache_stats", {"provider": provider, "cached_tokens": 0})
1316
+ # Cache-stability observation (Anthropic-shape tails):
1317
+ # input/cache fields live in message_start, which the
1318
+ # 64KB tail may evict on very long streams — record
1319
+ # only when at least one real field survived.
1320
+ m_in = re.search(r'"input_tokens":\s*(\d+)', tail_text)
1321
+ m_cw = re.search(r'"cache_creation_input_tokens":\s*(\d+)', tail_text)
1322
+ sse_input = int(m_in.group(1)) if m_in else 0
1323
+ if m_cached or sse_input > 0:
1324
+ _record_cache_obs(
1325
+ proxy_tracker, provider, mutation_kinds,
1326
+ sse_input,
1327
+ int(m_cached.group(1)) if m_cached else 0,
1328
+ int(m_cw.group(1)) if m_cw else 0,
1329
+ )
1242
1330
  except Exception:
1243
1331
  pass
1244
1332
  else:
@@ -1274,6 +1362,14 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
1274
1362
  or usage.get("prompt_cache_hit_tokens")
1275
1363
  or 0
1276
1364
  )
1365
+ # Cache-stability observation (non-stream path: both
1366
+ # Anthropic and OpenAI usage shapes are available).
1367
+ _record_cache_obs(
1368
+ proxy_tracker, provider, mutation_kinds,
1369
+ int(usage.get("prompt_tokens") or usage.get("input_tokens") or 0),
1370
+ int(cached or 0),
1371
+ int(usage.get("cache_creation_input_tokens") or 0),
1372
+ )
1277
1373
  if cached:
1278
1374
  BROADCASTER.publish("cache_stats", {"provider": provider, "cached_tokens": int(cached)})
1279
1375
  # Prune-miss telemetry: model called a tool outside the
package/src/superseded.py CHANGED
@@ -278,3 +278,46 @@ class SupersededPruner:
278
278
  "transcript_path": transcript_path,
279
279
  **stats
280
280
  }
281
+
282
+ FOLD_AT_REST_MIN_BYTES = 100_000
283
+ FOLD_AT_REST_BACKUP_MAX = 20_000_000
284
+
285
+ @classmethod
286
+ def fold_at_rest(cls, transcript_path: str) -> Dict[str, Any]:
287
+ """Stop-hook entry (fold-at-rest): prunes superseded intermediate reads
288
+ from an idle session transcript IN PLACE.
289
+
290
+ Safety envelope:
291
+ - Tombstones are structure-preserving: every JSONL line stays a valid
292
+ message with identical ids/parent chain — only oversized content
293
+ strings shrink to reversible stash markers. Claude Code appends new
294
+ turns to the same file, so the chain never breaks.
295
+ - Atomic rewrite (tmp + os.replace) via prune_transcript; a one-file
296
+ ``.tokensafe.bak`` copy of the pre-fold bytes is kept for rollback.
297
+ - Sessions below 100KB are skipped outright (nothing worth folding).
298
+ - Fail-open: any error returns success=False, transcript untouched."""
299
+ if not transcript_path or not os.path.exists(transcript_path):
300
+ return {"success": False, "error": f"Transcript not found: {transcript_path}"}
301
+ try:
302
+ size = os.path.getsize(transcript_path)
303
+ except OSError as e:
304
+ return {"success": False, "error": str(e)}
305
+ if size < cls.FOLD_AT_REST_MIN_BYTES:
306
+ return {"success": False, "skipped": "below fold-at-rest size threshold"}
307
+
308
+ raw_backup: Optional[bytes] = None
309
+ if size <= cls.FOLD_AT_REST_BACKUP_MAX:
310
+ try:
311
+ with open(transcript_path, "rb") as f:
312
+ raw_backup = f.read()
313
+ except Exception:
314
+ raw_backup = None
315
+
316
+ res = cls.prune_transcript(transcript_path)
317
+ if res.get("success") and res.get("pruned_count", 0) > 0 and raw_backup:
318
+ try:
319
+ with open(f"{transcript_path}.tokensafe.bak", "wb") as f:
320
+ f.write(raw_backup)
321
+ except Exception:
322
+ pass
323
+ return res
@@ -241,7 +241,7 @@ class TelemetrySync:
241
241
  current_last_id = last_id
242
242
  headers = {
243
243
  "Content-Type": "application/json",
244
- "User-Agent": "TokenSafe-Sync/4.2.13"
244
+ "User-Agent": "TokenSafe-Sync/4.3.0"
245
245
  }
246
246
  if active_key:
247
247
  headers["Authorization"] = f"Bearer {active_key}"
@@ -0,0 +1,105 @@
1
+ """
2
+ TokenSafe Aged Thinking Fold (proxy stage 1.6, OPT-IN, DEFAULT OFF).
3
+
4
+ Collapses extended-thinking payloads of AGED assistant turns into one-line
5
+ stubs inside the proxy pipeline. The ``_tokensafe_thinking`` side-channel key
6
+ stays present holding a valid text block, so shape-sensitive mirrors (the
7
+ z.ai 1214 class) keep accepting the rebuilt tool_use turns — only the mass
8
+ shrinks. Recent turns (last ``keep_recent`` messages) are never touched, and
9
+ the fold is idempotent via an in-content marker (KV-cache stable re-runs).
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).
13
+ """
14
+
15
+ import os
16
+ from typing import Any, Dict, List, Tuple
17
+
18
+ from src.tokenizer import count_tokens
19
+
20
+ THINKING_FOLD_MARKER = "[TokenSafe: aged thinking folded"
21
+ DEFAULT_KEEP_RECENT = 6
22
+ DEFAULT_MIN_CHARS = 2000
23
+
24
+
25
+ def _env_flag(name: str) -> bool:
26
+ return os.environ.get(name, "").strip().lower() in ("1", "true", "yes")
27
+
28
+
29
+ def _thinking_text_len(blocks: Any) -> int:
30
+ if not isinstance(blocks, list):
31
+ return 0
32
+ total = 0
33
+ for b in blocks:
34
+ if isinstance(b, dict):
35
+ total += len(str(b.get("text") or b.get("thinking") or ""))
36
+ elif isinstance(b, str):
37
+ total += len(b)
38
+ return total
39
+
40
+
41
+ def _has_marker(blocks: Any) -> bool:
42
+ if not isinstance(blocks, list):
43
+ return False
44
+ for b in blocks:
45
+ text = str(b.get("text") or b.get("thinking") or "") if isinstance(b, dict) else str(b)
46
+ if THINKING_FOLD_MARKER in text:
47
+ return True
48
+ return False
49
+
50
+
51
+ def fold_aged_thinking(
52
+ messages: List[Dict[str, Any]],
53
+ keep_recent: int = DEFAULT_KEEP_RECENT,
54
+ min_chars: int = DEFAULT_MIN_CHARS,
55
+ record: bool = True,
56
+ session_id: str = "proxy_session",
57
+ ) -> Tuple[List[Dict[str, Any]], Dict[str, Any]]:
58
+ """Folds aged ``_tokensafe_thinking`` payloads in place. Returns (messages, stats).
59
+
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"):
65
+ return messages, stats
66
+
67
+ protected_from = max(0, len(messages) - keep_recent)
68
+ for idx, msg in enumerate(messages):
69
+ if idx >= protected_from or not isinstance(msg, dict) or msg.get("role") != "assistant":
70
+ continue
71
+ blocks = msg.get("_tokensafe_thinking")
72
+ if not isinstance(blocks, list) or not blocks or _has_marker(blocks):
73
+ continue
74
+ orig_len = _thinking_text_len(blocks)
75
+ if orig_len < min_chars:
76
+ continue
77
+ orig_tokens = count_tokens(
78
+ "".join(
79
+ str(b.get("text") or b.get("thinking") or "") if isinstance(b, dict) else str(b)
80
+ for b in blocks
81
+ )
82
+ )
83
+ 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
+ new_tokens = count_tokens(stub_text)
86
+ stats["folded"] += 1
87
+ stats["orig_tokens"] += orig_tokens
88
+ stats["new_tokens"] += new_tokens
89
+ stats["saved_tokens"] += max(0, orig_tokens - new_tokens)
90
+
91
+ if stats["folded"] and record:
92
+ try:
93
+ from src.metrics import MetricsTracker
94
+ MetricsTracker().record_event(
95
+ session_id=session_id,
96
+ event_type="THINKING_FOLD",
97
+ original_tokens=stats["orig_tokens"],
98
+ optimized_tokens=stats["new_tokens"],
99
+ details={"folded": stats["folded"]},
100
+ measurement="measured",
101
+ )
102
+ except Exception:
103
+ pass
104
+
105
+ return messages, stats
@@ -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 = "4.2.13"
20
+ CURRENT_VERSION = "4.3.0"
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