tokensafe 4.12.1 → 4.12.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.
@@ -2,8 +2,14 @@
2
2
  TokenSafe MCP Config Manager (v3.3.0).
3
3
 
4
4
  Inspects, wraps, and unwraps third-party MCP servers across AI coding agent configs
5
- (Claude Code, Cursor, Codex, Windsurf) to route them through `tokensafe mcp-proxy`.
6
- Preserves original command & arguments under `_tokensafe_orig` for 100% reversible unwrapping.
5
+ (Claude Code/Desktop, Cursor, Codex, Windsurf, Antigravity, ZCode, Copilot, Kimi,
6
+ Cline/Roo) to route them through `tokensafe mcp-proxy`. Preserves original command
7
+ & arguments under `_tokensafe_orig` for 100% reversible unwrapping.
8
+
9
+ Codex CLI is the one JSON-wrapped host we cannot cover yet: its MCP servers live
10
+ in `~/.codex/config.toml` (TOML), so wrapping it needs a TOML writer. Until then
11
+ `tokensafe mcp wrap` reports it as unsupported rather than silently rewriting the
12
+ wrong file.
7
13
  """
8
14
 
9
15
  import os
@@ -14,12 +20,33 @@ from typing import Dict, Any, List, Optional, Tuple
14
20
 
15
21
  HOME = os.path.expanduser("~")
16
22
 
23
+
24
+ def _vscode_user_dir() -> str:
25
+ """VS Code's per-user directory, where extension MCP configs live."""
26
+ if sys.platform == "darwin":
27
+ return os.path.join(HOME, "Library", "Application Support", "Code", "User")
28
+ if sys.platform == "win32":
29
+ appdata = os.environ.get("APPDATA") or os.path.join(HOME, "AppData", "Roaming")
30
+ return os.path.join(appdata, "Code", "User")
31
+ return os.path.join(os.environ.get("XDG_CONFIG_HOME") or os.path.join(HOME, ".config"), "Code", "User")
32
+
33
+
17
34
  CONFIG_CANDIDATES = [
18
35
  ("Claude Code / Desktop", os.path.join(HOME, ".claude.json")),
19
36
  ("Claude Settings", os.path.join(HOME, ".claude", "settings.json")),
20
37
  ("Cursor Global", os.path.join(HOME, ".cursor", "mcp.json")),
21
38
  ("Codex Global", os.path.join(HOME, ".codex", "config.json")),
22
39
  ("Windsurf Global", os.path.join(HOME, ".codeium", "windsurf", "mcp_config.json")),
40
+ ("Antigravity", os.path.join(HOME, ".gemini", "config", "mcp_config.json")),
41
+ ("ZCode", os.path.join(HOME, ".zcode", "cli", "config.json")),
42
+ ("Copilot", os.path.join(HOME, ".copilot", "mcp-config.json")),
43
+ ("Kimi Code", os.path.join(HOME, ".kimi-code", "mcp.json")),
44
+ ("Cline (VS Code)", os.path.join(
45
+ _vscode_user_dir(), "globalStorage", "saoudrizwan.claude-dev",
46
+ "settings", "cline_mcp_settings.json")),
47
+ ("Roo Code (VS Code)", os.path.join(
48
+ _vscode_user_dir(), "globalStorage", "rooveterinaryinc.roo-cline",
49
+ "settings", "mcp_settings.json")),
23
50
  ]
24
51
 
25
52
 
package/src/mcp_proxy.py CHANGED
@@ -25,6 +25,28 @@ MAX_UNFOLDED_BYTES = 8800
25
25
  HEAD_LINES = 15
26
26
  TAIL_LINES = 10
27
27
 
