tokensafe 1.7.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 +35 -0
- package/hooks/pre_invocation.py +35 -0
- package/package.json +1 -1
- package/plugin.json +1 -1
- package/server.json +3 -3
- package/skills/token-optimizer/SKILL.md +1 -0
- package/src/agent_firewall.py +87 -18
- package/src/governor.py +98 -0
- package/src/mcp_server.py +26 -1
- package/src/telemetry_sync.py +1 -1
- package/src/version_checker.py +1 -1
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:
|
package/hooks/pre_invocation.py
CHANGED
|
@@ -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
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.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
|
+
"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.
|
|
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.
|
|
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
|
|
package/src/agent_firewall.py
CHANGED
|
@@ -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
|
|
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
|
-
|
|
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
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
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:
|
|
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
|
-
|
|
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/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.
|
|
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:
|
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.8.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.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
|