tokensafe 4.5.1 → 4.5.3
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/kimi.plugin.json +1 -1
- package/package.json +1 -1
- package/plugin.json +1 -1
- package/server.json +3 -3
- package/src/batch_editor.py +195 -5
- package/src/mcp_server.py +26 -4
- package/src/metrics.py +71 -15
- package/src/telemetry_sync.py +47 -18
- package/src/version_checker.py +1 -1
package/kimi.plugin.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tokensafe",
|
|
3
|
-
"version": "4.5.
|
|
3
|
+
"version": "4.5.3",
|
|
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.5.
|
|
4
|
+
"version": "4.5.3",
|
|
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.5.
|
|
4
|
+
"version": "4.5.3",
|
|
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.5.
|
|
6
|
+
"version": "4.5.3",
|
|
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.5.
|
|
26
|
+
"version": "4.5.3",
|
|
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.5.
|
|
42
|
+
"version": "4.5.3",
|
|
43
43
|
"runtimeHint": "uvx",
|
|
44
44
|
"transport": {
|
|
45
45
|
"type": "stdio"
|
package/src/batch_editor.py
CHANGED
|
@@ -16,16 +16,183 @@ Key capabilities:
|
|
|
16
16
|
import os
|
|
17
17
|
import re
|
|
18
18
|
import difflib
|
|
19
|
+
import shlex
|
|
19
20
|
import subprocess
|
|
20
21
|
import time
|
|
21
22
|
from typing import Dict, Any, List, Optional, Tuple
|
|
22
23
|
|
|
24
|
+
from src.guard import TokenSafeGuard
|
|
25
|
+
from src.paths import is_plugin_or_system_dir
|
|
23
26
|
from src.secret_redactor import SecretRedactor
|
|
24
27
|
from src.format_parsers.ansi import strip_ansi
|
|
25
28
|
|
|
26
29
|
MAX_BATCH_FILES = 50
|
|
27
30
|
MAX_VERIFY_OUTPUT_CHARS = 4000
|
|
28
31
|
|
|
32
|
+
_VERIFY_SIMPLE_RUNNERS = frozenset({
|
|
33
|
+
"pytest", "py.test", "ruff", "mypy", "pyright", "flake8", "tox", "nox",
|
|
34
|
+
"vitest", "jest", "mocha", "ava", "tsc", "eslint", "prettier", "biome",
|
|
35
|
+
"oxlint", "rspec", "phpunit", "ctest",
|
|
36
|
+
})
|
|
37
|
+
_VERIFY_PYTHON_RUNNERS = frozenset({
|
|
38
|
+
"python", "python3", "python3.10", "python3.11", "python3.12", "python3.13",
|
|
39
|
+
})
|
|
40
|
+
_VERIFY_PYTHON_MODULES = frozenset({
|
|
41
|
+
"unittest", "pytest", "py_compile", "compileall", "mypy", "ruff", "flake8", "doctest",
|
|
42
|
+
})
|
|
43
|
+
_VERIFY_JS_PKG_MANAGERS = frozenset({"npm", "pnpm", "yarn"})
|
|
44
|
+
_VERIFY_SAFE_SCRIPT_PREFIXES = ("test", "lint", "check", "typecheck", "build")
|
|
45
|
+
_VERIFY_SUBCOMMAND_ALLOWLIST = {
|
|
46
|
+
"go": frozenset({"test", "vet", "build"}),
|
|
47
|
+
"cargo": frozenset({"test", "check", "clippy", "build"}),
|
|
48
|
+
"dotnet": frozenset({"test", "build"}),
|
|
49
|
+
"zig": frozenset({"test", "build"}),
|
|
50
|
+
"swift": frozenset({"test", "build"}),
|
|
51
|
+
"tokensafe": frozenset({"tests"}),
|
|
52
|
+
}
|
|
53
|
+
_VERIFY_FORBIDDEN_FLAGS = frozenset({
|
|
54
|
+
"-c", "-e", "--eval", "-p", "--print", "-r", "--require",
|
|
55
|
+
"--import", "--loader", "-exec", "--exec", "-toolexec",
|
|
56
|
+
})
|
|
57
|
+
_DISALLOWED_SYSTEM_DIRS = frozenset({"/etc", "/usr", "/bin", "/sbin", "/System", "/private/etc"})
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _has_unquoted_shell_operators(cmd_str: str) -> bool:
|
|
61
|
+
"""Detects shell chaining, redirection, or command substitution operators."""
|
|
62
|
+
in_single = False
|
|
63
|
+
in_double = False
|
|
64
|
+
escaped = False
|
|
65
|
+
n = len(cmd_str)
|
|
66
|
+
for i, ch in enumerate(cmd_str):
|
|
67
|
+
if ch in ("\n", "\r", "\x00"):
|
|
68
|
+
return True
|
|
69
|
+
if escaped:
|
|
70
|
+
escaped = False
|
|
71
|
+
continue
|
|
72
|
+
if ch == "\\" and not in_single:
|
|
73
|
+
escaped = True
|
|
74
|
+
continue
|
|
75
|
+
if ch == "'" and not in_double:
|
|
76
|
+
in_single = not in_single
|
|
77
|
+
continue
|
|
78
|
+
if ch == '"' and not in_single:
|
|
79
|
+
in_double = not in_double
|
|
80
|
+
continue
|
|
81
|
+
if not in_single:
|
|
82
|
+
if ch == "`":
|
|
83
|
+
return True
|
|
84
|
+
if ch == "$" and i + 1 < n and cmd_str[i + 1] in ("(", "{"):
|
|
85
|
+
return True
|
|
86
|
+
if not in_single and not in_double and ch in (";", "|", "&", ">", "<"):
|
|
87
|
+
return True
|
|
88
|
+
return False
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def validate_verify_command(
|
|
92
|
+
verify_cmd: str, base_dir: str = ""
|
|
93
|
+
) -> Tuple[Optional[List[str]], Optional[str], Optional[str]]:
|
|
94
|
+
"""
|
|
95
|
+
Validates an inline verify command through TokenSafeGuard, shell-operator
|
|
96
|
+
rejection, shlex tokenization, and a strict verification-runner allowlist.
|
|
97
|
+
Returns (argv, error_reason, guard_check_name).
|
|
98
|
+
"""
|
|
99
|
+
cmd_str = str(verify_cmd or "").strip()
|
|
100
|
+
if not cmd_str:
|
|
101
|
+
return None, "Verification command cannot be empty.", "VERIFY_COMMAND_BLOCKED"
|
|
102
|
+
|
|
103
|
+
guard_res = TokenSafeGuard.inspect_command(cmd_str, cwd=base_dir)
|
|
104
|
+
if guard_res.blocked:
|
|
105
|
+
return (
|
|
106
|
+
None,
|
|
107
|
+
f"TokenSafe Security Guard ({guard_res.check_name}) blocked verify command: {guard_res.reason}",
|
|
108
|
+
guard_res.check_name,
|
|
109
|
+
)
|
|
110
|
+
|
|
111
|
+
if _has_unquoted_shell_operators(cmd_str):
|
|
112
|
+
return (
|
|
113
|
+
None,
|
|
114
|
+
"Shell chaining, redirection, and command substitution operators are disallowed in apply_edits.verify.",
|
|
115
|
+
"VERIFY_COMMAND_BLOCKED",
|
|
116
|
+
)
|
|
117
|
+
|
|
118
|
+
try:
|
|
119
|
+
argv = shlex.split(cmd_str)
|
|
120
|
+
except ValueError as exc:
|
|
121
|
+
return None, f"Malformed verify command syntax: {exc}", "VERIFY_COMMAND_BLOCKED"
|
|
122
|
+
|
|
123
|
+
if not argv:
|
|
124
|
+
return None, "Verification command cannot be empty.", "VERIFY_COMMAND_BLOCKED"
|
|
125
|
+
|
|
126
|
+
raw_exe = argv[0]
|
|
127
|
+
if "/" in raw_exe or "\\" in raw_exe:
|
|
128
|
+
return (
|
|
129
|
+
None,
|
|
130
|
+
f"Path-qualified executables ('{raw_exe}') are disallowed in apply_edits.verify.",
|
|
131
|
+
"VERIFY_COMMAND_BLOCKED",
|
|
132
|
+
)
|
|
133
|
+
|
|
134
|
+
exe = raw_exe.lower()
|
|
135
|
+
if exe.endswith(".exe"):
|
|
136
|
+
exe = exe[:-4]
|
|
137
|
+
|
|
138
|
+
args_rest = argv[1:]
|
|
139
|
+
if any(a in _VERIFY_FORBIDDEN_FLAGS or a.startswith("--eval=") or a.startswith("-exec=") for a in args_rest):
|
|
140
|
+
return (
|
|
141
|
+
None,
|
|
142
|
+
f"Flag '{next(a for a in args_rest if a in _VERIFY_FORBIDDEN_FLAGS or a.startswith(('--eval=', '-exec=')))}' is disallowed in apply_edits.verify.",
|
|
143
|
+
"VERIFY_COMMAND_BLOCKED",
|
|
144
|
+
)
|
|
145
|
+
|
|
146
|
+
if exe in _VERIFY_PYTHON_RUNNERS:
|
|
147
|
+
if len(argv) >= 3 and argv[1] == "-m" and argv[2] in _VERIFY_PYTHON_MODULES:
|
|
148
|
+
return argv, None, None
|
|
149
|
+
return (
|
|
150
|
+
None,
|
|
151
|
+
f"Python verify commands must use '-m <allowed_module>' (one of {sorted(_VERIFY_PYTHON_MODULES)}).",
|
|
152
|
+
"VERIFY_COMMAND_BLOCKED",
|
|
153
|
+
)
|
|
154
|
+
|
|
155
|
+
if exe in _VERIFY_JS_PKG_MANAGERS:
|
|
156
|
+
if args_rest and args_rest[0] in ("test", "t", "lint", "check", "typecheck", "build"):
|
|
157
|
+
return argv, None, None
|
|
158
|
+
if len(args_rest) >= 2 and args_rest[0] == "run" and args_rest[1].startswith(_VERIFY_SAFE_SCRIPT_PREFIXES):
|
|
159
|
+
return argv, None, None
|
|
160
|
+
return (
|
|
161
|
+
None,
|
|
162
|
+
f"'{exe}' verify command only allows test/lint/check/typecheck/build subcommands.",
|
|
163
|
+
"VERIFY_COMMAND_BLOCKED",
|
|
164
|
+
)
|
|
165
|
+
|
|
166
|
+
if exe == "bun":
|
|
167
|
+
if args_rest and args_rest[0] == "test":
|
|
168
|
+
return argv, None, None
|
|
169
|
+
if len(args_rest) >= 2 and args_rest[0] == "run" and args_rest[1].startswith(_VERIFY_SAFE_SCRIPT_PREFIXES):
|
|
170
|
+
return argv, None, None
|
|
171
|
+
return (
|
|
172
|
+
None,
|
|
173
|
+
"'bun' verify command only allows 'bun test' or 'bun run <test|lint|check|typecheck|build>*'.",
|
|
174
|
+
"VERIFY_COMMAND_BLOCKED",
|
|
175
|
+
)
|
|
176
|
+
|
|
177
|
+
if exe in _VERIFY_SUBCOMMAND_ALLOWLIST:
|
|
178
|
+
allowed_subs = _VERIFY_SUBCOMMAND_ALLOWLIST[exe]
|
|
179
|
+
if args_rest and args_rest[0] in allowed_subs:
|
|
180
|
+
return argv, None, None
|
|
181
|
+
return (
|
|
182
|
+
None,
|
|
183
|
+
f"'{exe}' verify command only allows subcommands: {sorted(allowed_subs)}.",
|
|
184
|
+
"VERIFY_COMMAND_BLOCKED",
|
|
185
|
+
)
|
|
186
|
+
|
|
187
|
+
if exe in _VERIFY_SIMPLE_RUNNERS:
|
|
188
|
+
return argv, None, None
|
|
189
|
+
|
|
190
|
+
return (
|
|
191
|
+
None,
|
|
192
|
+
f"Executable '{raw_exe}' is not in the allowlisted verification runners for apply_edits.verify.",
|
|
193
|
+
"VERIFY_COMMAND_BLOCKED",
|
|
194
|
+
)
|
|
195
|
+
|
|
29
196
|
|
|
30
197
|
def _find_closest_line_hint(target: str, content: str, max_lines_preview: int = 5) -> str:
|
|
31
198
|
"""Finds closest matching snippet in content to provide actionable line-drift retry guidance."""
|
|
@@ -140,6 +307,29 @@ def execute_batch_edits(
|
|
|
140
307
|
|
|
141
308
|
base_dir = os.path.abspath(cwd or os.getcwd())
|
|
142
309
|
real_base = os.path.realpath(base_dir)
|
|
310
|
+
if is_plugin_or_system_dir(base_dir) or real_base in _DISALLOWED_SYSTEM_DIRS or not os.path.isdir(real_base):
|
|
311
|
+
return {
|
|
312
|
+
"success": False,
|
|
313
|
+
"error": f"Refusing batch edits in system, plugin, or non-existent directory '{cwd or base_dir}'.",
|
|
314
|
+
"applied_files": [],
|
|
315
|
+
"failed_files": []
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
verified_argv: Optional[List[str]] = None
|
|
319
|
+
if verify:
|
|
320
|
+
verified_argv, verify_err, verify_check = validate_verify_command(str(verify), base_dir=real_base)
|
|
321
|
+
if verify_err or not verified_argv:
|
|
322
|
+
return {
|
|
323
|
+
"success": False,
|
|
324
|
+
"blocked": True,
|
|
325
|
+
"check_name": verify_check or "VERIFY_COMMAND_BLOCKED",
|
|
326
|
+
"error": verify_err or "Verification command blocked.",
|
|
327
|
+
"applied_count": 0,
|
|
328
|
+
"applied_files": [],
|
|
329
|
+
"failed_count": 0,
|
|
330
|
+
"failed_files": [],
|
|
331
|
+
"dry_run": dry_run,
|
|
332
|
+
}
|
|
143
333
|
|
|
144
334
|
# Pre-validation & secret check
|
|
145
335
|
prepared_files: Dict[str, Dict[str, Any]] = {}
|
|
@@ -345,15 +535,15 @@ def execute_batch_edits(
|
|
|
345
535
|
"dry_run": dry_run
|
|
346
536
|
}
|
|
347
537
|
|
|
348
|
-
# Execute inline verify command if requested and files were modified
|
|
349
|
-
if
|
|
538
|
+
# Execute inline verify command if requested and files were modified (shell=False, allowlisted argv)
|
|
539
|
+
if verified_argv and applied_files_info and not dry_run:
|
|
350
540
|
cmd_str = str(verify).strip()
|
|
351
541
|
t0 = time.time()
|
|
352
542
|
try:
|
|
353
543
|
proc = subprocess.run(
|
|
354
|
-
|
|
355
|
-
shell=
|
|
356
|
-
cwd=
|
|
544
|
+
verified_argv,
|
|
545
|
+
shell=False,
|
|
546
|
+
cwd=real_base,
|
|
357
547
|
stdout=subprocess.PIPE,
|
|
358
548
|
stderr=subprocess.STDOUT,
|
|
359
549
|
text=True,
|
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.5.
|
|
45
|
+
"version": "4.5.3"
|
|
46
46
|
}
|
|
47
47
|
|
|
48
48
|
# MCP client attribution: the initialize handshake carries clientInfo, which
|
|
@@ -552,9 +552,10 @@ FULL_TOOLS = [ { 'annotations': {'readOnlyHint': True},
|
|
|
552
552
|
'type': 'object'},
|
|
553
553
|
'maxItems': 50,
|
|
554
554
|
'type': 'array'},
|
|
555
|
-
'verify': { 'description': 'Optional
|
|
555
|
+
'verify': { 'description': 'Optional allowlisted verification command '
|
|
556
556
|
'after applying edits (e.g. npm test, pytest, '
|
|
557
|
-
'cargo test)'
|
|
557
|
+
'cargo test, go test, python3 -m unittest) '
|
|
558
|
+
'validated via TokenSafeGuard without a shell',
|
|
558
559
|
'type': 'string'},
|
|
559
560
|
'verify_timeout_sec': { 'description': 'Verification timeout in seconds '
|
|
560
561
|
'(default 30)',
|
|
@@ -2653,7 +2654,19 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
|
|
|
2653
2654
|
dry_run = bool(args.get("dry_run", False))
|
|
2654
2655
|
verify = args.get("verify")
|
|
2655
2656
|
verify_timeout = int(args.get("verify_timeout_sec") or 30)
|
|
2656
|
-
|
|
2657
|
+
raw_cwd = args.get("cwd")
|
|
2658
|
+
active_ws = get_active_workspace()
|
|
2659
|
+
if raw_cwd:
|
|
2660
|
+
if not os.path.isabs(str(raw_cwd)) and active_ws and os.path.isdir(os.path.join(active_ws, str(raw_cwd))):
|
|
2661
|
+
cwd = os.path.abspath(os.path.join(active_ws, str(raw_cwd)))
|
|
2662
|
+
else:
|
|
2663
|
+
cwd = os.path.abspath(str(raw_cwd))
|
|
2664
|
+
else:
|
|
2665
|
+
cwd, err = _resolve_project_root(args)
|
|
2666
|
+
if err or not cwd:
|
|
2667
|
+
return _fallback_error("apply_edits", err or "unspecified project workspace cwd")
|
|
2668
|
+
if is_plugin_or_system_dir(cwd):
|
|
2669
|
+
return _fallback_error("apply_edits", f"refusing to run apply_edits in system root or plugin dir '{cwd}'")
|
|
2657
2670
|
|
|
2658
2671
|
res = execute_batch_edits(
|
|
2659
2672
|
edits=edits,
|
|
@@ -2663,6 +2676,15 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
|
|
|
2663
2676
|
verify_timeout_sec=verify_timeout,
|
|
2664
2677
|
cwd=cwd
|
|
2665
2678
|
)
|
|
2679
|
+
if res.get("blocked"):
|
|
2680
|
+
tracker.record_event(
|
|
2681
|
+
session_id=_mcp_session_id(),
|
|
2682
|
+
event_type=f"GUARD_{res.get('check_name') or 'VERIFY_COMMAND_BLOCKED'}",
|
|
2683
|
+
original_tokens=count_tokens(str(verify or "")),
|
|
2684
|
+
optimized_tokens=0,
|
|
2685
|
+
details={"cmd": str(verify or "")[:100], "reason": str(res.get("error") or "")}
|
|
2686
|
+
)
|
|
2687
|
+
return _fallback_error("apply_edits", str(res.get("error") or "verify command blocked"))
|
|
2666
2688
|
lines = []
|
|
2667
2689
|
if res.get("success"):
|
|
2668
2690
|
action_desc = "Validated" if dry_run else "Applied"
|
package/src/metrics.py
CHANGED
|
@@ -150,22 +150,32 @@ class MetricsTracker:
|
|
|
150
150
|
user_ver = int(uv_row[0]) if uv_row else 0
|
|
151
151
|
except Exception:
|
|
152
152
|
user_ver = 0
|
|
153
|
-
if user_ver >=
|
|
153
|
+
if user_ver >= 4:
|
|
154
154
|
_INITIALIZED_METRICS_DBS.add(self.db_path)
|
|
155
155
|
return
|
|
156
156
|
if user_ver >= 2:
|
|
157
157
|
tbl = cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='events';").fetchone()
|
|
158
158
|
if tbl is not None:
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
159
|
+
if user_ver < 3:
|
|
160
|
+
cursor.execute(
|
|
161
|
+
"UPDATE events SET measurement = 'estimated' "
|
|
162
|
+
"WHERE measurement = 'measured' AND event_type IN "
|
|
163
|
+
"('GRAPH_TOPOLOGY', 'HISTORY_FOLD', 'PROMPT', 'ROLLUP_LIFETIME', "
|
|
164
|
+
"'COMMAND_FILTER', 'LOOP_GUARD', 'SCOPED_SEARCH', 'DIR_LIST', "
|
|
165
|
+
"'GUARD_SECRET', 'GUARD_DESTRUCTIVE', 'GUARD_TLS_VERIFY_BYPASS', "
|
|
166
|
+
"'GUARD_JUNK_READ', 'GUARD_INFINITE', 'GUARD_RAW_CODE_SEARCH');"
|
|
167
|
+
)
|
|
168
|
+
for alter_sql in (
|
|
169
|
+
"ALTER TABLE lifetime_aggregates ADD COLUMN pruned_synced_orig_tokens INTEGER NOT NULL DEFAULT 0;",
|
|
170
|
+
"ALTER TABLE lifetime_aggregates ADD COLUMN pruned_synced_saved_tokens INTEGER NOT NULL DEFAULT 0;",
|
|
171
|
+
"ALTER TABLE lifetime_aggregates ADD COLUMN pruned_synced_usd REAL NOT NULL DEFAULT 0.0;",
|
|
172
|
+
):
|
|
173
|
+
try:
|
|
174
|
+
cursor.execute(alter_sql)
|
|
175
|
+
except sqlite3.OperationalError:
|
|
176
|
+
pass
|
|
167
177
|
try:
|
|
168
|
-
cursor.execute("PRAGMA user_version =
|
|
178
|
+
cursor.execute("PRAGMA user_version = 4;")
|
|
169
179
|
except sqlite3.Error:
|
|
170
180
|
pass
|
|
171
181
|
_INITIALIZED_METRICS_DBS.add(self.db_path)
|
|
@@ -226,9 +236,21 @@ class MetricsTracker:
|
|
|
226
236
|
total_optimized_tokens INTEGER DEFAULT 0,
|
|
227
237
|
total_saved_tokens INTEGER DEFAULT 0,
|
|
228
238
|
total_usd_saved REAL DEFAULT 0.0,
|
|
229
|
-
breakdown TEXT DEFAULT '{}'
|
|
239
|
+
breakdown TEXT DEFAULT '{}',
|
|
240
|
+
pruned_synced_orig_tokens INTEGER NOT NULL DEFAULT 0,
|
|
241
|
+
pruned_synced_saved_tokens INTEGER NOT NULL DEFAULT 0,
|
|
242
|
+
pruned_synced_usd REAL NOT NULL DEFAULT 0.0
|
|
230
243
|
)
|
|
231
244
|
""")
|
|
245
|
+
for alter_sql in (
|
|
246
|
+
"ALTER TABLE lifetime_aggregates ADD COLUMN pruned_synced_orig_tokens INTEGER NOT NULL DEFAULT 0;",
|
|
247
|
+
"ALTER TABLE lifetime_aggregates ADD COLUMN pruned_synced_saved_tokens INTEGER NOT NULL DEFAULT 0;",
|
|
248
|
+
"ALTER TABLE lifetime_aggregates ADD COLUMN pruned_synced_usd REAL NOT NULL DEFAULT 0.0;",
|
|
249
|
+
):
|
|
250
|
+
try:
|
|
251
|
+
cursor.execute(alter_sql)
|
|
252
|
+
except sqlite3.OperationalError:
|
|
253
|
+
pass
|
|
232
254
|
cursor.execute("""
|
|
233
255
|
INSERT OR IGNORE INTO lifetime_aggregates (
|
|
234
256
|
id, total_events, total_original_tokens, total_optimized_tokens,
|
|
@@ -257,7 +279,7 @@ class MetricsTracker:
|
|
|
257
279
|
GROUP BY substr(timestamp, 1, 10)
|
|
258
280
|
""", (cutoff_30,))
|
|
259
281
|
try:
|
|
260
|
-
cursor.execute("PRAGMA user_version =
|
|
282
|
+
cursor.execute("PRAGMA user_version = 4;")
|
|
261
283
|
except sqlite3.Error:
|
|
262
284
|
pass
|
|
263
285
|
_INITIALIZED_METRICS_DBS.add(self.db_path)
|
|
@@ -883,6 +905,33 @@ class MetricsTracker:
|
|
|
883
905
|
current_breakdown[ev_type]["saved"] += vals["saved"]
|
|
884
906
|
current_breakdown[ev_type]["estimated_saved"] += vals["estimated_saved"]
|
|
885
907
|
|
|
908
|
+
# Track how much of the pruned mass was already synced individually to Cloud
|
|
909
|
+
last_synced_id = 0
|
|
910
|
+
sync_state_path = os.path.join(os.path.dirname(self.db_path), "sync_state.json")
|
|
911
|
+
if os.path.exists(sync_state_path):
|
|
912
|
+
try:
|
|
913
|
+
with open(sync_state_path, "r", encoding="utf-8") as sf:
|
|
914
|
+
sdata = json.load(sf)
|
|
915
|
+
if isinstance(sdata, dict):
|
|
916
|
+
last_synced_id = int(sdata.get("last_synced_event_id", 0) or 0)
|
|
917
|
+
except Exception:
|
|
918
|
+
last_synced_id = 0
|
|
919
|
+
synced_orig, synced_saved, synced_usd = 0, 0, 0.0
|
|
920
|
+
if last_synced_id > 0:
|
|
921
|
+
cursor.execute(f"""
|
|
922
|
+
SELECT
|
|
923
|
+
COALESCE(SUM(original_tokens), 0),
|
|
924
|
+
COALESCE(SUM(saved_tokens), 0),
|
|
925
|
+
COALESCE(SUM(est_usd_saved), 0.0)
|
|
926
|
+
FROM events
|
|
927
|
+
WHERE ({combined_where}) AND id <= ?
|
|
928
|
+
""", [*params, last_synced_id])
|
|
929
|
+
s_row = cursor.fetchone()
|
|
930
|
+
if s_row:
|
|
931
|
+
synced_orig = int(s_row[0] or 0)
|
|
932
|
+
synced_saved = int(s_row[1] or 0)
|
|
933
|
+
synced_usd = float(s_row[2] or 0.0)
|
|
934
|
+
|
|
886
935
|
# 4. Update lifetime_aggregates
|
|
887
936
|
cursor.execute("""
|
|
888
937
|
UPDATE lifetime_aggregates SET
|
|
@@ -891,12 +940,16 @@ class MetricsTracker:
|
|
|
891
940
|
total_optimized_tokens = total_optimized_tokens + ?,
|
|
892
941
|
total_saved_tokens = total_saved_tokens + ?,
|
|
893
942
|
total_usd_saved = total_usd_saved + ?,
|
|
894
|
-
breakdown =
|
|
943
|
+
breakdown = ?,
|
|
944
|
+
pruned_synced_orig_tokens = COALESCE(pruned_synced_orig_tokens, 0) + ?,
|
|
945
|
+
pruned_synced_saved_tokens = COALESCE(pruned_synced_saved_tokens, 0) + ?,
|
|
946
|
+
pruned_synced_usd = COALESCE(pruned_synced_usd, 0.0) + ?
|
|
895
947
|
WHERE id = 1
|
|
896
948
|
""", (
|
|
897
949
|
agg_row["cnt"], agg_row["orig"], agg_row["opt"],
|
|
898
950
|
agg_row["saved"], agg_row["usd"],
|
|
899
|
-
json.dumps(current_breakdown, ensure_ascii=False)
|
|
951
|
+
json.dumps(current_breakdown, ensure_ascii=False),
|
|
952
|
+
synced_orig, synced_saved, synced_usd,
|
|
900
953
|
))
|
|
901
954
|
|
|
902
955
|
# 5. Delete pruned events
|
|
@@ -944,7 +997,10 @@ class MetricsTracker:
|
|
|
944
997
|
total_optimized_tokens = 0,
|
|
945
998
|
total_saved_tokens = 0,
|
|
946
999
|
total_usd_saved = 0.0,
|
|
947
|
-
breakdown = '{}'
|
|
1000
|
+
breakdown = '{}',
|
|
1001
|
+
pruned_synced_orig_tokens = 0,
|
|
1002
|
+
pruned_synced_saved_tokens = 0,
|
|
1003
|
+
pruned_synced_usd = 0.0
|
|
948
1004
|
WHERE id = 1
|
|
949
1005
|
""")
|
|
950
1006
|
self.vacuum()
|
package/src/telemetry_sync.py
CHANGED
|
@@ -239,10 +239,17 @@ class TelemetrySync:
|
|
|
239
239
|
total_sent = 0
|
|
240
240
|
cumulative_synced = state.get("total_synced_events", 0)
|
|
241
241
|
rollup_synced = bool(state.get("lifetime_rollup_synced", False))
|
|
242
|
+
has_rollup_watermark = "last_synced_rollup_tokens" in state
|
|
243
|
+
last_synced_rollup = int(state.get("last_synced_rollup_tokens", 0) or 0)
|
|
244
|
+
last_synced_rollup_orig = int(state.get("last_synced_rollup_orig", 0) or 0)
|
|
245
|
+
last_synced_rollup_usd = float(state.get("last_synced_rollup_usd", 0.0) or 0.0)
|
|
246
|
+
current_rollup_tokens = last_synced_rollup
|
|
247
|
+
current_rollup_orig = last_synced_rollup_orig
|
|
248
|
+
current_rollup_usd = last_synced_rollup_usd
|
|
242
249
|
current_last_id = last_id
|
|
243
250
|
headers = {
|
|
244
251
|
"Content-Type": "application/json",
|
|
245
|
-
"User-Agent": "TokenSafe-Sync/4.5.
|
|
252
|
+
"User-Agent": "TokenSafe-Sync/4.5.3"
|
|
246
253
|
}
|
|
247
254
|
if active_key:
|
|
248
255
|
headers["Authorization"] = f"Bearer {active_key}"
|
|
@@ -255,7 +262,10 @@ class TelemetrySync:
|
|
|
255
262
|
"last_quota_sync_at": state.get("last_quota_sync_at", 0),
|
|
256
263
|
"consecutive_failures": int(state.get("consecutive_failures", 0) or 0) + 1,
|
|
257
264
|
"total_synced_events": cumulative_synced,
|
|
258
|
-
"lifetime_rollup_synced": rollup_synced
|
|
265
|
+
"lifetime_rollup_synced": rollup_synced,
|
|
266
|
+
"last_synced_rollup_tokens": last_synced_rollup,
|
|
267
|
+
"last_synced_rollup_orig": last_synced_rollup_orig,
|
|
268
|
+
"last_synced_rollup_usd": last_synced_rollup_usd,
|
|
259
269
|
}
|
|
260
270
|
cls.save_state(fail_state)
|
|
261
271
|
return {
|
|
@@ -267,8 +277,6 @@ class TelemetrySync:
|
|
|
267
277
|
page_limit = 2000
|
|
268
278
|
max_pages = 25
|
|
269
279
|
batch_size = min(max(1, int(batch_size or 50)), 200)
|
|
270
|
-
last_synced_rollup = int(state.get("last_synced_rollup_tokens", 0) or 0)
|
|
271
|
-
current_rollup_tokens = last_synced_rollup
|
|
272
280
|
for page_idx in range(max_pages):
|
|
273
281
|
try:
|
|
274
282
|
with closing(sqlite3.connect(db_path, timeout=5.0)) as conn:
|
|
@@ -279,20 +287,37 @@ class TelemetrySync:
|
|
|
279
287
|
if page_idx == 0:
|
|
280
288
|
try:
|
|
281
289
|
life_row = cur.execute("SELECT * FROM lifetime_aggregates WHERE id = 1").fetchone()
|
|
282
|
-
if life_row
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
290
|
+
if life_row:
|
|
291
|
+
life_dict = dict(life_row)
|
|
292
|
+
syncable_orig = max(0, int(life_dict.get("total_original_tokens") or 0) - int(life_dict.get("pruned_synced_orig_tokens") or 0))
|
|
293
|
+
syncable_saved = max(0, int(life_dict.get("total_saved_tokens") or 0) - int(life_dict.get("pruned_synced_saved_tokens") or 0))
|
|
294
|
+
syncable_usd = max(0.0, float(life_dict.get("total_usd_saved") or 0.0) - float(life_dict.get("pruned_synced_usd") or 0.0))
|
|
295
|
+
# Upgrade migration from pre-watermark sync_state.json: do not re-emit already synced rollup
|
|
296
|
+
if rollup_synced and not has_rollup_watermark:
|
|
297
|
+
last_synced_rollup = syncable_saved
|
|
298
|
+
last_synced_rollup_orig = syncable_orig
|
|
299
|
+
last_synced_rollup_usd = syncable_usd
|
|
300
|
+
current_rollup_tokens = syncable_saved
|
|
301
|
+
current_rollup_orig = syncable_orig
|
|
302
|
+
current_rollup_usd = syncable_usd
|
|
303
|
+
has_rollup_watermark = True
|
|
304
|
+
elif syncable_saved > last_synced_rollup:
|
|
305
|
+
current_rollup_tokens = syncable_saved
|
|
306
|
+
current_rollup_orig = syncable_orig
|
|
307
|
+
current_rollup_usd = syncable_usd
|
|
308
|
+
delta_orig = max(0, syncable_orig - last_synced_rollup_orig)
|
|
309
|
+
delta_saved = syncable_saved - last_synced_rollup
|
|
310
|
+
delta_usd = max(0.0, syncable_usd - last_synced_rollup_usd)
|
|
311
|
+
synthetic_events.append({
|
|
312
|
+
"event_type": "ROLLUP_LIFETIME",
|
|
313
|
+
"original_tokens": delta_orig or delta_saved,
|
|
314
|
+
"saved_tokens": delta_saved,
|
|
315
|
+
"usd_saved": delta_usd,
|
|
316
|
+
"model": "aggregate",
|
|
317
|
+
"timestamp": int(time.time()),
|
|
318
|
+
# Rolled-up historical mass of mixed provenance: conservatively estimated.
|
|
319
|
+
"measurement": "estimated"
|
|
320
|
+
})
|
|
296
321
|
except Exception:
|
|
297
322
|
pass
|
|
298
323
|
|
|
@@ -441,6 +466,8 @@ class TelemetrySync:
|
|
|
441
466
|
if ev_payload and ev_payload.get("event_type") == "ROLLUP_LIFETIME":
|
|
442
467
|
rollup_synced = True
|
|
443
468
|
last_synced_rollup = current_rollup_tokens
|
|
469
|
+
last_synced_rollup_orig = current_rollup_orig
|
|
470
|
+
last_synced_rollup_usd = current_rollup_usd
|
|
444
471
|
cls.save_state({
|
|
445
472
|
"last_synced_event_id": current_last_id,
|
|
446
473
|
"last_synced_at": int(time.time()),
|
|
@@ -450,6 +477,8 @@ class TelemetrySync:
|
|
|
450
477
|
"total_synced_events": cumulative_synced,
|
|
451
478
|
"lifetime_rollup_synced": rollup_synced,
|
|
452
479
|
"last_synced_rollup_tokens": last_synced_rollup,
|
|
480
|
+
"last_synced_rollup_orig": last_synced_rollup_orig,
|
|
481
|
+
"last_synced_rollup_usd": last_synced_rollup_usd,
|
|
453
482
|
})
|
|
454
483
|
else:
|
|
455
484
|
return _record_failure(f"Server returned HTTP {resp.status}")
|
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.5.
|
|
20
|
+
CURRENT_VERSION = "4.5.3"
|
|
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
|