tokensafe 1.4.14 → 1.5.0

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 CHANGED
@@ -3,6 +3,7 @@
3
3
  </p>
4
4
 
5
5
  <h1 align="center">⚡ TokenSafe</h1>
6
+ <!-- mcp-name: dev.tokensafe/tokensafe -->
6
7
 
7
8
  <p align="center">
8
9
  <b>Autonomous Zero-Loss Token Economy & Context Optimizer for AI Coding Agents</b><br>
@@ -328,6 +329,19 @@ Verified across 8 real-world production software engineering scenarios (131,604
328
329
  | **OAuth JWT Expiration Triage** | Controller bug investigation | 3,757 | **401** | **-89.3%** | **3 ➔ 2 turns (+33%)** | 100% Pass |
329
330
  | **CI Test Failure Extraction** | Full test log & stack trace | 5,009 | **1,127** | **-77.5%** | 3 turns | 100% Pass |
330
331
 
332
+ > **How to read these numbers:** the benchmark is a **simulated** harness — the compression ratios are real, deterministic tool-output deltas on real files, while the "turn speedup" column models agent behavior. We never present simulated numbers as metered ones. Every production event TokenSafe records is labeled `measured` (literally metered I/O reduction) or `estimated` (counterfactual baseline) — see **[METRICS.md](METRICS.md)** for the full methodology, and the dashboard exposes the `measured` / `estimated` split alongside every total.
333
+
334
+ ---
335
+
336
+ ## 📐 Metrics Honesty
337
+
338
+ TokenSafe labels every savings event as one of:
339
+
340
+ - **`measured`** — the model literally received fewer bytes than the tool produced (sliced file reads, filtered command output, skeletons). The delta is a fact.
341
+ - **`estimated`** — the model received a compact artifact and "saved" is counted against a reasonable alternative (architecture graph vs. a full crawl; folded history digest, which is *injected* while the raw history remains in context).
342
+
343
+ Sums on the dashboard and landing page always show the split (`X metered · Y est.`). When a live number is unavailable we render `—`, never a fabricated constant. USD figures are derived estimates (`tokens × $1.5 / 1M`), not invoices. Details: **[METRICS.md](METRICS.md)**.
344
+
331
345
  ---
332
346
 
333
347
  ## 💎 Pricing & 7-Day Free Trial
@@ -22,6 +22,24 @@ from src.metrics import MetricsTracker
22
22
  from src.environment_auditor import EnvironmentAuditor
23
23
  from src.license_manager import LicenseManager
24
24
 
25
+ def _proxy_is_active() -> bool:
26
+ """True when the local tokensafe-proxy recently served agent traffic.
27
+
28
+ The proxy REPLACES the last user message with its TOCP form (real
29
+ replace-mode); injecting a second compressed copy from the hook would
30
+ duplicate the optimization and double-count it in metrics."""
31
+ try:
32
+ import time as _time
33
+ marker = os.path.join(
34
+ os.environ.get("TOKENSAFE_DATA_DIR", os.path.join(PROJECT_ROOT, "data")),
35
+ ".proxy_active",
36
+ )
37
+ if os.path.exists(marker):
38
+ return _time.time() - os.path.getmtime(marker) < 120.0
39
+ except Exception:
40
+ pass
41
+ return False
42
+
25
43
  def main():
26
44
  try:
27
45
  raw_input = sys.stdin.read()
@@ -80,8 +98,9 @@ def main():
80
98
  except Exception:
81
99
  pass
82
100
 
83
- # 1. Prompt Compaction (Tier 2 LLM Distillation paused if community quota exceeded)
84
- if last_user_input and len(last_user_input.strip()) >= 5:
101
+ # 1. Prompt Compaction (Tier 2 LLM Distillation paused if community quota exceeded).
102
+ # Skipped while the proxy is in the loop: it already replaced the prompt.
103
+ if last_user_input and len(last_user_input.strip()) >= 5 and not _proxy_is_active():
85
104
  enable_distill = not quota.get("is_quota_exceeded", False)
86
105
  compaction = PromptCompactor.compact(last_user_input, enable_deepseek=enable_distill)
87
106
  saved_tokens = compaction["saved_tokens"]
package/package.json CHANGED
@@ -1,6 +1,7 @@
1
1
  {
2
2
  "name": "tokensafe",
3
- "version": "1.4.14",
3
+ "mcpName": "dev.tokensafe/tokensafe",
4
+ "version": "1.5.0",
4
5
  "description": "Autonomous Zero-Loss Token Economy & Context Optimizer for AI Coding Agents",
5
6
  "main": "bin/tokensafe.js",
6
7
  "bin": {
@@ -22,6 +23,7 @@
22
23
  "proto/",
23
24
  "extensions/",
24
25
  "plugin.json",
26
+ "server.json",
25
27
  "README.md",
26
28
  "LICENSE"
27
29
  ],
package/plugin.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "agy-token-optimizer",
3
3
  "displayName": "TokenSafe",
4
- "version": "1.4.14",
4
+ "version": "1.5.0",
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/server.json ADDED
@@ -0,0 +1,62 @@
1
+ {
2
+ "$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json",
3
+ "name": "dev.tokensafe/tokensafe",
4
+ "title": "TokenSafe",
5
+ "description": "Cut AI coding agent token usage up to 90% via AST slicing, dependency graphs & security guards.",
6
+ "version": "1.5.0",
7
+ "websiteUrl": "https://tokensafe.dev",
8
+ "repository": {
9
+ "url": "https://github.com/NekoSin4eG/tokensafe",
10
+ "source": "github"
11
+ },
12
+ "icons": [
13
+ {
14
+ "src": "https://tokensafe.dev/favicon-96x96.png",
15
+ "mimeType": "image/png",
16
+ "sizes": [
17
+ "96x96"
18
+ ]
19
+ },
20
+ {
21
+ "src": "https://tokensafe.dev/logo.svg",
22
+ "mimeType": "image/svg+xml",
23
+ "sizes": [
24
+ "any"
25
+ ]
26
+ }
27
+ ],
28
+ "packages": [
29
+ {
30
+ "registryType": "npm",
31
+ "registryBaseUrl": "https://registry.npmjs.org",
32
+ "identifier": "tokensafe",
33
+ "version": "1.5.0",
34
+ "runtimeHint": "npx",
35
+ "transport": {
36
+ "type": "stdio"
37
+ },
38
+ "packageArguments": [
39
+ {
40
+ "type": "positional",
41
+ "value": "mcp"
42
+ }
43
+ ]
44
+ },
45
+ {
46
+ "registryType": "pypi",
47
+ "registryBaseUrl": "https://pypi.org",
48
+ "identifier": "tokensafe",
49
+ "version": "1.5.0",
50
+ "runtimeHint": "uvx",
51
+ "transport": {
52
+ "type": "stdio"
53
+ },
54
+ "packageArguments": [
55
+ {
56
+ "type": "positional",
57
+ "value": "mcp"
58
+ }
59
+ ]
60
+ }
61
+ ]
62
+ }
package/src/cli.py CHANGED
@@ -22,12 +22,28 @@ from src.compactor import PromptCompactor
22
22
  from src.tokenizer import count_tokens
23
23
 
24
24
  def main():
25
- tracker = MetricsTracker()
26
- dashboard = Dashboard(tracker)
27
-
28
25
  args = sys.argv[1:]
29
26
  command = args[0] if args else "stats"
30
27
 
28
+ # Fast path: version queries must not construct MetricsTracker (which creates
29
+ # the data dir and SQLite database). `tokensafe --version` may run in read-only
30
+ # or foreign directories and must stay side-effect free.
31
+ if command in ("version", "--version", "-v"):
32
+ from src.version_checker import CURRENT_VERSION, VersionChecker
33
+ print(f"TokenSafe v{CURRENT_VERSION}")
34
+ if "--check" in args or "-c" in args:
35
+ banner = VersionChecker.get_banner()
36
+ if banner:
37
+ print(banner)
38
+ else:
39
+ print("\033[32m✔ TokenSafe is up to date.\033[0m")
40
+ if "--notify" in args or "--prompt" in args:
41
+ VersionChecker.notify_os_update(force=True)
42
+ return
43
+
44
+ tracker = MetricsTracker()
45
+ dashboard = Dashboard(tracker)
46
+
31
47
  if command in ("stats", "dashboard"):
32
48
  try:
33
49
  from src.telemetry_sync import TelemetrySync
@@ -78,18 +94,6 @@ def main():
78
94
  from src.installer import AgentInstaller
79
95
  AgentInstaller.self_update()
80
96
 
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
97
  elif command in ("check-update", "check_update"):
94
98
  from src.version_checker import CURRENT_VERSION, VersionChecker
95
99
  print(f"\n\033[1m\033[36m⚡ CHECKING FOR TOKENSAFE UPDATES ⚡\033[0m\n")
package/src/mcp_server.py CHANGED
@@ -35,7 +35,7 @@ from src.scoped_search import ScopedSearch
35
35
 
36
36
  SERVER_INFO = {
37
37
  "name": "tokensafe-mcp",
38
- "version": "1.4.14"
38
+ "version": "1.5.0"
39
39
  }
40
40
 
41
41
  TOOLS = [
package/src/metrics.py CHANGED
@@ -14,6 +14,30 @@ from datetime import datetime, timedelta
14
14
  from typing import Dict, List, Optional, Any, Generator
15
15
 
16
16
  USD_PER_TOKEN = 1.50 / 1_000_000.0
17
+
18
+ # Event types whose `original_tokens` baseline is a counterfactual estimate rather
19
+ # than literally metered I/O (see METRICS.md). Everything else counts as measured.
20
+ # GRAPH_TOPOLOGY: "original" is what a hypothetical full-file crawl would have cost.
21
+ # HISTORY_FOLD: a folded digest is INJECTED as a system message; the full history
22
+ # physically stays in the context window.
23
+ # PROMPT: the TOCP form is injected alongside the original prompt until
24
+ # replace-mode is verified end-to-end.
25
+ # ROLLUP_LIFETIME: pruned-and-rolled-up historical mass of mixed provenance;
26
+ # conservatively labelled estimated.
27
+ ESTIMATED_EVENT_TYPES = frozenset({
28
+ "GRAPH_TOPOLOGY",
29
+ "HISTORY_FOLD",
30
+ "PROMPT",
31
+ "ROLLUP_LIFETIME",
32
+ })
33
+
34
+ def resolve_measurement(event_type: str, explicit: Optional[str] = None) -> str:
35
+ """Resolves the measurement label for an event: explicit override wins,
36
+ then the estimated-type map, then 'measured'."""
37
+ if explicit in ("measured", "estimated"):
38
+ return explicit
39
+ return "estimated" if event_type in ESTIMATED_EVENT_TYPES else "measured"
40
+
17
41
  _METRICS_INIT_LOCK = threading.Lock()
18
42
  _INITIALIZED_METRICS_DBS: set = set()
19
43
  # Retention / telemetry cadence is wall-clock based (marker file) rather than
@@ -122,9 +146,25 @@ class MetricsTracker:
122
146
  saved_tokens INTEGER NOT NULL,
123
147
  reduction_pct REAL NOT NULL,
124
148
  est_usd_saved REAL NOT NULL,
125
- details TEXT
149
+ details TEXT,
150
+ measurement TEXT NOT NULL DEFAULT 'measured'
126
151
  )
127
152
  """)
153
+ # Migration for databases created before the measurement column existed.
154
+ try:
155
+ cursor.execute(
156
+ "ALTER TABLE events ADD COLUMN measurement TEXT NOT NULL DEFAULT 'measured';"
157
+ )
158
+ except sqlite3.OperationalError:
159
+ pass # column already present
160
+ # Retroactively label counterfactual event types recorded before the
161
+ # measured/estimated split was introduced (idempotent: new events of
162
+ # these types are already inserted with measurement='estimated').
163
+ cursor.execute(
164
+ "UPDATE events SET measurement = 'estimated' "
165
+ "WHERE measurement = 'measured' AND event_type IN "
166
+ "('GRAPH_TOPOLOGY', 'HISTORY_FOLD', 'PROMPT', 'ROLLUP_LIFETIME');"
167
+ )
128
168
  cursor.execute("""
129
169
  CREATE TABLE IF NOT EXISTS lifetime_aggregates (
130
170
  id INTEGER PRIMARY KEY CHECK (id = 1),
@@ -152,9 +192,17 @@ class MetricsTracker:
152
192
  event_type: str,
153
193
  original_tokens: int,
154
194
  optimized_tokens: int,
155
- details: Optional[Dict[str, Any]] = None
195
+ details: Optional[Dict[str, Any]] = None,
196
+ measurement: Optional[str] = None
156
197
  ) -> Dict[str, Any]:
157
- """Records an optimization event and updates session totals."""
198
+ """Records an optimization event and updates session totals.
199
+
200
+ `measurement` labels the honesty of `saved_tokens`:
201
+ 'measured' - literally metered I/O reduction (tool output was smaller)
202
+ 'estimated' - counterfactual baseline (see ESTIMATED_EVENT_TYPES / METRICS.md)
203
+ When omitted, the label is derived from the event type.
204
+ """
205
+ measurement_label = resolve_measurement(event_type, measurement)
158
206
  saved_tokens = max(0, original_tokens - optimized_tokens)
159
207
  reduction_pct = (saved_tokens / original_tokens * 100.0) if original_tokens > 0 else 0.0
160
208
  est_usd = round(saved_tokens * USD_PER_TOKEN, 6)
@@ -167,10 +215,12 @@ class MetricsTracker:
167
215
  cursor.execute("""
168
216
  INSERT INTO events (
169
217
  session_id, timestamp, event_type, original_tokens,
170
- optimized_tokens, saved_tokens, reduction_pct, est_usd_saved, details
171
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
218
+ optimized_tokens, saved_tokens, reduction_pct, est_usd_saved, details,
219
+ measurement
220
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
172
221
  """, (session_id, now_iso, event_type, original_tokens,
173
- optimized_tokens, saved_tokens, round(reduction_pct, 2), est_usd, details_json))
222
+ optimized_tokens, saved_tokens, round(reduction_pct, 2), est_usd, details_json,
223
+ measurement_label))
174
224
 
