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.
- package/bin/tokensafe +1 -1
- package/extensions/cursor-tokensafe/extension.js +21 -8
- package/hooks/claude_code_hook.py +13 -5
- package/hooks/cursor_hook.py +7 -4
- package/hooks/post_tool_use.py +24 -6
- package/hooks/pre_invocation.py +40 -27
- package/hooks/pre_tool_use.py +85 -83
- package/hooks/session_start.py +8 -4
- package/hooks/stop_hook.py +7 -4
- package/package.json +1 -1
- package/plugin.json +1 -1
- package/server.json +3 -3
- package/src/agent_firewall.py +38 -21
- package/src/cache_normalizer.py +39 -10
- package/src/cli.py +144 -91
- package/src/command_sanitizer.py +248 -136
- package/src/compactor.py +55 -25
- package/src/dashboard.py +17 -10
- package/src/deepseek_distiller.py +26 -17
- package/src/dependency_prefetcher.py +66 -41
- package/src/diff_slicer.py +23 -17
- package/src/distiller.py +45 -17
- package/src/distiller_cache.py +74 -47
- package/src/environment_auditor.py +34 -12
- package/src/governor.py +83 -26
- package/src/graph_engine.py +653 -140
- package/src/guard.py +316 -132
- package/src/history_compactor.py +57 -26
- package/src/installer.py +174 -131
- package/src/license_manager.py +12 -9
- package/src/loop_detector.py +68 -29
- package/src/mcp_server.py +200 -60
- package/src/metrics.py +141 -54
- package/src/paths.py +32 -6
- package/src/proxy.py +121 -52
- package/src/scoped_search.py +18 -6
- package/src/secret_redactor.py +78 -59
- package/src/skeletonizer.py +68 -13
- package/src/slicer.py +25 -7
- package/src/team_cache.py +10 -3
- package/src/telemetry_sync.py +110 -39
- package/src/tokenizer.py +24 -13
- package/src/treesitter_backend.py +539 -0
- package/src/version_checker.py +67 -32
- package/src/weekly_digest.py +6 -3
package/src/license_manager.py
CHANGED
|
@@ -351,8 +351,10 @@ class LicenseManager:
|
|
|
351
351
|
try:
|
|
352
352
|
if target_dir:
|
|
353
353
|
os.makedirs(target_dir, exist_ok=True)
|
|
354
|
-
|
|
354
|
+
tmp_path = f"{target_file}.tmp.{os.getpid()}"
|
|
355
|
+
with open(tmp_path, "w", encoding="utf-8") as f:
|
|
355
356
|
json.dump(record, f, indent=2)
|
|
357
|
+
os.replace(tmp_path, target_file)
|
|
356
358
|
except Exception:
|
|
357
359
|
pass
|
|
358
360
|
|
|
@@ -436,6 +438,7 @@ class LicenseManager:
|
|
|
436
438
|
if tracker is not None and hasattr(tracker, "_get_connection"):
|
|
437
439
|
try:
|
|
438
440
|
with tracker._get_connection() as conn:
|
|
441
|
+
conn.execute("BEGIN IMMEDIATE;")
|
|
439
442
|
conn.execute("""
|
|
440
443
|
CREATE TABLE IF NOT EXISTS quota_banner_state (
|
|
441
444
|
session_id TEXT PRIMARY KEY,
|
|
@@ -443,18 +446,18 @@ class LicenseManager:
|
|
|
443
446
|
updated_at INTEGER NOT NULL
|
|
444
447
|
)
|
|
445
448
|
""")
|
|
446
|
-
row = conn.execute(
|
|
447
|
-
"SELECT turns FROM quota_banner_state WHERE session_id = ?",
|
|
448
|
-
(sid,),
|
|
449
|
-
).fetchone()
|
|
450
|
-
turn_no = (int(row["turns"]) if row else 0) + 1
|
|
451
449
|
conn.execute("""
|
|
452
450
|
INSERT INTO quota_banner_state (session_id, turns, updated_at)
|
|
453
|
-
VALUES (?,
|
|
451
|
+
VALUES (?, 1, ?)
|
|
454
452
|
ON CONFLICT(session_id) DO UPDATE SET
|
|
455
|
-
turns =
|
|
453
|
+
turns = quota_banner_state.turns + 1,
|
|
456
454
|
updated_at = excluded.updated_at
|
|
457
|
-
""", (sid,
|
|
455
|
+
""", (sid, int(time.time())))
|
|
456
|
+
row = conn.execute(
|
|
457
|
+
"SELECT turns FROM quota_banner_state WHERE session_id = ?",
|
|
458
|
+
(sid,),
|
|
459
|
+
).fetchone()
|
|
460
|
+
turn_no = int(row["turns"]) if row else 1
|
|
458
461
|
return turn_no == 1 or (turn_no % n == 0)
|
|
459
462
|
except Exception:
|
|
460
463
|
pass
|
package/src/loop_detector.py
CHANGED
|
@@ -15,9 +15,21 @@ from src.paths import resolve_data_dir
|
|
|
15
15
|
class LoopDetector:
|
|
16
16
|
"""Tracks tool invocation signatures to detect hallucination loops."""
|
|
17
17
|
|
|
18
|
-
|
|
18
|
+
_DEFAULT_STATE_FILE = os.path.join(resolve_data_dir(), "loop_state.json")
|
|
19
|
+
STATE_FILE = _DEFAULT_STATE_FILE
|
|
19
20
|
MAX_IDENTICAL_REPEATS = 3
|
|
20
21
|
SESSION_TTL_SECONDS = 48 * 3600 # prune sessions idle for more than 2 days
|
|
22
|
+
MAX_SESSIONS = 2000
|
|
23
|
+
|
|
24
|
+
@classmethod
|
|
25
|
+
def _state_file(cls) -> str:
|
|
26
|
+
# Honor dynamic TOKENSAFE_DATA_DIR changes unless a test explicitly overrode STATE_FILE
|
|
27
|
+
if cls.STATE_FILE != cls._DEFAULT_STATE_FILE:
|
|
28
|
+
return cls.STATE_FILE
|
|
29
|
+
env_dir = os.environ.get("TOKENSAFE_DATA_DIR")
|
|
30
|
+
if env_dir:
|
|
31
|
+
return os.path.join(env_dir, "loop_state.json")
|
|
32
|
+
return cls.STATE_FILE
|
|
21
33
|
|
|
22
34
|
@classmethod
|
|
23
35
|
def _get_call_signature(cls, tool_name: str, args: Dict[str, Any]) -> str:
|
|
@@ -30,46 +42,62 @@ class LoopDetector:
|
|
|
30
42
|
def _locked_state(cls):
|
|
31
43
|
"""
|
|
32
44
|
Exclusive read-modify-write guard for the shared state file.
|
|
33
|
-
|
|
34
|
-
their increments overwrote each other and identical calls went undetected.
|
|
35
|
-
Uses fcntl on POSIX and degrades to lock-free (best effort) elsewhere.
|
|
45
|
+
Uses fcntl on POSIX and msvcrt on Windows.
|
|
36
46
|
"""
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
47
|
+
state_file = cls._state_file()
|
|
48
|
+
os.makedirs(os.path.dirname(state_file) or ".", exist_ok=True)
|
|
49
|
+
lock_path = state_file + ".lock"
|
|
50
|
+
handle = open(lock_path, "a+")
|
|
51
|
+
locked_posix = False
|
|
52
|
+
locked_win = False
|
|
41
53
|
try:
|
|
42
54
|
try:
|
|
43
55
|
import fcntl
|
|
44
56
|
fcntl.flock(handle.fileno(), fcntl.LOCK_EX)
|
|
45
|
-
|
|
57
|
+
locked_posix = True
|
|
46
58
|
except ImportError:
|
|
47
|
-
|
|
59
|
+
try:
|
|
60
|
+
import msvcrt
|
|
61
|
+
msvcrt.locking(handle.fileno(), msvcrt.LK_LOCK, 1)
|
|
62
|
+
locked_win = True
|
|
63
|
+
except Exception:
|
|
64
|
+
pass
|
|
48
65
|
yield
|
|
49
66
|
finally:
|
|
50
67
|
try:
|
|
51
|
-
if
|
|
68
|
+
if locked_posix:
|
|
52
69
|
import fcntl
|
|
53
70
|
fcntl.flock(handle.fileno(), fcntl.LOCK_UN)
|
|
71
|
+
elif locked_win:
|
|
72
|
+
import msvcrt
|
|
73
|
+
handle.seek(0)
|
|
74
|
+
msvcrt.locking(handle.fileno(), msvcrt.LK_UNLCK, 1)
|
|
54
75
|
except Exception:
|
|
55
76
|
pass
|
|
56
77
|
handle.close()
|
|
57
78
|
|
|
58
79
|
@classmethod
|
|
59
80
|
def _load_state(cls) -> Dict[str, Any]:
|
|
60
|
-
|
|
81
|
+
state_file = cls._state_file()
|
|
82
|
+
if os.path.exists(state_file):
|
|
61
83
|
try:
|
|
62
|
-
with open(
|
|
63
|
-
|
|
84
|
+
with open(state_file, "r", encoding="utf-8") as f:
|
|
85
|
+
data = json.load(f)
|
|
86
|
+
return data if isinstance(data, dict) else {}
|
|
64
87
|
except Exception:
|
|
65
88
|
return {}
|
|
66
89
|
return {}
|
|
67
90
|
|
|
68
91
|
@classmethod
|
|
69
92
|
def _save_state(cls, state: Dict[str, Any]):
|
|
93
|
+
state_file = cls._state_file()
|
|
70
94
|
try:
|
|
71
|
-
|
|
95
|
+
parent = os.path.dirname(state_file) or "."
|
|
96
|
+
os.makedirs(parent, exist_ok=True)
|
|
97
|
+
tmp_path = f"{state_file}.tmp.{os.getpid()}"
|
|
98
|
+
with open(tmp_path, "w", encoding="utf-8") as f:
|
|
72
99
|
json.dump(state, f)
|
|
100
|
+
os.replace(tmp_path, state_file)
|
|
73
101
|
except Exception:
|
|
74
102
|
pass
|
|
75
103
|
|
|
@@ -87,13 +115,27 @@ class LoopDetector:
|
|
|
87
115
|
with cls._locked_state():
|
|
88
116
|
state = cls._load_state()
|
|
89
117
|
|
|
90
|
-
# Prune stale sessions so the state file cannot grow unboundedly
|
|
118
|
+
# Prune stale or corrupted sessions so the state file cannot grow unboundedly
|
|
91
119
|
now = time.time()
|
|
92
|
-
stale = [
|
|
93
|
-
|
|
120
|
+
stale = []
|
|
121
|
+
for cid, s in state.items():
|
|
122
|
+
if not isinstance(s, dict):
|
|
123
|
+
stale.append(cid)
|
|
124
|
+
continue
|
|
125
|
+
try:
|
|
126
|
+
updated = float(s.get("updated", 0) or 0)
|
|
127
|
+
except (TypeError, ValueError):
|
|
128
|
+
stale.append(cid)
|
|
129
|
+
continue
|
|
130
|
+
if (now - updated) > cls.SESSION_TTL_SECONDS:
|
|
131
|
+
stale.append(cid)
|
|
94
132
|
for cid in stale:
|
|
95
133
|
state.pop(cid, None)
|
|
96
134
|
|
|
135
|
+
if len(state) > cls.MAX_SESSIONS:
|
|
136
|
+
ordered = sorted(state.items(), key=lambda kv: float((kv[1] or {}).get("updated", 0) or 0), reverse=True)
|
|
137
|
+
state = dict(ordered[: cls.MAX_SESSIONS])
|
|
138
|
+
|
|
97
139
|
session_state = state.get(conversation_id, {
|
|
98
140
|
"last_sig": "",
|
|
99
141
|
"repeat_count": 0,
|
|
@@ -123,14 +165,11 @@ class LoopDetector:
|
|
|
123
165
|
|
|
124
166
|
@classmethod
|
|
125
167
|
def reset_session(cls, conversation_id: str):
|
|
126
|
-
"""Clears state for a conversation."""
|
|
127
|
-
if os.path.exists(cls.
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
json.dump(state, f)
|
|
135
|
-
except Exception:
|
|
136
|
-
pass
|
|
168
|
+
"""Clears state for a conversation safely under lock."""
|
|
169
|
+
if not os.path.exists(cls._state_file()):
|
|
170
|
+
return
|
|
171
|
+
with cls._locked_state():
|
|
172
|
+
state = cls._load_state()
|
|
173
|
+
if conversation_id in state:
|
|
174
|
+
del state[conversation_id]
|
|
175
|
+
cls._save_state(state)
|
package/src/mcp_server.py
CHANGED
|
@@ -40,7 +40,7 @@ from src.license_manager import LicenseManager
|
|
|
40
40
|
|
|
41
41
|
SERVER_INFO = {
|
|
42
42
|
"name": "tokensafe-mcp",
|
|
43
|
-
"version": "2.
|
|
43
|
+
"version": "2.7.1"
|
|
44
44
|
}
|
|
45
45
|
|
|
46
46
|
# MCP client attribution: the initialize handshake carries clientInfo, which
|
|
@@ -284,10 +284,18 @@ def build_dir_tree(dir_path: str, max_depth: int = 2, max_entries: int = 80) ->
|
|
|
284
284
|
if not os.path.isdir(dir_path):
|
|
285
285
|
return f"Error: Path is not a directory: {dir_path}"
|
|
286
286
|
|
|
287
|
+
dirs_ignore_dots = {
|
|
288
|
+
".git", ".hg", ".svn", ".venv", ".cache", ".idea", ".vscode",
|
|
289
|
+
".next", ".turbo", ".pytest_cache", ".mypy_cache", ".DS_Store",
|
|
290
|
+
".system_generated", ".Trash",
|
|
291
|
+
}
|
|
292
|
+
safe_dot_prefixes = (".env.example", ".env.sample", ".env.template")
|
|
293
|
+
|
|
287
294
|
base_name = os.path.basename(os.path.abspath(dir_path)) or dir_path
|
|
288
295
|
lines = [f"📁 **{base_name}/** (max depth: {max_depth})"]
|
|
289
296
|
entries_count = 0
|
|
290
297
|
start_time = time.monotonic()
|
|
298
|
+
visited_real_dirs = {os.path.realpath(dir_path)}
|
|
291
299
|
|
|
292
300
|
def _traverse(curr_dir: str, prefix: str, current_depth: int):
|
|
293
301
|
nonlocal entries_count
|
|
@@ -305,14 +313,21 @@ def build_dir_tree(dir_path: str, max_depth: int = 2, max_entries: int = 80) ->
|
|
|
305
313
|
dirs = []
|
|
306
314
|
files = []
|
|
307
315
|
for it in items:
|
|
308
|
-
if it.startswith('.') and it not in SECRET_FILES and it != '.gitignore':
|
|
309
|
-
continue
|
|
310
316
|
full_p = os.path.join(curr_dir, it)
|
|
311
317
|
if os.path.isdir(full_p):
|
|
312
|
-
if it in IGNORE_DIRS:
|
|
318
|
+
if it in IGNORE_DIRS or it in dirs_ignore_dots:
|
|
319
|
+
continue
|
|
320
|
+
if it.startswith('.') and it not in (".github", ".gitlab", ".claude", ".gemini", ".agents", ".cursor", ".vscode-test"):
|
|
313
321
|
continue
|
|
314
322
|
dirs.append(it)
|
|
315
323
|
else:
|
|
324
|
+
if it in SECRET_FILES or it.startswith(".env.") and not it.endswith((".example", ".sample", ".template")):
|
|
325
|
+
files.append(it)
|
|
326
|
+
continue
|
|
327
|
+
if any(fnmatch.fnmatch(it, pat) for pat in IGNORE_FILES):
|
|
328
|
+
continue
|
|
329
|
+
if it.startswith('.') and it not in ('.gitignore', '.gitattributes', '.dockerignore', '.editorconfig', '.npmrc', '.nvmrc', '.python-version', '.prettierrc', '.eslintrc', '.eslintrc.json', '.eslintrc.js') and not any(it.startswith(p) for p in safe_dot_prefixes):
|
|
330
|
+
continue
|
|
316
331
|
files.append(it)
|
|
317
332
|
|
|
318
333
|
all_items = [(d, True) for d in dirs] + [(f, False) for f in files]
|
|
@@ -330,15 +345,18 @@ def build_dir_tree(dir_path: str, max_depth: int = 2, max_entries: int = 80) ->
|
|
|
330
345
|
|
|
331
346
|
if is_dir:
|
|
332
347
|
entries_count += 1
|
|
348
|
+
real_sub = os.path.realpath(item_path)
|
|
349
|
+
if real_sub in visited_real_dirs:
|
|
350
|
+
lines.append(f"{prefix}{pointer}📁 {name}/ [symlink cycle]")
|
|
351
|
+
continue
|
|
333
352
|
lines.append(f"{prefix}{pointer}📁 {name}/")
|
|
353
|
+
visited_real_dirs.add(real_sub)
|
|
334
354
|
_traverse(item_path, prefix + extension_prefix, current_depth + 1)
|
|
335
355
|
else:
|
|
336
|
-
if name in SECRET_FILES:
|
|
356
|
+
if name in SECRET_FILES or (name.startswith(".env.") and not name.endswith((".example", ".sample", ".template"))):
|
|
337
357
|
lines.append(f"{prefix}{pointer}🔒 {name} [PROTECTED SECRET]")
|
|
338
358
|
entries_count += 1
|
|
339
359
|
continue
|
|
340
|
-
if any(fnmatch.fnmatch(name, pat) for pat in IGNORE_FILES):
|
|
341
|
-
continue
|
|
342
360
|
try:
|
|
343
361
|
sz = os.path.getsize(item_path)
|
|
344
362
|
sz_str = format_file_size(sz)
|
|
@@ -363,8 +381,11 @@ def _resolve_project_root(args: dict) -> Tuple[Optional[str], Optional[str]]:
|
|
|
363
381
|
target_abs = os.path.abspath(target)
|
|
364
382
|
if os.path.isfile(target_abs):
|
|
365
383
|
target_abs = os.path.dirname(target_abs)
|
|
366
|
-
if target_abs
|
|
367
|
-
return
|
|
384
|
+
if target_abs in system_roots:
|
|
385
|
+
return None, f"Error: Refusing to scan system root or home directory '{target}'. Please provide a specific project directory."
|
|
386
|
+
if not os.path.isdir(target_abs):
|
|
387
|
+
return None, f"Error: project_path not found or not a directory: '{target}'."
|
|
388
|
+
return target_abs, None
|
|
368
389
|
|
|
369
390
|
# Check environment variables
|
|
370
391
|
for env_var in ("AGY_PROJECT_PATH", "WORKSPACE_FOLDER", "PROJECT_DIR", "PWD"):
|
|
@@ -437,6 +458,30 @@ class _SafeTrackerProxy:
|
|
|
437
458
|
except Exception:
|
|
438
459
|
return 0
|
|
439
460
|
|
|
461
|
+
def get_monthly_saved_tokens(self, *args, **kwargs):
|
|
462
|
+
try:
|
|
463
|
+
return self._inner.get_monthly_saved_tokens(*args, **kwargs)
|
|
464
|
+
except Exception:
|
|
465
|
+
return 0
|
|
466
|
+
|
|
467
|
+
def get_last_event(self, *args, **kwargs):
|
|
468
|
+
try:
|
|
469
|
+
return self._inner.get_last_event(*args, **kwargs)
|
|
470
|
+
except Exception:
|
|
471
|
+
return None
|
|
472
|
+
|
|
473
|
+
def get_summary(self, *args, **kwargs):
|
|
474
|
+
try:
|
|
475
|
+
return self._inner.get_summary(*args, **kwargs)
|
|
476
|
+
except Exception:
|
|
477
|
+
return {}
|
|
478
|
+
|
|
479
|
+
def get_recent_events(self, *args, **kwargs):
|
|
480
|
+
try:
|
|
481
|
+
return self._inner.get_recent_events(*args, **kwargs)
|
|
482
|
+
except Exception:
|
|
483
|
+
return []
|
|
484
|
+
|
|
440
485
|
def __getattr__(self, name):
|
|
441
486
|
return getattr(self._inner, name)
|
|
442
487
|
|
|
@@ -504,8 +549,58 @@ def _team_skeleton_prewarm(
|
|
|
504
549
|
pass
|
|
505
550
|
|
|
506
551
|
|
|
552
|
+
def _safe_int(value, default: int, lo: Optional[int] = None, hi: Optional[int] = None) -> int:
|
|
553
|
+
if value is None or isinstance(value, bool):
|
|
554
|
+
n = default
|
|
555
|
+
else:
|
|
556
|
+
try:
|
|
557
|
+
n = int(value)
|
|
558
|
+
except (TypeError, ValueError):
|
|
559
|
+
n = default
|
|
560
|
+
if lo is not None:
|
|
561
|
+
n = max(lo, n)
|
|
562
|
+
if hi is not None:
|
|
563
|
+
n = min(hi, n)
|
|
564
|
+
return n
|
|
565
|
+
|
|
566
|
+
|
|
567
|
+
def _is_binary_file(path: str, probe_bytes: int = 4096) -> bool:
|
|
568
|
+
try:
|
|
569
|
+
with open(path, "rb") as f:
|
|
570
|
+
chunk = f.read(probe_bytes)
|
|
571
|
+
return b"\x00" in chunk
|
|
572
|
+
except OSError:
|
|
573
|
+
return False
|
|
574
|
+
|
|
575
|
+
|
|
576
|
+
def _read_line_slice(path: str, start_line: Optional[int], end_line: Optional[int]) -> Tuple[Optional[str], Optional[str]]:
|
|
577
|
+
"""Reads 1-based [start_line..end_line] using bounded iteration. Returns (content, err_msg)."""
|
|
578
|
+
if start_line is not None and start_line < 1:
|
|
579
|
+
start_line = 1
|
|
580
|
+
if end_line is not None and end_line < 1:
|
|
581
|
+
return None, "end_line must be >= 1"
|
|
582
|
+
if start_line is not None and end_line is not None and start_line > end_line:
|
|
583
|
+
return None, f"start_line ({start_line}) cannot be greater than end_line ({end_line})"
|
|
584
|
+
|
|
585
|
+
s = 1 if start_line is None else start_line
|
|
586
|
+
selected: List[str] = []
|
|
587
|
+
total_seen = 0
|
|
588
|
+
with open(path, "r", encoding="utf-8", errors="replace") as f:
|
|
589
|
+
for idx, line in enumerate(f, 1):
|
|
590
|
+
total_seen = idx
|
|
591
|
+
if idx < s:
|
|
592
|
+
continue
|
|
593
|
+
if end_line is not None and idx > end_line:
|
|
594
|
+
break
|
|
595
|
+
selected.append(line)
|
|
596
|
+
if s > total_seen and total_seen > 0:
|
|
597
|
+
return None, f"start_line {s} is beyond end of file ({total_seen} lines)"
|
|
598
|
+
return "".join(selected), None
|
|
599
|
+
|
|
600
|
+
|
|
507
601
|
def _resolve_dep_mode(args: dict) -> Tuple[bool, str]:
|
|
508
|
-
|
|
602
|
+
raw_inc = args.get("include_deps")
|
|
603
|
+
inc_deps = True if raw_inc is None else bool(raw_inc)
|
|
509
604
|
if not inc_deps:
|
|
510
605
|
return False, "none"
|
|
511
606
|
raw_mode = str(args.get("dep_mode") or "").strip().lower()
|
|
@@ -526,10 +621,12 @@ def handle_tool_call(name: str, args: dict) -> dict:
|
|
|
526
621
|
symbol = (args.get("symbol") or "").strip()
|
|
527
622
|
_, eff_dep_mode = _resolve_dep_mode(args)
|
|
528
623
|
cache_sym = f"{symbol}@{eff_dep_mode}" if (symbol and eff_dep_mode != "signature") else symbol
|
|
529
|
-
|
|
624
|
+
is_ranged = args.get("start_line") is not None or args.get("end_line") is not None
|
|
625
|
+
is_quota_truncated = "[TokenSafe Community 500k limit reached:" in text_out or "// Quota exceeded" in text_out
|
|
626
|
+
if text_out and path and not is_ranged and not is_quota_truncated:
|
|
530
627
|
abs_path = os.path.abspath(path)
|
|
531
628
|
cur_hash = AgentFirewall._file_content_hash(abs_path)
|
|
532
|
-
if cur_hash
|
|
629
|
+
if cur_hash:
|
|
533
630
|
_IN_PROCESS_DELIVERED[(abs_path, symbol, eff_dep_mode)] = (cur_hash, _EPOCH_GEN)
|
|
534
631
|
# Never overwrite cached skeleton with a firewall header or pointer hit
|
|
535
632
|
if not text_out.startswith("// [TokenSafe Subagent Firewall:"):
|
|
@@ -573,37 +670,56 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
|
|
|
573
670
|
# Clamp explicit line ranges to sane bounds so bad indices can never produce
|
|
574
671
|
# empty output or negative-index slicing artifacts.
|
|
575
672
|
try:
|
|
576
|
-
if start_line is not None:
|
|
577
|
-
start_line =
|
|
578
|
-
|
|
673
|
+
if start_line is not None and not isinstance(start_line, bool):
|
|
674
|
+
start_line = int(start_line)
|
|
675
|
+
elif isinstance(start_line, bool):
|
|
676
|
+
raise TypeError("start_line cannot be bool")
|
|
677
|
+
if end_line is not None and not isinstance(end_line, bool):
|
|
579
678
|
end_line = int(end_line)
|
|
679
|
+
elif isinstance(end_line, bool):
|
|
680
|
+
raise TypeError("end_line cannot be bool")
|
|
580
681
|
except (TypeError, ValueError):
|
|
581
682
|
return _fallback_error("smart_read_file", "start_line/end_line must be integers")
|
|
582
683
|
|
|
684
|
+
if end_line is not None and end_line < 1:
|
|
685
|
+
return _fallback_error("smart_read_file", "end_line must be >= 1")
|
|
686
|
+
if start_line is not None:
|
|
687
|
+
start_line = max(1, start_line)
|
|
688
|
+
|
|
583
689
|
if not path or not os.path.exists(path):
|
|
584
690
|
return {"isError": True, "content": [{"type": "text", "text": f"File not found: {path}"}]}
|
|
585
691
|
try:
|
|
586
|
-
|
|
692
|
+
st = os.stat(path)
|
|
693
|
+
if not stat.S_ISREG(st.st_mode):
|
|
587
694
|
return _fallback_error("smart_read_file", f"path is not a regular file: {path}")
|
|
588
695
|
except OSError as e:
|
|
589
696
|
return _fallback_error("smart_read_file", f"cannot stat path: {e}")
|
|
590
697
|
|
|
698
|
+
if _is_binary_file(path):
|
|
699
|
+
return _fallback_error("smart_read_file", f"'{os.path.basename(path)}' appears to be a binary file")
|
|
700
|
+
|
|
591
701
|
# Community 500k quota reached: soft-degrade to bounded raw read (disable Graph/AST/Pointer/Team Cache)
|
|
592
702
|
if is_quota_exceeded:
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
if start_line > e_line:
|
|
598
|
-
return _fallback_error("smart_read_file", f"start_line {start_line} is beyond end of file ({len(lines)} lines)")
|
|
599
|
-
raw_chunk = "".join(lines[start_line - 1 : e_line])
|
|
703
|
+
if start_line is not None or end_line is not None:
|
|
704
|
+
raw_chunk, err = _read_line_slice(path, start_line, end_line)
|
|
705
|
+
if err:
|
|
706
|
+
return _fallback_error("smart_read_file", err)
|
|
600
707
|
else:
|
|
601
|
-
cap =
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
708
|
+
cap = 250
|
|
709
|
+
raw_lines: List[str] = []
|
|
710
|
+
total_seen = 0
|
|
711
|
+
with open(path, "r", encoding="utf-8", errors="replace") as f:
|
|
712
|
+
for idx, line in enumerate(f, 1):
|
|
713
|
+
total_seen = idx
|
|
714
|
+
if idx <= cap:
|
|
715
|
+
raw_lines.append(line)
|
|
716
|
+
elif idx == cap + 1:
|
|
717
|
+
pass
|
|
718
|
+
raw_chunk = "".join(raw_lines)
|
|
719
|
+
if total_seen > cap:
|
|
720
|
+
raw_chunk += f"\n// [TokenSafe Community 500k limit reached: showing raw lines 1-{cap} of {total_seen}. AST/graph slicing & pointer dedup are paused.]\n"
|
|
605
721
|
banner = _quota_banner_if_due(quota, tracker, _mcp_session_id())
|
|
606
|
-
return {"content": [{"type": "text", "text": banner + raw_chunk}]}
|
|
722
|
+
return {"content": [{"type": "text", "text": banner + (raw_chunk or "")}]}
|
|
607
723
|
|
|
608
724
|
abs_path = os.path.abspath(path)
|
|
609
725
|
sym_clean = (symbol or "").strip()
|
|
@@ -630,20 +746,15 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
|
|
|
630
746
|
if is_loop:
|
|
631
747
|
return {"isError": True, "content": [{"type": "text", "text": f"⚠️ {msg}"}]}
|
|
632
748
|
|
|
633
|
-
#
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
end_line = min(end_line, len(lines))
|
|
643
|
-
if start_line > end_line:
|
|
644
|
-
return _fallback_error("smart_read_file", f"start_line {start_line} is beyond end of file ({len(lines)} lines)")
|
|
645
|
-
content = "".join(lines[start_line - 1 : end_line])
|
|
646
|
-
return {"content": [{"type": "text", "text": (prefetch_block or "") + content}]}
|
|
749
|
+
# Explicit line range (handles single-bound start_line or end_line as well as both)
|
|
750
|
+
if start_line is not None or end_line is not None:
|
|
751
|
+
content, err = _read_line_slice(path, start_line, end_line)
|
|
752
|
+
if err:
|
|
753
|
+
return _fallback_error("smart_read_file", err)
|
|
754
|
+
prefetch_block = ""
|
|
755
|
+
if not sym_clean or eff_dep_mode == "full":
|
|
756
|
+
prefetch_block, _ = DependencyPrefetcher.prefetch_for_file(path)
|
|
757
|
+
return {"content": [{"type": "text", "text": (prefetch_block or "") + (content or "")}]}
|
|
647
758
|
|
|
648
759
|
if symbol:
|
|
649
760
|
# Team pre-warm hit: a teammate already skeletonized this symbol
|
|
@@ -660,6 +771,9 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
|
|
|
660
771
|
optimized_tokens=skel_t,
|
|
661
772
|
details={"file": os.path.basename(path), "symbol": symbol, "dep_mode": eff_dep_mode, "source": "team_cache"}
|
|
662
773
|
)
|
|
774
|
+
prefetch_block = ""
|
|
775
|
+
if eff_dep_mode == "full":
|
|
776
|
+
prefetch_block, _ = DependencyPrefetcher.prefetch_for_file(path)
|
|
663
777
|
header = f"// [TokenSafe Team-Cached Skeleton for '{symbol}' | shared by a teammate]\n"
|
|
664
778
|
return {"content": [{"type": "text", "text": (prefetch_block or "") + header + team_skel}]}
|
|
665
779
|
|
|
@@ -699,30 +813,49 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
|
|
|
699
813
|
dep_label = "Full body + 1-hop signature deps"
|
|
700
814
|
header = f"// [TokenSafe Graph-Guided Skeleton for '{symbol}' | {dep_label}]\n"
|
|
701
815
|
_team_skeleton_prewarm(path, symbol, graph_skel, saved, dep_mode=eff_dep_mode)
|
|
816
|
+
prefetch_block = ""
|
|
817
|
+
if eff_dep_mode == "full":
|
|
818
|
+
prefetch_block, _ = DependencyPrefetcher.prefetch_for_file(path)
|
|
702
819
|
return {"content": [{"type": "text", "text": (prefetch_block or "") + header + graph_skel}]}
|
|
703
820
|
except Exception:
|
|
704
821
|
pass
|
|
705
822
|
|
|
706
823
|
overwrite, metrics = ToolSlicer.optimize_read_file({"Path": path}, context_hint=symbol)
|
|
707
824
|
if overwrite:
|
|
708
|
-
with open(path, "r", encoding="utf-8", errors="replace") as f:
|
|
709
|
-
lines = f.readlines()
|
|
710
825
|
s_line = overwrite["StartLine"]
|
|
711
826
|
e_line = overwrite["EndLine"]
|
|
712
|
-
content =
|
|
827
|
+
content, _ = _read_line_slice(path, s_line, e_line)
|
|
828
|
+
prefetch_block = ""
|
|
829
|
+
if eff_dep_mode == "full":
|
|
830
|
+
prefetch_block, _ = DependencyPrefetcher.prefetch_for_file(path)
|
|
713
831
|
header = f"// [TOCP Targeted Window: lines {s_line}-{e_line} for '{symbol}']\n"
|
|
714
|
-
return {"content": [{"type": "text", "text": (prefetch_block or "") + header + content}]}
|
|
832
|
+
return {"content": [{"type": "text", "text": (prefetch_block or "") + header + (content or "")}]}
|
|
715
833
|
|
|
716
|
-
# Check AST skeleton
|
|
717
|
-
skel_path, orig_t, skel_t = Skeletonizer.get_skeleton_file(path)
|
|
834
|
+
# Check AST skeleton (preserves target_symbol body when symbol was given; avoids duplicate prefetch)
|
|
835
|
+
skel_path, orig_t, skel_t = Skeletonizer.get_skeleton_file(path, target_symbol=(symbol or None))
|
|
718
836
|
if skel_path and os.path.exists(skel_path):
|
|
719
837
|
with open(skel_path, "r", encoding="utf-8", errors="replace") as f:
|
|
720
838
|
content = f.read()
|
|
839
|
+
if orig_t > skel_t:
|
|
840
|
+
tracker.record_event(
|
|
841
|
+
session_id=_mcp_session_id(),
|
|
842
|
+
event_type="AST_SKELETON",
|
|
843
|
+
original_tokens=orig_t,
|
|
844
|
+
optimized_tokens=skel_t,
|
|
845
|
+
details={"target_file": os.path.basename(path), "saved_tokens": orig_t - skel_t}
|
|
846
|
+
)
|
|
721
847
|
return {"content": [{"type": "text", "text": content}]}
|
|
722
848
|
|
|
723
|
-
# Default read
|
|
724
|
-
|
|
725
|
-
|
|
849
|
+
# Default bounded read (avoid dumping multi-MB files raw)
|
|
850
|
+
prefetch_block, _ = DependencyPrefetcher.prefetch_for_file(path)
|
|
851
|
+
max_raw_bytes = 512 * 1024
|
|
852
|
+
if st.st_size > max_raw_bytes:
|
|
853
|
+
with open(path, "r", encoding="utf-8", errors="replace") as f:
|
|
854
|
+
content = f.read(max_raw_bytes)
|
|
855
|
+
content += f"\n// [TokenSafe: file truncated at 512KB ({st.st_size:,} bytes total). Use start_line/end_line or symbol to inspect specific sections.]\n"
|
|
856
|
+
else:
|
|
857
|
+
with open(path, "r", encoding="utf-8", errors="replace") as f:
|
|
858
|
+
content = f.read()
|
|
726
859
|
return {"content": [{"type": "text", "text": (prefetch_block or "") + content}]}
|
|
727
860
|
|
|
728
861
|
elif name == "compress_prompt":
|
|
@@ -986,7 +1119,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
|
|
|
986
1119
|
if is_quota_exceeded:
|
|
987
1120
|
banner = _quota_banner_if_due(quota, tracker, _mcp_session_id())
|
|
988
1121
|
return {"content": [{"type": "text", "text": banner + raw_diff}]}
|
|
989
|
-
max_ctx =
|
|
1122
|
+
max_ctx = _safe_int(args.get("max_context"), 2, lo=0, hi=50)
|
|
990
1123
|
sliced, orig_t, opt_t = DiffSlicer.slice_diff(raw_diff, max_context_lines=max_ctx)
|
|
991
1124
|
saved = max(0, orig_t - opt_t)
|
|
992
1125
|
if saved > 0:
|
|
@@ -1074,12 +1207,14 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
|
|
|
1074
1207
|
|
|
1075
1208
|
# Resolve path relative to current working directory or absolute
|
|
1076
1209
|
abs_path = os.path.abspath(path)
|
|
1210
|
+
if not os.path.isdir(abs_path):
|
|
1211
|
+
return _fallback_error("list_dir", f"directory not found: {abs_path}")
|
|
1077
1212
|
system_roots = {"/", "/Users", "/home", "/root", os.path.expanduser("~")}
|
|
1078
|
-
depth =
|
|
1213
|
+
depth = _safe_int(args.get("depth"), 2, lo=1, hi=4)
|
|
1079
1214
|
if abs_path in system_roots:
|
|
1080
1215
|
# Do not walk entire home dir or filesystem root deeply
|
|
1081
1216
|
depth = 1
|
|
1082
|
-
max_entries =
|
|
1217
|
+
max_entries = _safe_int(args.get("max_entries"), 80, lo=10, hi=150)
|
|
1083
1218
|
|
|
1084
1219
|
tree_output = build_dir_tree(abs_path, max_depth=depth, max_entries=max_entries)
|
|
1085
1220
|
tree_tokens = count_tokens(tree_output)
|
|
@@ -1111,7 +1246,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
|
|
|
1111
1246
|
return _fallback_error("scoped_search", err or "unspecified project_path")
|
|
1112
1247
|
target_path = resolved_path
|
|
1113
1248
|
|
|
1114
|
-
max_res = args.get("max_results", 25)
|
|
1249
|
+
max_res = _safe_int(args.get("max_results"), 25, lo=1, hi=100)
|
|
1115
1250
|
c_sens = bool(args.get("case_sensitive", False))
|
|
1116
1251
|
u_regex = bool(args.get("use_regex", False))
|
|
1117
1252
|
|
|
@@ -1210,10 +1345,13 @@ def run_mcp_server():
|
|
|
1210
1345
|
req = json.loads(line)
|
|
1211
1346
|
except Exception:
|
|
1212
1347
|
continue
|
|
1348
|
+
if not isinstance(req, dict):
|
|
1349
|
+
continue
|
|
1213
1350
|
|
|
1214
1351
|
msg_id = req.get("id")
|
|
1215
1352
|
method = req.get("method")
|
|
1216
|
-
|
|
1353
|
+
raw_params = req.get("params")
|
|
1354
|
+
params = raw_params if isinstance(raw_params, dict) else {}
|
|
1217
1355
|
|
|
1218
1356
|
# Notifications (no id, or notifications/*) must never receive JSON-RPC responses
|
|
1219
1357
|
if msg_id is None or (isinstance(method, str) and method.startswith("notifications/")):
|
|
@@ -1223,8 +1361,9 @@ def run_mcp_server():
|
|
|
1223
1361
|
|
|
1224
1362
|
if method == "initialize":
|
|
1225
1363
|
try:
|
|
1226
|
-
client_info =
|
|
1227
|
-
|
|
1364
|
+
client_info = params.get("clientInfo") or {}
|
|
1365
|
+
if isinstance(client_info, dict):
|
|
1366
|
+
_set_mcp_client(str(client_info.get("name") or ""))
|
|
1228
1367
|
except Exception:
|
|
1229
1368
|
pass
|
|
1230
1369
|
try:
|
|
@@ -1241,8 +1380,9 @@ def run_mcp_server():
|
|
|
1241
1380
|
_TOOLS_LISTED = True
|
|
1242
1381
|
response["result"] = {"tools": TOOLS}
|
|
1243
1382
|
elif method == "tools/call":
|
|
1244
|
-
tool_name = params.get("name"
|
|
1245
|
-
|
|
1383
|
+
tool_name = str(params.get("name") or "")
|
|
1384
|
+
raw_tool_args = params.get("arguments")
|
|
1385
|
+
tool_args = raw_tool_args if isinstance(raw_tool_args, dict) else {}
|
|
1246
1386
|
try:
|
|
1247
1387
|
response["result"] = _execute_with_timeout(tool_name, tool_args)
|
|
1248
1388
|
except Exception as e:
|