tokensafe 1.4.4 → 1.4.6
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/hooks/post_tool_use.py +15 -1
- package/hooks/pre_invocation.py +10 -3
- package/package.json +1 -1
- package/plugin.json +1 -1
- package/src/cli.py +29 -0
- package/src/mcp_server.py +7 -1
- package/src/telemetry_sync.py +63 -11
- package/src/version_checker.py +170 -1
package/hooks/post_tool_use.py
CHANGED
|
@@ -2,12 +2,19 @@
|
|
|
2
2
|
"""
|
|
3
3
|
Antigravity Lifecycle Hook: PostToolUse
|
|
4
4
|
Fires after tool execution.
|
|
5
|
-
Fulfills Antigravity PostToolUse contract by returning `{}`.
|
|
5
|
+
1. Fulfills Antigravity PostToolUse contract by returning `{}`.
|
|
6
|
+
2. Triggers detached background telemetry sync if pending events exist.
|
|
6
7
|
"""
|
|
7
8
|
|
|
9
|
+
import os
|
|
8
10
|
import sys
|
|
9
11
|
import json
|
|
10
12
|
|
|
13
|
+
HOOK_DIR = os.path.dirname(os.path.abspath(__file__))
|
|
14
|
+
PROJECT_ROOT = os.path.dirname(HOOK_DIR)
|
|
15
|
+
if PROJECT_ROOT not in sys.path:
|
|
16
|
+
sys.path.insert(0, PROJECT_ROOT)
|
|
17
|
+
|
|
11
18
|
def main():
|
|
12
19
|
try:
|
|
13
20
|
# Drain stdin to keep pipes clean
|
|
@@ -15,6 +22,13 @@ def main():
|
|
|
15
22
|
except Exception:
|
|
16
23
|
pass
|
|
17
24
|
|
|
25
|
+
# Non-blocking telemetry sync trigger (detached background process)
|
|
26
|
+
try:
|
|
27
|
+
from src.telemetry_sync import TelemetrySync
|
|
28
|
+
TelemetrySync.sync_background(throttle_seconds=60.0)
|
|
29
|
+
except Exception:
|
|
30
|
+
pass
|
|
31
|
+
|
|
18
32
|
# PostToolUse contract expects an empty JSON object {}
|
|
19
33
|
print(json.dumps({}))
|
|
20
34
|
|
package/hooks/pre_invocation.py
CHANGED
|
@@ -42,12 +42,19 @@ def main():
|
|
|
42
42
|
tracker = MetricsTracker()
|
|
43
43
|
inject_steps = []
|
|
44
44
|
|
|
45
|
-
# 0.
|
|
45
|
+
# 0. Asynchronous telemetry sync (detached & throttled to 60s)
|
|
46
|
+
try:
|
|
47
|
+
from src.telemetry_sync import TelemetrySync
|
|
48
|
+
TelemetrySync.sync_background(throttle_seconds=60.0)
|
|
49
|
+
except Exception:
|
|
50
|
+
pass
|
|
51
|
+
|
|
52
|
+
# 1. Quota and Environment Audits (Fires on first invocation)
|
|
46
53
|
quota = LicenseManager.check_quota(tracker)
|
|
47
54
|
if invocation_num <= 1:
|
|
48
55
|
try:
|
|
49
|
-
from src.
|
|
50
|
-
|
|
56
|
+
from src.version_checker import VersionChecker
|
|
57
|
+
VersionChecker.notify_os_update_background()
|
|
51
58
|
except Exception:
|
|
52
59
|
pass
|
|
53
60
|
if quota.get("warning"):
|
package/package.json
CHANGED
package/plugin.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "agy-token-optimizer",
|
|
3
3
|
"displayName": "TokenSafe",
|
|
4
|
-
"version": "1.4.
|
|
4
|
+
"version": "1.4.6",
|
|
5
5
|
"description": "Zero-Loss Token Economy & Context Optimizer for AI Agents. Compresses prompts, slices AST/tool outputs, and prevents stuck loops.",
|
|
6
6
|
"logo": "assets/logo.svg",
|
|
7
7
|
"author": {
|
package/src/cli.py
CHANGED
|
@@ -78,6 +78,35 @@ def main():
|
|
|
78
78
|
from src.installer import AgentInstaller
|
|
79
79
|
AgentInstaller.self_update()
|
|
80
80
|
|
|
81
|
+
elif command in ("version", "--version", "-v"):
|
|
82
|
+
from src.version_checker import CURRENT_VERSION, VersionChecker
|
|
83
|
+
print(f"TokenSafe v{CURRENT_VERSION}")
|
|
84
|
+
if "--check" in args or "-c" in args:
|
|
85
|
+
banner = VersionChecker.get_banner()
|
|
86
|
+
if banner:
|
|
87
|
+
print(banner)
|
|
88
|
+
else:
|
|
89
|
+
print("\033[32m✔ TokenSafe is up to date.\033[0m")
|
|
90
|
+
if "--notify" in args or "--prompt" in args:
|
|
91
|
+
VersionChecker.notify_os_update(force=True)
|
|
92
|
+
|
|
93
|
+
elif command in ("check-update", "check_update"):
|
|
94
|
+
from src.version_checker import CURRENT_VERSION, VersionChecker
|
|
95
|
+
print(f"\n\033[1m\033[36m⚡ CHECKING FOR TOKENSAFE UPDATES ⚡\033[0m\n")
|
|
96
|
+
print(f" Current version: v{CURRENT_VERSION}")
|
|
97
|
+
info = VersionChecker.check_version(force_fetch=True)
|
|
98
|
+
latest = info.get("latest_version", CURRENT_VERSION)
|
|
99
|
+
avail = info.get("update_available", False)
|
|
100
|
+
print(f" Latest version: v{latest}")
|
|
101
|
+
banner = VersionChecker.get_banner()
|
|
102
|
+
if banner:
|
|
103
|
+
print(banner)
|
|
104
|
+
else:
|
|
105
|
+
print("\n \033[32m✔ TokenSafe is up to date.\033[0m\n")
|
|
106
|
+
if avail or "--notify" in args or "--prompt" in args or "-p" in args:
|
|
107
|
+
print(" \033[36mTriggering native OS update dialog...\033[0m")
|
|
108
|
+
VersionChecker.notify_os_update(force=True)
|
|
109
|
+
|
|
81
110
|
elif command in ("guard", "security"):
|
|
82
111
|
from src.guard import TokenSafeGuard
|
|
83
112
|
sub = args[1] if len(args) > 1 else "help"
|
package/src/mcp_server.py
CHANGED
|
@@ -31,7 +31,7 @@ from src.guard import TokenSafeGuard
|
|
|
31
31
|
|
|
32
32
|
SERVER_INFO = {
|
|
33
33
|
"name": "tokensafe-mcp",
|
|
34
|
-
"version": "1.4.
|
|
34
|
+
"version": "1.4.6"
|
|
35
35
|
}
|
|
36
36
|
|
|
37
37
|
TOOLS = [
|
|
@@ -595,6 +595,12 @@ def run_mcp_server():
|
|
|
595
595
|
"isError": True,
|
|
596
596
|
"content": [{"type": "text", "text": f"Error: {str(e)}\n{traceback.format_exc()}"}]
|
|
597
597
|
}
|
|
598
|
+
finally:
|
|
599
|
+
try:
|
|
600
|
+
from src.telemetry_sync import TelemetrySync
|
|
601
|
+
TelemetrySync.sync_background(throttle_seconds=60.0)
|
|
602
|
+
except Exception:
|
|
603
|
+
pass
|
|
598
604
|
else:
|
|
599
605
|
response["error"] = {"code": -32601, "message": f"Method not found: {method}"}
|
|
600
606
|
|
package/src/telemetry_sync.py
CHANGED
|
@@ -17,6 +17,7 @@ import json
|
|
|
17
17
|
import time
|
|
18
18
|
import sqlite3
|
|
19
19
|
import threading
|
|
20
|
+
import subprocess
|
|
20
21
|
import urllib.request
|
|
21
22
|
import urllib.parse
|
|
22
23
|
import urllib.error
|
|
@@ -32,6 +33,7 @@ from src.license_manager import LicenseManager
|
|
|
32
33
|
DATA_DIR = os.path.join(PROJECT_ROOT, "data")
|
|
33
34
|
METRICS_DB_PATH = os.path.join(DATA_DIR, "metrics.db")
|
|
34
35
|
SYNC_STATE_PATH = os.path.join(DATA_DIR, "sync_state.json")
|
|
36
|
+
SYNC_LOCK_PATH = os.path.join(DATA_DIR, ".sync.lock")
|
|
35
37
|
|
|
36
38
|
|
|
37
39
|
def _get_cloud_url() -> str:
|
|
@@ -234,7 +236,7 @@ class TelemetrySync:
|
|
|
234
236
|
total_sent = 0
|
|
235
237
|
headers = {
|
|
236
238
|
"Content-Type": "application/json",
|
|
237
|
-
"User-Agent": "TokenSafe-Sync/1.4.
|
|
239
|
+
"User-Agent": "TokenSafe-Sync/1.4.6"
|
|
238
240
|
}
|
|
239
241
|
if active_key:
|
|
240
242
|
headers["Authorization"] = f"Bearer {active_key}"
|
|
@@ -288,22 +290,72 @@ class TelemetrySync:
|
|
|
288
290
|
}
|
|
289
291
|
|
|
290
292
|
@classmethod
|
|
291
|
-
def sync_background(cls, throttle_seconds: float =
|
|
293
|
+
def sync_background(cls, throttle_seconds: float = 60.0, force: bool = False):
|
|
292
294
|
"""
|
|
293
|
-
Spawns a detached, non-blocking
|
|
294
|
-
Throttled to run at most once every `throttle_seconds` (default:
|
|
295
|
+
Spawns a detached, non-blocking background OS process to sync metrics.
|
|
296
|
+
Throttled to run at most once every `throttle_seconds` (default: 60s)
|
|
297
|
+
using persistent state from sync_state.json.
|
|
298
|
+
Detached from parent process group so it survives the termination of short-lived CLI lifecycle hooks.
|
|
295
299
|
"""
|
|
296
300
|
now = time.time()
|
|
297
|
-
|
|
301
|
+
state = cls.get_state()
|
|
302
|
+
last_synced = state.get("last_synced_at", 0)
|
|
303
|
+
if not force and (now - last_synced) < throttle_seconds:
|
|
298
304
|
return
|
|
299
305
|
|
|
300
|
-
|
|
306
|
+
status = cls.get_sync_status()
|
|
307
|
+
if status.get("pending_events", 0) == 0:
|
|
308
|
+
return
|
|
301
309
|
|
|
302
|
-
|
|
310
|
+
# Prevent overlapping sync runs via PID lock file
|
|
311
|
+
if os.path.exists(SYNC_LOCK_PATH):
|
|
303
312
|
try:
|
|
304
|
-
|
|
305
|
-
|
|
313
|
+
with open(SYNC_LOCK_PATH, "r", encoding="utf-8") as f:
|
|
314
|
+
pid = int(f.read().strip())
|
|
315
|
+
# Check if PID is still alive
|
|
316
|
+
os.kill(pid, 0)
|
|
317
|
+
return
|
|
318
|
+
except (ValueError, OSError, ProcessLookupError):
|
|
306
319
|
pass
|
|
307
320
|
|
|
308
|
-
|
|
309
|
-
|
|
321
|
+
try:
|
|
322
|
+
flags = 0
|
|
323
|
+
if os.name == "nt":
|
|
324
|
+
flags = subprocess.CREATE_NEW_PROCESS_GROUP | subprocess.DETACHED_PROCESS
|
|
325
|
+
script_path = os.path.abspath(__file__)
|
|
326
|
+
subprocess.Popen(
|
|
327
|
+
[sys.executable, script_path, "--background"],
|
|
328
|
+
cwd=PROJECT_ROOT,
|
|
329
|
+
stdout=subprocess.DEVNULL,
|
|
330
|
+
stderr=subprocess.DEVNULL,
|
|
331
|
+
stdin=subprocess.DEVNULL,
|
|
332
|
+
start_new_session=(os.name != "nt"),
|
|
333
|
+
creationflags=flags
|
|
334
|
+
)
|
|
335
|
+
except Exception:
|
|
336
|
+
# Fallback to daemon thread if process spawn fails
|
|
337
|
+
def _worker():
|
|
338
|
+
try:
|
|
339
|
+
cls.sync(timeout=2.0)
|
|
340
|
+
except Exception:
|
|
341
|
+
pass
|
|
342
|
+
|
|
343
|
+
t = threading.Thread(target=_worker, daemon=True)
|
|
344
|
+
t.start()
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
if __name__ == "__main__":
|
|
348
|
+
is_bg = "--background" in sys.argv
|
|
349
|
+
os.makedirs(DATA_DIR, exist_ok=True)
|
|
350
|
+
try:
|
|
351
|
+
with open(SYNC_LOCK_PATH, "w", encoding="utf-8") as f:
|
|
352
|
+
f.write(str(os.getpid()))
|
|
353
|
+
res = TelemetrySync.sync(timeout=5.0 if is_bg else 10.0, verbose=not is_bg)
|
|
354
|
+
if not is_bg:
|
|
355
|
+
print(json.dumps(res, indent=2))
|
|
356
|
+
finally:
|
|
357
|
+
try:
|
|
358
|
+
if os.path.exists(SYNC_LOCK_PATH):
|
|
359
|
+
os.remove(SYNC_LOCK_PATH)
|
|
360
|
+
except Exception:
|
|
361
|
+
pass
|
package/src/version_checker.py
CHANGED
|
@@ -9,12 +9,14 @@ import sys
|
|
|
9
9
|
import json
|
|
10
10
|
import time
|
|
11
11
|
import re
|
|
12
|
+
import subprocess
|
|
13
|
+
import threading
|
|
12
14
|
import urllib.parse
|
|
13
15
|
import urllib.request
|
|
14
16
|
import urllib.error
|
|
15
17
|
from typing import Dict, Any, Optional, Tuple
|
|
16
18
|
|
|
17
|
-
CURRENT_VERSION = "1.4.
|
|
19
|
+
CURRENT_VERSION = "1.4.6"
|
|
18
20
|
CACHE_TTL = 86400 # 24 hours
|
|
19
21
|
|
|
20
22
|
PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
@@ -163,3 +165,170 @@ class VersionChecker:
|
|
|
163
165
|
)
|
|
164
166
|
|
|
165
167
|
return None
|
|
168
|
+
|
|
169
|
+
@classmethod
|
|
170
|
+
def show_os_dialog(
|
|
171
|
+
cls,
|
|
172
|
+
current_version: str = CURRENT_VERSION,
|
|
173
|
+
latest_version: str = CURRENT_VERSION,
|
|
174
|
+
update_command: str = "tokensafe update"
|
|
175
|
+
) -> bool:
|
|
176
|
+
"""
|
|
177
|
+
Displays a native OS desktop popup dialog with English texts and 'Update Now' / 'Later' buttons.
|
|
178
|
+
Uses zero external third-party packages (macOS AppleScript, Windows ctypes/PowerShell, Linux zenity/notify-send).
|
|
179
|
+
"""
|
|
180
|
+
plat = sys.platform
|
|
181
|
+
|
|
182
|
+
if plat == "darwin":
|
|
183
|
+
try:
|
|
184
|
+
escaped_cmd = update_command.replace('"', '\\"')
|
|
185
|
+
apple_script = f'''
|
|
186
|
+
set dialogResult to display dialog "A new version of TokenSafe (v{latest_version}) is available.\\n\\nCurrent version: v{current_version}\\nLatest version: v{latest_version}\\n\\nWould you like to update now?" with title "TokenSafe Update Available" buttons {{"Later", "Update Now"}} default button "Update Now" with icon note
|
|
187
|
+
if button returned of dialogResult is "Update Now" then
|
|
188
|
+
tell application "Terminal"
|
|
189
|
+
activate
|
|
190
|
+
do script "{escaped_cmd}"
|
|
191
|
+
end tell
|
|
192
|
+
end if
|
|
193
|
+
'''
|
|
194
|
+
subprocess.Popen(
|
|
195
|
+
["osascript", "-e", apple_script],
|
|
196
|
+
stdout=subprocess.DEVNULL,
|
|
197
|
+
stderr=subprocess.DEVNULL,
|
|
198
|
+
stdin=subprocess.DEVNULL,
|
|
199
|
+
start_new_session=True
|
|
200
|
+
)
|
|
201
|
+
return True
|
|
202
|
+
except Exception:
|
|
203
|
+
return False
|
|
204
|
+
|
|
205
|
+
elif plat == "win32":
|
|
206
|
+
try:
|
|
207
|
+
import ctypes
|
|
208
|
+
flags = 0x00000004 | 0x00000040 | 0x00010000 | 0x00040000 # MB_YESNO | MB_ICONINFORMATION | MB_SETFOREGROUND | MB_TOPMOST
|
|
209
|
+
msg = (
|
|
210
|
+
f"A new version of TokenSafe (v{latest_version}) is available.\n\n"
|
|
211
|
+
f"Current version: v{current_version}\n"
|
|
212
|
+
f"Latest version: v{latest_version}\n\n"
|
|
213
|
+
"Would you like to update now?"
|
|
214
|
+
)
|
|
215
|
+
title = "TokenSafe Update Available"
|
|
216
|
+
|
|
217
|
+
def _win_worker():
|
|
218
|
+
res = ctypes.windll.user32.MessageBoxW(0, msg, title, flags)
|
|
219
|
+
if res == 6: # IDYES
|
|
220
|
+
subprocess.Popen(
|
|
221
|
+
["cmd.exe", "/c", "start", "cmd.exe", "/k", update_command],
|
|
222
|
+
creationflags=getattr(subprocess, "DETACHED_PROCESS", 0)
|
|
223
|
+
)
|
|
224
|
+
|
|
225
|
+
threading.Thread(target=_win_worker, daemon=True).start()
|
|
226
|
+
return True
|
|
227
|
+
except Exception:
|
|
228
|
+
return False
|
|
229
|
+
|
|
230
|
+
elif plat.startswith("linux"):
|
|
231
|
+
try:
|
|
232
|
+
zenity_cmd = [
|
|
233
|
+
"zenity",
|
|
234
|
+
"--question",
|
|
235
|
+
"--title=TokenSafe Update Available",
|
|
236
|
+
f"--text=A new version of TokenSafe (v{latest_version}) is available.\n\nCurrent version: v{current_version}\nLatest version: v{latest_version}\n\nWould you like to update now?",
|
|
237
|
+
"--ok-label=Update Now",
|
|
238
|
+
"--cancel-label=Later"
|
|
239
|
+
]
|
|
240
|
+
p = subprocess.Popen(zenity_cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
|
241
|
+
|
|
242
|
+
def _zenity_wait():
|
|
243
|
+
if p.wait() == 0:
|
|
244
|
+
for term in (
|
|
245
|
+
["x-terminal-emulator", "-e", update_command],
|
|
246
|
+
["gnome-terminal", "--", update_command],
|
|
247
|
+
["konsole", "-e", update_command],
|
|
248
|
+
["xterm", "-e", update_command]
|
|
249
|
+
):
|
|
250
|
+
try:
|
|
251
|
+
subprocess.Popen(term)
|
|
252
|
+
break
|
|
253
|
+
except Exception:
|
|
254
|
+
pass
|
|
255
|
+
|
|
256
|
+
threading.Thread(target=_zenity_wait, daemon=True).start()
|
|
257
|
+
return True
|
|
258
|
+
except Exception:
|
|
259
|
+
pass
|
|
260
|
+
|
|
261
|
+
try:
|
|
262
|
+
subprocess.Popen([
|
|
263
|
+
"notify-send",
|
|
264
|
+
"TokenSafe Update Available",
|
|
265
|
+
f"A new version (v{latest_version}) is available. Run: {update_command}"
|
|
266
|
+
])
|
|
267
|
+
return True
|
|
268
|
+
except Exception:
|
|
269
|
+
return False
|
|
270
|
+
|
|
271
|
+
return False
|
|
272
|
+
|
|
273
|
+
@classmethod
|
|
274
|
+
def notify_os_update(
|
|
275
|
+
cls,
|
|
276
|
+
current_version: str = CURRENT_VERSION,
|
|
277
|
+
license_key: str = "",
|
|
278
|
+
force: bool = False,
|
|
279
|
+
timeout: float = 1.5
|
|
280
|
+
) -> bool:
|
|
281
|
+
"""
|
|
282
|
+
Checks if an update is available and presents a native OS desktop popup dialog.
|
|
283
|
+
Throttled to at most once per 24 hours per target version unless force=True.
|
|
284
|
+
Returns True if prompt was dispatched, False otherwise.
|
|
285
|
+
"""
|
|
286
|
+
info = cls.check_version(current_version=current_version, license_key=license_key, timeout=timeout)
|
|
287
|
+
update_available = info.get("update_available", False)
|
|
288
|
+
latest = info.get("latest_version", current_version)
|
|
289
|
+
cmd = info.get("update_command", "tokensafe update")
|
|
290
|
+
|
|
291
|
+
if not update_available and not force:
|
|
292
|
+
return False
|
|
293
|
+
|
|
294
|
+
cached = cls.load_cache() or {}
|
|
295
|
+
now = int(time.time())
|
|
296
|
+
last_notified_ver = cached.get("last_os_notify_version", "")
|
|
297
|
+
last_notified_at = cached.get("last_os_notify_at", 0)
|
|
298
|
+
|
|
299
|
+
if not force and last_notified_ver == latest and (now - last_notified_at) < CACHE_TTL:
|
|
300
|
+
return False
|
|
301
|
+
|
|
302
|
+
cached["last_os_notify_version"] = latest
|
|
303
|
+
cached["last_os_notify_at"] = now
|
|
304
|
+
cls.save_cache(cached)
|
|
305
|
+
|
|
306
|
+
return cls.show_os_dialog(
|
|
307
|
+
current_version=current_version,
|
|
308
|
+
latest_version=latest,
|
|
309
|
+
update_command=cmd
|
|
310
|
+
)
|
|
311
|
+
|
|
312
|
+
@classmethod
|
|
313
|
+
def notify_os_update_background(
|
|
314
|
+
cls,
|
|
315
|
+
current_version: str = CURRENT_VERSION,
|
|
316
|
+
license_key: str = "",
|
|
317
|
+
force: bool = False
|
|
318
|
+
):
|
|
319
|
+
"""
|
|
320
|
+
Dispatches notify_os_update in a background non-blocking thread.
|
|
321
|
+
"""
|
|
322
|
+
def _bg():
|
|
323
|
+
try:
|
|
324
|
+
cls.notify_os_update(
|
|
325
|
+
current_version=current_version,
|
|
326
|
+
license_key=license_key,
|
|
327
|
+
force=force,
|
|
328
|
+
timeout=1.5
|
|
329
|
+
)
|
|
330
|
+
except Exception:
|
|
331
|
+
pass
|
|
332
|
+
|
|
333
|
+
t = threading.Thread(target=_bg, daemon=True)
|
|
334
|
+
t.start()
|