175
225
  # 2. Upsert session
176
226
  cursor.execute("""
@@ -193,7 +243,8 @@ class MetricsTracker:
193
243
  return {
194
244
  "saved_tokens": saved_tokens,
195
245
  "reduction_pct": round(reduction_pct, 1),
196
- "est_usd_saved": est_usd
246
+ "est_usd_saved": est_usd,
247
+ "measurement": measurement_label
197
248
  }
198
249
 
199
250
  def get_summary(self) -> Dict[str, Any]:
@@ -213,12 +264,14 @@ class MetricsTracker:
213
264
 
214
265
  # 2. Active events
215
266
  cursor.execute("""
216
- SELECT
267
+ SELECT
217
268
  COUNT(*) as active_events,
218
269
  COALESCE(SUM(original_tokens), 0) as active_orig,
219
270
  COALESCE(SUM(optimized_tokens), 0) as active_opt,
220
271
  COALESCE(SUM(saved_tokens), 0) as active_saved,
221
- COALESCE(SUM(est_usd_saved), 0.0) as active_usd
272
+ COALESCE(SUM(est_usd_saved), 0.0) as active_usd,
273
+ COALESCE(SUM(CASE WHEN measurement = 'measured' THEN saved_tokens ELSE 0 END), 0) as active_saved_measured,
274
+ COALESCE(SUM(CASE WHEN measurement = 'estimated' THEN saved_tokens ELSE 0 END), 0) as active_saved_estimated
222
275
  FROM events
223
276
  """)
224
277
  ev_row = cursor.fetchone()
@@ -229,7 +282,8 @@ class MetricsTracker:
229
282
 
230
283
  # 3. Breakdown of active events
231
284
  cursor.execute("""
232
- SELECT event_type, COUNT(*) as count, COALESCE(SUM(saved_tokens), 0) as saved
285
+ SELECT event_type, COUNT(*) as count, COALESCE(SUM(saved_tokens), 0) as saved,
286
+ COALESCE(SUM(CASE WHEN measurement = 'estimated' THEN saved_tokens ELSE 0 END), 0) as estimated_saved
233
287
  FROM events
234
288
  GROUP BY event_type
235
289
  """)
@@ -237,11 +291,13 @@ class MetricsTracker:
237
291
  for r in cursor.fetchall():
238
292
  ev_type = r["event_type"]
239
293
  if ev_type not in combined_breakdown:
240
- combined_breakdown[ev_type] = {"count": 0, "saved": 0}
294
+ combined_breakdown[ev_type] = {"count": 0, "saved": 0, "estimated_saved": 0}
241
295
  else:
242
296
  combined_breakdown[ev_type] = dict(combined_breakdown[ev_type])
297
+ combined_breakdown[ev_type].setdefault("estimated_saved", 0)
243
298
  combined_breakdown[ev_type]["count"] += r["count"]
244
299
  combined_breakdown[ev_type]["saved"] += r["saved"]
300
+ combined_breakdown[ev_type]["estimated_saved"] += r["estimated_saved"]
245
301
 
246
302
  total_events = life_events + (ev_row["active_events"] if ev_row else 0)
247
303
  total_orig = life_orig + (ev_row["active_orig"] if ev_row else 0)
@@ -250,12 +306,22 @@ class MetricsTracker:
250
306
  total_usd = life_usd + (ev_row["active_usd"] if ev_row else 0.0)
251
307
  overall_reduction = (total_saved / total_orig * 100.0) if total_orig > 0 else 0.0
252
308
 
309
+ # Honesty split: lifetime rollup breakdown carries per-type estimated mass
310
+ # (see prune); active events are split directly by the measurement column.
311
+ life_estimated = sum(int(v.get("estimated_saved", 0) or 0) for v in life_breakdown.values())
312
+ saved_measured = (ev_row["active_saved_measured"] if ev_row else 0) + (
313
+ life_saved - life_estimated
314
+ )
315
+ saved_estimated = (ev_row["active_saved_estimated"] if ev_row else 0) + life_estimated
316
+
253
317
  return {
254
318
  "session_count": max(session_count, 1 if total_events > 0 else 0),
255
319
  "total_events": total_events,
256
320
  "total_original_tokens": total_orig,
257
321
  "total_optimized_tokens": total_opt,
258
322
  "total_saved_tokens": total_saved,
323
+ "total_saved_tokens_measured": saved_measured,
324
+ "total_saved_tokens_estimated": saved_estimated,
259
325
  "overall_reduction_pct": round(overall_reduction, 1),
260
326
  "total_usd_saved": round(total_usd, 4),
261
327
  "breakdown": combined_breakdown
@@ -282,7 +348,8 @@ class MetricsTracker:
282
348
  cursor = conn.cursor()
283
349
  cursor.execute("""
284
350
  SELECT id, session_id, timestamp, event_type, original_tokens,
285
- optimized_tokens, saved_tokens, reduction_pct, est_usd_saved, details
351
+ optimized_tokens, saved_tokens, reduction_pct, est_usd_saved, details,
352
+ measurement
286
353
  FROM events
287
354
  ORDER BY id DESC
288
355
  LIMIT ?
@@ -391,7 +458,7 @@ class MetricsTracker:
391
458
 
392
459
  # 1. Calculate aggregates for events to be pruned
393
460
  cursor.execute(f"""
394
- SELECT
461
+ SELECT
395
462
  COUNT(*) as cnt,
396
463
  COALESCE(SUM(original_tokens), 0) as orig,
397
464
  COALESCE(SUM(optimized_tokens), 0) as opt,
@@ -404,15 +471,16 @@ class MetricsTracker:
404
471
  prune_count = agg_row["cnt"] if agg_row else 0
405
472
 
406
473
  if prune_count > 0:
407
- # 2. Breakdown of pruned events
474
+ # 2. Breakdown of pruned events (with estimated share for the honesty split)
408
475
  cursor.execute(f"""
409
- SELECT event_type, COUNT(*) as cnt, COALESCE(SUM(saved_tokens), 0) as saved
476
+ SELECT event_type, COUNT(*) as cnt, COALESCE(SUM(saved_tokens), 0) as saved,
477
+ COALESCE(SUM(CASE WHEN measurement = 'estimated' THEN saved_tokens ELSE 0 END), 0) as est_saved
410
478
  FROM events
411
479
  WHERE {combined_where}
412
480
  GROUP BY event_type
413
481
  """, params)
414
482
  pruned_breakdown = {
415
- r["event_type"]: {"count": r["cnt"], "saved": r["saved"]}
483
+ r["event_type"]: {"count": r["cnt"], "saved": r["saved"], "estimated_saved": r["est_saved"]}
416
484
  for r in cursor.fetchall()
417
485
  }
418
486
 
@@ -423,11 +491,13 @@ class MetricsTracker:
423
491
 
424
492
  for ev_type, vals in pruned_breakdown.items():
425
493
  if ev_type not in current_breakdown:
426
- current_breakdown[ev_type] = {"count": 0, "saved": 0}
494
+ current_breakdown[ev_type] = {"count": 0, "saved": 0, "estimated_saved": 0}
427
495
  else:
428
496
  current_breakdown[ev_type] = dict(current_breakdown[ev_type])
497
+ current_breakdown[ev_type].setdefault("estimated_saved", 0)
429
498
  current_breakdown[ev_type]["count"] += vals["count"]
430
499
  current_breakdown[ev_type]["saved"] += vals["saved"]
500
+ current_breakdown[ev_type]["estimated_saved"] += vals["estimated_saved"]
431
501
 
432
502
  # 4. Update lifetime_aggregates
433
503
  cursor.execute("""
package/src/proxy.py CHANGED
@@ -150,11 +150,29 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
150
150
  return
151
151
 
152
152
  if self.path.startswith("/v1/chat/completions"):
153
+ self._touch_proxy_heartbeat()
153
154
  self.handle_chat_completions()
154
155
  else:
155
156
  self.send_response(404)
156
157
  self.end_headers()
157
158
 
159
+ @staticmethod
160
+ def _touch_proxy_heartbeat():
161
+ """Marks the proxy as actively serving agent traffic.
162
+
163
+ Lifecycle hooks read this marker to skip their own prompt compaction:
164
+ when the proxy is in the loop it REPLACES the last user message with the
165
+ TOCP form, so hook-side injection would double-count the same prompt."""
166
+ try:
167
+ marker = os.path.join(
168
+ os.environ.get("TOKENSAFE_DATA_DIR", os.path.join(BASE_DIR, "data")),
169
+ ".proxy_active",
170
+ )
171
+ with open(marker, "w", encoding="utf-8") as f:
172
+ f.write(str(int(__import__("time").time())))
173
+ except Exception:
174
+ pass
175
+
158
176
  def handle_chat_completions(self):
159
177
  try:
160
178
  content_len = int(self.headers.get("Content-Length", 0))
@@ -166,6 +184,8 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
166
184
  self.wfile.write(json.dumps({"error": f"Invalid JSON payload: {e}"}).encode("utf-8"))
167
185
  return
168
186
 
187
+ proxy_tracker = MetricsTracker()
188
+
169
189
  # 1. Local Secret Redaction: Scrub credentials across all messages before dispatch
170
190
  messages = payload.get("messages", [])
171
191
  if messages:
@@ -173,7 +193,9 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
173
193
  if secrets_scrubbed > 0:
174
194
  print(f"[TokenSafe] Scrubbed {secrets_scrubbed} sensitive secret(s) from payload before transmission.")
175
195
 
176
- # 2. Ingress Optimization: Compact last user message
196
+ # 2. Ingress Optimization: REPLACE the last user message with its TOCP form.
197
+ # This is the real replace-mode: the upstream model never sees the verbose
198
+ # original, so the delta is literally measured (see METRICS.md).
177
199
  target_symbol = None
178
200
  if messages:
179
201
  for idx in reversed(range(len(messages))):
@@ -183,6 +205,22 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
183
205
  compaction = PromptCompactor.compact(raw_user, enable_deepseek=False)
184
206
  if compaction["saved_tokens"] > 5:
185
207
  msg["content"] = compaction["compact_text"]
208
+ try:
209
+ proxy_tracker.record_event(
210
+ session_id="proxy_session",
211
+ event_type="PROMPT",
212
+ original_tokens=compaction["original_tokens"],
213
+ optimized_tokens=compaction["compact_tokens"],
214
+ details={
215
+ "mode": "proxy_replace",
216
+ "action": compaction.get("action"),
217
+ "symbol": compaction.get("symbol"),
218
+ "tier": compaction.get("tier", "REGEX"),
219
+ },
220
+ measurement="measured", # bytes literally swapped
221
+ )
222
+ except Exception:
223
+ pass
186
224
  target_symbol = compaction.get("symbol")
187
225
  break
188
226
 
@@ -29,6 +29,7 @@ if PROJECT_ROOT not in sys.path:
29
29
  sys.path.insert(0, PROJECT_ROOT)
30
30
 
31
31
  from src.license_manager import LicenseManager
32
+ from src.metrics import resolve_measurement
32
33
 
33
34
  DATA_DIR = os.path.join(PROJECT_ROOT, "data")
34
35
  METRICS_DB_PATH = os.path.join(DATA_DIR, "metrics.db")
@@ -178,16 +179,29 @@ class TelemetrySync:
178
179
  "saved_tokens": int(life_row["total_saved_tokens"]),
179
180
  "usd_saved": float(life_row["total_usd_saved"]),
180
181
  "model": "aggregate",
181
- "timestamp": int(time.time())
182
+ "timestamp": int(time.time()),
183
+ # Rolled-up historical mass of mixed provenance: conservatively estimated.
184
+ "measurement": "estimated"
182
185
  })
