tokensafe 1.6.0 → 1.8.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 CHANGED
@@ -69,6 +69,55 @@ 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
+
86
+ ## 🧠 Context Budget HUD
87
+
88
+ Agents (and humans) usually discover context exhaustion by quality degradation — too late. TokenSafe exposes the remaining budget as a first-class MCP tool:
89
+
90
+ ```json
91
+ { "tool": "tokensafe:context_budget", "args": { "model": "claude-x" } }
92
+ ```
93
+
94
+ ```json
95
+ {
96
+ "window_tokens": 200000,
97
+ "used_estimated": 168000,
98
+ "used_pct": 84.0,
99
+ "breakdown": { "tools": 165000, "history": 2300, "prompts": 700, "other": 0 },
100
+ "threshold": "warning",
101
+ "recommendation": "Context is heavy. Prefer tokensafe:smart_read_file ... and consider tokensafe:compact_conversation."
102
+ }
103
+ ```
104
+
105
+ - Window resolution: explicit arg → `TOKENSAFE_CONTEXT_WINDOW` env → model-family default (Gemini 1M, Claude 200k, GPT 128k).
106
+ - **80% warning injected into the agent automatically** by the Antigravity/ZCode `pre_invocation` hook — once per session (marker-event guarded).
107
+ - Honesty: counts only TokenSafe-instrumented flows (tool slices, skeletons, compacted prompts) — labeled `estimated`, a floor, never a fabricated total (see [METRICS.md](METRICS.md)).
108
+
109
+ ## 💰 Per-Seat ROI (Team)
110
+
111
+ Team owners pay per seat — now they see the return per seat. The dashboard's Team Seats table carries an **ROI column** per developer: saved tokens, USD equivalent, and the `metered/estimated` honesty split, computed in a single grouped query. Seats without activity render `—`, never a fabricated number.
112
+
113
+ ## 💾 Persistent Diff-Aware Read-Cache
114
+
115
+ The subagent dedup cache (per-session) now has a persistent layer keyed by **sha256 of the file's raw bytes**:
116
+
117
+ - Survives MCP-server restarts **and** `git checkout` (which resets mtime but not content — content is the only truth).
118
+ - Any real edit changes the hash and invalidates the entry instantly.
119
+ - Bounded: artifacts >256k chars are never cached; the layer prunes itself to the latest 500 entries (hourly amortized).
120
+
72
121
  ## 🔌 Universal MCP Server Configuration
73
122
 
74
123
  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()
@@ -19,6 +19,7 @@ sys.path.insert(0, PROJECT_ROOT)
19
19
  from src.compactor import PromptCompactor
20
20
  from src.history_compactor import HistoryCompactor
21
21
  from src.metrics import MetricsTracker
22
+ from src.governor import ContextBudget
22
23
  from src.environment_auditor import EnvironmentAuditor
23
24
  from src.license_manager import LicenseManager
24
25
 
@@ -221,6 +222,40 @@ def main():
221
222
  if inject_steps:
222
223
  response["injectSteps"] = inject_steps
223
224
 
225
+ # 4. Context Budget HUD warning: inject once per session when the
226
+ # instrumented context crosses 80% of the estimated window.
227
+ try:
228
+ budget = ContextBudget.estimate(
229
+ tracker, session_id=conversation_id,
230
+ model=payload.get("model") or os.environ.get("AGY_MODEL") or os.environ.get("MODEL") or ""
231
+ )
232
+ if budget["used_pct"] >= 80 and budget["instrumented_events"] >= 3:
233
+ already = tracker.get_last_event(conversation_id, "BUDGET_WARNING")
234
+ if not already:
235
+ warn = (
236
+ f"🧠 **Context Budget:** ~{budget['used_pct']}% of the estimated window used "
237
+ f"({budget['used_estimated']:,}/{budget['window_tokens']:,} tokens, instrumented floor). "
238
+ f"{budget['recommendation']}"
239
+ )
240
+ inject_steps.append({
241
+ "systemMessage": {
242
+ "systemMessage": "",
243
+ "metadata": {"user_markdown": warn}
244
+ }
245
+ })
246
+ tracker.record_event(
247
+ session_id=conversation_id,
248
+ event_type="BUDGET_WARNING",
249
+ original_tokens=0,
250
+ optimized_tokens=0,
251
+ details={"used_pct": budget["used_pct"], "window": budget["window_tokens"]}
252
+ )
253
+ except Exception:
254
+ pass
255
+
256
+ if inject_steps:
257
+ response["injectSteps"] = inject_steps
258
+
224
259
  print(json.dumps(response))
