tokensafe 1.4.4 → 1.4.5

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.
@@ -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
 
@@ -42,14 +42,16 @@ def main():
42
42
  tracker = MetricsTracker()
43
43
  inject_steps = []
44
44
 
45
- # 0. Quota and Environment Audits (Fires on first invocation)
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
- try:
49
- from src.telemetry_sync import TelemetrySync
50
- TelemetrySync.sync_background()
51
- except Exception:
52
- pass
53
55
  if quota.get("warning"):
54
56
  inject_steps.append({
55
57
  "systemMessage": {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tokensafe",
3
- "version": "1.4.4",
3
+ "version": "1.4.5",
4
4
  "description": "Autonomous Zero-Loss Token Economy & Context Optimizer for AI Coding Agents",
5
5
  "main": "bin/tokensafe.js",
6
6
  "bin": {
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",
4
+ "version": "1.4.5",
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/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.3"
34
+ "version": "1.4.5"
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
 
@@ -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.4"
239
+ "User-Agent": "TokenSafe-Sync/1.4.5"
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 = 300.0):
293
+ def sync_background(cls, throttle_seconds: float = 60.0, force: bool = False):
292
294
  """
293
- Spawns a detached, non-blocking daemon thread to sync metrics.
294
- Throttled to run at most once every `throttle_seconds` (default: 5 minutes).
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
- if now - cls._last_bg_sync_time < throttle_seconds:
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
- cls._last_bg_sync_time = now
306
+ status = cls.get_sync_status()
307
+ if status.get("pending_events", 0) == 0:
308
+ return
301
309
 
302
- def _worker():
310
+ # Prevent overlapping sync runs via PID lock file
311
+ if os.path.exists(SYNC_LOCK_PATH):
303
312
  try:
304
- cls.sync(timeout=2.0)
305
- except Exception:
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
- t = threading.Thread(target=_worker, daemon=True)
309
- t.start()
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
@@ -14,7 +14,7 @@ import urllib.request
14
14
  import urllib.error
15
15
  from typing import Dict, Any, Optional, Tuple
16
16
 
17
- CURRENT_VERSION = "1.4.4"
17
+ CURRENT_VERSION = "1.4.5"
18
18
  CACHE_TTL = 86400 # 24 hours
19
19
 
20
20
  PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))