tokensafe 1.7.0 → 2.0.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
@@ -83,6 +83,41 @@ Beyond MCP, TokenSafe ships **lifecycle-hook adapters** that run natively inside
83
83
 
84
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
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
+
86
121
  ## 🔌 Universal MCP Server Configuration
87
122
 
88
123
  Connect TokenSafe directly to **Claude Desktop** (`claude_desktop_config.json`) or **Cursor** MCP Settings:
@@ -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.7.0",
4
+ "version": "2.0.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.7.0",
4
+ "version": "2.0.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/rules/AGENTS.md CHANGED
@@ -34,11 +34,11 @@ Execute the specified action directly based on these extracted parameters.
34
34
  6. **Directory Navigation**: Never run verbose `ls -la` or `ls -l`; use `tokensafe:list_dir(path, depth=2)` to inspect directory trees without permissions, timestamps, or lockfiles (-90% tokens).
35
35
  7. **Style & Design Tokens**: When inspecting CSS/SCSS/LESS/Tailwind, `tokensafe:smart_read_file` automatically preserves all design tokens (`:root`, `@theme`, CSS variables) in full while folding component selectors.
36
36
 
37
- ### 4. Turn Token Savings Footer (Proof-of-Savings)
37
+ ### 4. Turn Token Savings Footer (Proof-of-Savings — always in English)
38
38
  At the end of your response for any turn where tools were executed, files were inspected, commands were sanitized, or prompts were compacted, append a compact 1-line footer:
39
- `⚡ **TokenSafe Turn Savings**: +<tokens> tokens saved on this turn (<breakdown>) | Cumulative Total: <total> tokens`
39
+ `⚡ **TokenSafe Turn Savings**: +<tokens> tokens saved on this turn (<breakdown>) | Cumulative Total: <total> tokens (≈$<usd> approx)`
40
40
  Example:
41
- `⚡ **TokenSafe Turn Savings**: +3,520 tokens (~88%) | Cumulative Total: 3.04M tokens ($4.56)`
41
+ `⚡ **TokenSafe Turn Savings**: +3,520 tokens (~88%) | Cumulative Total: 3.04M tokens (≈$4.56 approx)`
42
42
 
43
43
  ### 5. Secret Leak Prevention Directive (Zero Hardcoded Fallbacks)
44
44
  1. **Never Hardcode Credential Fallbacks**: Never provide real private keys, API secrets, access tokens, or webhook secrets as default fallback arguments in `os.environ.get()`, `os.getenv()`, or `process.env`. If an environment variable is absent, raise an explicit configuration error or use an empty string / test mock. Real credentials must exist strictly in environment variables.
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.7.0",
6
+ "version": "2.0.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.7.0",
33
+ "version": "2.0.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.7.0",
49
+ "version": "2.0.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
 
@@ -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/dashboard.py CHANGED
@@ -93,7 +93,19 @@ class Dashboard:
93
93
 
94
94
  out.append(f" {BOLD}Total Tokens Saved:{RESET} {GREEN}{BOLD}{total_saved:,}{RESET} tokens")
95
95
  out.append(f" {BOLD}Efficiency Gain:{RESET} {YELLOW}{BOLD}{render_bar(pct)}{RESET}")
96
- out.append(f" {BOLD}Estimated Savings:{RESET} {GREEN}${usd:.4f} USD{RESET}")
96
+ out.append(f" {BOLD}Estimated Savings:{RESET} {GREEN}≈${usd:.4f} USD{RESET} {DIM}(derived: tokens × $1.5/M — approximation, not a bill){RESET}")
97
+
98
+ # Per-agent breakdown (honest Cumulative Total across ALL agents)
99
+ by_agent = summary.get("by_agent") or {}
100
+ if by_agent:
101
+ out.append(f"\n {BOLD}By Agent:{RESET}")
102
+ for agent, stats in by_agent.items():
103
+ out.append(
104
+ f" • {agent:<14} {stats['saved_tokens']:>12,} tok "
105
+ f"({stats['saved_tokens_measured']:,} metered / {stats['saved_tokens_estimated']:,} est.) "
106
+ f"≈${stats['est_usd_saved']:.2f}"
107
+ )
108
+ out.append("")
97
109
  out.append(f" {BOLD}Context Traffic:{RESET} {orig:,} raw ➔ {opt:,} optimized ({events_count} events)\n")
