tokensafe 4.2.11 → 4.2.13
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 +1 -1
- package/hooks/claude_code_hook.py +3 -3
- package/hooks/cursor_hook.py +2 -2
- package/hooks/kimi_hook.py +4 -4
- package/kimi.plugin.json +1 -1
- package/package.json +1 -1
- package/plugin.json +1 -1
- package/server.json +3 -3
- package/src/adapter_core.py +80 -7
- package/src/license_manager.py +6 -2
- package/src/live_relay.py +2 -1
- package/src/mcp_server.py +2 -2
- package/src/proxy.py +22 -1
- package/src/ssl_context.py +22 -0
- package/src/team_cache.py +4 -3
- package/src/telemetry_sync.py +22 -7
- package/src/treesitter_backend.py +24 -0
- package/src/version_checker.py +1 -1
|
@@ -92,7 +92,7 @@ def handle(event: str, payload: dict) -> dict:
|
|
|
92
92
|
}
|
|
93
93
|
return {}
|
|
94
94
|
|
|
95
|
-
context, meta = compact_for_injection(prompt, AGENT, session_id)
|
|
95
|
+
context, meta = compact_for_injection(prompt, AGENT, session_id, transcript_path=str(payload.get("transcript_path") or ""))
|
|
96
96
|
if context and meta.get("compacted"):
|
|
97
97
|
parts.append(
|
|
98
98
|
f"{context}\n"
|
|
@@ -160,7 +160,7 @@ def handle(event: str, payload: dict) -> dict:
|
|
|
160
160
|
tool_input = {}
|
|
161
161
|
if tool in ("Bash", "Shell", "bash"):
|
|
162
162
|
command = str(tool_input.get("command") or "")
|
|
163
|
-
verdict = guard_command(command, AGENT, session_id, cwd=str(payload.get("cwd") or ""))
|
|
163
|
+
verdict = guard_command(command, AGENT, session_id, cwd=str(payload.get("cwd") or ""), transcript_path=str(payload.get("transcript_path") or ""))
|
|
164
164
|
if verdict["decision"] == "deny":
|
|
165
165
|
return {
|
|
166
166
|
"hookSpecificOutput": {
|
|
@@ -183,7 +183,7 @@ def handle(event: str, payload: dict) -> dict:
|
|
|
183
183
|
file_path = str(tool_input.get("file_path") or tool_input.get("Path") or tool_input.get("path") or "")
|
|
184
184
|
content = tool_input.get("content") or tool_input.get("Content") or tool_input.get("file_text") or ""
|
|
185
185
|
append = bool(tool_input.get("append") or tool_input.get("Append") or False)
|
|
186
|
-
verdict = guard_write(file_path, str(content or ""), append, AGENT, session_id)
|
|
186
|
+
verdict = guard_write(file_path, str(content or ""), append, AGENT, session_id, transcript_path=str(payload.get("transcript_path") or ""))
|
|
187
187
|
if verdict["decision"] == "deny":
|
|
188
188
|
return {
|
|
189
189
|
"hookSpecificOutput": {
|
package/hooks/cursor_hook.py
CHANGED
|
@@ -42,7 +42,7 @@ def handle(event: str, payload: dict) -> dict:
|
|
|
42
42
|
|
|
43
43
|
if event == "beforeShellExecution":
|
|
44
44
|
command = str(payload.get("command") or "")
|
|
45
|
-
verdict = guard_command(command, AGENT, session_id, cwd=str(payload.get("cwd") or ""))
|
|
45
|
+
verdict = guard_command(command, AGENT, session_id, cwd=str(payload.get("cwd") or ""), transcript_path=str(payload.get("transcript_path") or ""))
|
|
46
46
|
if verdict["decision"] == "deny":
|
|
47
47
|
return {"permission": "deny", "user_message": verdict["reason"]}
|
|
48
48
|
if verdict["decision"] == "ask":
|
|
@@ -51,7 +51,7 @@ def handle(event: str, payload: dict) -> dict:
|
|
|
51
51
|
|
|
52
52
|
if event == "beforeReadFile":
|
|
53
53
|
file_path = str(payload.get("file_path") or "")
|
|
54
|
-
verdict = guard_read(file_path, AGENT, session_id)
|
|
54
|
+
verdict = guard_read(file_path, AGENT, session_id, transcript_path=str(payload.get("transcript_path") or ""))
|
|
55
55
|
if verdict["decision"] == "deny":
|
|
56
56
|
return {"permission": "deny", "user_message": verdict["reason"]}
|
|
57
57
|
return {"permission": "allow"}
|
package/hooks/kimi_hook.py
CHANGED
|
@@ -93,7 +93,7 @@ def handle(event: str, payload: dict) -> dict:
|
|
|
93
93
|
}
|
|
94
94
|
return {}
|
|
95
95
|
|
|
96
|
-
context, meta = compact_for_injection(prompt, AGENT, session_id)
|
|
96
|
+
context, meta = compact_for_injection(prompt, AGENT, session_id, transcript_path=str(payload.get("transcript_path") or ""))
|
|
97
97
|
if context and meta.get("compacted"):
|
|
98
98
|
parts.append(
|
|
99
99
|
f"{context}\n"
|
|
@@ -118,7 +118,7 @@ def handle(event: str, payload: dict) -> dict:
|
|
|
118
118
|
|
|
119
119
|
if tool in ("Bash", "Shell", "bash"):
|
|
120
120
|
command = str(tool_input.get("command") or "")
|
|
121
|
-
verdict = guard_command(command, AGENT, session_id, cwd=str(payload.get("cwd") or ""))
|
|
121
|
+
verdict = guard_command(command, AGENT, session_id, cwd=str(payload.get("cwd") or ""), transcript_path=str(payload.get("transcript_path") or ""))
|
|
122
122
|
if verdict["decision"] == "deny":
|
|
123
123
|
return {
|
|
124
124
|
"hookSpecificOutput": {
|
|
@@ -140,7 +140,7 @@ def handle(event: str, payload: dict) -> dict:
|
|
|
140
140
|
file_path = str(tool_input.get("file_path") or tool_input.get("Path") or tool_input.get("path") or "")
|
|
141
141
|
content = tool_input.get("content") or tool_input.get("Content") or tool_input.get("file_text") or ""
|
|
142
142
|
append = bool(tool_input.get("append") or tool_input.get("Append") or False)
|
|
143
|
-
verdict = guard_write(file_path, str(content or ""), append, AGENT, session_id)
|
|
143
|
+
verdict = guard_write(file_path, str(content or ""), append, AGENT, session_id, transcript_path=str(payload.get("transcript_path") or ""))
|
|
144
144
|
if verdict["decision"] == "deny":
|
|
145
145
|
return {
|
|
146
146
|
"hookSpecificOutput": {
|
|
@@ -160,7 +160,7 @@ def handle(event: str, payload: dict) -> dict:
|
|
|
160
160
|
|
|
161
161
|
elif tool in ("Read", "read_file", "view_file"):
|
|
162
162
|
file_path = str(tool_input.get("file_path") or tool_input.get("path") or tool_input.get("Path") or "")
|
|
163
|
-
verdict = guard_read(file_path, AGENT, session_id)
|
|
163
|
+
verdict = guard_read(file_path, AGENT, session_id, transcript_path=str(payload.get("transcript_path") or ""))
|
|
164
164
|
if verdict["decision"] == "deny":
|
|
165
165
|
return {
|
|
166
166
|
"hookSpecificOutput": {
|
package/kimi.plugin.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tokensafe",
|
|
3
|
-
"version": "4.2.
|
|
3
|
+
"version": "4.2.13",
|
|
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.2.
|
|
4
|
+
"version": "4.2.13",
|
|
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.2.
|
|
4
|
+
"version": "4.2.13",
|
|
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.2.
|
|
6
|
+
"version": "4.2.13",
|
|
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.2.
|
|
26
|
+
"version": "4.2.13",
|
|
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.2.
|
|
42
|
+
"version": "4.2.13",
|
|
43
43
|
"runtimeHint": "uvx",
|
|
44
44
|
"transport": {
|
|
45
45
|
"type": "stdio"
|
package/src/adapter_core.py
CHANGED
|
@@ -16,6 +16,7 @@ import os
|
|
|
16
16
|
import sys
|
|
17
17
|
import re
|
|
18
18
|
import json
|
|
19
|
+
import time
|
|
19
20
|
from typing import Dict, Any, Optional, Tuple
|
|
20
21
|
|
|
21
22
|
from src.tokenizer import count_tokens
|
|
@@ -100,7 +101,75 @@ def _get_tracker():
|
|
|
100
101
|
return None
|
|
101
102
|
|
|
102
103
|
|
|
103
|
-
|
|
104
|
+
# --- Model attribution -------------------------------------------------------
|
|
105
|
+
# Lifecycle hooks never receive the host model, so event details resolve it
|
|
106
|
+
# best-effort: 1) the session transcript (CC-family JSONL stores message.model
|
|
107
|
+
# on assistant entries — read the file tail only, cached by mtime so repeated
|
|
108
|
+
# hook invocations stay cheap), 2) the local proxy's state file (the proxy sees
|
|
109
|
+
# every request and stamps its last-seen model), 3) host env (MODEL /
|
|
110
|
+
# AGY_MODEL). Anything unknown stays "" — the landing feed renders "—" instead
|
|
111
|
+
# of a fabricated name (see telemetry_sync / record_telemetry).
|
|
112
|
+
_MODEL_TRANSCRIPT_CACHE: Dict[str, Tuple[float, str]] = {}
|
|
113
|
+
_PROXY_STATE_TTL_S = 600
|
|
114
|
+
_TRANSCRIPT_TAIL_BYTES = 262144
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _sniff_transcript_model(transcript_path: str) -> str:
|
|
118
|
+
path = str(transcript_path or "")
|
|
119
|
+
if not path:
|
|
120
|
+
return ""
|
|
121
|
+
try:
|
|
122
|
+
mtime = os.path.getmtime(path)
|
|
123
|
+
except OSError:
|
|
124
|
+
return ""
|
|
125
|
+
cached = _MODEL_TRANSCRIPT_CACHE.get(path)
|
|
126
|
+
if cached and cached[0] == mtime:
|
|
127
|
+
return cached[1]
|
|
128
|
+
model = ""
|
|
129
|
+
try:
|
|
130
|
+
with open(path, "rb") as f:
|
|
131
|
+
f.seek(0, os.SEEK_END)
|
|
132
|
+
size = f.tell()
|
|
133
|
+
f.seek(max(0, size - _TRANSCRIPT_TAIL_BYTES))
|
|
134
|
+
tail = f.read().decode("utf-8", errors="ignore")
|
|
135
|
+
for line in reversed(tail.splitlines()):
|
|
136
|
+
if '"model"' not in line:
|
|
137
|
+
continue
|
|
138
|
+
m = re.search(r'"model"\s*:\s*"([^"]+)"', line)
|
|
139
|
+
if m and m.group(1):
|
|
140
|
+
model = m.group(1)[:64]
|
|
141
|
+
break
|
|
142
|
+
except OSError:
|
|
143
|
+
model = ""
|
|
144
|
+
_MODEL_TRANSCRIPT_CACHE[path] = (mtime, model)
|
|
145
|
+
return model
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _read_proxy_state_model() -> str:
|
|
149
|
+
try:
|
|
150
|
+
from src.paths import resolve_data_dir
|
|
151
|
+
state_path = os.path.join(resolve_data_dir(), "proxy_state.json")
|
|
152
|
+
with open(state_path, "r", encoding="utf-8") as f:
|
|
153
|
+
state = json.load(f)
|
|
154
|
+
if time.time() - float(state.get("ts") or 0) > _PROXY_STATE_TTL_S:
|
|
155
|
+
return ""
|
|
156
|
+
return str(state.get("model") or "")[:64]
|
|
157
|
+
except Exception:
|
|
158
|
+
return ""
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def resolve_event_model(transcript_path: str = "", session_id: str = "") -> str:
|
|
162
|
+
"""Best-effort model attribution for recorded events. Fails open to ''."""
|
|
163
|
+
model = _sniff_transcript_model(transcript_path)
|
|
164
|
+
if model:
|
|
165
|
+
return model
|
|
166
|
+
model = _read_proxy_state_model()
|
|
167
|
+
if model:
|
|
168
|
+
return model
|
|
169
|
+
return os.environ.get("MODEL") or os.environ.get("AGY_MODEL") or ""
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def compact_for_injection(prompt: str, agent: str, session_id: str, transcript_path: str = "") -> Tuple[str, Dict[str, Any]]:
|
|
104
173
|
"""Compacts a user prompt into its TOCP form for context injection.
|
|
105
174
|
|
|
106
175
|
Returns (context_text, meta). context_text is '' when compaction is not
|
|
@@ -124,7 +193,8 @@ def compact_for_injection(prompt: str, agent: str, session_id: str) -> Tuple[str
|
|
|
124
193
|
event_type="PROMPT",
|
|
125
194
|
original_tokens=compaction["original_tokens"],
|
|
126
195
|
optimized_tokens=compaction["compact_tokens"],
|
|
127
|
-
details={"agent": agent, "mode": "hook_inject", "tier": compaction.get("tier", "REGEX")
|
|
196
|
+
details={"agent": agent, "mode": "hook_inject", "tier": compaction.get("tier", "REGEX"),
|
|
197
|
+
"model": resolve_event_model(transcript_path, session_id)},
|
|
128
198
|
)
|
|
129
199
|
except Exception:
|
|
130
200
|
pass
|
|
@@ -134,7 +204,7 @@ def compact_for_injection(prompt: str, agent: str, session_id: str) -> Tuple[str
|
|
|
134
204
|
return "", meta
|
|
135
205
|
|
|
136
206
|
|
|
137
|
-
def guard_command(command: str, agent: str, session_id: str = "", cwd: str = "") -> Dict[str, Any]:
|
|
207
|
+
def guard_command(command: str, agent: str, session_id: str = "", cwd: str = "", transcript_path: str = "") -> Dict[str, Any]:
|
|
138
208
|
"""Pre-execution shell guard. Returns:
|
|
139
209
|
{decision: allow|deny|ask, reason, saved_tokens} where saved_tokens is the
|
|
140
210
|
MEASURED mass of blocked output (0 for allowed commands)."""
|
|
@@ -154,7 +224,8 @@ def guard_command(command: str, agent: str, session_id: str = "", cwd: str = "")
|
|
|
154
224
|
event_type=f"GUARD_{kind}",
|
|
155
225
|
original_tokens=est,
|
|
156
226
|
optimized_tokens=0,
|
|
157
|
-
details={"agent": agent, "command": cmd[:120]
|
|
227
|
+
details={"agent": agent, "command": cmd[:120],
|
|
228
|
+
"model": resolve_event_model(transcript_path, session_id)},
|
|
158
229
|
)
|
|
159
230
|
except Exception:
|
|
160
231
|
pass
|
|
@@ -193,7 +264,7 @@ def guard_command(command: str, agent: str, session_id: str = "", cwd: str = "")
|
|
|
193
264
|
return result
|
|
194
265
|
|
|
195
266
|
|
|
196
|
-
def guard_read(file_path: str, agent: str, session_id: str = "") -> Dict[str, Any]:
|
|
267
|
+
def guard_read(file_path: str, agent: str, session_id: str = "", transcript_path: str = "") -> Dict[str, Any]:
|
|
197
268
|
"""Pre-read guard: denies lockfiles/bundles/dist junk that would burn the
|
|
198
269
|
context window. Blocked reads are recorded as measured savings."""
|
|
199
270
|
result = {"decision": "allow", "reason": "", "saved_tokens": 0}
|
|
@@ -211,7 +282,8 @@ def guard_read(file_path: str, agent: str, session_id: str = "") -> Dict[str, An
|
|
|
211
282
|
event_type="GUARD_JUNK_READ",
|
|
212
283
|
original_tokens=est,
|
|
213
284
|
optimized_tokens=0,
|
|
214
|
-
details={"agent": agent, "file": os.path.basename(normalized)
|
|
285
|
+
details={"agent": agent, "file": os.path.basename(normalized),
|
|
286
|
+
"model": resolve_event_model(transcript_path, session_id)},
|
|
215
287
|
)
|
|
216
288
|
except Exception:
|
|
217
289
|
pass
|
|
@@ -225,7 +297,7 @@ def guard_read(file_path: str, agent: str, session_id: str = "") -> Dict[str, An
|
|
|
225
297
|
return result
|
|
226
298
|
|
|
227
299
|
|
|
228
|
-
def guard_write(file_path: str, content: str, append: bool = False, agent: str = "", session_id: str = "") -> Dict[str, Any]:
|
|
300
|
+
def guard_write(file_path: str, content: str, append: bool = False, agent: str = "", session_id: str = "", transcript_path: str = "") -> Dict[str, Any]:
|
|
229
301
|
"""Pre-write egress guard (v3.0.0): full-file Write over an existing file
|
|
230
302
|
burns expensive OUTPUT tokens. Policy:
|
|
231
303
|
- new file / append / no content -> allow
|
|
@@ -273,6 +345,7 @@ def guard_write(file_path: str, content: str, append: bool = False, agent: str =
|
|
|
273
345
|
"existing_lines": len(existing_lines),
|
|
274
346
|
"delta_lines": delta_lines,
|
|
275
347
|
"decision": decision,
|
|
348
|
+
"model": resolve_event_model(transcript_path, session_id),
|
|
276
349
|
},
|
|
277
350
|
)
|
|
278
351
|
except Exception:
|
package/src/license_manager.py
CHANGED
|
@@ -17,6 +17,7 @@ import threading
|
|
|
17
17
|
from typing import Dict, Any, Tuple, Optional, List
|
|
18
18
|
|
|
19
19
|
from src.paths import resolve_data_dir
|
|
20
|
+
from src.ssl_context import shared_ssl_context
|
|
20
21
|
|
|
21
22
|
PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
22
23
|
DATA_DIR = resolve_data_dir()
|
|
@@ -226,7 +227,10 @@ class LicenseManager:
|
|
|
226
227
|
headers={"Content-Type": "application/json", "User-Agent": "TokenSafe/Community-License"},
|
|
227
228
|
method="POST"
|
|
228
229
|
)
|
|
229
|
-
|
|
230
|
+
# Shared SSL context: this runs in a daemon thread (session_start
|
|
231
|
+
# hook) that can outlive the main thread; a lazily created context
|
|
232
|
+
# there races OPENSSL_cleanup at interpreter exit (SIGSEGV).
|
|
233
|
+
with urllib.request.urlopen(req, timeout=2.5, context=shared_ssl_context()) as resp:
|
|
230
234
|
data = json.loads(resp.read().decode("utf-8") or "{}")
|
|
231
235
|
license_key = str(data.get("license_key", "") or "")
|
|
232
236
|
if resp.status != 200 or not data.get("success") or not license_key:
|
|
@@ -548,7 +552,7 @@ class LicenseManager:
|
|
|
548
552
|
headers={"Content-Type": "application/json", "User-Agent": "TokenSafe/Refresh"},
|
|
549
553
|
method="POST"
|
|
550
554
|
)
|
|
551
|
-
with urllib.request.urlopen(req, timeout=3.5) as resp:
|
|
555
|
+
with urllib.request.urlopen(req, timeout=3.5, context=shared_ssl_context()) as resp:
|
|
552
556
|
data = json.loads(resp.read().decode("utf-8") or "{}")
|
|
553
557
|
new_key = data.get("license_key", "")
|
|
554
558
|
if resp.status == 200 and data.get("success") and new_key:
|
package/src/live_relay.py
CHANGED
|
@@ -16,6 +16,7 @@ from collections import deque
|
|
|
16
16
|
from typing import Dict
|
|
17
17
|
|
|
18
18
|
from src.license_manager import LicenseManager
|
|
19
|
+
from src.ssl_context import shared_ssl_context
|
|
19
20
|
|
|
20
21
|
_MACHINE_HASH = ""
|
|
21
22
|
|
|
@@ -94,7 +95,7 @@ class LiveRelay:
|
|
|
94
95
|
"Authorization": f"Bearer {key}",
|
|
95
96
|
"User-Agent": "TokenSafe-LiveRelay/2.8",
|
|
96
97
|
}, method="POST")
|
|
97
|
-
with urllib.request.urlopen(req, timeout=4.0) as resp:
|
|
98
|
+
with urllib.request.urlopen(req, timeout=4.0, context=shared_ssl_context()) as resp:
|
|
98
99
|
resp.read()
|
|
99
100
|
except Exception:
|
|
100
101
|
pass # live telemetry is best-effort and must never block the proxy
|
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.
|
|
45
|
+
"version": "4.2.13"
|
|
46
46
|
}
|
|
47
47
|
|
|
48
48
|
# MCP client attribution: the initialize handshake carries clientInfo, which
|
|
@@ -2035,7 +2035,7 @@ def run_mcp_server():
|
|
|
2035
2035
|
finally:
|
|
2036
2036
|
try:
|
|
2037
2037
|
from src.telemetry_sync import TelemetrySync
|
|
2038
|
-
TelemetrySync.sync_background(throttle_seconds=
|
|
2038
|
+
TelemetrySync.sync_background(throttle_seconds=5.0)
|
|
2039
2039
|
except Exception:
|
|
2040
2040
|
pass
|
|
2041
2041
|
else:
|
package/src/proxy.py
CHANGED
|
@@ -668,12 +668,33 @@ class _AnthropicSSETranslator:
|
|
|
668
668
|
}
|
|
669
669
|
return (b"data: " + json.dumps(payload, ensure_ascii=False).encode("utf-8") + b"\n\n")
|
|
670
670
|
|
|
671
|
+
def _touch_proxy_model_state(self, model: str) -> None:
|
|
672
|
+
"""Persists the last-seen model so hook-side attribution can read it:
|
|
673
|
+
adapters resolve event models from ~/.tokensafe/data/proxy_state.json
|
|
674
|
+
because lifecycle hosts never pass the model to hooks. Throttled to one
|
|
675
|
+
write per 30s (or on model change); never raises."""
|
|
676
|
+
now = time.time()
|
|
677
|
+
if model == getattr(self, "_model_state_model", "") and now - getattr(self, "_model_state_ts", 0.0) < 30.0:
|
|
678
|
+
return
|
|
679
|
+
try:
|
|
680
|
+
from src.paths import resolve_data_dir
|
|
681
|
+
state_path = os.path.join(resolve_data_dir(), "proxy_state.json")
|
|
682
|
+
tmp = f"{state_path}.tmp.{os.getpid()}"
|
|
683
|
+
with open(tmp, "w", encoding="utf-8") as f:
|
|
684
|
+
json.dump({"model": str(model or "")[:64], "ts": now}, f)
|
|
685
|
+
os.replace(tmp, state_path)
|
|
686
|
+
self._model_state_ts = now
|
|
687
|
+
self._model_state_model = model
|
|
688
|
+
except Exception:
|
|
689
|
+
pass
|
|
690
|
+
|
|
671
691
|
def _handle_event(self, event: str, data: Dict[str, Any]) -> bytes:
|
|
672
692
|
out = b""
|
|
673
693
|
if event == "message_start":
|
|
674
694
|
msg = data.get("message") or {}
|
|
675
695
|
if msg.get("model"):
|
|
676
696
|
self.model = msg["model"]
|
|
697
|
+
self._touch_proxy_model_state(str(self.model))
|
|
677
698
|
self._usage_in = int((msg.get("usage") or {}).get("input_tokens") or 0)
|
|
678
699
|
out += self._chunk({"role": "assistant", "content": ""})
|
|
679
700
|
elif event == "content_block_start":
|
|
@@ -1011,7 +1032,7 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
|
|
|
1011
1032
|
measurement="measured", # bytes literally swapped
|
|
1012
1033
|
)
|
|
1013
1034
|
from src.telemetry_sync import TelemetrySync
|
|
1014
|
-
TelemetrySync.sync_background(throttle_seconds=
|
|
1035
|
+
TelemetrySync.sync_background(throttle_seconds=5.0)
|
|
1015
1036
|
except Exception:
|
|
1016
1037
|
pass
|
|
1017
1038
|
target_symbol = compaction.get("symbol")
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"""Shared SSL context, created once on the importing (main) thread.
|
|
2
|
+
|
|
3
|
+
Short-lived hook processes exit while daemon threads (live-relay flush,
|
|
4
|
+
team-cache put) are still opening HTTPS. With urllib's default handler
|
|
5
|
+
each thread lazily builds its own SSLContext, and on Python 3.13 +
|
|
6
|
+
OpenSSL 3.x that lazy set_default_verify_paths can collide with
|
|
7
|
+
OPENSSL_cleanup running on the main thread during interpreter shutdown
|
|
8
|
+
(observed as SIGSEGV in pthread_rwlock_wrlock from EVP_PKEY_asn1_find_str
|
|
9
|
+
while the main thread is already in exit()). Sharing one pre-created
|
|
10
|
+
context removes the lazy per-thread store mutation entirely, and importing
|
|
11
|
+
this module also warms the OpenSSL store on the main thread before any
|
|
12
|
+
daemon thread starts.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
import ssl
|
|
16
|
+
|
|
17
|
+
_CONTEXT = ssl.create_default_context()
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def shared_ssl_context() -> ssl.SSLContext:
|
|
21
|
+
"""Returns the process-wide SSLContext (safe to share across threads)."""
|
|
22
|
+
return _CONTEXT
|
package/src/team_cache.py
CHANGED
|
@@ -14,6 +14,7 @@ import urllib.error
|
|
|
14
14
|
import urllib.parse
|
|
15
15
|
from typing import Optional, Dict, Any, Tuple
|
|
16
16
|
from src.license_manager import LicenseManager
|
|
17
|
+
from src.ssl_context import shared_ssl_context
|
|
17
18
|
|
|
18
19
|
class TeamCache:
|
|
19
20
|
"""Distributed cross-developer cache client for TokenSafe Team tier."""
|
|
@@ -105,7 +106,7 @@ class TeamCache:
|
|
|
105
106
|
|
|
106
107
|
eff_timeout = cls.DEFAULT_TIMEOUT if timeout is None else max(0.05, float(timeout))
|
|
107
108
|
try:
|
|
108
|
-
with urllib.request.urlopen(req, timeout=eff_timeout) as resp:
|
|
109
|
+
with urllib.request.urlopen(req, timeout=eff_timeout, context=shared_ssl_context()) as resp:
|
|
109
110
|
if resp.status == 200:
|
|
110
111
|
data = json.loads(resp.read().decode("utf-8"))
|
|
111
112
|
val = data.get("value") or data.get("cached_value")
|
|
@@ -176,7 +177,7 @@ class TeamCache:
|
|
|
176
177
|
}
|
|
177
178
|
)
|
|
178
179
|
try:
|
|
179
|
-
with urllib.request.urlopen(req, timeout=1.5):
|
|
180
|
+
with urllib.request.urlopen(req, timeout=1.5, context=shared_ssl_context()):
|
|
180
181
|
cls._clear_cooldown(cloud_url)
|
|
181
182
|
except urllib.error.HTTPError as he:
|
|
182
183
|
if he.code in (401, 403) or he.code >= 500:
|
|
@@ -200,7 +201,7 @@ class TeamCache:
|
|
|
200
201
|
headers={"Authorization": f"Bearer {lic_key}", "User-Agent": "TokenSafe-TeamCache/1.0"}
|
|
201
202
|
)
|
|
202
203
|
try:
|
|
203
|
-
with urllib.request.urlopen(req, timeout=max(2.5, cls.DEFAULT_TIMEOUT)) as resp:
|
|
204
|
+
with urllib.request.urlopen(req, timeout=max(2.5, cls.DEFAULT_TIMEOUT), context=shared_ssl_context()) as resp:
|
|
204
205
|
if resp.status == 200:
|
|
205
206
|
res = json.loads(resp.read().decode("utf-8"))
|
|
206
207
|
res["active"] = True
|
package/src/telemetry_sync.py
CHANGED
|
@@ -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.
|
|
244
|
+
"User-Agent": "TokenSafe-Sync/4.2.13"
|
|
245
245
|
}
|
|
246
246
|
if active_key:
|
|
247
247
|
headers["Authorization"] = f"Bearer {active_key}"
|
|
@@ -350,12 +350,22 @@ class TelemetrySync:
|
|
|
350
350
|
except Exception:
|
|
351
351
|
ts_int = int(time.time())
|
|
352
352
|
|
|
353
|
-
|
|
353
|
+
# Model attribution: event details win, then host-provided env
|
|
354
|
+
# (AGY_MODEL / MODEL). No hardcoded default — hook-path events
|
|
355
|
+
# genuinely don't know the model unless the host exposes it,
|
|
356
|
+
# and an empty value renders as "—" instead of lying.
|
|
357
|
+
model_name = os.environ.get("AGY_MODEL") or os.environ.get("MODEL") or ""
|
|
358
|
+
# Agent attribution fills the landing feed's model column when
|
|
359
|
+
# the model itself is unknown (details.agent is always present
|
|
360
|
+
# on hook-recorded events).
|
|
361
|
+
agent_name = ""
|
|
354
362
|
if r["details"]:
|
|
355
363
|
try:
|
|
356
364
|
det = json.loads(r["details"]) if isinstance(r["details"], str) else r["details"]
|
|
357
|
-
if isinstance(det, dict)
|
|
358
|
-
|
|
365
|
+
if isinstance(det, dict):
|
|
366
|
+
if det.get("model"):
|
|
367
|
+
model_name = str(det["model"])
|
|
368
|
+
agent_name = str(det.get("agent") or "")
|
|
359
369
|
except Exception:
|
|
360
370
|
pass
|
|
361
371
|
|
|
@@ -365,6 +375,7 @@ class TelemetrySync:
|
|
|
365
375
|
"saved_tokens": int(r["saved_tokens"] or 0),
|
|
366
376
|
"usd_saved": float(r["est_usd_saved"] or 0.0),
|
|
367
377
|
"model": model_name,
|
|
378
|
+
"agent": agent_name,
|
|
368
379
|
"timestamp": ts_int,
|
|
369
380
|
"measurement": resolve_measurement(str(r["event_type"] or "PROMPT"), r["measurement"])
|
|
370
381
|
}))
|
|
@@ -485,11 +496,15 @@ class TelemetrySync:
|
|
|
485
496
|
return cls._is_pid_alive(pid)
|
|
486
497
|
|
|
487
498
|
@classmethod
|
|
488
|
-
def sync_background(cls, throttle_seconds: float =
|
|
499
|
+
def sync_background(cls, throttle_seconds: float = 5.0, force: bool = False):
|
|
489
500
|
"""
|
|
490
501
|
Spawns a detached, non-blocking background OS process to sync metrics.
|
|
491
|
-
Throttled to run at most once every `throttle_seconds` (default:
|
|
492
|
-
|
|
502
|
+
Throttled to run at most once every `throttle_seconds` (default: 5s) so
|
|
503
|
+
cloud-side live feeds (public network panel, dashboards) reflect fresh
|
|
504
|
+
events within seconds instead of tens of seconds. Sync only fires when
|
|
505
|
+
pending events exist, and failure backoff (2^n up to 300s) still guards
|
|
506
|
+
flaky connections, so the tighter cadence adds no idle traffic.
|
|
507
|
+
Uses persistent state from sync_state.json.
|
|
493
508
|
Detached from parent process group so it survives the termination of short-lived CLI lifecycle hooks.
|
|
494
509
|
"""
|
|
495
510
|
if _telemetry_disabled():
|
|
@@ -8,11 +8,14 @@ languages:
|
|
|
8
8
|
|
|
9
9
|
All language grammars are standard mandatory dependencies with pre-compiled wheels.
|
|
10
10
|
Fail-safe fallback to stdlib ast / regex lexer is preserved if a grammar cannot load.
|
|
11
|
+
Isolated runs (`python -I` / `-s`, sanitized env) hide user site-packages where the
|
|
12
|
+
wheels usually live; the backend probes that directory explicitly before degrading.
|
|
11
13
|
"""
|
|
12
14
|
|
|
13
15
|
import importlib
|
|
14
16
|
import os
|
|
15
17
|
import re
|
|
18
|
+
import sys
|
|
16
19
|
from typing import Any, Callable, Dict, List, Optional, Set, Tuple
|
|
17
20
|
|
|
18
21
|
# Extension -> (module_name, loader_attr)
|
|
@@ -134,6 +137,22 @@ class TreeSitterBackend:
|
|
|
134
137
|
flag = os.environ.get("TOKENSAFE_TREESITTER", "auto").strip().lower()
|
|
135
138
|
return flag not in ("0", "false", "off", "no", "disabled")
|
|
136
139
|
|
|
140
|
+
@staticmethod
|
|
141
|
+
def _probe_user_site() -> bool:
|
|
142
|
+
"""Isolated runs (`python -I` / `-s`) skip user site-packages, where the
|
|
143
|
+
grammar wheels typically live. If that directory exists on disk but is
|
|
144
|
+
missing from sys.path, append it so the lazy imports can recover."""
|
|
145
|
+
try:
|
|
146
|
+
import site
|
|
147
|
+
|
|
148
|
+
user_sp = site.getusersitepackages()
|
|
149
|
+
except Exception:
|
|
150
|
+
return False
|
|
151
|
+
if user_sp and os.path.isdir(user_sp) and user_sp not in sys.path:
|
|
152
|
+
sys.path.append(user_sp)
|
|
153
|
+
return True
|
|
154
|
+
return False
|
|
155
|
+
|
|
137
156
|
@classmethod
|
|
138
157
|
def is_available(cls) -> bool:
|
|
139
158
|
if not cls.is_enabled():
|
|
@@ -144,6 +163,11 @@ class TreeSitterBackend:
|
|
|
144
163
|
cls._ts_mod = importlib.import_module("tree_sitter")
|
|
145
164
|
except Exception:
|
|
146
165
|
cls._ts_mod = None
|
|
166
|
+
try:
|
|
167
|
+
if cls._probe_user_site():
|
|
168
|
+
cls._ts_mod = importlib.import_module("tree_sitter")
|
|
169
|
+
except Exception:
|
|
170
|
+
cls._ts_mod = None
|
|
147
171
|
return cls._ts_mod is not None
|
|
148
172
|
|
|
149
173
|
@classmethod
|
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.2.
|
|
20
|
+
CURRENT_VERSION = "4.2.13"
|
|
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
|