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.
Files changed (46) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/README.md +1 -1
  3. package/hooks/claude_code_hook.py +8 -2
  4. package/hooks/cursor_hook.py +2 -1
  5. package/hooks/kimi_hook.py +2 -1
  6. package/hooks/post_tool_use.py +15 -1
  7. package/hooks/pre_invocation.py +4 -2
  8. package/hooks/pre_tool_use.py +13 -6
  9. package/hooks/session_start.py +7 -2
  10. package/hooks/stop_hook.py +2 -1
  11. package/hooks/zcode_hook.py +2 -1
  12. package/kimi.plugin.json +1 -1
  13. package/package.json +1 -1
  14. package/plugin.json +1 -1
  15. package/server.json +3 -3
  16. package/src/acp/server.py +5 -0
  17. package/src/atomic_io.py +74 -0
  18. package/src/auto_inject.py +8 -4
  19. package/src/backend_release.py +3 -3
  20. package/src/batch_editor.py +2 -14
  21. package/src/cli.py +10 -0
  22. package/src/command_sanitizer.py +1 -1
  23. package/src/context_index.py +954 -0
  24. package/src/file_state.py +4 -3
  25. package/src/fts_index.py +12 -32
  26. package/src/graph_engine.py +43 -95
  27. package/src/guard.py +1 -1
  28. package/src/installer.py +64 -4
  29. package/src/license_manager.py +66 -0
  30. package/src/mcp_proxy.py +3 -0
  31. package/src/mcp_server.py +103 -5
  32. package/src/mistakes.py +45 -21
  33. package/src/oumv_gateway.py +61 -18
  34. package/src/paths.py +5 -12
  35. package/src/project_memory.py +264 -0
  36. package/src/result_ledger.py +40 -0
  37. package/src/retrofit.py +15 -8
  38. package/src/scoped_search.py +93 -53
  39. package/src/session_brief.py +14 -3
  40. package/src/skeletonizer.py +44 -2
  41. package/src/snapshot.py +17 -1
  42. package/src/stdio_io.py +50 -0
  43. package/src/telemetry_sync.py +1 -1
  44. package/src/version_checker.py +1 -1
  45. package/src/win_paths.py +172 -0
  46. package/src/workspace_roots.py +2 -6
