tokensafe 2.7.0 → 2.7.2
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 +139 -83
- 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 +65 -40
- package/src/diff_slicer.py +23 -17
- package/src/distiller.py +45 -17
- package/src/distiller_cache.py +80 -48
- package/src/environment_auditor.py +34 -12
- package/src/governor.py +83 -26
- package/src/graph_engine.py +1 -1
- 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 +206 -65
- 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/slicer.py +15 -3
- package/src/team_cache.py +89 -16
- package/src/telemetry_sync.py +110 -39
- package/src/tokenizer.py +24 -13
- package/src/treesitter_backend.py +1 -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)
|