tokensafe 4.7.6 → 4.7.8

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.6",
2
+ "version": "4.7.8",
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.6",
3
+ "version": "4.7.8",
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.6",
4
+ "version": "4.7.8",
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.6",
4
+ "version": "4.7.8",
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.6",
6
+ "version": "4.7.8",
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.6",
26
+ "version": "4.7.8",
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.6",
42
+ "version": "4.7.8",
43
43
  "runtimeHint": "uvx",
44
44
  "transport": {
45
45
  "type": "stdio"
@@ -233,7 +233,17 @@ def go_patch_state(workspace: str) -> Dict[str, Any]:
233
233
 
234
234
 
235
235
  _GO_MODULE = "github.com/tokensafe-dev/tokensafe-backend/go"
236
- _GO_MODULE_VERSION = "v0.4.3"
236
+ # Keep in step with the backend release tag (go/vX.Y.Z): injection must never
237
+ # downgrade an adapter that is already newer than this pin.
238
+ _GO_MODULE_VERSION = "v0.7.0"
239
+
240
+
241
+ def _version_tuple(tag: str):
242
+ """`v1.2.3` -> (1, 2, 3); raises ValueError when the tag is not semver."""
243
+ parts = tag.lstrip("v").split(".")
244
+ if len(parts) < 2:
245
+ raise ValueError(tag)
246
+ return tuple(int(part) for part in parts[:3] + ["0"] * (3 - len(parts[:3])))
237
247
 
238
248
 
239
249
  def _ensure_go_dependency(workspace: str) -> Optional[str]:
@@ -247,10 +257,10 @@ def _ensure_go_dependency(workspace: str) -> Optional[str]:
247
257
  except OSError as exc:
248
258
  return f"cannot read go.mod: {exc}"
249
259
 
250
- # Skip only when the pinned version is already required; an older requirement
251
- # would build against an adapter that lacks AutoMount.
260
+ # Never downgrade: a project already on a newer go/v* tag keeps it, and an
261
+ # older requirement is raised to the pin.
252
262
  match = re.search(re.escape(_GO_MODULE) + r"\s+v([0-9][\w.+-]*)", content)
253
- if match and f"v{match.group(1)}" == _GO_MODULE_VERSION:
263
+ if match and _version_tuple(f"v{match.group(1)}") >= _version_tuple(_GO_MODULE_VERSION):
254
264
  return None
255
265
 
256
266
  go_bin = shutil.which("go")
@@ -502,6 +512,251 @@ def revert_go_patch(workspace: str) -> Dict[str, Any]:
502
512
  # Plan / apply / revert for the CLI and the first-prompt hook
503
513
  # --------------------------------------------------------------------------- #
504
514
 
515
+ def _find_node_entrypoint(workspace: str) -> Optional[str]:
516
+ """Finds the Node entry file that creates the framework app."""
517
+ candidates: List[str] = []
518
+ pkg_path = os.path.join(workspace, "package.json")
519
+ try:
520
+ with open(pkg_path, "r", encoding="utf-8") as f:
521
+ pkg = json.load(f)
522
+ main = pkg.get("main")
523
+ if isinstance(main, str) and main:
524
+ candidates.append(main)
525
+ except Exception:
526
+ pass
527
+ candidates += ["src/index.js", "src/server.js", "src/app.js", "index.js", "server.js", "app.js"]
528
+ for rel in candidates:
529
+ path = os.path.join(workspace, rel)
530
+ if os.path.isfile(path):
531
+ return path
532
+ return None
533
+
534
+
535
+ def _node_framework_of(workspace: str) -> Optional[str]:
536
+ try:
537
+ with open(os.path.join(workspace, "package.json"), "r", encoding="utf-8") as f:
538
+ pkg = json.load(f)
539
+ deps = {**(pkg.get("dependencies") or {}), **(pkg.get("devDependencies") or {})}
540
+ except Exception:
541
+ return None
542
+ if "fastify" in deps:
543
+ return "fastify"
544
+ if "express" in deps:
545
+ return "express"
546
+ return None
547
+
548
+
549
+ def node_patch_state(workspace: str) -> Dict[str, Any]:
550
+ """Reports whether the one-line OUMV mount is already in the Node entrypoint."""
551
+ path = _find_node_entrypoint(workspace)
552
+ if not path:
553
+ return {"entrypoint": None, "patched": False, "framework": _node_framework_of(workspace)}
554
+ try:
555
+ with open(path, "r", encoding="utf-8") as f:
556
+ source = f.read()
557
+ except OSError:
558
+ return {"entrypoint": path, "patched": False, "framework": _node_framework_of(workspace)}
559
+ return {
560
+ "entrypoint": os.path.relpath(path, workspace),
561
+ "patched": _MARK_BEGIN in source and _MARK_END in source,
562
+ "framework": _node_framework_of(workspace),
563
+ }
564
+
565
+
566
+ def apply_node_patch(workspace: str, dry_run: bool = False) -> Dict[str, Any]:
567
+ """Inserts one mount line between tokensafe markers, with a byte-exact backup."""
568
+ framework = _node_framework_of(workspace)
569
+ path = _find_node_entrypoint(workspace)
570
+ if framework not in ("express", "fastify"):
571
+ return {"status": "skipped", "reason": "no supported Node framework (express/fastify) found"}
572
+ if not path:
573
+ return {"status": "skipped", "reason": "no Node entrypoint found"}
574
+
575
+ with open(path, "r", encoding="utf-8") as f:
576
+ source = f.read()
577
+ if _MARK_BEGIN in source:
578
+ return {"status": "already_patched", "entrypoint": os.path.relpath(path, workspace)}
579
+
580
+ if framework == "express":
581
+ pattern = re.compile(r"(?m)^(?P<indent>[ \t]*)(?:const|let|var)\s+\w+\s*=\s*express\(\)[ \t]*;?[ \t]*$")
582
+ mount = (
583
+ f"{_MARK_BEGIN}\n"
584
+ "require('tokensafe-backend-node').mountTokensafe(app);\n"
585
+ f"{_MARK_END}\n"
586
+ )
587
+ else:
588
+ pattern = re.compile(r"(?m)^(?P<indent>[ \t]*)(?:const|let|var)\s+(?P<var>\w+)\s*=\s*(?:Fastify|fastify)\([^)]*\)[ \t]*;?[ \t]*$")
589
+ mount = (
590
+ f"{_MARK_BEGIN}\n"
591
+ "void require('tokensafe-backend-node').registerTokensafe(app);\n"
592
+ f"{_MARK_END}\n"
593
+ )
594
+
595
+ found = pattern.search(source)
596
+ if not found:
597
+ return {
598
+ "status": "skipped",
599
+ "reason": f"could not find `{framework}(...)` assignment in {os.path.relpath(path, workspace)}",
600
+ }
601
+
602
+ line_end = source.find("\n", found.end())
603
+ insert_at = len(source) if line_end < 0 else line_end + 1
604
+ patched = source[:insert_at] + mount + source[insert_at:]
605
+
606
+ if dry_run:
607
+ return {"status": "dry_run", "entrypoint": os.path.relpath(path, workspace), "preview": mount.strip()}
608
+
609
+ backup_dir = _inject_dir(workspace)
610
+ os.makedirs(backup_dir, exist_ok=True)
611
+ backup_path = os.path.join(backup_dir, os.path.relpath(path, workspace).replace(os.sep, "__") + ".bak")
612
+ shutil.copy2(path, backup_path)
613
+ with open(path, "w", encoding="utf-8") as f:
614
+ f.write(patched)
615
+ with open(os.path.join(backup_dir, "manifest.json"), "w", encoding="utf-8") as f:
616
+ json.dump({"entrypoint": path, "backup": backup_path, "framework": framework, "mode": "node_mount"}, f, indent=2)
617
+ return {
618
+ "status": "patched",
619
+ "entrypoint": os.path.relpath(path, workspace),
620
+ "framework": framework,
621
+ "mode": "node_mount",
622
+ "backup": backup_path,
623
+ "line": mount.splitlines()[1],
624
+ }
625
+
626
+
627
+ def revert_node_patch(workspace: str) -> Dict[str, Any]:
628
+ manifest_path = os.path.join(_inject_dir(workspace), "manifest.json")
629
+ if not os.path.isfile(manifest_path):
630
+ return {"status": "clean", "reason": "no Node patch manifest"}
631
+ try:
632
+ with open(manifest_path, "r", encoding="utf-8") as f:
633
+ manifest = json.load(f)
634
+ except Exception as exc:
635
+ return {"status": "error", "reason": f"cannot read manifest: {exc}"}
636
+ if manifest.get("mode") != "node_mount":
637
+ return {"status": "clean", "reason": "manifest is not a Node patch"}
638
+ entrypoint = manifest.get("entrypoint")
639
+ backup = manifest.get("backup")
640
+ if not (entrypoint and backup and os.path.isfile(backup)):
641
+ return {"status": "error", "reason": "backup missing; restore manually"}
642
+ shutil.copy2(backup, entrypoint)
643
+ os.unlink(manifest_path)
644
+ return {"status": "reverted", "entrypoint": os.path.relpath(entrypoint, workspace)}
645
+
646
+
647
+ def _sidecar_cache_dir() -> str:
648
+ return os.path.join(_tokensafe_home(), "sidecars")
649
+
650
+
651
+ # Pinned to the backend release: the sidecars are single files, so the cache is
652
+ # content-addressed by SHA-256 and a clean machine downloads the exact bytes the
653
+ # release was certified from. Bump both the tag and the hashes together.
654
+ _SIDECAR_RELEASE_TAG = "v0.7.0"
655
+ _SIDECARS = {
656
+ "spring": (
657
+ "java/src/dev/tokensafe/oumv/OumvSpring.java",
658
+ "OumvSpring.java",
659
+ "b6dda1ecf9638bbcb867310139d9dce1421d0f9f43e6db490ddf2e327637d949",
660
+ ),
661
+ "php": (
662
+ "php/bin/oumv-php",
663
+ "oumv-php",
664
+ "31955f8bd2735a47ef70edae05f978436d70f326da38043bc11248100761ed12",
665
+ ),
666
+ }
667
+
668
+
669
+ def _sha256_file(path: str) -> str:
670
+ digest = hashlib.sha256()
671
+ with open(path, "rb") as handle:
672
+ for chunk in iter(lambda: handle.read(65536), b""):
673
+ digest.update(chunk)
674
+ return digest.hexdigest()
675
+
676
+
677
+ def sidecar_run_command(kind: str, sidecar_path: str, workspace: str) -> Optional[str]:
678
+ """The exact command that starts the sidecar against `workspace`."""
679
+ if not sidecar_path:
680
+ return None
681
+ if kind == "spring":
682
+ return f"tokensafe run-backend java {sidecar_path} --root {workspace} --port 7331"
683
+ if kind == "php":
684
+ return f"tokensafe run-backend php -S 127.0.0.1:7332 {sidecar_path} --root {workspace}"
685
+ return None
686
+
687
+
688
+ def ensure_sidecar(kind: str) -> Tuple[Optional[str], str]:
689
+ """Caches OumvSpring.java / oumv-php at the pinned release and verifies SHA-256.
690
+
691
+ Order: a valid cache → a local checkout whose bytes match the pin (developer
692
+ flow, no network) → download from the release tag. A hash mismatch is never
693
+ accepted silently; the note says what failed instead of handing back a
694
+ different file under the certified name.
695
+ """
696
+ if kind not in _SIDECARS:
697
+ return None, f"unknown sidecar {kind!r}"
698
+ rel_source, filename, expected_sha = _SIDECARS[kind]
699
+ cache_dir = _sidecar_cache_dir()
700
+ target = os.path.join(cache_dir, filename)
701
+
702
+ def adopt(source: str, note: str) -> Tuple[str, str]:
703
+ os.makedirs(cache_dir, exist_ok=True)
704
+ shutil.copy2(source, target)
705
+ if kind == "php":
706
+ os.chmod(target, 0o755)
707
+ return target, note
708
+
709
+ if os.path.isfile(target) and _sha256_file(target) == expected_sha:
710
+ return target, f"cached at {_SIDECAR_RELEASE_TAG}"
711
+
712
+ repo_candidates = []
713
+ env_repo = os.environ.get("OUMV_BACKEND_REPO")
714
+ if env_repo:
715
+ repo_candidates.append(env_repo)
716
+ here = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
717
+ repo_candidates += [
718
+ os.path.join(os.path.dirname(here), "tokensafe-backend"),
719
+ os.path.join(here, "..", "tokensafe-backend"),
720
+ ]
721
+ local_mismatch = None
722
+ for repo in repo_candidates:
723
+ candidate = os.path.join(os.path.abspath(repo), rel_source)
724
+ if not os.path.isfile(candidate):
725
+ continue
726
+ if _sha256_file(candidate) == expected_sha:
727
+ return adopt(candidate, f"cached from local checkout matching {_SIDECAR_RELEASE_TAG}")
728
+ local_mismatch = candidate
729
+
730
+ if os.environ.get("TOKENSAFE_SIDECAR_OFFLINE") == "1":
731
+ if local_mismatch:
732
+ return adopt(local_mismatch, f"local checkout (unpinned, offline): {local_mismatch}")
733
+ return None, "offline (TOKENSAFE_SIDECAR_OFFLINE=1) and no cached sidecar"
734
+
735
+ url = (
736
+ f"https://raw.githubusercontent.com/tokensafe-dev/tokensafe-backend/"
737
+ f"{_SIDECAR_RELEASE_TAG}/{rel_source}"
738
+ )
739
+ try:
740
+ import urllib.request
741
+
742
+ with urllib.request.urlopen(url, timeout=30) as response:
743
+ payload = response.read()
744
+ except Exception as exc:
745
+ if local_mismatch:
746
+ return adopt(local_mismatch, f"download failed ({exc}); local checkout (unpinned): {local_mismatch}")
747
+ return None, f"cannot download {url}: {exc}"
748
+
749
+ actual = hashlib.sha256(payload).hexdigest()
750
+ if actual != expected_sha:
751
+ return None, f"sha256 mismatch for {url}: expected {expected_sha}, got {actual}"
752
+ os.makedirs(cache_dir, exist_ok=True)
753
+ with open(target, "wb") as handle:
754
+ handle.write(payload)
755
+ if kind == "php":
756
+ os.chmod(target, 0o755)
757
+ return target, f"downloaded from {_SIDECAR_RELEASE_TAG}"
758
+
759
+
505
760
  def plan(workspace: str) -> Dict[str, Any]:
506
761
  """Describes what apply would do, without touching anything."""
507
762
  stack = detect_project_stack(workspace)
@@ -523,8 +778,15 @@ def plan(workspace: str) -> Dict[str, Any]:
523
778
  backend = stack.get("backend")
524
779
  if backend:
525
780
  provider = backend.get("provider")
526
- entry_id = "backend/fastapi" if provider == "fastapi" else "backend/go"
781
+ entry_id = {
782
+ "fastapi": "backend/fastapi",
783
+ "go": "backend/go",
784
+ "node": "backend/node",
785
+ "spring": "backend/spring",
786
+ "php": "backend/php",
787
+ }.get(provider, "backend/go")
527
788
  entry = catalog.get(entry_id, {})
789
+ install = entry.get("technology", {}).get("package", {}).get("install")
528
790
  if provider == "fastapi":
529
791
  actions.append({
530
792
  "kind": "python_autoload",
@@ -532,7 +794,7 @@ def plan(workspace: str) -> Dict[str, Any]:
532
794
  "framework": "fastapi",
533
795
  "writes_repo": False,
534
796
  "description": "sitecustomize patches uvicorn; mount_tokensafe(app) runs on import",
535
- "install": entry.get("technology", {}).get("package", {}).get("install", 'pip install "tokensafe-backend-python @ git+https://github.com/tokensafe-dev/tokensafe-backend.git#subdirectory=python"'),
797
+ "install": install or 'pip install "tokensafe-backend-python @ git+https://github.com/tokensafe-dev/tokensafe-backend.git#subdirectory=python"',
536
798
  "run": python_run_hint(workspace),
537
799
  })
538
800
  elif provider == "go":
@@ -545,7 +807,32 @@ def plan(workspace: str) -> Dict[str, Any]:
545
807
  "already_patched": state["patched"],
546
808
  "entrypoint": state["entrypoint"],
547
809
  "description": "one AutoMount() line between tokensafe markers; byte-exact backup + --revert",
548
- "install": entry.get("technology", {}).get("package", {}).get("install"),
810
+ "install": install,
811
+ })
812
+ elif provider == "node":
813
+ state = node_patch_state(workspace)
814
+ actions.append({
815
+ "kind": "node_one_line_patch",
816
+ "profile": "backend",
817
+ "framework": state.get("framework") or backend.get("framework"),
818
+ "writes_repo": True,
819
+ "already_patched": state["patched"],
820
+ "entrypoint": state["entrypoint"],
821
+ "description": "one mountTokensafe(app)/registerTokensafe(app) line between tokensafe markers; byte-exact backup + --revert",
822
+ "install": install or "npm install tokensafe-backend-node",
823
+ })
824
+ elif provider in ("spring", "php"):
825
+ sidecar_path, note = ensure_sidecar(provider)
826
+ command = sidecar_run_command(provider, sidecar_path or "", workspace)
827
+ actions.append({
828
+ "kind": "sidecar",
829
+ "profile": "backend",
830
+ "framework": backend.get("framework", provider),
831
+ "writes_repo": False,
832
+ "sidecar": sidecar_path,
833
+ "install": note,
834
+ "run": command,
835
+ "description": "static route scan + OCC edits + verify through the single-file sidecar; nothing is written into the project",
549
836
  })
