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,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
@@ -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 = "2.8.4"
20
+ CURRENT_VERSION = "3.0.0"
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