tokensafe 1.3.0 → 1.3.2
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 +148 -6
- package/bin/agy-tokens +152 -4
- package/hooks/pre_invocation.py +17 -0
- package/hooks/pre_tool_use.py +23 -3
- package/package.json +2 -2
- 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/cache_normalizer.py +105 -0
- package/src/compactor.py +30 -5
- package/src/dashboard.py +41 -6
- package/src/deepseek_distiller.py +10 -2
- package/src/diff_slicer.py +120 -0
- package/src/distiller.py +12 -3
- package/src/distiller_cache.py +216 -0
- package/src/environment_auditor.py +259 -0
- package/src/governor.py +166 -0
- package/src/installer.py +104 -33
- package/src/mcp_server.py +35 -1
- package/src/metrics.py +216 -21
- package/src/proxy.py +142 -19
- package/src/version_checker.py +1 -1
- package/src/weekly_digest.py +305 -0
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
"""
|
|
2
|
+
TokenSafe Subagent Firewall: Cross-Agent Deduplication Cache.
|
|
3
|
+
Detects redundant file inspection across parent-subagent workflows and swarms.
|
|
4
|
+
If an agent or subagent requests a file already ingested within the session,
|
|
5
|
+
serves cached AST representation and suppresses quadratic token waste.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import os
|
|
9
|
+
import time
|
|
10
|
+
import sqlite3
|
|
11
|
+
from typing import Tuple, Optional, Dict, Any
|
|
12
|
+
from src.metrics import MetricsTracker
|
|
13
|
+
from src.tokenizer import count_tokens
|
|
14
|
+
|
|
15
|
+
class AgentFirewall:
|
|
16
|
+
"""Manages cross-agent shared file cache within active sessions."""
|
|
17
|
+
|
|
18
|
+
_INITIALIZED_DBS = set()
|
|
19
|
+
|
|
20
|
+
@classmethod
|
|
21
|
+
def _ensure_table(cls, tracker: MetricsTracker):
|
|
22
|
+
"""Initializes the subagent cache table once per database path."""
|
|
23
|
+
if tracker.db_path in cls._INITIALIZED_DBS:
|
|
24
|
+
return
|
|
25
|
+
with tracker._get_connection() as conn:
|
|
26
|
+
conn.execute("""
|
|
27
|
+
CREATE TABLE IF NOT EXISTS subagent_file_cache (
|
|
28
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
29
|
+
session_id TEXT NOT NULL,
|
|
30
|
+
file_path TEXT NOT NULL,
|
|
31
|
+
mtime REAL NOT NULL,
|
|
32
|
+
symbol TEXT NOT NULL DEFAULT '',
|
|
33
|
+
content TEXT NOT NULL,
|
|
34
|
+
tokens INTEGER NOT NULL,
|
|
35
|
+
created_at INTEGER NOT NULL,
|
|
36
|
+
hit_count INTEGER NOT NULL DEFAULT 0,
|
|
37
|
+
UNIQUE(session_id, file_path, symbol)
|
|
38
|
+
);
|
|
39
|
+
""")
|
|
40
|
+
conn.execute("CREATE INDEX IF NOT EXISTS idx_subagent_cache ON subagent_file_cache(session_id, file_path);")
|
|
41
|
+
cls._INITIALIZED_DBS.add(tracker.db_path)
|
|
42
|
+
|
|
43
|
+
@classmethod
|
|
44
|
+
def check_cache(
|
|
45
|
+
cls,
|
|
46
|
+
session_id: str,
|
|
47
|
+
file_path: str,
|
|
48
|
+
symbol: str = "",
|
|
49
|
+
tracker: Optional[MetricsTracker] = None
|
|
50
|
+
) -> Tuple[bool, Optional[str], int]:
|
|
51
|
+
"""
|
|
52
|
+
Checks if file has already been ingested in this session with unchanged mtime.
|
|
53
|
+
Returns: (is_hit, cached_content_or_none, tokens_saved)
|
|
54
|
+
"""
|
|
55
|
+
if not file_path or not os.path.exists(file_path):
|
|
56
|
+
return False, None, 0
|
|
57
|
+
|
|
58
|
+
tracker = tracker or MetricsTracker()
|
|
59
|
+
cls._ensure_table(tracker)
|
|
60
|
+
|
|
61
|
+
try:
|
|
62
|
+
current_mtime = os.path.getmtime(file_path)
|
|
63
|
+
except OSError:
|
|
64
|
+
return False, None, 0
|
|
65
|
+
|
|
66
|
+
abs_path = os.path.abspath(file_path)
|
|
67
|
+
symbol_key = (symbol or "").strip()
|
|
68
|
+
|
|
69
|
+
hit_data = None
|
|
70
|
+
with tracker._get_connection() as conn:
|
|
71
|
+
row = conn.execute("""
|
|
72
|
+
SELECT id, content, tokens, mtime, hit_count
|
|
73
|
+
FROM subagent_file_cache
|
|
74
|
+
WHERE session_id = ? AND file_path = ? AND symbol = ?;
|
|
75
|
+
""", (session_id, abs_path, symbol_key)).fetchone()
|
|
76
|
+
|
|
77
|
+
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)
|
|
85
|
+
|
|
86
|
+
if hit_data:
|
|
87
|
+
content, tokens, hit_count = hit_data
|
|
88
|
+
try:
|
|
89
|
+
tracker.record_event(
|
|
90
|
+
session_id=session_id,
|
|
91
|
+
event_type="SUBAGENT_DEDUP",
|
|
92
|
+
original_tokens=tokens,
|
|
93
|
+
optimized_tokens=40, # minimal cache reference tokens
|
|
94
|
+
details={
|
|
95
|
+
"target_file": os.path.basename(abs_path),
|
|
96
|
+
"symbol": symbol_key,
|
|
97
|
+
"hit_number": hit_count
|
|
98
|
+
}
|
|
99
|
+
)
|
|
100
|
+
except Exception:
|
|
101
|
+
pass
|
|
102
|
+
|
|
103
|
+
header = (
|
|
104
|
+
f"// [TokenSafe Subagent Firewall: Reused session read for '{os.path.basename(abs_path)}' "
|
|
105
|
+
f"(Dedup Hit #{hit_count}, Saved ~{tokens - 40} tokens)]\n"
|
|
106
|
+
)
|
|
107
|
+
return True, header + content, max(0, tokens - 40)
|
|
108
|
+
|
|
109
|
+
return False, None, 0
|
|
110
|
+
|
|
111
|
+
@classmethod
|
|
112
|
+
def record_cache(
|
|
113
|
+
cls,
|
|
114
|
+
session_id: str,
|
|
115
|
+
file_path: str,
|
|
116
|
+
content: str,
|
|
117
|
+
symbol: str = "",
|
|
118
|
+
tracker: Optional[MetricsTracker] = None
|
|
119
|
+
):
|
|
120
|
+
"""Caches file read content for subagent reuse in the active session."""
|
|
121
|
+
if not file_path or not content or not os.path.exists(file_path):
|
|
122
|
+
return
|
|
123
|
+
|
|
124
|
+
tracker = tracker or MetricsTracker()
|
|
125
|
+
cls._ensure_table(tracker)
|
|
126
|
+
|
|
127
|
+
try:
|
|
128
|
+
mtime = os.path.getmtime(file_path)
|
|
129
|
+
except OSError:
|
|
130
|
+
mtime = time.time()
|
|
131
|
+
|
|
132
|
+
abs_path = os.path.abspath(file_path)
|
|
133
|
+
symbol_key = (symbol or "").strip()
|
|
134
|
+
tokens = count_tokens(content)
|
|
135
|
+
now = int(time.time())
|
|
136
|
+
|
|
137
|
+
with tracker._get_connection() as conn:
|
|
138
|
+
conn.execute("""
|
|
139
|
+
INSERT INTO subagent_file_cache (session_id, file_path, mtime, symbol, content, tokens, created_at, hit_count)
|
|
140
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, 0)
|
|
141
|
+
ON CONFLICT(session_id, file_path, symbol) DO UPDATE SET
|
|
142
|
+
mtime = excluded.mtime,
|
|
143
|
+
content = excluded.content,
|
|
144
|
+
tokens = excluded.tokens,
|
|
145
|
+
created_at = excluded.created_at;
|
|
146
|
+
""", (session_id, abs_path, mtime, symbol_key, content, tokens, now))
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
"""
|
|
2
|
+
TokenSafe Prompt Cache Prefix Normalizer.
|
|
3
|
+
Normalizes system instructions, architectural banners, and invariant tool definitions
|
|
4
|
+
into deterministic prefixes to guarantee up to 90% prompt cache hit rates on
|
|
5
|
+
Anthropic (Claude 3.5), DeepSeek-V3, and OpenAI.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import re
|
|
9
|
+
import json
|
|
10
|
+
import hashlib
|
|
11
|
+
from typing import Dict, List, Any, Tuple, Optional
|
|
12
|
+
from src.tokenizer import count_tokens
|
|
13
|
+
|
|
14
|
+
class PromptCacheNormalizer:
|
|
15
|
+
"""Normalizes prompt message streams into cache-friendly deterministic prefixes."""
|
|
16
|
+
|
|
17
|
+
VOLATILE_PATTERNS = [
|
|
18
|
+
re.compile(r"The current local time is:.*?(?=\n|$)", re.IGNORECASE),
|
|
19
|
+
re.compile(r"timestamp=\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z?", re.IGNORECASE),
|
|
20
|
+
re.compile(r"request_id=['\"][a-zA-Z0-9_-]+['\"]", re.IGNORECASE),
|
|
21
|
+
re.compile(r"uuid=['\"][a-f0-9-]{36}['\"]", re.IGNORECASE),
|
|
22
|
+
re.compile(r"turn_count=\d+", re.IGNORECASE),
|
|
23
|
+
]
|
|
24
|
+
|
|
25
|
+
@classmethod
|
|
26
|
+
def strip_volatile_elements(cls, text: str) -> str:
|
|
27
|
+
"""Removes volatile timestamps and ephemeral request IDs from static prefix."""
|
|
28
|
+
for pattern in cls.VOLATILE_PATTERNS:
|
|
29
|
+
text = pattern.sub("", text)
|
|
30
|
+
return text
|
|
31
|
+
|
|
32
|
+
@classmethod
|
|
33
|
+
def compute_prefix_hash(cls, prefix_text: str) -> str:
|
|
34
|
+
"""Returns SHA256 hash of normalized static prefix."""
|
|
35
|
+
cleaned = re.sub(r"\s+", " ", prefix_text).strip()
|
|
36
|
+
return hashlib.sha256(cleaned.encode("utf-8")).hexdigest()
|
|
37
|
+
|
|
38
|
+
@classmethod
|
|
39
|
+
def normalize_messages(
|
|
40
|
+
cls,
|
|
41
|
+
messages: List[Dict[str, Any]],
|
|
42
|
+
provider: str = "generic",
|
|
43
|
+
inject_cache_control: bool = True
|
|
44
|
+
) -> Tuple[List[Dict[str, Any]], Dict[str, Any]]:
|
|
45
|
+
"""
|
|
46
|
+
Normalizes message list:
|
|
47
|
+
1. Separates static system/prefix instructions from dynamic turns
|
|
48
|
+
2. Sanitizes non-deterministic markers in the static prefix
|
|
49
|
+
3. For Anthropic: Injects 'cache_control: {"type": "ephemeral"}' if tokens >= 1024
|
|
50
|
+
4. Calculates prefix hash and estimated cache savings
|
|
51
|
+
"""
|
|
52
|
+
if not messages:
|
|
53
|
+
return messages, {"prefix_tokens": 0, "cache_hit_eligible": False}
|
|
54
|
+
|
|
55
|
+
normalized = []
|
|
56
|
+
static_prefix_parts = []
|
|
57
|
+
last_static_idx = -1
|
|
58
|
+
|
|
59
|
+
for idx, msg in enumerate(messages):
|
|
60
|
+
msg_copy = dict(msg)
|
|
61
|
+
role = msg_copy.get("role", "")
|
|
62
|
+
content = msg_copy.get("content", "")
|
|
63
|
+
|
|
64
|
+
# Static prefix includes system messages and developer instructions before first user turn
|
|
65
|
+
if role in ("system", "developer") and isinstance(content, str):
|
|
66
|
+
cleaned_content = cls.strip_volatile_elements(content)
|
|
67
|
+
msg_copy["content"] = cleaned_content
|
|
68
|
+
static_prefix_parts.append(cleaned_content)
|
|
69
|
+
last_static_idx = idx
|
|
70
|
+
normalized.append(msg_copy)
|
|
71
|
+
|
|
72
|
+
prefix_str = "\n".join(static_prefix_parts)
|
|
73
|
+
prefix_tokens = count_tokens(prefix_str) if prefix_str else 0
|
|
74
|
+
prefix_hash = cls.compute_prefix_hash(prefix_str) if prefix_str else ""
|
|
75
|
+
|
|
76
|
+
# Anthropic caching requires >= 1024 tokens for Claude 3.5 Sonnet / Haiku
|
|
77
|
+
# DeepSeek caches 64-token chunks
|
|
78
|
+
cache_eligible = prefix_tokens >= 64
|
|
79
|
+
cache_control_injected = False
|
|
80
|
+
|
|
81
|
+
if inject_cache_control and last_static_idx >= 0 and prefix_tokens >= 1024:
|
|
82
|
+
target_msg = normalized[last_static_idx]
|
|
83
|
+
content_val = target_msg.get("content")
|
|
84
|
+
if isinstance(content_val, str):
|
|
85
|
+
# Anthropic structured content format with cache_control block
|
|
86
|
+
target_msg["content"] = [
|
|
87
|
+
{
|
|
88
|
+
"type": "text",
|
|
89
|
+
"text": content_val,
|
|
90
|
+
"cache_control": {"type": "ephemeral"}
|
|
91
|
+
}
|
|
92
|
+
]
|
|
93
|
+
cache_control_injected = True
|
|
94
|
+
elif isinstance(content_val, list) and len(content_val) > 0:
|
|
95
|
+
if isinstance(content_val[-1], dict):
|
|
96
|
+
content_val[-1]["cache_control"] = {"type": "ephemeral"}
|
|
97
|
+
cache_control_injected = True
|
|
98
|
+
|
|
99
|
+
return normalized, {
|
|
100
|
+
"prefix_tokens": prefix_tokens,
|
|
101
|
+
"prefix_hash": prefix_hash,
|
|
102
|
+
"cache_eligible": cache_eligible,
|
|
103
|
+
"cache_control_injected": cache_control_injected,
|
|
104
|
+
"provider": provider
|
|
105
|
+
}
|
package/src/compactor.py
CHANGED
|
@@ -4,8 +4,10 @@ into ultra-dense Token-Optimized Communication Protocol (TOCP) S-Expressions.
|
|
|
4
4
|
Supports 3-Tier Routing: Pass-through -> Regex Compactor -> DeepSeek-V3 Distiller.
|
|
5
5
|
"""
|
|
6
6
|
|
|
7
|
+
import os
|
|
8
|
+
import json
|
|
7
9
|
import re
|
|
8
|
-
from typing import Dict, List, Optional
|
|
10
|
+
from typing import Dict, List, Optional, Any
|
|
9
11
|
from src.tokenizer import count_tokens
|
|
10
12
|
from src.distiller import UniversalDistiller
|
|
11
13
|
from src.secret_redactor import SecretRedactor
|
|
@@ -65,13 +67,35 @@ class PromptCompactor:
|
|
|
65
67
|
(re.compile(r"\b(unit_test|юнит\w*)\b", re.I), "unit_test"),
|
|
66
68
|
]
|
|
67
69
|
|
|
70
|
+
DEFAULT_MIN_DISTILL_TOKENS = 100
|
|
71
|
+
|
|
72
|
+
@classmethod
|
|
73
|
+
def _get_min_distill_tokens(cls) -> int:
|
|
74
|
+
"""Loads minimum token threshold for LLM distillation from config or returns 100."""
|
|
75
|
+
base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
76
|
+
config_path = os.path.join(base_dir, "data", "config.json")
|
|
77
|
+
if os.path.exists(config_path):
|
|
78
|
+
try:
|
|
79
|
+
with open(config_path, "r", encoding="utf-8") as f:
|
|
80
|
+
conf = json.load(f)
|
|
81
|
+
if "llm_distill_min_tokens" in conf:
|
|
82
|
+
return int(conf["llm_distill_min_tokens"])
|
|
83
|
+
except Exception:
|
|
84
|
+
pass
|
|
85
|
+
return cls.DEFAULT_MIN_DISTILL_TOKENS
|
|
86
|
+
|
|
68
87
|
@classmethod
|
|
69
|
-
def compact(
|
|
88
|
+
def compact(
|
|
89
|
+
cls,
|
|
90
|
+
raw_text: str,
|
|
91
|
+
enable_deepseek: bool = True,
|
|
92
|
+
min_distill_tokens: Optional[int] = None
|
|
93
|
+
) -> Dict[str, Any]:
|
|
70
94
|
"""
|
|
71
95
|
Compresses input prompt via 3-Tier Architecture:
|
|
72
96
|
- Tier 0: Pass-through for very short inputs (< 6 tokens)
|
|
73
|
-
- Tier
|
|
74
|
-
- Tier
|
|
97
|
+
- Tier 1: Local Regex Compactor (0ms, 0 external tokens) for inputs < 100 tokens
|
|
98
|
+
- Tier 2: LLM Distiller (DeepSeek / Gemini / OpenAI) for long/complex prompts (>= 100 tokens)
|
|
75
99
|
"""
|
|
76
100
|
if not raw_text or not raw_text.strip():
|
|
77
101
|
return {
|
|
@@ -112,7 +136,8 @@ class PromptCompactor:
|
|
|
112
136
|
}
|
|
113
137
|
|
|
114
138
|
# Tier 2: LLM Intent Distiller (Gemini / OpenAI / DeepSeek)
|
|
115
|
-
if
|
|
139
|
+
min_distill = min_distill_tokens if min_distill_tokens is not None else cls._get_min_distill_tokens()
|
|
140
|
+
if enable_deepseek and original_tokens >= min_distill:
|
|
116
141
|
distilled = UniversalDistiller.distill(raw_text)
|
|
117
142
|
if distilled:
|
|
118
143
|
dist_tokens = count_tokens(distilled)
|
package/src/dashboard.py
CHANGED
|
@@ -262,25 +262,27 @@ class Dashboard:
|
|
|
262
262
|
<h1 class="title">⚡ Antigravity Token Optimizer</h1>
|
|
263
263
|
<p class="subtitle">Next-gen Autonomous Token Economy & Context Preservation</p>
|
|
264
264
|
</div>
|
|
265
|
-
<div class="subtitle"
|
|
265
|
+
<div id="live-pill" class="subtitle" style="display: flex; align-items: center; gap: 6px;">
|
|
266
|
+
<span style="color: #10b981;">●</span> Live SQLite Tracking
|
|
267
|
+
</div>
|
|
266
268
|
</div>
|
|
267
269
|
|
|
268
270
|
<div class="stats-grid">
|
|
269
271
|
<div class="stat-card">
|
|
270
272
|
<div class="stat-label">Total Tokens Saved</div>
|
|
271
|
-
<div class="stat-value highlight">{total_saved:,}</div>
|
|
273
|
+
<div id="val-total-saved" class="stat-value highlight">{total_saved:,}</div>
|
|
272
274
|
</div>
|
|
273
275
|
<div class="stat-card">
|
|
274
276
|
<div class="stat-label">Net Efficiency Gain</div>
|
|
275
|
-
<div class="stat-value">{pct:.1f}%</div>
|
|
277
|
+
<div id="val-efficiency-gain" class="stat-value">{pct:.1f}%</div>
|
|
276
278
|
</div>
|
|
277
279
|
<div class="stat-card">
|
|
278
280
|
<div class="stat-label">Estimated Value Saved</div>
|
|
279
|
-
<div class="stat-value highlight">${usd:.4f}</div>
|
|
281
|
+
<div id="val-usd-saved" class="stat-value highlight">${usd:.4f}</div>
|
|
280
282
|
</div>
|
|
281
283
|
<div class="stat-card">
|
|
282
284
|
<div class="stat-label">Context Traffic</div>
|
|
283
|
-
<div class="stat-value" style="font-size: 20px; line-height: 38px;">{orig:,} ➔ {opt:,}</div>
|
|
285
|
+
<div id="val-traffic" class="stat-value" style="font-size: 20px; line-height: 38px;">{orig:,} ➔ {opt:,}</div>
|
|
284
286
|
</div>
|
|
285
287
|
</div>
|
|
286
288
|
|
|
@@ -301,12 +303,45 @@ class Dashboard:
|
|
|
301
303
|
<th>Savings</th>
|
|
302
304
|
</tr>
|
|
303
305
|
</thead>
|
|
304
|
-
<tbody>
|
|
306
|
+
<tbody id="events-tbody">
|
|
305
307
|
{recent_rows}
|
|
306
308
|
</tbody>
|
|
307
309
|
</table>
|
|
308
310
|
</div>
|
|
309
311
|
</div>
|
|
312
|
+
<script>
|
|
313
|
+
if (window.EventSource) {{
|
|
314
|
+
const source = new EventSource('/api/events');
|
|
315
|
+
const pill = document.getElementById('live-pill');
|
|
316
|
+
source.onopen = () => {{
|
|
317
|
+
if (pill) pill.innerHTML = '<span style="color: #10b981;">●</span> LIVE SSE STREAMING';
|
|
318
|
+
}};
|
|
319
|
+
source.addEventListener('stats_update', (e) => {{
|
|
320
|
+
try {{
|
|
321
|
+
const data = JSON.parse(e.data);
|
|
322
|
+
if (data.total_saved_tokens !== undefined) {{
|
|
323
|
+
const el = document.getElementById('val-total-saved');
|
|
324
|
+
if (el) el.innerText = Number(data.total_saved_tokens).toLocaleString();
|
|
325
|
+
}}
|
|
326
|
+
if (data.overall_reduction_pct !== undefined) {{
|
|
327
|
+
const el = document.getElementById('val-efficiency-gain');
|
|
328
|
+
if (el) el.innerText = data.overall_reduction_pct.toFixed(1) + '%';
|
|
329
|
+
}}
|
|
330
|
+
if (data.total_usd_saved !== undefined) {{
|
|
331
|
+
const el = document.getElementById('val-usd-saved');
|
|
332
|
+
if (el) el.innerText = '$' + data.total_usd_saved.toFixed(4);
|
|
333
|
+
}}
|
|
334
|
+
if (data.total_original_tokens !== undefined && data.total_optimized_tokens !== undefined) {{
|
|
335
|
+
const el = document.getElementById('val-traffic');
|
|
336
|
+
if (el) el.innerText = Number(data.total_original_tokens).toLocaleString() + ' ➔ ' + Number(data.total_optimized_tokens).toLocaleString();
|
|
337
|
+
}}
|
|
338
|
+
}} catch (err) {{}}
|
|
339
|
+
}});
|
|
340
|
+
source.onerror = () => {{
|
|
341
|
+
if (pill) pill.innerHTML = '<span style="color: #64748b;">○</span> Disconnected (Reconnecting)';
|
|
342
|
+
}};
|
|
343
|
+
}}
|
|
344
|
+
</script>
|
|
310
345
|
</body>
|
|
311
346
|
</html>
|
|
312
347
|
"""
|
|
@@ -10,6 +10,7 @@ import re
|
|
|
10
10
|
import urllib.request
|
|
11
11
|
import urllib.error
|
|
12
12
|
from typing import Optional, Dict, Any
|
|
13
|
+
from src.distiller_cache import DistillationCache
|
|
13
14
|
|
|
14
15
|
class DeepSeekDistiller:
|
|
15
16
|
"""Uses DeepSeek-Flash as a high-density semantic compiler for prompts."""
|
|
@@ -33,7 +34,7 @@ Output: (DEBUG auth.controller.ts [oauth google timeout_504 missing_avatar] "fix
|
|
|
33
34
|
Rules:
|
|
34
35
|
1. Output ONLY the S-Expression starting with ( and ending with ).
|
|
35
36
|
2. No markdown code blocks, no preamble, no explanations.
|
|
36
|
-
3. Keep minimal_intent ultra-compact (under 10 words, English preferred for BPE token economy)."""
|
|
37
|
+
3. Keep minimal_intent ultra-compact (under 10 words, English preferred for BPE token economy). Total response MUST be under 50 tokens."""
|
|
37
38
|
|
|
38
39
|
@classmethod
|
|
39
40
|
def _get_config(cls) -> Dict[str, Any]:
|
|
@@ -56,6 +57,7 @@ Rules:
|
|
|
56
57
|
config["api_key"] = file_conf["deepseek_api_key"]
|
|
57
58
|
config["model"] = file_conf.get("deepseek_model", config["model"])
|
|
58
59
|
config["timeout"] = file_conf.get("deepseek_timeout", config["timeout"])
|
|
60
|
+
config["max_tokens"] = int(file_conf.get("distill_max_tokens", 60))
|
|
59
61
|
config["enabled"] = file_conf.get("enable_deepseek_tier", True)
|
|
60
62
|
except Exception:
|
|
61
63
|
pass
|
|
@@ -72,6 +74,11 @@ Rules:
|
|
|
72
74
|
if not conf["enabled"] or not conf["api_key"] or not raw_text or len(raw_text.strip()) < 10:
|
|
73
75
|
return None
|
|
74
76
|
|
|
77
|
+
# Check distillation cache before remote roundtrips
|
|
78
|
+
cached = DistillationCache.get(raw_text)
|
|
79
|
+
if cached:
|
|
80
|
+
return cached
|
|
81
|
+
|
|
75
82
|
payload = {
|
|
76
83
|
"model": conf["model"],
|
|
77
84
|
"messages": [
|
|
@@ -79,7 +86,7 @@ Rules:
|
|
|
79
86
|
{"role": "user", "content": raw_text.strip()}
|
|
80
87
|
],
|
|
81
88
|
"temperature": 0.0,
|
|
82
|
-
"max_tokens":
|
|
89
|
+
"max_tokens": conf.get("max_tokens", 60),
|
|
83
90
|
"effort": "low"
|
|
84
91
|
}
|
|
85
92
|
|
|
@@ -102,6 +109,7 @@ Rules:
|
|
|
102
109
|
# Clean backticks if any
|
|
103
110
|
content = re.sub(r"^```[a-zA-Z]*\n?|```$", "", content).strip()
|
|
104
111
|
if content.startswith("(") and content.endswith(")"):
|
|
112
|
+
DistillationCache.set(raw_text, content, provider="deepseek")
|
|
105
113
|
return content
|
|
106
114
|
except Exception:
|
|
107
115
|
# Network issue, timeout, or rate limit: fallback gracefully
|
|
@@ -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"
|
package/src/distiller.py
CHANGED
|
@@ -11,6 +11,7 @@ import re
|
|
|
11
11
|
import urllib.request
|
|
12
12
|
import urllib.error
|
|
13
13
|
from typing import Optional, Dict, Any, Tuple
|
|
14
|
+
from src.distiller_cache import DistillationCache
|
|
14
15
|
|
|
15
16
|
class UniversalDistiller:
|
|
16
17
|
"""Multi-provider semantic intent compiler supporting DeepSeek, OpenAI, and Google Gemini."""
|
|
@@ -32,7 +33,7 @@ Output: (DEBUG auth.controller.ts [oauth google timeout_504 missing_avatar] "fix
|
|
|
32
33
|
Rules:
|
|
33
34
|
1. Output ONLY the S-Expression starting with ( and ending with ).
|
|
34
35
|
2. No markdown code blocks, no preamble, no explanations.
|
|
35
|
-
3. Keep minimal_intent ultra-compact (under 10 words, English preferred for BPE token economy)."""
|
|
36
|
+
3. Keep minimal_intent ultra-compact (under 10 words, English preferred for BPE token economy). Total response MUST be under 50 tokens."""
|
|
36
37
|
|
|
37
38
|
PROVIDERS = {
|
|
38
39
|
"deepseek": {
|
|
@@ -82,12 +83,14 @@ Rules:
|
|
|
82
83
|
if api_key:
|
|
83
84
|
model = config_file_data.get(f"{key}_model", p_info["default_model"])
|
|
84
85
|
timeout = float(config_file_data.get(f"{key}_timeout", cls.DEFAULT_TIMEOUT))
|
|
86
|
+
max_tokens = int(config_file_data.get("distill_max_tokens", 60))
|
|
85
87
|
available[key] = {
|
|
86
88
|
"provider": key,
|
|
87
89
|
"name": p_info["name"],
|
|
88
90
|
"api_key": api_key,
|
|
89
91
|
"model": model,
|
|
90
92
|
"timeout": timeout,
|
|
93
|
+
"max_tokens": max_tokens,
|
|
91
94
|
"endpoint": p_info["endpoint"]
|
|
92
95
|
}
|
|
93
96
|
|
|
@@ -102,6 +105,11 @@ Rules:
|
|
|
102
105
|
if not raw_text or len(raw_text.strip()) < 10:
|
|
103
106
|
return None
|
|
104
107
|
|
|
108
|
+
# Check distillation cache before remote API roundtrips
|
|
109
|
+
cached = DistillationCache.get(raw_text)
|
|
110
|
+
if cached:
|
|
111
|
+
return cached
|
|
112
|
+
|
|
105
113
|
providers = cls.get_configured_providers()
|
|
106
114
|
if not providers:
|
|
107
115
|
return None
|
|
@@ -127,6 +135,7 @@ Rules:
|
|
|
127
135
|
if result:
|
|
128
136
|
clean = cls._sanitize_s_expression(result)
|
|
129
137
|
if clean:
|
|
138
|
+
DistillationCache.set(raw_text, clean, provider=p_key)
|
|
130
139
|
return clean
|
|
131
140
|
except Exception:
|
|
132
141
|
continue
|
|
@@ -142,7 +151,7 @@ Rules:
|
|
|
142
151
|
{"role": "user", "content": raw_text.strip()}
|
|
143
152
|
],
|
|
144
153
|
"temperature": 0.0,
|
|
145
|
-
"max_tokens":
|
|
154
|
+
"max_tokens": conf.get("max_tokens", 60)
|
|
146
155
|
}
|
|
147
156
|
if conf.get("provider") == "deepseek" or "deepseek" in str(conf.get("endpoint", "")).lower():
|
|
148
157
|
payload["effort"] = "low"
|
|
@@ -177,7 +186,7 @@ Rules:
|
|
|
177
186
|
],
|
|
178
187
|
"generationConfig": {
|
|
179
188
|
"temperature": 0.0,
|
|
180
|
-
"maxOutputTokens":
|
|
189
|
+
"maxOutputTokens": conf.get("max_tokens", 60)
|
|
181
190
|
}
|
|
182
191
|
}
|
|
183
192
|
|