tokensafe 2.9.0 → 3.0.1
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.
- package/README.md +57 -1
- package/hooks/claude_code_hook.py +24 -1
- package/hooks/pre_tool_use.py +7 -32
- package/package.json +1 -1
- package/plugin.json +1 -1
- package/server.json +3 -3
- package/src/adapter_core.py +71 -0
- package/src/benchmark_real.py +562 -0
- package/src/cli.py +129 -6
- package/src/command_sanitizer.py +0 -26
- package/src/dashboard.py +26 -4
- package/src/distiller.py +41 -2
- package/src/governor.py +1 -0
- package/src/guard.py +0 -5
- package/src/installer.py +279 -1
- package/src/license_manager.py +31 -4
- package/src/mcp_server.py +1 -1
- package/src/metrics.py +25 -0
- package/src/proxy.py +455 -5
- package/src/result_ledger.py +314 -0
- package/src/slicer.py +0 -39
- package/src/telemetry_sync.py +1 -1
- package/src/tool_pruner.py +244 -0
- package/src/version_checker.py +1 -15
|
@@ -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
|
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
|
package/src/telemetry_sync.py
CHANGED
|
@@ -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/
|
|
231
|
+
"User-Agent": "TokenSafe-Sync/3.0.1"
|
|
232
232
|
}
|
|
233
233
|
if active_key:
|
|
234
234
|
headers["Authorization"] = f"Bearer {active_key}"
|
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
"""
|
|
2
|
+
TokenSafe Session-Stable Tool Pruner (proxy-stage, v3.0.0).
|
|
3
|
+
|
|
4
|
+
The proxy sees the FULL tools[] array of every MCP server. Most sessions use a
|
|
5
|
+
small fraction of the declared tools, yet every unused schema burns floor
|
|
6
|
+
tokens on every request (~8.7K in a typical session).
|
|
7
|
+
|
|
8
|
+
Opt-in (TOKENSAFE_TOOL_PRUNING=1). Instead of Anthropic-style tool search
|
|
9
|
+
(impossible here: the proxy never EXECUTES tools — the agent does), we pick a
|
|
10
|
+
relevance-ranked SUBSET once per pseudo-session and keep it byte-stable for
|
|
11
|
+
the whole session, so the tools[] KV-cache prefix never churns mid-session:
|
|
12
|
+
|
|
13
|
+
- Pseudo-session key = sha256(first_user_content + model)[:16] — the first
|
|
14
|
+
user message is replayed verbatim in every request of a session, so the key
|
|
15
|
+
is stable; a new session almost always means a new key.
|
|
16
|
+
- Subset = top-K tools scored against the first user message (keyword overlap
|
|
17
|
+
over name+description) + the always-allow allowlist.
|
|
18
|
+
- The agent still knows ALL its tools, so a pruned-tool call still executes —
|
|
19
|
+
we just measure the miss rate (TOOL_PRUNE_MISS) to watch quality impact.
|
|
20
|
+
|
|
21
|
+
State: data/proxy_tool_subsets.json {key: {tools: [names], ts}} with TTL
|
|
22
|
+
pruning. Stateless for requests of an already-keyed session.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
import hashlib
|
|
26
|
+
import json
|
|
27
|
+
import os
|
|
28
|
+
import re
|
|
29
|
+
import time
|
|
30
|
+
from typing import Any, Dict, List, Optional, Tuple
|
|
31
|
+
|
|
32
|
+
from src.tokenizer import count_tokens
|
|
33
|
+
|
|
34
|
+
STATE_FILENAME = "proxy_tool_subsets.json"
|
|
35
|
+
STATE_TTL_SECONDS = 24 * 3600
|
|
36
|
+
STATE_MAX_KEYS = 64
|
|
37
|
+
DEFAULT_KEEP = 14
|
|
38
|
+
_TOKEN_RE = re.compile(r"[a-zA-Z_][a-zA-Z0-9_\-]{2,}")
|
|
39
|
+
|
|
40
|
+
_STOPWORDS = {
|
|
41
|
+
"the", "and", "for", "with", "this", "that", "from", "into", "your",
|
|
42
|
+
"you", "are", "can", "will", "not", "use", "using", "when", "what",
|
|
43
|
+
"which", "how", "all", "any", "get", "set", "list", "name", "path",
|
|
44
|
+
"file", "type", "string", "integer", "boolean", "object", "array",
|
|
45
|
+
"optional", "required", "default", "returns", "return", "description",
|
|
46
|
+
"parameter", "parameters", "schema", "tool", "tools", "please", "need",
|
|
47
|
+
"want", "make", "add", "fix", "code", "project",
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _tool_name(tool: Dict[str, Any]) -> str:
|
|
52
|
+
if isinstance(tool, dict):
|
|
53
|
+
if tool.get("name"):
|
|
54
|
+
return str(tool["name"])
|
|
55
|
+
fn = tool.get("function")
|
|
56
|
+
if isinstance(fn, dict) and fn.get("name"):
|
|
57
|
+
return str(fn["name"])
|
|
58
|
+
return ""
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _tool_desc(tool: Dict[str, Any]) -> str:
|
|
62
|
+
if isinstance(tool, dict):
|
|
63
|
+
if isinstance(tool.get("description"), str):
|
|
64
|
+
return tool["description"]
|
|
65
|
+
fn = tool.get("function")
|
|
66
|
+
if isinstance(fn, dict) and isinstance(fn.get("description"), str):
|
|
67
|
+
return fn["description"]
|
|
68
|
+
return ""
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _session_key(messages: List[Dict[str, Any]], model: str) -> str:
|
|
72
|
+
first_user = ""
|
|
73
|
+
for m in messages or []:
|
|
74
|
+
if isinstance(m, dict) and m.get("role") == "user":
|
|
75
|
+
c = m.get("content")
|
|
76
|
+
first_user = c if isinstance(c, str) else json.dumps(c, ensure_ascii=False)
|
|
77
|
+
break
|
|
78
|
+
return hashlib.sha256((first_user + "|" + str(model or "")).encode("utf-8", "replace")).hexdigest()[:16]
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _allowlist() -> List[str]:
|
|
82
|
+
raw = os.environ.get("TOKENSAFE_TOOL_PRUNE_ALLOWLIST", "")
|
|
83
|
+
return [t.strip() for t in raw.split(",") if t.strip()]
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _state_path() -> str:
|
|
87
|
+
from src.paths import resolve_data_dir
|
|
88
|
+
return os.path.join(resolve_data_dir(), STATE_FILENAME)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _load_state() -> Dict[str, Any]:
|
|
92
|
+
try:
|
|
93
|
+
with open(_state_path(), "r", encoding="utf-8") as f:
|
|
94
|
+
data = json.load(f)
|
|
95
|
+
return data if isinstance(data, dict) else {}
|
|
96
|
+
except Exception:
|
|
97
|
+
return {}
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _save_state(state: Dict[str, Any]) -> None:
|
|
101
|
+
try:
|
|
102
|
+
os.makedirs(os.path.dirname(_state_path()), exist_ok=True)
|
|
103
|
+
with open(_state_path(), "w", encoding="utf-8") as f:
|
|
104
|
+
json.dump(state, f)
|
|
105
|
+
except Exception:
|
|
106
|
+
pass
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _prune_state(state: Dict[str, Any]) -> Dict[str, Any]:
|
|
110
|
+
now = time.time()
|
|
111
|
+
alive = {k: v for k, v in state.items()
|
|
112
|
+
if isinstance(v, dict) and (now - float(v.get("ts", 0) or 0)) < STATE_TTL_SECONDS}
|
|
113
|
+
if len(alive) > STATE_MAX_KEYS:
|
|
114
|
+
ranked = sorted(alive.items(), key=lambda kv: -float(kv[1].get("ts", 0) or 0))
|
|
115
|
+
alive = dict(ranked[:STATE_MAX_KEYS])
|
|
116
|
+
return alive
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _score_tool(tool: Dict[str, Any], query_tokens: set) -> float:
|
|
120
|
+
name = _tool_name(tool)
|
|
121
|
+
text = f"{name} {_tool_desc(tool)}".lower()
|
|
122
|
+
tokens = set(_TOKEN_RE.findall(text)) - _STOPWORDS
|
|
123
|
+
overlap = len(tokens & query_tokens)
|
|
124
|
+
# Name hits outweigh description hits; exact name-in-query is strongest.
|
|
125
|
+
name_bonus = 3.0 if name.lower() in query_tokens else 0.0
|
|
126
|
+
return overlap + name_bonus
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def select_subset(
|
|
130
|
+
tools: List[Dict[str, Any]],
|
|
131
|
+
messages: List[Dict[str, Any]],
|
|
132
|
+
model: str = "",
|
|
133
|
+
) -> Tuple[Optional[List[str]], Dict[str, Any]]:
|
|
134
|
+
"""
|
|
135
|
+
Returns (subset_tool_names_or_None, meta). None means "no pruning"
|
|
136
|
+
(flag off, pool small enough, or no user content to score against).
|
|
137
|
+
The result is deterministic per (session_key, pool); selection happens
|
|
138
|
+
once per pseudo-session and is then served from the state file.
|
|
139
|
+
"""
|
|
140
|
+
meta: Dict[str, Any] = {"applied": False, "pool": len(tools or [])}
|
|
141
|
+
if not tools or not isinstance(tools, list):
|
|
142
|
+
return None, meta
|
|
143
|
+
if os.environ.get("TOKENSAFE_TOOL_PRUNING", "").strip().lower() not in ("1", "true", "yes"):
|
|
144
|
+
return None, meta
|
|
145
|
+
|
|
146
|
+
keep = DEFAULT_KEEP
|
|
147
|
+
raw_keep = os.environ.get("TOKENSAFE_TOOL_PRUNE_KEEP", "")
|
|
148
|
+
if raw_keep.strip().isdigit():
|
|
149
|
+
keep = max(1, int(raw_keep.strip()))
|
|
150
|
+
if len(tools) <= keep:
|
|
151
|
+
meta["reason"] = "pool<=keep"
|
|
152
|
+
return None, meta
|
|
153
|
+
|
|
154
|
+
key = _session_key(messages, model)
|
|
155
|
+
if not key:
|
|
156
|
+
return None, meta
|
|
157
|
+
state = _prune_state(_load_state())
|
|
158
|
+
entry = state.get(key)
|
|
159
|
+
if isinstance(entry, dict) and isinstance(entry.get("tools"), list):
|
|
160
|
+
cached_names = [str(n) for n in entry["tools"]]
|
|
161
|
+
meta.update({"applied": True, "session_key": key, "cached": True, "subset": len(cached_names)})
|
|
162
|
+
return cached_names, meta
|
|
163
|
+
|
|
164
|
+
# Score once per pseudo-session against the first user message.
|
|
165
|
+
query_text = ""
|
|
166
|
+
for m in messages or []:
|
|
167
|
+
if isinstance(m, dict) and m.get("role") == "user":
|
|
168
|
+
c = m.get("content")
|
|
169
|
+
query_text = c if isinstance(c, str) else json.dumps(c, ensure_ascii=False)
|
|
170
|
+
break
|
|
171
|
+
query_tokens = set(_TOKEN_RE.findall(query_text.lower())) - _STOPWORDS
|
|
172
|
+
|
|
173
|
+
allow = set(_allowlist())
|
|
174
|
+
scored = sorted(
|
|
175
|
+
tools,
|
|
176
|
+
key=lambda t: (-_score_tool(t, query_tokens), _tool_name(t)),
|
|
177
|
+
)
|
|
178
|
+
subset: List[str] = []
|
|
179
|
+
for t in scored:
|
|
180
|
+
name = _tool_name(t)
|
|
181
|
+
if not name or name in subset:
|
|
182
|
+
continue
|
|
183
|
+
if len(subset) >= keep and name not in allow:
|
|
184
|
+
continue
|
|
185
|
+
subset.append(name)
|
|
186
|
+
# Allowlisted tools always make the cut, even beyond K.
|
|
187
|
+
for t in tools:
|
|
188
|
+
name = _tool_name(t)
|
|
189
|
+
if name in allow and name not in subset:
|
|
190
|
+
subset.append(name)
|
|
191
|
+
|
|
192
|
+
meta.update({"applied": True, "session_key": key, "cached": False, "subset": len(subset), "pool": len(tools)})
|
|
193
|
+
state[key] = {"tools": subset, "ts": time.time()}
|
|
194
|
+
_save_state(state)
|
|
195
|
+
return subset, meta
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def apply_subset(
|
|
199
|
+
tools: List[Dict[str, Any]],
|
|
200
|
+
messages: List[Dict[str, Any]],
|
|
201
|
+
model: str = "",
|
|
202
|
+
record_metrics: bool = True,
|
|
203
|
+
) -> Tuple[List[Dict[str, Any]], Dict[str, Any]]:
|
|
204
|
+
"""Filters tools[] down to the session subset. Returns (tools, meta)."""
|
|
205
|
+
subset_names, meta = select_subset(tools, messages, model)
|
|
206
|
+
if not subset_names:
|
|
207
|
+
return tools, meta
|
|
208
|
+
keep_set = set(subset_names)
|
|
209
|
+
pruned = [t for t in tools if _tool_name(t) in keep_set]
|
|
210
|
+
if len(pruned) == len(tools):
|
|
211
|
+
meta["applied"] = False
|
|
212
|
+
return tools, meta
|
|
213
|
+
meta["saved_tokens"] = max(0, count_tokens(json.dumps(tools, ensure_ascii=False)) - count_tokens(json.dumps(pruned, ensure_ascii=False)))
|
|
214
|
+
if record_metrics and meta.get("saved_tokens"):
|
|
215
|
+
try:
|
|
216
|
+
from src.metrics import MetricsTracker
|
|
217
|
+
MetricsTracker().record_event(
|
|
218
|
+
session_id=f"prune_{meta.get('session_key', 'sess')}",
|
|
219
|
+
event_type="TOOL_PRUNE",
|
|
220
|
+
original_tokens=count_tokens(json.dumps(tools, ensure_ascii=False)),
|
|
221
|
+
optimized_tokens=count_tokens(json.dumps(pruned, ensure_ascii=False)),
|
|
222
|
+
details={"pool": len(tools), "subset": len(pruned), "cached": meta.get("cached", False)},
|
|
223
|
+
measurement="measured",
|
|
224
|
+
)
|
|
225
|
+
except Exception:
|
|
226
|
+
pass
|
|
227
|
+
return pruned, meta
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def detect_prune_miss(response_json: Dict[str, Any], sent_tool_names: set) -> Optional[str]:
|
|
231
|
+
"""Returns the first tool name the model called that was NOT in the sent
|
|
232
|
+
subset (quality-impact telemetry; the call still flows to the agent)."""
|
|
233
|
+
if not isinstance(response_json, dict):
|
|
234
|
+
return None
|
|
235
|
+
for choice in response_json.get("choices") or []:
|
|
236
|
+
msg = choice.get("message") if isinstance(choice, dict) else None
|
|
237
|
+
for tc in (msg or {}).get("tool_calls") or []:
|
|
238
|
+
if not isinstance(tc, dict):
|
|
239
|
+
continue
|
|
240
|
+
fn = tc.get("function") if isinstance(tc.get("function"), dict) else {}
|
|
241
|
+
name = str(fn.get("name") or "")
|
|
242
|
+
if name and name not in sent_tool_names:
|
|
243
|
+
return name
|
|
244
|
+
return None
|
package/src/version_checker.py
CHANGED
|
@@ -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 = "
|
|
20
|
+
CURRENT_VERSION = "3.0.1"
|
|
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
|
|
@@ -52,20 +52,6 @@ YELLOW = "\033[33m"
|
|
|
52
52
|
RED = "\033[31m"
|
|
53
53
|
DIM = "\033[2m"
|
|
54
54
|
|
|
55
|
-
def semver_tuple(v_str: str) -> Tuple[int, ...]:
|
|
56
|
-
"""Parses semver string like '1.2.0' into numeric tuple (1, 2, 0)."""
|
|
57
|
-
if not v_str:
|
|
58
|
-
return (0, 0, 0)
|
|
59
|
-
clean = re.sub(r"^[^\d]*", "", str(v_str).strip())
|
|
60
|
-
parts = clean.split(".")
|
|
61
|
-
nums = []
|
|
62
|
-
for p in parts[:3]:
|
|
63
|
-
m = re.match(r"\d+", p)
|
|
64
|
-
nums.append(int(m.group(0)) if m else 0)
|
|
65
|
-
while len(nums) < 3:
|
|
66
|
-
nums.append(0)
|
|
67
|
-
return tuple(nums)
|
|
68
|
-
|
|
69
55
|
class VersionChecker:
|
|
70
56
|
"""Manages cached client-side version discovery and CLI banners."""
|
|
71
57
|
|