98
110
 
99
111
  # Breakdown by category
@@ -155,7 +167,7 @@ class Dashboard:
155
167
  md.append(f"| **Total Tokens Saved** | **{total_saved:,} tokens** |")
156
168
  md.append(f"| **Context Ratio** | {orig:,} raw ➔ {opt:,} optimized |")
157
169
  md.append(f"| **Net Efficiency Gain** | `{render_bar(pct)}` |")
158
- md.append(f"| **Estimated Value Saved** | **${usd:.4f} USD** |\n")
170
+ md.append(f"| **Estimated Value Saved** | **≈${usd:.4f} USD** (derived approximation) |\n")
159
171
 
160
172
  md.append("### Source Breakdown\n")
161
173
  md.append("| Pipeline Stage | Events | Tokens Saved |")
@@ -373,7 +385,7 @@ class Dashboard:
373
385
  }}
374
386
  if (data.total_usd_saved !== undefined) {{
375
387
  const el = document.getElementById('val-usd-saved');
376
- if (el) el.innerText = '$' + data.total_usd_saved.toFixed(4);
388
+ if (el) el.innerText = '≈$' + data.total_usd_saved.toFixed(4);
377
389
  }}
378
390
  if (data.total_original_tokens !== undefined && data.total_optimized_tokens !== undefined) {{
379
391
  const el = document.getElementById('val-traffic');
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
@@ -41,9 +41,9 @@ UNIFIED_TOKENSAFE_RULE = (
41
41
  "3. **Architecture Discovery**: Always call `tokensafe:get_architecture_graph(project_path)` before exploratory multi-file reading. Returns project God Nodes and key dependency hubs in < 250 tokens without file crawling.\n"
42
42
  "4. **API Surface Map**: Use `tokensafe:get_api_surface(project_path)` to get all exported classes, types, and interfaces in a single markdown map.\n"
43
43
  "5. **Command Sanitization**: Use `sanitize_command` on high-output terminal commands (`git diff`, `pytest`, `find`, `grep`) to prevent lockfile or test log context contamination.\n"
44
- "6. **Proof-of-Savings Turn Footer (English default)**:\n"
44
+ "6. **Proof-of-Savings Turn Footer (always in English)**:\n"
45
45
  "At the end of your response for any turn where tools were executed, files were inspected, commands were sanitized, or prompts were compacted, append a compact 1-line footer in English:\n"
46
- "`⚡ **TokenSafe Turn Savings**: +<tokens> tokens saved on this turn (<breakdown>) | Cumulative Total: <total> tokens ($<usd>)`\n"
46
+ "`⚡ **TokenSafe Turn Savings**: +<tokens> tokens saved on this turn (<breakdown>) | Cumulative Total: <total> tokens (≈$<usd> approx)`\n"
47
47
  )
48
48
 
49
49
  AGENTS_REGISTRY = {
package/src/mcp_server.py CHANGED
@@ -9,6 +9,7 @@ import os
9
9
  import stat
10
10
  import time
11
11
  import json
12
+ import re
12
13
  import threading
13
14
  import traceback
14
15
  import fnmatch
@@ -30,6 +31,7 @@ from src.graph_engine import GraphEngine
30
31
  from src.tokenizer import count_tokens
31
32
  from src.history_compactor import HistoryCompactor
32
33
  from src.team_cache import TeamCache
34
+ from src.governor import ContextBudget
33
35
  from src.agent_firewall import AgentFirewall
34
36
  from src.diff_slicer import DiffSlicer
35
37
  from src.guard import TokenSafeGuard
@@ -37,9 +39,22 @@ from src.scoped_search import ScopedSearch
37
39
 
38
40
  SERVER_INFO = {
39
41
  "name": "tokensafe-mcp",
40
- "version": "1.7.0"
42
+ "version": "2.0.0"
41
43
  }
42
44
 
45
+ # MCP client attribution: the initialize handshake carries clientInfo, which
46
+ # lets every session-scoped metric name the REAL agent instead of a shared
47
+ # anonymous bucket (see METRICS.md by_agent).
48
+ _MCP_CLIENT_NAME = ""
49
+
50
+ def _set_mcp_client(name: str):
51
+ global _MCP_CLIENT_NAME
52
+ clean = re.sub(r"[^a-z0-9_-]", "", str(name or "").lower())[:30]
53
+ _MCP_CLIENT_NAME = clean
54
+
55
+ def _mcp_session_id() -> str:
56
+ return f"mcp:{_MCP_CLIENT_NAME}" if _MCP_CLIENT_NAME else "mcp_session"
57
+
43
58
  TOOLS = [
44
59
  {
45
60
  "name": "smart_read_file",
@@ -87,6 +102,18 @@ TOOLS = [
87
102
  "required": ["prompt"]
88
103
  }
89
104
  },
105
+ {
106
+ "name": "context_budget",
107
+ "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.",
108
+ "inputSchema": {
109
+ "type": "object",
110
+ "properties": {
111
+ "model": {"type": "string", "description": "Optional: model name to resolve window size (default: env TOKENSAFE_CONTEXT_WINDOW or 200k)"},
112
+ "window_tokens": {"type": "integer", "description": "Optional: explicit context window size in tokens"},
113
+ "session_id": {"type": "string", "description": "Optional: session identifier (default: mcp_session)"}
114
+ }
115
+ }
116
+ },
90
117
  {
91
118
  "name": "compact_conversation",
92
119
  "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.",
@@ -441,7 +468,7 @@ def handle_tool_call(name: str, args: dict) -> dict:
441
468
  if text_out:
442
469
  try:
443
470
  AgentFirewall.record_cache(
444
- session_id="mcp_session",
471
+ session_id=_mcp_session_id(),
445
472
  file_path=args.get("path", ""),
446
473
  content=text_out,
447
474
  symbol=(args.get("symbol") or "").strip(),
@@ -481,12 +508,12 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
481
508
  return _fallback_error("smart_read_file", f"cannot stat path: {e}")
482
509
 
483
510
  # Check Subagent Firewall dedup cache
484
- is_hit, cached_text, saved_dedup = AgentFirewall.check_cache("mcp_session", path, symbol=symbol or "", tracker=tracker)
511
+ is_hit, cached_text, saved_dedup = AgentFirewall.check_cache(_mcp_session_id(), path, symbol=symbol or "", tracker=tracker)
485
512
  if is_hit and cached_text:
486
513
  return {"content": [{"type": "text", "text": cached_text}]}
487
514
 
488
515
  # Check loop detector
489
- is_loop, repeats, msg = LoopDetector.check_loop("mcp_session", "smart_read_file", args)
516
+ is_loop, repeats, msg = LoopDetector.check_loop(_mcp_session_id(), "smart_read_file", args)
490
517
  if is_loop:
491
518
  return {"isError": True, "content": [{"type": "text", "text": f"⚠️ {msg}"}]}
492
519
 
@@ -512,7 +539,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
512
539
  orig_t = count_tokens(raw_code)
513
540
  skel_t = count_tokens(team_skel)
514
541
  tracker.record_event(
515
- session_id="mcp_session",
542
+ session_id=_mcp_session_id(),
516
543
  event_type="TEAM_CACHE_HIT",
517
544
  original_tokens=orig_t,
518
545
  optimized_tokens=skel_t,
@@ -532,7 +559,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
532
559
  skel_t = count_tokens(graph_skel)
533
560
  saved = max(0, orig_t - skel_t)
534
561
  tracker.record_event(
535
- session_id="mcp_session",
562
+ session_id=_mcp_session_id(),
536
563
  event_type="GRAPH_SKELETON",
537
564
  original_tokens=orig_t,
538
565
  optimized_tokens=skel_t,
@@ -572,6 +599,18 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
572
599
  res = PromptCompactor.compact(prompt, enable_deepseek=True)
573
600
  return {"content": [{"type": "text", "text": json.dumps(res, indent=2, ensure_ascii=False)}]}
574
601
 
602
+ elif name == "context_budget":
603
+ model = str(args.get("model") or "")
604
+ window_tokens = args.get("window_tokens")
605
+ session_id = str(args.get("session_id") or _mcp_session_id())
606
+ try:
607
+ if window_tokens is not None:
608
+ window_tokens = int(window_tokens)
609
+ except (TypeError, ValueError):
610
+ window_tokens = None
611
+ budget = ContextBudget.estimate(tracker, session_id=session_id, model=model, window_tokens=window_tokens)
612
+ return {"content": [{"type": "text", "text": json.dumps(budget, indent=2, ensure_ascii=False)}]}
613
+
575
614
  elif name == "compact_conversation":
576
615
  transcript_path = args.get("transcript_path", "")
577
616
  try:
@@ -588,7 +627,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
588
627
  }, indent=2)}]}
589
628
  saved = max(0, orig_t - folded_t)
590
629
  tracker.record_event(
591
- session_id="mcp_session",
630
+ session_id=_mcp_session_id(),
592
631
  event_type="HISTORY_FOLD",
593
632
  original_tokens=orig_t,
594
633
  optimized_tokens=folded_t,
@@ -610,7 +649,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
610
649
  guard_res = TokenSafeGuard.inspect_command(cmd)
611
650
  if guard_res.blocked:
612
651
  tracker.record_event(
613
- session_id="mcp_session",
652
+ session_id=_mcp_session_id(),
614
653
  event_type=f"GUARD_{guard_res.check_name}",
615
654
  original_tokens=count_tokens(cmd),
616
655
  optimized_tokens=0,
@@ -658,7 +697,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
658
697
  })
659
698
  if c_res.blocked:
660
699
  tracker.record_event(
661
- session_id="mcp_session",
700
+ session_id=_mcp_session_id(),
662
701
  event_type=f"GUARD_{c_res.check_name}",
663
702
  original_tokens=count_tokens(cmd),
664
703
  optimized_tokens=0,
@@ -678,7 +717,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
678
717
  })
679
718
  if w_res.blocked:
680
719
  tracker.record_event(
681
- session_id="mcp_session",
720
+ session_id=_mcp_session_id(),
682
721
  event_type=f"GUARD_{w_res.check_name}",
683
722
  original_tokens=count_tokens(code),
684
723
  optimized_tokens=0,
@@ -706,7 +745,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
706
745
  saved = max(0, orig_t - opt_t)
707
746
  if saved > 0:
708
747
  tracker.record_event(
709
- session_id="mcp_session",
748
+ session_id=_mcp_session_id(),
710
749
  event_type="DIFF_SLICER",
711
750
  original_tokens=orig_t,
712
751
  optimized_tokens=opt_t,
@@ -740,7 +779,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
740
779
  est_crawl_tokens = min(50000, max(5000, capped_files * 600))
741
780
  topo_tokens = 250
742
781
  tracker.record_event(
743
- session_id="mcp_session",
782
+ session_id=_mcp_session_id(),
744
783
  event_type="GRAPH_TOPOLOGY",
745
784
  original_tokens=est_crawl_tokens,
746
785
  optimized_tokens=topo_tokens,
@@ -762,7 +801,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
762
801
  capped_files = min(100, len(graph.file_symbols))
763
802
  est_orig_tokens = min(60000, max(10000, capped_files * 600))
764
803
  tracker.record_event(
765
- session_id="mcp_session",
804
+ session_id=_mcp_session_id(),
766
805
  event_type="GRAPH_TOPOLOGY",
767
806
  original_tokens=est_orig_tokens,
768
807
  optimized_tokens=surface_tokens,
@@ -789,7 +828,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
789
828
  # Estimate equivalent tokens from multiple verbose ls -la calls (at least ~800 tokens)
790
829
  est_orig_tokens = max(800, tree_tokens * 6)
791
830
  tracker.record_event(
792
- session_id="mcp_session",
831
+ session_id=_mcp_session_id(),
793
832
  event_type="DIR_LIST",
794
833
  original_tokens=est_orig_tokens,
795
834
  optimized_tokens=tree_tokens,
@@ -833,7 +872,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
833
872
  res_tokens = count_tokens(md_text)
834
873
  est_orig = max(1500, res_tokens * 8)
835
874
  tracker.record_event(
836
- session_id="mcp_session",
875
+ session_id=_mcp_session_id(),
837
876
  event_type="SCOPED_SEARCH",
838
877
  original_tokens=est_orig,
839
878
  optimized_tokens=res_tokens,
@@ -915,6 +954,11 @@ def run_mcp_server():
915
954
  response = {"jsonrpc": "2.0", "id": msg_id}
916
955
 
917
956
  if method == "initialize":
957
+ try:
958
+ client_info = (params or {}).get("clientInfo") or {}
959
+ _set_mcp_client(str(client_info.get("name") or ""))
960
+ except Exception:
961
+ pass
918
962
  try:
919
963
  from src.telemetry_sync import TelemetrySync
920
964
  TelemetrySync.sync_background()
package/src/metrics.py CHANGED
@@ -247,6 +247,61 @@ class MetricsTracker:
247
247
  "measurement": measurement_label
248
248
  }
249
249
 
250
+ @staticmethod
251
+ def _infer_agent(session_id: str, details: Dict[str, Any]) -> str:
252
+ """Best-effort attribution of an event to the agent that produced it.
253
+ Explicit details.agent (new adapters) wins; session_id prefixes cover
254
+ the historic naming conventions."""
255
+ explicit = details.get("agent")
256
+ if explicit:
257
+ return str(explicit)
258
+ sid = session_id or ""
259
+ if sid == "mcp_session":
260
+ return "mcp"
261
+ if sid == "proxy_session":
262
+ return "proxy"
263
+ if sid.startswith("hook_"):
264
+ return sid[len("hook_"):] or "hook"
265
+ if sid.startswith("mcp:"):
266
+ return sid[4:] or "mcp"
267
+ return "antigravity"
268
+
269
+ def get_by_agent(self) -> Dict[str, Dict[str, Any]]:
270
+ """Per-agent savings breakdown for the honest Cumulative Total:
271
+ aggregates events by the agent that produced them, with the
272
+ measured/estimated split (see METRICS.md)."""
273
+ by_agent: Dict[str, Dict[str, Any]] = {}
274
+ try:
275
+ with self._get_connection() as conn:
276
+ cursor = conn.cursor()
277
+ cursor.execute("""
278
+ SELECT session_id, saved_tokens, est_usd_saved, measurement, details
279
+ FROM events
280
+ """)
281
+ for row in cursor.fetchall():
282
+ try:
283
+ details = json.loads(row["details"] or "{}")
284
+ if not isinstance(details, dict):
285
+ details = {}
286
+ except Exception:
287
+ details = {}
288
+ agent = self._infer_agent(row["session_id"], details)
289
+ bucket = by_agent.setdefault(agent, {
290
+ "events": 0, "saved_tokens": 0, "saved_tokens_measured": 0,
291
+ "saved_tokens_estimated": 0, "est_usd_saved": 0.0,
292
+ })
293
+ saved = int(row["saved_tokens"] or 0)
294
+ measurement = row["measurement"] or "measured"
295
+ bucket["events"] += 1
296
+ bucket["saved_tokens"] += saved
297
+ bucket["saved_tokens_measured"] += saved if measurement == "measured" else 0
298
+ bucket["saved_tokens_estimated"] += saved if measurement == "estimated" else 0
299
+ bucket["est_usd_saved"] = round(bucket["est_usd_saved"] + float(row["est_usd_saved"] or 0.0), 4)
300
+ except Exception:
301
+ pass
302
+ # Largest contributor first
303
+ return dict(sorted(by_agent.items(), key=lambda kv: kv[1]["saved_tokens"], reverse=True))
304
+
250
305
  def get_summary(self) -> Dict[str, Any]:
251
306
  """Returns cumulative statistics across all sessions, including lifetime rollups."""
252
307
  with self._get_connection() as conn:
@@ -324,6 +379,8 @@ class MetricsTracker:
324
379
  "total_saved_tokens_estimated": saved_estimated,
325
380
  "overall_reduction_pct": round(overall_reduction, 1),
326
381
  "total_usd_saved": round(total_usd, 4),
382
+ "total_usd_saved_approx": True, # USD is a derived estimate (~$1.5/M blended), never a bill
383
+ "by_agent": self.get_by_agent(),
327
384
  "breakdown": combined_breakdown
328
385
  }
329
386
 
@@ -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.7.0"
267
+ "User-Agent": "TokenSafe-Sync/2.0.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.7.0"
19
+ CURRENT_VERSION = "2.0.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