tokensafe 4.5.4 → 4.5.5
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/kimi.plugin.json +1 -1
- package/package.json +1 -1
- package/plugin.json +1 -1
- package/server.json +3 -3
- package/src/cli.py +31 -2
- package/src/environment_auditor.py +149 -9
- package/src/mcp_server.py +1 -1
- package/src/syntax_guard.py +1 -1
- package/src/telemetry_sync.py +1 -1
- package/src/version_checker.py +1 -1
package/kimi.plugin.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tokensafe",
|
|
3
|
-
"version": "4.5.
|
|
3
|
+
"version": "4.5.5",
|
|
4
4
|
"description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
|
|
5
5
|
"homepage": "https://tokensafe.dev",
|
|
6
6
|
"license": "MIT",
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tokensafe",
|
|
3
3
|
"mcpName": "dev.tokensafe/tokensafe",
|
|
4
|
-
"version": "4.5.
|
|
4
|
+
"version": "4.5.5",
|
|
5
5
|
"description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
|
|
6
6
|
"main": "bin/tokensafe.js",
|
|
7
7
|
"bin": {
|
package/plugin.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tokensafe",
|
|
3
3
|
"displayName": "TokenSafe",
|
|
4
|
-
"version": "4.5.
|
|
4
|
+
"version": "4.5.5",
|
|
5
5
|
"description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
|
|
6
6
|
"logo": "assets/logo.png",
|
|
7
7
|
"developerName": "TokenSafe",
|
package/server.json
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"name": "dev.tokensafe/tokensafe",
|
|
4
4
|
"title": "TokenSafe",
|
|
5
5
|
"description": "Your AI agent is smart enough to code all day. Local firewall & zero-loss runtime.",
|
|
6
|
-
"version": "4.5.
|
|
6
|
+
"version": "4.5.5",
|
|
7
7
|
"websiteUrl": "https://tokensafe.dev",
|
|
8
8
|
"repository": {
|
|
9
9
|
"url": "https://github.com/tokensafe-dev/tokensafe",
|
|
@@ -23,7 +23,7 @@
|
|
|
23
23
|
"registryType": "npm",
|
|
24
24
|
"registryBaseUrl": "https://registry.npmjs.org",
|
|
25
25
|
"identifier": "tokensafe",
|
|
26
|
-
"version": "4.5.
|
|
26
|
+
"version": "4.5.5",
|
|
27
27
|
"runtimeHint": "npx",
|
|
28
28
|
"transport": {
|
|
29
29
|
"type": "stdio"
|
|
@@ -39,7 +39,7 @@
|
|
|
39
39
|
"registryType": "pypi",
|
|
40
40
|
"registryBaseUrl": "https://pypi.org",
|
|
41
41
|
"identifier": "tokensafe",
|
|
42
|
-
"version": "4.5.
|
|
42
|
+
"version": "4.5.5",
|
|
43
43
|
"runtimeHint": "uvx",
|
|
44
44
|
"transport": {
|
|
45
45
|
"type": "stdio"
|
package/src/cli.py
CHANGED
|
@@ -116,7 +116,8 @@ def _print_help():
|
|
|
116
116
|
print(" expand-ref <hash> Restore folded tool/command/file result by its 8-char hash")
|
|
117
117
|
print(" wrap <command> Run command with compact output folding (e.g. tests/logs)")
|
|
118
118
|
print(" web <url> Fetch web page/docs and print clean compact Markdown")
|
|
119
|
-
print(" doctor [--cleanup]
|
|
119
|
+
print(" doctor [--fix | --cleanup] Audit MCP/skill overhead, repair configs & consolidate ghost rules")
|
|
120
|
+
print(" skills [list|disable|enable] Inspect and toggle active skills to cut turn context tax")
|
|
120
121
|
print(" tests [pytest] [--traceback] Run the unit test suite (compact failure report)")
|
|
121
122
|
print(" prune [--days N | --max N] Compact metrics database (roll old events)")
|
|
122
123
|
print(" vacuum Reclaim SQLite disk space")
|
|
@@ -960,6 +961,34 @@ def main(argv: Optional[List[str]] = None):
|
|
|
960
961
|
res = CompetitorAuditor.cleanup(c["id"])
|
|
961
962
|
print(f" \033[32m✔ Cleaned {c['name']}: {', '.join(res.get('removed', []))}\033[0m")
|
|
962
963
|
|
|
964
|
+
elif command in ("skills", "skill"):
|
|
965
|
+
from src.environment_auditor import EnvironmentAuditor
|
|
966
|
+
sub = args[1] if len(args) > 1 else "list"
|
|
967
|
+
if sub in ("disable", "off", "rm"):
|
|
968
|
+
if len(args) < 3:
|
|
969
|
+
print("Usage: tokensafe skills disable <skill_name>")
|
|
970
|
+
sys.exit(1)
|
|
971
|
+
target = args[2].strip()
|
|
972
|
+
res = EnvironmentAuditor.disable_skill(target)
|
|
973
|
+
if res.get("success"):
|
|
974
|
+
print(f"\n\033[32m✔ Skill '{res['skill']}' disabled ({res['path']}).\033[0m\n")
|
|
975
|
+
else:
|
|
976
|
+
print(f"\n\033[31m✖ {res.get('error', 'Failed to disable skill')}\033[0m\n")
|
|
977
|
+
sys.exit(1)
|
|
978
|
+
elif sub in ("enable", "on", "add"):
|
|
979
|
+
if len(args) < 3:
|
|
980
|
+
print("Usage: tokensafe skills enable <skill_name>")
|
|
981
|
+
sys.exit(1)
|
|
982
|
+
target = args[2].strip()
|
|
983
|
+
res = EnvironmentAuditor.enable_skill(target)
|
|
984
|
+
if res.get("success"):
|
|
985
|
+
print(f"\n\033[32m✔ Skill '{res['skill']}' re-enabled ({res['path']}).\033[0m\n")
|
|
986
|
+
else:
|
|
987
|
+
print(f"\n\033[31m✖ {res.get('error', 'Failed to enable skill')}\033[0m\n")
|
|
988
|
+
sys.exit(1)
|
|
989
|
+
else:
|
|
990
|
+
print(EnvironmentAuditor.format_skills_report())
|
|
991
|
+
|
|
963
992
|
elif command in ("web", "fetch", "url"):
|
|
964
993
|
if len(args) < 2:
|
|
965
994
|
print("Usage: tokensafe web <url>")
|
|
@@ -1659,7 +1688,7 @@ def main(argv: Optional[List[str]] = None):
|
|
|
1659
1688
|
|
|
1660
1689
|
else:
|
|
1661
1690
|
print(f"Unknown command: {command}")
|
|
1662
|
-
print("Available commands: init, login, logout, stats, status, sync, html, test, tests, expand-ref, wrap, web, doctor, providers, mcp, benchmark, proxy, graph, map, skeleton, guard, mistakes, vacuum, prune, digest, activate, license, markdown, install, uninstall, setup, update, check-update, reset. Run 'tokensafe help' for details.")
|
|
1691
|
+
print("Available commands: init, login, logout, stats, status, sync, html, test, tests, expand-ref, wrap, web, doctor, skills, providers, mcp, benchmark, proxy, graph, map, skeleton, guard, mistakes, vacuum, prune, digest, activate, license, markdown, install, uninstall, setup, update, check-update, reset. Run 'tokensafe help' for details.")
|
|
1663
1692
|
sys.exit(1)
|
|
1664
1693
|
|
|
1665
1694
|
if __name__ == "__main__":
|
|
@@ -656,8 +656,11 @@ class EnvironmentAuditor:
|
|
|
656
656
|
shutil.copy2(p, f"{p}.backup")
|
|
657
657
|
cleaned = AgentInstaller._clean_codex_orphans(orig_text)
|
|
658
658
|
try:
|
|
659
|
-
|
|
660
|
-
|
|
659
|
+
try:
|
|
660
|
+
import tomllib
|
|
661
|
+
tomllib.loads(cleaned)
|
|
662
|
+
except ImportError:
|
|
663
|
+
pass
|
|
661
664
|
with open(p, "w", encoding="utf-8") as f:
|
|
662
665
|
f.write(cleaned)
|
|
663
666
|
fixed.append(f"Repaired TOML syntax/orphans in {p} (backup: {p}.backup)")
|
|
@@ -743,20 +746,155 @@ class EnvironmentAuditor:
|
|
|
743
746
|
"backup_dir": backup_dir if fixed else None,
|
|
744
747
|
}
|
|
745
748
|
|
|
749
|
+
@classmethod
|
|
750
|
+
def list_skills(cls, workspace_root: Optional[str] = None) -> List[Dict[str, Any]]:
|
|
751
|
+
"""Lists active and disabled skills across all skill roots with source & token estimate."""
|
|
752
|
+
skills: List[Dict[str, Any]] = []
|
|
753
|
+
disabled_plugins = cls._get_disabled_plugin_names()
|
|
754
|
+
plugins_dir = os.path.abspath(cls.get_plugins_dir())
|
|
755
|
+
seen_real = set()
|
|
756
|
+
|
|
757
|
+
for sdir in cls.get_skills_dirs(workspace_root):
|
|
758
|
+
is_plugins_root = os.path.abspath(sdir) == plugins_dir
|
|
759
|
+
for root, dirs, files in os.walk(sdir, followlinks=True):
|
|
760
|
+
real_root = os.path.realpath(root)
|
|
761
|
+
if real_root in seen_real:
|
|
762
|
+
dirs[:] = []
|
|
763
|
+
continue
|
|
764
|
+
seen_real.add(real_root)
|
|
765
|
+
if is_plugins_root and os.path.abspath(root) == plugins_dir:
|
|
766
|
+
dirs[:] = [d for d in dirs if d not in disabled_plugins and not d.endswith(".disabled")]
|
|
767
|
+
else:
|
|
768
|
+
dirs[:] = [d for d in dirs if d not in ("node_modules", ".git", "__pycache__", ".venv", "venv")]
|
|
769
|
+
|
|
770
|
+
if "SKILL.md" in files:
|
|
771
|
+
folder_name = os.path.basename(root)
|
|
772
|
+
is_disabled = folder_name.endswith(".disabled") or ".disabled" + os.sep in root
|
|
773
|
+
clean_name = folder_name[:-9] if folder_name.endswith(".disabled") else folder_name
|
|
774
|
+
desc = ""
|
|
775
|
+
try:
|
|
776
|
+
with open(os.path.join(root, "SKILL.md"), "r", encoding="utf-8", errors="replace") as f:
|
|
777
|
+
head = f.read(1200)
|
|
778
|
+
m_name = re.search(r"(?m)^name:\s*(.+)$", head)
|
|
779
|
+
if m_name and m_name.group(1).strip():
|
|
780
|
+
clean_name = m_name.group(1).strip().strip("'\"")
|
|
781
|
+
m_desc = re.search(r"(?m)^description:\s*(.+)$", head)
|
|
782
|
+
if m_desc:
|
|
783
|
+
raw_desc = m_desc.group(1).strip().strip("'\"")
|
|
784
|
+
if raw_desc in (">", ">-", "|", "|-"):
|
|
785
|
+
after = head[m_desc.end():]
|
|
786
|
+
for next_l in after.splitlines():
|
|
787
|
+
stripped = next_l.strip()
|
|
788
|
+
if stripped and not re.match(r"^[A-Za-z0-9_-]+:\s*", stripped):
|
|
789
|
+
desc = stripped[:90]
|
|
790
|
+
break
|
|
791
|
+
else:
|
|
792
|
+
desc = raw_desc[:90]
|
|
793
|
+
except Exception:
|
|
794
|
+
pass
|
|
795
|
+
skills.append({
|
|
796
|
+
"name": clean_name,
|
|
797
|
+
"dir_name": folder_name[:-9] if folder_name.endswith(".disabled") else folder_name,
|
|
798
|
+
"path": root,
|
|
799
|
+
"root": sdir,
|
|
800
|
+
"disabled": is_disabled,
|
|
801
|
+
"est_tokens": EST_TOKENS_PER_SKILL,
|
|
802
|
+
"description": desc,
|
|
803
|
+
"builtin": "builtin" in root.split(os.sep),
|
|
804
|
+
})
|
|
805
|
+
dirs[:] = []
|
|
806
|
+
return sorted(skills, key=lambda x: (x["disabled"], x["name"].lower()))
|
|
807
|
+
|
|
808
|
+
@classmethod
|
|
809
|
+
def disable_skill(cls, skill_name: str, workspace_root: Optional[str] = None) -> Dict[str, Any]:
|
|
810
|
+
"""Disables a user/workspace skill by renaming its directory to `<name>.disabled`."""
|
|
811
|
+
target = skill_name.strip().lower()
|
|
812
|
+
for sk in cls.list_skills(workspace_root):
|
|
813
|
+
if sk["disabled"]:
|
|
814
|
+
continue
|
|
815
|
+
if sk["name"].lower() == target or sk["dir_name"].lower() == target:
|
|
816
|
+
if sk["builtin"]:
|
|
817
|
+
return {"success": False, "error": f"Skill '{sk['name']}' is a builtin Antigravity skill and cannot be renamed safely."}
|
|
818
|
+
src_path = sk["path"]
|
|
819
|
+
dst_path = f"{src_path}.disabled"
|
|
820
|
+
if os.path.exists(dst_path):
|
|
821
|
+
return {"success": False, "error": f"Target '{dst_path}' already exists."}
|
|
822
|
+
try:
|
|
823
|
+
os.rename(src_path, dst_path)
|
|
824
|
+
return {"success": True, "skill": sk["name"], "path": dst_path}
|
|
825
|
+
except Exception as exc:
|
|
826
|
+
return {"success": False, "error": str(exc)}
|
|
827
|
+
return {"success": False, "error": f"Active skill '{skill_name}' not found."}
|
|
828
|
+
|
|
829
|
+
@classmethod
|
|
830
|
+
def enable_skill(cls, skill_name: str, workspace_root: Optional[str] = None) -> Dict[str, Any]:
|
|
831
|
+
"""Re-enables a previously `.disabled` skill directory."""
|
|
832
|
+
target = skill_name.strip().lower()
|
|
833
|
+
for sk in cls.list_skills(workspace_root):
|
|
834
|
+
if not sk["disabled"]:
|
|
835
|
+
continue
|
|
836
|
+
if sk["name"].lower() == target or sk["dir_name"].lower() == target:
|
|
837
|
+
src_path = sk["path"]
|
|
838
|
+
if not src_path.endswith(".disabled"):
|
|
839
|
+
continue
|
|
840
|
+
dst_path = src_path[:-9]
|
|
841
|
+
if os.path.exists(dst_path):
|
|
842
|
+
return {"success": False, "error": f"Target '{dst_path}' already exists."}
|
|
843
|
+
try:
|
|
844
|
+
os.rename(src_path, dst_path)
|
|
845
|
+
return {"success": True, "skill": sk["name"], "path": dst_path}
|
|
846
|
+
except Exception as exc:
|
|
847
|
+
return {"success": False, "error": str(exc)}
|
|
848
|
+
return {"success": False, "error": f"Disabled skill '{skill_name}' not found."}
|
|
849
|
+
|
|
850
|
+
@classmethod
|
|
851
|
+
def format_skills_report(cls, workspace_root: Optional[str] = None) -> str:
|
|
852
|
+
"""Formats a clean CLI list of active & disabled skills grouped by token overhead."""
|
|
853
|
+
skills = cls.list_skills(workspace_root)
|
|
854
|
+
active = [s for s in skills if not s["disabled"]]
|
|
855
|
+
disabled = [s for s in skills if s["disabled"]]
|
|
856
|
+
lines = [
|
|
857
|
+
f"\n\033[1m\033[36m⚡ TOKENSAFE SKILLS INVENTORY ({len(active)} active, {len(disabled)} disabled) ⚡\033[0m\n",
|
|
858
|
+
f" \033[1mActive Context Overhead:\033[0m ~{len(active) * EST_TOKENS_PER_SKILL:,} tokens/turn (~{EST_TOKENS_PER_SKILL} tok/skill)\n",
|
|
859
|
+
]
|
|
860
|
+
for s in active:
|
|
861
|
+
tag = "\033[2m[builtin]\033[0m" if s["builtin"] else f"\033[2m[{os.path.basename(s['root'])}]\033[0m"
|
|
862
|
+
desc = f" — {s['description']}" if s["description"] else ""
|
|
863
|
+
lines.append(f" \033[32m✔\033[0m \033[1m{s['name']:<28}\033[0m {tag}{desc}")
|
|
864
|
+
if disabled:
|
|
865
|
+
lines.append("\n \033[2mDisabled Skills:\033[0m")
|
|
866
|
+
for s in disabled:
|
|
867
|
+
lines.append(f" \033[2m○ {s['name']:<28} [{os.path.basename(s['root'])}]\033[0m")
|
|
868
|
+
lines.append("\n 💡 Tip: Run \033[36mtokensafe skills disable <name>\033[0m (or \033[36mtokensafe skills enable <name>\033[0m) to manage overhead.\n")
|
|
869
|
+
return "\n".join(lines)
|
|
870
|
+
|
|
746
871
|
@classmethod
|
|
747
872
|
def format_cli_report(cls, workspace_root: Optional[str] = None) -> str:
|
|
748
|
-
"""Formats visual CLI report for tokensafe doctor."""
|
|
873
|
+
"""Formats visual CLI report for tokensafe doctor (pure static environment score)."""
|
|
749
874
|
report = cls.audit(workspace_root)
|
|
750
875
|
q_score: Dict[str, Any] = {}
|
|
751
876
|
score_line = ""
|
|
752
877
|
try:
|
|
753
878
|
from src.quality_score import ContextQualityScore
|
|
754
879
|
from src.governor import ContextBudget
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
880
|
+
window = ContextBudget.resolve_window()
|
|
881
|
+
static_overhead = (
|
|
882
|
+
int(report.get("total_static_tokens_per_turn", 0) or 0)
|
|
883
|
+
+ int((report.get("ghost_tokens") or {}).get("ghost_tokens_per_turn", 0) or 0)
|
|
884
|
+
+ int((report.get("rules") or {}).get("total_tokens", 0) or 0)
|
|
885
|
+
)
|
|
886
|
+
used_pct = round(min(100.0, (static_overhead / window) * 100.0), 1) if window > 0 else 0.0
|
|
887
|
+
static_budget = {
|
|
888
|
+
"used_estimated": static_overhead,
|
|
889
|
+
"window_tokens": window,
|
|
890
|
+
"used_pct": used_pct,
|
|
891
|
+
}
|
|
892
|
+
q_score = ContextQualityScore.calculate(budget=static_budget, audit=report)
|
|
758
893
|
color = "\033[32m" if q_score["grade"] in ("S", "A") else ("\033[33m" if q_score["grade"] == "B" else "\033[31m")
|
|
759
|
-
score_line =
|
|
894
|
+
score_line = (
|
|
895
|
+
f" \033[1mEnvironment Quality Score:\033[0m {color}\033[1mGrade {q_score['grade']} ({q_score['label']})\033[0m "
|
|
896
|
+
f"— {q_score['headroom_pct']:.1f}% fresh-turn headroom, {q_score['score']}/100 pts\n"
|
|
897
|
+
)
|
|
760
898
|
except Exception:
|
|
761
899
|
score_line = ""
|
|
762
900
|
|
|
@@ -784,6 +922,8 @@ class EnvironmentAuditor:
|
|
|
784
922
|
if report["total_skills"] >= 15 and report.get("skills_breakdown"):
|
|
785
923
|
for sdir, cnt in sorted(report["skills_breakdown"].items(), key=lambda kv: -kv[1])[:4]:
|
|
786
924
|
lines.append(f" \033[2m• {sdir}: {cnt} skill(s)\033[0m")
|
|
925
|
+
if report["skills_tokens_per_turn"] >= 4000:
|
|
926
|
+
lines.append(" \033[36m💡 Tip: Run 'tokensafe skills list' and 'tokensafe skills disable <name>' to trim unused skills\033[0m")
|
|
787
927
|
|
|
788
928
|
rules = report.get("rules") or {}
|
|
789
929
|
if rules.get("files"):
|
|
@@ -824,9 +964,9 @@ class EnvironmentAuditor:
|
|
|
824
964
|
if has_auto_fixable:
|
|
825
965
|
lines.append(" ➜ Run: \033[36mtokensafe doctor --fix\033[0m to repair configs & consolidate ghost rule duplicates (with backups)")
|
|
826
966
|
if report["skills_tokens_per_turn"] >= 4000:
|
|
827
|
-
lines.append(f" ➜
|
|
967
|
+
lines.append(f" ➜ Run: \033[36mtokensafe skills list\033[0m (currently {report['total_skills']} skills ≈ ~{report['skills_tokens_per_turn']:,} tok/turn; disable unused via \033[36mtokensafe skills disable <name>\033[0m)")
|
|
828
968
|
if q_score.get("headroom_pct", 100.0) < 35.0:
|
|
829
|
-
lines.append(" ➜ Run: \033[36mtokensafe
|
|
969
|
+
lines.append(" ➜ Run: \033[36mtokensafe budget\033[0m to inspect live session context usage")
|
|
830
970
|
else:
|
|
831
971
|
lines.append("\n \033[32m✔ Environment healthy: No critical context bloat detected.\033[0m")
|
|
832
972
|
|
package/src/mcp_server.py
CHANGED
package/src/syntax_guard.py
CHANGED
package/src/telemetry_sync.py
CHANGED
|
@@ -249,7 +249,7 @@ class TelemetrySync:
|
|
|
249
249
|
current_last_id = last_id
|
|
250
250
|
headers = {
|
|
251
251
|
"Content-Type": "application/json",
|
|
252
|
-
"User-Agent": "TokenSafe-Sync/4.5.
|
|
252
|
+
"User-Agent": "TokenSafe-Sync/4.5.5"
|
|
253
253
|
}
|
|
254
254
|
if active_key:
|
|
255
255
|
headers["Authorization"] = f"Bearer {active_key}"
|
package/src/version_checker.py
CHANGED
|
@@ -17,7 +17,7 @@ import urllib.request
|
|
|
17
17
|
import urllib.error
|
|
18
18
|
from typing import Dict, Any, Optional, Tuple
|
|
19
19
|
|
|
20
|
-
CURRENT_VERSION = "4.5.
|
|
20
|
+
CURRENT_VERSION = "4.5.5"
|
|
21
21
|
CACHE_TTL = 86400 # 24 hours
|
|
22
22
|
# When the cloud is unreachable we must NOT cache the synthesized "up to date"
|
|
23
23
|
# answer for a full day — otherwise an update released right after an outage
|