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.
@@ -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.3"
315
315
  }
316
316
  if active_key:
317
317
  headers["Authorization"] = f"Bearer {active_key}"
@@ -0,0 +1,347 @@
1
+ """
2
+ Codex CLI MCP config editor (TOML).
3
+
4
+ Codex keeps its MCP servers in `~/.codex/config.toml`, so the JSON manager
5
+ cannot wrap them. A general TOML serializer is the wrong tool here: it would
6
+ reformat a hand-edited file (comments, ordering, inline tables) and turn a
7
+ one-line change into an unreviewable diff.
8
+
9
+ This module edits by splice instead. It locates `[mcp_servers.<name>]`, parses
10
+ just the `command`/`args` values it needs, and rewrites those lines only. The
11
+ original definition is preserved in a `# tokensafe:orig {json}` comment inside
12
+ the table, so `unwrap` restores byte-identical content while remaining readable
13
+ to a human (and ignored by Codex's parser).
14
+
15
+ One documented limit: an `args` array spread over several lines is collapsed to
16
+ one line when wrapped, and unwrap restores the same values in that single-line
17
+ form — semantically identical, not byte-identical. The usual single-line form,
18
+ which is what Codex's own docs show, round-trips exactly.
19
+
20
+ Python's stdlib has `tomllib` for reading only, and only from 3.11; the project
21
+ supports 3.10, so the small subset parser below is the primary path. Tests
22
+ cross-check it against `tomllib` whenever the interpreter has one.
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ import json
28
+ import os
29
+ import re
30
+ from dataclasses import dataclass
31
+ from typing import Any, Dict, List, Optional, Sequence, Tuple
32
+
33
+ MARKER_PREFIX = "# tokensafe:orig "
34
+ _TABLE_RE = re.compile(r"^\s*\[(?!\[)(?P<path>.+?)\]\s*(?:#.*)?$")
35
+ _KEY_RE = re.compile(r"^\s*(?P<key>[A-Za-z_][\w-]*)\s*=\s*(?P<value>.*)$")
36
+ _STRING_TOKEN_RE = re.compile(r'"(?:[^"\\]|\\.)*"|\'[^\']*\'')
37
+
38
+
39
+ @dataclass
40
+ class TomlSection:
41
+ path: Tuple[str, ...]
42
+ header_index: int # line index of the `[table]` header
43
+ body_start: int # first line after the header
44
+ body_end: int # exclusive
45
+
46
+
47
+ class TomlServerError(ValueError):
48
+ """Raised when the file cannot be edited safely."""
49
+
50
+
51
+ # ---------------------------------------------------------------------------
52
+ # Subset parsing
53
+ # ---------------------------------------------------------------------------
54
+
55
+ def _unquote(token: str) -> str:
56
+ token = token.strip()
57
+ if len(token) >= 2 and token[0] == token[-1] and token[0] in ("'", '"'):
58
+ inner = token[1:-1]
59
+ if token[0] == "'":
60
+ return inner
61
+ try:
62
+ return json.loads(f'"{inner}"')
63
+ except Exception:
64
+ return inner
65
+ return token
66
+
67
+
68
+ def _split_table_path(raw: str) -> Tuple[str, ...]:
69
+ """`mcp_servers."my server"` -> ("mcp_servers", "my server")."""
70
+ parts: List[str] = []
71
+ current: List[str] = []
72
+ quote: Optional[str] = None
73
+ for ch in raw:
74
+ if quote:
75
+ current.append(ch)
76
+ if ch == quote:
77
+ quote = None
78
+ elif ch in ('"', "'"):
79
+ quote = ch
80
+ current.append(ch)
81
+ elif ch == ".":
82
+ parts.append(_unquote("".join(current)))
83
+ current = []
84
+ else:
85
+ current.append(ch)
86
+ tail = _unquote("".join(current))
87
+ if tail:
88
+ parts.append(tail)
89
+ return tuple(parts)
90
+
91
+
92
+ def iter_sections(text: str) -> List[TomlSection]:
93
+ lines = text.splitlines()
94
+ headers: List[Tuple[int, Tuple[str, ...]]] = []
95
+ for idx, line in enumerate(lines):
96
+ match = _TABLE_RE.match(line)
97
+ if match:
98
+ headers.append((idx, _split_table_path(match.group("path"))))
99
+ sections: List[TomlSection] = []
100
+ for pos, (idx, path) in enumerate(headers):
101
+ end = headers[pos + 1][0] if pos + 1 < len(headers) else len(lines)
102
+ sections.append(TomlSection(path=path, header_index=idx, body_start=idx + 1, body_end=end))
103
+ return sections
104
+
105
+
106
+ def find_section(text: str, server_name: str) -> Optional[TomlSection]:
107
+ for section in iter_sections(text):
108
+ if len(section.path) == 2 and section.path[0] == "mcp_servers" and section.path[1] == server_name:
109
+ return section
110
+ return None
111
+
112
+
113
+ def _scan_value(lines: Sequence[str], start: int, end: int) -> Optional[Tuple[str, int]]:
114
+ """Returns (raw literal text, last line index) for a possibly multi-line value."""
115
+ if start >= end:
116
+ return None
117
+ match = _KEY_RE.match(lines[start])
118
+ if not match:
119
+ return None
120
+ first = match.group("value")
121
+ stripped = first.strip()
122
+ if not stripped:
123
+ return None
124
+ if not stripped.startswith("["):
125
+ return stripped, start
126
+ # Array: accumulate until brackets balance outside strings.
127
+ depth = 0
128
+ quote: Optional[str] = None
129
+ for idx in range(start, end):
130
+ chunk = lines[idx] if idx > start else first
131
+ for ch in chunk:
132
+ if quote:
133
+ if ch == quote:
134
+ quote = None
135
+ elif ch in ('"', "'"):
136
+ quote = ch
137
+ elif ch == "[":
138
+ depth += 1
139
+ elif ch == "]":
140
+ depth -= 1
141
+ if depth <= 0:
142
+ return " ".join(l.strip() for l in lines[start:idx + 1]).split("=", 1)[1].strip(), idx
143
+ return None
144
+
145
+
146
+ def _parse_string_array(raw: str) -> List[str]:
147
+ tokens = _STRING_TOKEN_RE.findall(raw)
148
+ remainder = _STRING_TOKEN_RE.sub("", raw).replace("[", "").replace("]", "").replace(",", "")
149
+ if remainder.strip():
150
+ raise TomlServerError(
151
+ f"args holds non-string elements ({remainder.strip()!r}); wrap this server by hand"
152
+ )
153
+ return [_unquote(token) for token in tokens]
154
+
155
+
156
+ def _parse_string(raw: str) -> str:
157
+ raw = raw.strip()
158
+ if raw[:1] not in ('"', "'"):
159
+ raise TomlServerError(f"expected a quoted string, got {raw[:40]!r}")
160
+ return _unquote(raw)
161
+
162
+
163
+ def _find_key(lines: Sequence[str], section: TomlSection, key: str) -> Optional[Tuple[int, int, str]]:
164
+ """Returns (first_line, last_line, raw_value) for `key = value` in the section."""
165
+ for idx in range(section.body_start, section.body_end):
166
+ if lines[idx].lstrip().startswith(MARKER_PREFIX):
167
+ continue
168
+ match = _KEY_RE.match(lines[idx])
169
+ if not match or match.group("key") != key:
170
+ continue
171
+ scanned = _scan_value(lines, idx, section.body_end)
172
+ if scanned is None:
173
+ return None
174
+ raw, last = scanned
175
+ return idx, last, raw
176
+ return None
177
+
178
+
179
+ def list_servers(text: str) -> List[Dict[str, Any]]:
180
+ """Server entries of `[mcp_servers.*]` tables with their wrap state."""
181
+ lines = text.splitlines()
182
+ found: List[Dict[str, Any]] = []
183
+ for section in iter_sections(text):
184
+ if len(section.path) != 2 or section.path[0] != "mcp_servers":
185
+ continue
186
+ name = section.path[1]
187
+ orig: Optional[Dict[str, Any]] = None
188
+ for idx in range(section.body_start, section.body_end):
189
+ line = lines[idx]
190
+ if line.lstrip().startswith(MARKER_PREFIX):
191
+ try:
192
+ orig = json.loads(line.lstrip()[len(MARKER_PREFIX):])
193
+ except Exception:
194
+ orig = None
195
+ break
196
+ command_loc = _find_key(lines, section, "command")
197
+ args_loc = _find_key(lines, section, "args")
198
+ try:
199
+ command = _parse_string(command_loc[2]) if command_loc else ""
200
+ args = _parse_string_array(args_loc[2]) if args_loc else []
201
+ except TomlServerError:
202
+ command, args = "", []
203
+ found.append({
204
+ "agent": "Codex CLI",
205
+ "server_name": name,
206
+ "command": command,
207
+ "args": args,
208
+ "is_wrapped": orig is not None,
209
+ "orig_def": orig,
210
+ })
211
+ return found
212
+
213
+
214
+ # ---------------------------------------------------------------------------
215
+ # Editing
216
+ # ---------------------------------------------------------------------------
217
+
218
+ def _toml_string(value: str) -> str:
219
+ """A TOML basic string. json.dumps produces an accepted subset."""
220
+ return json.dumps(str(value), ensure_ascii=False)
221
+
222
+
223
+ def _toml_string_array(values: Sequence[str]) -> str:
224
+ return "[" + ", ".join(_toml_string(v) for v in values) + "]"
225
+
226
+
227
+ def _replace_lines(lines: List[str], replacements: List[Tuple[int, int, str]]) -> List[str]:
228
+ """Applies (first, last_inclusive, new_text) from the bottom up."""
229
+ out = list(lines)
230
+ for first, last, new_text in sorted(replacements, key=lambda r: r[0], reverse=True):
231
+ out[first:last + 1] = new_text.splitlines()
232
+ return out
233
+
234
+
235
+ def wrap_server_text(
236
+ text: str,
237
+ server_name: str,
238
+ proxy_cmd: str,
239
+ proxy_args: Sequence[str],
240
+ ) -> str:
241
+ """Rewrites one server to route through `tokensafe mcp-proxy`."""
242
+ section = find_section(text, server_name)
243
+ if section is None:
244
+ raise TomlServerError(f"no [mcp_servers.{server_name}] table in this file")
245
+ lines = text.splitlines()
246
+ if any(lines[idx].lstrip().startswith(MARKER_PREFIX)
247
+ for idx in range(section.body_start, section.body_end)):
248
+ raise TomlServerError(f"server {server_name!r} is already wrapped")
249
+
250
+ command_loc = _find_key(lines, section, "command")
251
+ if command_loc is None:
252
+ raise TomlServerError(f"server {server_name!r} has no command key")
253
+ args_loc = _find_key(lines, section, "args")
254
+
255
+ original = {
256
+ "command": _parse_string(command_loc[2]),
257
+ "args": _parse_string_array(args_loc[2]) if args_loc else [],
258
+ # Remembered so unwrap restores a server that never had `args`
259
+ # instead of leaving a synthetic `args = []` behind.
260
+ "args_present": args_loc is not None,
261
+ }
262
+ marker = MARKER_PREFIX + json.dumps(original, ensure_ascii=False)
263
+
264
+ new_command = f"command = {_toml_string(proxy_cmd)}"
265
+ new_args = f"args = {_toml_string_array(proxy_args)}"
266
+ if args_loc:
267
+ replacements: List[Tuple[int, int, str]] = [
268
+ (command_loc[0], command_loc[1], new_command),
269
+ (args_loc[0], args_loc[1], new_args),
270
+ ]
271
+ else:
272
+ # No args key yet: emit both lines in one replacement so the two edits
273
+ # cannot overwrite each other.
274
+ replacements = [(command_loc[0], command_loc[1], new_command + "\n" + new_args)]
275
+ lines = _replace_lines(lines, replacements)
276
+ lines.insert(section.header_index + 1, marker)
277
+ return "\n".join(lines) + ("\n" if text.endswith("\n") else "")
278
+
279
+
280
+ def unwrap_server_text(text: str, server_name: str) -> str:
281
+ """Restores `command`/`args` from the marker and drops it."""
282
+ section = find_section(text, server_name)
283
+ if section is None:
284
+ raise TomlServerError(f"no [mcp_servers.{server_name}] table in this file")
285
+ lines = text.splitlines()
286
+ marker_index: Optional[int] = None
287
+ original: Optional[Dict[str, Any]] = None
288
+ for idx in range(section.body_start, section.body_end):
289
+ stripped = lines[idx].lstrip()
290
+ if stripped.startswith(MARKER_PREFIX):
291
+ marker_index = idx
292
+ try:
293
+ original = json.loads(stripped[len(MARKER_PREFIX):])
294
+ except Exception as exc:
295
+ raise TomlServerError(f"unreadable TokenSafe marker on line {idx + 1}: {exc}")
296
+ break
297
+ if marker_index is None or not isinstance(original, dict) or "command" not in original:
298
+ raise TomlServerError(f"server {server_name!r} is not wrapped by TokenSafe")
299
+
300
+ command_loc = _find_key(lines, section, "command")
301
+ args_loc = _find_key(lines, section, "args")
302
+ if command_loc is None:
303
+ raise TomlServerError(f"server {server_name!r} lost its command key while wrapped")
304
+
305
+ new_command = f"command = {_toml_string(original['command'])}"
306
+ new_args = f"args = {_toml_string_array(original.get('args') or [])}"
307
+ if args_loc and not original.get("args_present", True):
308
+ # The server had no args key before wrapping: drop the synthetic line.
309
+ replacements: List[Tuple[int, int, str]] = [
310
+ (command_loc[0], command_loc[1], new_command),
311
+ (args_loc[0], args_loc[1], ""),
312
+ ]
313
+ elif args_loc:
314
+ replacements = [
315
+ (command_loc[0], command_loc[1], new_command),
316
+ (args_loc[0], args_loc[1], new_args),
317
+ ]
318
+ else:
319
+ replacements = [(command_loc[0], command_loc[1], new_command + "\n" + new_args)]
320
+ lines = _replace_lines(lines, replacements)
321
+ # The marker moved if it sat above the replaced lines.
322
+ for idx in range(len(lines)):
323
+ if lines[idx].lstrip().startswith(MARKER_PREFIX):
324
+ del lines[idx]
325
+ break
326
+ return "\n".join(lines) + ("\n" if text.endswith("\n") else "")
327
+
328
+
329
+ def read_text(path: str) -> str:
330
+ with open(path, "r", encoding="utf-8") as handle:
331
+ return handle.read()
332
+
333
+
334
+ def write_text(path: str, text: str) -> None:
335
+ """Atomic write with a one-time `.bak.tokensafe` backup."""
336
+ backup = f"{path}.bak.tokensafe"
337
+ if not os.path.exists(backup):
338
+ with open(backup, "w", encoding="utf-8") as handle:
339
+ handle.write(read_text(path))
340
+ tmp = f"{path}.tmp.{os.getpid()}"
341
+ with open(tmp, "w", encoding="utf-8") as handle:
342
+ handle.write(text)
343
+ os.replace(tmp, path)
344
+
345
+
346
+ def is_toml_path(path: str) -> bool:
347
+ return str(path).lower().endswith(".toml")
@@ -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.3"
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