tokensafe 4.2.0 → 4.2.1

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.2.0",
2
+ "version": "4.2.1",
3
3
  "name": "tokensafe",
4
4
  "description": "Your coding agent isn't getting dumber. Your context is just full of trash. Local context firewall & zero-loss runtime for Cursor, Claude Code, and autonomous agents.",
5
5
  "author": {
package/hooks.json CHANGED
@@ -15,6 +15,13 @@
15
15
  "timeout": 10
16
16
  }
17
17
  ],
18
+ "UserPromptSubmit": [
19
+ {
20
+ "type": "command",
21
+ "command": "python3 hooks/pre_invocation.py",
22
+ "timeout": 10
23
+ }
24
+ ],
18
25
  "PreToolUse": [
19
26
  {
20
27
  "matcher": "read_file|view_file|run_command|write_file|edit_file",
package/kimi.plugin.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tokensafe",
3
- "version": "4.2.0",
3
+ "version": "4.2.1",
4
4
  "description": "Your coding agent isn't getting dumber. Your context is just full of trash. Local context firewall & zero-loss runtime for Cursor, Claude Code, and autonomous 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.2.0",
4
+ "version": "4.2.1",
5
5
  "description": "Your coding agent isn't getting dumber. Your context is just full of trash. Local context firewall & zero-loss runtime for Cursor, Claude Code, and autonomous 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.2.0",
4
+ "version": "4.2.1",
5
5
  "description": "Your coding agent isn't getting dumber. Your context is just full of trash. Local context firewall & zero-loss runtime for Cursor, Claude Code, and autonomous agents.",
6
6
  "logo": "https://tokensafe.dev/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 agent isn't getting dumber, your context is full of trash. Local firewall & zero-loss runtime.",
6
- "version": "4.2.0",
6
+ "version": "4.2.1",
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": "4.2.0",
33
+ "version": "4.2.1",
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": "4.2.0",
49
+ "version": "4.2.1",
50
50
  "runtimeHint": "uvx",
51
51
  "transport": {
52
52
  "type": "stdio"
package/src/installer.py CHANGED
@@ -228,7 +228,7 @@ class AgentInstaller:
228
228
  Codex has no lifecycle hooks (MCP + AGENTS.md remain the integration)."""
229
229
  if agent_key == "codex":
230
230
  return False, "Codex CLI has no lifecycle hooks — MCP + AGENTS.md stay the integration"
231
- if agent_key not in ("claude_code", "cursor", "kimi"):
231
+ if agent_key not in ("claude_code", "cursor", "kimi", "zcode"):
232
232
  return False, "hooks not applicable for this agent"
233
233
 
234
234
  claude_cmd = cls._tokensafe_hook_command("claude_code_hook.py")
@@ -331,6 +331,66 @@ class AgentInstaller:
331
331
  cls._atomic_write_json(config_file, data)
332
332
  return True, "hooks registered (SessionStart + UserPromptSubmit + PreToolUse guard/write + PostToolUse stdout compact)"
333
333
 
334
+ if agent_key == "zcode":
335
+ config_file = os.path.join(HOME, ".zcode", "cli", "config.json")
336
+ data, err = cls._load_json_with_backup(config_file)
337
+ if err or data is None:
338
+ return False, err or f"Failed to parse {config_file}"
339
+ # ZCode configuration-file hooks are disabled by default and only run
340
+ # with enabled=true. The bundled hook scripts already speak the ZCode
341
+ # contract (injectSteps/systemMessage outputs + decision/reason), so
342
+ # registration is pure plumbing — no adapter shim needed.
343
+ hooks_block = data.get("hooks") if isinstance(data.get("hooks"), dict) else {}
344
+ hooks_block["enabled"] = True
345
+ events = hooks_block.get("events") if isinstance(hooks_block.get("events"), dict) else {}
346
+
347
+ def _zcode_entry(script_name: str) -> dict:
348
+ return {"hooks": [{
349
+ "type": "process",
350
+ "command": PYTHON_BIN,
351
+ "args": [os.path.join(PROJECT_ROOT, "hooks", script_name)],
352
+ "timeoutMs": 10000,
353
+ }]}
354
+
355
+ def _sync_zcode_event(event_name: str, script_name: str) -> bool:
356
+ entry = _zcode_entry(script_name)
357
+ expected = os.path.join(PROJECT_ROOT, "hooks", script_name)
358
+ entries = events.get(event_name)
359
+ if not isinstance(entries, list):
360
+ events[event_name] = [entry]
361
+ return True
362
+ seen = False
363
+ dirty = False
364
+ for e in entries:
365
+ if isinstance(e, dict) and isinstance(e.get("hooks"), list):
366
+ for h in e["hooks"]:
367
+ args = h.get("args") if isinstance(h, dict) else None
368
+ if not isinstance(args, list):
369
+ continue
370
+ if any(isinstance(a, str) and a.endswith(script_name) for a in args):
371
+ seen = True
372
+ if args[-1] != expected:
373
+ args[-1] = expected
374
+ dirty = True
375
+ if not seen:
376
+ entries.append(entry)
377
+ dirty = True
378
+ return dirty
379
+
380
+ changed = any([
381
+ _sync_zcode_event("SessionStart", "session_start.py"),
382
+ _sync_zcode_event("UserPromptSubmit", "pre_invocation.py"),
383
+ _sync_zcode_event("PreToolUse", "pre_tool_use.py"),
384
+ _sync_zcode_event("PostToolUse", "post_tool_use.py"),
385
+ _sync_zcode_event("Stop", "stop_hook.py"),
386
+ ])
387
+ if changed:
388
+ hooks_block["events"] = events
389
+ data["hooks"] = hooks_block
390
+ cls._atomic_write_json(config_file, data)
391
+ return True, "ZCode hooks registered in ~/.zcode/cli/config.json (SessionStart + UserPromptSubmit + PreToolUse guard + PostToolUse compact + Stop) — restart the app to take effect"
392
+ return True, "TokenSafe ZCode hooks already registered"
393
+
334
394
  # cursor
335
395
  config_file = os.path.join(HOME, ".cursor", "hooks.json")
336
396
  os.makedirs(os.path.dirname(config_file), exist_ok=True)
@@ -503,7 +563,11 @@ class AgentInstaller:
503
563
  with open(path, "w", encoding="utf-8") as f:
504
564
  json.dump(routes, f, indent=2)
505
565
  return True
506
- except Exception:
566
+ except Exception as e:
567
+ try:
568
+ sys.stderr.write(f"[TokenSafe] WARN: proxy route registration failed ({label}): {e}\n")
569
+ except Exception:
570
+ pass
507
571
  return False
508
572
 
509
573
  @classmethod
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.2.0"
45
+ "version": "4.2.1"
46
46
  }
47
47
 
48
48
  # MCP client attribution: the initialize handshake carries clientInfo, which
@@ -1864,6 +1864,45 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
1864
1864
  return _fallback_error(name, f"unknown tool '{name}'")
1865
1865
 
1866
1866
 
1867
+ def _redact_result_secrets(result):
1868
+ """Egress guard at the MCP boundary: strips recognized secret patterns from
1869
+ tool results BEFORE they enter any agent's context. Covers every MCP-connected
1870
+ agent (CC, Cursor, Cline, Windsurf, Copilot, Kimi, Codex, Antigravity, ZCode)
1871
+ even when the proxy is not on the path. Same redactor the proxy pipeline uses.
1872
+ Fail-open: any internal problem returns the result untouched."""
1873
+ try:
1874
+ if result is None:
1875
+ return result
1876
+ from src.secret_redactor import SecretRedactor
1877
+ except Exception:
1878
+ return result
1879
+ total = 0
1880
+
1881
+ def _walk(node):
1882
+ nonlocal total
1883
+ if isinstance(node, str):
1884
+ red, n, _ = SecretRedactor.redact_text(node)
1885
+ if n:
1886
+ total += n
1887
+ return red
1888
+ if isinstance(node, dict):
1889
+ return {k: _walk(v) for k, v in node.items()}
1890
+ if isinstance(node, list):
1891
+ return [_walk(v) for v in node]
1892
+ return node
1893
+
1894
+ try:
1895
+ redacted = _walk(result)
1896
+ except Exception:
1897
+ return result
1898
+ if total:
1899
+ try:
1900
+ sys.stderr.write(f"[TokenSafe] MCP egress redaction: {total} secret occurrence(s) stripped from tool result\n")
1901
+ except Exception:
1902
+ pass
1903
+ return redacted
1904
+
1905
+
1867
1906
  def _execute_with_timeout(tool_name: str, tool_args: dict, timeout: float = MCP_TOOL_TIMEOUT) -> dict:
1868
1907
  """Runs handle_tool_call inside a daemon thread with hard timeout so stdio MCP never freezes."""
1869
1908
  box = {"result": None, "error": None}
@@ -1977,9 +2016,9 @@ def run_mcp_server():
1977
2016
  from src.json_repair import parse_tool_arguments
1978
2017
  tool_args = parse_tool_arguments(raw_tool_args) or {}
1979
2018
  try:
1980
- response["result"] = _execute_with_timeout(tool_name, tool_args)
2019
+ response["result"] = _redact_result_secrets(_execute_with_timeout(tool_name, tool_args))
1981
2020
  except Exception as e:
1982
- response["result"] = _fallback_error(tool_name, f"{type(e).__name__}: {str(e)}")
2021
+ response["result"] = _redact_result_secrets(_fallback_error(tool_name, f"{type(e).__name__}: {str(e)}"))
1983
2022
  finally:
1984
2023
  try:
1985
2024
  from src.telemetry_sync import TelemetrySync
package/src/proxy.py CHANGED
@@ -834,6 +834,10 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
834
834
  try:
835
835
  openai_payload = _translate_anthropic_payload_to_openai(payload)
836
836
  except Exception as e:
837
+ try:
838
+ sys.stderr.write(f"[TokenSafe][debug] translate fail body[:800]={json.dumps(payload)[:800]}\n")
839
+ except Exception:
840
+ pass
837
841
  self._send_json_error(400, f"Failed to translate Anthropic payload: {e}")
838
842
  return False
839
843
  self._client_shape = "anthropic"
@@ -879,6 +883,10 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
879
883
  return self.rfile.read(content_len)
880
884
 
881
885
  def _send_json_error(self, status_code: int, message: str):
886
+ try:
887
+ sys.stderr.write(f"[TokenSafe] {self.command} {self.path} -> {status_code}: {message}\n")
888
+ except Exception:
889
+ pass
882
890
  err_bytes = json.dumps({"error": message}).encode("utf-8")
883
891
  self.send_response(status_code)
884
892
  self.send_header("Content-Type", "application/json")
@@ -241,7 +241,7 @@ class TelemetrySync:
241
241
  current_last_id = last_id
242
242
  headers = {
243
243
  "Content-Type": "application/json",
244
- "User-Agent": "TokenSafe-Sync/4.2.0"
244
+ "User-Agent": "TokenSafe-Sync/4.2.1"
245
245
  }
246
246
  if active_key:
247
247
  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.2.0"
20
+ CURRENT_VERSION = "4.2.1"
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