tokensafe 2.6.1 → 2.7.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.
Files changed (45) hide show
  1. package/bin/tokensafe +1 -1
  2. package/extensions/cursor-tokensafe/extension.js +21 -8
  3. package/hooks/claude_code_hook.py +13 -5
  4. package/hooks/cursor_hook.py +7 -4
  5. package/hooks/post_tool_use.py +24 -6
  6. package/hooks/pre_invocation.py +40 -27
  7. package/hooks/pre_tool_use.py +85 -83
  8. package/hooks/session_start.py +8 -4
  9. package/hooks/stop_hook.py +7 -4
  10. package/package.json +1 -1
  11. package/plugin.json +1 -1
  12. package/server.json +3 -3
  13. package/src/agent_firewall.py +38 -21
  14. package/src/cache_normalizer.py +39 -10
  15. package/src/cli.py +144 -91
  16. package/src/command_sanitizer.py +248 -136
  17. package/src/compactor.py +55 -25
  18. package/src/dashboard.py +17 -10
  19. package/src/deepseek_distiller.py +26 -17
  20. package/src/dependency_prefetcher.py +66 -41
  21. package/src/diff_slicer.py +23 -17
  22. package/src/distiller.py +45 -17
  23. package/src/distiller_cache.py +74 -47
  24. package/src/environment_auditor.py +34 -12
  25. package/src/governor.py +83 -26
  26. package/src/graph_engine.py +653 -140
  27. package/src/guard.py +316 -132
  28. package/src/history_compactor.py +57 -26
  29. package/src/installer.py +174 -131
  30. package/src/license_manager.py +12 -9
  31. package/src/loop_detector.py +68 -29
  32. package/src/mcp_server.py +200 -60
  33. package/src/metrics.py +141 -54
  34. package/src/paths.py +32 -6
  35. package/src/proxy.py +121 -52
  36. package/src/scoped_search.py +18 -6
  37. package/src/secret_redactor.py +78 -59
  38. package/src/skeletonizer.py +68 -13
  39. package/src/slicer.py +25 -7
  40. package/src/team_cache.py +10 -3
  41. package/src/telemetry_sync.py +110 -39
  42. package/src/tokenizer.py +24 -13
  43. package/src/treesitter_backend.py +539 -0
  44. package/src/version_checker.py +67 -32
  45. package/src/weekly_digest.py +6 -3
package/src/metrics.py CHANGED
@@ -99,14 +99,22 @@ class MetricsTracker:
99
99
  """
100
100
  marker = os.path.join(os.path.dirname(db_path) or ".", ".metrics_last_prune")
101
101
  claim = marker + ".claim"
102
+ _CLAIM_STALE_TTL = 300.0
102
103
  try:
103
- if os.path.exists(marker) and (time.time() - os.path.getmtime(marker)) < _AUTOPRUNE_INTERVAL:
104
+ now = time.time()
105
+ if os.path.exists(marker) and (now - os.path.getmtime(marker)) < _AUTOPRUNE_INTERVAL:
104
106
  return
107
+ if os.path.exists(claim):
108
+ try:
109
+ if (now - os.path.getmtime(claim)) > _CLAIM_STALE_TTL:
110
+ os.unlink(claim)
111
+ except OSError:
112
+ pass
105
113
  try:
106
114
  fd = os.open(claim, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
107
115
  os.close(fd)
108
116
  except FileExistsError:
109
- return # another process is pruning right now
117
+ return # another active process is pruning right now
110
118
  try:
111
119
  tracker = cls(db_path)
112
120
  tracker.prune(days=tracker.retention_days, max_events=tracker.max_events, vacuum=False)
@@ -132,6 +140,24 @@ class MetricsTracker:
132
140
  return
133
141
  with self._get_connection() as conn:
134
142
  cursor = conn.cursor()
143
+ try:
144
+ uv_row = cursor.execute("PRAGMA user_version;").fetchone()
145
+ user_ver = int(uv_row[0]) if uv_row else 0
146
+ except Exception:
147
+ user_ver = 0
148
+ if user_ver >= 2:
149
+ tbl = cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='events';").fetchone()
150
+ if tbl is not None:
151
+ cursor.execute(
152
+ "UPDATE events SET measurement = 'estimated' "
153
+ "WHERE measurement = 'measured' AND event_type IN "
154
+ "('GRAPH_TOPOLOGY', 'HISTORY_FOLD', 'PROMPT', 'ROLLUP_LIFETIME', "
155
+ "'COMMAND_FILTER', 'LOOP_GUARD', 'SCOPED_SEARCH', 'DIR_LIST', "
156
+ "'GUARD_SECRET', 'GUARD_DESTRUCTIVE', 'GUARD_TLS_VERIFY_BYPASS', "
157
+ "'GUARD_JUNK_READ', 'GUARD_INFINITE', 'GUARD_RAW_CODE_SEARCH');"
158
+ )
159
+ _INITIALIZED_METRICS_DBS.add(self.db_path)
160
+ return
135
161
  try:
136
162
  cursor.execute("PRAGMA journal_mode=WAL;")
137
163
  except sqlite3.Error:
@@ -199,6 +225,7 @@ class MetricsTracker:
199
225
  """)
