tokensafe 4.6.4 → 4.7.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.
Files changed (44) hide show
  1. package/.codex-plugin/plugin.json +2 -2
  2. package/LICENSE +202 -21
  3. package/README.md +30 -4
  4. package/hooks/claude_code_hook.py +17 -15
  5. package/hooks/kimi_hook.py +14 -12
  6. package/hooks/pre_invocation.py +7 -12
  7. package/hooks/session_start.py +8 -2
  8. package/kimi.plugin.json +2 -2
  9. package/package.json +2 -2
  10. package/plugin.json +2 -1
  11. package/rules/AGENTS.md +1 -1
  12. package/server.json +3 -3
  13. package/src/acp/__init__.py +15 -0
  14. package/src/acp/server.py +328 -0
  15. package/src/adapter_core.py +2 -1
  16. package/src/agent/__init__.py +11 -0
  17. package/src/agent/context.py +99 -0
  18. package/src/agent/loop.py +385 -0
  19. package/src/agent/pricing.py +77 -0
  20. package/src/agent/providers.py +486 -0
  21. package/src/agent/tools.py +98 -0
  22. package/src/agent_firewall.py +16 -1
  23. package/src/auto_inject.py +93 -7
  24. package/src/batch_editor.py +106 -15
  25. package/src/bench/__init__.py +1 -0
  26. package/src/bench/driver.py +234 -0
  27. package/src/bench/go_target.py +646 -0
  28. package/src/bench/mechanics.py +214 -0
  29. package/src/bench/react_target.py +541 -0
  30. package/src/bench/runner.py +331 -0
  31. package/src/bench/tokensafe_mcp.py +144 -0
  32. package/src/cli.py +156 -0
  33. package/src/history_compactor.py +200 -2
  34. package/src/installer.py +3 -3
  35. package/src/mcp_server.py +510 -237
  36. package/src/paths.py +41 -2
  37. package/src/retrofit.py +27 -5
  38. package/src/scaffold.py +8 -6
  39. package/src/scoped_search.py +67 -5
  40. package/src/session_brief.py +180 -15
  41. package/src/session_context.py +124 -0
  42. package/src/skeletonizer.py +9 -3
  43. package/src/telemetry_sync.py +1 -1
  44. package/src/version_checker.py +1 -1
