tokensafe 4.13.3 → 4.15.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/.codex-plugin/plugin.json +1 -1
- package/README.md +1 -1
- package/hooks/claude_code_hook.py +8 -2
- package/hooks/cursor_hook.py +2 -1
- package/hooks/kimi_hook.py +2 -1
- package/hooks/post_tool_use.py +15 -1
- package/hooks/pre_invocation.py +4 -2
- package/hooks/pre_tool_use.py +13 -6
- package/hooks/session_start.py +7 -2
- package/hooks/stop_hook.py +2 -1
- package/hooks/zcode_hook.py +2 -1
- package/kimi.plugin.json +1 -1
- package/package.json +1 -1
- package/plugin.json +1 -1
- package/server.json +3 -3
- package/src/acp/server.py +5 -0
- package/src/atomic_io.py +74 -0
- package/src/auto_inject.py +8 -4
- package/src/backend_release.py +3 -3
- package/src/batch_editor.py +2 -14
- package/src/cli.py +10 -0
- package/src/command_sanitizer.py +1 -1
- package/src/context_index.py +954 -0
- package/src/file_state.py +4 -3
- package/src/fts_index.py +12 -32
- package/src/graph_engine.py +43 -95
- package/src/guard.py +1 -1
- package/src/installer.py +64 -4
- package/src/license_manager.py +66 -0
- package/src/mcp_proxy.py +3 -0
- package/src/mcp_server.py +103 -5
- package/src/mistakes.py +45 -21
- package/src/oumv_gateway.py +61 -18
- package/src/paths.py +5 -12
- package/src/project_memory.py +264 -0
- package/src/result_ledger.py +40 -0
- package/src/retrofit.py +15 -8
- package/src/scoped_search.py +93 -53
- package/src/session_brief.py +14 -3
- package/src/skeletonizer.py +44 -2
- package/src/snapshot.py +17 -1
- package/src/stdio_io.py +50 -0
- package/src/telemetry_sync.py +1 -1
- package/src/version_checker.py +1 -1
- package/src/win_paths.py +172 -0
- package/src/workspace_roots.py +2 -6
package/src/file_state.py
CHANGED
|
@@ -27,6 +27,7 @@ import tempfile
|
|
|
27
27
|
from typing import Any, Dict, Optional
|
|
28
28
|
|
|
29
29
|
from src.paths import resolve_data_dir
|
|
30
|
+
from src.win_paths import state_key
|
|
30
31
|
|
|
31
32
|
STATE_FILENAME = "file_state.json"
|
|
32
33
|
_MAX_ENTRIES = 512
|
|
@@ -124,9 +125,9 @@ def record_seen(path: str) -> bool:
|
|
|
124
125
|
(deleted targets can never be stale)."""
|
|
125
126
|
if not path:
|
|
126
127
|
return False
|
|
127
|
-
abs_path =
|
|
128
|
+
abs_path = state_key(path)
|
|
128
129
|
try:
|
|
129
|
-
with open(
|
|
130
|
+
with open(os.path.abspath(path), "rb") as f:
|
|
130
131
|
blob = f.read()
|
|
131
132
|
except FileNotFoundError:
|
|
132
133
|
try:
|
|
@@ -159,7 +160,7 @@ def check_stale(path: str) -> Optional[Dict[str, Any]]:
|
|
|
159
160
|
if not path:
|
|
160
161
|
return None
|
|
161
162
|
try:
|
|
162
|
-
abs_path =
|
|
163
|
+
abs_path = state_key(path)
|
|
163
164
|
if _skip_path(abs_path):
|
|
164
165
|
return None
|
|
165
166
|
entry = _load_state().get(abs_path)
|
package/src/fts_index.py
CHANGED
|
@@ -12,10 +12,9 @@ native FTS5 module with the trigram tokenizer.
|
|
|
12
12
|
import os
|
|
13
13
|
import sqlite3
|
|
14
14
|
import time
|
|
15
|
-
import hashlib
|
|
16
|
-
import shutil
|
|
17
15
|
from typing import List, Dict, Any, Optional, Tuple
|
|
18
16
|
|
|
17
|
+
from src.context_index import index_db_path
|
|
19
18
|
from src.paths import resolve_data_dir
|
|
20
19
|
|
|
21
20
|
# Ignored directories and extensions reused for clean index
|
|
@@ -46,32 +45,12 @@ from src.paths import resolve_data_dir, ensure_tokensafe_gitignore
|
|
|
46
45
|
|
|
47
46
|
|
|
48
47
|
def _resolve_fts_db_path(project_root: str) -> str:
|
|
49
|
-
"""
|
|
48
|
+
"""Path of the unified index that stores the line corpus.
|
|
50
49
|
|
|
51
|
-
|
|
52
|
-
|
|
50
|
+
Kept as a function because callers (and tests) assert that the corpus
|
|
51
|
+
never lands inside the project working tree.
|
|
53
52
|
"""
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
# Legacy cleanup: if fts.db was mistakenly created in project .tokensafe, migrate or remove
|
|
57
|
-
proj_tokensafe = os.path.join(project_root, ".tokensafe")
|
|
58
|
-
legacy_file = os.path.join(proj_tokensafe, "fts.db")
|
|
59
|
-
|
|
60
|
-
cache_dir = os.path.join(resolve_data_dir(), "cache", "fts")
|
|
61
|
-
os.makedirs(cache_dir, exist_ok=True)
|
|
62
|
-
p_hash = hashlib.sha256(os.path.abspath(project_root).encode("utf-8")).hexdigest()[:16]
|
|
63
|
-
target_path = os.path.join(cache_dir, f"fts_{p_hash}.db")
|
|
64
|
-
|
|
65
|
-
if os.path.isfile(legacy_file) and not os.path.isfile(target_path):
|
|
66
|
-
try:
|
|
67
|
-
shutil.move(legacy_file, target_path)
|
|
68
|
-
for extra in (f"{legacy_file}-wal", f"{legacy_file}-shm"):
|
|
69
|
-
if os.path.isfile(extra):
|
|
70
|
-
os.remove(extra)
|
|
71
|
-
except Exception:
|
|
72
|
-
pass
|
|
73
|
-
|
|
74
|
-
return target_path
|
|
53
|
+
return index_db_path(project_root)
|
|
75
54
|
|
|
76
55
|
|
|
77
56
|
class CodeFTSIndex:
|
|
@@ -343,9 +322,10 @@ class CodeFTSIndex:
|
|
|
343
322
|
return results
|
|
344
323
|
|
|
345
324
|
def clear(self):
|
|
346
|
-
"""Clears
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
325
|
+
"""Clears the text corpus; graph rows in the same file stay intact."""
|
|
326
|
+
try:
|
|
327
|
+
with self._get_connection() as con:
|
|
328
|
+
con.execute("DELETE FROM code_lines")
|
|
329
|
+
con.execute("DELETE FROM file_meta")
|
|
330
|
+
except Exception:
|
|
331
|
+
pass
|
package/src/graph_engine.py
CHANGED
|
@@ -22,12 +22,12 @@ import os
|
|
|
22
22
|
import re
|
|
23
23
|
import sqlite3
|
|
24
24
|
import stat
|
|
25
|
-
import tempfile
|
|
26
25
|
import threading
|
|
27
26
|
import time
|
|
28
27
|
from typing import Dict, Set, List, Optional, Tuple, Any
|
|
29
28
|
|
|
30
29
|
from src.paths import resolve_data_dir
|
|
30
|
+
from src.context_index import ContextIndex, index_db_path, legacy_graph_db_path
|
|
31
31
|
from src.globmatch import GlobPatternError, compile_patterns, matches_any, split_negations
|
|
32
32
|
|
|
33
33
|
IGNORED_DIRS = {
|
|
@@ -399,6 +399,11 @@ class CodeGraph:
|
|
|
399
399
|
self.api_links: List[Dict[str, Any]] = [] # cross-stack edges: frontend call -> backend endpoint
|
|
400
400
|
self.last_scanned: float = 0.0
|
|
401
401
|
self.backend: str = self._detect_backend()
|
|
402
|
+
# Files the last scan touched or dropped, so persistence can write
|
|
403
|
+
# incrementally instead of rebuilding the whole index.
|
|
404
|
+
self._dirty_files: Set[str] = set()
|
|
405
|
+
self._deleted_files: Set[str] = set()
|
|
406
|
+
self._ctx_index: Optional[ContextIndex] = None
|
|
402
407
|
|
|
403
408
|
if self.use_disk_cache and os.environ.get("TOKENSAFE_GRAPH_DISK_CACHE", "1") != "0":
|
|
404
409
|
self._load_disk_cache()
|
|
@@ -414,9 +419,8 @@ class CodeGraph:
|
|
|
414
419
|
return "stdlib"
|
|
415
420
|
|
|
416
421
|
def _cache_path(self) -> str:
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
return os.path.join(cache_dir, f"{key}.db")
|
|
422
|
+
# One index per workspace: graph rows and the line corpus share it.
|
|
423
|
+
return index_db_path(self.root_dir)
|
|
420
424
|
|
|
421
425
|
def _legacy_json_cache_path(self) -> str:
|
|
422
426
|
cache_dir = os.path.join(resolve_data_dir(), "graph_cache")
|
|
@@ -439,6 +443,13 @@ class CodeGraph:
|
|
|
439
443
|
|
|
440
444
|
def _load_disk_cache(self) -> bool:
|
|
441
445
|
path = self._cache_path()
|
|
446
|
+
if not os.path.exists(path):
|
|
447
|
+
# The unified index is new: import a pre-kernel graph cache once.
|
|
448
|
+
try:
|
|
449
|
+
if os.path.exists(legacy_graph_db_path(self.root_dir)):
|
|
450
|
+
ContextIndex(self.root_dir)
|
|
451
|
+
except Exception:
|
|
452
|
+
pass
|
|
442
453
|
if os.path.exists(path):
|
|
443
454
|
try:
|
|
444
455
|
con = sqlite3.connect(path, timeout=5.0)
|
|
@@ -567,98 +578,31 @@ class CodeGraph:
|
|
|
567
578
|
|
|
568
579
|
return False
|
|
569
580
|
|
|
581
|
+
|
|
582
|
+
def _context_index(self) -> ContextIndex:
|
|
583
|
+
if self._ctx_index is None:
|
|
584
|
+
self._ctx_index = ContextIndex(self.root_dir)
|
|
585
|
+
return self._ctx_index
|
|
586
|
+
|
|
570
587
|
def _save_disk_cache(self) -> None:
|
|
588
|
+
"""Writes only what the last scan touched; global tables are rebuilt."""
|
|
571
589
|
if not self.use_disk_cache or os.environ.get("TOKENSAFE_GRAPH_DISK_CACHE", "1") == "0":
|
|
572
590
|
return
|
|
573
|
-
|
|
574
|
-
|
|
591
|
+
dirty = set(self._dirty_files)
|
|
592
|
+
deleted = set(self._deleted_files)
|
|
593
|
+
self._dirty_files.clear()
|
|
594
|
+
self._deleted_files.clear()
|
|
595
|
+
changed: Optional[Set[str]] = dirty if (dirty or deleted) else None
|
|
575
596
|
try:
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
cur.execute("CREATE TABLE graph_meta (key TEXT PRIMARY KEY, val TEXT)")
|
|
586
|
-
cur.execute("CREATE TABLE file_stats (rel_path TEXT PRIMARY KEY, mtime REAL, size INTEGER)")
|
|
587
|
-
cur.execute("CREATE TABLE symbols (sym_key TEXT PRIMARY KEY, rel_path TEXT, name TEXT, kind TEXT, line_start INTEGER, line_end INTEGER, signature TEXT)")
|
|
588
|
-
cur.execute("CREATE TABLE file_symbols (rel_path TEXT, sym_key TEXT, idx INTEGER, PRIMARY KEY (rel_path, sym_key))")
|
|
589
|
-
cur.execute("CREATE TABLE file_imports (rel_path TEXT, imported TEXT, PRIMARY KEY (rel_path, imported))")
|
|
590
|
-
cur.execute("CREATE TABLE glob_imports (rel_path TEXT, pattern TEXT, PRIMARY KEY (rel_path, pattern))")
|
|
591
|
-
cur.execute("CREATE TABLE edges (source TEXT, target TEXT, PRIMARY KEY (source, target))")
|
|
592
|
-
cur.execute("CREATE TABLE api_endpoints (rel_path TEXT, route TEXT, sym_key TEXT, method TEXT)")
|
|
593
|
-
cur.execute("CREATE TABLE api_calls (rel_path TEXT, route TEXT, sym_key TEXT, method TEXT)")
|
|
594
|
-
cur.execute("CREATE TABLE file_mounts (rel_path TEXT, prefix TEXT, ident TEXT, module TEXT)")
|
|
595
|
-
cur.execute("CREATE TABLE api_links (link_json TEXT)")
|
|
596
|
-
|
|
597
|
-
cur.executemany(
|
|
598
|
-
"INSERT INTO graph_meta VALUES (?, ?)",
|
|
599
|
-
[
|
|
600
|
-
("version", str(_CACHE_SCHEMA_VERSION)),
|
|
601
|
-
("root_dir", self.root_dir),
|
|
602
|
-
("backend", self.backend),
|
|
603
|
-
("last_scanned", str(self.last_scanned)),
|
|
604
|
-
],
|
|
605
|
-
)
|
|
606
|
-
cur.executemany(
|
|
607
|
-
"INSERT INTO file_stats VALUES (?, ?, ?)",
|
|
608
|
-
[(k, v[0], v[1]) for k, v in self.file_stats.items()],
|
|
609
|
-
)
|
|
610
|
-
cur.executemany(
|
|
611
|
-
"INSERT INTO symbols VALUES (?, ?, ?, ?, ?, ?, ?)",
|
|
612
|
-
[
|
|
613
|
-
(k, s.file_path, s.name, s.kind, s.line_start, s.line_end, s.signature)
|
|
614
|
-
for k, s in self.symbols.items()
|
|
615
|
-
],
|
|
616
|
-
)
|
|
617
|
-
fs_rows = []
|
|
618
|
-
for rel_path, sym_keys in self.file_symbols.items():
|
|
619
|
-
for idx, sym_key in enumerate(sym_keys):
|
|
620
|
-
fs_rows.append((rel_path, sym_key, idx))
|
|
621
|
-
cur.executemany("INSERT INTO file_symbols VALUES (?, ?, ?)", fs_rows)
|
|
622
|
-
|
|
623
|
-
cur.executemany(
|
|
624
|
-
"INSERT INTO file_imports VALUES (?, ?)",
|
|
625
|
-
[(rel_path, imp) for rel_path, imps in self.file_imports.items() for imp in imps],
|
|
626
|
-
)
|
|
627
|
-
cur.executemany(
|
|
628
|
-
"INSERT INTO glob_imports VALUES (?, ?)",
|
|
629
|
-
[(rel_path, pat) for rel_path, pats in self.glob_imports.items() for pat in pats],
|
|
630
|
-
)
|
|
631
|
-
cur.executemany(
|
|
632
|
-
"INSERT INTO edges VALUES (?, ?)",
|
|
633
|
-
[(src, tgt) for src, tgts in self.edges.items() for tgt in tgts],
|
|
634
|
-
)
|
|
635
|
-
cur.executemany(
|
|
636
|
-
"INSERT INTO api_endpoints VALUES (?, ?, ?, ?)",
|
|
637
|
-
[(rel, ep[0], ep[1], ep[2] if len(ep) > 2 else None) for rel, eps in self.file_endpoints.items() for ep in eps],
|
|
638
|
-
)
|
|
639
|
-
cur.executemany(
|
|
640
|
-
"INSERT INTO api_calls VALUES (?, ?, ?, ?)",
|
|
641
|
-
[(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],
|
|
642
|
-
)
|
|
643
|
-
cur.executemany(
|
|
644
|
-
"INSERT INTO file_mounts VALUES (?, ?, ?, ?)",
|
|
645
|
-
[(rel, prefix, ident, module) for rel, mounts in self.file_mounts.items() for (prefix, ident, module) in mounts],
|
|
646
|
-
)
|
|
647
|
-
cur.executemany(
|
|
648
|
-
"INSERT INTO api_links VALUES (?)",
|
|
649
|
-
[(json.dumps(lk, ensure_ascii=False),) for lk in self.api_links],
|
|
650
|
-
)
|
|
651
|
-
con.commit()
|
|
652
|
-
finally:
|
|
653
|
-
con.close()
|
|
654
|
-
os.replace(tmp_path, path)
|
|
655
|
-
GraphEngine._prune_cache(cache_dir, path)
|
|
656
|
-
except Exception:
|
|
657
|
-
try:
|
|
658
|
-
os.unlink(tmp_path)
|
|
659
|
-
except OSError:
|
|
660
|
-
pass
|
|
661
|
-
except OSError:
|
|
597
|
+
index = self._context_index()
|
|
598
|
+
index.save_graph(self, changed=changed, deleted=deleted)
|
|
599
|
+
if changed is None:
|
|
600
|
+
index.sync_text(list(self.file_stats.keys()))
|
|
601
|
+
else:
|
|
602
|
+
index.sync_text(dirty, deleted)
|
|
603
|
+
ContextIndex.prune(keep_path=index.db_path)
|
|
604
|
+
except Exception:
|
|
605
|
+
# The index is a cache: a failed write must never break the scan.
|
|
662
606
|
pass
|
|
663
607
|
|
|
664
608
|
def add_edge(self, source: str, target: str):
|
|
@@ -683,8 +627,9 @@ class CodeGraph:
|
|
|
683
627
|
Fast incremental scan of the workspace.
|
|
684
628
|
Parses modified files only (checked via `(mtime, size)`); returns number of files re-indexed.
|
|
685
629
|
"""
|
|
686
|
-
|
|
687
|
-
|
|
630
|
+
from src.win_paths import is_system_root
|
|
631
|
+
|
|
632
|
+
if is_system_root(self.root_dir):
|
|
688
633
|
return 0
|
|
689
634
|
|
|
690
635
|
current_backend = self._detect_backend()
|
|
@@ -706,11 +651,11 @@ class CodeGraph:
|
|
|
706
651
|
full_path = os.path.join(dirpath, filename)
|
|
707
652
|
rel_path = os.path.relpath(full_path, self.root_dir).replace("\\", "/")
|
|
708
653
|
if _is_generated_asset(rel_path, filename):
|
|
709
|
-
# A bundle indexed by an older scan must be dropped, not just skipped.
|
|
710
654
|
if rel_path in self.file_symbols or rel_path in self.file_stats:
|
|
711
655
|
self._purge_file(rel_path)
|
|
712
656
|
self.file_stats.pop(rel_path, None)
|
|
713
657
|
self.file_mtimes.pop(rel_path, None)
|
|
658
|
+
self._deleted_files.add(rel_path)
|
|
714
659
|
reindexed += 1
|
|
715
660
|
continue
|
|
716
661
|
current_files.add(rel_path)
|
|
@@ -722,6 +667,7 @@ class CodeGraph:
|
|
|
722
667
|
self._purge_file(rel_path)
|
|
723
668
|
self.file_stats.pop(rel_path, None)
|
|
724
669
|
self.file_mtimes.pop(rel_path, None)
|
|
670
|
+
self._deleted_files.add(rel_path)
|
|
725
671
|
reindexed += 1
|
|
726
672
|
continue
|
|
727
673
|
sig = (st.st_mtime, st.st_size)
|
|
@@ -741,6 +687,7 @@ class CodeGraph:
|
|
|
741
687
|
self._index_file(full_path, rel_path)
|
|
742
688
|
self.file_stats[rel_path] = sig
|
|
743
689
|
self.file_mtimes[rel_path] = st.st_mtime
|
|
690
|
+
self._dirty_files.add(rel_path)
|
|
744
691
|
reindexed += 1
|
|
745
692
|
|
|
746
693
|
# Purge removed files
|
|
@@ -749,6 +696,7 @@ class CodeGraph:
|
|
|
749
696
|
self._purge_file(del_path)
|
|
750
697
|
self.file_stats.pop(del_path, None)
|
|
751
698
|
self.file_mtimes.pop(del_path, None)
|
|
699
|
+
self._deleted_files.add(del_path)
|
|
752
700
|
|
|
753
701
|
if reindexed > 0 or deleted or force:
|
|
754
702
|
self._resolve_local_imports()
|
package/src/guard.py
CHANGED
package/src/installer.py
CHANGED
|
@@ -17,6 +17,7 @@ import hashlib
|
|
|
17
17
|
import shutil
|
|
18
18
|
import re
|
|
19
19
|
import shlex
|
|
20
|
+
from src.win_paths import quote_hook_command
|
|
20
21
|
import signal
|
|
21
22
|
import subprocess
|
|
22
23
|
import time
|
|
@@ -351,9 +352,14 @@ class AgentInstaller:
|
|
|
351
352
|
|
|
352
353
|
@staticmethod
|
|
353
354
|
def _tokensafe_hook_command(script_name: str) -> str:
|
|
354
|
-
"""Shell command string for a bundled hook adapter (
|
|
355
|
+
"""Shell command string for a bundled hook adapter (platform-quoted).
|
|
356
|
+
|
|
357
|
+
``shlex.quote`` single-quotes any path with a space; cmd.exe does not
|
|
358
|
+
treat ``'`` as quoting, so a Windows profile like ``C:\\Users\\Oleg
|
|
359
|
+
Savelev`` registered a hook that could never start.
|
|
360
|
+
"""
|
|
355
361
|
script = os.path.join(PROJECT_ROOT, "hooks", script_name)
|
|
356
|
-
return
|
|
362
|
+
return quote_hook_command([PYTHON_BIN, script])
|
|
357
363
|
|
|
358
364
|
@staticmethod
|
|
359
365
|
def _load_json_with_backup(config_file: str) -> Tuple[Optional[Dict[str, Any]], Optional[str]]:
|
|
@@ -1406,13 +1412,17 @@ WantedBy=default.target
|
|
|
1406
1412
|
# Once the plugin declares its own mcp_config.json (loaded by
|
|
1407
1413
|
# Antigravity together with the plugin), a leftover user-level
|
|
1408
1414
|
# tokensafe entry would register the MCP server twice. Migrate it
|
|
1409
|
-
# away —
|
|
1415
|
+
# away — but only when the plugin manifest can actually start the
|
|
1416
|
+
# server. On Windows that means rewriting `sh -c` / `python3` first.
|
|
1417
|
+
plugin_ready = cls._rewrite_plugin_manifests(target) if os.name == "nt" else True
|
|
1410
1418
|
migrated = False
|
|
1411
|
-
if os.name != "nt" and os.path.isfile(os.path.join(PROJECT_ROOT, "mcp_config.json")):
|
|
1419
|
+
if (os.name != "nt" or plugin_ready) and os.path.isfile(os.path.join(PROJECT_ROOT, "mcp_config.json")):
|
|
1412
1420
|
migrated = cls._remove_user_level_tokensafe_mcp()
|
|
1413
1421
|
msg = f"Symlinked plugin into {target}"
|
|
1414
1422
|
if migrated:
|
|
1415
1423
|
msg += "; migrated user-level MCP entry to the plugin-declared server"
|
|
1424
|
+
if os.name == "nt" and not plugin_ready:
|
|
1425
|
+
msg += "; kept the user-level MCP entry (the plugin copy could not be rewritten)"
|
|
1416
1426
|
return True, msg
|
|
1417
1427
|
|
|
1418
1428
|
elif info["type"] == "cursor_env":
|
|
@@ -1912,6 +1922,56 @@ WantedBy=default.target
|
|
|
1912
1922
|
continue
|
|
1913
1923
|
return removed
|
|
1914
1924
|
|
|
1925
|
+
@classmethod
|
|
1926
|
+
def _rewrite_plugin_manifests(cls, plugin_dir: str) -> bool:
|
|
1927
|
+
"""Windows: make the plugin-declared MCP server and hooks startable.
|
|
1928
|
+
|
|
1929
|
+
The repo manifests assume a POSIX shell (`sh -c ...`) and a `python3`
|
|
1930
|
+
executable; cmd.exe has neither. A symlinked plugin points back at the
|
|
1931
|
+
repository and is never rewritten (the caller keeps the user-level MCP
|
|
1932
|
+
entry in that case). Returns True when the MCP manifest was rewritten.
|
|
1933
|
+
"""
|
|
1934
|
+
if os.name != "nt" or os.path.islink(plugin_dir):
|
|
1935
|
+
return False
|
|
1936
|
+
rewrote_mcp = False
|
|
1937
|
+
mcp_path = os.path.join(plugin_dir, "mcp_config.json")
|
|
1938
|
+
try:
|
|
1939
|
+
with open(mcp_path, "r", encoding="utf-8") as handle:
|
|
1940
|
+
mcp_data = json.load(handle)
|
|
1941
|
+
server = ((mcp_data.get("mcpServers") or {}).get("tokensafe") or {})
|
|
1942
|
+
if isinstance(server, dict) and server.get("command") == "sh":
|
|
1943
|
+
server["command"] = PYTHON_BIN
|
|
1944
|
+
server["args"] = [MCP_SERVER_PATH]
|
|
1945
|
+
cls._write_file_safely(mcp_path, json.dumps(mcp_data, indent=2) + "\n")
|
|
1946
|
+
rewrote_mcp = True
|
|
1947
|
+
except Exception:
|
|
1948
|
+
rewrote_mcp = False
|
|
1949
|
+
|
|
1950
|
+
def _fix_commands(node):
|
|
1951
|
+
if isinstance(node, dict):
|
|
1952
|
+
command = node.get("command")
|
|
1953
|
+
if isinstance(command, str) and command.split()[0:1] in (["python3"], ["python"]):
|
|
1954
|
+
rest = command.split(None, 1)[1:] or [""]
|
|
1955
|
+
node["command"] = quote_hook_command([PYTHON_BIN, *rest])
|
|
1956
|
+
for value in node.values():
|
|
1957
|
+
_fix_commands(value)
|
|
1958
|
+
elif isinstance(node, list):
|
|
1959
|
+
for value in node:
|
|
1960
|
+
_fix_commands(value)
|
|
1961
|
+
|
|
1962
|
+
for name in ("hooks.json", "kimi.plugin.json"):
|
|
1963
|
+
path = os.path.join(plugin_dir, name)
|
|
1964
|
+
if not os.path.isfile(path):
|
|
1965
|
+
continue
|
|
1966
|
+
try:
|
|
1967
|
+
with open(path, "r", encoding="utf-8") as handle:
|
|
1968
|
+
manifest = json.load(handle)
|
|
1969
|
+
_fix_commands(manifest)
|
|
1970
|
+
cls._write_file_safely(path, json.dumps(manifest, indent=2) + "\n")
|
|
1971
|
+
except Exception:
|
|
1972
|
+
continue
|
|
1973
|
+
return rewrote_mcp
|
|
1974
|
+
|
|
1915
1975
|
@classmethod
|
|
1916
1976
|
def _symlink_dir(cls, source_path: str, target_path: str):
|
|
1917
1977
|
"""Safely creates or replaces a symlink to a directory (falls back to copytree if symlinks fail)."""
|
package/src/license_manager.py
CHANGED
|
@@ -317,6 +317,64 @@ class LicenseManager:
|
|
|
317
317
|
sig = hmac.new(hmac_key.encode("utf-8"), payload_bytes, hashlib.sha256).hexdigest()[:32]
|
|
318
318
|
return f"TS1.{payload_b64}.{sig}"
|
|
319
319
|
|
|
320
|
+
@classmethod
|
|
321
|
+
def _disk_cache_path(cls) -> str:
|
|
322
|
+
try:
|
|
323
|
+
return os.path.join(resolve_data_dir(), "license_state.json")
|
|
324
|
+
except Exception:
|
|
325
|
+
return ""
|
|
326
|
+
|
|
327
|
+
@staticmethod
|
|
328
|
+
def _cache_slot(cache_key: str) -> str:
|
|
329
|
+
return hashlib.sha256(cache_key.encode("utf-8")).hexdigest()[:16]
|
|
330
|
+
|
|
331
|
+
@classmethod
|
|
332
|
+
def _disk_cache_get(cls, cache_key: str) -> Optional[Dict[str, Any]]:
|
|
333
|
+
"""Cross-process verified-license cache (hooks are short-lived processes)."""
|
|
334
|
+
path = cls._disk_cache_path()
|
|
335
|
+
if not path:
|
|
336
|
+
return None
|
|
337
|
+
try:
|
|
338
|
+
with open(path, "r", encoding="utf-8") as fh:
|
|
339
|
+
data = json.load(fh)
|
|
340
|
+
entry = (data.get("entries") or {}).get(cls._cache_slot(cache_key))
|
|
341
|
+
if not isinstance(entry, dict) or float(entry.get("expires", 0)) <= time.time():
|
|
342
|
+
return None
|
|
343
|
+
payload = entry.get("payload")
|
|
344
|
+
return dict(payload) if isinstance(payload, dict) else None
|
|
345
|
+
except Exception:
|
|
346
|
+
return None
|
|
347
|
+
|
|
348
|
+
@classmethod
|
|
349
|
+
def _disk_cache_put(cls, cache_key: str, payload: Dict[str, Any], expires: float) -> None:
|
|
350
|
+
path = cls._disk_cache_path()
|
|
351
|
+
if not path:
|
|
352
|
+
return
|
|
353
|
+
try:
|
|
354
|
+
data: Dict[str, Any] = {}
|
|
355
|
+
try:
|
|
356
|
+
with open(path, "r", encoding="utf-8") as fh:
|
|
357
|
+
loaded = json.load(fh)
|
|
358
|
+
if isinstance(loaded, dict):
|
|
359
|
+
data = loaded
|
|
360
|
+
except Exception:
|
|
361
|
+
data = {}
|
|
362
|
+
entries = data.get("entries") if isinstance(data.get("entries"), dict) else {}
|
|
363
|
+
now = time.time()
|
|
364
|
+
alive = {
|
|
365
|
+
key: value
|
|
366
|
+
for key, value in entries.items()
|
|
367
|
+
if isinstance(value, dict) and float(value.get("expires", 0)) > now
|
|
368
|
+
}
|
|
369
|
+
alive[cls._cache_slot(cache_key)] = {"payload": payload, "expires": expires}
|
|
370
|
+
payload_out = {"version": 1, "entries": dict(list(alive.items())[-8:])}
|
|
371
|
+
tmp = f"{path}.tmp.{os.getpid()}"
|
|
372
|
+
with open(tmp, "w", encoding="utf-8") as fh:
|
|
373
|
+
json.dump(payload_out, fh)
|
|
374
|
+
os.replace(tmp, path)
|
|
375
|
+
except Exception:
|
|
376
|
+
pass
|
|
377
|
+
|
|
320
378
|
@classmethod
|
|
321
379
|
def validate_license(
|
|
322
380
|
cls,
|
|
@@ -346,6 +404,12 @@ class LicenseManager:
|
|
|
346
404
|
if cached and now < cached[1]:
|
|
347
405
|
return True, dict(cached[0]), "License is active and valid (cached)"
|
|
348
406
|
|
|
407
|
+
# Same fast path across processes: every hook is a fresh interpreter,
|
|
408
|
+
# so the in-process memo above never survives to the next tool call.
|
|
409
|
+
disk_cached = cls._disk_cache_get(cache_key)
|
|
410
|
+
if disk_cached is not None:
|
|
411
|
+
return True, disk_cached, "License is active and valid (disk cache)"
|
|
412
|
+
|
|
349
413
|
parts = license_key.split(".")
|
|
350
414
|
if len(parts) != 3 or parts[0] not in ("TS1", "TS2"):
|
|
351
415
|
return False, {}, "Invalid license key format (must start with TS2. or TS1.)"
|
|
@@ -418,6 +482,8 @@ class LicenseManager:
|
|
|
418
482
|
cls._VALIDATION_CACHE.pop(oldest, None)
|
|
419
483
|
cls._VALIDATION_CACHE[cache_key] = (payload, now + ttl)
|
|
420
484
|
|
|
485
|
+
cls._disk_cache_put(cache_key, payload, now + ttl)
|
|
486
|
+
|
|
421
487
|
return True, payload, "License is active and valid"
|
|
422
488
|
|
|
423
489
|
@classmethod
|
package/src/mcp_proxy.py
CHANGED