tokensafe 4.5.0 → 4.5.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/.codex-plugin/plugin.json +1 -1
- package/bin/agy-tokens +10 -1
- package/bin/tokensafe.js +2 -1
- package/hooks/claude_code_hook.py +38 -126
- package/hooks/cursor_hook.py +45 -1
- package/hooks/kimi_hook.py +46 -90
- package/hooks/pre_invocation.py +23 -4
- package/hooks/pre_tool_use.py +40 -22
- package/hooks/session_start.py +28 -10
- package/hooks/zcode_hook.py +95 -0
- package/hooks.json +1 -1
- package/kimi.plugin.json +17 -1
- package/mcp_config.json +10 -4
- package/package.json +1 -1
- package/plugin.json +1 -1
- package/rules/AGENTS.md +24 -24
- package/server.json +3 -3
- package/skills/token-optimizer/SKILL.md +61 -86
- package/skills/token-optimizer/references/mcp-tools.md +32 -132
- package/src/adapter_core.py +231 -7
- package/src/batch_editor.py +73 -22
- package/src/batch_search.py +31 -11
- package/src/burn_monitor.py +581 -0
- package/src/cache_normalizer.py +2 -0
- package/src/cli.py +34 -4
- package/src/compactor.py +1 -1
- package/src/dashboard.py +17 -9
- package/src/diff_slicer.py +1 -1
- package/src/distiller.py +11 -1
- package/src/environment_auditor.py +30 -6
- package/src/format_parsers/ansi.py +1 -1
- package/src/format_parsers/lockfiles.py +22 -17
- package/src/format_parsers/tabular.py +6 -3
- package/src/fts_index.py +26 -20
- package/src/governor.py +2 -2
- package/src/graph_engine.py +31 -9
- package/src/guard.py +3 -3
- package/src/image_downscale.py +26 -0
- package/src/installer.py +61 -48
- package/src/license_manager.py +49 -16
- package/src/live_relay.py +9 -8
- package/src/mcp_server.py +487 -48
- package/src/metrics.py +78 -13
- package/src/mistakes.py +4 -2
- package/src/paths.py +4 -1
- package/src/proxy.py +302 -123
- package/src/result_ledger.py +39 -1
- package/src/schema_slicer.py +40 -18
- package/src/scoped_search.py +66 -23
- package/src/skeletonizer.py +22 -11
- package/src/slicer.py +6 -4
- package/src/stash.py +37 -7
- package/src/superseded.py +42 -23
- package/src/syntax_guard.py +2 -0
- package/src/team_cache.py +3 -0
- package/src/telemetry_sync.py +96 -54
- package/src/thinking_fold.py +50 -12
- package/src/transcript_analyzer.py +270 -68
- package/src/treesitter_backend.py +2 -0
- package/src/type_slicer.py +60 -18
- package/src/version_checker.py +1 -1
- package/src/web_reader.py +55 -22
package/src/dashboard.py
CHANGED
|
@@ -321,16 +321,18 @@ class Dashboard:
|
|
|
321
321
|
"""
|
|
322
322
|
|
|
323
323
|
tier, payload = LicenseManager.get_active_license()
|
|
324
|
-
if tier
|
|
324
|
+
if tier in ("guest", "free"):
|
|
325
325
|
monthly_saved = self.tracker.get_monthly_saved_tokens()
|
|
326
|
-
limit = 500_000
|
|
326
|
+
limit = 50_000 if tier == "guest" else 500_000
|
|
327
327
|
q_pct = min(100.0, round(monthly_saved / limit * 100.0, 1))
|
|
328
|
+
edition_label = "Guest Mode (50k):" if tier == "guest" else "Community Edition:"
|
|
329
|
+
cta_text = "Login / Upgrade" if tier == "guest" else "Upgrade to Solo (Unlimited)"
|
|
328
330
|
banner_html = f"""
|
|
329
331
|
<div style="background: rgba(234, 179, 8, 0.1); border: 1px solid rgba(234, 179, 8, 0.3); border-radius: 12px; padding: 14px 18px; margin-bottom: 24px; display: flex; justify-content: space-between; align-items: center; font-size: 13px;">
|
|
330
332
|
<div>
|
|
331
|
-
<strong style="color: #eab308;">⚡
|
|
333
|
+
<strong style="color: #eab308;">⚡ {edition_label}</strong> {monthly_saved:,} / {limit:,} free measured tokens saved this month ({q_pct}%).
|
|
332
334
|
</div>
|
|
333
|
-
<a href="https://tokensafe.dev/
|
|
335
|
+
<a href="https://tokensafe.dev/pricing" target="_blank" style="background: #10b981; color: #090a0f; font-weight: 700; padding: 6px 14px; border-radius: 8px; text-decoration: none; font-size: 12px;">{cta_text}</a>
|
|
334
336
|
</div>
|
|
335
337
|
"""
|
|
336
338
|
else:
|
|
@@ -454,13 +456,17 @@ class Dashboard:
|
|
|
454
456
|
</div>
|
|
455
457
|
</div>
|
|
456
458
|
<script>
|
|
457
|
-
|
|
458
|
-
const source = new EventSource('/api/events');
|
|
459
|
+
(function() {{
|
|
459
460
|
const pill = document.getElementById('live-pill');
|
|
461
|
+
if (location.protocol === 'file:' || !window.EventSource) {{
|
|
462
|
+
if (pill) pill.innerHTML = '<span style="color: #64748b;">●</span> Static Snapshot (local HTML)';
|
|
463
|
+
return;
|
|
464
|
+
}}
|
|
465
|
+
const source = new EventSource('/api/events');
|
|
460
466
|
source.onopen = () => {{
|
|
461
467
|
if (pill) pill.innerHTML = '<span style="color: #10b981;">●</span> LIVE SSE STREAMING';
|
|
462
468
|
}};
|
|
463
|
-
|
|
469
|
+
const applyStats = (e) => {{
|
|
464
470
|
try {{
|
|
465
471
|
const data = JSON.parse(e.data);
|
|
466
472
|
if (data.total_saved_tokens !== undefined) {{
|
|
@@ -480,11 +486,13 @@ class Dashboard:
|
|
|
480
486
|
if (el) el.innerText = Number(data.total_original_tokens).toLocaleString() + ' ➔ ' + Number(data.total_optimized_tokens).toLocaleString();
|
|
481
487
|
}}
|
|
482
488
|
}} catch (err) {{}}
|
|
483
|
-
}}
|
|
489
|
+
}};
|
|
490
|
+
source.addEventListener('init', applyStats);
|
|
491
|
+
source.addEventListener('stats_update', applyStats);
|
|
484
492
|
source.onerror = () => {{
|
|
485
493
|
if (pill) pill.innerHTML = '<span style="color: #64748b;">○</span> Disconnected (Reconnecting)';
|
|
486
494
|
}};
|
|
487
|
-
}}
|
|
495
|
+
}})();
|
|
488
496
|
</script>
|
|
489
497
|
</body>
|
|
490
498
|
</html>
|
package/src/diff_slicer.py
CHANGED
|
@@ -131,7 +131,7 @@ class DiffSlicer:
|
|
|
131
131
|
continue
|
|
132
132
|
if ":!" in stage or re.search(r"(?:^|\s)(?:--unified=\d+|-U\d*)\b", stage):
|
|
133
133
|
continue
|
|
134
|
-
new_stage = re.sub(r"\
|
|
134
|
+
new_stage = re.sub(r"(\bgit(?:\s+-C\s+\S+)?\s+diff)\b", r"\1 -U2", stage, count=1)
|
|
135
135
|
if "-- " not in stage and not stage.rstrip().endswith("--"):
|
|
136
136
|
toks = CommandSanitizer._split_tokens_safe(stage)
|
|
137
137
|
diff_pos = toks.index("diff") if "diff" in toks else 1
|
package/src/distiller.py
CHANGED
|
@@ -182,8 +182,18 @@ Rules:
|
|
|
182
182
|
}
|
|
183
183
|
)
|
|
184
184
|
try:
|
|
185
|
+
from src.ssl_context import shared_ssl_context
|
|
185
186
|
_egress_increment("booster")
|
|
186
|
-
|
|
187
|
+
ssl_ctx = shared_ssl_context()
|
|
188
|
+
try:
|
|
189
|
+
resp_ctx = (
|
|
190
|
+
urllib.request.urlopen(req, timeout=timeout, context=ssl_ctx)
|
|
191
|
+
if ssl_ctx is not None
|
|
192
|
+
else urllib.request.urlopen(req, timeout=timeout)
|
|
193
|
+
)
|
|
194
|
+
except TypeError:
|
|
195
|
+
resp_ctx = urllib.request.urlopen(req, timeout=timeout)
|
|
196
|
+
with resp_ctx as resp:
|
|
187
197
|
if resp.status == 200:
|
|
188
198
|
data = json.loads(resp.read().decode("utf-8"))
|
|
189
199
|
if data.get("success") and data.get("distilled"):
|
|
@@ -37,7 +37,12 @@ class EnvironmentAuditor:
|
|
|
37
37
|
home = os.path.expanduser("~")
|
|
38
38
|
return [
|
|
39
39
|
os.path.join(home, ".gemini", "config", "mcp_config.json"),
|
|
40
|
-
os.path.join(home, ".gemini", "antigravity", "mcp_config.json")
|
|
40
|
+
os.path.join(home, ".gemini", "antigravity", "mcp_config.json"),
|
|
41
|
+
os.path.join(home, ".zcode", "cli", "config.json"),
|
|
42
|
+
os.path.join(home, ".claude.json"),
|
|
43
|
+
os.path.join(home, ".cursor", "mcp.json"),
|
|
44
|
+
os.path.join(home, ".kimi-code", "mcp.json"),
|
|
45
|
+
os.path.join(home, ".codex", "config.toml"),
|
|
41
46
|
]
|
|
42
47
|
|
|
43
48
|
@classmethod
|
|
@@ -102,14 +107,33 @@ class EnvironmentAuditor:
|
|
|
102
107
|
# antigravity dir can legitimately carry servers (they are merged by
|
|
103
108
|
# Antigravity too), so breaking on the first one undercounts.
|
|
104
109
|
for p in cls.get_config_paths():
|
|
105
|
-
if os.path.isfile(p):
|
|
110
|
+
if not os.path.isfile(p):
|
|
111
|
+
continue
|
|
112
|
+
if p.endswith(".toml"):
|
|
106
113
|
try:
|
|
107
|
-
with open(p, "
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
114
|
+
with open(p, "rb") as f:
|
|
115
|
+
raw_bytes = f.read()
|
|
116
|
+
try:
|
|
117
|
+
import tomllib
|
|
118
|
+
loaded_toml = tomllib.loads(raw_bytes.decode("utf-8", errors="replace"))
|
|
119
|
+
if isinstance(loaded_toml.get("mcp_servers"), dict):
|
|
120
|
+
configured.update(loaded_toml["mcp_servers"])
|
|
121
|
+
except Exception:
|
|
122
|
+
text = raw_bytes.decode("utf-8", errors="replace")
|
|
123
|
+
for m in re.finditer(r"^\s*\[mcp_servers\.([^\]]+)\]", text, re.MULTILINE):
|
|
124
|
+
s_name = m.group(1).strip().strip('"\'')
|
|
125
|
+
if s_name:
|
|
126
|
+
configured.setdefault(s_name, {})
|
|
111
127
|
except Exception:
|
|
112
128
|
continue
|
|
129
|
+
continue
|
|
130
|
+
try:
|
|
131
|
+
with open(p, "r", encoding="utf-8") as f:
|
|
132
|
+
loaded = json.load(f)
|
|
133
|
+
if isinstance(loaded, dict) and isinstance(loaded.get("mcpServers"), dict):
|
|
134
|
+
configured.update(loaded["mcpServers"])
|
|
135
|
+
except Exception:
|
|
136
|
+
continue
|
|
113
137
|
# Plugin-declared servers (plugins/<name>/mcp_config.json) are loaded
|
|
114
138
|
# by Antigravity together with the plugin — audit them too, unless the
|
|
115
139
|
# plugin itself is disabled.
|
|
@@ -12,7 +12,7 @@ import re
|
|
|
12
12
|
# 1. CSI sequences: \x1b\[[0-9;]*[A-Za-z] (colors, cursor movements, erase line)
|
|
13
13
|
# 2. OSC sequences: \x1b\][^\x07\x1b]*(\x07|\x1b\\) (hyperlinks, window titles)
|
|
14
14
|
# 3. Simple escapes: \x1b[()][AB012], \x1b[=>]
|
|
15
|
-
_ANSI_CSI_RE = re.compile(r"\x1b\[[0-9
|
|
15
|
+
_ANSI_CSI_RE = re.compile(r"\x1b\[[0-9;?=<>*!]*[ -/]*[@-~]")
|
|
16
16
|
_ANSI_OSC_RE = re.compile(r"\x1b\][^\x07\x1b]*(\x07|\x1b\\)")
|
|
17
17
|
_ANSI_OTHER_RE = re.compile(r"\x1b[()][AB012]|\x1b[=>]")
|
|
18
18
|
|
|
@@ -530,21 +530,26 @@ class LockfileReducer:
|
|
|
530
530
|
pass
|
|
531
531
|
|
|
532
532
|
elif "cargo.lock" in fname or "poetry.lock" in fname:
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
r'(
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
source_val =
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
533
|
+
# Parse TOML [[package]] sections resiliently (supports optional checksum & TOML dependency arrays)
|
|
534
|
+
sections = re.split(r'(?m)^\[\[package\]\]\s*$', content)
|
|
535
|
+
for sec in sections[1:]:
|
|
536
|
+
m_name = re.search(r'(?m)^name\s*=\s*"([^"]+)"', sec)
|
|
537
|
+
if not m_name or m_name.group(1) != norm_pkg:
|
|
538
|
+
continue
|
|
539
|
+
m_ver = re.search(r'(?m)^version\s*=\s*"([^"]+)"', sec)
|
|
540
|
+
ver = m_ver.group(1) if m_ver else "*"
|
|
541
|
+
m_src = re.search(r'(?m)^source\s*=\s*"([^"]*)"', sec)
|
|
542
|
+
source_val = m_src.group(1) if m_src else None
|
|
543
|
+
m_deps = re.search(r'(?ms)^dependencies\s*=\s*\[(.*?)\]', sec)
|
|
544
|
+
deps: List[str] = []
|
|
545
|
+
if m_deps:
|
|
546
|
+
raw_arr = m_deps.group(1)
|
|
547
|
+
try:
|
|
548
|
+
parsed = json.loads(f"[{raw_arr}]")
|
|
549
|
+
if isinstance(parsed, list):
|
|
550
|
+
deps = [str(d) for d in parsed]
|
|
551
|
+
except Exception:
|
|
552
|
+
deps = re.findall(r'"([^"]+)"', raw_arr)
|
|
548
553
|
res_dict = {
|
|
549
554
|
"found": True,
|
|
550
555
|
"package": norm_pkg,
|
|
@@ -556,8 +561,8 @@ class LockfileReducer:
|
|
|
556
561
|
return res_dict
|
|
557
562
|
|
|
558
563
|
elif "pnpm-lock" in fname:
|
|
559
|
-
# Pnpm regex lookup
|
|
560
|
-
pnpm_re = re.compile(rf'["\']
|
|
564
|
+
# Pnpm regex lookup with strict left boundary so 'react' never matches 'preact'
|
|
565
|
+
pnpm_re = re.compile(rf'(?:^|[\s"\'/]){re.escape(norm_pkg)}[@/]([0-9a-zA-Z._+-]+)["\']?:', re.MULTILINE)
|
|
561
566
|
m = pnpm_re.search(content)
|
|
562
567
|
if m:
|
|
563
568
|
return {
|
|
@@ -154,9 +154,12 @@ class TabularReducer:
|
|
|
154
154
|
resp = e.get("response", {})
|
|
155
155
|
method = req.get("method", "GET")
|
|
156
156
|
url = req.get("url", "")
|
|
157
|
-
status = resp.get("status", 0)
|
|
158
|
-
body_size = resp.get("bodySize"
|
|
159
|
-
|
|
157
|
+
status = resp.get("status", 0) or 0
|
|
158
|
+
body_size = resp.get("bodySize") or 0
|
|
159
|
+
try:
|
|
160
|
+
time_ms = int(float(e.get("time") or 0))
|
|
161
|
+
except (TypeError, ValueError):
|
|
162
|
+
time_ms = 0
|
|
160
163
|
|
|
161
164
|
# Strip query params if too long
|
|
162
165
|
clean_url = url.split("?")[0] if len(url) > 80 else url
|
package/src/fts_index.py
CHANGED
|
@@ -178,15 +178,8 @@ class CodeFTSIndex:
|
|
|
178
178
|
if prev and abs(prev[0] - f_mtime) < 0.001 and prev[1] == f_size:
|
|
179
179
|
continue # File unchanged
|
|
180
180
|
|
|
181
|
-
files_to_index
|
|
182
|
-
|
|
183
|
-
# beyond the cap must still enter found_paths, or the
|
|
184
|
-
# prune step below would treat them as deleted on every
|
|
185
|
-
# run (repos > max_files lost their tail permanently).
|
|
186
|
-
if len(files_to_index) >= max_files:
|
|
187
|
-
break
|
|
188
|
-
if len(files_to_index) >= max_files:
|
|
189
|
-
break
|
|
181
|
+
if len(files_to_index) < max_files:
|
|
182
|
+
files_to_index.append((rel_path, full_path, f_mtime, f_size))
|
|
190
183
|
|
|
191
184
|
# Index modified/new files in batches
|
|
192
185
|
for rel_path, full_path, f_mtime, f_size in files_to_index:
|
|
@@ -257,6 +250,9 @@ class CodeFTSIndex:
|
|
|
257
250
|
escaped_q = clean_q.replace('"', '""')
|
|
258
251
|
fts_query = f'"{escaped_q}"'
|
|
259
252
|
|
|
253
|
+
def _escape_like(val: str) -> str:
|
|
254
|
+
return val.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
|
|
255
|
+
|
|
260
256
|
results = []
|
|
261
257
|
try:
|
|
262
258
|
con = self._get_connection()
|
|
@@ -265,11 +261,11 @@ class CodeFTSIndex:
|
|
|
265
261
|
sql = """
|
|
266
262
|
SELECT rel_path, line_no, content, bm25(code_lines) AS rank
|
|
267
263
|
FROM code_lines
|
|
268
|
-
WHERE code_lines MATCH ? AND rel_path LIKE ?
|
|
264
|
+
WHERE code_lines MATCH ? AND rel_path LIKE ? ESCAPE '\\'
|
|
269
265
|
ORDER BY rank
|
|
270
266
|
LIMIT ?;
|
|
271
267
|
"""
|
|
272
|
-
cur = con.execute(sql, (fts_query, f"%{path_filter}%", limit))
|
|
268
|
+
cur = con.execute(sql, (fts_query, f"%{_escape_like(path_filter)}%", limit))
|
|
273
269
|
else:
|
|
274
270
|
sql = """
|
|
275
271
|
SELECT rel_path, line_no, content, bm25(code_lines) AS rank
|
|
@@ -295,7 +291,7 @@ class CodeFTSIndex:
|
|
|
295
291
|
and_query = " AND ".join(
|
|
296
292
|
f'"{term.replace(chr(34), chr(34) * 2)}"' for term in clean_q.split()
|
|
297
293
|
)
|
|
298
|
-
params2 = ([f"%{path_filter}%"] if path_filter else []) + [limit]
|
|
294
|
+
params2 = ([f"%{_escape_like(path_filter)}%"] if path_filter else []) + [limit]
|
|
299
295
|
cur = con.execute(sql, (and_query, *params2))
|
|
300
296
|
for row in cur.fetchall():
|
|
301
297
|
results.append({
|
|
@@ -305,14 +301,24 @@ class CodeFTSIndex:
|
|
|
305
301
|
"bm25_rank": row[3]
|
|
306
302
|
})
|
|
307
303
|
except sqlite3.OperationalError:
|
|
308
|
-
# If trigram MATCH fails (e.g. query < 3 chars), fallback to LIKE
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
304
|
+
# If trigram MATCH fails (e.g. query < 3 chars), fallback to escaped LIKE
|
|
305
|
+
escaped_q_like = f"%{_escape_like(clean_q)}%"
|
|
306
|
+
if path_filter:
|
|
307
|
+
like_sql = """
|
|
308
|
+
SELECT rel_path, line_no, content, 0.0 AS rank
|
|
309
|
+
FROM code_lines
|
|
310
|
+
WHERE content LIKE ? ESCAPE '\\' AND rel_path LIKE ? ESCAPE '\\'
|
|
311
|
+
LIMIT ?;
|
|
312
|
+
"""
|
|
313
|
+
cur = con.execute(like_sql, (escaped_q_like, f"%{_escape_like(path_filter)}%", limit))
|
|
314
|
+
else:
|
|
315
|
+
like_sql = """
|
|
316
|
+
SELECT rel_path, line_no, content, 0.0 AS rank
|
|
317
|
+
FROM code_lines
|
|
318
|
+
WHERE content LIKE ? ESCAPE '\\'
|
|
319
|
+
LIMIT ?;
|
|
320
|
+
"""
|
|
321
|
+
cur = con.execute(like_sql, (escaped_q_like, limit))
|
|
316
322
|
for row in cur.fetchall():
|
|
317
323
|
results.append({
|
|
318
324
|
"file": row[0],
|
package/src/governor.py
CHANGED
|
@@ -379,12 +379,12 @@ class ContextBudget:
|
|
|
379
379
|
pct = round(used / window * 100.0, 1) if window > 0 else 0.0
|
|
380
380
|
if pct >= 95:
|
|
381
381
|
threshold, recommendation = "critical", (
|
|
382
|
-
"Context nearly exhausted. Call tokensafe:
|
|
382
|
+
"Context nearly exhausted. Call tokensafe:session_context(action='compact', ...) on the "
|
|
383
383
|
"session transcript now, or start a fresh session carrying the ledger.")
|
|
384
384
|
elif pct >= 80:
|
|
385
385
|
threshold, recommendation = "warning", (
|
|
386
386
|
"Context is heavy. Prefer tokensafe:smart_read_file with symbol= for "
|
|
387
|
-
"further reads and consider tokensafe:
|
|
387
|
+
"further reads and consider tokensafe:session_context(action='compact', ...).")
|
|
388
388
|
elif pct >= 50:
|
|
389
389
|
threshold, recommendation = "notice", (
|
|
390
390
|
"Half the estimated window is used. Keep reads surgical (symbol=, include_deps=false).")
|
package/src/graph_engine.py
CHANGED
|
@@ -22,6 +22,7 @@ import re
|
|
|
22
22
|
import sqlite3
|
|
23
23
|
import stat
|
|
24
24
|
import tempfile
|
|
25
|
+
import threading
|
|
25
26
|
import time
|
|
26
27
|
from typing import Dict, Set, List, Optional, Tuple, Any
|
|
27
28
|
|
|
@@ -51,7 +52,7 @@ _SKIP_CALLS = {
|
|
|
51
52
|
"true", "false", "null", "undefined", "None", "True", "False",
|
|
52
53
|
}
|
|
53
54
|
|
|
54
|
-
_CACHE_SCHEMA_VERSION =
|
|
55
|
+
_CACHE_SCHEMA_VERSION = 5
|
|
55
56
|
|
|
56
57
|
_STATIC_ASSET_EXTS = {
|
|
57
58
|
".png", ".jpg", ".jpeg", ".gif", ".svg", ".ico", ".webp",
|
|
@@ -340,6 +341,15 @@ class CodeGraph:
|
|
|
340
341
|
except sqlite3.OperationalError:
|
|
341
342
|
pass
|
|
342
343
|
|
|
344
|
+
self.api_links = []
|
|
345
|
+
try:
|
|
346
|
+
for row in cur.execute("SELECT link_json FROM api_links").fetchall():
|
|
347
|
+
link_obj = json.loads(row[0])
|
|
348
|
+
if isinstance(link_obj, dict):
|
|
349
|
+
self.api_links.append(link_obj)
|
|
350
|
+
except Exception:
|
|
351
|
+
pass
|
|
352
|
+
|
|
343
353
|
self.last_scanned = float(meta.get("last_scanned", 0.0))
|
|
344
354
|
return True
|
|
345
355
|
finally:
|
|
@@ -406,6 +416,7 @@ class CodeGraph:
|
|
|
406
416
|
cur.execute("CREATE TABLE edges (source TEXT, target TEXT, PRIMARY KEY (source, target))")
|
|
407
417
|
cur.execute("CREATE TABLE api_endpoints (rel_path TEXT, route TEXT, sym_key TEXT, method TEXT)")
|
|
408
418
|
cur.execute("CREATE TABLE api_calls (rel_path TEXT, route TEXT, sym_key TEXT, method TEXT)")
|
|
419
|
+
cur.execute("CREATE TABLE api_links (link_json TEXT)")
|
|
409
420
|
|
|
410
421
|
cur.executemany(
|
|
411
422
|
"INSERT INTO graph_meta VALUES (?, ?)",
|
|
@@ -449,6 +460,10 @@ class CodeGraph:
|
|
|
449
460
|
"INSERT INTO api_calls VALUES (?, ?, ?, ?)",
|
|
450
461
|
[(rel, call[0], call[1], call[2] if len(call) > 2 else None) for rel, calls in self.file_api_calls.items() for call in calls],
|
|
451
462
|
)
|
|
463
|
+
cur.executemany(
|
|
464
|
+
"INSERT INTO api_links VALUES (?)",
|
|
465
|
+
[(json.dumps(lk, ensure_ascii=False),) for lk in self.api_links],
|
|
466
|
+
)
|
|
452
467
|
con.commit()
|
|
453
468
|
finally:
|
|
454
469
|
con.close()
|
|
@@ -507,6 +522,11 @@ class CodeGraph:
|
|
|
507
522
|
try:
|
|
508
523
|
st = os.stat(full_path)
|
|
509
524
|
if not stat.S_ISREG(st.st_mode) or st.st_size > 2 * 1024 * 1024:
|
|
525
|
+
if rel_path in self.file_symbols or rel_path in self.file_stats:
|
|
526
|
+
self._purge_file(rel_path)
|
|
527
|
+
self.file_stats.pop(rel_path, None)
|
|
528
|
+
self.file_mtimes.pop(rel_path, None)
|
|
529
|
+
reindexed += 1
|
|
510
530
|
continue
|
|
511
531
|
sig = (st.st_mtime, st.st_size)
|
|
512
532
|
except OSError:
|
|
@@ -1712,6 +1732,7 @@ class GraphEngine:
|
|
|
1712
1732
|
"""Multi-Project Manager for automatic background graph execution."""
|
|
1713
1733
|
|
|
1714
1734
|
_instances: Dict[str, CodeGraph] = {}
|
|
1735
|
+
_instances_lock = threading.RLock()
|
|
1715
1736
|
|
|
1716
1737
|
@classmethod
|
|
1717
1738
|
def find_project_root(cls, start_path: str) -> str:
|
|
@@ -1737,15 +1758,16 @@ class GraphEngine:
|
|
|
1737
1758
|
# Rescans are full AST crawls; a 3s TTL caused near-constant rescans on every
|
|
1738
1759
|
# smart_read_file(symbol=...) call. 60s keeps graphs fresh without the churn.
|
|
1739
1760
|
rescan_ttl = float(os.environ.get("TOKENSAFE_GRAPH_TTL", "60.0"))
|
|
1740
|
-
|
|
1741
|
-
|
|
1742
|
-
|
|
1743
|
-
cls._instances[root_abs] = graph
|
|
1744
|
-
else:
|
|
1745
|
-
graph = cls._instances[root_abs]
|
|
1746
|
-
if time.time() - graph.last_scanned > rescan_ttl:
|
|
1761
|
+
with cls._instances_lock:
|
|
1762
|
+
if root_abs not in cls._instances:
|
|
1763
|
+
graph = CodeGraph(root_abs, use_disk_cache=True)
|
|
1747
1764
|
graph.scan()
|
|
1748
|
-
|
|
1765
|
+
cls._instances[root_abs] = graph
|
|
1766
|
+
else:
|
|
1767
|
+
graph = cls._instances[root_abs]
|
|
1768
|
+
if time.time() - graph.last_scanned > rescan_ttl:
|
|
1769
|
+
graph.scan()
|
|
1770
|
+
return graph
|
|
1749
1771
|
|
|
1750
1772
|
@classmethod
|
|
1751
1773
|
def for_file(cls, file_path: str) -> Tuple[CodeGraph, str]:
|
package/src/guard.py
CHANGED
|
@@ -670,8 +670,8 @@ class TokenSafeGuard:
|
|
|
670
670
|
f"TokenSafe Protocol mandates using MCP tools to prevent context window bloat:\n"
|
|
671
671
|
f"• To search keywords, symbols, or configs: call 'tokensafe:scoped_search(query, scope)'\n"
|
|
672
672
|
f"• To inspect definitions/symbols in a file: call 'tokensafe:smart_read_file(path, symbol)'\n"
|
|
673
|
-
f"• To locate God Nodes & architecture: call 'tokensafe:
|
|
674
|
-
f"• To inspect project exports & types: call 'tokensafe:
|
|
673
|
+
f"• To locate God Nodes & architecture: call 'tokensafe:repo_map(view=\"graph\", project_path=...)'\n"
|
|
674
|
+
f"• To inspect project exports & types: call 'tokensafe:repo_map(view=\"api\", project_path=...)'"
|
|
675
675
|
)
|
|
676
676
|
|
|
677
677
|
elif cmd_tok == "find":
|
|
@@ -681,7 +681,7 @@ class TokenSafeGuard:
|
|
|
681
681
|
if has_code_ext or has_code_dir or is_root_file_crawl:
|
|
682
682
|
return (
|
|
683
683
|
f"Raw file crawl via 'find' blocked: '{sub_cmd}'. "
|
|
684
|
-
f"Use 'tokensafe:scoped_search(query)' or 'tokensafe:
|
|
684
|
+
f"Use 'tokensafe:scoped_search(query)' or 'tokensafe:repo_map(view=\"tree\")' "
|
|
685
685
|
f"instead of scanning directory trees."
|
|
686
686
|
)
|
|
687
687
|
|
package/src/image_downscale.py
CHANGED
|
@@ -72,6 +72,27 @@ def _read_dimensions_sips(path: str) -> Optional[Tuple[int, int]]:
|
|
|
72
72
|
return None
|
|
73
73
|
|
|
74
74
|
|
|
75
|
+
def _read_dimensions_imagemagick(path: str) -> Optional[Tuple[int, int]]:
|
|
76
|
+
cmd = shutil.which("magick") or shutil.which("identify")
|
|
77
|
+
if not cmd:
|
|
78
|
+
return None
|
|
79
|
+
try:
|
|
80
|
+
args = [cmd, "identify"] if os.path.basename(cmd).startswith("magick") else [cmd]
|
|
81
|
+
res = subprocess.run(
|
|
82
|
+
[*args, "-format", "%w %h", path],
|
|
83
|
+
capture_output=True, text=True, timeout=5
|
|
84
|
+
)
|
|
85
|
+
if res.returncode == 0:
|
|
86
|
+
parts = res.stdout.strip().split()
|
|
87
|
+
if len(parts) >= 2:
|
|
88
|
+
w, h = int(parts[0]), int(parts[1])
|
|
89
|
+
if w > 0 and h > 0:
|
|
90
|
+
return (w, h)
|
|
91
|
+
except Exception:
|
|
92
|
+
pass
|
|
93
|
+
return None
|
|
94
|
+
|
|
95
|
+
|
|
75
96
|
def get_image_dimensions(path: str) -> Optional[Tuple[int, int]]:
|
|
76
97
|
dims = _read_dimensions_pillow(path)
|
|
77
98
|
if dims:
|
|
@@ -80,6 +101,9 @@ def get_image_dimensions(path: str) -> Optional[Tuple[int, int]]:
|
|
|
80
101
|
dims = _read_dimensions_sips(path)
|
|
81
102
|
if dims:
|
|
82
103
|
return dims
|
|
104
|
+
dims = _read_dimensions_imagemagick(path)
|
|
105
|
+
if dims:
|
|
106
|
+
return dims
|
|
83
107
|
return None
|
|
84
108
|
|
|
85
109
|
|
|
@@ -163,6 +187,8 @@ class ImageDownscaler:
|
|
|
163
187
|
with Image.open(image_path) as img:
|
|
164
188
|
resample_filter = getattr(Image.Resampling, "LANCZOS", Image.LANCZOS if hasattr(Image, "LANCZOS") else 1)
|
|
165
189
|
resized = img.resize((new_w, new_h), resample=resample_filter)
|
|
190
|
+
if ext in (".jpg", ".jpeg", ".bmp") and resized.mode in ("RGBA", "LA", "P"):
|
|
191
|
+
resized = resized.convert("RGB")
|
|
166
192
|
resized.save(optimized_path)
|
|
167
193
|
engine_used = "pillow"
|
|
168
194
|
except Exception:
|