28
+ # Tool-surface profiles. Mirrors `_LEAN_TOOL_NAMES` / `TOOLS` in mcp_server.py;
29
+ # kept local so the stdio proxy never imports the whole server module.
30
+ # tests/test_mcp_proxy.py asserts both lists stay in sync.
31
+ DEFAULT_PROFILE_TOOLS = frozenset({
32
+ "smart_read_file", "scoped_search", "apply_edits", "repo_map",
33
+ "session_context", "oumv", "run_helper",
34
+ })
35
+ LEAN_PROFILE_TOOLS = frozenset({
36
+ "smart_read_file", "scoped_search", "apply_edits", "repo_map", "oumv",
37
+ })
38
+
39
+
40
+ def _looks_like_tokensafe(cmd: List[str]) -> bool:
41
+ """Only our own server may have its tools/list filtered."""
42
+ joined = " ".join(str(part) for part in cmd).lower()
43
+ return "tokensafe" in joined or "mcp_server.py" in joined
44
+
45
+
46
+ def _filter_tools_list(tools: List[Any], profile: str) -> List[Any]:
47
+ keep = LEAN_PROFILE_TOOLS if profile == "lean" else DEFAULT_PROFILE_TOOLS
48
+ return [t for t in tools if isinstance(t, dict) and t.get("name") in keep]
49
+
28
50
 
29
51
  def fold_tool_text(text: str, tool_name: str = "mcp_tool") -> Tuple[str, bool]:
