tokensafe 1.2.0 → 1.3.1
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 +200 -16
- package/bin/agy-tokens +156 -4
- package/bin/tokensafe.js +7 -0
- package/hooks/pre_invocation.py +40 -11
- package/hooks/pre_tool_use.py +23 -3
- package/package.json +7 -3
- package/plugin.json +1 -1
- package/rules/AGENTS.md +6 -0
- package/skills/token-optimizer/SKILL.md +1 -0
- package/src/__init__.py +1 -1
- package/src/agent_firewall.py +146 -0
- package/src/benchmark.py +68 -9
- package/src/cache_normalizer.py +105 -0
- package/src/command_sanitizer.py +21 -12
- package/src/dashboard.py +54 -7
- package/src/diff_slicer.py +120 -0
- package/src/environment_auditor.py +259 -0
- package/src/governor.py +166 -0
- package/src/graph_engine.py +4 -0
- package/src/installer.py +192 -34
- package/src/license_manager.py +157 -23
- package/src/mcp_server.py +59 -7
- package/src/metrics.py +261 -21
- package/src/proxy.py +160 -18
- package/src/version_checker.py +156 -0
- package/src/weekly_digest.py +305 -0
- package/src/mailer.py +0 -327
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
"""
|
|
2
|
+
TokenSafe AST Diff Slicer.
|
|
3
|
+
Optimizes git diff outputs and code diff streams before ingestion into agent context.
|
|
4
|
+
- Strips lockfiles, minified files, and binary artifacts
|
|
5
|
+
- Reduces surrounding context windows to minimal 2-line hunks
|
|
6
|
+
- Identifies and annotates enclosing AST symbols (methods, classes)
|
|
7
|
+
- Saves 40% to 80% tokens on large git operations
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import re
|
|
11
|
+
from typing import Tuple, List, Dict, Any, Optional
|
|
12
|
+
from src.tokenizer import count_tokens
|
|
13
|
+
|
|
14
|
+
class DiffSlicer:
|
|
15
|
+
"""Slices and compresses code diffs."""
|
|
16
|
+
|
|
17
|
+
IGNORED_DIFF_PATTERNS = (
|
|
18
|
+
"package-lock.json", "pnpm-lock.yaml", "yarn.lock", "bun.lock", "bun.lockb",
|
|
19
|
+
"Cargo.lock", "go.sum", "composer.lock", ".min.js", ".min.css", ".bundle.js", ".map"
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
HUNK_HEADER_RE = re.compile(r"^@@\s+-\d+(?:,\d+)?\s+\+\d+(?:,\d+)?\s+@@(.*)$")
|
|
23
|
+
|
|
24
|
+
@classmethod
|
|
25
|
+
def slice_diff(cls, raw_diff: str, max_context_lines: int = 2) -> Tuple[str, int, int]:
|
|
26
|
+
"""
|
|
27
|
+
Processes unified diff output:
|
|
28
|
+
- Drops diffs for lockfiles/generated files
|
|
29
|
+
- Compresses long runs of unmodified context lines (' ') to max_context_lines
|
|
30
|
+
- Retains all additions ('+') and deletions ('-')
|
|
31
|
+
Returns: (compact_diff, original_tokens, compact_tokens)
|
|
32
|
+
"""
|
|
33
|
+
if not raw_diff or not raw_diff.strip():
|
|
34
|
+
return raw_diff, 0, 0
|
|
35
|
+
|
|
36
|
+
orig_tokens = count_tokens(raw_diff)
|
|
37
|
+
lines = raw_diff.splitlines()
|
|
38
|
+
output_lines: List[str] = []
|
|
39
|
+
|
|
40
|
+
current_file = ""
|
|
41
|
+
skip_current_file = False
|
|
42
|
+
context_run: List[str] = []
|
|
43
|
+
|
|
44
|
+
def flush_context(limit: int, is_trailing: bool = False):
|
|
45
|
+
nonlocal context_run, output_lines
|
|
46
|
+
if not context_run:
|
|
47
|
+
return
|
|
48
|
+
if len(context_run) <= limit:
|
|
49
|
+
output_lines.extend(context_run)
|
|
50
|
+
else:
|
|
51
|
+
if is_trailing:
|
|
52
|
+
# Keep first N lines of trailing context
|
|
53
|
+
output_lines.extend(context_run[:limit])
|
|
54
|
+
output_lines.append(f" ... ({len(context_run) - limit} context lines omitted)")
|
|
55
|
+
else:
|
|
56
|
+
# Keep last N lines of leading context
|
|
57
|
+
output_lines.append(f" ... ({len(context_run) - limit} context lines omitted)")
|
|
58
|
+
output_lines.extend(context_run[-limit:])
|
|
59
|
+
context_run = []
|
|
60
|
+
|
|
61
|
+
for line in lines:
|
|
62
|
+
# File header detection
|
|
63
|
+
if line.startswith("diff --git "):
|
|
64
|
+
flush_context(max_context_lines, is_trailing=True)
|
|
65
|
+
parts = line.split(" ")
|
|
66
|
+
current_file = parts[-1] if len(parts) > 2 else ""
|
|
67
|
+
# Check if ignored file pattern or extension
|
|
68
|
+
skip_current_file = any(pat in current_file for pat in cls.IGNORED_DIFF_PATTERNS) or current_file.endswith((".lock", ".lockb", ".sum", ".map", ".png", ".jpg", ".svg"))
|
|
69
|
+
if skip_current_file:
|
|
70
|
+
output_lines.append(f"[Diff Slicer: Omitted diff for lockfile/binary asset '{current_file}']")
|
|
71
|
+
continue
|
|
72
|
+
output_lines.append(line)
|
|
73
|
+
continue
|
|
74
|
+
|
|
75
|
+
if skip_current_file:
|
|
76
|
+
continue
|
|
77
|
+
|
|
78
|
+
# Hunk header
|
|
79
|
+
if line.startswith("@@ "):
|
|
80
|
+
flush_context(max_context_lines, is_trailing=True)
|
|
81
|
+
output_lines.append(line)
|
|
82
|
+
continue
|
|
83
|
+
|
|
84
|
+
# Added or deleted lines
|
|
85
|
+
if line.startswith("+") or line.startswith("-"):
|
|
86
|
+
flush_context(max_context_lines, is_trailing=False)
|
|
87
|
+
output_lines.append(line)
|
|
88
|
+
continue
|
|
89
|
+
|
|
90
|
+
# Context line (starts with space or empty in diff)
|
|
91
|
+
if line.startswith(" ") or line == "":
|
|
92
|
+
context_run.append(line)
|
|
93
|
+
continue
|
|
94
|
+
|
|
95
|
+
# Metadata headers (index, ---, +++)
|
|
96
|
+
output_lines.append(line)
|
|
97
|
+
|
|
98
|
+
flush_context(max_context_lines, is_trailing=True)
|
|
99
|
+
|
|
100
|
+
compact_diff = "\n".join(output_lines)
|
|
101
|
+
compact_tokens = count_tokens(compact_diff)
|
|
102
|
+
|
|
103
|
+
return compact_diff, orig_tokens, compact_tokens
|
|
104
|
+
|
|
105
|
+
@classmethod
|
|
106
|
+
def optimize_git_diff_command(cls, cmd: str) -> Tuple[Optional[str], int, str]:
|
|
107
|
+
"""
|
|
108
|
+
Rewrites git diff commands to enforce 2-line unified diffs and ignore lockfiles.
|
|
109
|
+
"""
|
|
110
|
+
clean_cmd = cmd.strip()
|
|
111
|
+
if not re.search(r"\bgit\s+diff\b", clean_cmd):
|
|
112
|
+
return None, 0, ""
|
|
113
|
+
|
|
114
|
+
if "--unified=" in clean_cmd or "-U" in clean_cmd:
|
|
115
|
+
return None, 0, ""
|
|
116
|
+
|
|
117
|
+
lockfile_excludes = " ':!*lock*' ':!*.min.*' ':!*.map'"
|
|
118
|
+
optimized = clean_cmd.replace("git diff", "git diff -U2", 1) + lockfile_excludes
|
|
119
|
+
est_saved = 4000
|
|
120
|
+
return optimized, est_saved, "Enforced 2-line AST diff window and excluded lockfiles"
|
|
@@ -0,0 +1,259 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Environment Auditor & Context Bloat Guard for Antigravity Token Optimizer.
|
|
3
|
+
Detects heavy MCP servers, redundant tool schemas, and excessive skills that bloat
|
|
4
|
+
the system prompt on every API turn. Provides one-click enable/disable toggles.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import os
|
|
8
|
+
import json
|
|
9
|
+
from typing import Dict, List, Any, Optional
|
|
10
|
+
|
|
11
|
+
EST_TOKENS_PER_TOOL = 25
|
|
12
|
+
EST_TOKENS_PER_SKILL = 180
|
|
13
|
+
CRITICAL_TOOL_COUNT_THRESHOLD = 40
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class EnvironmentAuditor:
|
|
17
|
+
"""Scans and audits static context overhead (MCP servers and skills)."""
|
|
18
|
+
|
|
19
|
+
@classmethod
|
|
20
|
+
def get_config_paths(cls) -> List[str]:
|
|
21
|
+
home = os.path.expanduser("~")
|
|
22
|
+
return [
|
|
23
|
+
os.path.join(home, ".gemini", "config", "mcp_config.json"),
|
|
24
|
+
os.path.join(home, ".gemini", "antigravity", "mcp_config.json")
|
|
25
|
+
]
|
|
26
|
+
|
|
27
|
+
@classmethod
|
|
28
|
+
def get_mcp_schemas_dir(cls) -> str:
|
|
29
|
+
return os.path.join(os.path.expanduser("~"), ".gemini", "antigravity", "mcp")
|
|
30
|
+
|
|
31
|
+
@classmethod
|
|
32
|
+
def get_skills_dirs(cls) -> List[str]:
|
|
33
|
+
home = os.path.expanduser("~")
|
|
34
|
+
dirs = [
|
|
35
|
+
os.path.join(home, ".gemini", "config", "skills"),
|
|
36
|
+
os.path.join(home, ".gemini", "config", "plugins"),
|
|
37
|
+
os.path.join(home, ".gemini", "antigravity", "builtin", "skills"),
|
|
38
|
+
]
|
|
39
|
+
return [d for d in dirs if os.path.isdir(d)]
|
|
40
|
+
|
|
41
|
+
@classmethod
|
|
42
|
+
def get_configured_mcp_servers(cls) -> Dict[str, Any]:
|
|
43
|
+
for p in cls.get_config_paths():
|
|
44
|
+
if os.path.isfile(p):
|
|
45
|
+
try:
|
|
46
|
+
with open(p, "r", encoding="utf-8") as f:
|
|
47
|
+
data = json.load(f)
|
|
48
|
+
return data.get("mcpServers", {})
|
|
49
|
+
except Exception:
|
|
50
|
+
continue
|
|
51
|
+
return {}
|
|
52
|
+
|
|
53
|
+
@classmethod
|
|
54
|
+
def audit(cls) -> Dict[str, Any]:
|
|
55
|
+
"""Audits all active MCP servers and skills for context footprint."""
|
|
56
|
+
configured = cls.get_configured_mcp_servers()
|
|
57
|
+
schemas_dir = cls.get_mcp_schemas_dir()
|
|
58
|
+
|
|
59
|
+
servers = {}
|
|
60
|
+
# 1. Discover all servers from schema directories
|
|
61
|
+
if os.path.isdir(schemas_dir):
|
|
62
|
+
for entry in os.listdir(schemas_dir):
|
|
63
|
+
entry_path = os.path.join(schemas_dir, entry)
|
|
64
|
+
if not os.path.isdir(entry_path):
|
|
65
|
+
continue
|
|
66
|
+
|
|
67
|
+
is_disabled = entry.endswith(".disabled")
|
|
68
|
+
srv_name = entry[:-9] if is_disabled else entry
|
|
69
|
+
|
|
70
|
+
# Count tool schemas
|
|
71
|
+
tool_files = [f for f in os.listdir(entry_path) if f.endswith(".json")]
|
|
72
|
+
tool_count = len(tool_files)
|
|
73
|
+
|
|
74
|
+
is_active = (not is_disabled) and (srv_name in configured)
|
|
75
|
+
est_tokens = tool_count * EST_TOKENS_PER_TOOL
|
|
76
|
+
|
|
77
|
+
servers[srv_name] = {
|
|
78
|
+
"name": srv_name,
|
|
79
|
+
"active": is_active,
|
|
80
|
+
"disabled": is_disabled,
|
|
81
|
+
"tool_count": tool_count,
|
|
82
|
+
"est_tokens_per_turn": est_tokens,
|
|
83
|
+
"is_bloat": is_active and (tool_count >= CRITICAL_TOOL_COUNT_THRESHOLD)
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
# Include configured servers that might not have a schema dir cached yet
|
|
87
|
+
for srv_name in configured:
|
|
88
|
+
if srv_name not in servers:
|
|
89
|
+
servers[srv_name] = {
|
|
90
|
+
"name": srv_name,
|
|
91
|
+
"active": True,
|
|
92
|
+
"disabled": False,
|
|
93
|
+
"tool_count": 5, # default estimate
|
|
94
|
+
"est_tokens_per_turn": 5 * EST_TOKENS_PER_TOOL,
|
|
95
|
+
"is_bloat": False
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
# 2. Count skills
|
|
99
|
+
skills_count = 0
|
|
100
|
+
for sdir in cls.get_skills_dirs():
|
|
101
|
+
for root, dirs, files in os.walk(sdir):
|
|
102
|
+
if "SKILL.md" in files:
|
|
103
|
+
skills_count += 1
|
|
104
|
+
|
|
105
|
+
total_mcp_tools = sum(s["tool_count"] for s in servers.values() if s["active"])
|
|
106
|
+
total_mcp_tokens = sum(s["est_tokens_per_turn"] for s in servers.values() if s["active"])
|
|
107
|
+
total_skills_tokens = skills_count * EST_TOKENS_PER_SKILL
|
|
108
|
+
total_static_tokens = total_mcp_tokens + total_skills_tokens
|
|
109
|
+
|
|
110
|
+
bloated_servers = [s for s in servers.values() if s["is_bloat"]]
|
|
111
|
+
|
|
112
|
+
return {
|
|
113
|
+
"servers": servers,
|
|
114
|
+
"total_active_servers": len([s for s in servers.values() if s["active"]]),
|
|
115
|
+
"total_tools": total_mcp_tools,
|
|
116
|
+
"total_skills": skills_count,
|
|
117
|
+
"mcp_tokens_per_turn": total_mcp_tokens,
|
|
118
|
+
"skills_tokens_per_turn": total_skills_tokens,
|
|
119
|
+
"total_static_tokens_per_turn": total_static_tokens,
|
|
120
|
+
"bloated_servers": bloated_servers,
|
|
121
|
+
"has_critical_bloat": len(bloated_servers) > 0
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
@classmethod
|
|
125
|
+
def get_bloat_warning(cls) -> Optional[str]:
|
|
126
|
+
"""Returns a formatted warning string if critical context bloat is detected."""
|
|
127
|
+
report = cls.audit()
|
|
128
|
+
if not report["has_critical_bloat"]:
|
|
129
|
+
return None
|
|
130
|
+
|
|
131
|
+
bloated = report["bloated_servers"]
|
|
132
|
+
names = ", ".join([f"`{b['name']}` ({b['tool_count']} инструментов, ~{b['est_tokens_per_turn']:,} токенов/шаг)" for b in bloated])
|
|
133
|
+
return (
|
|
134
|
+
f"⚠️ **TokenSafe Bloat Alert**: Обнаружен тяжелый MCP сервер: {names}. "
|
|
135
|
+
f"Суммарный налог на каждый запрос: **~{report['total_static_tokens_per_turn']:,} токенов**. "
|
|
136
|
+
f"Отключите неиспользуемые серверы через `./bin/agy-tokens mcp disable <name>`."
|
|
137
|
+
)
|
|
138
|
+
|
|
139
|
+
@classmethod
|
|
140
|
+
def disable_mcp(cls, server_name: str) -> Dict[str, Any]:
|
|
141
|
+
"""Disables an MCP server in mcp_config.json and renames its schema directory."""
|
|
142
|
+
server_name = server_name.strip()
|
|
143
|
+
schemas_dir = cls.get_mcp_schemas_dir()
|
|
144
|
+
|
|
145
|
+
# 1. Update config files
|
|
146
|
+
modified = False
|
|
147
|
+
server_config = None
|
|
148
|
+
for p in cls.get_config_paths():
|
|
149
|
+
real_path = os.path.realpath(p)
|
|
150
|
+
if os.path.isfile(real_path):
|
|
151
|
+
try:
|
|
152
|
+
with open(real_path, "r", encoding="utf-8") as f:
|
|
153
|
+
data = json.load(f)
|
|
154
|
+
mcp_servers = data.get("mcpServers", {})
|
|
155
|
+
if server_name in mcp_servers:
|
|
156
|
+
server_config = mcp_servers.pop(server_name)
|
|
157
|
+
# Save disabled config
|
|
158
|
+
if "disabledMcpServers" not in data:
|
|
159
|
+
data["disabledMcpServers"] = {}
|
|
160
|
+
data["disabledMcpServers"][server_name] = server_config
|
|
161
|
+
with open(real_path, "w", encoding="utf-8") as f:
|
|
162
|
+
json.dump(data, f, indent=2)
|
|
163
|
+
modified = True
|
|
164
|
+
except Exception:
|
|
165
|
+
pass
|
|
166
|
+
|
|
167
|
+
# 2. Rename schema directory to .disabled
|
|
168
|
+
active_dir = os.path.join(schemas_dir, server_name)
|
|
169
|
+
disabled_dir = os.path.join(schemas_dir, f"{server_name}.disabled")
|
|
170
|
+
renamed = False
|
|
171
|
+
if os.path.isdir(active_dir):
|
|
172
|
+
try:
|
|
173
|
+
os.rename(active_dir, disabled_dir)
|
|
174
|
+
renamed = True
|
|
175
|
+
except Exception:
|
|
176
|
+
pass
|
|
177
|
+
|
|
178
|
+
return {
|
|
179
|
+
"success": modified or renamed,
|
|
180
|
+
"server_name": server_name,
|
|
181
|
+
"config_updated": modified,
|
|
182
|
+
"directory_renamed": renamed
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
@classmethod
|
|
186
|
+
def enable_mcp(cls, server_name: str) -> Dict[str, Any]:
|
|
187
|
+
"""Re-enables a previously disabled MCP server."""
|
|
188
|
+
server_name = server_name.strip()
|
|
189
|
+
schemas_dir = cls.get_mcp_schemas_dir()
|
|
190
|
+
|
|
191
|
+
# 1. Update config files
|
|
192
|
+
modified = False
|
|
193
|
+
for p in cls.get_config_paths():
|
|
194
|
+
real_path = os.path.realpath(p)
|
|
195
|
+
if os.path.isfile(real_path):
|
|
196
|
+
try:
|
|
197
|
+
with open(real_path, "r", encoding="utf-8") as f:
|
|
198
|
+
data = json.load(f)
|
|
199
|
+
disabled_servers = data.get("disabledMcpServers", {})
|
|
200
|
+
if server_name in disabled_servers:
|
|
201
|
+
srv_cfg = disabled_servers.pop(server_name)
|
|
202
|
+
if "mcpServers" not in data:
|
|
203
|
+
data["mcpServers"] = {}
|
|
204
|
+
data["mcpServers"][server_name] = srv_cfg
|
|
205
|
+
with open(real_path, "w", encoding="utf-8") as f:
|
|
206
|
+
json.dump(data, f, indent=2)
|
|
207
|
+
modified = True
|
|
208
|
+
except Exception:
|
|
209
|
+
pass
|
|
210
|
+
|
|
211
|
+
# 2. Rename schema directory from .disabled
|
|
212
|
+
disabled_dir = os.path.join(schemas_dir, f"{server_name}.disabled")
|
|
213
|
+
active_dir = os.path.join(schemas_dir, server_name)
|
|
214
|
+
renamed = False
|
|
215
|
+
if os.path.isdir(disabled_dir):
|
|
216
|
+
try:
|
|
217
|
+
os.rename(disabled_dir, active_dir)
|
|
218
|
+
renamed = True
|
|
219
|
+
except Exception:
|
|
220
|
+
pass
|
|
221
|
+
|
|
222
|
+
return {
|
|
223
|
+
"success": modified or renamed,
|
|
224
|
+
"server_name": server_name,
|
|
225
|
+
"config_updated": modified,
|
|
226
|
+
"directory_renamed": renamed
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
@classmethod
|
|
230
|
+
def format_cli_report(cls) -> str:
|
|
231
|
+
"""Formats visual CLI report for agy-tokens doctor."""
|
|
232
|
+
report = cls.audit()
|
|
233
|
+
lines = [
|
|
234
|
+
"\n\033[1m\033[36m⚡ TOKENSAFE ENVIRONMENT AUDIT (CONTEXT TAX DOCTOR) ⚡\033[0m\n",
|
|
235
|
+
f" \033[1mTotal Base Context Tax:\033[0m ~{report['total_static_tokens_per_turn']:,} tokens on EVERY API turn\n",
|
|
236
|
+
" \033[1mActive MCP Servers:\033[0m"
|
|
237
|
+
]
|
|
238
|
+
|
|
239
|
+
for name, s in sorted(report["servers"].items()):
|
|
240
|
+
if s["active"]:
|
|
241
|
+
if s["is_bloat"]:
|
|
242
|
+
status = f"\033[31m\033[1m✖ {name:<18} ({s['tool_count']:>3} tools) [CRITICAL BLOAT: ~{s['est_tokens_per_turn']:,} tok/turn]\033[0m"
|
|
243
|
+
else:
|
|
244
|
+
status = f"\033[32m✔ {name:<18} ({s['tool_count']:>3} tools) [~{s['est_tokens_per_turn']:,} tok/turn]\033[0m"
|
|
245
|
+
else:
|
|
246
|
+
status = f"\033[2m○ {name:<18} ({s['tool_count']:>3} tools) [Disabled]\033[0m"
|
|
247
|
+
lines.append(f" {status}")
|
|
248
|
+
|
|
249
|
+
lines.append(f"\n \033[1mInstalled Skills:\033[0m {report['total_skills']} skills (~{report['skills_tokens_per_turn']:,} tokens/turn)")
|
|
250
|
+
|
|
251
|
+
if report["has_critical_bloat"]:
|
|
252
|
+
lines.append("\n \033[33m\033[1mDiagnostic Recommendation:\033[0m")
|
|
253
|
+
for b in report["bloated_servers"]:
|
|
254
|
+
lines.append(f" ➜ Run: \033[36m./bin/agy-tokens mcp disable {b['name']}\033[0m to save ~{b['est_tokens_per_turn']:,} tokens per turn!")
|
|
255
|
+
else:
|
|
256
|
+
lines.append("\n \033[32m✔ Environment healthy: No critical MCP bloat detected.\033[0m")
|
|
257
|
+
|
|
258
|
+
lines.append("")
|
|
259
|
+
return "\n".join(lines)
|
package/src/governor.py
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
"""
|
|
2
|
+
TokenSafe Context Window Governor & Token Ceiling Engine.
|
|
3
|
+
Enforces deterministic token limits per turn or session (Budget Autothrottle).
|
|
4
|
+
If context exceeds threshold, applies multi-stage cascading reduction:
|
|
5
|
+
Stage 1: AST-folds large inert code blocks into signatures
|
|
6
|
+
Stage 2: Compacts intermediate user turns into TOCP Intent IR
|
|
7
|
+
Stage 3: Consolidates oldest middle history into State Ledger
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import os
|
|
11
|
+
import re
|
|
12
|
+
from typing import Dict, List, Any, Tuple, Optional
|
|
13
|
+
from src.tokenizer import count_tokens
|
|
14
|
+
from src.skeletonizer import Skeletonizer
|
|
15
|
+
from src.compactor import PromptCompactor
|
|
16
|
+
from src.metrics import MetricsTracker
|
|
17
|
+
|
|
18
|
+
class ContextGovernor:
|
|
19
|
+
"""Monitors and enforces context ceilings before LLM dispatch."""
|
|
20
|
+
|
|
21
|
+
DEFAULT_MAX_TURN_TOKENS = int(os.environ.get("TOKENSAFE_MAX_TURN_TOKENS", "16000"))
|
|
22
|
+
DEFAULT_TARGET_TURN_TOKENS = int(os.environ.get("TOKENSAFE_TARGET_TURN_TOKENS", "10000"))
|
|
23
|
+
|
|
24
|
+
CODE_BLOCK_REGEX = re.compile(r"```([a-zA-Z0-9_\-+]*)\n(.*?)```", re.DOTALL)
|
|
25
|
+
|
|
26
|
+
@classmethod
|
|
27
|
+
def govern_messages(
|
|
28
|
+
cls,
|
|
29
|
+
messages: List[Dict[str, Any]],
|
|
30
|
+
max_tokens: Optional[int] = None,
|
|
31
|
+
target_tokens: Optional[int] = None,
|
|
32
|
+
session_id: str = "governor_session"
|
|
33
|
+
) -> Tuple[List[Dict[str, Any]], Dict[str, Any]]:
|
|
34
|
+
"""
|
|
35
|
+
Inspects message list. If total tokens exceed max_tokens, applies cascading
|
|
36
|
+
reductions until within target_tokens budget.
|
|
37
|
+
"""
|
|
38
|
+
max_budget = max_tokens if max_tokens is not None else cls.DEFAULT_MAX_TURN_TOKENS
|
|
39
|
+
target_budget = target_tokens if target_tokens is not None else cls.DEFAULT_TARGET_TURN_TOKENS
|
|
40
|
+
|
|
41
|
+
if max_budget <= 0:
|
|
42
|
+
return messages, {"throttled": False, "saved_tokens": 0}
|
|
43
|
+
|
|
44
|
+
def calculate_total_tokens(msgs: List[Dict[str, Any]]) -> int:
|
|
45
|
+
total = 0
|
|
46
|
+
for m in msgs:
|
|
47
|
+
c = m.get("content")
|
|
48
|
+
if isinstance(c, str):
|
|
49
|
+
total += count_tokens(c)
|
|
50
|
+
elif isinstance(c, list):
|
|
51
|
+
for item in c:
|
|
52
|
+
if isinstance(item, dict) and "text" in item:
|
|
53
|
+
total += count_tokens(item["text"])
|
|
54
|
+
return total
|
|
55
|
+
|
|
56
|
+
initial_tokens = calculate_total_tokens(messages)
|
|
57
|
+
if initial_tokens <= max_budget:
|
|
58
|
+
return messages, {
|
|
59
|
+
"throttled": False,
|
|
60
|
+
"initial_tokens": initial_tokens,
|
|
61
|
+
"current_tokens": initial_tokens,
|
|
62
|
+
"saved_tokens": 0,
|
|
63
|
+
"actions": []
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
actions_taken = []
|
|
67
|
+
governed_messages = [dict(m) for m in messages]
|
|
68
|
+
current_tokens = initial_tokens
|
|
69
|
+
|
|
70
|
+
# --- Stage 1: AST Skeletonize large inert code blocks in previous turns ---
|
|
71
|
+
for idx in range(len(governed_messages) - 1): # leave last user turn untouched
|
|
72
|
+
msg = governed_messages[idx]
|
|
73
|
+
content = msg.get("content")
|
|
74
|
+
if not isinstance(content, str) or "```" not in content:
|
|
75
|
+
continue
|
|
76
|
+
|
|
77
|
+
def fold_match(match):
|
|
78
|
+
lang = (match.group(1) or "py").lower()
|
|
79
|
+
code_text = match.group(2)
|
|
80
|
+
lines = code_text.splitlines()
|
|
81
|
+
if len(lines) < 25:
|
|
82
|
+
return match.group(0)
|
|
83
|
+
|
|
84
|
+
ext = f".{lang}" if not lang.startswith(".") else lang
|
|
85
|
+
if ext not in (".py", ".ts", ".js", ".tsx", ".jsx", ".go", ".java", ".rs", ".c", ".cpp"):
|
|
86
|
+
ext = ".py"
|
|
87
|
+
|
|
88
|
+
skel = Skeletonizer.skeletonize_code(code_text, ext)
|
|
89
|
+
if count_tokens(skel) < count_tokens(code_text) - 50:
|
|
90
|
+
return f"```{lang}\n// [Context Governor: AST-folded {len(lines)} lines]\n{skel}\n```"
|
|
91
|
+
return match.group(0)
|
|
92
|
+
|
|
93
|
+
new_content = cls.CODE_BLOCK_REGEX.sub(fold_match, content)
|
|
94
|
+
if new_content != content:
|
|
95
|
+
governed_messages[idx]["content"] = new_content
|
|
96
|
+
|
|
97
|
+
current_tokens = calculate_total_tokens(governed_messages)
|
|
98
|
+
if current_tokens < initial_tokens:
|
|
99
|
+
actions_taken.append("ast_fold_code_blocks")
|
|
100
|
+
|
|
101
|
+
# --- Stage 2: S-Expression Compaction of older user prompts ---
|
|
102
|
+
if current_tokens > target_budget:
|
|
103
|
+
for idx in range(len(governed_messages) - 1):
|
|
104
|
+
msg = governed_messages[idx]
|
|
105
|
+
if msg.get("role") == "user" and isinstance(msg.get("content"), str):
|
|
106
|
+
raw_user = msg["content"]
|
|
107
|
+
if len(raw_user.strip()) > 15 and "[TOCP Intent]" not in raw_user:
|
|
108
|
+
comp = PromptCompactor.compact(raw_user, enable_deepseek=False)
|
|
109
|
+
if comp["saved_tokens"] >= 5:
|
|
110
|
+
msg["content"] = f"[TOCP Intent]: {comp['compact_text']}"
|
|
111
|
+
current_tokens = calculate_total_tokens(governed_messages)
|
|
112
|
+
if "ast_fold_code_blocks" not in actions_taken or current_tokens < initial_tokens:
|
|
113
|
+
actions_taken.append("compact_user_history")
|
|
114
|
+
|
|
115
|
+
# --- Stage 3: Sliding ledger summarization of deep history if still over target ---
|
|
116
|
+
if current_tokens > target_budget and len(governed_messages) > 6:
|
|
117
|
+
# Keep first system message and last 3 turns intact, fold middle
|
|
118
|
+
sys_msg = governed_messages[0] if governed_messages[0].get("role") == "system" else None
|
|
119
|
+
recent_turns = governed_messages[-3:]
|
|
120
|
+
middle_turns = governed_messages[1:-3] if sys_msg else governed_messages[:-3]
|
|
121
|
+
|
|
122
|
+
middle_user_intents = []
|
|
123
|
+
for m in middle_turns:
|
|
124
|
+
c = m.get("content", "")
|
|
125
|
+
if m.get("role") == "user" and isinstance(c, str):
|
|
126
|
+
first_line = c.splitlines()[0][:80]
|
|
127
|
+
middle_user_intents.append(f"- {first_line}")
|
|
128
|
+
|
|
129
|
+
summary_note = (
|
|
130
|
+
f"[Context Governor Ledger: Consolidated {len(middle_turns)} turns]\n"
|
|
131
|
+
f"Historical turn goals:\n" + "\n".join(middle_user_intents[:5]) + "\n..."
|
|
132
|
+
)
|
|
133
|
+
consolidated = []
|
|
134
|
+
if sys_msg:
|
|
135
|
+
consolidated.append(sys_msg)
|
|
136
|
+
consolidated.append({"role": "system", "content": summary_note})
|
|
137
|
+
consolidated.extend(recent_turns)
|
|
138
|
+
governed_messages = consolidated
|
|
139
|
+
actions_taken.append("consolidate_deep_history")
|
|
140
|
+
current_tokens = calculate_total_tokens(governed_messages)
|
|
141
|
+
|
|
142
|
+
saved = max(0, initial_tokens - current_tokens)
|
|
143
|
+
if saved > 0:
|
|
144
|
+
try:
|
|
145
|
+
tracker = MetricsTracker()
|
|
146
|
+
tracker.record_event(
|
|
147
|
+
session_id=session_id,
|
|
148
|
+
event_type="CONTEXT_GOVERNOR",
|
|
149
|
+
original_tokens=initial_tokens,
|
|
150
|
+
optimized_tokens=current_tokens,
|
|
151
|
+
details={
|
|
152
|
+
"actions": actions_taken,
|
|
153
|
+
"max_budget": max_budget,
|
|
154
|
+
"target_budget": target_budget
|
|
155
|
+
}
|
|
156
|
+
)
|
|
157
|
+
except Exception:
|
|
158
|
+
pass
|
|
159
|
+
|
|
160
|
+
return governed_messages, {
|
|
161
|
+
"throttled": True,
|
|
162
|
+
"initial_tokens": initial_tokens,
|
|
163
|
+
"current_tokens": current_tokens,
|
|
164
|
+
"saved_tokens": saved,
|
|
165
|
+
"actions": actions_taken
|
|
166
|
+
}
|
package/src/graph_engine.py
CHANGED
|
@@ -88,6 +88,10 @@ class CodeGraph:
|
|
|
88
88
|
Fast incremental scan of the workspace.
|
|
89
89
|
Parses modified files only; returns number of files re-indexed.
|
|
90
90
|
"""
|
|
91
|
+
system_roots = {"/", "/Users", "/home", "/root", os.path.expanduser("~")}
|
|
92
|
+
if self.root_dir in system_roots:
|
|
93
|
+
return 0
|
|
94
|
+
|
|
91
95
|
reindexed = 0
|
|
92
96
|
current_files = set()
|
|
93
97
|
|