tokensafe 1.3.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/src/mcp_server.py CHANGED
@@ -23,10 +23,12 @@ from src.metrics import MetricsTracker
23
23
  from src.dashboard import Dashboard
24
24
  from src.graph_engine import GraphEngine
25
25
  from src.tokenizer import count_tokens
26
+ from src.agent_firewall import AgentFirewall
27
+ from src.diff_slicer import DiffSlicer
26
28
 
27
29
  SERVER_INFO = {
28
30
  "name": "tokensafe-mcp",
29
- "version": "1.2.0"
31
+ "version": "1.3.1"
30
32
  }
31
33
 
32
34
  TOOLS = [
@@ -86,6 +88,18 @@ TOOLS = [
86
88
  "required": ["command"]
87
89
  }
88
90
  },
91
+ {
92
+ "name": "slice_diff",
93
+ "description": "Slices unified diffs, omitting lockfiles and minimizing context lines to reduce tokens by up to 80%.",
94
+ "inputSchema": {
95
+ "type": "object",
96
+ "properties": {
97
+ "diff": {"type": "string", "description": "Raw git diff text"},
98
+ "max_context": {"type": "integer", "description": "Maximum surrounding context lines (default: 2)"}
99
+ },
100
+ "required": ["diff"]
101
+ }
102
+ },
89
103
  {
90
104
  "name": "get_token_savings_metrics",
91
105
  "description": "Returns cumulative token and cost savings analytics.",
@@ -108,6 +122,11 @@ def handle_tool_call(name: str, args: dict) -> dict:
108
122
  if not path or not os.path.exists(path):
109
123
  return {"isError": True, "content": [{"type": "text", "text": f"File not found: {path}"}]}
110
124
 
125
+ # Check Subagent Firewall dedup cache
126
+ is_hit, cached_text, saved_dedup = AgentFirewall.check_cache("mcp_session", path, symbol=symbol or "", tracker=tracker)
127
+ if is_hit and cached_text:
128
+ return {"content": [{"type": "text", "text": cached_text}]}
129
+
111
130
  # Check loop detector
112
131
  is_loop, repeats, msg = LoopDetector.check_loop("mcp_session", "smart_read_file", args)
113
132
  if is_loop:
@@ -183,6 +202,21 @@ def handle_tool_call(name: str, args: dict) -> dict:
183
202
  }
184
203
  return {"content": [{"type": "text", "text": json.dumps(result, indent=2)}]}
185
204
 
205
+ elif name == "slice_diff":
206
+ raw_diff = args.get("diff", "")
207
+ max_ctx = int(args.get("max_context", 2))
208
+ sliced, orig_t, opt_t = DiffSlicer.slice_diff(raw_diff, max_context_lines=max_ctx)
209
+ saved = max(0, orig_t - opt_t)
210
+ if saved > 0:
211
+ tracker.record_event(
212
+ session_id="mcp_session",
213
+ event_type="DIFF_SLICER",
214
+ original_tokens=orig_t,
215
+ optimized_tokens=opt_t,
216
+ details={"saved_tokens": saved, "max_context": max_ctx}
217
+ )
218
+ return {"content": [{"type": "text", "text": sliced}]}
219
+
186
220
  elif name == "get_token_savings_metrics":
187
221
  dashboard = Dashboard(tracker)
188
222
  return {"content": [{"type": "text", "text": dashboard.render_markdown()}]}
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
- base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
23
- data_dir = os.path.join(base_dir, "data")
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(DISTINCT session_id) as session_count,
123
- COUNT(*) as total_events,
124
- COALESCE(SUM(original_tokens), 0) as total_orig,
125
- COALESCE(SUM(optimized_tokens), 0) as total_opt,
126
- COALESCE(SUM(saved_tokens), 0) as total_saved,
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
- row = cursor.fetchone()
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
- breakdown = {r["event_type"]: {"count": r["count"], "saved": r["saved"]} for r in cursor.fetchall()}
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
- total_orig = row["total_orig"]
140
- total_saved = row["total_saved"]
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": row["session_count"],
145
- "total_events": row["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": row["total_opt"],
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(row["total_usd"], 4),
151
- "breakdown": 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]]:
@@ -219,9 +279,144 @@ class MetricsTracker:
219
279
  GROUP BY session_id
220
280
  """)
221
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
+
222
406
  def reset(self):
223
407
  """Resets all metrics data."""
224
408
  with self._get_connection() as conn:
225
409
  cursor = conn.cursor()
226
410
  cursor.execute("DELETE FROM events")
227
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
 
@@ -37,7 +73,10 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
37
73
  """Protects against DNS rebinding and cross-origin attacks from arbitrary browser origins."""
38
74
  origin = self.headers.get("Origin", "")
39
75
  if origin:
40
- allowed_prefixes = ("http://127.0.0.1", "http://localhost", "https://tokensafe.dev")
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()])
41
80
  if not any(origin.startswith(a) for a in allowed_prefixes):
42
81
  self.send_response(403)
43
82
  self.send_header("Content-Type", "application/json")
@@ -67,6 +106,35 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
67
106
  self.end_headers()
68
107
  self.wfile.write(json.dumps(summary, indent=2).encode("utf-8"))
69
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
+
70
138
  elif self.path == "/health":
71
139
  self.send_response(200)
72
140
  self.send_header("Content-Type", "application/json")
@@ -130,29 +198,75 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
130
198
  except Exception:
131
199
  pass
132
200
 
133
- # 4. Forward to Upstream
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
134
214
  auth_header = self.headers.get("Authorization", "")
135
- # Check if local config has deepseek key
136
- config_path = os.path.join(BASE_DIR, "data", "config.json")
137
- upstream_key = ""
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")
138
221
  if os.path.exists(config_path):
139
222
  try:
140
223
  with open(config_path) as f:
141
- conf = json.load(f)
142
- upstream_key = conf.get("deepseek_api_key", "")
224
+ conf_keys = json.load(f)
143
225
  except Exception:
144
226
  pass
145
227
 
146
- final_auth = auth_header or (f"Bearer {upstream_key}" if upstream_key else "")
147
- upstream_url = os.environ.get("TOKENSAFE_UPSTREAM_URL", "https://api.deepseek.com/chat/completions")
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}"
148
265
 
149
266
  req = urllib.request.Request(
150
267
  upstream_url,
151
268
  data=json.dumps(payload).encode("utf-8"),
152
- headers={
153
- "Authorization": final_auth,
154
- "Content-Type": "application/json"
155
- }
269
+ headers=headers
156
270
  )
157
271
 
158
272
  try:
@@ -164,6 +278,14 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
164
278
  self.send_header(k, v)
165
279
  self.end_headers()
166
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
167
289
  except urllib.error.HTTPError as e:
168
290
  self.send_response(e.code)
169
291
  self.end_headers()
@@ -173,7 +295,7 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
173
295
  self.end_headers()
174
296
  self.wfile.write(json.dumps({"error": f"Upstream proxy error: {str(e)}"}).encode("utf-8"))
175
297
 
176
- def run_proxy(port: int = DEFAULT_PORT):
298
+ def run_proxy(port: int = DEFAULT_PORT, host: str = DEFAULT_HOST):
177
299
  # Auto-initialize Knowledge Graph & API Surface on startup
178
300
  hubs_summary = "active"
179
301
  try:
@@ -185,11 +307,12 @@ def run_proxy(port: int = DEFAULT_PORT):
185
307
  except Exception as e:
186
308
  hubs_summary = f"initialized ({e})"
187
309
 
188
- server_address = ("127.0.0.1", port)
310
+ server_address = (host, port)
189
311
  httpd = HTTPServer(server_address, TokenSafeProxyHandler)
190
- print(f"\n⚡ TokenSafe Local AI Proxy running on: http://127.0.0.1:{port}")
191
- print(f" Dashboard: http://127.0.0.1:{port}/dashboard")
192
- print(f" OpenAI-compatible URL: http://127.0.0.1:{port}/v1")
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")
193
316
  print(f" Auto-Graph: {hubs_summary}")
194
317
  print(f" API Surface: tokensafe-out/API_SURFACE.md")
195
318
  try:
@@ -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.3.0"
17
+ CURRENT_VERSION = "1.3.1"
18
18
  CACHE_TTL = 86400 # 24 hours
19
19
 
20
20
  PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))