225
260
 
226
261
  if __name__ == "__main__":
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "tokensafe",
3
3
  "mcpName": "dev.tokensafe/tokensafe",
4
- "version": "1.6.0",
4
+ "version": "1.8.0",
5
5
  "description": "Autonomous Zero-Loss Token Economy & Context Optimizer for AI Coding Agents",
6
6
  "main": "bin/tokensafe.js",
7
7
  "bin": {
package/plugin.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "agy-token-optimizer",
3
3
  "displayName": "TokenSafe",
4
- "version": "1.6.0",
4
+ "version": "1.8.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.0",
6
+ "version": "1.8.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.6.0",
33
+ "version": "1.8.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.6.0",
49
+ "version": "1.8.0",
50
50
  "runtimeHint": "uvx",
51
51
  "transport": {
52
52
  "type": "stdio"
@@ -57,6 +57,7 @@ All tools are exposed via Model Context Protocol (stdio JSON-RPC 2.0).
57
57
  | `tokensafe:slice_diff` | Slices unified git diffs, eliminating lockfiles and minimizing hunk context lines. | **-50% to -80%** diff size |
58
58
  | `tokensafe:compress_prompt` | Compresses verbose user instructions into lean TOCP S-expressions via DeepSeek/Regex. | **-40% to -65%** prompt tokens |
59
59
  | `tokensafe:compact_conversation` | On-demand context compaction: folds a long JSONL session transcript into a lean Consolidated State Ledger (`transcript_path`, optional `invocation_num`). Call when the context window feels heavy or before a new subtask. | **-80% to -95%** history tokens |
60
+ | `tokensafe:context_budget` | Context Budget HUD: estimated window usage (`model`/`window_tokens`/`session_id`) with tools/history/prompts breakdown and 50/80/95% thresholds. Call before deciding to compact. | Floor estimate, always labeled estimated |
60
61
  | `tokensafe:guard_inspect` | Pre-flight security & hygiene audit for commands or code snippets (secrets, TLS, SQLi, raw grep). | **Zero-Risk** pre-flight gate |
61
62
  | `tokensafe:get_token_savings_metrics` | Returns cumulative analytics: tokens saved, context ratio, USD value, and optimization source breakdown. | Persistent SQLite analytics |
62
63
 
@@ -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
@@ -3,19 +3,28 @@ TokenSafe Subagent Firewall: Cross-Agent Deduplication Cache.
3
3
  Detects redundant file inspection across parent-subagent workflows and swarms.
4
4
  If an agent or subagent requests a file already ingested within the session,
5
5
  serves cached AST representation and suppresses quadratic token waste.
6
+
7
+ Persistent layer: entries are additionally keyed by the FILE'S CONTENT HASH
8
+ (sha256), so a cache hit survives (a) session restarts and (b) `git checkout`
9
+ mtime resets — content is the only truth. A hash mismatch (real edit) invalidates.
6
10
  """
7
11
 
8
12
  import os
9
13
  import time
10
14
  import sqlite3
15
+ import hashlib
11
16
  from typing import Tuple, Optional, Dict, Any
12
17
  from src.metrics import MetricsTracker
13
18
  from src.tokenizer import count_tokens
14
19
 
15
20
  class AgentFirewall:
16
- """Manages cross-agent shared file cache within active sessions."""
21
+ """Manages cross-agent shared file cache within and across sessions."""
17
22
 
18
23
  _INITIALIZED_DBS = set()
24
+ _MAX_CONTENT_CHARS = 262_144 # refuse to cache >256k-char artifacts
25
+ _PRUNE_INTERVAL = 3600.0 # amortized hourly prune of the persistent layer
26
+ _PRUNE_KEEP = 500
27
+ _last_prune = 0.0
19
28
 
20
29
  @classmethod
21
30
  def _ensure_table(cls, tracker: MetricsTracker):
@@ -34,12 +43,47 @@ class AgentFirewall:
34
43
  tokens INTEGER NOT NULL,
35
44
  created_at INTEGER NOT NULL,
36
45
  hit_count INTEGER NOT NULL DEFAULT 0,
46
+ content_hash TEXT NOT NULL DEFAULT '',
37
47
  UNIQUE(session_id, file_path, symbol)
38
48
  );
39
49
  """)
50
+ # Migration for pre-hash databases (public export & upgrades).
51
+ try:
52
+ conn.execute("ALTER TABLE subagent_file_cache ADD COLUMN content_hash TEXT NOT NULL DEFAULT '';")
53
+ except sqlite3.OperationalError:
54
+ pass # column already present
40
55
  conn.execute("CREATE INDEX IF NOT EXISTS idx_subagent_cache ON subagent_file_cache(session_id, file_path);")
56
+ conn.execute("CREATE INDEX IF NOT EXISTS idx_subagent_hash ON subagent_file_cache(file_path, symbol, content_hash);")
41
57
  cls._INITIALIZED_DBS.add(tracker.db_path)
42
58
 
59
+ @staticmethod
60
+ def _file_content_hash(file_path: str) -> str:
61
+ """sha256 of the file's RAW bytes — the diff-aware truth that survives
62
+ git checkout mtime resets."""
63
+ try:
64
+ with open(file_path, "rb") as f:
65
+ return hashlib.sha256(f.read()).hexdigest()
66
+ except OSError:
67
+ return ""
68
+
69
+ @classmethod
70
+ def _maybe_prune(cls, tracker: MetricsTracker):
71
+ """Amortized retention: keeps the persistent layer bounded without a cron."""
72
+ now = time.time()
73
+ if now - cls._last_prune < cls._PRUNE_INTERVAL:
74
+ return
75
+ cls._last_prune = now
76
+ try:
77
+ with tracker._get_connection() as conn:
78
+ conn.execute("""
79
+ DELETE FROM subagent_file_cache
80
+ WHERE id NOT IN (
81
+ SELECT id FROM subagent_file_cache ORDER BY created_at DESC LIMIT ?
82
+ );
83
+ """, (cls._PRUNE_KEEP,))
84
+ except Exception:
85
+ pass
86
+
43
87
  @classmethod
44
88
  def check_cache(
45
89
  cls,
@@ -49,7 +93,11 @@ class AgentFirewall:
49
93
  tracker: Optional[MetricsTracker] = None
50
94
  ) -> Tuple[bool, Optional[str], int]:
51
95
  """
52
- Checks if file has already been ingested in this session with unchanged mtime.
96
+ Two-stage lookup:
97
+ 1. In-session entry with unchanged mtime (fast path, unchanged semantics).
98
+ 2. Cross-session entry whose content_hash matches the file's CURRENT
99
+ bytes — survives restarts and git-checkout mtime resets; any real
100
+ edit changes the hash and invalidates the entry.
53
101
  Returns: (is_hit, cached_content_or_none, tokens_saved)
54
102
  """
55
103
  if not file_path or not os.path.exists(file_path):
@@ -65,26 +113,39 @@ class AgentFirewall:
65
113
 
66
114
  abs_path = os.path.abspath(file_path)
67
115
  symbol_key = (symbol or "").strip()
116
+ current_hash = cls._file_content_hash(abs_path)
68
117
 
69
118
  hit_data = None
119
+ hit_scope = "session"
70
120
  with tracker._get_connection() as conn:
121
+ # Stage 1: in-session, mtime-validated
71
122
  row = conn.execute("""
72
- SELECT id, content, tokens, mtime, hit_count
123
+ SELECT id, content, tokens, mtime, hit_count
73
124
  FROM subagent_file_cache
74
125
  WHERE session_id = ? AND file_path = ? AND symbol = ?;
75
126
  """, (session_id, abs_path, symbol_key)).fetchone()
76
127
 
77
128
  if row and row["mtime"] >= current_mtime:
78
- cache_id = row["id"]
79
- content = row["content"]
80
- tokens = row["tokens"]
81
- hit_count = row["hit_count"] + 1
82
-
83
- conn.execute("UPDATE subagent_file_cache SET hit_count = ? WHERE id = ?;", (hit_count, cache_id))
84
- hit_data = (content, tokens, hit_count)
129
+ hit_data = (row["id"], row["content"], row["tokens"], row["hit_count"] + 1)
130
+ elif current_hash:
131
+ # Stage 2: cross-session, content-hash-validated
132
+ row2 = conn.execute("""
133
+ SELECT id, content, tokens, hit_count
134
+ FROM subagent_file_cache
135
+ WHERE file_path = ? AND symbol = ? AND content_hash = ?
136
+ ORDER BY created_at DESC LIMIT 1;
137
+ """, (abs_path, symbol_key, current_hash)).fetchone()
138
+ if row2:
139
+ hit_data = (row2["id"], row2["content"], row2["tokens"], row2["hit_count"] + 1)
140
+ hit_scope = "persistent"
85
141
 
86
142
  if hit_data:
87
- content, tokens, hit_count = hit_data
143
+ cache_id, content, tokens, hit_count = hit_data
144
+ try:
145
+ with tracker._get_connection() as conn:
146
+ conn.execute("UPDATE subagent_file_cache SET hit_count = ? WHERE id = ?;", (hit_count, cache_id))
147
+ except Exception:
148
+ pass
88
149
  try:
89
150
  tracker.record_event(
90
151
  session_id=session_id,
@@ -94,14 +155,16 @@ class AgentFirewall:
94
155
  details={
95
156
  "target_file": os.path.basename(abs_path),
96
157
  "symbol": symbol_key,
97
- "hit_number": hit_count
158
+ "hit_number": hit_count,
159
+ "scope": hit_scope
98
160
  }
99
161
  )
100
162
  except Exception:
101
163
  pass
102
164
 
165
+ scope_label = "Persistent cache" if hit_scope == "persistent" else "Reused session read"
103
166
  header = (
104
- f"// [TokenSafe Subagent Firewall: Reused session read for '{os.path.basename(abs_path)}' "
167
+ f"// [TokenSafe Subagent Firewall: {scope_label} for '{os.path.basename(abs_path)}' "
105
168
  f"(Dedup Hit #{hit_count}, Saved ~{tokens - 40} tokens)]\n"
106
169
  )
107
170
  return True, header + content, max(0, tokens - 40)
@@ -117,9 +180,12 @@ class AgentFirewall:
117
180
  symbol: str = "",
118
181
  tracker: Optional[MetricsTracker] = None
119
182
  ):
