tokensafe 4.12.1 → 4.12.3

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,24 +2,54 @@
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, Windsurf, Codex, 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 stores its servers in `~/.codex/config.toml`, so it goes through
10
+ `src/toml_mcp_config.py`: a splice editor that touches only the two keys it must
11
+ and keeps the original definition in a `# tokensafe:orig {json}` comment inside
12
+ the table. Hand-written comments, ordering and other tables stay byte-identical.
7
13
  """
8
14
 
9
15
  import os
10
16
  import sys
11
17
  import json
12
18
  import shutil
13
- from typing import Dict, Any, List, Optional, Tuple
19
+ from typing import Dict, Any, List, Optional, Sequence, Tuple
20
+
21
+ from src import toml_mcp_config as toml_mcp
14
22
 
15
23
  HOME = os.path.expanduser("~")
16
24
 
25
+
26
+ def _vscode_user_dir() -> str:
27
+ """VS Code's per-user directory, where extension MCP configs live."""
28
+ if sys.platform == "darwin":
29
+ return os.path.join(HOME, "Library", "Application Support", "Code", "User")
30
+ if sys.platform == "win32":
31
+ appdata = os.environ.get("APPDATA") or os.path.join(HOME, "AppData", "Roaming")
32
+ return os.path.join(appdata, "Code", "User")
33
+ return os.path.join(os.environ.get("XDG_CONFIG_HOME") or os.path.join(HOME, ".config"), "Code", "User")
34
+
35
+
17
36
  CONFIG_CANDIDATES = [
18
37
  ("Claude Code / Desktop", os.path.join(HOME, ".claude.json")),
19
38
  ("Claude Settings", os.path.join(HOME, ".claude", "settings.json")),
20
39
  ("Cursor Global", os.path.join(HOME, ".cursor", "mcp.json")),
21
40
  ("Codex Global", os.path.join(HOME, ".codex", "config.json")),
41
+ ("Codex CLI (TOML)", os.path.join(HOME, ".codex", "config.toml")),
22
42
  ("Windsurf Global", os.path.join(HOME, ".codeium", "windsurf", "mcp_config.json")),
43
+ ("Antigravity", os.path.join(HOME, ".gemini", "config", "mcp_config.json")),
44
+ ("ZCode", os.path.join(HOME, ".zcode", "cli", "config.json")),
45
+ ("Copilot", os.path.join(HOME, ".copilot", "mcp-config.json")),
46
+ ("Kimi Code", os.path.join(HOME, ".kimi-code", "mcp.json")),
47
+ ("Cline (VS Code)", os.path.join(
48
+ _vscode_user_dir(), "globalStorage", "saoudrizwan.claude-dev",
49
+ "settings", "cline_mcp_settings.json")),
50
+ ("Roo Code (VS Code)", os.path.join(
51
+ _vscode_user_dir(), "globalStorage", "rooveterinaryinc.roo-cline",
52
+ "settings", "mcp_settings.json")),
23
53
  ]
24
54
 
25
55
 
@@ -65,6 +95,17 @@ class MCPConfigManager:
65
95
  """Lists all registered MCP servers and their wrapping status."""
66
96
  results = []
67
97
  for agent_name, path in cls.get_existing_configs():
98
+ if toml_mcp.is_toml_path(path):
99
+ try:
100
+ for entry in toml_mcp.list_servers(toml_mcp.read_text(path)):
101
+ if entry["server_name"] in ("tokensafe", "tokensafe-mcp", "tokensafe-cloud"):
102
+ continue
103
+ entry["config_path"] = path
104
+ results.append(entry)
105
+ except Exception:
106
+ continue
107
+ continue
108
+
68
109
  data = cls._read_config(path)
69
110
  if not data:
70
111
  continue
@@ -99,9 +140,49 @@ class MCPConfigManager:
99
140
  })
100
141
  return results
101
142
 
143
+ @classmethod
144
+ def _proxy_command(cls, orig_cmd: str, orig_args: Sequence[str]) -> Tuple[str, List[str]]:
145
+ """The `tokensafe mcp-proxy -- <cmd>` invocation for this machine."""
146
+ tokensafe_bin = shutil.which("tokensafe")
147
+ if tokensafe_bin:
148
+ return tokensafe_bin, ["mcp-proxy", "--", orig_cmd] + list(orig_args)
149
+ script_dir = os.path.dirname(os.path.realpath(__file__))
150
+ cli_path = os.path.join(script_dir, "cli.py")
151
+ return sys.executable, [cli_path, "mcp-proxy", "--", orig_cmd] + list(orig_args)
152
+
153
+ @classmethod
154
+ def _wrap_toml_server(cls, config_path: str, server_name: str) -> bool:
155
+ try:
156
+ text = toml_mcp.read_text(config_path)
157
+ entry = next(
158
+ (s for s in toml_mcp.list_servers(text) if s["server_name"] == server_name),
159
+ None,
160
+ )
161
+ if not entry or not entry["command"]:
162
+ return False
163
+ proxy_cmd, proxy_args = cls._proxy_command(entry["command"], entry["args"])
164
+ new_text = toml_mcp.wrap_server_text(text, server_name, proxy_cmd, proxy_args)
165
+ toml_mcp.write_text(config_path, new_text)
166
+ return True
167
+ except Exception:
168
+ return False
169
+
170
+ @classmethod
171
+ def _unwrap_toml_server(cls, config_path: str, server_name: str) -> bool:
172
+ try:
173
+ text = toml_mcp.read_text(config_path)
174
+ new_text = toml_mcp.unwrap_server_text(text, server_name)
175
+ toml_mcp.write_text(config_path, new_text)
176
+ return True
177
+ except Exception:
178
+ return False
179
+
102
180
  @classmethod
103
181
  def wrap_server(cls, config_path: str, server_name: str) -> bool:
104
182
  """Wraps a specific server in config_path to route through tokensafe mcp-proxy."""
183
+ if toml_mcp.is_toml_path(config_path):
184
+ return cls._wrap_toml_server(config_path, server_name)
185
+
105
186
  data = cls._read_config(config_path)
106
187
  if not data:
107
188
  return False
@@ -129,18 +210,7 @@ class MCPConfigManager:
129
210
  "args": list(orig_args)
130
211
  }
131
212
 
132
- # Resolve tokensafe CLI binary path or python entrypoint
133
- tokensafe_bin = shutil.which("tokensafe")
134
- if tokensafe_bin:
135
- proxy_cmd = tokensafe_bin
136
- proxy_args = ["mcp-proxy", "--", orig_cmd] + list(orig_args)
137
- else:
138
- proxy_cmd = sys.executable
139
- # Find cli.py path
140
- script_dir = os.path.dirname(os.path.realpath(__file__))
141
- cli_path = os.path.join(script_dir, "cli.py")
142
- proxy_args = [cli_path, "mcp-proxy", "--", orig_cmd] + list(orig_args)
143
-
213
+ proxy_cmd, proxy_args = cls._proxy_command(orig_cmd, list(orig_args))
144
214
  s_def["command"] = proxy_cmd
145
215
  s_def["args"] = proxy_args
146
216
 
@@ -149,6 +219,9 @@ class MCPConfigManager:
149
219
  @classmethod
150
220
  def unwrap_server(cls, config_path: str, server_name: str) -> bool:
151
221
  """Restores original command and args for a wrapped server."""
222
+ if toml_mcp.is_toml_path(config_path):
223
+ return cls._unwrap_toml_server(config_path, server_name)
224
+
152
225
  data = cls._read_config(config_path)
153
226
  if not data:
154
227
  return False
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.3"
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,