tokensafe 4.6.3 → 4.7.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.
- package/.codex-plugin/plugin.json +2 -2
- package/LICENSE +202 -21
- package/README.md +44 -7
- package/hooks/claude_code_hook.py +24 -2
- package/hooks/kimi_hook.py +20 -0
- package/hooks/pre_invocation.py +7 -12
- package/hooks/session_start.py +8 -0
- package/kimi.plugin.json +2 -2
- package/package.json +2 -2
- package/plugin.json +2 -1
- package/server.json +3 -3
- package/src/acp/__init__.py +15 -0
- package/src/acp/server.py +328 -0
- package/src/adapter_core.py +22 -3
- package/src/agent/__init__.py +11 -0
- package/src/agent/context.py +99 -0
- package/src/agent/loop.py +385 -0
- package/src/agent/pricing.py +77 -0
- package/src/agent/providers.py +486 -0
- package/src/agent/tools.py +98 -0
- package/src/auto_inject.py +517 -0
- package/src/bench/__init__.py +1 -0
- package/src/bench/driver.py +219 -0
- package/src/bench/go_target.py +360 -0
- package/src/bench/react_target.py +234 -0
- package/src/bench/runner.py +247 -0
- package/src/cli.py +244 -5
- package/src/command_sanitizer.py +54 -0
- package/src/guard.py +63 -10
- package/src/history_compactor.py +200 -2
- package/src/mcp_server.py +65 -13
- package/src/paths.py +99 -2
- package/src/retrofit.py +91 -4
- package/src/savings.py +81 -0
- package/src/scaffold.py +190 -8
- package/src/session_brief.py +154 -0
- package/src/session_context.py +124 -0
- package/src/telemetry_sync.py +93 -25
- package/src/version_checker.py +1 -1
- package/hooks/__pycache__/claude_code_hook.cpython-312.pyc +0 -0
- package/hooks/__pycache__/cursor_hook.cpython-312.pyc +0 -0
- package/hooks/__pycache__/kimi_hook.cpython-312.pyc +0 -0
- package/hooks/__pycache__/pre_invocation.cpython-312.pyc +0 -0
- package/hooks/__pycache__/pre_tool_use.cpython-312.pyc +0 -0
- package/hooks/__pycache__/session_start.cpython-312.pyc +0 -0
- package/hooks/__pycache__/stop_hook.cpython-312.pyc +0 -0
- package/hooks/__pycache__/zcode_hook.cpython-312.pyc +0 -0
|
@@ -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)
|
package/src/telemetry_sync.py
CHANGED
|
@@ -67,6 +67,47 @@ def _sync_state_path() -> str:
|
|
|
67
67
|
return os.path.join(_data_dir(), "sync_state.json")
|
|
68
68
|
|
|
69
69
|
|
|
70
|
+
_ROLLUP_WATERMARK_KEYS = (
|
|
71
|
+
"last_synced_rollup_tokens",
|
|
72
|
+
"last_synced_rollup_orig",
|
|
73
|
+
"last_synced_rollup_usd",
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _sync_meta_read(db_path: str, key: str) -> Optional[str]:
|
|
78
|
+
"""Reads a durable sync marker from the metrics DB (survives state-file loss)."""
|
|
79
|
+
try:
|
|
80
|
+
with closing(sqlite3.connect(db_path, timeout=5.0)) as conn:
|
|
81
|
+
conn.execute("PRAGMA busy_timeout=3000")
|
|
82
|
+
row = conn.execute("SELECT value FROM sync_meta WHERE key = ?", (key,)).fetchone()
|
|
83
|
+
return str(row[0]) if row and row[0] is not None else None
|
|
84
|
+
except Exception:
|
|
85
|
+
return None
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _sync_meta_write(db_path: str, values: Dict[str, Any]) -> None:
|
|
89
|
+
"""Persists durable sync markers next to the events they describe (best effort)."""
|
|
90
|
+
if not values:
|
|
91
|
+
return
|
|
92
|
+
for _attempt in range(2):
|
|
93
|
+
try:
|
|
94
|
+
with closing(sqlite3.connect(db_path, timeout=5.0)) as conn:
|
|
95
|
+
# The sync loop holds a read connection open while paging.
|
|
96
|
+
conn.execute("PRAGMA busy_timeout=3000")
|
|
97
|
+
conn.execute("CREATE TABLE IF NOT EXISTS sync_meta (key TEXT PRIMARY KEY, value TEXT NOT NULL)")
|
|
98
|
+
conn.executemany(
|
|
99
|
+
"INSERT INTO sync_meta (key, value) VALUES (?, ?) "
|
|
100
|
+
"ON CONFLICT(key) DO UPDATE SET value = excluded.value",
|
|
101
|
+
[(k, str(v)) for k, v in values.items()],
|
|
102
|
+
)
|
|
103
|
+
conn.commit()
|
|
104
|
+
return
|
|
105
|
+
except sqlite3.OperationalError:
|
|
106
|
+
time.sleep(0.2)
|
|
107
|
+
except Exception:
|
|
108
|
+
return
|
|
109
|
+
|
|
110
|
+
|
|
70
111
|
def _sync_lock_path() -> str:
|
|
71
112
|
if SYNC_LOCK_PATH != _DEFAULT_SYNC_LOCK_PATH:
|
|
72
113
|
return SYNC_LOCK_PATH
|
|
@@ -93,31 +134,52 @@ class TelemetrySync:
|
|
|
93
134
|
|
|
94
135
|
@classmethod
|
|
95
136
|
def get_state(cls) -> Dict[str, Any]:
|
|
96
|
-
"""Loads sync cursor state from
|
|
137
|
+
"""Loads sync cursor state, overlaying durable watermarks from the metrics DB.
|
|
138
|
+
|
|
139
|
+
sync_state.json is easy to lose (fresh data dir, manual cleanup), and losing it
|
|
140
|
+
makes the client replay its whole lifetime rollup, which the server cannot tell
|
|
141
|
+
apart from real usage. The metrics DB survives, so the larger watermark wins.
|
|
142
|
+
"""
|
|
97
143
|
state_path = _sync_state_path()
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
144
|
+
state: Dict[str, Any] = {
|
|
145
|
+
"last_synced_event_id": 0,
|
|
146
|
+
"last_synced_at": 0,
|
|
147
|
+
"total_synced_events": 0,
|
|
148
|
+
"lifetime_rollup_synced": False,
|
|
149
|
+
}
|
|
150
|
+
if os.path.exists(state_path):
|
|
151
|
+
try:
|
|
152
|
+
with open(state_path, "r", encoding="utf-8") as f:
|
|
153
|
+
loaded = json.load(f)
|
|
154
|
+
if isinstance(loaded, dict):
|
|
155
|
+
state.update(loaded)
|
|
156
|
+
except Exception:
|
|
157
|
+
pass
|
|
158
|
+
|
|
159
|
+
db_path = _metrics_db_path()
|
|
160
|
+
durable_rollup = False
|
|
161
|
+
for key in _ROLLUP_WATERMARK_KEYS:
|
|
162
|
+
raw = _sync_meta_read(db_path, key)
|
|
163
|
+
if raw is None:
|
|
164
|
+
continue
|
|
165
|
+
try:
|
|
166
|
+
durable = float(raw) if key.endswith("_usd") else int(float(raw))
|
|
167
|
+
except (TypeError, ValueError):
|
|
168
|
+
continue
|
|
169
|
+
if durable > 0:
|
|
170
|
+
durable_rollup = True
|
|
171
|
+
current = state.get(key)
|
|
172
|
+
try:
|
|
173
|
+
current_val: Optional[float] = (
|
|
174
|
+
float(current) if key.endswith("_usd") else int(float(current))
|
|
175
|
+
) if current is not None else None
|
|
176
|
+
except (TypeError, ValueError):
|
|
177
|
+
current_val = None
|
|
178
|
+
if current_val is None or durable > current_val:
|
|
179
|
+
state[key] = durable
|
|
180
|
+
if durable_rollup:
|
|
181
|
+
state["lifetime_rollup_synced"] = True
|
|
182
|
+
return state
|
|
121
183
|
|
|
122
184
|
@classmethod
|
|
123
185
|
def save_state(cls, state: Dict[str, Any]):
|
|
@@ -249,7 +311,7 @@ class TelemetrySync:
|
|
|
249
311
|
current_last_id = last_id
|
|
250
312
|
headers = {
|
|
251
313
|
"Content-Type": "application/json",
|
|
252
|
-
"User-Agent": "TokenSafe-Sync/4.
|
|
314
|
+
"User-Agent": "TokenSafe-Sync/4.7.0"
|
|
253
315
|
}
|
|
254
316
|
if active_key:
|
|
255
317
|
headers["Authorization"] = f"Bearer {active_key}"
|
|
@@ -472,6 +534,12 @@ class TelemetrySync:
|
|
|
472
534
|
last_synced_rollup = current_rollup_tokens
|
|
473
535
|
last_synced_rollup_orig = current_rollup_orig
|
|
474
536
|
last_synced_rollup_usd = current_rollup_usd
|
|
537
|
+
# Durable copy: survives deletion/corruption of sync_state.json.
|
|
538
|
+
_sync_meta_write(db_path, {
|
|
539
|
+
"last_synced_rollup_tokens": last_synced_rollup,
|
|
540
|
+
"last_synced_rollup_orig": last_synced_rollup_orig,
|
|
541
|
+
"last_synced_rollup_usd": last_synced_rollup_usd,
|
|
542
|
+
})
|
|
475
543
|
cls.save_state({
|
|
476
544
|
"last_synced_event_id": current_last_id,
|
|
477
545
|
"last_synced_at": int(time.time()),
|
package/src/version_checker.py
CHANGED
|
@@ -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.
|
|
20
|
+
CURRENT_VERSION = "4.7.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
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|