200
226
  cursor.execute("CREATE INDEX IF NOT EXISTS idx_events_timestamp ON events(timestamp)")
201
227
  cursor.execute("CREATE INDEX IF NOT EXISTS idx_events_session_id ON events(session_id)")
228
+ cursor.execute("CREATE INDEX IF NOT EXISTS idx_events_measurement_type ON events(measurement, event_type)")
202
229
  cursor.execute("""
203
230
  CREATE TABLE IF NOT EXISTS quota_daily (
204
231
  day_key TEXT PRIMARY KEY,
@@ -217,6 +244,10 @@ class MetricsTracker:
217
244
  WHERE timestamp >= ? AND measurement = 'measured' AND saved_tokens > 0
218
245
  GROUP BY substr(timestamp, 1, 10)
219
246
  """, (cutoff_30,))
247
+ try:
248
+ cursor.execute("PRAGMA user_version = 2;")
249
+ except sqlite3.Error:
250
+ pass
220
251
  _INITIALIZED_METRICS_DBS.add(self.db_path)
221
252
 
222
253
  def _quota_mirror_path(self) -> str:
@@ -228,69 +259,118 @@ class MetricsTracker:
228
259
  return os.path.join(os.path.dirname(default_data), ".qledger.json")
229
260
  return os.path.join(os.path.dirname(self.db_path), ".qledger.json")
230
261
 
262
+ @staticmethod
263
+ def _qledger_write_atomic(mirror_path: str, data: Dict[str, Any]) -> None:
264
+ parent = os.path.dirname(mirror_path) or "."
265
+ os.makedirs(parent, exist_ok=True)
266
+ tmp_p = f"{mirror_path}.tmp.{os.getpid()}.{threading.get_ident()}"
267
+ with open(tmp_p, "w", encoding="utf-8") as f:
268
+ json.dump(data, f)
269
+ os.replace(tmp_p, mirror_path)
270
+
271
+ @staticmethod
272
+ def _qledger_locked(mirror_path: str, mutate_fn):
273
+ parent = os.path.dirname(mirror_path) or "."
274
+ os.makedirs(parent, exist_ok=True)
275
+ lock_path = mirror_path + ".lock"
276
+ fh = open(lock_path, "a+")
277
+ locked_posix = False
278
+ locked_win = False
279
+ try:
280
+ try:
281
+ import fcntl
282
+ fcntl.flock(fh.fileno(), fcntl.LOCK_EX)
283
+ locked_posix = True
284
+ except ImportError:
285
+ try:
286
+ import msvcrt
287
+ msvcrt.locking(fh.fileno(), msvcrt.LK_LOCK, 1)
288
+ locked_win = True
289
+ except Exception:
290
+ pass
291
+ return mutate_fn()
292
+ finally:
293
+ try:
294
+ if locked_posix:
295
+ import fcntl
296
+ fcntl.flock(fh.fileno(), fcntl.LOCK_UN)
297
+ elif locked_win:
298
+ import msvcrt
299
+ fh.seek(0)
300
+ msvcrt.locking(fh.fileno(), msvcrt.LK_UNLCK, 1)
301
+ except Exception:
302
+ pass
303
+ fh.close()
304
+
231
305
  def _sync_quota_mirror(self, day_key: str, delta_measured: int = 0) -> int:
