tokensafe 2.8.4 → 3.0.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.
@@ -0,0 +1,314 @@
1
+ """
2
+ TokenSafe Tool Result Ledger (proxy-stage, v3.0.0).
3
+
4
+ After an LLM has CONSUMED a tool result, that result keeps burning input tokens
5
+ on every subsequent request — in long sessions old tool results are 50-70% of
6
+ the messages mass. The Ledger replaces aged, oversized tool results with a
7
+ compact summary + a deterministic re-hydration anchor, and archives the
8
+ original to disk so nothing is lost.
9
+
10
+ Design invariants:
11
+ - Stateless across requests: a folded result is recognized by its marker, so
12
+ the fold is idempotent and survives proxy restarts without session state.
13
+ - Cache-aware: an anchor is byte-deterministic (no timestamps/counters), so a
14
+ folded prefix stays KV-cache stable; each result is folded exactly once.
15
+ - Quality-safe: only results older than the recent tail and above a token
16
+ floor are folded; originals are archived locally; anchors point back to the
17
+ exact re-run / re-read command.
18
+
19
+ Applies to the OpenAI chat shape (role:"tool" messages paired with
20
+ assistant.tool_calls) — the only shape the proxy ingests on
21
+ /v1/chat/completions. Runs BEFORE ContextGovernor so the governor sees the
22
+ already-lightened mass.
23
+ """
24
+
25
+ import hashlib
26
+ import json
27
+ import os
28
+ import re
29
+ from typing import Any, Dict, List, Optional, Tuple
30
+
31
+ from src.tokenizer import count_tokens
32
+
33
+ # Deterministic marker used both for idempotence detection and as the model-
34
+ # visible anchor header. No timestamps, no hit counters (KV-cache stability).
35
+ FOLD_MARKER = "[TokenSafe Ledger:"
36
+ ARCHIVE_DIRNAME = "tool_ledger"
37
+ MAX_ARCHIVE_CHARS = 256 * 1024 # refuse to archive oversized artifacts
38
+ HEAD_LINES = 12
39
+ TAIL_LINES = 12
40
+
41
+ # Tool classification reused from the history compactor (same vocabulary the
42
+ # whole product uses for read/edit/command tools).
43
+ from src.history_compactor import _COMMAND_TOOLS, _READ_TOOLS # noqa: E402
44
+ from src.history_compactor import _arg_value, _COMMAND_KEYS, _PATH_KEYS # noqa: E402
45
+
46
+ _LANG_EXT_MAP = {
47
+ "py": ".py", "python": ".py", "ts": ".ts", "tsx": ".tsx", "js": ".js",
48
+ "jsx": ".jsx", "go": ".go", "java": ".java", "rs": ".rs", "c": ".c",
49
+ "cpp": ".cpp", "cs": ".cs", "kt": ".kt", "swift": ".swift", "php": ".php",
50
+ "rb": ".rb", "css": ".css", "scss": ".scss",
51
+ }
52
+
53
+
54
+ def _env_flag(name: str, default: str = "1") -> bool:
55
+ raw = os.environ.get(name, default)
56
+ return str(raw).strip().lower() not in ("0", "false", "no", "off")
57
+
58
+
59
+ def _content_hash(text: str) -> str:
60
+ return hashlib.sha256(text.encode("utf-8", "replace")).hexdigest()
61
+
62
+
63
+ def _archive_result(text: str, sha: str) -> Optional[str]:
64
+ """Archives the original result under data/tool_ledger/<sha>.json.
65
+ Returns the archive path, or None when oversized/refused."""
66
+ if len(text) > MAX_ARCHIVE_CHARS:
67
+ return None
68
+ try:
69
+ from src.paths import resolve_data_dir
70
+ archive_dir = os.path.join(resolve_data_dir(), ARCHIVE_DIRNAME)
71
+ os.makedirs(archive_dir, exist_ok=True)
72
+ path = os.path.join(archive_dir, f"{sha[:16]}.json")
73
+ if not os.path.exists(path):
74
+ with open(path, "w", encoding="utf-8") as f:
75
+ json.dump({"sha256": sha, "chars": len(text), "content": text}, f, ensure_ascii=False)
76
+ return path
77
+ except Exception:
78
+ return None
79
+
80
+
81
+ def _head_tail(text: str, head: int = HEAD_LINES, tail: int = TAIL_LINES) -> str:
82
+ lines = text.splitlines()
83
+ if len(lines) <= head + tail + 2:
84
+ return text
85
+ return "\n".join(lines[:head] + [f"... [{len(lines) - head - tail} lines omitted] ..."] + lines[-tail:])
86
+
87
+
88
+ def _compact_read_result(text: str, path: str) -> Optional[str]:
89
+ """AST skeleton for source reads; head/tail fallback for unknown types.
90
+ Produces both candidates when possible and returns the shortest — the
91
+ skeleton only wins when it actually compresses substantially."""
92
+ ext = os.path.splitext(path or "")[1].lower() or None
93
+ candidates: List[str] = []
94
+ lines = text.splitlines()
95
+ if ext and ext in list(_LANG_EXT_MAP.values()) and len(lines) >= 25:
96
+ try:
97
+ from src.skeletonizer import Skeletonizer
98
+ skel = Skeletonizer.skeletonize_code(text, ext)
99
+ if skel and count_tokens(skel) < count_tokens(text) * 0.6:
100
+ candidates.append(
101
+ f"[folded AST skeleton of {len(lines)} lines]\n"
102
+ + skel
103
+ + f"\n[... {len(lines)} lines total; full source archived]"
104
+ )
105
+ except Exception:
106
+ pass
107
+ folded = _head_tail(text)
108
+ if folded != text:
109
+ candidates.append(folded)
110
+ if not candidates:
111
+ return None
112
+ return min(candidates, key=count_tokens)
113
+
114
+
115
+ def _compact_command_result(text: str) -> Optional[str]:
116
+ """Test summaries first (PASS: ...), log-style head/tail otherwise."""
117
+ try:
118
+ from src.command_sanitizer import CommandSanitizer
119
+ compacted = CommandSanitizer.compact_test_output(text, 0)
120
+ if compacted is not text and len(compacted) < len(text) * 0.6:
121
+ return compacted + "\n[... full output archived]"
122
+ except Exception:
123
+ pass
124
+ folded = _head_tail(text)
125
+ return folded if folded != text else None
126
+
127
+
128
+ def _compact_generic_result(text: str) -> Optional[str]:
129
+ folded = _head_tail(text)
130
+ return folded if folded != text else None
131
+
132
+
133
+ def _maybe_distill_history(text: str) -> Optional[str]:
134
+ """Optional managed-cloud summarization (D): paid license + explicit opt-in
135
+ only; degrades silently to the mechanical fold on any failure."""
136
+ if not _env_flag("TOKENSAFE_HISTORY_DISTILL", "0"):
137
+ return None
138
+ try:
139
+ from src.distiller import UniversalDistiller
140
+ tier, _lic = None, None
141
+ try:
142
+ from src.license_manager import LicenseManager
143
+ tier, _lic = LicenseManager.get_active_license()
144
+ except Exception:
145
+ return None
146
+ if tier == "free":
147
+ return None
148
+ return UniversalDistiller.distill_history(text)
149
+ except Exception:
150
+ return None
151
+
152
+
153
+ def _compact_result(tool_name: str, tool_args: Dict[str, Any], text: str) -> Optional[str]:
154
+ """Returns the compact replacement content, or None when nothing shorter
155
+ was produced (caller then leaves the result untouched)."""
156
+ if tool_name in _COMMAND_TOOLS:
157
+ # Command results: the mechanical PASS/head-tail fold is strictly
158
+ # better than prose distillation (deterministic, zero latency).
159
+ return _compact_command_result(text)
160
+ if tool_name in _READ_TOOLS:
161
+ path = _arg_value(tool_args, _PATH_KEYS)
162
+ return _compact_read_result(text, path)
163
+ # Mixed/prose results: managed distillation when enabled, else head/tail.
164
+ distilled = _maybe_distill_history(text)
165
+ if distilled:
166
+ return distilled
167
+ return _compact_generic_result(text)
168
+
169
+
170
+ def _args_preview(tool_args: Dict[str, Any], tool_name: str) -> str:
171
+ preview = _arg_value(tool_args, _PATH_KEYS) or _arg_value(tool_args, _COMMAND_KEYS)
172
+ if not preview:
173
+ try:
174
+ preview = json.dumps(tool_args, ensure_ascii=False)
175
+ except Exception:
176
+ preview = ""
177
+ preview = (preview or "").replace("\n", " ")
178
+ return preview[:60] + ("..." if len(preview) > 60 else "")
179
+
180
+
181
+ def _fold_anchor(tool_name: str, preview: str, orig_tokens: int, new_tokens: int, sha: str, archive_path: Optional[str]) -> str:
182
+ archive_note = f" Original archived at {archive_path}." if archive_path else " Original NOT archived (oversized)."
183
+ return (
184
+ f"{FOLD_MARKER} {tool_name} ({preview}) result consumed earlier — folded "
185
+ f"~{orig_tokens}→{new_tokens} tokens (sha256:{sha[:8]}).{archive_note} "
186
+ f"To re-inspect: re-run {tool_name}, or use smart_read_file(force_full=true) for file reads.]"
187
+ )
188
+
189
+
190
+ def _result_text(content: Any) -> str:
191
+ """Extracts the text mass of an OpenAI tool message content (str or blocks)."""
192
+ if isinstance(content, str):
193
+ return content
194
+ if isinstance(content, list):
195
+ parts = []
196
+ for b in content:
197
+ if isinstance(b, dict) and isinstance(b.get("text"), str):
198
+ parts.append(b["text"])
199
+ return "\n".join(parts)
200
+ return ""
201
+
202
+
203
+ def _set_result_text(msg: Dict[str, Any], new_text: str) -> None:
204
+ content = msg.get("content")
205
+ if isinstance(content, list):
206
+ # Keep block structure; replace the first text block, drop the rest.
207
+ replaced = False
208
+ kept = []
209
+ for b in content:
210
+ if not replaced and isinstance(b, dict) and isinstance(b.get("text"), str):
211
+ kept.append(dict(b, text=new_text))
212
+ replaced = True
213
+ elif isinstance(b, dict) and isinstance(b.get("text"), str):
214
+ continue # redundant text blocks collapse into the fold
215
+ else:
216
+ kept.append(b)
217
+ if not replaced:
218
+ kept.insert(0, {"type": "text", "text": new_text})
219
+ msg["content"] = kept
220
+ else:
221
+ msg["content"] = new_text
222
+
223
+
224
+ def _assistant_tool_calls(msg: Dict[str, Any]) -> List[Tuple[str, str, Dict[str, Any]]]:
225
+ """Yields (call_id, tool_name, args) for OpenAI-style assistant tool_calls."""
226
+ calls = []
227
+ for tc in msg.get("tool_calls") or []:
228
+ if not isinstance(tc, dict):
229
+ continue
230
+ fn = tc.get("function") if isinstance(tc.get("function"), dict) else {}
231
+ call_id = str(tc.get("id") or "")
232
+ name = str(fn.get("name") or "")
233
+ raw_args = fn.get("arguments")
234
+ args: Dict[str, Any] = {}
235
+ if isinstance(raw_args, dict):
236
+ args = raw_args
237
+ elif isinstance(raw_args, str):
238
+ try:
239
+ parsed = json.loads(raw_args)
240
+ if isinstance(parsed, dict):
241
+ args = parsed
242
+ except Exception:
243
+ args = {}
244
+ if call_id and name:
245
+ calls.append((call_id, name, args))
246
+ return calls
247
+
248
+
249
+ def fold_tool_results(
250
+ messages: List[Dict[str, Any]],
251
+ session_id: str = "proxy_session",
252
+ keep_recent: int = 6,
253
+ min_tokens: int = 800,
254
+ record_metrics: bool = True,
255
+ ) -> Tuple[List[Dict[str, Any]], Dict[str, Any]]:
256
+ """
257
+ Folds aged, oversized tool results into compact anchors (in-place on a
258
+ shallow copy of the message list). Returns (messages, stats).
259
+
260
+ Gates: TOKENSAFE_TOOL_LEDGER=0 disables; results inside the last
261
+ `keep_recent` messages are never folded; results under `min_tokens` stay
262
+ verbatim; already-folded results (marker present) are never re-folded.
263
+ """
264
+ stats: Dict[str, Any] = {"folded": 0, "orig_tokens": 0, "new_tokens": 0, "saved_tokens": 0}
265
+ if not messages or not _env_flag("TOKENSAFE_TOOL_LEDGER"):
266
+ return messages, stats
267
+
268
+ # Map call_id -> (tool_name, args) from ALL assistant turns.
269
+ call_meta: Dict[str, Tuple[str, Dict[str, Any]]] = {}
270
+ for m in messages:
271
+ if isinstance(m, dict) and m.get("role") == "assistant":
272
+ for call_id, name, args in _assistant_tool_calls(m):
273
+ call_meta[call_id] = (name, args)
274
+
275
+ protected_from = max(0, len(messages) - keep_recent)
276
+ for idx, msg in enumerate(messages):
277
+ if idx >= protected_from or not isinstance(msg, dict) or msg.get("role") != "tool":
278
+ continue
279
+ call_id = str(msg.get("tool_call_id") or "")
280
+ tool_name, tool_args = call_meta.get(call_id, ("unknown_tool", {}))
281
+ text = _result_text(msg.get("content"))
282
+ if not text or FOLD_MARKER in text:
283
+ continue # empty or already folded — idempotence marker
284
+ orig_tokens = count_tokens(text)
285
+ if orig_tokens < min_tokens:
286
+ continue
287
+ compacted = _compact_result(tool_name, tool_args, text)
288
+ if not compacted or count_tokens(compacted) >= orig_tokens * 0.85:
289
+ continue # compaction must earn its cache-break
290
+ new_tokens = count_tokens(compacted)
291
+ sha = _content_hash(text)
292
+ anchor = _fold_anchor(tool_name, _args_preview(tool_args, tool_name), orig_tokens, new_tokens, sha, _archive_result(text, sha))
293
+ final_text = f"{anchor}\n\n{compacted}" if not compacted.startswith(FOLD_MARKER) else compacted
294
+ _set_result_text(msg, final_text)
295
+ stats["folded"] += 1
296
+ stats["orig_tokens"] += orig_tokens
297
+ stats["new_tokens"] += new_tokens
298
+ stats["saved_tokens"] += max(0, orig_tokens - new_tokens)
299
+
300
+ if stats["folded"] and record_metrics:
301
+ try:
302
+ from src.metrics import MetricsTracker
303
+ MetricsTracker().record_event(
304
+ session_id=session_id,
305
+ event_type="TOOL_LEDGER",
306
+ original_tokens=stats["orig_tokens"],
307
+ optimized_tokens=stats["new_tokens"],
308
+ details={"folded": stats["folded"]},
309
+ measurement="measured",
310
+ )
311
+ except Exception:
312
+ pass
313
+
314
+ return messages, stats
@@ -77,6 +77,17 @@ class ScopedSearch:
77
77
  return ext == f".{scope}"
