File size: 2,615 Bytes
48d9178
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
916303a
 
 
7ba8208
 
48d9178
 
 
 
 
 
 
 
916303a
 
48d9178
 
 
 
 
 
 
 
 
 
 
 
 
 
 
916303a
 
 
 
 
48d9178
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
"""il_shared_usage.py — mirror ONE usage event into the shared Upstash Redis list.

WRITE-ONLY client. It appends to the same `usage:events` list that the IL CMS MCP
server reads, so a single always-on dashboard
(https://il-mcp-server.vercel.app/dashboard?key=<DASHBOARD_KEY>) shows activity from
EVERY IL tool in one place. Fire-and-forget: any failure is swallowed so it can never
break the caller. Drop an identical copy of this file into each tool's folder.

Env (set by each tool's launch script):
  UPSTASH_REDIS_REST_URL, UPSTASH_REDIS_REST_TOKEN  — the shared store.
  IL_USAGE_SOURCE — label for this process, e.g. "gpt-backend" / "paper-gen" / "web-app".
"""
from __future__ import annotations

import os
from datetime import datetime, timezone, timedelta

try:
    import requests
except Exception:  # requests missing -> logging simply becomes a no-op
    requests = None

# All timestamps normalised to Indian Standard Time so every process (local, ngrok,
# Vercel-UTC) lands on one consistent clock in the shared dashboard.
IST = timezone(timedelta(hours=5, minutes=30))

# Usage events go to the Supabase `usage_events` table (Upstash retired 2026-07-11).
# Set SUPABASE_URL and SUPABASE_KEY in this tool's environment. Fire-and-forget: if unset
# or on any error, logging silently no-ops so it can never break the caller.
_SB_URL = os.environ.get("SUPABASE_URL", "").rstrip("/")
_SB_KEY = os.environ.get("SUPABASE_KEY", "") or os.environ.get("SUPABASE_SERVICE_KEY", "")


def _source() -> str:
    return os.environ.get("IL_USAGE_SOURCE", "").strip() or "local"


def push(tool, action="", author="", phone="", ok=True,
         question_id="", status="", subject="", detail=""):
    """Append one usage event to Supabase. Never raises."""
    if not (requests and _SB_URL and _SB_KEY):
        return
    try:
        ev = {
            "ts": datetime.now(IST).replace(tzinfo=None).isoformat(timespec="seconds"),
            "source": _source(),
            "tool": tool,
            "action": action or "",
            "phone": phone or "",
            "author": author or "",
            "ok": bool(ok),
            "question_id": question_id or "",
            "status": status or "",
            "subject": subject or "",
            "detail": detail or "",
        }
        requests.post(
            f"{_SB_URL}/rest/v1/usage_events",
            headers={"apikey": _SB_KEY, "Authorization": f"Bearer {_SB_KEY}",
                     "Content-Type": "application/json", "Prefer": "return=minimal"},
            json=ev, timeout=6).raise_for_status()
    except Exception:
        pass