tokensafe 4.2.10 → 4.2.12
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/mcp_server.py +1 -1
- package/src/proxy.py +21 -0
- package/src/telemetry_sync.py +15 -4
- package/src/tokenizer.py +21 -15
- 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.12",
|
|
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.12",
|
|
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.12",
|
|
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.12",
|
|
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.12",
|
|
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.12",
|
|
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/mcp_server.py
CHANGED
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":
|
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.12"
|
|
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
|
}))
|
package/src/tokenizer.py
CHANGED
|
@@ -33,6 +33,16 @@ class TokenCounter:
|
|
|
33
33
|
r"""'s|'t|'re|'ve|'m|'ll|'d|[a-zA-Z\u00C0-\u024F\u0400-\u04FF_]+|\d{1,3}|[\u3400-\u4DBF\u4E00-\u9FFF\uF900-\uFAFF\u3040-\u30FF\u31F0-\u31FF\uAC00-\uD7AF]+|[^\w\s]+|\s+"""
|
|
34
34
|
)
|
|
35
35
|
|
|
36
|
+
# Script detection via C-level regex scans — replaces per-char Python loops
|
|
37
|
+
# that previously dominated the hot path (~46% of runtime on mixed text).
|
|
38
|
+
_CYRILLIC_RE = re.compile(r"[\u0400-\u04FF]")
|
|
39
|
+
_CJK_RE = re.compile(
|
|
40
|
+
r"[\u3400-\u4DBF\u4E00-\u9FFF\uF900-\uFAFF\u3040-\u30FF\u31F0-\u31FF\uAC00-\uD7AF]"
|
|
41
|
+
)
|
|
42
|
+
# English / code identifier subword split (hoisted: avoids the re-module
|
|
43
|
+
# cache lookup on every word of every payload).
|
|
44
|
+
_SUBWORD_REGEX = re.compile(r"[A-Z]?[a-z]+|[A-Z]+(?=[A-Z][a-z]|\d|\W|$)|\d+")
|
|
45
|
+
|
|
36
46
|
@classmethod
|
|
37
47
|
def count(cls, text: Optional[str]) -> int:
|
|
38
48
|
"""Calculate or estimate token count for any text."""
|
|
@@ -59,9 +69,9 @@ class TokenCounter:
|
|
|
59
69
|
# Check if whitespace
|
|
60
70
|
if chunk.isspace():
|
|
61
71
|
if "\n" in chunk:
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
tokens +=
|
|
72
|
+
newlines = chunk.count("\n")
|
|
73
|
+
tokens += newlines
|
|
74
|
+
tokens += (len(chunk) - newlines) // 4
|
|
65
75
|
else:
|
|
66
76
|
# In BPE, single spaces are merged into adjacent word tokens (e.g. " world").
|
|
67
77
|
# Only indentations (e.g., 4 spaces) add extra tokens.
|
|
@@ -79,17 +89,13 @@ class TokenCounter:
|
|
|
79
89
|
tokens += max(1, (len(chunk) + 2) // 3)
|
|
80
90
|
continue
|
|
81
91
|
|
|
82
|
-
# Alphabetic words: Check script
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
or '\u31F0' <= char <= '\u31FF' # Katakana Phonetic Extensions
|
|
90
|
-
or '\uAC00' <= char <= '\uD7AF' # Hangul syllables
|
|
91
|
-
for char in chunk
|
|
92
|
-
)
|
|
92
|
+
# Alphabetic words: Check script. ASCII chunks (the dominant case for
|
|
93
|
+
# code and English payloads) cannot be Cyrillic or CJK — skip the scan.
|
|
94
|
+
if chunk.isascii():
|
|
95
|
+
is_cyrillic = is_cjk = False
|
|
96
|
+
else:
|
|
97
|
+
is_cyrillic = cls._CYRILLIC_RE.search(chunk) is not None
|
|
98
|
+
is_cjk = cls._CJK_RE.search(chunk) is not None
|
|
93
99
|
|
|
94
100
|
if is_cjk:
|
|
95
101
|
# CJK: typically ~1.8 tokens per character
|
|
@@ -106,7 +112,7 @@ class TokenCounter:
|
|
|
106
112
|
tokens += max(3, (len(chunk) + 2) // 3)
|
|
107
113
|
else:
|
|
108
114
|
# English / Code identifier
|
|
109
|
-
subwords =
|
|
115
|
+
subwords = cls._SUBWORD_REGEX.findall(chunk)
|
|
110
116
|
if subwords:
|
|
111
117
|
for sub in subwords:
|
|
112
118
|
if len(sub) <= 7:
|
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.12"
|
|
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
|