tokensafe 1.6.0 → 1.7.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.
- package/README.md +14 -0
- package/hooks/claude_code_hook.py +92 -0
- package/hooks/cursor_hook.py +85 -0
- package/package.json +1 -1
- package/plugin.json +1 -1
- package/server.json +3 -3
- package/src/adapter_core.py +167 -0
- package/src/installer.py +78 -0
- package/src/mcp_server.py +1 -1
- package/src/telemetry_sync.py +1 -1
- package/src/version_checker.py +1 -1
package/README.md
CHANGED
|
@@ -69,6 +69,20 @@ pure-Python path adds no measurable latency after the first hook invocation.
|
|
|
69
69
|
|
|
70
70
|
---
|
|
71
71
|
|
|
72
|
+
## 🪝 Universal Agent Hooks (Claude Code & Cursor)
|
|
73
|
+
|
|
74
|
+
Beyond MCP, TokenSafe ships **lifecycle-hook adapters** that run natively inside your agent's loop — installed automatically by `tokensafe setup`:
|
|
75
|
+
|
|
76
|
+
| Agent | Hook | What it does |
|
|
77
|
+
|---|---|---|
|
|
78
|
+
| **Claude Code** | `UserPromptSubmit` | Compacts the prompt into a TOCP S-expression and injects it as `additionalContext` (labeled *estimated* per [METRICS.md](METRICS.md)) |
|
|
79
|
+
| **Claude Code** | `PreToolUse` (Bash) | Denies secret-bearing and destructive commands; asks on TLS-verification bypasses |
|
|
80
|
+
| **Cursor** | `beforeShellExecution` | Same shell guard — deny secrets/destruction, ask on `-k`/`--insecure` |
|
|
81
|
+
| **Cursor** | `beforeReadFile` | Blocks lockfile/bundle/`dist/` dumps that would burn ~50k context tokens |
|
|
82
|
+
| **Codex CLI** | — | No lifecycle hooks yet; MCP + AGENTS.md remain the integration |
|
|
83
|
+
|
|
84
|
+
All adapters **fail open**: a crash never blocks the host agent (Cursor's block-on-invalid-JSON contract is explicitly honored — every error path prints valid allow-JSON).
|
|
85
|
+
|
|
72
86
|
## 🔌 Universal MCP Server Configuration
|
|
73
87
|
|
|
74
88
|
Connect TokenSafe directly to **Claude Desktop** (`claude_desktop_config.json`) or **Cursor** MCP Settings:
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""
|
|
3
|
+
TokenSafe adapter for Claude Code lifecycle hooks.
|
|
4
|
+
|
|
5
|
+
Registered via ~/.claude/settings.json:
|
|
6
|
+
UserPromptSubmit -> compacts the prompt and INJECTS the TOCP form as
|
|
7
|
+
additionalContext (verified inject point in the
|
|
8
|
+
official Claude Code hooks schema).
|
|
9
|
+
PreToolUse (Bash) -> denies secret-bearing / destructive commands,
|
|
10
|
+
asks on TLS-verification bypasses.
|
|
11
|
+
|
|
12
|
+
Contract: stdin = one JSON payload, stdout = one JSON response.
|
|
13
|
+
Fail-open: any internal error emits `{}` (Claude treats empty stdout as allow).
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
import sys
|
|
17
|
+
import json
|
|
18
|
+
import os
|
|
19
|
+
|
|
20
|
+
HOOK_DIR = os.path.dirname(os.path.abspath(__file__))
|
|
21
|
+
PROJECT_ROOT = os.path.dirname(HOOK_DIR)
|
|
22
|
+
if PROJECT_ROOT not in sys.path:
|
|
23
|
+
sys.path.insert(0, PROJECT_ROOT)
|
|
24
|
+
|
|
25
|
+
from src.adapter_core import compact_for_injection, guard_command
|
|
26
|
+
|
|
27
|
+
AGENT = "claude_code"
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def handle(event: str, payload: dict) -> dict:
|
|
31
|
+
session_id = str(payload.get("session_id") or "") or f"hook_{AGENT}"
|
|
32
|
+
|
|
33
|
+
if event == "UserPromptSubmit":
|
|
34
|
+
prompt = str(payload.get("prompt") or "")
|
|
35
|
+
context, meta = compact_for_injection(prompt, AGENT, session_id)
|
|
36
|
+
if context and meta.get("compacted"):
|
|
37
|
+
return {
|
|
38
|
+
"hookSpecificOutput": {
|
|
39
|
+
"hookEventName": "UserPromptSubmit",
|
|
40
|
+
"additionalContext": (
|
|
41
|
+
f"{context}\n"
|
|
42
|
+
f"(TokenSafe: compacted ~{meta['saved_tokens']} prompt tokens, "
|
|
43
|
+
f"-{meta.get('reduction_pct', 0)}% — original intent preserved.)"
|
|
44
|
+
),
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
return {}
|
|
48
|
+
|
|
49
|
+
if event == "PreToolUse":
|
|
50
|
+
tool = str(payload.get("tool_name") or "")
|
|
51
|
+
tool_input = payload.get("tool_input") or {}
|
|
52
|
+
if tool in ("Bash", "Shell", "bash"):
|
|
53
|
+
command = str(tool_input.get("command") or "")
|
|
54
|
+
verdict = guard_command(command, AGENT, session_id)
|
|
55
|
+
if verdict["decision"] == "deny":
|
|
56
|
+
return {
|
|
57
|
+
"hookSpecificOutput": {
|
|
58
|
+
"hookEventName": "PreToolUse",
|
|
59
|
+
"permissionDecision": "deny",
|
|
60
|
+
"permissionDecisionReason": verdict["reason"],
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
if verdict["decision"] == "ask":
|
|
64
|
+
return {
|
|
65
|
+
"hookSpecificOutput": {
|
|
66
|
+
"hookEventName": "PreToolUse",
|
|
67
|
+
"permissionDecision": "ask",
|
|
68
|
+
"permissionDecisionReason": verdict["reason"],
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
return {}
|
|
72
|
+
|
|
73
|
+
return {}
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def main():
|
|
77
|
+
try:
|
|
78
|
+
raw = sys.stdin.read()
|
|
79
|
+
payload = json.loads(raw) if raw.strip() else {}
|
|
80
|
+
except Exception:
|
|
81
|
+
print(json.dumps({}))
|
|
82
|
+
return
|
|
83
|
+
event = str(payload.get("hook_event_name") or "")
|
|
84
|
+
try:
|
|
85
|
+
response = handle(event, payload if isinstance(payload, dict) else {})
|
|
86
|
+
except Exception:
|
|
87
|
+
response = {}
|
|
88
|
+
print(json.dumps(response))
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
if __name__ == "__main__":
|
|
92
|
+
main()
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""
|
|
3
|
+
TokenSafe adapter for Cursor agent hooks (~/.cursor/hooks.json).
|
|
4
|
+
|
|
5
|
+
Honest capability matrix (per official Cursor hooks docs):
|
|
6
|
+
beforeShellExecution -> allow/deny/ask: blocks secret-bearing,
|
|
7
|
+
destructive and TLS-bypassing commands.
|
|
8
|
+
beforeReadFile -> allow/deny: blocks lockfile/bundle/dist dumps
|
|
9
|
+
that would burn ~50k context tokens.
|
|
10
|
+
beforeSubmitPrompt -> allow/deny ONLY (no injection in Cursor yet):
|
|
11
|
+
records nothing, always allows. Kept as a no-op
|
|
12
|
+
so the hook wiring is future-proof.
|
|
13
|
+
stop / afterFileEdit -> observational no-ops.
|
|
14
|
+
|
|
15
|
+
IMPORTANT: Cursor BLOCKS the action when a hook prints invalid JSON.
|
|
16
|
+
Fail-open here means printing a valid per-event ALLOW response from the
|
|
17
|
+
exception handler, never an empty string.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
import sys
|
|
21
|
+
import json
|
|
22
|
+
import os
|
|
23
|
+
|
|
24
|
+
HOOK_DIR = os.path.dirname(os.path.abspath(__file__))
|
|
25
|
+
PROJECT_ROOT = os.path.dirname(HOOK_DIR)
|
|
26
|
+
if PROJECT_ROOT not in sys.path:
|
|
27
|
+
sys.path.insert(0, PROJECT_ROOT)
|
|
28
|
+
|
|
29
|
+
from src.adapter_core import guard_command, guard_read
|
|
30
|
+
|
|
31
|
+
AGENT = "cursor"
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _allow(event: str) -> dict:
|
|
35
|
+
if event == "beforeSubmitPrompt":
|
|
36
|
+
return {"continue": True}
|
|
37
|
+
return {"permission": "allow"}
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def handle(event: str, payload: dict) -> dict:
|
|
41
|
+
session_id = str(payload.get("conversation_id") or payload.get("session_id") or "") or f"hook_{AGENT}"
|
|
42
|
+
|
|
43
|
+
if event == "beforeShellExecution":
|
|
44
|
+
command = str(payload.get("command") or "")
|
|
45
|
+
verdict = guard_command(command, AGENT, session_id)
|
|
46
|
+
if verdict["decision"] == "deny":
|
|
47
|
+
return {"permission": "deny", "user_message": verdict["reason"]}
|
|
48
|
+
if verdict["decision"] == "ask":
|
|
49
|
+
return {"permission": "ask", "agent_message": verdict["reason"]}
|
|
50
|
+
return {"permission": "allow"}
|
|
51
|
+
|
|
52
|
+
if event == "beforeReadFile":
|
|
53
|
+
file_path = str(payload.get("file_path") or "")
|
|
54
|
+
verdict = guard_read(file_path, AGENT, session_id)
|
|
55
|
+
if verdict["decision"] == "deny":
|
|
56
|
+
return {"permission": "deny", "user_message": verdict["reason"]}
|
|
57
|
+
return {"permission": "allow"}
|
|
58
|
+
|
|
59
|
+
if event == "beforeSubmitPrompt":
|
|
60
|
+
# Cursor cannot inject context (allow/deny only). Nothing honest to
|
|
61
|
+
# record: the model still sees the full prompt. Always allow.
|
|
62
|
+
return {"continue": True}
|
|
63
|
+
|
|
64
|
+
return _allow(event)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def main():
|
|
68
|
+
try:
|
|
69
|
+
raw = sys.stdin.read()
|
|
70
|
+
payload = json.loads(raw) if raw.strip() else {}
|
|
71
|
+
except Exception:
|
|
72
|
+
print(json.dumps({}))
|
|
73
|
+
return
|
|
74
|
+
event = str(payload.get("hook_event_name") or "")
|
|
75
|
+
try:
|
|
76
|
+
response = handle(event, payload if isinstance(payload, dict) else {})
|
|
77
|
+
except Exception:
|
|
78
|
+
response = _allow(event)
|
|
79
|
+
if not isinstance(response, dict) or not response:
|
|
80
|
+
response = _allow(event)
|
|
81
|
+
print(json.dumps(response))
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
if __name__ == "__main__":
|
|
85
|
+
main()
|
package/package.json
CHANGED
package/plugin.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "agy-token-optimizer",
|
|
3
3
|
"displayName": "TokenSafe",
|
|
4
|
-
"version": "1.
|
|
4
|
+
"version": "1.7.0",
|
|
5
5
|
"description": "Zero-Loss Token Economy & Context Optimizer for AI Agents. Compresses prompts, slices AST/tool outputs, and prevents stuck loops.",
|
|
6
6
|
"logo": "assets/logo.svg",
|
|
7
7
|
"author": {
|
package/server.json
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"name": "dev.tokensafe/tokensafe",
|
|
4
4
|
"title": "TokenSafe",
|
|
5
5
|
"description": "Cut AI coding agent token usage up to 90% via AST slicing, dependency graphs & security guards.",
|
|
6
|
-
"version": "1.
|
|
6
|
+
"version": "1.7.0",
|
|
7
7
|
"websiteUrl": "https://tokensafe.dev",
|
|
8
8
|
"repository": {
|
|
9
9
|
"url": "https://github.com/NekoSin4eG/tokensafe",
|
|
@@ -30,7 +30,7 @@
|
|
|
30
30
|
"registryType": "npm",
|
|
31
31
|
"registryBaseUrl": "https://registry.npmjs.org",
|
|
32
32
|
"identifier": "tokensafe",
|
|
33
|
-
"version": "1.
|
|
33
|
+
"version": "1.7.0",
|
|
34
34
|
"runtimeHint": "npx",
|
|
35
35
|
"transport": {
|
|
36
36
|
"type": "stdio"
|
|
@@ -46,7 +46,7 @@
|
|
|
46
46
|
"registryType": "pypi",
|
|
47
47
|
"registryBaseUrl": "https://pypi.org",
|
|
48
48
|
"identifier": "tokensafe",
|
|
49
|
-
"version": "1.
|
|
49
|
+
"version": "1.7.0",
|
|
50
50
|
"runtimeHint": "uvx",
|
|
51
51
|
"transport": {
|
|
52
52
|
"type": "stdio"
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Shared core for cross-agent lifecycle-hook adapters (Claude Code, Cursor, ZCode).
|
|
3
|
+
|
|
4
|
+
Design rules (see METRICS.md):
|
|
5
|
+
- Savings are only recorded for REAL reductions: injected TOCP prompts are
|
|
6
|
+
labeled estimated; blocked reads/commands are measured (the model never
|
|
7
|
+
receives the blocked bytes).
|
|
8
|
+
- Adapters ALWAYS fail open: an adapter crash must never block the host agent.
|
|
9
|
+
(Cursor additionally blocks on invalid JSON, so adapters return valid
|
|
10
|
+
allow-JSON from the exception handler.)
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
import os
|
|
14
|
+
import sys
|
|
15
|
+
import re
|
|
16
|
+
import json
|
|
17
|
+
from typing import Dict, Any, Optional, Tuple
|
|
18
|
+
|
|
19
|
+
PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
20
|
+
if PROJECT_ROOT not in sys.path:
|
|
21
|
+
sys.path.insert(0, PROJECT_ROOT)
|
|
22
|
+
|
|
23
|
+
# High-precision deny patterns: secrets and irreversible destruction only.
|
|
24
|
+
_SECRET_PATTERNS = [
|
|
25
|
+
r"sk_live_[0-9a-zA-Z]{10,}",
|
|
26
|
+
r"AKIA[0-9A-Z]{16}",
|
|
27
|
+
r"ghp_[0-9a-zA-Z]{30,}",
|
|
28
|
+
r"xox[baprs]-[0-9a-zA-Z-]{10,}",
|
|
29
|
+
r"-----BEGIN [A-Z ]*PRIVATE KEY-----",
|
|
30
|
+
]
|
|
31
|
+
_DESTRUCTIVE_PATTERNS = [
|
|
32
|
+
r"rm\s+(-[a-zA-Z]*\s+)*-?[rf]{2,}[a-zA-Z]*\s+(--\s+)?/(?:\s|$)", # rm -rf /
|
|
33
|
+
r"rm\s+(-[a-zA-Z]*\s+)*-?[rf]{2,}[a-zA-Z]*\s+~(?:/\s*)?(?:\s|$)", # rm -rf ~
|
|
34
|
+
r"dd\s+.*of=/dev/[sd]",
|
|
35
|
+
r"mkfs\.\w+",
|
|
36
|
+
r"chmod\s+-R\s+777\s+/(?:\s|$)",
|
|
37
|
+
r":\(\)\{.*\};:", # fork bomb
|
|
38
|
+
]
|
|
39
|
+
_TLS_BYPASS_PATTERNS = [
|
|
40
|
+
r"curl\s+(-[a-zA-Z]+\s+)*-k\b",
|
|
41
|
+
r"curl\s+.*--insecure",
|
|
42
|
+
r"NODE_TLS_REJECT_UNAUTHORIZED\s*=\s*0",
|
|
43
|
+
r"wget\s+.*--no-check-certificate",
|
|
44
|
+
]
|
|
45
|
+
|
|
46
|
+
# Lockfiles/junk that must never be dumped into an agent context.
|
|
47
|
+
_JUNK_READ_PATTERNS = [
|
|
48
|
+
r"(^|/)(bun\.lock|package-lock\.json|pnpm-lock\.yaml|yarn\.lock|Cargo\.lock|go\.sum|composer\.lock)$",
|
|
49
|
+
r"\.(min\.js|min\.css|bundle\.js|map)$",
|
|
50
|
+
r"(^|/)dist/",
|
|
51
|
+
r"(^|/)node_modules/",
|
|
52
|
+
]
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _get_tracker():
|
|
56
|
+
try:
|
|
57
|
+
from src.metrics import MetricsTracker
|
|
58
|
+
return MetricsTracker()
|
|
59
|
+
except Exception:
|
|
60
|
+
return None
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def compact_for_injection(prompt: str, agent: str, session_id: str) -> Tuple[str, Dict[str, Any]]:
|
|
64
|
+
"""Compacts a user prompt into its TOCP form for context injection.
|
|
65
|
+
|
|
66
|
+
Returns (context_text, meta). context_text is '' when compaction is not
|
|
67
|
+
worthwhile. Savings are recorded as estimated: the compressed form is
|
|
68
|
+
injected alongside the original (no verified replace in host agents)."""
|
|
69
|
+
meta: Dict[str, Any] = {"agent": agent, "compacted": False}
|
|
70
|
+
if not prompt or len(prompt.strip()) < 5:
|
|
71
|
+
return "", meta
|
|
72
|
+
try:
|
|
73
|
+
from src.compactor import PromptCompactor
|
|
74
|
+
from src.tokenizer import count_tokens
|
|
75
|
+
compaction = PromptCompactor.compact(prompt, enable_deepseek=False)
|
|
76
|
+
saved = compaction.get("saved_tokens", 0)
|
|
77
|
+
if saved < 5:
|
|
78
|
+
return "", meta
|
|
79
|
+
tracker = _get_tracker()
|
|
80
|
+
if tracker:
|
|
81
|
+
try:
|
|
82
|
+
tracker.record_event(
|
|
83
|
+
session_id=session_id or f"hook_{agent}",
|
|
84
|
+
event_type="PROMPT",
|
|
85
|
+
original_tokens=compaction["original_tokens"],
|
|
86
|
+
optimized_tokens=compaction["compact_tokens"],
|
|
87
|
+
details={"agent": agent, "mode": "hook_inject", "tier": compaction.get("tier", "REGEX")},
|
|
88
|
+
)
|
|
89
|
+
except Exception:
|
|
90
|
+
pass
|
|
91
|
+
meta.update({"compacted": True, "saved_tokens": saved, "reduction_pct": compaction.get("reduction_pct", 0)})
|
|
92
|
+
return f"[TOCP Compressed Intent]: {compaction['compact_text']}", meta
|
|
93
|
+
except Exception:
|
|
94
|
+
return "", meta
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def guard_command(command: str, agent: str, session_id: str = "") -> Dict[str, Any]:
|
|
98
|
+
"""Pre-execution shell guard. Returns:
|
|
99
|
+
{decision: allow|deny|ask, reason, saved_tokens} where saved_tokens is the
|
|
100
|
+
MEASURED mass of blocked output (0 for allowed commands)."""
|
|
101
|
+
result = {"decision": "allow", "reason": "", "saved_tokens": 0}
|
|
102
|
+
if not command or not command.strip():
|
|
103
|
+
return result
|
|
104
|
+
cmd = command.strip()
|
|
105
|
+
text = cmd
|
|
106
|
+
|
|
107
|
+
def blocked(kind: str, reason: str, decision: str = "deny"):
|
|
108
|
+
est = max(50, len(cmd) // 4) # blocked mass never reaches the model
|
|
109
|
+
tracker = _get_tracker()
|
|
110
|
+
if tracker:
|
|
111
|
+
try:
|
|
112
|
+
tracker.record_event(
|
|
113
|
+
session_id=session_id or f"hook_{agent}",
|
|
114
|
+
event_type=f"GUARD_{kind}",
|
|
115
|
+
original_tokens=est,
|
|
116
|
+
optimized_tokens=0,
|
|
117
|
+
details={"agent": agent, "command": cmd[:120]},
|
|
118
|
+
)
|
|
119
|
+
except Exception:
|
|
120
|
+
pass
|
|
121
|
+
result.update({"decision": decision, "reason": reason, "saved_tokens": est})
|
|
122
|
+
|
|
123
|
+
for pat in _SECRET_PATTERNS:
|
|
124
|
+
if re.search(pat, text):
|
|
125
|
+
blocked("SECRET", f"Blocked: command contains a hardcoded secret ({pat[:12]}... pattern)")
|
|
126
|
+
return result
|
|
127
|
+
for pat in _DESTRUCTIVE_PATTERNS:
|
|
128
|
+
if re.search(pat, text):
|
|
129
|
+
blocked("DESTRUCTIVE", "Blocked: irreversible/destructive operation")
|
|
130
|
+
return result
|
|
131
|
+
for pat in _TLS_BYPASS_PATTERNS:
|
|
132
|
+
if re.search(pat, text):
|
|
133
|
+
blocked("TLS_VERIFY_BYPASS", "Certificate verification disabled — confirm this is intentional", decision="ask")
|
|
134
|
+
return result
|
|
135
|
+
return result
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def guard_read(file_path: str, agent: str, session_id: str = "") -> Dict[str, Any]:
|
|
139
|
+
"""Pre-read guard: denies lockfiles/bundles/dist junk that would burn the
|
|
140
|
+
context window. Blocked reads are recorded as measured savings."""
|
|
141
|
+
result = {"decision": "allow", "reason": "", "saved_tokens": 0}
|
|
142
|
+
if not file_path:
|
|
143
|
+
return result
|
|
144
|
+
normalized = file_path.replace("\\", "/")
|
|
145
|
+
for pat in _JUNK_READ_PATTERNS:
|
|
146
|
+
if re.search(pat, normalized):
|
|
147
|
+
est = 4000 # typical lockfile dump size floor
|
|
148
|
+
tracker = _get_tracker()
|
|
149
|
+
if tracker:
|
|
150
|
+
try:
|
|
151
|
+
tracker.record_event(
|
|
152
|
+
session_id=session_id or f"hook_{agent}",
|
|
153
|
+
event_type="GUARD_JUNK_READ",
|
|
154
|
+
original_tokens=est,
|
|
155
|
+
optimized_tokens=0,
|
|
156
|
+
details={"agent": agent, "file": os.path.basename(normalized)},
|
|
157
|
+
)
|
|
158
|
+
except Exception:
|
|
159
|
+
pass
|
|
160
|
+
result.update({
|
|
161
|
+
"decision": "deny",
|
|
162
|
+
"reason": f"TokenSafe: '{os.path.basename(normalized)}' is machine-generated bulk "
|
|
163
|
+
f"(~{est // 1000}k tokens). Inspect it via 'tokensafe:scoped_search' or grep a symbol instead.",
|
|
164
|
+
"saved_tokens": est,
|
|
165
|
+
})
|
|
166
|
+
return result
|
|
167
|
+
return result
|
package/src/installer.py
CHANGED
|
@@ -135,6 +135,72 @@ class AgentInstaller:
|
|
|
135
135
|
}
|
|
136
136
|
return detected
|
|
137
137
|
|
|
138
|
+
@staticmethod
|
|
139
|
+
def _tokensafe_hook_command(script_name: str) -> str:
|
|
140
|
+
"""Shell command string for a bundled hook adapter (space-safe)."""
|
|
141
|
+
script = os.path.join(PROJECT_ROOT, "hooks", script_name)
|
|
142
|
+
return f"{shlex.quote(PYTHON_BIN)} {shlex.quote(script)}"
|
|
143
|
+
|
|
144
|
+
@classmethod
|
|
145
|
+
def install_hooks_config(cls, agent_key: str) -> Tuple[bool, str]:
|
|
146
|
+
"""Registers TokenSafe lifecycle-hook adapters with agents that support them.
|
|
147
|
+
Claude Code: UserPromptSubmit (TOCP injection) + PreToolUse (shell guard).
|
|
148
|
+
Cursor: beforeShellExecution / beforeReadFile guards.
|
|
149
|
+
Codex has no lifecycle hooks (MCP + AGENTS.md remain the integration)."""
|
|
150
|
+
if agent_key == "codex":
|
|
151
|
+
return False, "Codex CLI has no lifecycle hooks — MCP + AGENTS.md stay the integration"
|
|
152
|
+
if agent_key not in ("claude_code", "cursor"):
|
|
153
|
+
return False, "hooks not applicable for this agent"
|
|
154
|
+
|
|
155
|
+
claude_cmd = cls._tokensafe_hook_command("claude_code_hook.py")
|
|
156
|
+
cursor_cmd = cls._tokensafe_hook_command("cursor_hook.py")
|
|
157
|
+
|
|
158
|
+
if agent_key == "claude_code":
|
|
159
|
+
info = AGENTS_REGISTRY["claude_code"]
|
|
160
|
+
config_file = info.get("agents_md_path", "").replace("CLAUDE.md", "settings.json")
|
|
161
|
+
config_file = os.path.join(HOME, ".claude", "settings.json")
|
|
162
|
+
os.makedirs(os.path.dirname(config_file), exist_ok=True)
|
|
163
|
+
data: Dict[str, Any] = {}
|
|
164
|
+
if os.path.exists(config_file):
|
|
165
|
+
try:
|
|
166
|
+
with open(config_file, "r", encoding="utf-8") as f:
|
|
167
|
+
data = json.load(f)
|
|
168
|
+
except Exception:
|
|
169
|
+
data = {}
|
|
170
|
+
hooks = data.get("hooks") if isinstance(data.get("hooks"), dict) else {}
|
|
171
|
+
blob = json.dumps(hooks)
|
|
172
|
+
if "claude_code_hook.py" in blob:
|
|
173
|
+
return True, "TokenSafe Claude Code hooks already registered"
|
|
174
|
+
prompt_entry = {"hooks": [{"type": "command", "command": claude_cmd, "timeout": 10}]}
|
|
175
|
+
bash_entry = {"matcher": "Bash", "hooks": [{"type": "command", "command": claude_cmd, "timeout": 10}]}
|
|
176
|
+
hooks.setdefault("UserPromptSubmit", []).append(prompt_entry)
|
|
177
|
+
hooks.setdefault("PreToolUse", []).append(bash_entry)
|
|
178
|
+
data["hooks"] = hooks
|
|
179
|
+
cls._write_file_safely(config_file, json.dumps(data, indent=2))
|
|
180
|
+
return True, "hooks registered (UserPromptSubmit + PreToolUse guard)"
|
|
181
|
+
|
|
182
|
+
# cursor
|
|
183
|
+
config_file = os.path.join(HOME, ".cursor", "hooks.json")
|
|
184
|
+
os.makedirs(os.path.dirname(config_file), exist_ok=True)
|
|
185
|
+
data = {}
|
|
186
|
+
if os.path.exists(config_file):
|
|
187
|
+
try:
|
|
188
|
+
with open(config_file, "r", encoding="utf-8") as f:
|
|
189
|
+
data = json.load(f)
|
|
190
|
+
except Exception:
|
|
191
|
+
data = {}
|
|
192
|
+
hooks = data.get("hooks") if isinstance(data.get("hooks"), dict) else {}
|
|
193
|
+
blob = json.dumps(hooks)
|
|
194
|
+
if "cursor_hook.py" in blob:
|
|
195
|
+
return True, "TokenSafe Cursor hooks already registered"
|
|
196
|
+
shell_entry = {"command": cursor_cmd, "timeout": 10}
|
|
197
|
+
hooks.setdefault("beforeShellExecution", []).append(dict(shell_entry))
|
|
198
|
+
hooks.setdefault("beforeReadFile", []).append(dict(shell_entry))
|
|
199
|
+
hooks.setdefault("beforeSubmitPrompt", []).append(dict(shell_entry))
|
|
200
|
+
data["hooks"] = hooks
|
|
201
|
+
cls._write_file_safely(config_file, json.dumps(data, indent=2))
|
|
202
|
+
return True, "guards registered (shell + junk-read + prompt pipeline)"
|
|
203
|
+
|
|
138
204
|
@classmethod
|
|
139
205
|
def install_mcp_config(cls, agent_key: str) -> Tuple[bool, str]:
|
|
140
206
|
"""Injects TokenSafe MCP config into target agent."""
|
|
@@ -489,6 +555,10 @@ class AgentInstaller:
|
|
|
489
555
|
for key, info in agents.items():
|
|
490
556
|
if info["installed"] or force:
|
|
491
557
|
ok, msg = cls.install_mcp_config(key)
|
|
558
|
+
if ok:
|
|
559
|
+
h_ok, h_msg = cls.install_hooks_config(key)
|
|
560
|
+
if h_ok:
|
|
561
|
+
msg = f"{msg}; {h_msg}"
|
|
492
562
|
results[key] = {"name": info["name"], "success": ok, "message": msg}
|
|
493
563
|
# Also configure project rules
|
|
494
564
|
proj_res = cls.install_project(os.getcwd())
|
|
@@ -536,6 +606,10 @@ class AgentInstaller:
|
|
|
536
606
|
if is_sel:
|
|
537
607
|
name = agents[key]["name"]
|
|
538
608
|
ok, msg = cls.install_mcp_config(key)
|
|
609
|
+
if ok:
|
|
610
|
+
h_ok, h_msg = cls.install_hooks_config(key)
|
|
611
|
+
if h_ok:
|
|
612
|
+
msg = f"{msg}; {h_msg}"
|
|
539
613
|
if ok:
|
|
540
614
|
print(f" \033[32m✔\033[0m \033[1m{name}\033[0m: {msg}")
|
|
541
615
|
installed_count += 1
|
|
@@ -743,6 +817,10 @@ class AgentInstaller:
|
|
|
743
817
|
for key, info in agents.items():
|
|
744
818
|
if info["installed"]:
|
|
745
819
|
ok, msg = cls.install_mcp_config(key)
|
|
820
|
+
if ok:
|
|
821
|
+
h_ok, h_msg = cls.install_hooks_config(key)
|
|
822
|
+
if h_ok:
|
|
823
|
+
msg = f"{msg}; {h_msg}"
|
|
746
824
|
if ok:
|
|
747
825
|
print(f" {GREEN}✔{RESET} {info['name']}: {msg}")
|
|
748
826
|
synced_count += 1
|
package/src/mcp_server.py
CHANGED
package/src/telemetry_sync.py
CHANGED
|
@@ -264,7 +264,7 @@ class TelemetrySync:
|
|
|
264
264
|
rollup_synced = bool(state.get("lifetime_rollup_synced", False))
|
|
265
265
|
headers = {
|
|
266
266
|
"Content-Type": "application/json",
|
|
267
|
-
"User-Agent": "TokenSafe-Sync/1.
|
|
267
|
+
"User-Agent": "TokenSafe-Sync/1.7.0"
|
|
268
268
|
}
|
|
269
269
|
if active_key:
|
|
270
270
|
headers["Authorization"] = f"Bearer {active_key}"
|
package/src/version_checker.py
CHANGED
|
@@ -16,7 +16,7 @@ import urllib.request
|
|
|
16
16
|
import urllib.error
|
|
17
17
|
from typing import Dict, Any, Optional, Tuple
|
|
18
18
|
|
|
19
|
-
CURRENT_VERSION = "1.
|
|
19
|
+
CURRENT_VERSION = "1.7.0"
|
|
20
20
|
CACHE_TTL = 86400 # 24 hours
|
|
21
21
|
# When the cloud is unreachable we must NOT cache the synthesized "up to date"
|
|
22
22
|
# answer for a full day — otherwise an update released right after an outage
|