232
- """Merges quota_daily with a sidecar ledger so deleting metrics.db or pruning >5k rows cannot reset quota."""
306
+ """Merges quota_daily with a sidecar ledger under file lock so concurrent hooks cannot drop deltas."""
233
307
  mirror_path = self._quota_mirror_path()
234
308
  cutoff_day = (datetime.now() - timedelta(days=30)).strftime("%Y-%m-%d")
235
- data: Dict[str, Any] = {"days": {}, "server_floor": 0, "server_floor_ts": 0}
236
- try:
237
- if os.path.exists(mirror_path):
238
- with open(mirror_path, "r", encoding="utf-8") as f:
239
- loaded = json.load(f)
240
- if isinstance(loaded, dict):
241
- data.update(loaded)
242
- except Exception:
243
- pass
244
- days = {
245
- str(k): int(v)
246
- for k, v in (data.get("days") or {}).items()
247
- if str(k) >= cutoff_day and int(v or 0) > 0
248
- }
249
- if delta_measured > 0 and day_key >= cutoff_day:
250
- days[day_key] = days.get(day_key, 0) + int(delta_measured)
251
- data["days"] = days
252
- if delta_measured > 0:
309
+
310
+ def _do():
311
+ data: Dict[str, Any] = {"days": {}, "server_floor": 0, "server_floor_ts": 0}
253
312
  try:
254
- os.makedirs(os.path.dirname(mirror_path), exist_ok=True)
255
- tmp_p = mirror_path + ".tmp"
256
- with open(tmp_p, "w", encoding="utf-8") as f:
257
- json.dump(data, f)
258
- os.replace(tmp_p, mirror_path)
313
+ if os.path.exists(mirror_path):
314
+ with open(mirror_path, "r", encoding="utf-8") as f:
315
+ loaded = json.load(f)
316
+ if isinstance(loaded, dict):
317
+ data.update(loaded)
259
318
  except Exception:
260
319
  pass
261
- local_sum = sum(days.values())
262
- srv_floor = 0
320
+ days = {
321
+ str(k): int(v)
322
+ for k, v in (data.get("days") or {}).items()
323
+ if str(k) >= cutoff_day and int(v or 0) > 0
324
+ }
325
+ if delta_measured > 0 and day_key >= cutoff_day:
326
+ days[day_key] = days.get(day_key, 0) + int(delta_measured)
327
+ data["days"] = days
328
+ if delta_measured > 0:
329
+ try:
330
+ self._qledger_write_atomic(mirror_path, data)
331
+ except Exception:
332
+ pass
333
+ local_sum = sum(days.values())
334
+ srv_floor = 0
335
+ try:
336
+ if time.time() - float(data.get("server_floor_ts", 0)) <= 30 * 86400:
337
+ srv_floor = int(data.get("server_floor", 0) or 0)
338
+ except Exception:
339
+ srv_floor = 0
340
+ return max(local_sum, srv_floor)
341
+
263
342
  try:
264
- if time.time() - float(data.get("server_floor_ts", 0)) <= 30 * 86400:
265
- srv_floor = int(data.get("server_floor", 0) or 0)
343
+ return self._qledger_locked(mirror_path, _do)
266
344
  except Exception:
267
- srv_floor = 0
268
- return max(local_sum, srv_floor)
345
+ return _do()
269
346
 
270
347
  def record_server_quota_floor(self, server_monthly_measured: int) -> None:
271
- """Persists a server-verified 30-day measured quota floor so client resets cannot roll back usage."""
348
+ """Persists a server-verified 30-day measured quota floor under file lock."""
272
349
  if int(server_monthly_measured or 0) <= 0:
273
350
  return
274
351
  mirror_path = self._quota_mirror_path()