@@ -0,0 +1,50 @@
1
+ """UTF-8 stdio for hosts whose console defaults to a legacy code page.
2
+
3
+ On Windows a pipe is decoded with the ANSI code page (cp1252) unless
4
+ ``PYTHONUTF8``/``PYTHONIOENCODING`` is set. A single CJK character or emoji in a
5
+ file then raised ``UnicodeEncodeError`` inside the MCP server's write, which the
6
+ loop caught by exiting — every later tool call failed. Hooks had the same
7
+ problem on input and silently fell back to ``{}``.
8
+
9
+ ``ensure_utf8_stdio`` fixes the streams a process already owns;
10
+ ``read_stdin_text`` reads the hook payload from the raw buffer so decoding never
11
+ depends on the console at all.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import json
17
+ import sys
18
+ from typing import Any, Dict
19
+
20
+
21
+ def ensure_utf8_stdio() -> None:
22
+ for name in ("stdin", "stdout", "stderr"):
23
+ stream = getattr(sys, name, None)
24
+ if stream is None:
25
+ continue
26
+ try:
27
+ stream.reconfigure(encoding="utf-8", errors="replace")
28
+ except Exception:
29
+ pass
30
+
31
+
32
+ def read_stdin_text() -> str:
33
+ try:
34
+ buffer = getattr(sys.stdin, "buffer", None)
35
+ if buffer is not None:
36
+ return buffer.read().decode("utf-8", "replace")
37
+ return sys.stdin.read()
38
+ except Exception:
39
+ return ""
40
+
41
+
42
+ def read_payload() -> Dict[str, Any]:
43
+ raw = read_stdin_text()
44
+ if not raw.strip():
45
+ return {}
46
+ try:
47
+ data = json.loads(raw)
48
+ except Exception:
49
+ return {}
50
+ return data if isinstance(data, dict) else {}
@@ -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.13.3"
314
+ "User-Agent": "TokenSafe-Sync/4.15.0"
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.13.3"
20
+ CURRENT_VERSION = "4.15.0"
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
@@ -0,0 +1,172 @@
1
+ """Cross-platform path semantics used by every workspace boundary check.
2
+
3
+ The engine grew up POSIX-first: ``startswith(abspath(root))`` passes on a
4
+ case-sensitive filesystem with one separator, and every guard that used it was
5
+ wrong on Windows in a different way (backslashes, drive letters, case folding,
6
+ ``.cmd`` wrappers, POSIX quoting). This module is the single place those
7
+ decisions live.
8
+
9
+ Nothing here writes to disk; all helpers are pure and cheap enough for the hook
10
+ path.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import os
16
+ from typing import Iterable, List, Optional
17
+
18
+ # Path module used for every boundary decision. Tests swap it for ``ntpath``
19
+ # (with a small realpath shim) to exercise Windows semantics on POSIX CI.
20
+ _path = os.path
21
+
22
+
23
+ def norm_key(path: str) -> str:
24
+ """Canonical comparison key: absolute, resolved, case-folded on Windows.
25
+
26
+ Missing paths resolve through :func:`os.path.realpath`'s parent handling, so
27
+ a not-yet-created file still compares inside its workspace on POSIX and on
28
+ Windows alike.
29
+ """
30
+ try:
31
+ expanded = os.path.expanduser(str(path))
32
+ except (TypeError, ValueError):
33
+ return ""
34
+ if not expanded:
35
+ return ""
36
+ if os.name == "nt" and expanded.startswith("\\\\?\\"):
37
+ # Extended-length prefix: strip it so it compares with normal paths.
38
+ expanded = expanded[4:]
39
+ try:
40
+ real = _path.realpath(_path.abspath(expanded))
41
+ except (OSError, ValueError):
42
+ return ""
43
+ return _path.normcase(real)
44
+
45
+
46
+ def state_key(path: str) -> str:
47
+ """Stable state-file key: absolute, case-folded on Windows, no symlink walk.
48
+
49
+ Symlink resolution is deliberately excluded: state files persist across runs
50
+ and a moved link must not orphan every entry.
51
+ """
52
+ try:
53
+ return _path.normcase(_path.abspath(_path.expanduser(str(path))))
54
+ except (TypeError, ValueError):
55
+ return ""
56
+
57
+
58
+ def is_within(root: str, path: str) -> bool:
59
+ """True when ``path`` is ``root`` or lives under it, case/separator-safe."""
60
+ root_key = norm_key(root)
61
+ path_key = norm_key(path)
62
+ if not root_key or not path_key:
63
+ return False
64
+ if root_key == path_key:
65
+ return True
66
+ try:
67
+ return _path.commonpath([root_key, path_key]) == root_key
68
+ except ValueError:
69
+ # Different drives on Windows, or a UNC root vs a local path.
70
+ return False
71
+
72
+
73
+ def path_segments(path: str) -> List[str]:
74
+ """Lower-cased path components with both separators normalised."""
75
+ raw = str(path or "").replace("\\", "/")
76
+ return [segment.lower() for segment in raw.split("/") if segment]
77
+
78
+
79
+ def _has_segment_sequence(path: str, sequence: Iterable[str]) -> bool:
80
+ want = [segment.lower() for segment in sequence]
81
+ parts = path_segments(path)
82
+ width = len(want)
83
+ if width == 0 or len(parts) < width:
84
+ return False
85
+ return any(parts[idx:idx + width] == want for idx in range(len(parts) - width + 1))
86
+
87
+
88
+ def is_system_root(path: str) -> bool:
89
+ """Drive root, POSIX root, the user's home, or a top-level system dir."""
90
+ key = norm_key(path)
91
+ if not key:
92
+ return True
93
+ home_key = norm_key(_path.expanduser("~")) if _path.expanduser("~") else ""
94
+ if home_key and key == home_key:
95
+ return True
96
+ drive, tail = _path.splitdrive(key)
97
+ if drive:
98
+ if tail in ("", _path.sep, "/"):
99
+ return True
100
+ if os.name == "nt" and tail.lower() in (_path.sep + "users", _path.sep + "windows"):
101
+ return True
102
+ else:
103
+ if key == _path.normcase(_path.sep):
104
+ return True
105
+ if os.name != "nt" and key in {
106
+ _path.normcase("/users"),
107
+ _path.normcase("/home"),
108
+ _path.normcase("/root"),
109
+ }:
110
+ return True
111
+ return False
112
+
113
+
114
+ _PLUGIN_SEGMENTS = (
115
+ (".gemini", "config", "plugins"),
116
+ (".gemini", "config", "plugins", "tokensafe"),
117
+ (".cursor", "extensions"),
118
+ ("plugins", "tokensafe"),
119
+ (".tokensafe",),
120
+ )
121
+
122
+
123
+ def is_plugin_dir(path: str) -> bool:
124
+ """True inside an agent plugin/config directory (both separators)."""
125
+ if not path:
126
+ return True
127
+ return any(_has_segment_sequence(path, sequence) for sequence in _PLUGIN_SEGMENTS)
128
+
129
+
130
+ def transient_roots() -> List[str]:
131
+ """OS scratch directories for this platform (``/tmp`` is not ``C:\\tmp``)."""
132
+ roots: List[str] = []
133
+ if os.name != "nt":
134
+ roots.extend(("/tmp", "/var/tmp", "/private/tmp", "/var/folders", "/private/var/folders"))
135
+ try:
136
+ import tempfile
137
+
138
+ roots.append(tempfile.gettempdir())
139
+ except Exception:
140
+ pass
141
+ return roots
142
+
143
+
144
+ def quote_hook_command(argv: List[str]) -> str:
145
+ """Shell command string for a host config file, quoted for that shell.
146
+
147
+ POSIX hosts run hooks through ``/bin/sh`` and accept single quotes; Windows
148
+ hosts run ``cmd.exe``, where ``shlex.quote`` wraps the path in single quotes
149
+ that cmd.exe does not treat as quoting and the hook never starts.
150
+ """
151
+ parts = [str(arg) for arg in argv]
152
+ if os.name == "nt":
153
+ import subprocess as _subprocess
154
+
155
+ return _subprocess.list2cmdline(parts)
156
+ import shlex as _shlex
157
+
158
+ return " ".join(_shlex.quote(part) for part in parts)
159
+
160
+
161
+ def resolve_executable(name: str) -> Optional[str]:
162
+ """``npm`` -> ``npm.cmd`` on Windows (``CreateProcess`` needs the extension)."""
163
+ if not name:
164
+ return None
165
+ import shutil as _shutil
166
+
167
+ found = _shutil.which(name)
168
+ if found:
169
+ return found
170
+ if os.name == "nt" and not name.lower().endswith((".cmd", ".bat", ".exe")):
171
+ return _shutil.which(name + ".cmd") or _shutil.which(name + ".bat")
172
+ return None
@@ -14,6 +14,7 @@ import threading
14
14
  from typing import Any, Dict, Iterable, List, Optional, Tuple
15
15
 
16
16
  from src.paths import is_plugin_or_system_dir
17
+ from src.win_paths import is_within
17
18
 
18
19
  _LOCK = threading.Lock()
19
20
  _ROOTS: List[str] = []
@@ -60,12 +61,7 @@ def reset_roots(paths: Iterable[Any] = ()) -> List[str]:
60
61
 
61
62
 
62
63
  def _within(root: str, path: str) -> bool:
63
- try:
64
- real_root = os.path.realpath(root)
65
- real_path = os.path.realpath(path)
66
- return os.path.commonpath([real_root, real_path]) == real_root
67
- except (OSError, ValueError):
68
- return False
64
+ return is_within(root, path)
69
65
 
70
66
 
71
67
  def _fmt_roots(roots: List[str]) -> str: