tokensafe 1.2.0 → 1.3.1
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/README.md +200 -16
- package/bin/agy-tokens +156 -4
- package/bin/tokensafe.js +7 -0
- package/hooks/pre_invocation.py +40 -11
- package/hooks/pre_tool_use.py +23 -3
- package/package.json +7 -3
- package/plugin.json +1 -1
- package/rules/AGENTS.md +6 -0
- package/skills/token-optimizer/SKILL.md +1 -0
- package/src/__init__.py +1 -1
- package/src/agent_firewall.py +146 -0
- package/src/benchmark.py +68 -9
- package/src/cache_normalizer.py +105 -0
- package/src/command_sanitizer.py +21 -12
- package/src/dashboard.py +54 -7
- package/src/diff_slicer.py +120 -0
- package/src/environment_auditor.py +259 -0
- package/src/governor.py +166 -0
- package/src/graph_engine.py +4 -0
- package/src/installer.py +192 -34
- package/src/license_manager.py +157 -23
- package/src/mcp_server.py +59 -7
- package/src/metrics.py +261 -21
- package/src/proxy.py +160 -18
- package/src/version_checker.py +156 -0
- package/src/weekly_digest.py +305 -0
- package/src/mailer.py +0 -327
package/src/metrics.py
CHANGED
|
@@ -8,23 +8,28 @@ import os
|
|
|
8
8
|
import json
|
|
9
9
|
import sqlite3
|
|
10
10
|
from contextlib import contextmanager
|
|
11
|
-
from datetime import datetime
|
|
11
|
+
from datetime import datetime, timedelta
|
|
12
12
|
from typing import Dict, List, Optional, Any, Generator
|
|
13
13
|
|
|
14
14
|
USD_PER_TOKEN = 1.50 / 1_000_000.0
|
|
15
15
|
|
|
16
16
|
|
|
17
17
|
class MetricsTracker:
|
|
18
|
-
"""Manages persistent token savings metrics in SQLite."""
|
|
18
|
+
"""Manages persistent token savings metrics in SQLite with lifetime rollups and retention."""
|
|
19
19
|
|
|
20
20
|
def __init__(self, db_path: Optional[str] = None):
|
|
21
21
|
if db_path is None:
|
|
22
|
-
|
|
23
|
-
|
|
22
|
+
data_dir = os.environ.get("TOKENSAFE_DATA_DIR")
|
|
23
|
+
if not data_dir:
|
|
24
|
+
base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
25
|
+
data_dir = os.path.join(base_dir, "data")
|
|
24
26
|
os.makedirs(data_dir, exist_ok=True)
|
|
25
|
-
db_path = os.path.join(data_dir, "metrics.db")
|
|
27
|
+
db_path = os.environ.get("TOKENSAFE_DB_PATH", os.path.join(data_dir, "metrics.db"))
|
|
26
28
|
|
|
27
29
|
self.db_path = db_path
|
|
30
|
+
self.retention_days = int(os.environ.get("TOKENSAFE_RETENTION_DAYS", "30"))
|
|
31
|
+
self.max_events = int(os.environ.get("TOKENSAFE_MAX_EVENTS", "5000"))
|
|
32
|
+
self._event_counter = 0
|
|
28
33
|
self._init_db()
|
|
29
34
|
|
|
30
35
|
@contextmanager
|
|
@@ -65,6 +70,25 @@ class MetricsTracker:
|
|
|
65
70
|
details TEXT
|
|
66
71
|
)
|
|
67
72
|
""")
|
|
73
|
+
cursor.execute("""
|
|
74
|
+
CREATE TABLE IF NOT EXISTS lifetime_aggregates (
|
|
75
|
+
id INTEGER PRIMARY KEY CHECK (id = 1),
|
|
76
|
+
total_events INTEGER DEFAULT 0,
|
|
77
|
+
total_original_tokens INTEGER DEFAULT 0,
|
|
78
|
+
total_optimized_tokens INTEGER DEFAULT 0,
|
|
79
|
+
total_saved_tokens INTEGER DEFAULT 0,
|
|
80
|
+
total_usd_saved REAL DEFAULT 0.0,
|
|
81
|
+
breakdown TEXT DEFAULT '{}'
|
|
82
|
+
)
|
|
83
|
+
""")
|
|
84
|
+
cursor.execute("""
|
|
85
|
+
INSERT OR IGNORE INTO lifetime_aggregates (
|
|
86
|
+
id, total_events, total_original_tokens, total_optimized_tokens,
|
|
87
|
+
total_saved_tokens, total_usd_saved, breakdown
|
|
88
|
+
) VALUES (1, 0, 0, 0, 0, 0.0, '{}')
|
|
89
|
+
""")
|
|
90
|
+
cursor.execute("CREATE INDEX IF NOT EXISTS idx_events_timestamp ON events(timestamp)")
|
|
91
|
+
cursor.execute("CREATE INDEX IF NOT EXISTS idx_events_session_id ON events(session_id)")
|
|
68
92
|
|
|
69
93
|
def record_event(
|
|
70
94
|
self,
|
|
@@ -107,6 +131,15 @@ class MetricsTracker:
|
|
|
107
131
|
""", (session_id, now_iso, now_iso, original_tokens,
|
|
108
132
|
optimized_tokens, saved_tokens, est_usd))
|
|
109
133
|
|
|
134
|
+
# Periodic amortized auto-retention check (every 100 events)
|
|
135
|
+
self._event_counter += 1
|
|
136
|
+
if self._event_counter >= 100:
|
|
137
|
+
self._event_counter = 0
|
|
138
|
+
try:
|
|
139
|
+
self.prune(days=self.retention_days, max_events=self.max_events, vacuum=False)
|
|
140
|
+
except Exception:
|
|
141
|
+
pass
|
|
142
|
+
|
|
110
143
|
return {
|
|
111
144
|
"saved_tokens": saved_tokens,
|
|
112
145
|
"reduction_pct": round(reduction_pct, 1),
|
|
@@ -114,41 +147,68 @@ class MetricsTracker:
|
|
|
114
147
|
}
|
|
115
148
|
|
|
116
149
|
def get_summary(self) -> Dict[str, Any]:
|
|
117
|
-
"""Returns cumulative statistics across all sessions."""
|
|
150
|
+
"""Returns cumulative statistics across all sessions, including lifetime rollups."""
|
|
118
151
|
with self._get_connection() as conn:
|
|
119
152
|
cursor = conn.cursor()
|
|
153
|
+
|
|
154
|
+
# 1. Lifetime aggregates
|
|
155
|
+
cursor.execute("SELECT * FROM lifetime_aggregates WHERE id = 1")
|
|
156
|
+
life_row = cursor.fetchone()
|
|
157
|
+
life_events = life_row["total_events"] if life_row else 0
|
|
158
|
+
life_orig = life_row["total_original_tokens"] if life_row else 0
|
|
159
|
+
life_opt = life_row["total_optimized_tokens"] if life_row else 0
|
|
160
|
+
life_saved = life_row["total_saved_tokens"] if life_row else 0
|
|
161
|
+
life_usd = life_row["total_usd_saved"] if life_row else 0.0
|
|
162
|
+
life_breakdown = json.loads(life_row["breakdown"] or "{}") if life_row else {}
|
|
163
|
+
|
|
164
|
+
# 2. Active events
|
|
120
165
|
cursor.execute("""
|
|
121
166
|
SELECT
|
|
122
|
-
COUNT(
|
|
123
|
-
|
|
124
|
-
COALESCE(SUM(
|
|
125
|
-
COALESCE(SUM(
|
|
126
|
-
COALESCE(SUM(
|
|
127
|
-
COALESCE(SUM(est_usd_saved), 0.0) as total_usd
|
|
167
|
+
COUNT(*) as active_events,
|
|
168
|
+
COALESCE(SUM(original_tokens), 0) as active_orig,
|
|
169
|
+
COALESCE(SUM(optimized_tokens), 0) as active_opt,
|
|
170
|
+
COALESCE(SUM(saved_tokens), 0) as active_saved,
|
|
171
|
+
COALESCE(SUM(est_usd_saved), 0.0) as active_usd
|
|
128
172
|
FROM events
|
|
129
173
|
""")
|
|
130
|
-
|
|
174
|
+
ev_row = cursor.fetchone()
|
|
131
175
|
|
|
176
|
+
cursor.execute("SELECT COUNT(DISTINCT session_id) as session_count FROM sessions")
|
|
177
|
+
sess_row = cursor.fetchone()
|
|
178
|
+
session_count = sess_row["session_count"] if sess_row else 0
|
|
179
|
+
|
|
180
|
+
# 3. Breakdown of active events
|
|
132
181
|
cursor.execute("""
|
|
133
182
|
SELECT event_type, COUNT(*) as count, COALESCE(SUM(saved_tokens), 0) as saved
|
|
134
183
|
FROM events
|
|
135
184
|
GROUP BY event_type
|
|
136
185
|
""")
|
|
137
|
-
|
|
186
|
+
combined_breakdown = dict(life_breakdown)
|
|
187
|
+
for r in cursor.fetchall():
|
|
188
|
+
ev_type = r["event_type"]
|
|
189
|
+
if ev_type not in combined_breakdown:
|
|
190
|
+
combined_breakdown[ev_type] = {"count": 0, "saved": 0}
|
|
191
|
+
else:
|
|
192
|
+
combined_breakdown[ev_type] = dict(combined_breakdown[ev_type])
|
|
193
|
+
combined_breakdown[ev_type]["count"] += r["count"]
|
|
194
|
+
combined_breakdown[ev_type]["saved"] += r["saved"]
|
|
138
195
|
|
|
139
|
-
|
|
140
|
-
|
|
196
|
+
total_events = life_events + (ev_row["active_events"] if ev_row else 0)
|
|
197
|
+
total_orig = life_orig + (ev_row["active_orig"] if ev_row else 0)
|
|
198
|
+
total_opt = life_opt + (ev_row["active_opt"] if ev_row else 0)
|
|
199
|
+
total_saved = life_saved + (ev_row["active_saved"] if ev_row else 0)
|
|
200
|
+
total_usd = life_usd + (ev_row["active_usd"] if ev_row else 0.0)
|
|
141
201
|
overall_reduction = (total_saved / total_orig * 100.0) if total_orig > 0 else 0.0
|
|
142
202
|
|
|
143
203
|
return {
|
|
144
|
-
"session_count":
|
|
145
|
-
"total_events":
|
|
204
|
+
"session_count": max(session_count, 1 if total_events > 0 else 0),
|
|
205
|
+
"total_events": total_events,
|
|
146
206
|
"total_original_tokens": total_orig,
|
|
147
|
-
"total_optimized_tokens":
|
|
207
|
+
"total_optimized_tokens": total_opt,
|
|
148
208
|
"total_saved_tokens": total_saved,
|
|
149
209
|
"overall_reduction_pct": round(overall_reduction, 1),
|
|
150
|
-
"total_usd_saved": round(
|
|
151
|
-
"breakdown":
|
|
210
|
+
"total_usd_saved": round(total_usd, 4),
|
|
211
|
+
"breakdown": combined_breakdown
|
|
152
212
|
}
|
|
153
213
|
|
|
154
214
|
def get_recent_events(self, limit: int = 10) -> List[Dict[str, Any]]:
|
|
@@ -174,9 +234,189 @@ class MetricsTracker:
|
|
|
174
234
|
events.append(ev)
|
|
175
235
|
return events
|
|
176
236
|
|
|
237
|
+
def get_last_event(self, session_id: str, event_type: str) -> Optional[Dict[str, Any]]:
|
|
238
|
+
"""Returns the most recent event of a given type for a session."""
|
|
239
|
+
with self._get_connection() as conn:
|
|
240
|
+
cursor = conn.cursor()
|
|
241
|
+
cursor.execute("""
|
|
242
|
+
SELECT id, session_id, timestamp, event_type, original_tokens,
|
|
243
|
+
optimized_tokens, saved_tokens, reduction_pct, est_usd_saved, details
|
|
244
|
+
FROM events
|
|
245
|
+
WHERE session_id = ? AND event_type = ?
|
|
246
|
+
ORDER BY id DESC
|
|
247
|
+
LIMIT 1
|
|
248
|
+
""", (session_id, event_type))
|
|
249
|
+
row = cursor.fetchone()
|
|
250
|
+
if not row:
|
|
251
|
+
return None
|
|
252
|
+
res = dict(row)
|
|
253
|
+
try:
|
|
254
|
+
res["details"] = json.loads(res["details"])
|
|
255
|
+
except Exception:
|
|
256
|
+
pass
|
|
257
|
+
return res
|
|
258
|
+
|
|
259
|
+
def recalculate_sessions(self):
|
|
260
|
+
"""Recalculates sessions table aggregates directly from events table."""
|
|
261
|
+
with self._get_connection() as conn:
|
|
262
|
+
cursor = conn.cursor()
|
|
263
|
+
cursor.execute("DELETE FROM sessions")
|
|
264
|
+
cursor.execute("""
|
|
265
|
+
INSERT INTO sessions (
|
|
266
|
+
session_id, created_at, last_updated,
|
|
267
|
+
total_original_tokens, total_optimized_tokens,
|
|
268
|
+
total_saved_tokens, total_usd_saved
|
|
269
|
+
)
|
|
270
|
+
SELECT
|
|
271
|
+
session_id,
|
|
272
|
+
MIN(timestamp) as created_at,
|
|
273
|
+
MAX(timestamp) as last_updated,
|
|
274
|
+
COALESCE(SUM(original_tokens), 0) as total_original_tokens,
|
|
275
|
+
COALESCE(SUM(optimized_tokens), 0) as total_optimized_tokens,
|
|
276
|
+
COALESCE(SUM(saved_tokens), 0) as total_saved_tokens,
|
|
277
|
+
COALESCE(SUM(est_usd_saved), 0.0) as total_usd_saved
|
|
278
|
+
FROM events
|
|
279
|
+
GROUP BY session_id
|
|
280
|
+
""")
|
|
281
|
+
|
|
282
|
+
def prune(
|
|
283
|
+
self,
|
|
284
|
+
days: Optional[int] = None,
|
|
285
|
+
max_events: Optional[int] = None,
|
|
286
|
+
vacuum: bool = True
|
|
287
|
+
) -> Dict[str, Any]:
|
|
288
|
+
"""
|
|
289
|
+
Prunes raw events older than `days` or exceeding `max_events`.
|
|
290
|
+
Preserves cumulative metrics by rolling pruned data into `lifetime_aggregates`.
|
|
291
|
+
"""
|
|
292
|
+
db_size_before = os.path.getsize(self.db_path) if os.path.exists(self.db_path) else 0
|
|
293
|
+
|
|
294
|
+
where_clauses = []
|
|
295
|
+
params = []
|
|
296
|
+
|
|
297
|
+
if days is not None and days > 0:
|
|
298
|
+
cutoff_time = (datetime.now() - timedelta(days=days)).isoformat()
|
|
299
|
+
where_clauses.append("timestamp < ?")
|
|
300
|
+
params.append(cutoff_time)
|
|
301
|
+
|
|
302
|
+
if max_events is not None and max_events > 0:
|
|
303
|
+
with self._get_connection() as conn:
|
|
304
|
+
cursor = conn.cursor()
|
|
305
|
+
cursor.execute(
|
|
306
|
+
"SELECT id FROM events ORDER BY id DESC LIMIT 1 OFFSET ?",
|
|
307
|
+
(max_events,)
|
|
308
|
+
)
|
|
309
|
+
row = cursor.fetchone()
|
|
310
|
+
if row:
|
|
311
|
+
cutoff_id = row[0]
|
|
312
|
+
where_clauses.append("id <= ?")
|
|
313
|
+
params.append(cutoff_id)
|
|
314
|
+
|
|
315
|
+
if not where_clauses:
|
|
316
|
+
return {
|
|
317
|
+
"pruned_events": 0,
|
|
318
|
+
"db_size_before": db_size_before,
|
|
319
|
+
"db_size_after": db_size_before
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
combined_where = " OR ".join(where_clauses)
|
|
323
|
+
|
|
324
|
+
with self._get_connection() as conn:
|
|
325
|
+
cursor = conn.cursor()
|
|
326
|
+
|
|
327
|
+
# 1. Calculate aggregates for events to be pruned
|
|
328
|
+
cursor.execute(f"""
|
|
329
|
+
SELECT
|
|
330
|
+
COUNT(*) as cnt,
|
|
331
|
+
COALESCE(SUM(original_tokens), 0) as orig,
|
|
332
|
+
COALESCE(SUM(optimized_tokens), 0) as opt,
|
|
333
|
+
COALESCE(SUM(saved_tokens), 0) as saved,
|
|
334
|
+
COALESCE(SUM(est_usd_saved), 0.0) as usd
|
|
335
|
+
FROM events
|
|
336
|
+
WHERE {combined_where}
|
|
337
|
+
""", params)
|
|
338
|
+
agg_row = cursor.fetchone()
|
|
339
|
+
prune_count = agg_row["cnt"] if agg_row else 0
|
|
340
|
+
|
|
341
|
+
if prune_count > 0:
|
|
342
|
+
# 2. Breakdown of pruned events
|
|
343
|
+
cursor.execute(f"""
|
|
344
|
+
SELECT event_type, COUNT(*) as cnt, COALESCE(SUM(saved_tokens), 0) as saved
|
|
345
|
+
FROM events
|
|
346
|
+
WHERE {combined_where}
|
|
347
|
+
GROUP BY event_type
|
|
348
|
+
""", params)
|
|
349
|
+
pruned_breakdown = {
|
|
350
|
+
r["event_type"]: {"count": r["cnt"], "saved": r["saved"]}
|
|
351
|
+
for r in cursor.fetchall()
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
# 3. Fetch existing lifetime aggregates
|
|
355
|
+
cursor.execute("SELECT * FROM lifetime_aggregates WHERE id = 1")
|
|
356
|
+
life_row = cursor.fetchone()
|
|
357
|
+
current_breakdown = json.loads(life_row["breakdown"] or "{}") if life_row else {}
|
|
358
|
+
|
|
359
|
+
for ev_type, vals in pruned_breakdown.items():
|
|
360
|
+
if ev_type not in current_breakdown:
|
|
361
|
+
current_breakdown[ev_type] = {"count": 0, "saved": 0}
|
|
362
|
+
else:
|
|
363
|
+
current_breakdown[ev_type] = dict(current_breakdown[ev_type])
|
|
364
|
+
current_breakdown[ev_type]["count"] += vals["count"]
|
|
365
|
+
current_breakdown[ev_type]["saved"] += vals["saved"]
|
|
366
|
+
|
|
367
|
+
# 4. Update lifetime_aggregates
|
|
368
|
+
cursor.execute("""
|
|
369
|
+
UPDATE lifetime_aggregates SET
|
|
370
|
+
total_events = total_events + ?,
|
|
371
|
+
total_original_tokens = total_original_tokens + ?,
|
|
372
|
+
total_optimized_tokens = total_optimized_tokens + ?,
|
|
373
|
+
total_saved_tokens = total_saved_tokens + ?,
|
|
374
|
+
total_usd_saved = total_usd_saved + ?,
|
|
375
|
+
breakdown = ?
|
|
376
|
+
WHERE id = 1
|
|
377
|
+
""", (
|
|
378
|
+
agg_row["cnt"], agg_row["orig"], agg_row["opt"],
|
|
379
|
+
agg_row["saved"], agg_row["usd"],
|
|
380
|
+
json.dumps(current_breakdown, ensure_ascii=False)
|
|
381
|
+
))
|
|
382
|
+
|
|
383
|
+
# 5. Delete pruned events
|
|
384
|
+
cursor.execute(f"DELETE FROM events WHERE {combined_where}", params)
|
|
385
|
+
|
|
386
|
+
if vacuum and prune_count > 0:
|
|
387
|
+
self.vacuum()
|
|
388
|
+
|
|
389
|
+
db_size_after = os.path.getsize(self.db_path) if os.path.exists(self.db_path) else 0
|
|
390
|
+
|
|
391
|
+
return {
|
|
392
|
+
"pruned_events": prune_count,
|
|
393
|
+
"db_size_before": db_size_before,
|
|
394
|
+
"db_size_after": db_size_after
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
def vacuum(self):
|
|
398
|
+
"""Reclaims unused disk space by running VACUUM on SQLite."""
|
|
399
|
+
try:
|
|
400
|
+
conn = sqlite3.connect(self.db_path, isolation_level=None)
|
|
401
|
+
conn.execute("VACUUM")
|
|
402
|
+
conn.close()
|
|
403
|
+
except Exception:
|
|
404
|
+
pass
|
|
405
|
+
|
|
177
406
|
def reset(self):
|
|
178
407
|
"""Resets all metrics data."""
|
|
179
408
|
with self._get_connection() as conn:
|
|
180
409
|
cursor = conn.cursor()
|
|
181
410
|
cursor.execute("DELETE FROM events")
|
|
182
411
|
cursor.execute("DELETE FROM sessions")
|
|
412
|
+
cursor.execute("""
|
|
413
|
+
UPDATE lifetime_aggregates SET
|
|
414
|
+
total_events = 0,
|
|
415
|
+
total_original_tokens = 0,
|
|
416
|
+
total_optimized_tokens = 0,
|
|
417
|
+
total_saved_tokens = 0,
|
|
418
|
+
total_usd_saved = 0.0,
|
|
419
|
+
breakdown = '{}'
|
|
420
|
+
WHERE id = 1
|
|
421
|
+
""")
|
|
422
|
+
self.vacuum()
|
package/src/proxy.py
CHANGED
|
@@ -8,10 +8,12 @@ Endpoint: http://127.0.0.1:8765/v1
|
|
|
8
8
|
import sys
|
|
9
9
|
import os
|
|
10
10
|
import json
|
|
11
|
+
import queue
|
|
12
|
+
import threading
|
|
11
13
|
import urllib.request
|
|
12
14
|
import urllib.error
|
|
13
15
|
from http.server import HTTPServer, BaseHTTPRequestHandler
|
|
14
|
-
from typing import Dict, Any
|
|
16
|
+
from typing import Dict, Any, List
|
|
15
17
|
|
|
16
18
|
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
17
19
|
sys.path.insert(0, BASE_DIR)
|
|
@@ -22,10 +24,44 @@ from src.dashboard import Dashboard
|
|
|
22
24
|
from src.loop_detector import LoopDetector
|
|
23
25
|
from src.secret_redactor import SecretRedactor
|
|
24
26
|
from src.graph_engine import GraphEngine
|
|
27
|
+
from src.cache_normalizer import PromptCacheNormalizer
|
|
28
|
+
from src.governor import ContextGovernor
|
|
25
29
|
|
|
26
30
|
DEFAULT_PORT = 8765
|
|
31
|
+
DEFAULT_HOST = os.environ.get("HOST", os.environ.get("TOKENSAFE_HOST", "0.0.0.0"))
|
|
27
32
|
DEFAULT_UPSTREAM = "https://api.deepseek.com/v1"
|
|
28
33
|
|
|
34
|
+
class EventBroadcaster:
|
|
35
|
+
"""Thread-safe pub/sub for Server-Sent Events (SSE) streaming."""
|
|
36
|
+
def __init__(self):
|
|
37
|
+
self._subscribers: List[queue.Queue] = []
|
|
38
|
+
self._lock = threading.Lock()
|
|
39
|
+
|
|
40
|
+
def subscribe(self) -> queue.Queue:
|
|
41
|
+
q = queue.Queue(maxsize=50)
|
|
42
|
+
with self._lock:
|
|
43
|
+
self._subscribers.append(q)
|
|
44
|
+
return q
|
|
45
|
+
|
|
46
|
+
def unsubscribe(self, q: queue.Queue):
|
|
47
|
+
with self._lock:
|
|
48
|
+
if q in self._subscribers:
|
|
49
|
+
self._subscribers.remove(q)
|
|
50
|
+
|
|
51
|
+
def publish(self, event_type: str, data: Dict[str, Any]):
|
|
52
|
+
payload = f"event: {event_type}\ndata: {json.dumps(data, ensure_ascii=False)}\n\n"
|
|
53
|
+
with self._lock:
|
|
54
|
+
dead = []
|
|
55
|
+
for q in self._subscribers:
|
|
56
|
+
try:
|
|
57
|
+
q.put_nowait(payload)
|
|
58
|
+
except queue.Full:
|
|
59
|
+
dead.append(q)
|
|
60
|
+
for d in dead:
|
|
61
|
+
self._subscribers.remove(d)
|
|
62
|
+
|
|
63
|
+
BROADCASTER = EventBroadcaster()
|
|
64
|
+
|
|
29
65
|
class TokenSafeProxyHandler(BaseHTTPRequestHandler):
|
|
30
66
|
"""Handles HTTP requests and proxies /v1/chat/completions with token optimization."""
|
|
31
67
|
|
|
@@ -33,7 +69,26 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
|
|
|
33
69
|
# Mute noisy default server logs
|
|
34
70
|
pass
|
|
35
71
|
|
|
72
|
+
def _validate_origin(self) -> bool:
|
|
73
|
+
"""Protects against DNS rebinding and cross-origin attacks from arbitrary browser origins."""
|
|
74
|
+
origin = self.headers.get("Origin", "")
|
|
75
|
+
if origin:
|
|
76
|
+
allowed_prefixes = ["http://127.0.0.1", "http://localhost", "http://0.0.0.0", "https://tokensafe.dev"]
|
|
77
|
+
custom_origins = os.environ.get("TOKENSAFE_ALLOWED_ORIGINS", "")
|
|
78
|
+
if custom_origins:
|
|
79
|
+
allowed_prefixes.extend([o.strip() for o in custom_origins.split(",") if o.strip()])
|
|
80
|
+
if not any(origin.startswith(a) for a in allowed_prefixes):
|
|
81
|
+
self.send_response(403)
|
|
82
|
+
self.send_header("Content-Type", "application/json")
|
|
83
|
+
self.end_headers()
|
|
84
|
+
self.wfile.write(b'{"error": "Forbidden: Untrusted cross-origin request rejected"}')
|
|
85
|
+
return False
|
|
86
|
+
return True
|
|
87
|
+
|
|
36
88
|
def do_GET(self):
|
|
89
|
+
if not self._validate_origin():
|
|
90
|
+
return
|
|
91
|
+
|
|
37
92
|
tracker = MetricsTracker()
|
|
38
93
|
dashboard = Dashboard(tracker)
|
|
39
94
|
|
|
@@ -51,6 +106,35 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
|
|
|
51
106
|
self.end_headers()
|
|
52
107
|
self.wfile.write(json.dumps(summary, indent=2).encode("utf-8"))
|
|
53
108
|
|
|
109
|
+
elif self.path in ("/api/events", "/events"):
|
|
110
|
+
self.send_response(200)
|
|
111
|
+
self.send_header("Content-Type", "text/event-stream")
|
|
112
|
+
self.send_header("Cache-Control", "no-cache")
|
|
113
|
+
self.send_header("Connection", "keep-alive")
|
|
114
|
+
self.send_header("Access-Control-Allow-Origin", "*")
|
|
115
|
+
self.end_headers()
|
|
116
|
+
|
|
117
|
+
q = BROADCASTER.subscribe()
|
|
118
|
+
try:
|
|
119
|
+
initial_summary = tracker.get_summary()
|
|
120
|
+
init_msg = f"event: init\ndata: {json.dumps(initial_summary, ensure_ascii=False)}\n\n"
|
|
121
|
+
self.wfile.write(init_msg.encode("utf-8"))
|
|
122
|
+
self.wfile.flush()
|
|
123
|
+
|
|
124
|
+
while True:
|
|
125
|
+
try:
|
|
126
|
+
msg = q.get(timeout=15.0)
|
|
127
|
+
self.wfile.write(msg.encode("utf-8"))
|
|
128
|
+
self.wfile.flush()
|
|
129
|
+
except queue.Empty:
|
|
130
|
+
self.wfile.write(b": heartbeat\n\n")
|
|
131
|
+
self.wfile.flush()
|
|
132
|
+
except (BrokenPipeError, ConnectionResetError):
|
|
133
|
+
pass
|
|
134
|
+
finally:
|
|
135
|
+
BROADCASTER.unsubscribe(q)
|
|
136
|
+
return
|
|
137
|
+
|
|
54
138
|
elif self.path == "/health":
|
|
55
139
|
self.send_response(200)
|
|
56
140
|
self.send_header("Content-Type", "application/json")
|
|
@@ -62,6 +146,9 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
|
|
|
62
146
|
self.end_headers()
|
|
63
147
|
|
|
64
148
|
def do_POST(self):
|
|
149
|
+
if not self._validate_origin():
|
|
150
|
+
return
|
|
151
|
+
|
|
65
152
|
if self.path.startswith("/v1/chat/completions"):
|
|
66
153
|
self.handle_chat_completions()
|
|
67
154
|
else:
|
|
@@ -111,29 +198,75 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
|
|
|
111
198
|
except Exception:
|
|
112
199
|
pass
|
|
113
200
|
|
|
114
|
-
# 4.
|
|
201
|
+
# 4. Prompt Cache Prefix Normalization (100% Cache Hits)
|
|
202
|
+
if messages:
|
|
203
|
+
messages, cache_meta = PromptCacheNormalizer.normalize_messages(messages)
|
|
204
|
+
payload["messages"] = messages
|
|
205
|
+
|
|
206
|
+
# 5. Context Window Governor (Budget Autothrottle)
|
|
207
|
+
if messages:
|
|
208
|
+
messages, gov_stats = ContextGovernor.govern_messages(messages, session_id="proxy_session")
|
|
209
|
+
payload["messages"] = messages
|
|
210
|
+
if gov_stats.get("throttled"):
|
|
211
|
+
BROADCASTER.publish("governor_throttle", gov_stats)
|
|
212
|
+
|
|
213
|
+
# 6. Resolve Multi-Provider Upstream & API Key
|
|
115
214
|
auth_header = self.headers.get("Authorization", "")
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
215
|
+
custom_url = os.environ.get("TOKENSAFE_UPSTREAM_URL", "")
|
|
216
|
+
|
|
217
|
+
# Supported keys from environment or config
|
|
218
|
+
data_dir = os.environ.get("TOKENSAFE_DATA_DIR", os.path.join(BASE_DIR, "data"))
|
|
219
|
+
conf_keys = {}
|
|
220
|
+
config_path = os.path.join(data_dir, "config.json")
|
|
119
221
|
if os.path.exists(config_path):
|
|
120
222
|
try:
|
|
121
223
|
with open(config_path) as f:
|
|
122
|
-
|
|
123
|
-
upstream_key = conf.get("deepseek_api_key", "")
|
|
224
|
+
conf_keys = json.load(f)
|
|
124
225
|
except Exception:
|
|
125
226
|
pass
|
|
126
227
|
|
|
127
|
-
|
|
128
|
-
|
|
228
|
+
deepseek_key = os.environ.get("DEEPSEEK_API_KEY", "") or conf_keys.get("deepseek_api_key", "")
|
|
229
|
+
openai_key = os.environ.get("OPENAI_API_KEY", "") or conf_keys.get("openai_api_key", "")
|
|
230
|
+
gemini_key = os.environ.get("GEMINI_API_KEY", "") or conf_keys.get("gemini_api_key", "")
|
|
231
|
+
anthropic_key = os.environ.get("ANTHROPIC_API_KEY", "") or conf_keys.get("anthropic_api_key", "")
|
|
232
|
+
generic_upstream_key = os.environ.get("TOKENSAFE_UPSTREAM_KEY", "")
|
|
233
|
+
|
|
234
|
+
# Infer upstream URL if not provided
|
|
235
|
+
if not custom_url:
|
|
236
|
+
if openai_key and not deepseek_key:
|
|
237
|
+
upstream_url = "https://api.openai.com/v1/chat/completions"
|
|
238
|
+
resolved_key = openai_key
|
|
239
|
+
elif anthropic_key and not deepseek_key:
|
|
240
|
+
upstream_url = "https://api.anthropic.com/v1/messages"
|
|
241
|
+
resolved_key = anthropic_key
|
|
242
|
+
else:
|
|
243
|
+
upstream_url = "https://api.deepseek.com/chat/completions"
|
|
244
|
+
resolved_key = deepseek_key or generic_upstream_key
|
|
245
|
+
else:
|
|
246
|
+
upstream_url = custom_url
|
|
247
|
+
if "openai.com" in upstream_url:
|
|
248
|
+
resolved_key = openai_key or generic_upstream_key or deepseek_key
|
|
249
|
+
elif "anthropic.com" in upstream_url:
|
|
250
|
+
resolved_key = anthropic_key or generic_upstream_key
|
|
251
|
+
elif "googleapis.com" in upstream_url:
|
|
252
|
+
resolved_key = gemini_key or generic_upstream_key
|
|
253
|
+
else:
|
|
254
|
+
resolved_key = deepseek_key or generic_upstream_key or openai_key
|
|
255
|
+
|
|
256
|
+
headers = {"Content-Type": "application/json"}
|
|
257
|
+
if auth_header:
|
|
258
|
+
headers["Authorization"] = auth_header
|
|
259
|
+
elif resolved_key:
|
|
260
|
+
if "anthropic.com" in upstream_url:
|
|
261
|
+
headers["x-api-key"] = resolved_key
|
|
262
|
+
headers["anthropic-version"] = "2023-06-01"
|
|
263
|
+
else:
|
|
264
|
+
headers["Authorization"] = f"Bearer {resolved_key}"
|
|
129
265
|
|
|
130
266
|
req = urllib.request.Request(
|
|
131
267
|
upstream_url,
|
|
132
268
|
data=json.dumps(payload).encode("utf-8"),
|
|
133
|
-
headers=
|
|
134
|
-
"Authorization": final_auth,
|
|
135
|
-
"Content-Type": "application/json"
|
|
136
|
-
}
|
|
269
|
+
headers=headers
|
|
137
270
|
)
|
|
138
271
|
|
|
139
272
|
try:
|
|
@@ -145,6 +278,14 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
|
|
|
145
278
|
self.send_header(k, v)
|
|
146
279
|
self.end_headers()
|
|
147
280
|
self.wfile.write(resp_data)
|
|
281
|
+
|
|
282
|
+
# Broadcast live telemetry update to SSE dashboard subscribers
|
|
283
|
+
try:
|
|
284
|
+
tracker = MetricsTracker()
|
|
285
|
+
summary = tracker.get_summary()
|
|
286
|
+
BROADCASTER.publish("stats_update", summary)
|
|
287
|
+
except Exception:
|
|
288
|
+
pass
|
|
148
289
|
except urllib.error.HTTPError as e:
|
|
149
290
|
self.send_response(e.code)
|
|
150
291
|
self.end_headers()
|
|
@@ -154,7 +295,7 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
|
|
|
154
295
|
self.end_headers()
|
|
155
296
|
self.wfile.write(json.dumps({"error": f"Upstream proxy error: {str(e)}"}).encode("utf-8"))
|
|
156
297
|
|
|
157
|
-
def run_proxy(port: int = DEFAULT_PORT):
|
|
298
|
+
def run_proxy(port: int = DEFAULT_PORT, host: str = DEFAULT_HOST):
|
|
158
299
|
# Auto-initialize Knowledge Graph & API Surface on startup
|
|
159
300
|
hubs_summary = "active"
|
|
160
301
|
try:
|
|
@@ -166,11 +307,12 @@ def run_proxy(port: int = DEFAULT_PORT):
|
|
|
166
307
|
except Exception as e:
|
|
167
308
|
hubs_summary = f"initialized ({e})"
|
|
168
309
|
|
|
169
|
-
server_address = (
|
|
310
|
+
server_address = (host, port)
|
|
170
311
|
httpd = HTTPServer(server_address, TokenSafeProxyHandler)
|
|
171
|
-
|
|
172
|
-
print(f"
|
|
173
|
-
print(f"
|
|
312
|
+
display_host = "localhost" if host in ("0.0.0.0", "", "127.0.0.1") else host
|
|
313
|
+
print(f"\n⚡ TokenSafe Local AI Proxy running on: http://{display_host}:{port} (bound to {host})")
|
|
314
|
+
print(f" Dashboard: http://{display_host}:{port}/dashboard")
|
|
315
|
+
print(f" OpenAI-compatible URL: http://{display_host}:{port}/v1")
|
|
174
316
|
print(f" Auto-Graph: {hubs_summary}")
|
|
175
317
|
print(f" API Surface: tokensafe-out/API_SURFACE.md")
|
|
176
318
|
try:
|