183
186
  except Exception:
184
187
  pass
185
188
 
186
- rows = cur.execute(
187
- "SELECT id, timestamp, event_type, original_tokens, saved_tokens, est_usd_saved, details "
188
- "FROM events WHERE id > ? ORDER BY id ASC LIMIT 2000",
189
- (last_id,)
190
- ).fetchall()
189
+ # The measurement column may be absent on legacy databases that have
190
+ # not yet been migrated by MetricsTracker._init_db; fall back to the
191
+ # event-type map so sync never blocks on schema drift.
192
+ try:
193
+ rows = cur.execute(
194
+ "SELECT id, timestamp, event_type, original_tokens, saved_tokens, est_usd_saved, details, measurement "
195
+ "FROM events WHERE id > ? ORDER BY id ASC LIMIT 2000",
196
+ (last_id,)
197
+ ).fetchall()
198
+ except sqlite3.OperationalError:
199
+ rows = cur.execute(
200
+ "SELECT id, timestamp, event_type, original_tokens, saved_tokens, est_usd_saved, details, "
201
+ "NULL as measurement "
202
+ "FROM events WHERE id > ? ORDER BY id ASC LIMIT 2000",
203
+ (last_id,)
204
+ ).fetchall()
191
205
  conn.close()
192
206
  except Exception as e:
193
207
  return {
@@ -241,7 +255,8 @@ class TelemetrySync:
241
255
  "saved_tokens": int(r["saved_tokens"] or 0),
242
256
  "usd_saved": float(r["est_usd_saved"] or 0.0),
243
257
  "model": model_name,
244
- "timestamp": ts_int
258
+ "timestamp": ts_int,
259
+ "measurement": resolve_measurement(str(r["event_type"] or "PROMPT"), r["measurement"])
245
260
  }))
246
261
 
247
262
  total_sent = 0
@@ -249,7 +264,7 @@ class TelemetrySync:
249
264
  rollup_synced = bool(state.get("lifetime_rollup_synced", False))
250
265
  headers = {
251
266
  "Content-Type": "application/json",
252
- "User-Agent": "TokenSafe-Sync/1.4.14"
267
+ "User-Agent": "TokenSafe-Sync/1.5.0"
253
268
  }
254
269
  if active_key:
255
270
  headers["Authorization"] = f"Bearer {active_key}"
@@ -16,7 +16,7 @@ import urllib.request
16
16
  import urllib.error
17
17
  from typing import Dict, Any, Optional, Tuple
18
18
 
19
- CURRENT_VERSION = "1.4.14"
19
+ CURRENT_VERSION = "1.5.0"
20
20
  CACHE_TTL = 86400 # 24 hours
21
21
  # When the cloud is unreachable we must NOT cache the synthesized "up to date"
22
22
  # answer for a full day — otherwise an update released right after an outage
@@ -135,6 +135,15 @@ class VersionChecker:
135
135
  if resp.status == 200:
136
136
  data = json.loads(resp.read().decode("utf-8"))
137
137
  data["checked_at"] = now
138
+ # TS1 sunset: transparently swap in the reissued TS2 key.
139
+ # Never persist the key inside version_cache.json — it is a secret.
140
+ reissued = data.pop("reissued_license_key", "")
141
+ if reissued and reissued.startswith("TS2."):
142
+ try:
143
+ from src.license_manager import LicenseManager
144
+ LicenseManager.save_license(reissued)
145
+ except Exception:
146
+ pass
138
147
  data.pop("ttl", None) # authoritative server answer: full 24h cache
139
148
  cls.save_cache(data)
140
149
  return data
@@ -174,6 +183,11 @@ class VersionChecker:
174
183
 
175
184
  return None
176
185
 
186
+ @staticmethod
187
+ def _posix_single_quote(text: str) -> str:
188
+ """Quotes text for safe embedding inside a single-quoted shell string."""
189
+ return "'" + text.replace("'", "'\\''") + "'"
190
+
177
191
  @classmethod
