tokensafe 4.7.8 → 4.7.9

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.
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "4.7.8",
2
+ "version": "4.7.9",
3
3
  "name": "tokensafe",
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
  "author": {
package/kimi.plugin.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tokensafe",
3
- "version": "4.7.8",
3
+ "version": "4.7.9",
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": "Apache-2.0",
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "tokensafe",
3
3
  "mcpName": "dev.tokensafe/tokensafe",
4
- "version": "4.7.8",
4
+ "version": "4.7.9",
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.7.8",
4
+ "version": "4.7.9",
5
5
  "license": "Apache-2.0",
6
6
  "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.",
7
7
  "logo": "assets/logo.png",
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.7.8",
6
+ "version": "4.7.9",
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.7.8",
26
+ "version": "4.7.9",
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.7.8",
42
+ "version": "4.7.9",
43
43
  "runtimeHint": "uvx",
44
44
  "transport": {
45
45
  "type": "stdio"
@@ -648,6 +648,228 @@ def _sidecar_cache_dir() -> str:
648
648
  return os.path.join(_tokensafe_home(), "sidecars")
649
649
 
650
650
 
651
+ # --- ASP.NET Core -----------------------------------------------------------------
652
+ #
653
+ # The .NET adapter is a NuGet package with a middleware mount, so injection is the
654
+ # same shape as Go/Node: one visible, reversible block in Program.cs. The builder
655
+ # line is required only because ASP.NET Core does not expose the service collection
656
+ # after Build(), and EF Core DbContext discovery needs it.
657
+
658
+ _DOTNET_MARK_BEGIN = "// tokensafe:oumv:begin"
659
+ _DOTNET_MARK_END = "// tokensafe:oumv:end"
660
+ _DOTNET_PACKAGE = "TokenSafe.Oumv.AspNetCore"
661
+ _DOTNET_PACKAGE_VERSION = "0.1.0"
662
+
663
+
664
+ def _dotnet_web_project(workspace: str) -> Optional[str]:
665
+ """Finds a web csproj (Microsoft.NET.Sdk.Web or the ASP.NET Core framework reference)."""
666
+ for root, dirs, files in os.walk(workspace):
667
+ dirs[:] = [d for d in dirs if d not in ("bin", "obj", "node_modules", ".git", ".tokensafe")]
668
+ for name in files:
669
+ if not name.endswith(".csproj"):
670
+ continue
671
+ path = os.path.join(root, name)
672
+ try:
673
+ with open(path, "r", encoding="utf-8") as handle:
674
+ content = handle.read()
675
+ except OSError:
676
+ continue
677
+ if "Microsoft.NET.Sdk.Web" in content or "Microsoft.AspNetCore.App" in content:
678
+ return path
679
+ return None
680
+
681
+
682
+ def _find_dotnet_entrypoint(workspace: str, project: Optional[str] = None) -> Optional[str]:
683
+ """Program.cs next to the web project (top-level statements), if present."""
684
+ if project:
685
+ candidate = os.path.join(os.path.dirname(project), "Program.cs")
686
+ if os.path.isfile(candidate):
687
+ return candidate
688
+ candidate = os.path.join(workspace, "Program.cs")
689
+ return candidate if os.path.isfile(candidate) else None
690
+
691
+
692
+ def dotnet_patch_state(workspace: str) -> Dict[str, Any]:
693
+ """Reports whether the OUMV mount is already present in Program.cs."""
694
+ project = _dotnet_web_project(workspace)
695
+ entrypoint = _find_dotnet_entrypoint(workspace, project)
696
+ if not entrypoint:
697
+ return {"entrypoint": None, "patched": False, "project": project}
698
+ try:
699
+ with open(entrypoint, "r", encoding="utf-8") as handle:
700
+ source = handle.read()
701
+ except OSError:
702
+ return {"entrypoint": os.path.relpath(entrypoint, workspace), "patched": False, "project": project}
703
+ return {
704
+ "entrypoint": os.path.relpath(entrypoint, workspace),
705
+ "patched": _DOTNET_MARK_BEGIN in source and _DOTNET_MARK_END in source,
706
+ "project": os.path.relpath(project, workspace) if project else None,
707
+ }
708
+
709
+
710
+ def _dotnet_build(project: str) -> Tuple[bool, str]:
711
+ try:
712
+ result = subprocess.run(
713
+ ["dotnet", "build", project, "-c", "Release", "--nologo", "-v", "quiet"],
714
+ capture_output=True,
715
+ text=True,
716
+ timeout=600,
717
+ )
718
+ return result.returncode == 0, (result.stdout + result.stderr)[-1500:]
719
+ except FileNotFoundError:
720
+ return False, "dotnet SDK not found on PATH"
721
+ except subprocess.TimeoutExpired:
722
+ return False, "dotnet build timed out"
723
+
724
+
725
+ def _ensure_dotnet_dependency(project: str) -> Optional[str]:
726
+ """Adds the NuGet package once; returns a note when the CLI could not do it."""
727
+ try:
728
+ with open(project, "r", encoding="utf-8") as handle:
729
+ content = handle.read()
730
+ except OSError:
731
+ return f"could not read {project}"
732
+ if _DOTNET_PACKAGE in content:
733
+ return None
734
+ try:
735
+ result = subprocess.run(
736
+ ["dotnet", "add", project, "package", _DOTNET_PACKAGE, "--version", _DOTNET_PACKAGE_VERSION],
737
+ capture_output=True,
738
+ text=True,
739
+ timeout=300,
740
+ )
741
+ except FileNotFoundError:
742
+ return f"dotnet SDK not found; add <PackageReference Include=\"{_DOTNET_PACKAGE}\" Version=\"{_DOTNET_PACKAGE_VERSION}\" /> manually"
743
+ except subprocess.TimeoutExpired:
744
+ return "dotnet add package timed out"
745
+ if result.returncode != 0:
746
+ return f"dotnet add package failed; add the PackageReference manually: {(result.stdout + result.stderr)[-300:]}"
747
+ return None
748
+
749
+
750
+ def apply_dotnet_patch(workspace: str, dry_run: bool = False) -> Dict[str, Any]:
751
+ """Inserts `using`, `AddTokensafe()` and `UseTokensafe()` between tokensafe markers."""
752
+ project = _dotnet_web_project(workspace)
753
+ if not project:
754
+ return {"status": "skipped", "reason": "no ASP.NET Core (Microsoft.NET.Sdk.Web) project found"}
755
+ entrypoint = _find_dotnet_entrypoint(workspace, project)
756
+ if not entrypoint:
757
+ return {"status": "skipped", "reason": "no Program.cs next to the web project"}
758
+
759
+ with open(entrypoint, "r", encoding="utf-8") as handle:
760
+ source = handle.read()
761
+ if _DOTNET_MARK_BEGIN in source:
762
+ return {"status": "already_patched", "entrypoint": os.path.relpath(entrypoint, workspace)}
763
+
764
+ builder = re.search(
765
+ r"(?m)^(?P<indent>[ \t]*)(?:var|WebApplicationBuilder)\s+(?P<builder>\w+)\s*=\s*WebApplication\.CreateBuilder\(",
766
+ source,
767
+ )
768
+ app = re.search(
769
+ r"(?m)^(?P<indent>[ \t]*)(?:var|WebApplication)\s+(?P<app>\w+)\s*=\s*(?P<builder>\w+)\.Build\(\)\s*;",
770
+ source,
771
+ )
772
+ if not builder or not app:
773
+ return {
774
+ "status": "skipped",
775
+ "reason": "could not find `WebApplication.CreateBuilder(...)` and `builder.Build()` in Program.cs",
776
+ }
777
+ if builder.group("builder") != app.group("builder"):
778
+ return {"status": "skipped", "reason": "Program.cs builds the app from a different builder variable"}
779
+
780
+ def insertion(line_match: "re.Match[str]", body: str) -> Tuple[int, str]:
781
+ line_end = source.find("\n", line_match.end())
782
+ insert_at = len(source) if line_end < 0 else line_end + 1
783
+ indent = line_match.group("indent")
784
+ block = f"{_DOTNET_MARK_BEGIN}\n{indent}{body}\n{_DOTNET_MARK_END}\n"
785
+ return insert_at, block
786
+
787
+ services_at, services_block = insertion(
788
+ builder, f"{builder.group('builder')}.Services.AddTokensafe();"
789
+ )
790
+ mount_at, mount_block = insertion(app, f"{app.group('app')}.UseTokensafe();")
791
+
792
+ using_block = ""
793
+ if not re.search(r"(?m)^\s*using\s+TokenSafe\.Oumv\s*;", source):
794
+ using_lines = list(re.finditer(r"(?m)^using\s+[^;]+;\s*$", source))
795
+ using_block = f"{_DOTNET_MARK_BEGIN}\nusing TokenSafe.Oumv;\n{_DOTNET_MARK_END}\n"
796
+ if using_lines:
797
+ last = using_lines[-1]
798
+ line_end = source.find("\n", last.end())
799
+ using_at = len(source) if line_end < 0 else line_end + 1
800
+ else:
801
+ using_at = 0
802
+
803
+ patched = source
804
+ # Insert from the bottom up so earlier offsets stay valid.
805
+ for position, block in sorted(((services_at, services_block), (mount_at, mount_block)), reverse=True):
806
+ patched = patched[:position] + block + patched[position:]
807
+ if using_block:
808
+ patched = patched[:using_at] + using_block + patched[using_at:]
809
+
810
+ if dry_run:
811
+ return {
812
+ "status": "dry_run",
813
+ "entrypoint": os.path.relpath(entrypoint, workspace),
814
+ "preview": f"{builder.group('builder')}.Services.AddTokensafe();\n{app.group('app')}.UseTokensafe();",
815
+ }
816
+
817
+ backup_dir = _inject_dir(workspace)
818
+ os.makedirs(backup_dir, exist_ok=True)
819
+ backup_path = os.path.join(backup_dir, os.path.relpath(entrypoint, workspace).replace(os.sep, "__") + ".bak")
820
+ shutil.copy2(entrypoint, backup_path)
821
+ with open(entrypoint, "w", encoding="utf-8") as handle:
822
+ handle.write(patched)
823
+
824
+ dependency_note = _ensure_dotnet_dependency(project)
825
+ build_ok, build_output = _dotnet_build(project) if dependency_note is None else (False, "skipped")
826
+ if not build_ok:
827
+ shutil.copy2(backup_path, entrypoint)
828
+ os.unlink(backup_path)
829
+ return {
830
+ "status": "reverted",
831
+ "entrypoint": os.path.relpath(entrypoint, workspace),
832
+ "reason": dependency_note or "dotnet build failed",
833
+ "build": build_output[-800:],
834
+ }
835
+
836
+ with open(os.path.join(backup_dir, "manifest.json"), "w", encoding="utf-8") as handle:
837
+ json.dump(
838
+ {"entrypoint": entrypoint, "backup": backup_path, "framework": "aspnetcore", "mode": "dotnet_mount"},
839
+ handle,
840
+ indent=2,
841
+ )
842
+ return {
843
+ "status": "patched",
844
+ "entrypoint": os.path.relpath(entrypoint, workspace),
845
+ "framework": "aspnetcore",
846
+ "mode": "dotnet_mount",
847
+ "backup": backup_path,
848
+ "line": f"{app.group('app')}.UseTokensafe();",
849
+ "dependency": f"{_DOTNET_PACKAGE}@{_DOTNET_PACKAGE_VERSION}",
850
+ }
851
+
852
+
853
+ def revert_dotnet_patch(workspace: str) -> Dict[str, Any]:
854
+ manifest_path = os.path.join(_inject_dir(workspace), "manifest.json")
855
+ if not os.path.isfile(manifest_path):
856
+ return {"status": "clean", "reason": "no .NET patch manifest"}
857
+ try:
858
+ with open(manifest_path, "r", encoding="utf-8") as handle:
859
+ manifest = json.load(handle)
860
+ except Exception as exc:
861
+ return {"status": "error", "reason": f"cannot read manifest: {exc}"}
862
+ if manifest.get("mode") != "dotnet_mount":
863
+ return {"status": "clean", "reason": "manifest is not a .NET patch"}
864
+ entrypoint = manifest.get("entrypoint")
865
+ backup = manifest.get("backup")
866
+ if not (entrypoint and backup and os.path.isfile(backup)):
867
+ return {"status": "error", "reason": "backup missing; restore manually"}
868
+ shutil.copy2(backup, entrypoint)
869
+ os.unlink(manifest_path)
870
+ return {"status": "reverted", "entrypoint": os.path.relpath(entrypoint, workspace)}
871
+
872
+
651
873
  # Pinned to the backend release: the sidecars are single files, so the cache is
652
874
  # content-addressed by SHA-256 and a clean machine downloads the exact bytes the
653
875
  # release was certified from. Bump both the tag and the hashes together.
@@ -784,6 +1006,7 @@ def plan(workspace: str) -> Dict[str, Any]:
784
1006
  "node": "backend/node",
785
1007
  "spring": "backend/spring",
786
1008
  "php": "backend/php",
1009
+ "dotnet": "backend/aspnetcore",
787
1010
  }.get(provider, "backend/go")
788
1011
  entry = catalog.get(entry_id, {})
789
1012
  install = entry.get("technology", {}).get("package", {}).get("install")
@@ -821,6 +1044,20 @@ def plan(workspace: str) -> Dict[str, Any]:
821
1044
  "description": "one mountTokensafe(app)/registerTokensafe(app) line between tokensafe markers; byte-exact backup + --revert",
822
1045
  "install": install or "npm install tokensafe-backend-node",
823
1046
  })
