tokensafe 4.5.2 → 4.5.3

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.5.2",
2
+ "version": "4.5.3",
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.5.2",
3
+ "version": "4.5.3",
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.2",
4
+ "version": "4.5.3",
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.2",
4
+ "version": "4.5.3",
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.2",
6
+ "version": "4.5.3",
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.2",
26
+ "version": "4.5.3",
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.2",
42
+ "version": "4.5.3",
43
43
  "runtimeHint": "uvx",
44
44
  "transport": {
45
45
  "type": "stdio"
@@ -16,16 +16,183 @@ Key capabilities:
16
16
  import os
17
17
  import re
18
18
  import difflib
19
+ import shlex
19
20
  import subprocess
20
21
  import time
21
22
  from typing import Dict, Any, List, Optional, Tuple
22
23
 
24
+ from src.guard import TokenSafeGuard
25
+ from src.paths import is_plugin_or_system_dir
23
26
  from src.secret_redactor import SecretRedactor
24
27
  from src.format_parsers.ansi import strip_ansi
25
28
 
26
29
  MAX_BATCH_FILES = 50
27
30
  MAX_VERIFY_OUTPUT_CHARS = 4000
28
31
 
32
+ _VERIFY_SIMPLE_RUNNERS = frozenset({
33
+ "pytest", "py.test", "ruff", "mypy", "pyright", "flake8", "tox", "nox",
34
+ "vitest", "jest", "mocha", "ava", "tsc", "eslint", "prettier", "biome",
35
+ "oxlint", "rspec", "phpunit", "ctest",
36
+ })
37
+ _VERIFY_PYTHON_RUNNERS = frozenset({
38
+ "python", "python3", "python3.10", "python3.11", "python3.12", "python3.13",
39
+ })
40
+ _VERIFY_PYTHON_MODULES = frozenset({
41
+ "unittest", "pytest", "py_compile", "compileall", "mypy", "ruff", "flake8", "doctest",
42
+ })
43
+ _VERIFY_JS_PKG_MANAGERS = frozenset({"npm", "pnpm", "yarn"})
44
+ _VERIFY_SAFE_SCRIPT_PREFIXES = ("test", "lint", "check", "typecheck", "build")
45
+ _VERIFY_SUBCOMMAND_ALLOWLIST = {
46
+ "go": frozenset({"test", "vet", "build"}),
47
+ "cargo": frozenset({"test", "check", "clippy", "build"}),
48
+ "dotnet": frozenset({"test", "build"}),
49
+ "zig": frozenset({"test", "build"}),
50
+ "swift": frozenset({"test", "build"}),
51
+ "tokensafe": frozenset({"tests"}),
52
+ }
53
+ _VERIFY_FORBIDDEN_FLAGS = frozenset({
54
+ "-c", "-e", "--eval", "-p", "--print", "-r", "--require",
55
+ "--import", "--loader", "-exec", "--exec", "-toolexec",
56
+ })
57
+ _DISALLOWED_SYSTEM_DIRS = frozenset({"/etc", "/usr", "/bin", "/sbin", "/System", "/private/etc"})
58
+
59
+
60
+ def _has_unquoted_shell_operators(cmd_str: str) -> bool:
61
+ """Detects shell chaining, redirection, or command substitution operators."""
62
+ in_single = False
63
+ in_double = False
64
+ escaped = False
65
+ n = len(cmd_str)
66
+ for i, ch in enumerate(cmd_str):
67
+ if ch in ("\n", "\r", "\x00"):
68
+ return True
69
+ if escaped:
70
+ escaped = False
71
+ continue
72
+ if ch == "\\" and not in_single:
73
+ escaped = True
74
+ continue
75
+ if ch == "'" and not in_double:
76
+ in_single = not in_single
77
+ continue
78
+ if ch == '"' and not in_single:
79
+ in_double = not in_double
80
+ continue
81
+ if not in_single:
82
+ if ch == "`":
83
+ return True
84
+ if ch == "$" and i + 1 < n and cmd_str[i + 1] in ("(", "{"):
85
+ return True
86
+ if not in_single and not in_double and ch in (";", "|", "&", ">", "<"):
87
+ return True
88
+ return False
89
+
90
+
91
+ def validate_verify_command(
92
+ verify_cmd: str, base_dir: str = ""
93
+ ) -> Tuple[Optional[List[str]], Optional[str], Optional[str]]:
94
+ """
95
+ Validates an inline verify command through TokenSafeGuard, shell-operator
96
+ rejection, shlex tokenization, and a strict verification-runner allowlist.
97
+ Returns (argv, error_reason, guard_check_name).
98
+ """
99
+ cmd_str = str(verify_cmd or "").strip()
100
+ if not cmd_str:
101
+ return None, "Verification command cannot be empty.", "VERIFY_COMMAND_BLOCKED"
102
+
103
+ guard_res = TokenSafeGuard.inspect_command(cmd_str, cwd=base_dir)
104
+ if guard_res.blocked:
105
+ return (
106
+ None,
107
+ f"TokenSafe Security Guard ({guard_res.check_name}) blocked verify command: {guard_res.reason}",
108
+ guard_res.check_name,
109
+ )
110
+
111
+ if _has_unquoted_shell_operators(cmd_str):
112
+ return (
113
+ None,
114
+ "Shell chaining, redirection, and command substitution operators are disallowed in apply_edits.verify.",
115
+ "VERIFY_COMMAND_BLOCKED",
116
+ )
117
+
118
+ try:
119
+ argv = shlex.split(cmd_str)
120
+ except ValueError as exc:
121
+ return None, f"Malformed verify command syntax: {exc}", "VERIFY_COMMAND_BLOCKED"
122
+
123
+ if not argv:
124
+ return None, "Verification command cannot be empty.", "VERIFY_COMMAND_BLOCKED"
125
+
126
+ raw_exe = argv[0]
127
+ if "/" in raw_exe or "\\" in raw_exe:
128
+ return (
129
+ None,
130
+ f"Path-qualified executables ('{raw_exe}') are disallowed in apply_edits.verify.",
131
+ "VERIFY_COMMAND_BLOCKED",
132
+ )
133
+
134
+ exe = raw_exe.lower()
135
+ if exe.endswith(".exe"):
136
+ exe = exe[:-4]
137
+
138
+ args_rest = argv[1:]
139
+ if any(a in _VERIFY_FORBIDDEN_FLAGS or a.startswith("--eval=") or a.startswith("-exec=") for a in args_rest):
140
+ return (
141
+ None,
142
+ f"Flag '{next(a for a in args_rest if a in _VERIFY_FORBIDDEN_FLAGS or a.startswith(('--eval=', '-exec=')))}' is disallowed in apply_edits.verify.",
143
+ "VERIFY_COMMAND_BLOCKED",
144
+ )
145
+
146
+ if exe in _VERIFY_PYTHON_RUNNERS:
147
+ if len(argv) >= 3 and argv[1] == "-m" and argv[2] in _VERIFY_PYTHON_MODULES:
148
+ return argv, None, None
149
+ return (
150
+ None,
151
+ f"Python verify commands must use '-m <allowed_module>' (one of {sorted(_VERIFY_PYTHON_MODULES)}).",
152
+ "VERIFY_COMMAND_BLOCKED",
153
+ )
154
+
155
+ if exe in _VERIFY_JS_PKG_MANAGERS:
156
+ if args_rest and args_rest[0] in ("test", "t", "lint", "check", "typecheck", "build"):
157
+ return argv, None, None
158
+ if len(args_rest) >= 2 and args_rest[0] == "run" and args_rest[1].startswith(_VERIFY_SAFE_SCRIPT_PREFIXES):
159
+ return argv, None, None
160
+ return (
161
+ None,
162
+ f"'{exe}' verify command only allows test/lint/check/typecheck/build subcommands.",
163
+ "VERIFY_COMMAND_BLOCKED",
164
+ )
165
+
166
+ if exe == "bun":
167
+ if args_rest and args_rest[0] == "test":
168
+ return argv, None, None
169
+ if len(args_rest) >= 2 and args_rest[0] == "run" and args_rest[1].startswith(_VERIFY_SAFE_SCRIPT_PREFIXES):
170
+ return argv, None, None
171
+ return (
172
+ None,
173
+ "'bun' verify command only allows 'bun test' or 'bun run <test|lint|check|typecheck|build>*'.",
174
+ "VERIFY_COMMAND_BLOCKED",
175
+ )
176
+
177
+ if exe in _VERIFY_SUBCOMMAND_ALLOWLIST:
178
+ allowed_subs = _VERIFY_SUBCOMMAND_ALLOWLIST[exe]
179
+ if args_rest and args_rest[0] in allowed_subs:
180
+ return argv, None, None
181
+ return (
182
+ None,
183
+ f"'{exe}' verify command only allows subcommands: {sorted(allowed_subs)}.",
184
+ "VERIFY_COMMAND_BLOCKED",
185
+ )
186
+
187
+ if exe in _VERIFY_SIMPLE_RUNNERS:
188
+ return argv, None, None
189
+
190
+ return (
191
+ None,
192
+ f"Executable '{raw_exe}' is not in the allowlisted verification runners for apply_edits.verify.",
193
+ "VERIFY_COMMAND_BLOCKED",
194
+ )
195
+
29
196
 
30
197
  def _find_closest_line_hint(target: str, content: str, max_lines_preview: int = 5) -> str:
31
198
  """Finds closest matching snippet in content to provide actionable line-drift retry guidance."""
@@ -140,6 +307,29 @@ def execute_batch_edits(
140
307
 
141
308
  base_dir = os.path.abspath(cwd or os.getcwd())
142
309
  real_base = os.path.realpath(base_dir)
310
+ if is_plugin_or_system_dir(base_dir) or real_base in _DISALLOWED_SYSTEM_DIRS or not os.path.isdir(real_base):
311
+ return {
312
+ "success": False,
313
+ "error": f"Refusing batch edits in system, plugin, or non-existent directory '{cwd or base_dir}'.",
314
+ "applied_files": [],
315
+ "failed_files": []
316
+ }
317
+
318
+ verified_argv: Optional[List[str]] = None
319
+ if verify:
320
+ verified_argv, verify_err, verify_check = validate_verify_command(str(verify), base_dir=real_base)
321
+ if verify_err or not verified_argv:
322
+ return {
323
+ "success": False,
324
+ "blocked": True,
325
+ "check_name": verify_check or "VERIFY_COMMAND_BLOCKED",
326
+ "error": verify_err or "Verification command blocked.",
327
+ "applied_count": 0,
328
+ "applied_files": [],
329
+ "failed_count": 0,
330
+ "failed_files": [],
331
+ "dry_run": dry_run,
332
+ }
143
333
 
144
334
  # Pre-validation & secret check
145
335
  prepared_files: Dict[str, Dict[str, Any]] = {}
@@ -345,15 +535,15 @@ def execute_batch_edits(
345
535
  "dry_run": dry_run
346
536
  }
347
537
 
348
- # Execute inline verify command if requested and files were modified
349
- if verify and applied_files_info and not dry_run:
538
+ # Execute inline verify command if requested and files were modified (shell=False, allowlisted argv)
539
+ if verified_argv and applied_files_info and not dry_run:
350
540
  cmd_str = str(verify).strip()
351
541
  t0 = time.time()
352
542
  try:
353
543
  proc = subprocess.run(
354
- cmd_str,
355
- shell=True,
356
- cwd=base_dir,
544
+ verified_argv,
545
+ shell=False,
546
+ cwd=real_base,
357
547
  stdout=subprocess.PIPE,
358
548
  stderr=subprocess.STDOUT,
359
549
  text=True,
package/src/mcp_server.py CHANGED
@@ -42,7 +42,7 @@ from src.paths import get_active_workspace, is_plugin_or_system_dir
42
42
 
43
43
  SERVER_INFO = {
44
44
  "name": "tokensafe-mcp",
45
- "version": "4.5.2"
45
+ "version": "4.5.3"
46
46
  }
47
47
 
48
48
  # MCP client attribution: the initialize handshake carries clientInfo, which
@@ -552,9 +552,10 @@ FULL_TOOLS = [ { 'annotations': {'readOnlyHint': True},
552
552
  'type': 'object'},
553
553
  'maxItems': 50,
554
554
  'type': 'array'},
555
- 'verify': { 'description': 'Optional shell command to execute immediately '
555
+ 'verify': { 'description': 'Optional allowlisted verification command '
556
556
  'after applying edits (e.g. npm test, pytest, '
557
- 'cargo test)',
557
+ 'cargo test, go test, python3 -m unittest) '
558
+ 'validated via TokenSafeGuard without a shell',
558
559
  'type': 'string'},
559
560
  'verify_timeout_sec': { 'description': 'Verification timeout in seconds '
560
561
  '(default 30)',
@@ -2653,7 +2654,19 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
2653
2654
  dry_run = bool(args.get("dry_run", False))
2654
2655
  verify = args.get("verify")
2655
2656
  verify_timeout = int(args.get("verify_timeout_sec") or 30)
2656
- cwd = args.get("cwd") or get_active_workspace()
2657
+ raw_cwd = args.get("cwd")
2658
+ active_ws = get_active_workspace()
2659
+ if raw_cwd:
2660
+ if not os.path.isabs(str(raw_cwd)) and active_ws and os.path.isdir(os.path.join(active_ws, str(raw_cwd))):
2661
+ cwd = os.path.abspath(os.path.join(active_ws, str(raw_cwd)))
2662
+ else:
2663
+ cwd = os.path.abspath(str(raw_cwd))
2664
+ else:
2665
+ cwd, err = _resolve_project_root(args)
2666
+ if err or not cwd:
2667
+ return _fallback_error("apply_edits", err or "unspecified project workspace cwd")
2668
+ if is_plugin_or_system_dir(cwd):
2669
+ return _fallback_error("apply_edits", f"refusing to run apply_edits in system root or plugin dir '{cwd}'")
2657
2670
 
2658
2671
  res = execute_batch_edits(
2659
2672
  edits=edits,
@@ -2663,6 +2676,15 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
2663
2676
  verify_timeout_sec=verify_timeout,
2664
2677
  cwd=cwd
2665
2678
  )
2679
+ if res.get("blocked"):
2680
+ tracker.record_event(
2681
+ session_id=_mcp_session_id(),
2682
+ event_type=f"GUARD_{res.get('check_name') or 'VERIFY_COMMAND_BLOCKED'}",
2683
+ original_tokens=count_tokens(str(verify or "")),
2684
+ optimized_tokens=0,
2685
+ details={"cmd": str(verify or "")[:100], "reason": str(res.get("error") or "")}
2686
+ )
2687
+ return _fallback_error("apply_edits", str(res.get("error") or "verify command blocked"))
2666
2688
  lines = []
2667
2689
  if res.get("success"):
2668
2690
  action_desc = "Validated" if dry_run else "Applied"
@@ -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.2"
252
+ "User-Agent": "TokenSafe-Sync/4.5.3"
253
253
  }
254
254
  if active_key:
255
255
  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.5.2"
20
+ CURRENT_VERSION = "4.5.3"
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