275
- data: Dict[str, Any] = {"days": {}, "server_floor": 0, "server_floor_ts": 0}
276
- try:
277
- if os.path.exists(mirror_path):
278
- with open(mirror_path, "r", encoding="utf-8") as f:
279
- loaded = json.load(f)
280
- if isinstance(loaded, dict):
281
- data.update(loaded)
282
- except Exception:
283
- pass
284
- data["server_floor"] = max(int(data.get("server_floor", 0) or 0), int(server_monthly_measured))
285
- data["server_floor_ts"] = int(time.time())
352
+
353
+ def _do():
354
+ data: Dict[str, Any] = {"days": {}, "server_floor": 0, "server_floor_ts": 0}
355
+ try:
356
+ if os.path.exists(mirror_path):
357
+ with open(mirror_path, "r", encoding="utf-8") as f:
358
+ loaded = json.load(f)
359
+ if isinstance(loaded, dict):
360
+ data.update(loaded)
361
+ except Exception:
362
+ pass
363
+ data["server_floor"] = max(int(data.get("server_floor", 0) or 0), int(server_monthly_measured))
364
+ data["server_floor_ts"] = int(time.time())
365
+ try:
366
+ self._qledger_write_atomic(mirror_path, data)
367
+ except Exception:
368
+ pass
369
+
286
370
  try:
287
- os.makedirs(os.path.dirname(mirror_path), exist_ok=True)
288
- tmp_p = mirror_path + ".tmp"
289
- with open(tmp_p, "w", encoding="utf-8") as f:
290
- json.dump(data, f)
291
- os.replace(tmp_p, mirror_path)
371
+ self._qledger_locked(mirror_path, _do)
292
372
  except Exception:
293
- pass
373
+ _do()
294
374
 
295
375
  def record_event(
296
376
  self,
@@ -557,9 +637,10 @@ class MetricsTracker:
557
637
  for r in rows:
558
638
  ev = dict(r)
559
639
  try:
560
- ev["details"] = json.loads(ev["details"])
640
+ parsed = json.loads(ev["details"]) if ev.get("details") else {}
641
+ ev["details"] = parsed if isinstance(parsed, dict) else {}
561
642
  except Exception:
562
- pass
643
+ ev["details"] = {}
563
644
  events.append(ev)
564
645
  return events
565
646
 
@@ -580,9 +661,10 @@ class MetricsTracker:
580
661
  return None
581
662
  res = dict(row)
582
663
  try:
583
- res["details"] = json.loads(res["details"])
664
+ parsed = json.loads(res["details"]) if res.get("details") else {}
665
+ res["details"] = parsed if isinstance(parsed, dict) else {}
584
666
  except Exception:
585
- pass
667
+ res["details"] = {}
586
668
  return res
587
669
 
588
670
  def recalculate_sessions(self):
@@ -716,8 +798,13 @@ class MetricsTracker:
716
798
  cursor.execute(f"DELETE FROM events WHERE {combined_where}", params)
717
799
 
718
800
  cutoff_qd = (datetime.now() - timedelta(days=45)).strftime("%Y-%m-%d")
801
+ cutoff_banner = int(time.time()) - 30 * 86400
719
802
  with self._get_connection() as conn:
720
803
  conn.execute("DELETE FROM quota_daily WHERE day_key < ?", (cutoff_qd,))
804
+ try:
805
+ conn.execute("DELETE FROM quota_banner_state WHERE updated_at < ?", (cutoff_banner,))
806
+ except sqlite3.OperationalError:
807
+ pass
721
808
 
722
809
  if vacuum and prune_count > 0:
723
810
  self.vacuum()
package/src/paths.py CHANGED
@@ -18,6 +18,7 @@ active directory is identical for every agent on the machine.
18
18
 
19
19
  import os
20
20
  import shutil
21
+ import sqlite3
21
22
 
22
23
  PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
23
24
 
@@ -59,16 +60,22 @@ def resolve_data_dir() -> str:
59
60
  def _migrate_into(target: str) -> None:
60
61
  """One-time copy-if-absent carry-over from legacy and plugin directories.
61
62
 
62
- Copy-if-absent (never overwrite) keeps the target authoritative: source
63
- dirs then hold stale files, and re-copying them would roll state back.
64
- The tmp+os.replace dance keeps concurrent hook processes from observing a
65
- half-written file. Legacy <repo>/data is migrated first (historically
66
- authoritative); PLUGIN_DATA fills only the files it still lacks."""
63
+ Uses a sentinel marker (.migrated) once checked, and SQLite's online
64
+ backup API for metrics.db so active WAL transactions are never truncated."""
65
+ sentinel = os.path.join(target, ".migrated")
66
+ if os.path.isfile(sentinel):
67
+ return
67
68
  sources = [legacy_data_dir()]
68
69
  if plugin_data_dir():
69
70
  sources.append(plugin_data_dir())
70
71
  sources = [s for s in sources if os.path.isdir(s)]
71
72
  if not sources:
73
+ try:
74
+ os.makedirs(target, exist_ok=True)
75
+ with open(sentinel, "w", encoding="utf-8") as f:
76
+ f.write("1")
77
+ except Exception:
78
+ pass
72
79
  return
73
80
  try:
74
81
  os.makedirs(target, exist_ok=True)
@@ -79,8 +86,27 @@ def _migrate_into(target: str) -> None:
79
86
  src_file = os.path.join(source, name)
80
87
  dst_file = os.path.join(target, name)
81
88
  if os.path.isfile(src_file) and not os.path.exists(dst_file):
82
- tmp_file = dst_file + ".migrating"
89
+ tmp_file = f"{dst_file}.migrating.{os.getpid()}"
90
+ if name == "metrics.db":
91
+ try:
92
+ src_conn = sqlite3.connect(src_file, timeout=5.0)
93
+ dst_conn = sqlite3.connect(tmp_file, timeout=5.0)
94
+ try:
95
+ src_conn.backup(dst_conn)
96
+ finally:
97
+ dst_conn.close()
98
+ src_conn.close()
99
+ os.replace(tmp_file, dst_file)
100
+ continue
101
+ except Exception:
102
+ if os.path.exists(tmp_file):
103
+ try:
104
+ os.unlink(tmp_file)
105
+ except OSError:
106
+ pass
83
107
  shutil.copy2(src_file, tmp_file)
84
108
  os.replace(tmp_file, dst_file)
109
+ with open(sentinel, "w", encoding="utf-8") as f:
110
+ f.write("1")
85
111
  except Exception:
86
112
  pass
package/src/proxy.py CHANGED
@@ -12,7 +12,7 @@ import queue
12
12
  import threading
13
13
  import urllib.request
14
14
  import urllib.error
15
- from http.server import HTTPServer, BaseHTTPRequestHandler
15
+ from http.server import ThreadingHTTPServer, BaseHTTPRequestHandler
16
16
  from typing import Dict, Any, List
17
17
 
18
18
  BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
@@ -90,24 +90,36 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
90
90
  if not self._validate_origin():
91
91
  return
92
92
 
93
- tracker = MetricsTracker()
94
- dashboard = Dashboard(tracker)
93
+ if self.path == "/health":
94
+ payload_bytes = json.dumps({"status": "active", "proxy": "tokensafe"}).encode("utf-8")
95
+ self.send_response(200)
96
+ self.send_header("Content-Type", "application/json")
97
+ self.send_header("Content-Length", str(len(payload_bytes)))
98
+ self.end_headers()
99
+ self.wfile.write(payload_bytes)
100
+ return
95
101
 
96
102
  if self.path in ("/", "/dashboard", "/dashboard.html"):
97
- html = dashboard.render_html()
103
+ tracker = MetricsTracker()
104
+ html_bytes = Dashboard(tracker).render_html().encode("utf-8")
98
105
  self.send_response(200)
99
106
  self.send_header("Content-Type", "text/html; charset=utf-8")
107
+ self.send_header("Content-Length", str(len(html_bytes)))
100
108
  self.end_headers()
101
- self.wfile.write(html.encode("utf-8"))
109
+ self.wfile.write(html_bytes)
102
110
 
103
111
  elif self.path in ("/metrics", "/api/metrics"):
112
+ tracker = MetricsTracker()
104
113
  summary = tracker.get_summary()
114
+ summary_bytes = json.dumps(summary, indent=2).encode("utf-8")
105
115
  self.send_response(200)
106
116
  self.send_header("Content-Type", "application/json")
117
+ self.send_header("Content-Length", str(len(summary_bytes)))
107
118
  self.end_headers()
108
- self.wfile.write(json.dumps(summary, indent=2).encode("utf-8"))
119
+ self.wfile.write(summary_bytes)
109
120
 
110
121
  elif self.path in ("/api/events", "/events"):
122
+ tracker = MetricsTracker()
111
123
  self.send_response(200)
112
124
  self.send_header("Content-Type", "text/event-stream")
113
125
  self.send_header("Cache-Control", "no-cache")
@@ -136,15 +148,13 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
136
148
  BROADCASTER.unsubscribe(q)
137
149
  return
138
150
 
139
- elif self.path == "/health":
140
- self.send_response(200)
141
- self.send_header("Content-Type", "application/json")
142
- self.end_headers()
143
- self.wfile.write(json.dumps({"status": "active", "proxy": "tokensafe"}).encode("utf-8"))
144
-
145
151
  else:
152
+ err_bytes = b'{"error": "Not found"}'
146
153
  self.send_response(404)
154
+ self.send_header("Content-Type", "application/json")
155
+ self.send_header("Content-Length", str(len(err_bytes)))
147
156
  self.end_headers()
157
+ self.wfile.write(err_bytes)
148
158
 
149
159
  def do_POST(self):
150
160
  if not self._validate_origin():
@@ -171,15 +181,44 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
171
181
  except Exception:
172
182
  pass
173
183
 
184
+ def _read_request_body(self) -> bytes:
185
+ te = str(self.headers.get("Transfer-Encoding", "")).lower()
186
+ if "chunked" in te:
187
+ chunks: List[bytes] = []
188
+ while True:
189
+ line = self.rfile.readline()
190
+ if not line:
191
+ break
192
+ size_str = line.split(b";", 1)[0].strip()
193
+ chunk_size = int(size_str, 16)
194
+ if chunk_size == 0:
195
+ while True:
196
+ trailer = self.rfile.readline()
197
+ if not trailer or trailer in (b"\r\n", b"\n"):
198
+ break
199
+ break
200
+ chunks.append(self.rfile.read(chunk_size))
201
+ self.rfile.readline() # trailing CRLF
202
+ return b"".join(chunks)
203
+ content_len = max(0, int(self.headers.get("Content-Length", 0)))
204
+ return self.rfile.read(content_len)
205
+
206
+ def _send_json_error(self, status_code: int, message: str):
207
+ err_bytes = json.dumps({"error": message}).encode("utf-8")
208
+ self.send_response(status_code)
209
+ self.send_header("Content-Type", "application/json")
210
+ self.send_header("Content-Length", str(len(err_bytes)))
211
+ self.end_headers()
212
+ self.wfile.write(err_bytes)
213
+
174
214
  def handle_chat_completions(self):
175
215
  try:
176
- content_len = int(self.headers.get("Content-Length", 0))
177
- body = self.rfile.read(content_len)
216
+ body = self._read_request_body()
178
217
  payload = json.loads(body.decode("utf-8"))
218
+ if not isinstance(payload, dict):
219
+ raise ValueError("JSON body must be an object")
179
220
  except Exception as e:
180
- self.send_response(400)
181
- self.end_headers()
182
- self.wfile.write(json.dumps({"error": f"Invalid JSON payload: {e}"}).encode("utf-8"))
221
+ self._send_json_error(400, f"Invalid JSON payload: {e}")
183
222
  return
184
223
 
185
224
  proxy_tracker = MetricsTracker()
@@ -269,10 +308,6 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
269
308
 
270
309
  # 6. Prompt Cache Prefix & Tool Normalization (multi-breakpoint + deterministic ordering)
271
310
  if not is_quota_exceeded:
272
- if "tools" in payload and isinstance(payload["tools"], list):
273
- payload["tools"] = PromptCacheNormalizer.normalize_tools(
274
- payload["tools"], provider=provider, inject_cache_control=False
275
- )
276
311
  if messages:
277
312
  messages, cache_meta = PromptCacheNormalizer.normalize_messages(
278
313
  messages,
@@ -284,16 +319,23 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
284
319
  payload["tools"] = cache_meta["normalized_tools"]
285
320
  if provider == "openai" and cache_meta.get("prompt_cache_key"):
286
321
  payload.setdefault("prompt_cache_key", cache_meta["prompt_cache_key"])
322
+ elif "tools" in payload and isinstance(payload["tools"], list):
323
+ payload["tools"] = PromptCacheNormalizer.normalize_tools(
324
+ payload["tools"], provider=provider, inject_cache_control=False
325
+ )
287
326
 
288
327
  headers = {"Content-Type": "application/json"}
289
- if auth_header:
328
+ if provider == "anthropic":
329
+ x_api_key = self.headers.get("x-api-key", "") if hasattr(self.headers, "get") else ""
330
+ bearer_key = auth_header[7:].strip() if auth_header.lower().startswith("bearer ") else auth_header.strip()
331
+ api_key_val = x_api_key or bearer_key or resolved_key
332
+ if api_key_val:
333
+ headers["x-api-key"] = api_key_val
334
+ headers["anthropic-version"] = "2023-06-01"
335
+ elif auth_header:
290
336
  headers["Authorization"] = auth_header
291
337
  elif resolved_key:
292
- if "anthropic.com" in upstream_url:
293
- headers["x-api-key"] = resolved_key
294
- headers["anthropic-version"] = "2023-06-01"
295
- else:
296
- headers["Authorization"] = f"Bearer {resolved_key}"
338
+ headers["Authorization"] = f"Bearer {resolved_key}"
297
339
 
298
340
  req = urllib.request.Request(
299
341
  upstream_url,
@@ -301,48 +343,71 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
301
343
  headers=headers
302
344
  )
303
345
 
346
+ is_stream = bool(payload.get("stream"))
347
+ req_timeout = 120.0 if is_stream else 30.0
304
348
  try:
305
- with urllib.request.urlopen(req, timeout=30.0) as resp:
306
- resp_data = resp.read()
349
+ with urllib.request.urlopen(req, timeout=req_timeout) as resp:
307
350
  self.send_response(resp.status)
308
351
  for k, v in resp.getheaders():
309
352
  if k.lower() in ("content-type", "content-encoding"):
310
353
  self.send_header(k, v)
311
354
  if is_quota_exceeded:
312
355
  self.send_header("X-TokenSafe-Quota", "exceeded")
313
- LicenseManager.should_emit_quota_banner(proxy_tracker, session_id="proxy_session", every_n_turns=5)
314
- self.end_headers()
315
- self.wfile.write(resp_data)
316
356
 
317
- try:
318
- resp_json = json.loads(resp_data.decode("utf-8"))
319
- usage = resp_json.get("usage") or {}
320
- cached = (
321
- (usage.get("prompt_tokens_details") or {}).get("cached_tokens")
322
- or usage.get("cache_read_input_tokens")
323
- or usage.get("prompt_cache_hit_tokens")
324
- or 0
325
- )
326
- if cached:
327
- BROADCASTER.publish("cache_stats", {"provider": provider, "cached_tokens": int(cached)})
328
- except Exception:
329
- pass
357
+ if is_stream:
358
+ self.send_header("Cache-Control", "no-cache")
359
+ self.end_headers()
360
+ reader = getattr(resp, "read1", None) or resp.read
361
+ while True:
362
+ try:
363
+ chunk = reader(4096)
364
+ except TypeError:
365
+ chunk = resp.read()
366
+ if chunk:
367
+ self.wfile.write(chunk)
368
+ self.wfile.flush()
369
+ break
370
+ if not chunk:
371
+ break
372
+ self.wfile.write(chunk)
373
+ self.wfile.flush()
374
+ else:
375
+ resp_data = resp.read()
376
+ self.send_header("Content-Length", str(len(resp_data)))
377
+ self.end_headers()
378
+ self.wfile.write(resp_data)
379
+
380
+ try:
381
+ resp_json = json.loads(resp_data.decode("utf-8"))
382
+ usage = resp_json.get("usage") or {}
383
+ cached = (
384
+ (usage.get("prompt_tokens_details") or {}).get("cached_tokens")
385
+ or usage.get("cache_read_input_tokens")
386
+ or usage.get("prompt_cache_hit_tokens")
387
+ or 0
388
+ )
389
+ if cached:
390
+ BROADCASTER.publish("cache_stats", {"provider": provider, "cached_tokens": int(cached)})
391
+ except Exception:
392
+ pass
330
393
 
331
394
  # Broadcast live telemetry update to SSE dashboard subscribers
332
395
  try:
333
- tracker = MetricsTracker()
334
- summary = tracker.get_summary()
396
+ summary = proxy_tracker.get_summary()
335
397
  BROADCASTER.publish("stats_update", summary)
336
398
  except Exception:
337
399
  pass
338
400
  except urllib.error.HTTPError as e:
401
+ with e:
402
+ err_body = e.read()
403
+ ctype = e.headers.get("Content-Type", "application/json") if e.headers else "application/json"
339
404
  self.send_response(e.code)
405
+ self.send_header("Content-Type", ctype)
406
+ self.send_header("Content-Length", str(len(err_body)))
340
407
  self.end_headers()
341
- self.wfile.write(e.read())
408
+ self.wfile.write(err_body)
342
409
  except Exception as e:
343
- self.send_response(502)
344
- self.end_headers()
345
- self.wfile.write(json.dumps({"error": f"Upstream proxy error: {str(e)}"}).encode("utf-8"))
410
+ self._send_json_error(502, f"Upstream proxy error: {str(e)}")
346
411
 
347
412
  @staticmethod
348
413
  def _detect_provider(upstream_url: str) -> str:
@@ -396,7 +461,11 @@ def run_proxy(port: int = DEFAULT_PORT, host: str = DEFAULT_HOST):
396
461
  hubs_summary = f"initialized ({e})"
397
462
 
398
463
  server_address = (host, port)
399
- httpd = HTTPServer(server_address, TokenSafeProxyHandler)
464
+ class _TokenSafeThreadingServer(ThreadingHTTPServer):
465
+ daemon_threads = True
466
+ allow_reuse_address = True
467
+
468
+ httpd = _TokenSafeThreadingServer(server_address, TokenSafeProxyHandler)
400
469
  display_host = "localhost" if host in ("0.0.0.0", "", "127.0.0.1") else host
401
470
  print(f"\n⚡ TokenSafe Local AI Proxy running on: http://{display_host}:{port} (bound to {host})")
402
471
  print(f" Dashboard: http://{display_host}:{port}/dashboard")
@@ -115,7 +115,13 @@ class ScopedSearch:
115
115
 
116
116
  query = query.strip()
117
117
  scope = (scope or "all").lower().strip()
118
- max_results = min(100, max(1, int(max_results)))
118
+ if max_results is None or isinstance(max_results, bool):
119
+ max_results = 25
120
+ else:
121
+ try:
122
+ max_results = min(100, max(1, int(max_results)))
123
+ except (TypeError, ValueError):
124
+ max_results = 25
119
125
 
120
126
  # Compile search pattern
121
127
  flags = 0 if case_sensitive else re.IGNORECASE
@@ -148,13 +154,14 @@ class ScopedSearch:
148
154
  if total_scanned_files >= max_scanned_files:
149
155
  break
150
156
 
151
- # Prune ignored directories in-place
157
+ # Prune ignored directories in-place (allow safe dot-config dirs like .github/.claude/.gemini)
152
158
  dirnames[:] = [
153
- d for d in dirnames
154
- if d not in IGNORED_DIRS and not d.startswith(".")
159
+ d for d in sorted(dirnames)
160
+ if d not in IGNORED_DIRS and (not d.startswith(".") or d in (".github", ".gitlab", ".claude", ".gemini", ".agents"))
155
161
  ]
156
162
 
157
- for fname in filenames:
163
+ manifest_priority = {"package.json", "pyproject.toml", "cargo.toml", "go.mod"}
164
+ for fname in sorted(filenames, key=lambda s: (0 if s.lower() in manifest_priority else 1, s.lower())):
158
165
  if time.monotonic() - start_time > timeout_seconds:
159
166
  timed_out = True
160
167
  break
@@ -166,11 +173,14 @@ class ScopedSearch:
166
173
  if not cls.is_match_file(fname, rel_path, scope):
167
174
  continue
168
175
 
169
- # Skip non-regular files (FIFOs/pipes/devices) and files larger than 1MB
176
+ # Skip non-regular files (FIFOs/pipes/devices), >1MB files, and binary files (NUL byte probe)
170
177
  try:
171
178
  st = os.stat(full_path)
172
179
  if not stat.S_ISREG(st.st_mode) or st.st_size > 1024 * 1024:
173
180
  continue
181
+ with open(full_path, "rb") as bf:
182
+ if b"\x00" in bf.read(2048):
183
+ continue
174
184
  except OSError:
175
185
  continue
176
186
 
@@ -179,6 +189,8 @@ class ScopedSearch:
179
189
  try:
180
190
  with open(full_path, "r", encoding="utf-8", errors="replace") as f:
181
191
  for line_idx, line in enumerate(f, 1):
192
+ if len(line) > 8192:
193
+ continue
182
194
  if pattern.search(line):
183
195
  clean_line = line.strip()
184
196
  # Truncate long lines to 100 characters for compact token output