550
837
  else:
551
838
  actions.append({
@@ -595,9 +882,24 @@ def apply(workspace: str, dry_run: bool = False, include_go: bool = True) -> Dic
595
882
 
596
883
  if backend.get("provider") == "go" and include_go:
597
884
  results["actions"].append({"kind": "go_one_line_patch", **apply_go_patch(workspace, dry_run=dry_run)})
885
+ elif backend.get("provider") == "node":
886
+ results["actions"].append({"kind": "node_one_line_patch", **apply_node_patch(workspace, dry_run=dry_run)})
887
+ elif backend.get("provider") in ("spring", "php"):
888
+ sidecar_path, note = ensure_sidecar(backend["provider"])
889
+ results["actions"].append({
890
+ "kind": "sidecar",
891
+ "status": "ready" if sidecar_path else "needs-source",
892
+ "sidecar": sidecar_path,
893
+ "note": note,
894
+ "run": sidecar_run_command(backend["provider"], sidecar_path or "", workspace),
895
+ })
598
896
 
599
897
  return results
600
898
 
601
899
 
602
900
  def revert(workspace: str) -> Dict[str, Any]:
603
- return {"workspace": workspace, "go": revert_go_patch(workspace)}
901
+ return {
902
+ "workspace": workspace,
903
+ "go": revert_go_patch(workspace),
904
+ "node": revert_node_patch(workspace),
905
+ }
package/src/cli.py CHANGED
@@ -752,21 +752,30 @@ def main(argv: Optional[List[str]] = None):
752
752
  print(f" ✔ Existing configuration preserved: \033[1m{conf_file}\033[0m (use --force to overwrite)\n")
753
753
 
754
754
  elif command in ("run-backend", "run_backend"):
755
- # Executes the user's dev-server command with the OUMV autoload hook active.
756
- # Nothing is written into the repository: the hook lives in ~/.tokensafe.
755
+ # Executes the user's dev-server command. Python/uvicorn gets the OUMV
756
+ # autoload hook from ~/.tokensafe; Java/PHP/Node sidecars run as-is (they
757
+ # mount the runtime themselves and write their own descriptor).
757
758
  from src.auto_inject import backend_env, ensure_python_autoload
758
759
 
759
760
  argv_rest = [a for a in args[1:]]
760
761
  if not argv_rest:
761
- print("usage: tokensafe run-backend <command...> e.g. tokensafe run-backend uvicorn app:app --reload")
762
+ print(
763
+ "usage: tokensafe run-backend <command...>\n"
764
+ " tokensafe run-backend uvicorn app:app --reload\n"
765
+ " tokensafe run-backend java OumvSpring.java --root . --port 7331\n"
766
+ " tokensafe run-backend php -S 127.0.0.1:7332 oumv-php --root ."
767
+ )
762
768
  return
763
- ensure_python_autoload()
764
- env = backend_env()
765
769
  tool = argv_rest[0]
766
770
  resolved = shutil.which(tool)
767
771
  if not resolved:
768
772
  print(f"tokensafe run-backend: `{tool}` not found on PATH")
769
773
  return
774
+ if os.path.basename(tool) in ("java", "php", "node", "npm", "npx"):
775
+ print(f"⚡ Launching {os.path.basename(tool)} with the Sextant runtime")
776
+ os.execvpe(resolved, argv_rest, dict(os.environ))
777
+ ensure_python_autoload()
778
+ env = backend_env()
770
779
  os.execvpe(resolved, argv_rest, env)
771
780
 
772
781
  elif command in ("inject", "wire"):
@@ -903,7 +912,7 @@ def main(argv: Optional[List[str]] = None):
903
912
  cmd, source = resolve_zero_footprint_vite_command(
904
913
  target_dir, port=port_val, host=host_val, open_browser=open_browser
905
914
  )
906
- print(f"⚡ Launching Zero-Footprint Vite+React OUMV server ({source})...")
915
+ print(f"⚡ Launching Zero-Footprint Vite OUMV server ({source})...")
907
916
  proc = subprocess.run(cmd, cwd=target_dir)
908
917
  sys.exit(proc.returncode)
909
918