tokensafe 2.5.1 → 2.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/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "tokensafe",
3
3
  "mcpName": "dev.tokensafe/tokensafe",
4
- "version": "2.5.1",
4
+ "version": "2.5.2",
5
5
  "description": "Reduce your AI bills by up to 99% locally. Your agents read only needed code, keep prompt caches intact across turns, and keep secrets out of git.",
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": "2.5.1",
4
+ "version": "2.5.2",
5
5
  "description": "Reduce your AI bills by up to 99% locally. Your agents read only needed code, keep prompt caches intact across turns, and keep secrets out of git.",
6
6
  "logo": "assets/logo.svg",
7
7
  "author": {
package/server.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "name": "dev.tokensafe/tokensafe",
4
4
  "title": "TokenSafe",
5
5
  "description": "Reduce your AI bills by up to 99% locally: focused code, warm prompt caches & zero secret leaks.",
6
- "version": "2.5.1",
6
+ "version": "2.5.2",
7
7
  "websiteUrl": "https://tokensafe.dev",
8
8
  "repository": {
9
9
  "url": "https://github.com/tokensafe-dev/tokensafe",
@@ -30,7 +30,7 @@
30
30
  "registryType": "npm",
31
31
  "registryBaseUrl": "https://registry.npmjs.org",
32
32
  "identifier": "tokensafe",
33
- "version": "2.5.1",
33
+ "version": "2.5.2",
34
34
  "runtimeHint": "npx",
35
35
  "transport": {
36
36
  "type": "stdio"
@@ -46,7 +46,7 @@
46
46
  "registryType": "pypi",
47
47
  "registryBaseUrl": "https://pypi.org",
48
48
  "identifier": "tokensafe",
49
- "version": "2.5.1",
49
+ "version": "2.5.2",
50
50
  "runtimeHint": "uvx",
51
51
  "transport": {
52
52
  "type": "stdio"
package/src/installer.py CHANGED
@@ -814,34 +814,109 @@ class AgentInstaller:
814
814
  return restarted
815
815
 
816
816
  @staticmethod
817
- def _find_npm(home: Optional[str] = None) -> Optional[str]:
818
- """Locates an npm executable even in a clean non-interactive environment.
817
+ def _semver_dir_key(name: str) -> Tuple[int, ...]:
818
+ """Parses a version directory name like 'v24.14.0' into a numeric sort key."""
819
+ parts = re.findall(r"\d+", name or "")
820
+ return tuple(int(p) for p in parts[:4]) if parts else (0,)
819
821
 
820
- The updater dialog runs via `do shell script` + login shell, where .zshrc
821
- (and therefore nvm) is never sourced; PATH-only discovery made the npm
822
- channel silently skip updates. Falls back to well-known locations."""
823
- found = shutil.which("npm")
824
- if found:
825
- return found
822
+ @staticmethod
823
+ def _npm_subprocess_env(npm_bin: str) -> Dict[str, str]:
824
+ """Builds an env where `#!/usr/bin/env node` resolves the sibling node binary.
825
+
826
+ Under `do shell script` + login shell, nvm's bin dir is missing from PATH
827
+ or shadowed by `/usr/local/bin`. Running `<nvm>/bin/npm` without its own
828
+ bin directory first on PATH causes `env node` to execute `/usr/local/bin/node`,
829
+ making npm look at `/usr/local/lib` instead of the nvm prefix.
830
+ """
831
+ env = os.environ.copy()
832
+ bin_dir = os.path.dirname(os.path.abspath(npm_bin))
833
+ if bin_dir:
834
+ current_path = env.get("PATH", "")
835
+ path_parts = [p for p in current_path.split(os.pathsep) if p]
836
+ if not path_parts or os.path.normpath(path_parts[0]) != os.path.normpath(bin_dir):
837
+ env["PATH"] = f"{bin_dir}{os.pathsep}{current_path}" if current_path else bin_dir
838
+ return env
839
+
840
+ @staticmethod
841
+ def _find_npm_candidates(home: Optional[str] = None) -> List[str]:
842
+ """Discovers all executable npm binaries across PATH, project prefix, nvm, fnm, volta, and system dirs."""
826
843
  base = home or HOME
827
- candidates: List[str] = []
844
+ raw_candidates: List[str] = []
845
+
846
+ # 1. If running out of an npm node_modules install, include its own bin/npm first.
847
+ if os.path.basename(os.path.dirname(PROJECT_ROOT)) == "node_modules":
848
+ nm_parent = os.path.dirname(os.path.dirname(PROJECT_ROOT))
849
+ if os.path.basename(nm_parent) == "lib":
850
+ prefix = os.path.dirname(nm_parent)
851
+ raw_candidates.append(os.path.join(prefix, "bin", "npm"))
852
+ else:
853
+ raw_candidates.append(os.path.join(nm_parent, "npm.cmd"))
854
+ raw_candidates.append(os.path.join(nm_parent, "bin", "npm"))
855
+
856
+ # 2. PATH-resolved npm (note: on macOS login shells this may be /usr/local/bin/npm
857
+ # shadowing nvm, so we must NOT stop after checking only this one).
858
+ for exe in ("npm", "npm.cmd"):
859
+ found = shutil.which(exe)
860
+ if found:
861
+ raw_candidates.append(found)
862
+
863
+ # 3. nvm Node installations (newest semver first).
828
864
  nvm_dir = os.path.join(base, ".nvm", "versions", "node")
829
865
  try:
830
866
  if os.path.isdir(nvm_dir):
831
- # Newest installed node version wins.
832
- for version_dir in sorted(os.listdir(nvm_dir), reverse=True):
833
- candidates.append(os.path.join(nvm_dir, version_dir, "bin", "npm"))
867
+ for version_dir in sorted(
868
+ os.listdir(nvm_dir),
869
+ key=AgentInstaller._semver_dir_key,
870
+ reverse=True,
871
+ ):
872
+ raw_candidates.append(os.path.join(nvm_dir, version_dir, "bin", "npm"))
834
873
  except OSError:
835
874
  pass
836
- candidates += [
875
+
876
+ # 4. Other popular Node version managers + system/Homebrew locations.
877
+ raw_candidates.append(os.path.join(base, ".volta", "bin", "npm"))
878
+ raw_candidates.append(os.path.join(base, ".nodenv", "shims", "npm"))
879
+ raw_candidates.append(os.path.join(base, ".fnm", "aliases", "default", "bin", "npm"))
880
+ fnm_versions = os.path.join(base, ".local", "share", "fnm", "node-versions")
881
+ try:
882
+ if os.path.isdir(fnm_versions):
883
+ for version_dir in sorted(
884
+ os.listdir(fnm_versions),
885
+ key=AgentInstaller._semver_dir_key,
886
+ reverse=True,
887
+ ):
888
+ raw_candidates.append(os.path.join(fnm_versions, version_dir, "installation", "bin", "npm"))
889
+ except OSError:
890
+ pass
891
+
892
+ raw_candidates += [
837
893
  "/opt/homebrew/bin/npm",
838
894
  "/usr/local/bin/npm",
839
895
  "/usr/bin/npm",
840
896
  ]
841
- for cand in candidates:
897
+
898
+ seen = set()
899
+ unique: List[str] = []
900
+ for cand in raw_candidates:
901
+ if not cand:
902
+ continue
903
+ norm = os.path.normpath(os.path.abspath(cand))
904
+ if norm in seen:
905
+ continue
842
906
  if os.path.isfile(cand) and os.access(cand, os.X_OK):
843
- return cand
844
- return None
907
+ seen.add(norm)
908
+ unique.append(cand)
909
+ return unique
910
+
911
+ @staticmethod
912
+ def _find_npm(home: Optional[str] = None) -> Optional[str]:
913
+ """Locates an npm executable even in a clean non-interactive environment.
914
+
915
+ The updater dialog runs via `do shell script` + login shell, where .zshrc
916
+ (and therefore nvm) is never sourced; PATH-only discovery made the npm
917
+ channel silently skip updates. Falls back to well-known locations."""
918
+ candidates = AgentInstaller._find_npm_candidates(home=home)
919
+ return candidates[0] if candidates else None
845
920
 
846
921
  @classmethod
847
922
  def self_update(cls):
@@ -867,26 +942,50 @@ class AgentInstaller:
867
942
  except Exception as e:
868
943
  print(f" {YELLOW}⚠{RESET} Git pull skipped: {e}")
869
944
 
870
- # 2. Check npm global
871
- # The updater dialog runs via `do shell script` + login shell, which skips
872
- # .zshrc — nvm is NOT on PATH there, so PATH-only discovery silently
873
- # downgraded the npm channel (the active one for many installs).
874
- npm_bin = cls._find_npm()
875
- if npm_bin:
876
- try:
877
- res = subprocess.run([npm_bin, "list", "-g", "--depth=0", "tokensafe"], capture_output=True, text=True, timeout=15)
878
- if "tokensafe@" in res.stdout:
879
- print(f" {CYAN}→{RESET} Updating global npm package (npm install -g tokensafe@latest)...")
880
- up_res = subprocess.run([npm_bin, "install", "-g", "tokensafe@latest"], capture_output=True, text=True, timeout=120)
881
- if up_res.returncode == 0:
882
- print(f" {GREEN}✔{RESET} npm package upgraded successfully.")
883
- else:
884
- detail = (up_res.stderr or up_res.stdout or "").strip()[:200]
885
- print(f" {YELLOW}⚠{RESET} npm upgrade failed: {detail}")
886
- else:
887
- print(f" {CYAN}ℹ{RESET} tokensafe not installed via npm — skipping npm channel.")
888
- except Exception as e:
889
- print(f" {YELLOW}⚠{RESET} npm update skipped: {e}")
945
+ # 2. Check npm global across all discovered Node/npm prefixes
946
+ # A macOS login shell may have /usr/local/bin/npm on PATH ahead of nvm,
947
+ # and `#!/usr/bin/env node` inside nvm's npm also resolves /usr/local/bin/node
948
+ # unless npm's own bin dir is prepended to PATH.
949
+ primary_npm = cls._find_npm()
950
+ upgraded_npm_bins: List[str] = []
951
+ if primary_npm:
952
+ npm_candidates = cls._find_npm_candidates()
953
+ norm_seen = {os.path.normpath(os.path.abspath(p)) for p in npm_candidates}
954
+ if os.path.normpath(os.path.abspath(primary_npm)) not in norm_seen:
955
+ npm_candidates.insert(0, primary_npm)
956
+
957
+ found_npm_install = False
958
+ for npm_bin in npm_candidates:
959
+ npm_env = cls._npm_subprocess_env(npm_bin)
960
+ try:
961
+ res = subprocess.run(
962
+ [npm_bin, "list", "-g", "--depth=0", "tokensafe"],
963
+ env=npm_env,
964
+ capture_output=True,
965
+ text=True,
966
+ timeout=15,
967
+ )
968
+ if "tokensafe@" in (res.stdout or ""):
969
+ found_npm_install = True
970
+ print(f" {CYAN}→{RESET} Updating global npm package via {npm_bin} (npm install -g tokensafe@latest)...")
971
+ up_res = subprocess.run(
972
+ [npm_bin, "install", "-g", "tokensafe@latest"],
973
+ env=npm_env,
974
+ capture_output=True,
975
+ text=True,
976
+ timeout=120,
977
+ )
978
+ if up_res.returncode == 0:
979
+ print(f" {GREEN}✔{RESET} npm package upgraded successfully.")
980
+ upgraded_npm_bins.append(npm_bin)
981
+ else:
982
+ detail = (up_res.stderr or up_res.stdout or "").strip()[:200]
983
+ print(f" {YELLOW}⚠{RESET} npm upgrade failed: {detail}")
984
+ except Exception as e:
985
+ print(f" {YELLOW}⚠{RESET} npm update check failed ({npm_bin}): {e}")
986
+
987
+ if not found_npm_install:
988
+ print(f" {CYAN}ℹ{RESET} tokensafe not installed via npm — skipping npm channel.")
890
989
  else:
891
990
  print(f" {YELLOW}⚠{RESET} npm not found — skipping npm channel.")
892
991
 
@@ -932,9 +1031,17 @@ class AgentInstaller:
932
1031
  except Exception:
933
1032
  pass
934
1033
  try:
935
- tokensafe_bin = shutil.which("tokensafe")
1034
+ tokensafe_bin = None
1035
+ for npm_bin in upgraded_npm_bins:
1036
+ cand_bin = os.path.join(os.path.dirname(npm_bin), "tokensafe.cmd" if os.name == "nt" else "tokensafe")
1037
+ if os.path.isfile(cand_bin) and os.access(cand_bin, os.X_OK):
1038
+ tokensafe_bin = cand_bin
1039
+ break
1040
+ if not tokensafe_bin:
1041
+ tokensafe_bin = shutil.which("tokensafe")
936
1042
  sync_cmd = [tokensafe_bin, "version", "--check"] if tokensafe_bin else [sys.executable, os.path.join(PROJECT_ROOT, "src", "cli.py"), "version", "--check"]
937
- subprocess.run(sync_cmd, capture_output=True, text=True, timeout=5)
1043
+ sync_env = cls._npm_subprocess_env(tokensafe_bin) if tokensafe_bin else None
1044
+ subprocess.run(sync_cmd, env=sync_env, capture_output=True, text=True, timeout=5)
938
1045
  except Exception:
939
1046
  pass
940
1047
 
package/src/mcp_server.py CHANGED
@@ -40,7 +40,7 @@ from src.license_manager import LicenseManager
40
40
 
41
41
  SERVER_INFO = {
42
42
  "name": "tokensafe-mcp",
43
- "version": "2.5.1"
43
+ "version": "2.5.2"
44
44
  }
45
45
 
46
46
  # MCP client attribution: the initialize handshake carries clientInfo, which
@@ -276,7 +276,7 @@ class TelemetrySync:
276
276
  rollup_synced = bool(state.get("lifetime_rollup_synced", False))
277
277
  headers = {
278
278
  "Content-Type": "application/json",
279
- "User-Agent": "TokenSafe-Sync/2.5.1"
279
+ "User-Agent": "TokenSafe-Sync/2.5.2"
280
280
  }
281
281
  if active_key:
282
282
  headers["Authorization"] = f"Bearer {active_key}"
@@ -16,7 +16,7 @@ import urllib.request
16
16
  import urllib.error
17
17
  from typing import Dict, Any, Optional, Tuple
18
18
 
19
- CURRENT_VERSION = "2.5.1"
19
+ CURRENT_VERSION = "2.5.2"
20
20
  CACHE_TTL = 86400 # 24 hours
21
21
  # When the cloud is unreachable we must NOT cache the synthesized "up to date"
22
22
  # answer for a full day — otherwise an update released right after an outage