120
- """Caches file read content for subagent reuse in the active session."""
183
+ """Caches file read content for subagent reuse in the active session
184
+ AND persistently, keyed by content hash."""
121
185
  if not file_path or not content or not os.path.exists(file_path):
122
186
  return
187
+ if len(content) > cls._MAX_CONTENT_CHARS:
188
+ return # refuse to persist oversized artifacts
123
189
 
124
190
  tracker = tracker or MetricsTracker()
125
191
  cls._ensure_table(tracker)
@@ -133,14 +199,17 @@ class AgentFirewall:
133
199
  symbol_key = (symbol or "").strip()
134
200
  tokens = count_tokens(content)
135
201
  now = int(time.time())
202
+ content_hash = cls._file_content_hash(abs_path)
136
203
 
137
204
  with tracker._get_connection() as conn:
138
205
  conn.execute("""
139
- INSERT INTO subagent_file_cache (session_id, file_path, mtime, symbol, content, tokens, created_at, hit_count)
140
- VALUES (?, ?, ?, ?, ?, ?, ?, 0)
206
+ INSERT INTO subagent_file_cache (session_id, file_path, mtime, symbol, content, tokens, created_at, hit_count, content_hash)
207
+ VALUES (?, ?, ?, ?, ?, ?, ?, 0, ?)
141
208
  ON CONFLICT(session_id, file_path, symbol) DO UPDATE SET
142
209
  mtime = excluded.mtime,
143
210
  content = excluded.content,
144
211
  tokens = excluded.tokens,
145
- created_at = excluded.created_at;
146
- """, (session_id, abs_path, mtime, symbol_key, content, tokens, now))
212
+ created_at = excluded.created_at,
213
+ content_hash = excluded.content_hash;
214
+ """, (session_id, abs_path, mtime, symbol_key, content, tokens, now, content_hash))
215
+ cls._maybe_prune(tracker)
package/src/governor.py CHANGED
@@ -164,3 +164,101 @@ class ContextGovernor:
164
164
  "saved_tokens": saved,
165
165
  "actions": actions_taken
166
166
  }
167
+
168
+
169
+ class ContextBudget:
170
+ """Context Budget HUD: estimates how much of the model's context window the
171
+ current session has consumed, based on TokenSafe-instrumented flows.
172
+
173
+ Honesty (METRICS.md): only bytes that flowed through TokenSafe instruments
174
+ are counted (tool slices, skeletons, compacted prompts, folded history).
175
+ Un-instrumented traffic (agent reasoning, output tokens) is invisible here,
176
+ so `used_estimated` is a FLOOR, not an exact figure — always labeled
177
+ estimated."""
178
+
179
+ # Conservative defaults by model family substring (tokens)
180
+ WINDOW_DEFAULTS = [
181
+ ("gemini", 1_000_000),
182
+ ("claude", 200_000),
183
+ ("gpt", 128_000),
184
+ ("codex", 128_000),
185
+ ("o1", 200_000),
186
+ ("o3", 200_000),
187
+ ]
188
+ DEFAULT_WINDOW = 200_000
189
+
190
+ @classmethod
191
+ def resolve_window(cls, model: str = "", window_tokens: Optional[int] = None) -> int:
192
+ """Explicit window > env override > model-family default."""
193
+ if window_tokens and int(window_tokens) > 0:
194
+ return int(window_tokens)
195
+ env = os.environ.get("TOKENSAFE_CONTEXT_WINDOW", "")
196
+ if env.strip().isdigit() and int(env) > 0:
197
+ return int(env)
198
+ model_l = (model or "").lower()
199
+ for family, window in cls.WINDOW_DEFAULTS:
200
+ if family in model_l:
201
+ return window
202
+ return cls.DEFAULT_WINDOW
203
+
204
+ # Category mapping for the HUD breakdown (event_type -> bucket)
205
+ CATEGORY_MAP = {
206
+ "TOOL_READ": "tools", "GRAPH_SKELETON": "tools", "AST_SKELETON": "tools",
207
+ "SCOPED_SEARCH": "tools", "DIR_LIST": "tools", "COMMAND_FILTER": "tools",
208
+ "TEAM_CACHE_HIT": "tools", "SUBAGENT_DEDUP": "tools",
209
+ "HISTORY_FOLD": "history",
210
+ "PROMPT": "prompts",
211
+ "CONTEXT_GOVERNOR": "other", "OUTPUT_GUARD": "other", "SECRET_GUARD": "other",
212
+ "GRAPH_TOPOLOGY": "other",
213
+ }
214
+
215
+ @classmethod
216
+ def estimate(cls, tracker: MetricsTracker, session_id: str = "mcp_session",
217
+ model: str = "", window_tokens: Optional[int] = None) -> Dict[str, Any]:
218
+ window = cls.resolve_window(model, window_tokens)
219
+ breakdown = {"tools": 0, "history": 0, "prompts": 0, "other": 0}
220
+ instrumented_events = 0
221
+ try:
222
+ with tracker._get_connection() as conn:
223
+ cursor = conn.cursor()
224
+ cursor.execute(
225
+ "SELECT event_type, COALESCE(SUM(optimized_tokens), 0) AS received, COUNT(*) AS cnt "
226
+ "FROM events WHERE session_id = ? GROUP BY event_type;",
227
+ (session_id or "",)
228
+ )
229
+ for row in cursor.fetchall():
230
+ ev_type = row["event_type"]
231
+ bucket = cls.CATEGORY_MAP.get(ev_type, "other")
232
+ breakdown[bucket] += int(row["received"] or 0)
233
+ instrumented_events += int(row["cnt"] or 0)
234
+ except Exception:
235
+ pass
236
+
237
+ used = sum(breakdown.values())
238
+ pct = round(used / window * 100.0, 1) if window > 0 else 0.0
239
+ if pct >= 95:
240
+ threshold, recommendation = "critical", (
241
+ "Context nearly exhausted. Call tokensafe:compact_conversation on the "
242
+ "session transcript now, or start a fresh session carrying the ledger.")
243
+ elif pct >= 80:
244
+ threshold, recommendation = "warning", (
245
+ "Context is heavy. Prefer tokensafe:smart_read_file with symbol= for "
246
+ "further reads and consider tokensafe:compact_conversation.")
247
+ elif pct >= 50:
248
+ threshold, recommendation = "notice", (
249
+ "Half the estimated window is used. Keep reads surgical (symbol=, include_deps=false).")
250
+ else:
251
+ threshold, recommendation = "healthy", "Context budget healthy."
252
+
253
+ return {
254
+ "window_tokens": window,
255
+ "used_estimated": used,
256
+ "used_pct": pct,
257
+ "breakdown": breakdown,
258
+ "instrumented_events": instrumented_events,
259
+ "threshold": threshold,
260
+ "recommendation": recommendation,
261
+ "caveat": "Floor estimate: only TokenSafe-instrumented flows are counted "
262
+ "(agent reasoning/output is invisible to local hooks).",
263
+ "measurement": "estimated",
264
+ }
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
@@ -30,6 +30,7 @@ from src.graph_engine import GraphEngine
30
30
  from src.tokenizer import count_tokens
31
31
  from src.history_compactor import HistoryCompactor
32
32
  from src.team_cache import TeamCache
33
+ from src.governor import ContextBudget
33
34
  from src.agent_firewall import AgentFirewall
34
35
  from src.diff_slicer import DiffSlicer
35
36
  from src.guard import TokenSafeGuard
@@ -37,7 +38,7 @@ from src.scoped_search import ScopedSearch
37
38
 
38
39
  SERVER_INFO = {
39
40
  "name": "tokensafe-mcp",
40
- "version": "1.6.0"
41
+ "version": "1.8.0"
41
42
  }
42
43
 
43
44
  TOOLS = [
@@ -87,6 +88,18 @@ TOOLS = [
87
88
  "required": ["prompt"]
88
89
  }
89
90
  },
91
+ {
92
+ "name": "context_budget",
93
+ "description": "Context Budget HUD: estimates how much of the model's context window this session has consumed (tools/history/prompts breakdown, 50/80/95% thresholds). Call when deciding whether to compact or start fresh.",
94
+ "inputSchema": {
95
+ "type": "object",
96
+ "properties": {
97
+ "model": {"type": "string", "description": "Optional: model name to resolve window size (default: env TOKENSAFE_CONTEXT_WINDOW or 200k)"},
98
+ "window_tokens": {"type": "integer", "description": "Optional: explicit context window size in tokens"},
99
+ "session_id": {"type": "string", "description": "Optional: session identifier (default: mcp_session)"}
100
+ }
101
+ }
102
+ },
90
103
  {
91
104
  "name": "compact_conversation",
92
105
  "description": "On-demand context compaction: folds a long agent conversation transcript into a compact Consolidated State Ledger. Use when the context window feels heavy or before starting a new subtask inside the same session.",
@@ -572,6 +585,18 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
572
585
  res = PromptCompactor.compact(prompt, enable_deepseek=True)
573
586
  return {"content": [{"type": "text", "text": json.dumps(res, indent=2, ensure_ascii=False)}]}
574
587
 
588
+ elif name == "context_budget":
589
+ model = str(args.get("model") or "")
590
+ window_tokens = args.get("window_tokens")
591
+ session_id = str(args.get("session_id") or "mcp_session")
592
+ try:
593
+ if window_tokens is not None:
594
+ window_tokens = int(window_tokens)
595
+ except (TypeError, ValueError):
596
+ window_tokens = None
597
+ budget = ContextBudget.estimate(tracker, session_id=session_id, model=model, window_tokens=window_tokens)
598
+ return {"content": [{"type": "text", "text": json.dumps(budget, indent=2, ensure_ascii=False)}]}
599
+
575
600
  elif name == "compact_conversation":
576
601
  transcript_path = args.get("transcript_path", "")
577
602
  try:
@@ -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.6.0"
267
+ "User-Agent": "TokenSafe-Sync/1.8.0"
268
268
  }
269
269
  if active_key:
270
270
  headers["Authorization"] = f"Bearer {active_key}"
@@ -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.6.0"
19
+ CURRENT_VERSION = "1.8.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