1047
+ elif provider == "dotnet":
1048
+ state = dotnet_patch_state(workspace)
1049
+ actions.append({
1050
+ "kind": "dotnet_one_line_patch",
1051
+ "profile": "backend",
1052
+ "framework": "aspnetcore",
1053
+ "writes_repo": True,
1054
+ "already_patched": state["patched"],
1055
+ "entrypoint": state["entrypoint"],
1056
+ "project": state.get("project"),
1057
+ "description": "one AddTokensafe()/UseTokensafe() pair between tokensafe markers; byte-exact backup + --revert",
1058
+ "install": install or f"dotnet add package {_DOTNET_PACKAGE}",
1059
+ "run": "dotnet run",
1060
+ })
824
1061
  elif provider in ("spring", "php"):
825
1062
  sidecar_path, note = ensure_sidecar(provider)
826
1063
  command = sidecar_run_command(provider, sidecar_path or "", workspace)
@@ -884,6 +1121,8 @@ def apply(workspace: str, dry_run: bool = False, include_go: bool = True) -> Dic
884
1121
  results["actions"].append({"kind": "go_one_line_patch", **apply_go_patch(workspace, dry_run=dry_run)})
885
1122
  elif backend.get("provider") == "node":
886
1123
  results["actions"].append({"kind": "node_one_line_patch", **apply_node_patch(workspace, dry_run=dry_run)})