30
52
  """Folds oversized text and returns (folded_text, was_folded).
@@ -39,6 +61,17 @@ def fold_tool_text(text: str, tool_name: str = "mcp_tool") -> Tuple[str, bool]:
39
61
  if raw_bytes <= MAX_UNFOLDED_BYTES and len(text) <= MAX_UNFOLDED_CHARS and len(lines) <= MAX_UNFOLDED_LINES:
40
62
  return text, False
41
63
 
64
+ # A string catalog (i18n messages) is 100% payload: head/tail keeps the
65
+ # boilerplate and drops the middle, while a digest says what is inside.
66
+ try:
67
+ from src.format_parsers.i18n_strings import StringCatalogReducer, sniff
68
+ if sniff(text):
69
+ digest, was_reduced = StringCatalogReducer.reduce(text, "catalog.ts")
70
+ if was_reduced:
71
+ return digest, True
72
+ except Exception:
73
+ pass
74
+
42
75
  hash8, marker = stash_block(text, source=f"mcp:{tool_name}")
43
76
  head = lines[:HEAD_LINES]
44
77
  tail = lines[-TAIL_LINES:]
@@ -56,8 +89,10 @@ def fold_tool_text(text: str, tool_name: str = "mcp_tool") -> Tuple[str, bool]:
56
89
  return folded_res, True
57
90
 
58
91
 
59
- def compact_mcp_response(resp: Dict[str, Any]) -> Dict[str, Any]:
60
- """Inspects an MCP JSON-RPC response and compacts tools/call content blocks."""
92
+ def compact_mcp_response(resp: Dict[str, Any], toolsafe_server: bool = False) -> Dict[str, Any]:
93
+ """Compacts tools/call content blocks, and (for our own server only) trims
94
+ `tools/list` to the declared profile so a host never pays for tool schemas
95
+ the user turned off."""
61
96
  if not isinstance(resp, dict):
62
97
  return resp
63
98
 
@@ -65,34 +100,46 @@ def compact_mcp_response(resp: Dict[str, Any]) -> Dict[str, Any]:
65
100
  if not isinstance(result, dict):
66
101
  return resp
67
102
 
68
- content = result.get("content")
69
- if not isinstance(content, list):
70
- return resp
71
-
72
103
  modified = False
73
- new_content = []
74
- for block in content:
75
- if isinstance(block, dict) and block.get("type") == "text":
76
- raw_text = block.get("text", "")
77
- folded_text, was_folded = fold_tool_text(raw_text)
78
- if was_folded:
79
- new_block = dict(block)
80
- new_block["text"] = folded_text
81
- new_content.append(new_block)
104
+ new_result: Optional[Dict[str, Any]] = None
105
+
106
+ if toolsafe_server and isinstance(result.get("tools"), list):
107
+ profile = os.environ.get("TOKENSAFE_MCP_PROFILE", "").strip().lower()
108
+ if profile != "full":
109
+ kept = _filter_tools_list(result["tools"], profile)
110
+ if len(kept) != len(result["tools"]):
111
+ new_result = dict(result)
112
+ new_result["tools"] = kept
82
113
  modified = True
114
+
115
+ content = result.get("content")
116
+ if isinstance(content, list):
117
+ new_content = []
118
+ content_changed = False
119
+ for block in content:
120
+ if isinstance(block, dict) and block.get("type") == "text":
121
+ raw_text = block.get("text", "")
122
+ folded_text, was_folded = fold_tool_text(raw_text)
123
+ if was_folded:
124
+ new_block = dict(block)
125
+ new_block["text"] = folded_text
126
+ new_content.append(new_block)
127
+ content_changed = True
128
+ else:
129
+ new_content.append(block)
83
130
  else:
84
131
  new_content.append(block)
85
- else:
86
- new_content.append(block)
132
+ if content_changed:
133
+ new_result = dict(new_result or result)
134
+ new_result["content"] = new_content
135
+ modified = True
87
136
 
88
- if modified:
89
- new_resp = dict(resp)
90
- new_result = dict(result)
91
- new_result["content"] = new_content
92
- new_resp["result"] = new_result
93
- return new_resp
137
+ if not modified:
138
+ return resp
94
139
 
95
- return resp
140
+ new_resp = dict(resp)
141
+ new_resp["result"] = new_result
142
+ return new_resp
96
143
 
97
144
 
98
145
  def run_proxy(target_cmd: List[str]):
@@ -100,6 +147,7 @@ def run_proxy(target_cmd: List[str]):
100
147
  if not target_cmd:
101
148
  sys.stderr.write("TokenSafe MCP Proxy Error: No target command specified.\n")
102
149
  sys.exit(1)
150
+ toolsafe_server = _looks_like_tokensafe(target_cmd)
103
151
 
104
152
  try:
105
153
  proc = subprocess.Popen(
@@ -146,7 +194,7 @@ def run_proxy(target_cmd: List[str]):
146
194
  # Parse JSON-RPC line
147
195
  try:
148
196
  msg = json.loads(line_str)
149
- compacted = compact_mcp_response(msg)
197
+ compacted = compact_mcp_response(msg, toolsafe_server=toolsafe_server)
150
198
  out_line = json.dumps(compacted, ensure_ascii=False) + "\n"
151
199
  except Exception:
152
200
  out_line = line_str + "\n"
package/src/mcp_server.py CHANGED
@@ -45,7 +45,7 @@ from src.session_context import current_root, current_session_id
45
45
 
46
46
  SERVER_INFO = {
47
47
  "name": "tokensafe-mcp",
48
- "version": "4.12.1"
48
+ "version": "4.12.2"
49
49
  }
50
50
 
51
51
  # MCP client attribution: the initialize handshake carries clientInfo, which
@@ -900,7 +900,7 @@ TOOLS = [{'name': 'smart_read_file',
900
900
  'also accepted as path'}}}},
901
901
  {'name': 'run_helper',
902
902
  'annotations': {'readOnlyHint': False},
903
- 'description': "Utilities: 'sanitize','guard','diff','deps','web','expand','image','compress'.",
903
+ 'description': "Utilities: 'sanitize','guard','diff','deps','web','expand','image','compress','dict'.",
904
904
  'inputSchema': {'type': 'object',
905
905
  'properties': {'action': {'type': 'string',
906
906
  'enum': ['sanitize',
@@ -910,7 +910,8 @@ TOOLS = [{'name': 'smart_read_file',
910
910
  'web',
911
911
  'expand',
912
912
  'image',
913
- 'compress']},
913
+ 'compress',
914
+ 'dict']},
914
915
  'command': {'type': 'string'},
915
916
  'code': {'type': 'string'},
916
917
  'file_path': {'type': 'string'},
@@ -1992,6 +1993,7 @@ _HELPER_ACTIONS = {
1992
1993
  "expand": "expand_ref",
1993
1994
  "image": "optimize_image",
1994
1995
  "compress": "compress_prompt",
1996
+ "dict": "dict_catalog",
1995
1997
  }
1996
1998
 
1997
1999
 
@@ -2238,6 +2240,28 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
2238
2240
  except Exception:
2239
2241
  pass
2240
2242
 
2243
+ # String catalogs (i18n messages): 100% payload, AST folding cannot help.
2244
+ # A digest + reversible anchor replaces the whole file.
2245
+ from src.format_parsers.i18n_strings import StringCatalogReducer
2246
+ if StringCatalogReducer.is_string_catalog(path):
2247
+ try:
2248
+ with open(path, "r", encoding="utf-8", errors="replace") as f:
2249
+ raw_cat_text = f.read()
2250
+ reduced_cat, was_cat = StringCatalogReducer.reduce(raw_cat_text, path)
2251
+ if was_cat:
2252
+ orig_t = count_tokens(raw_cat_text)
2253
+ opt_t = count_tokens(reduced_cat)
2254
+ tracker.record_event(
2255
+ session_id=_mcp_session_id(),
2256
+ event_type="STRING_CATALOG_REDUCE",
2257
+ original_tokens=orig_t,
2258
+ optimized_tokens=opt_t,
2259
+ details={"file": os.path.basename(path), "saved": orig_t - opt_t}
2260
+ )
2261
+ return {"content": [{"type": "text", "text": reduced_cat}]}
2262
+ except Exception:
2263
+ pass
2264
+
2241
2265
  # Kubernetes manifests (.yaml / .yml with multiple resources):
2242
2266
  if path.lower().endswith((".yaml", ".yml")):
2243
2267
  from src.format_parsers.docker_k8s import ContainerAndK8sReducer
@@ -2728,6 +2752,72 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
2728
2752
  "stats": stats
2729
2753
  }, indent=2, ensure_ascii=False)}]}
2730
2754
 
2755
+ elif name == "dict_catalog":
2756
+ # String-catalog audit (lint/coverage/show/apply): the deterministic
2757
+ # alternative to reading 18 catalog files per locale.
2758
+ import shlex
2759
+ from src import i18n_catalog as _dict
2760
+
2761
+ raw_cmd = str(args.get("command") or args.get("cmd") or "coverage")
2762
+ try:
2763
+ tokens = shlex.split(raw_cmd)
2764
+ except ValueError:
2765
+ tokens = raw_cmd.split()
2766
+ sub = tokens[0] if tokens else "coverage"
2767
+ flags: Dict[str, str] = {}
2768
+ i = 1
2769
+ while i < len(tokens):
2770
+ tok = tokens[i]
2771
+ if tok.startswith("--"):
2772
+ key = tok[2:]
2773
+ if "=" in key:
2774
+ key, val = key.split("=", 1)
2775
+ elif i + 1 < len(tokens) and not tokens[i + 1].startswith("--"):
2776
+ val = tokens[i + 1]
2777
+ i += 1
2778
+ else:
2779
+ val = "1"
2780
+ flags[key.replace("-", "_")] = val
2781
+ i += 1
2782
+ root = str(
2783
+ args.get("cwd") or args.get("root") or args.get("path")
2784
+ or flags.get("root") or os.getcwd()
2785
+ )
2786
+ messages_dir = _dict.resolve_messages_dir(root)
2787
+ if not messages_dir:
2788
+ return _fallback_error(
2789
+ "run_helper",
2790
+ f"dict: no message catalog found under {root} (pass cwd or --root)",
2791
+ )
2792
+ try:
2793
+ text, payload = _dict.run_command(messages_dir, sub, flags)
2794
+ except ValueError as exc:
2795
+ return _fallback_error("run_helper", f"dict: {exc}")
2796
+ except Exception as exc:
2797
+ return _fallback_error("run_helper", f"dict failed: {type(exc).__name__}: {exc}")
2798
+
2799
+ # Measured: the catalog bytes the agent did not have to read.
2800
+ locale = flags.get("locale", "")
2801
+ if sub in ("lint", "coverage") and locale:
2802
+ try:
2803
+ catalog = _dict.load_locale(messages_dir, locale)
2804
+ orig_t = sum(count_tokens(text_part) for text_part in catalog.texts.values())
2805
+ opt_t = count_tokens(text)
2806
+ if orig_t > opt_t:
2807
+ tracker.record_event(
2808
+ session_id=_mcp_session_id(),
2809
+ event_type="STRING_CATALOG_LINT",
2810
+ original_tokens=orig_t,
2811
+ optimized_tokens=opt_t,
2812
+ details={"locale": locale, "command": sub},
2813
+ measurement="estimated",
2814
+ )
2815
+ except Exception:
2816
+ pass
2817
+ if flags.get("json"):
2818
+ return {"content": [{"type": "text", "text": json.dumps(payload, indent=2, ensure_ascii=False)}]}
2819
+ return {"content": [{"type": "text", "text": text}]}
2820
+
2731
2821
  elif name == "sanitize_command":
2732
2822
  cmd = args.get("command") or args.get("cmd") or args.get("c") or ""
2733
2823
  # Step 1: TokenSafe Guard security inspection
package/src/proxy.py CHANGED
@@ -28,7 +28,7 @@ from src.secret_redactor import SecretRedactor
28
28
  from src.graph_engine import GraphEngine
29
29
  from src.cache_normalizer import PromptCacheNormalizer
30
30
  from src.governor import ContextGovernor
31
- from src.result_ledger import fold_tool_results
31
+ from src.result_ledger import fold_catalog_results, fold_tool_results
32
32
  from src.thinking_fold import fold_aged_thinking
33
33
  from src.tool_pruner import _tool_name, apply_subset, detect_prune_miss
34
34
  from src.paths import resolve_data_dir
@@ -77,6 +77,10 @@ BROADCASTER = EventBroadcaster()
77
77
  _CACHE_OBS_MIN_INTERVAL_S = 30.0
78
78
  _last_cache_obs_ts = 0.0
79
79
  _SESSION_CACHE_WARM: Dict[Tuple[str, str], bool] = {}
80
+ # Set when the last response came back fully uncached on a large prompt: the
81
+ # provider's prompt cache expired (idle gap, model switch, restart). The next
82
+ # request then forces the ledger fold so the cold prompt is billed smaller.
83
+ _COLD_CACHE_PENDING: Dict[Tuple[str, str], bool] = {}
80
84
  _CACHE_STATE_LOCK = threading.Lock()
81
85
  _DEEP_REASONING_RE = re.compile(
82
86
  r"\b(architect|architecture|design|plan|audit|security|migrate|migration|investigate|refactor|root\s+cause)\b"
@@ -149,6 +153,33 @@ def _apply_effort_clamp(
149
153
  return None
150
154
 
151
155
 
156
+ STREAM_USAGE_PROVIDERS = frozenset({"openai", "deepseek", "gemini", "generic"})
157
+
158
+
159
+ def _ensure_stream_usage(payload: Dict[str, Any], provider: str) -> bool:
160
+ """Asks a streaming OpenAI-dialect request to end with a usage chunk.
161
+
162
+ Providers omit usage on `stream: true` unless `stream_options.include_usage`
163
+ is set, which leaves the cold-cache detector blind exactly when it matters.
164
+ Anthropic streams carry usage in `message_delta` already, so they are skipped.
165
+ Returns True when the payload was changed.
166
+ """
167
+ if not isinstance(payload, dict) or not payload.get("stream"):
168
+ return False
169
+ if provider not in STREAM_USAGE_PROVIDERS:
170
+ return False
171
+ if os.environ.get("TOKENSAFE_STREAM_USAGE", "1") in ("0", "false", "False"):
172
+ return False
173
+ stream_opts = payload.get("stream_options")
174
+ if not isinstance(stream_opts, dict):
175
+ stream_opts = {}
176
+ if stream_opts.get("include_usage"):
177
+ return False
178
+ stream_opts["include_usage"] = True
179
+ payload["stream_options"] = stream_opts
180
+ return True
181
+
182
+
152
183
  def _record_cache_obs(tracker, provider: str, mutation_kinds: List[str],
153
184
  input_tokens: int, cache_read: int, cache_write: int,
154
185
  model: str = "", output_tokens: int = 0,
@@ -1214,6 +1245,9 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
1214
1245
  cache_state_key = (_key_fingerprint(incoming_key or resolved_key), active_model)
1215
1246
  with _CACHE_STATE_LOCK:
1216
1247
  session_cache_warm = _SESSION_CACHE_WARM.get(cache_state_key)
1248
+ cold_restart = _COLD_CACHE_PENDING.pop(cache_state_key, False)
1249
+ if cold_restart:
1250
+ print("[TokenSafe] Cold prompt cache detected — forcing a history fold to shrink the uncached bill.")
1217
1251
 
1218
1252
  # 1.5 Tool Result Ledger: fold aged, oversized tool results into compact
1219
1253
  # anchors + local archive (idempotent via marker; cache-aware ROI gate).
@@ -1224,6 +1258,7 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
1224
1258
  model=active_model,
1225
1259
  provider=provider,
1226
1260
  cache_warm=session_cache_warm,
1261
+ force_fold=cold_restart,
1227
1262
  )
1228
1263
  payload["messages"] = messages
1229
1264
  if ledger_stats.get("folded"):
@@ -1234,6 +1269,22 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
1234
1269
  except Exception:
1235
1270
  pass
1236
1271
 
1272
+ # 1.55 String Catalog Policy: a tool result that is an i18n catalog is
1273
+ # replaced by a digest immediately, regardless of age. This is the
1274
+ # only stage that sees native host reads (read_file), so it runs
1275
+ # even when the license quota is exhausted — it lowers the bill.
1276
+ if messages:
1277
+ try:
1278
+ messages, catalog_stats = fold_catalog_results(messages)
1279
+ payload["messages"] = messages
1280
+ if catalog_stats.get("folded"):
1281
+ print(
1282
+ f"[TokenSafe] String catalogs: folded {catalog_stats['folded']} result(s), "
1283
+ f"~{catalog_stats['saved_tokens']} input tokens lighter."
1284
+ )
1285
+ except Exception:
1286
+ pass
1287
+
1237
1288
  # 1.6 Aged Thinking Fold (enabled by default; opt-out TOKENSAFE_FOLD_THINKING=0):
1238
1289
  # collapse extended-thinking payloads of aged assistant turns into
1239
1290
  # one-line stubs, gated by the same cache-break ROI check.
@@ -1416,6 +1467,11 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
1416
1467
  headers=headers
1417
1468
  )
1418
1469
 
1470
+ # Ask OpenAI-dialect providers to emit the trailing usage chunk; without
1471
+ # it a streaming session reports no input/cache numbers at all, and the
1472
+ # cold-cache detector below stays blind.
1473
+ _ensure_stream_usage(payload, provider)
1474
+
1419
1475
  is_stream = bool(payload.get("stream"))
1420
1476
  req_timeout = 120.0 if is_stream else 30.0
1421
1477
  try:
@@ -1442,7 +1498,10 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
1442
1498
  reader = getattr(resp, "read1", None) or resp.read
1443
1499
  # Best-effort usage capture from the stream tail: Anthropic
1444
1500
  # reports final usage in the trailing message_delta events.
1445
- sse_tail = bytearray() if sse_t is not None else None
1501
+ # Bounded tail capture runs for every dialect: with
1502
+ # stream_options.include_usage the final OpenAI chunk (or
1503
+ # the trailing Anthropic message_delta) carries the usage.
1504
+ sse_tail = bytearray()
1446
1505
  while True:
1447
1506
  try:
1448
1507
  chunk = reader(4096)
@@ -1476,10 +1535,13 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
1476
1535
  if sse_t is not None and sse_tail:
1477
1536
  tail_text = sse_tail.decode("utf-8", "replace")
1478
1537
  m_usage = re.search(
1479
- r'"usage":\s*\{[^}]*"(?:cache_read_input_tokens|input_tokens)":\s*(\d+)',
1538
+ r'"usage":\s*\{[^}]*"(?:cache_read_input_tokens|input_tokens|prompt_tokens)":\s*(\d+)',
1539
+ tail_text,
1540
+ )
1541
+ m_cached = re.search(
1542
+ r'"(?:cached_tokens|cache_read_input_tokens|prompt_cache_hit_tokens)":\s*(\d+)',
1480
1543
  tail_text,
1481
1544
  )
1482
- m_cached = re.search(r'"cache_read_input_tokens":\s*(\d+)', tail_text)
1483
1545
  if m_cached:
1484
1546
  BROADCASTER.publish("cache_stats", {"provider": provider, "cached_tokens": int(m_cached.group(1))})
1485
1547
  elif m_usage:
@@ -1488,14 +1550,16 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
1488
1550
  # input/cache fields live in message_start, which the
1489
1551
  # 64KB tail may evict on very long streams — record
1490
1552
  # only when at least one real field survived.
1491
- m_in = re.search(r'"input_tokens":\s*(\d+)', tail_text)
1492
- m_out = re.search(r'"output_tokens":\s*(\d+)', tail_text)
1553
+ m_in = re.search(r'"(?:prompt_tokens|input_tokens)":\s*(\d+)', tail_text)
1554
+ m_out = re.search(r'"(?:completion_tokens|output_tokens)":\s*(\d+)', tail_text)
1493
1555
  m_cw = re.search(r'"cache_creation_input_tokens":\s*(\d+)', tail_text)
1494
1556
  sse_input = int(m_in.group(1)) if m_in else 0
1495
1557
  sse_cached = int(m_cached.group(1)) if m_cached else 0
1496
1558
  sse_out = int(m_out.group(1)) if m_out else 0
1497
1559
  with _CACHE_STATE_LOCK:
1498
1560
  _SESSION_CACHE_WARM[cache_state_key] = bool(sse_cached > 0)
1561
+ if sse_input >= 50000 and sse_cached == 0:
1562
+ _COLD_CACHE_PENDING[cache_state_key] = True
1499
1563
  if m_cached or sse_input > 0:
1500
1564
  _record_cache_obs(
1501
1565
  proxy_tracker, provider, mutation_kinds,
@@ -1547,6 +1611,8 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
1547
1611
  out_tok_obs = int(usage.get("completion_tokens") or usage.get("output_tokens") or 0)
1548
1612
  with _CACHE_STATE_LOCK:
1549
1613
  _SESSION_CACHE_WARM[cache_state_key] = bool(int(cached or 0) > 0)
1614
+ if in_tok_obs >= 50000 and int(cached or 0) == 0:
1615
+ _COLD_CACHE_PENDING[cache_state_key] = True
1550
1616
  _record_cache_obs(
1551
1617
  proxy_tracker, provider, mutation_kinds,
1552
1618
  in_tok_obs,
@@ -98,6 +98,15 @@ def _compact_read_result(text: str, path: str) -> Optional[str]:
98
98
  except Exception:
99
99
  pass
100
100
 
101
+ try:
102
+ from src.format_parsers.i18n_strings import StringCatalogReducer
103
+ if StringCatalogReducer.is_string_catalog(path):
104
+ compacted_c, was_c = StringCatalogReducer.reduce(text, path)
105
+ if was_c:
106
+ return compacted_c
107
+ except Exception:
108
+ pass
109
+
101
110
  ext = os.path.splitext(path or "")[1].lower() or None
102
111
  candidates: List[str] = []
103
112
  lines = text.splitlines()
@@ -121,6 +130,93 @@ def _compact_read_result(text: str, path: str) -> Optional[str]:
121
130
  return min(candidates, key=count_tokens)
122
131
 
123
132
 
133
+ def _message_text(msg: Dict[str, Any]) -> str:
134
+ """Text of a tool message, whether content is a string or a block list."""
135
+ content = msg.get("content")
136
+ if isinstance(content, str):
137
+ return content
138
+ if isinstance(content, list):
139
+ parts = [
140
+ block.get("text", "") for block in content
141
+ if isinstance(block, dict) and isinstance(block.get("text"), str)
142
+ ]
143
+ return "\n".join(p for p in parts if p)
144
+ return ""
145
+
146
+
147
+ def fold_catalog_results(
148
+ messages: List[Dict[str, Any]],
149
+ session_id: str = "proxy_session",
150
+ record_metrics: bool = True,
151
+ ) -> Tuple[List[Dict[str, Any]], Dict[str, Any]]:
152
+ """Replaces i18n catalog tool results with a digest, regardless of age.
153
+
154
+ `fold_tool_results` protects the recent tail and results under the token
155
+ floor because a fresh read may still be needed verbatim. A string catalog
156
+ is the opposite case: once the model has looked at it, no later turn needs
157
+ it verbatim, and holding 18 of them per locale is what turns one review
158
+ pass into millions of input tokens. This stage is therefore age-blind,
159
+ path-aware when the host passes a path, and idempotent by marker.
160
+ """
161
+ from src.format_parsers.i18n_strings import StringCatalogReducer, sniff
162
+
163
+ stats: Dict[str, Any] = {"folded": 0, "orig_tokens": 0, "new_tokens": 0, "saved_tokens": 0}
164
+ if not messages or not _env_flag("TOKENSAFE_TOOL_LEDGER"):
165
+ return messages, stats
166
+ if not _env_flag("TOKENSAFE_CATALOG_FOLD"):
167
+ return messages, stats
168
+
169
+ call_paths: Dict[str, str] = {}
170
+ for msg in messages:
171
+ if isinstance(msg, dict) and msg.get("role") == "assistant":
172
+ for call_id, _name, args in _assistant_tool_calls(msg):
173
+ for key in _PATH_KEYS:
174
+ value = args.get(key)
175
+ if isinstance(value, str) and value:
176
+ call_paths[call_id] = value
177
+ break
178
+
179
+ for msg in messages:
180
+ if not isinstance(msg, dict) or msg.get("role") != "tool":
181
+ continue
182
+ text = _message_text(msg)
183
+ if not text or FOLD_MARKER in text or "[TokenSafe Catalog Digest" in text:
184
+ continue
185
+ if len(text) < 500:
186
+ continue
187
+ path = call_paths.get(str(msg.get("tool_call_id") or msg.get("id") or ""), "")
188
+ if not (path and StringCatalogReducer.is_string_catalog(path)):
189
+ if not sniff(text):
190
+ continue
191
+ reduced, was_reduced = StringCatalogReducer.reduce(text, path or "catalog.ts")
192
+ if not was_reduced:
193
+ continue
194
+ orig_tokens = count_tokens(text)
195
+ new_tokens = count_tokens(reduced)
196
+ if new_tokens >= orig_tokens:
197
+ continue
198
+ _set_result_text(msg, reduced)
199
+ stats["folded"] += 1
200
+ stats["orig_tokens"] += orig_tokens
201
+ stats["new_tokens"] += new_tokens
202
+ stats["saved_tokens"] += max(0, orig_tokens - new_tokens)
203
+
204
+ if stats["folded"] and record_metrics:
205
+ try:
206
+ from src.metrics import MetricsTracker
207
+ MetricsTracker().record_event(
208
+ session_id=session_id,
209
+ event_type="CATALOG_FOLD",
210
+ original_tokens=stats["orig_tokens"],
211
+ optimized_tokens=stats["new_tokens"],
212
+ details={"folded": stats["folded"]},
213
+ measurement="measured",
214
+ )
215
+ except Exception:
216
+ pass
217
+ return messages, stats
218
+
219
+
124
220
  def _compact_command_result(text: str) -> Optional[str]:
125
221
  """Test summaries first (PASS: ...), build/docker/log compaction next, log-style head/tail otherwise."""
126
222
  try:
@@ -332,6 +332,18 @@ def build_workspace_brief(
332
332
  if hints:
333
333
  lines.append("- " + "; ".join(hints))
334
334
 
335
+ # String catalogs: only mention `dict` where a catalog actually exists, so
336
+ # projects without i18n never pay for the line.
337
+ try:
338
+ from src.i18n_catalog import resolve_messages_dir
339
+ if resolve_messages_dir(workspace):
340
+ lines.append(
341
+ "- string catalogs: review and patch via `tokensafe dict lint --locale <l>` then "
342
+ "`dict apply` — never read whole messages/*/*.ts files (smart_read_file returns a digest)"
343
+ )
344
+ except Exception:
345
+ pass
346
+
335
347
  brief = "\n".join(lines)
336
348
  if len(brief) > max_chars:
337
349
  # Cut on a line boundary: a half-written path in a truncated root line
@@ -311,7 +311,7 @@ class TelemetrySync:
311
311
  current_last_id = last_id
312
312
  headers = {
313
313
  "Content-Type": "application/json",
314
- "User-Agent": "TokenSafe-Sync/4.12.1"
314
+ "User-Agent": "TokenSafe-Sync/4.12.2"
315
315
  }
316
316
  if active_key:
317
317
  headers["Authorization"] = f"Bearer {active_key}"
@@ -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.12.1"
20
+ CURRENT_VERSION = "4.12.2"
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