178
192
  def show_os_dialog(
179
193
  cls,
@@ -189,16 +203,24 @@ class VersionChecker:
189
203
 
190
204
  if plat == "darwin":
191
205
  try:
192
- # TCC-safe: driving Terminal.app via AppleScript requires an
193
- # Automation permission prompt that background (hook-spawned)
194
- # processes can never satisfy, which made "Update Now" silently fail.
195
- # `do shell script` needs no such permission; prefer the explicit
196
- # ~/.local/bin path because non-interactive shells lack the user PATH.
197
- escaped_cmd = update_command.replace('"', '\\"')
206
+ # TCC-safe: driving Terminal.app via AppleScript requires an Automation
207
+ # permission prompt that background (hook-spawned) processes can never
208
+ # satisfy, which made "Update Now" silently fail. `do shell script` needs
209
+ # no such permission. The updater runs inside a LOGIN shell so that
210
+ # profile-managed PATH entries (nvm, homebrew, volta, ~/.local/bin…)
211
+ # resolve the `tokensafe` executable; a bare non-interactive shell
212
+ # would not see them and log "command not found".
213
+ inner_cmd = f"nohup {update_command} > /tmp/tokensafe-update.log 2>&1 &"
214
+ shell_cmd = (
215
+ 'SHELL_BIN=${SHELL:-/bin/zsh}; [ -x "$SHELL_BIN" ] || SHELL_BIN=/bin/zsh; '
216
+ f'nohup "$SHELL_BIN" -lc {cls._posix_single_quote(inner_cmd)} >/dev/null 2>&1 &'
217
+ )
218
+ # Escape the shell command for embedding inside an AppleScript string literal
219
+ escaped_shell = shell_cmd.replace("\\", "\\\\").replace('"', '\\"')
198
220
  apple_script = f'''
199
221
  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
200
222
  if button returned of dialogResult is "Update Now" then
201
- do shell script "if [ -x \\"$HOME/.local/bin/tokensafe\\" ]; then CMD=\\"$HOME/.local/bin/tokensafe\\"; else CMD=\\"{escaped_cmd}\\"; fi; nohup \\"$CMD\\" update > /tmp/tokensafe-update.log 2>&1 &"
223
+ do shell script "{escaped_shell}"
202
224
  end if
203
225
  '''
204
226
  subprocess.Popen(