1124
+ elif backend.get("provider") == "dotnet":
1125
+ results["actions"].append({"kind": "dotnet_one_line_patch", **apply_dotnet_patch(workspace, dry_run=dry_run)})
887
1126
  elif backend.get("provider") in ("spring", "php"):
888
1127
  sidecar_path, note = ensure_sidecar(backend["provider"])
889
1128
  results["actions"].append({
@@ -902,4 +1141,5 @@ def revert(workspace: str) -> Dict[str, Any]:
902
1141
  "workspace": workspace,
903
1142
  "go": revert_go_patch(workspace),
904
1143
  "node": revert_node_patch(workspace),
1144
+ "dotnet": revert_dotnet_patch(workspace),
905
1145
  }
package/src/mcp_server.py CHANGED
@@ -44,7 +44,7 @@ from src.session_context import current_root, current_session_id
44
44
 
45
45
  SERVER_INFO = {
46
46
  "name": "tokensafe-mcp",
47
- "version": "4.7.8"
47
+ "version": "4.7.9"
48
48
  }
49
49
 
50
50
  # MCP client attribution: the initialize handshake carries clientInfo, which
package/src/retrofit.py CHANGED
@@ -4,9 +4,11 @@ Enables existing frontend and backend projects to adopt the OUMV protocol
4
4
  incrementally without migrating frameworks or restructuring codebases.
5
5
  """
6
6
 
7
+ import glob
7
8
  import os
8
9
  import json
9
10
  import time
11
+ from pathlib import Path
10
12
  from typing import Dict, Any, List, Optional, Tuple
11
13
 
12
14
  # Top-level directories that hold frontend source in a repo-root app (as opposed to
@@ -310,6 +312,44 @@ def detect_project_stack(workspace_dir: str) -> Dict[str, Any]:
310
312
  })
311
313
  break
312
314
 
315
+ # ASP.NET Core detection: Microsoft.NET.Sdk.Web or the ASP.NET Core
316
+ # framework reference in a csproj.
317
+ for csproj in sorted(glob.glob(os.path.join(target_dir, "**", "*.csproj"), recursive=True)):
318
+ if any(part in ("bin", "obj", "node_modules") for part in Path(csproj).parts):
319
+ continue
320
+ try:
321
+ with open(csproj, "r", encoding="utf-8", errors="replace") as f:
322
+ csproj_content = f.read()
323
+ except Exception:
324
+ continue
325
+ if "Microsoft.NET.Sdk.Web" not in csproj_content and "Microsoft.AspNetCore.App" not in csproj_content:
326
+ continue
327
+ rel_csproj = os.path.relpath(csproj, workspace_dir)
328
+ _add_detected(rel_csproj)
329
+ if "nuget/dotnet" not in stack["package_managers"]:
330
+ stack["package_managers"].append("nuget/dotnet")
331
+ dotnet_entry = {
332
+ "framework": "aspnetcore",
333
+ "provider": "dotnet",
334
+ "adapter": "tokensafe-backend/dotnet",
335
+ "language": "csharp",
336
+ "root": os.path.dirname(rel_csproj) or ".",
337
+ "oumv_supported": True,
338
+ "status": "ready",
339
+ }
340
+ if not stack["backend"] or not stack["backend"].get("oumv_supported", False):
341
+ stack["backend"] = dotnet_entry
342
+ _add_package({
343
+ "role": "backend",
344
+ "path": dotnet_entry["root"],
345
+ "framework": "aspnetcore",
346
+ "provider": "dotnet",
347
+ "adapter": "tokensafe-backend/dotnet",
348
+ "oumvSupported": True,
349
+ "status": "ready",
350
+ })
351
+ break
352
+
313
353
  composer_path = os.path.join(target_dir, "composer.json")
314
354
  if os.path.isfile(composer_path):
315
355
  try:
@@ -585,6 +625,32 @@ def get_adapters_catalog() -> List[Dict[str, Any]]:
585
625
  {"name": "verify.behavior", "constraints": {"readOnly": True, "developmentOnly": True}},
586
626
  ],
587
627
  },
628
+ {
629
+ "id": "backend/aspnetcore",
630
+ "name": "ASP.NET Core Adapter (minimal APIs, MVC controllers, EF Core)",
631
+ "profile": "backend",
632
+ "profiles": ["backend"],
633
+ "repo": "tokensafe-backend/dotnet",
634
+ "mode": "hybrid",
635
+ "status": "ready",
636
+ "description": "In-process endpoint dispatch for minimal APIs and controllers, Roslyn syntax pre-flight, and verify.sandboxRollback that rolls every auto-discovered EF Core DbContext back",
637
+ "technology": {
638
+ "language": "csharp",
639
+ "framework": "aspnetcore",
640
+ "package": {
641
+ "manager": "nuget",
642
+ "name": "TokenSafe.Oumv.AspNetCore",
643
+ "install": "dotnet add package TokenSafe.Oumv.AspNetCore",
644
+ },
645
+ },
646
+ "capabilities": [
647
+ {"name": "observe.resources", "constraints": {"readOnly": True, "developmentOnly": False}},
648
+ {"name": "observe.runtime_state", "constraints": {"readOnly": True, "developmentOnly": False}},
649
+ {"name": "understand.causality", "constraints": {"readOnly": True, "developmentOnly": False, "limitations": ["requires observed request traces (UseTokensafe middleware or oumv/verify)"]}},
650
+ {"name": "mutate.source", "constraints": {"readOnly": False, "developmentOnly": False, "requiresPermission": "permissions.mutate != false"}},
651
+ {"name": "verify.runtime_behavior", "constraints": {"readOnly": True, "developmentOnly": False}},
652
+ ],
653
+ },
588
654
  {
589
655
  "id": "backend/spring",
590
656
  "name": "Spring Boot Adapter (JDK-only sidecar)",
@@ -311,7 +311,7 @@ class TelemetrySync:
311
311
  current_last_id = last_id
312
312
  headers = {
313
313
  "Content-Type": "application/json",
314
- "User-Agent": "TokenSafe-Sync/4.7.8"
314
+ "User-Agent": "TokenSafe-Sync/4.7.9"
315
315
  }
316
316
  if active_key:
317
317
  headers["Authorization"] = f"Bearer {active_key}"
@@ -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.7.8"
20
+ CURRENT_VERSION = "4.7.9"
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