@@ -0,0 +1,124 @@
1
+ """Explicit per-session state: workspace root + metrics session id.
2
+
3
+ TokenSafe historically resolved both from process-global state: the machine-wide
4
+ ``~/.tokensafe/data/.active_workspace`` marker and the module-level MCP client
5
+ name. That is fine for a one-shot hook process, but it breaks as soon as a
6
+ single process owns several sessions — the MCP server serving two editor
7
+ windows, or the ACP agent server running one prompt per thread. A search that
8
+ is demonstrably scoped to repo A gets validated against repo B (or a leftover
9
+ temp directory) and rejected as "outside project root".
10
+
11
+ This module makes the context explicit and cheap:
12
+
13
+ * ``SessionContext`` is immutable and carries root + session id + agent.
14
+ * ``session_scope(...)`` binds it to the current thread/task via a
15
+ ContextVar, so it propagates through the call stack without threading a
16
+ parameter through every handler.
17
+ * Consumers call ``current_root()`` / ``current_session_id(default)`` and
18
+ fall back to the legacy global marker only when no scope is active, which
19
+ keeps hook processes behaving exactly as before.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import os
25
+ from contextlib import contextmanager
26
+ from contextvars import ContextVar, Token
27
+ from dataclasses import dataclass, field
28
+ from typing import Any, Dict, Iterator, Optional
29
+
30
+
31
+ @dataclass(frozen=True)
32
+ class SessionContext:
33
+ """One agent session: where it works and how its metrics are keyed."""
34
+
35
+ session_id: str = "ephemeral"
36
+ root: Optional[str] = None
37
+ agent: str = ""
38
+ data: Dict[str, Any] = field(default_factory=dict)
39
+
40
+ def __post_init__(self) -> None:
41
+ if self.root:
42
+ object.__setattr__(self, "root", os.path.realpath(os.path.abspath(self.root)))
43
+
44
+ @property
45
+ def valid_root(self) -> Optional[str]:
46
+ """Root only if it still exists on disk (temp dirs may be gone)."""
47
+ root = self.root
48
+ return root if root and os.path.isdir(root) else None
49
+
50
+
51
+ _CURRENT: ContextVar[Optional[SessionContext]] = ContextVar(
52
+ "tokensafe_session_context", default=None
53
+ )
54
+
55
+
56
+ def current() -> Optional[SessionContext]:
57
+ """The active session context, or None when running outside a scope."""
58
+ return _CURRENT.get()
59
+
60
+
61
+ def current_root() -> Optional[str]:
62
+ """Active workspace root, or None when no scope is bound."""
63
+ ctx = _CURRENT.get()
64
+ return ctx.valid_root if ctx else None
65
+
66
+
67
+ def current_session_id(default: str = "") -> str:
68
+ """Active session id, or ``default`` when no scope is bound."""
69
+ ctx = _CURRENT.get()
70
+ if ctx and ctx.session_id:
71
+ return ctx.session_id
72
+ return default
73
+
74
+
75
+ def activate(ctx: SessionContext) -> Token:
76
+ """Bind ``ctx`` to the current context; returns a token for ``deactivate``."""
77
+ return _CURRENT.set(ctx)
78
+
79
+
80
+ def deactivate(token: Token) -> None:
81
+ """Restore the previous context. Always pair with ``activate`` in ``finally``."""
82
+ _CURRENT.reset(token)
83
+
84
+
85
+ @contextmanager
86
+ def session_scope(
87
+ root: Optional[str] = None,
88
+ session_id: str = "ephemeral",
89
+ agent: str = "",
90
+ data: Optional[Dict[str, Any]] = None,
91
+ ) -> Iterator[SessionContext]:
92
+ """Bind a session for the duration of the block.
93
+
94
+ Threads do not inherit ContextVars, so a worker must open its own scope
95
+ (the ACP server does this per prompt).
96
+ """
97
+ ctx = SessionContext(
98
+ session_id=session_id or "ephemeral",
99
+ root=root,
100
+ agent=agent,
101
+ data=dict(data or {}),
102
+ )
103
+ token = _CURRENT.set(ctx)
104
+ try:
105
+ yield ctx
106
+ finally:
107
+ _CURRENT.reset(token)
108
+
109
+
110
+ def resolve_path(path: str, root: Optional[str] = None) -> str:
111
+ """Resolve ``path`` against an explicit root, then the active session root.
112
+
113
+ Absolute paths pass through unchanged. Unlike ``os.path.abspath`` this never
114
+ silently resolves against the process cwd, which is what the MCP server's
115
+ global-marker fallback used to do.
116
+ """
117
+ if not path or os.path.isabs(path):
118
+ return path
119
+ base = root or current_root()
120
+ if base:
121
+ candidate = os.path.join(base, path)
122
+ if os.path.exists(candidate):
123
+ return os.path.abspath(candidate)
124
+ return os.path.abspath(path)
@@ -119,6 +119,12 @@ class BraceLexer:
119
119
  class Skeletonizer:
120
120
  """Generates structural AST skeletons without LLMs with incremental mtime caching."""
121
121
 
122
+ # Below this size a skeleton costs MORE than it saves: the caller asked for the
123
+ # file, gets only signatures, and has to spend a second call to read the body it
124
+ # needed — measured in the OUMV agent matrix (a 155-line Go app: 727-char skeleton
125
+ # + 3,209-char re-read vs 3,200-char raw read in one call). Above it, folding wins.
126
+ MIN_SKELETON_LINES = 200
127
+
122
128
  # Design-token selectors matched on word boundaries so class names like
123
129
  # `.html-widget` or identifiers like `innerHTML` no longer masquerade as tokens.
124
130
  TOKEN_SELECTOR_REGEX = re.compile(r'(?<![\w.#-])(?::root|@theme|html|body)(?![\w-])')
@@ -782,7 +788,7 @@ class Skeletonizer:
782
788
  return None, 0, 0
783
789
 
784
790
  lines_count = len(code.splitlines())
785
- if lines_count < 150:
791
+ if lines_count < cls.MIN_SKELETON_LINES:
786
792
  return None, 0, 0
787
793
 
788
794
  ext = os.path.splitext(original_path)[1]
@@ -822,10 +828,10 @@ class Skeletonizer:
822
828
  else:
823
829
  header_comment = (
824
830
  f"// [TOCP AST Skeleton: {lines_count} lines folded into API signatures]\n"
825
- f"// [To inspect implementation of a specific method, call read_file with StartLine/EndLine]\n\n"
831
+ f"// [For one symbol's body call smart_read_file(symbol=...); for a range call smart_read_file(start_line=, end_line=)]\n\n"
826
832
  ) if ext != ".py" else (
827
833
  f"# [TOCP AST Skeleton: {lines_count} lines folded into API signatures]\n"
828
- f"# [To inspect implementation of a specific method, call read_file with StartLine/EndLine]\n\n"
834
+ f"# [For one symbol's body call smart_read_file(symbol=...); for a range call smart_read_file(start_line=, end_line=)]\n\n"
829
835
  )
830
836
 
831
837
  full_content = header_comment + (prefetch_block + "\n" if prefetch_block else "") + skeleton_content
@@ -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.6.4"
314
+ "User-Agent": "TokenSafe-Sync/4.7.1"
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.6.4"
20
+ CURRENT_VERSION = "4.7.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