78
78
  return True
79
79
 
80
+ @classmethod
81
+ def _looks_like_regex(cls, query: str) -> bool:
82
+ """Conservative auto-detection for use_regex=None (omitted): only
83
+ unambiguous regex constructs switch the mode — alternation pipes and
84
+ backslash character classes. Plain dots/brackets stay literal."""
85
+ if "|" in query:
86
+ return True
87
+ if re.search(r"\\[dwsbDWSB]", query):
88
+ return True
89
+ return False
90
+
80
91
  @classmethod
81
92
  def search(
82
93
  cls,
@@ -85,7 +96,7 @@ class ScopedSearch:
85
96
  scope: str = "all",
86
97
  max_results: int = 25,
87
98
  case_sensitive: bool = False,
88
- use_regex: bool = False
99
+ use_regex: Optional[bool] = None
89
100
  ) -> Dict[str, Any]:
90
101
  """
91
102
  Executes a bounded code/config search and returns structured results and compact markdown.
@@ -121,6 +132,9 @@ class ScopedSearch:
121
132
 
122
133
  query = query.strip()
123
134
  scope = (scope or "all").lower().strip()
135
+ # use_regex=None (omitted) -> auto-detect; explicit False forces literal, True forces regex
136
+ auto_regex = use_regex is None and cls._looks_like_regex(query)
137
+ regex_mode = bool(use_regex) if use_regex is not None else auto_regex
124
138
  if max_results is None or isinstance(max_results, bool):
125
139
  max_results = 25
126
140
  else:
@@ -132,18 +146,24 @@ class ScopedSearch:
132
146
  # Compile search pattern
133
147
  flags = 0 if case_sensitive else re.IGNORECASE
134
148
  try:
135
- if use_regex:
149
+ if regex_mode:
136
150
  pattern = re.compile(query, flags)
137
151
  else:
138
152
  pattern = re.compile(re.escape(query), flags)
139
153
  except Exception as e:
140
- return {
141
- "success": False,
142
- "error": f"Invalid regex pattern: {str(e)}",
143
- "matches": [],
144
- "total_matches": 0,
145
- "markdown": f"Regex compilation error: {str(e)}"
146
- }
154
+ if regex_mode and use_regex is None:
155
+ # Malformed auto-detected regex: degrade to literal instead of failing
156
+ regex_mode = False
157
+ auto_regex = False
158
+ pattern = re.compile(re.escape(query), flags)
159
+ else:
160
+ return {
161
+ "success": False,
162
+ "error": f"Invalid regex pattern: {str(e)}",
163
+ "matches": [],
164
+ "total_matches": 0,
165
+ "markdown": f"Regex compilation error: {str(e)}"
166
+ }
147
167
 
148
168
  matches: List[Dict[str, Any]] = []
149
169
  total_scanned_files = 0
@@ -222,11 +242,14 @@ class ScopedSearch:
222
242
 
223
243
  # Generate ultra-compact Markdown output (< 150 tokens)
224
244
  display_root = os.path.basename(root_dir) or root_dir
245
+ mode_suffix = ", auto-regex" if auto_regex and regex_mode else ""
225
246
  lines = [
226
- f"### TokenSafe Scoped Search: '{query}' ({len(matches)} match{'es' if len(matches) != 1 else ''} in {len(hit_files)} file{'s' if len(hit_files) != 1 else ''}, dir: `{display_root}`, scope: {scope})"
247
+ f"### TokenSafe Scoped Search: '{query}' ({len(matches)} match{'es' if len(matches) != 1 else ''} in {len(hit_files)} file{'s' if len(hit_files) != 1 else ''}, dir: `{display_root}`, scope: {scope}{mode_suffix})"
227
248
  ]
228
249
  if not matches:
229
250
  lines.append(f"_No matches found across {total_scanned_files} scanned files in `{root_dir}`._")
251
+ if auto_regex and regex_mode:
252
+ lines.append("_Auto-regex mode found nothing; pass use_regex=false to force a literal search._")
230
253
  else:
231
254
  for m in matches:
232
255
  lines.append(f"- `{m['file']}:{m['line']}`: `{m['text']}`")
package/src/slicer.py CHANGED
@@ -193,42 +193,3 @@ class ToolSlicer:
193
193
  return overwrite, metrics
194
194
 
195
195
  return {}, {"saved_tokens": 0, "original_tokens": total_tokens, "optimized_tokens": total_tokens}
196
-
197
- @classmethod
198
- def sanitize_command_log(cls, raw_output: str) -> Tuple[str, int, int]:
199
- """
200
- Sanitizes test/build command outputs by removing redundant node_modules stacks,
201
- excessive empty lines, and long progress bars.
202
- Returns: (sanitized_output, original_tokens, sanitized_tokens)
203
- """
204
- if not raw_output:
205
- return "", 0, 0
206
-
207
- orig_tokens = count_tokens(raw_output)
208
- lines = raw_output.splitlines()
209
-
210
- cleaned_lines = []
211
- skip_stack = False
212
-
213
- for line in lines:
214
- # Drop noisy node_modules / site-packages internal stack lines
215
- if re.search(r"at .*node_modules/|at .*site-packages/|at async Promise\.all", line):
216
- if not skip_stack:
217
- cleaned_lines.append(" [... internal dependency stack omitted ...]")
218
- skip_stack = True
219
- continue
220
- else:
221
- skip_stack = False
222
-
223
- # Drop progress bars
224
- if re.search(r"(\[=+>*\s*\]|\d+%\s*\|\s*█+)", line):
225
- continue
226
-
227
- cleaned_lines.append(line)
228
-
229
- sanitized = "\n".join(cleaned_lines)
230
- # Collapse multiple blank lines
231
- sanitized = re.sub(r"\n{3,}", "\n\n", sanitized)
232
- sanitized_tokens = count_tokens(sanitized)
233
-
234
- return sanitized, orig_tokens, sanitized_tokens
@@ -228,7 +228,7 @@ class TelemetrySync:
228
228
  current_last_id = last_id
229
229
  headers = {
230
230
  "Content-Type": "application/json",
231
- "User-Agent": "TokenSafe-Sync/2.8.4"
231
+ "User-Agent": "TokenSafe-Sync/3.0.0"
232
232
  }
233
233
  if active_key:
234
234
  headers["Authorization"] = f"Bearer {active_key}"