tokensafe 1.4.15 โ 1.6.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 +21 -8
- package/hooks/pre_invocation.py +21 -2
- package/package.json +3 -1
- package/plugin.json +1 -1
- package/server.json +62 -0
- package/skills/token-optimizer/SKILL.md +2 -0
- package/src/benchmark.py +32 -0
- package/src/cli.py +19 -15
- package/src/installer.py +55 -10
- package/src/mcp_server.py +101 -1
- package/src/metrics.py +87 -17
- package/src/proxy.py +39 -1
- package/src/skeletonizer.py +2 -1
- package/src/telemetry_sync.py +23 -8
- package/src/version_checker.py +10 -1
- package/hooks/__pycache__/pre_tool_use.cpython-313.pyc +0 -0
package/README.md
CHANGED
|
@@ -3,10 +3,11 @@
|
|
|
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>
|
|
9
|
-
Slashes LLM token costs by <b>up to 90
|
|
10
|
+
Slashes LLM token costs by <b>up to [90%*](METRICS.md)</b> with zero context loss.<br>
|
|
10
11
|
Built for <b>Cursor, Claude Desktop, Google Antigravity, Windsurf & Cline</b>.
|
|
11
12
|
</p>
|
|
12
13
|
|
|
@@ -315,7 +316,9 @@ tokensafe providers
|
|
|
315
316
|
|
|
316
317
|
## ๐ Zero-Loss SWE-bench Benchmark Results
|
|
317
318
|
|
|
318
|
-
|
|
319
|
+
Reference run across 8 real-world production software engineering scenarios (131,552 baseline tokens down to 7,263 tokens, **-94.5% net token reduction**, **+28.1% turn latency speedup** with **100% Zero-Loss accuracy retention**):
|
|
320
|
+
|
|
321
|
+
> Token counts vary by ยฑ1% between runs because prompt compaction is **measured live** on every execution; baseline sizes are modeled constants. The harness now ships a SIMULATION DISCLOSURE with a measured-vs-modeled evidence breakdown โ see [METRICS.md](METRICS.md).
|
|
319
322
|
|
|
320
323
|
| Benchmark Scenario | Task Complexity | Baseline Tokens | TokenSafe Tokens | Reduction | Turn Speedup | Accuracy |
|
|
321
324
|
|---|---|---|---|---|---|---|
|
|
@@ -328,6 +331,19 @@ Verified across 8 real-world production software engineering scenarios (131,604
|
|
|
328
331
|
| **OAuth JWT Expiration Triage** | Controller bug investigation | 3,757 | **401** | **-89.3%** | **3 โ 2 turns (+33%)** | 100% Pass |
|
|
329
332
|
| **CI Test Failure Extraction** | Full test log & stack trace | 5,009 | **1,127** | **-77.5%** | 3 turns | 100% Pass |
|
|
330
333
|
|
|
334
|
+
> **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.
|
|
335
|
+
|
|
336
|
+
---
|
|
337
|
+
|
|
338
|
+
## ๐ Metrics Honesty
|
|
339
|
+
|
|
340
|
+
TokenSafe labels every savings event as one of:
|
|
341
|
+
|
|
342
|
+
- **`measured`** โ the model literally received fewer bytes than the tool produced (sliced file reads, filtered command output, skeletons). The delta is a fact.
|
|
343
|
+
- **`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).
|
|
344
|
+
|
|
345
|
+
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)**.
|
|
346
|
+
|
|
331
347
|
---
|
|
332
348
|
|
|
333
349
|
## ๐ Pricing & 7-Day Free Trial
|
|
@@ -505,11 +521,8 @@ TokenSafe Cloud Backend enforces enterprise zero-trust security across all commu
|
|
|
505
521
|
| `POST` | `/api/team/seat/revoke` | **Bearer Auth** | `Authorization: Bearer <jwt\|key>`, JSON `{ owner_email, license_key }` | Revokes an active team seat license key. |
|
|
506
522
|
| `POST` | `/api/telemetry/sync` | **License Auth** | JSON `{ license_key, email, events: [...] }` | Syncs batch telemetry events (enforces max 50 events/batch). |
|
|
507
523
|
| `POST` | `/webhook/stripe` | **HMAC Sig** | `Stripe-Signature: t=...,v1=...` | Verifies Stripe webhook payload against `STRIPE_WEBHOOK_SECRET`. |
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
| `POST` | `/api/admin/license/issue`| **Admin Only** | `X-Admin-Secret` or Admin JWT | Manually issues or provisions a custom tier license. |
|
|
511
|
-
| `POST` | `/api/admin/license/revoke`| **Admin Only**| `X-Admin-Secret` or Admin JWT | Immediately revokes a license. |
|
|
512
|
-
| `POST` | `/api/admin/license/extend`| **Admin Only**| `X-Admin-Secret` or Admin JWT | Extends an active license duration. |
|
|
524
|
+
|
|
525
|
+
> **Note:** administrative endpoints are intentionally **not documented in the public API surface** โ not even their paths. They are restricted by a dedicated admin secret / admin JWT and live in the private operations manual only. Public clients never need them โ seat and license management is available through the [dashboard](https://dashboard.tokensafe.dev).
|
|
513
526
|
|
|
514
527
|
### 3. Server Configuration & Environment Variables
|
|
515
528
|
|
|
@@ -517,7 +530,7 @@ TokenSafe Cloud Backend enforces enterprise zero-trust security across all commu
|
|
|
517
530
|
|---|---|---|
|
|
518
531
|
| `TOKENSAFE_PRIVATE_KEY` | Production | 64-character hex Ed25519 seed for issuing `TS2.` licenses. |
|
|
519
532
|
| `ADMIN_SECRET_KEY` | Yes | High-entropy secret for administrative API access (`X-Admin-Secret`). |
|
|
520
|
-
| `ADMIN_EMAILS` | Optional | Comma-separated admin emails (e.g. `
|
|
533
|
+
| `ADMIN_EMAILS` | Optional | Comma-separated admin emails (e.g. `admin@yourcompany.com`). |
|
|
521
534
|
| `STRIPE_WEBHOOK_SECRET` | Production | Webhook secret (`whsec_...`) used to verify Stripe webhooks. |
|
|
522
535
|
| `SMTP_PASS` | Production | Password/token for transactional mail delivery via ImprovMX SMTP. |
|
|
523
536
|
| `JWT_SECRET` | Optional | Shared HMAC secret for verifying custom JWT tokens. Set a persistent value in production โ otherwise sessions invalidate on every restart. |
|
package/hooks/pre_invocation.py
CHANGED
|
@@ -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
|
-
|
|
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
|
-
"
|
|
3
|
+
"mcpName": "dev.tokensafe/tokensafe",
|
|
4
|
+
"version": "1.6.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
|
+
"version": "1.6.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.6.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.6.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.6.0",
|
|
50
|
+
"runtimeHint": "uvx",
|
|
51
|
+
"transport": {
|
|
52
|
+
"type": "stdio"
|
|
53
|
+
},
|
|
54
|
+
"packageArguments": [
|
|
55
|
+
{
|
|
56
|
+
"type": "positional",
|
|
57
|
+
"value": "mcp"
|
|
58
|
+
}
|
|
59
|
+
]
|
|
60
|
+
}
|
|
61
|
+
]
|
|
62
|
+
}
|
|
@@ -56,6 +56,7 @@ All tools are exposed via Model Context Protocol (stdio JSON-RPC 2.0).
|
|
|
56
56
|
| `tokensafe:sanitize_command` | Intercepts shell commands to strip lockfiles, cap unbounded git logs, and quiet test tracebacks. | Saves **10k-50k tokens** per run |
|
|
57
57
|
| `tokensafe:slice_diff` | Slices unified git diffs, eliminating lockfiles and minimizing hunk context lines. | **-50% to -80%** diff size |
|
|
58
58
|
| `tokensafe:compress_prompt` | Compresses verbose user instructions into lean TOCP S-expressions via DeepSeek/Regex. | **-40% to -65%** prompt tokens |
|
|
59
|
+
| `tokensafe:compact_conversation` | On-demand context compaction: folds a long JSONL session transcript into a lean Consolidated State Ledger (`transcript_path`, optional `invocation_num`). Call when the context window feels heavy or before a new subtask. | **-80% to -95%** history tokens |
|
|
59
60
|
| `tokensafe:guard_inspect` | Pre-flight security & hygiene audit for commands or code snippets (secrets, TLS, SQLi, raw grep). | **Zero-Risk** pre-flight gate |
|
|
60
61
|
| `tokensafe:get_token_savings_metrics` | Returns cumulative analytics: tokens saved, context ratio, USD value, and optimization source breakdown. | Persistent SQLite analytics |
|
|
61
62
|
|
|
@@ -168,6 +169,7 @@ For long-running autonomous sessions, TokenSafe actively manages context bloat:
|
|
|
168
169
|
1. **Multi-Turn History Compaction**:
|
|
169
170
|
- At conversation turn >= 3, automatically compiles past turns into a lean **Consolidated State Ledger**.
|
|
170
171
|
- Preserves active file paths, modified symbols, and pending tasks while discarding transient tool output noise.
|
|
172
|
+
- **Manual trigger**: call `tokensafe:compact_conversation` with the session's `transcript_path` any time you need to shed context between subtasks โ it returns the ledger JSON plus exact original/folded token counts.
|
|
171
173
|
2. **Subagent Deduplication Firewall**:
|
|
172
174
|
- Caches file reads across subagents. If subagent B attempts to read a file already inspected by subagent A, returns the cached skeleton instantly.
|
|
173
175
|
3. **Loop Guard**:
|
package/src/benchmark.py
CHANGED
|
@@ -136,33 +136,47 @@ class BenchmarkSuite:
|
|
|
136
136
|
# 2. Measure Tool / Command Execution
|
|
137
137
|
t_base_tokens = 0
|
|
138
138
|
t_opt_tokens = 0
|
|
139
|
+
# Honesty bookkeeping (see METRICS.md): which optimized-side tokens are
|
|
140
|
+
# produced live by the real tools vs. taken from modeled constants.
|
|
141
|
+
opt_measured_tokens = 0
|
|
142
|
+
opt_modeled_tokens = 0
|
|
139
143
|
opt_turns = task.get("baseline_turns", 1)
|
|
140
144
|
|
|
141
145
|
if "raw_tool_tokens" in task:
|
|
142
146
|
t_base_tokens += task["raw_tool_tokens"]
|
|
143
147
|
if task.get("is_graph_discovery"):
|
|
148
|
+
opt_modeled_tokens += task.get("graph_opt_tokens", 220)
|
|
144
149
|
t_opt_tokens += task.get("graph_opt_tokens", 220)
|
|
145
150
|
elif task.get("is_graph_slicer"):
|
|
151
|
+
opt_modeled_tokens += task.get("slicer_opt_tokens", 340)
|
|
146
152
|
t_opt_tokens += task.get("slicer_opt_tokens", 340)
|
|
147
153
|
else:
|
|
154
|
+
opt_modeled_tokens += 280
|
|
148
155
|
t_opt_tokens += 280
|
|
149
156
|
|
|
150
157
|
if "raw_command_tokens" in task:
|
|
151
158
|
cmd = task["command"]
|
|
152
159
|
new_cmd, saved, _ = CommandSanitizer.sanitize(cmd)
|
|
153
160
|
t_base_tokens += task["raw_command_tokens"]
|
|
161
|
+
# NOTE: `saved` is the sanitizer's downstream output ESTIMATE, not a
|
|
162
|
+
# live token delta, so it stays out of the measured bucket.
|
|
154
163
|
if task.get("is_git_grep"):
|
|
164
|
+
opt_modeled_tokens += task.get("sanitized_tokens", 180)
|
|
155
165
|
t_opt_tokens += task.get("sanitized_tokens", 180)
|
|
156
166
|
elif task.get("id") == "SWE-03":
|
|
167
|
+
opt_modeled_tokens += 350
|
|
157
168
|
t_opt_tokens += 350
|
|
158
169
|
elif task.get("id") == "SWE-04":
|
|
170
|
+
opt_modeled_tokens += 320
|
|
159
171
|
t_opt_tokens += 320
|
|
160
172
|
else:
|
|
173
|
+
opt_modeled_tokens += max(150, task["raw_command_tokens"] - saved)
|
|
161
174
|
t_opt_tokens += max(150, task["raw_command_tokens"] - saved)
|
|
162
175
|
|
|
163
176
|
if "accumulated_history_tokens" in task:
|
|
164
177
|
t_base_tokens += task["accumulated_history_tokens"]
|
|
165
178
|
# History fold CSL is ~120 tokens
|
|
179
|
+
opt_modeled_tokens += 120
|
|
166
180
|
t_opt_tokens += 120
|
|
167
181
|
|
|
168
182
|
# 3. Measure Output Guard
|
|
@@ -171,10 +185,13 @@ class BenchmarkSuite:
|
|
|
171
185
|
# Baseline rewrites whole file (1600-2200 output tokens)
|
|
172
186
|
# Optimized Output Guard enforces edit_file (80-120 diff tokens)
|
|
173
187
|
out_opt_tokens = 95
|
|
188
|
+
opt_modeled_tokens += out_opt_tokens
|
|
174
189
|
elif "opt_output_tokens" in task:
|
|
175
190
|
out_opt_tokens = task["opt_output_tokens"]
|
|
191
|
+
opt_modeled_tokens += out_opt_tokens
|
|
176
192
|
else:
|
|
177
193
|
out_opt_tokens = out_base_tokens
|
|
194
|
+
opt_modeled_tokens += out_opt_tokens # no guard win: mass is still modeled
|
|
178
195
|
|
|
179
196
|
# 4. Measure Turn Savings
|
|
180
197
|
if "opt_turns" in task:
|
|
@@ -204,6 +221,8 @@ class BenchmarkSuite:
|
|
|
204
221
|
"name": name,
|
|
205
222
|
"base_tokens": task_base_total,
|
|
206
223
|
"opt_tokens": task_opt_total,
|
|
224
|
+
"opt_measured_tokens": opt_measured_tokens + p_opt_tokens, # prompt compaction is always live
|
|
225
|
+
"opt_modeled_tokens": opt_modeled_tokens,
|
|
207
226
|
"saved_tokens": task_saved,
|
|
208
227
|
"reduction_pct": round(task_pct, 1),
|
|
209
228
|
"base_turns": task.get("baseline_turns", 1),
|
|
@@ -222,6 +241,8 @@ class BenchmarkSuite:
|
|
|
222
241
|
"tasks": results,
|
|
223
242
|
"total_base_tokens": total_base_tokens,
|
|
224
243
|
"total_opt_tokens": total_opt_tokens,
|
|
244
|
+
"total_opt_measured_tokens": sum(t["opt_measured_tokens"] for t in results),
|
|
245
|
+
"total_opt_modeled_tokens": sum(t["opt_modeled_tokens"] for t in results),
|
|
225
246
|
"total_saved_tokens": net_saved,
|
|
226
247
|
"net_reduction_pct": round(net_pct, 1),
|
|
227
248
|
"base_cost_usd": round(base_cost, 4),
|
|
@@ -245,6 +266,12 @@ class BenchmarkSuite:
|
|
|
245
266
|
out.append(f" {BOLD}Cost Comparison:{RESET} ${data['base_cost_usd']:.4f} โ {GREEN}${data['opt_cost_usd']:.4f} USD{RESET} (Saved: ${data['cost_saved_usd']:.4f})")
|
|
246
267
|
out.append(f" {BOLD}Agent Latency / Turns:{RESET} {data['total_base_turns']} turns โ {GREEN}{data['total_opt_turns']} turns{RESET} ({data['speedup_pct']}% faster via Prefetching)\n")
|
|
247
268
|
|
|
269
|
+
# SIMULATION DISCLOSURE โ honest provenance of every number (METRICS.md)
|
|
270
|
+
out.append(f" {BOLD}Evidence Breakdown:{RESET}")
|
|
271
|
+
out.append(f" โข {GREEN}Measured live{RESET}: {data['total_opt_measured_tokens']:,} optimized tokens (real tool outputs produced during this run)")
|
|
272
|
+
out.append(f" โข {YELLOW}Modeled{RESET}: {data['total_opt_modeled_tokens']:,} optimized tokens (constants for typical production sizes)")
|
|
273
|
+
out.append(f" โข All baseline sizes and turn counts are {YELLOW}modeled{RESET}; this is a simulation harness, not a metered production run.\n")
|
|
274
|
+
|
|
248
275
|
out.append(f"{BOLD}โโ Task Breakdown โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ{RESET}")
|
|
249
276
|
for t in data["tasks"]:
|
|
250
277
|
out.append(f" โข {BOLD}{t['id']}: {t['name']:<48}{RESET}")
|
|
@@ -258,6 +285,11 @@ class BenchmarkSuite:
|
|
|
258
285
|
md = []
|
|
259
286
|
md.append("# ๐ Zero-Loss SWE-bench Benchmark Report\n")
|
|
260
287
|
md.append("> **Objective Proof of 80%+ Cost Reduction with 100% Accuracy Retention.**\n")
|
|
288
|
+
md.append("> **SIMULATION DISCLOSURE:** this is a simulated harness. All *baseline* sizes and turn")
|
|
289
|
+
md.append("> counts are **modeled** from typical production values. On the optimized side,")
|
|
290
|
+
md.append(f"> **{data['total_opt_measured_tokens']:,} tokens are measured live** by running the real tools during this run,")
|
|
291
|
+
md.append(f"> while **{data['total_opt_modeled_tokens']:,} tokens are modeled constants**. Task success is self-verified.")
|
|
292
|
+
md.append("> Production savings are tracked separately with measured/estimated labels โ see [METRICS.md](METRICS.md).\n")
|
|
261
293
|
md.append("| Metric | Baseline (Standard Agent) | Optimized (`agy-token-optimizer`) | Gain |")
|
|
262
294
|
md.append("| :--- | :--- | :--- | :--- |")
|
|
263
295
|
md.append(f"| **Context Tokens** | `{data['total_base_tokens']:,}` | `{data['total_opt_tokens']:,}` | **-{data['net_reduction_pct']}%** |")
|
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/installer.py
CHANGED
|
@@ -643,6 +643,36 @@ class AgentInstaller:
|
|
|
643
643
|
|
|
644
644
|
return restarted
|
|
645
645
|
|
|
646
|
+
@staticmethod
|
|
647
|
+
def _find_npm(home: Optional[str] = None) -> Optional[str]:
|
|
648
|
+
"""Locates an npm executable even in a clean non-interactive environment.
|
|
649
|
+
|
|
650
|
+
The updater dialog runs via `do shell script` + login shell, where .zshrc
|
|
651
|
+
(and therefore nvm) is never sourced; PATH-only discovery made the npm
|
|
652
|
+
channel silently skip updates. Falls back to well-known locations."""
|
|
653
|
+
found = shutil.which("npm")
|
|
654
|
+
if found:
|
|
655
|
+
return found
|
|
656
|
+
base = home or HOME
|
|
657
|
+
candidates: List[str] = []
|
|
658
|
+
nvm_dir = os.path.join(base, ".nvm", "versions", "node")
|
|
659
|
+
try:
|
|
660
|
+
if os.path.isdir(nvm_dir):
|
|
661
|
+
# Newest installed node version wins.
|
|
662
|
+
for version_dir in sorted(os.listdir(nvm_dir), reverse=True):
|
|
663
|
+
candidates.append(os.path.join(nvm_dir, version_dir, "bin", "npm"))
|
|
664
|
+
except OSError:
|
|
665
|
+
pass
|
|
666
|
+
candidates += [
|
|
667
|
+
"/opt/homebrew/bin/npm",
|
|
668
|
+
"/usr/local/bin/npm",
|
|
669
|
+
"/usr/bin/npm",
|
|
670
|
+
]
|
|
671
|
+
for cand in candidates:
|
|
672
|
+
if os.path.isfile(cand) and os.access(cand, os.X_OK):
|
|
673
|
+
return cand
|
|
674
|
+
return None
|
|
675
|
+
|
|
646
676
|
@classmethod
|
|
647
677
|
def self_update(cls):
|
|
648
678
|
"""
|
|
@@ -668,29 +698,43 @@ class AgentInstaller:
|
|
|
668
698
|
print(f" {YELLOW}โ {RESET} Git pull skipped: {e}")
|
|
669
699
|
|
|
670
700
|
# 2. Check npm global
|
|
671
|
-
|
|
701
|
+
# The updater dialog runs via `do shell script` + login shell, which skips
|
|
702
|
+
# .zshrc โ nvm is NOT on PATH there, so PATH-only discovery silently
|
|
703
|
+
# downgraded the npm channel (the active one for many installs).
|
|
704
|
+
npm_bin = cls._find_npm()
|
|
705
|
+
if npm_bin:
|
|
672
706
|
try:
|
|
673
|
-
res = subprocess.run([
|
|
707
|
+
res = subprocess.run([npm_bin, "list", "-g", "--depth=0", "tokensafe"], capture_output=True, text=True, timeout=15)
|
|
674
708
|
if "tokensafe@" in res.stdout:
|
|
675
709
|
print(f" {CYAN}โ{RESET} Updating global npm package (npm install -g tokensafe@latest)...")
|
|
676
|
-
up_res = subprocess.run([
|
|
710
|
+
up_res = subprocess.run([npm_bin, "install", "-g", "tokensafe@latest"], capture_output=True, text=True, timeout=120)
|
|
677
711
|
if up_res.returncode == 0:
|
|
678
712
|
print(f" {GREEN}โ{RESET} npm package upgraded successfully.")
|
|
679
|
-
|
|
680
|
-
|
|
713
|
+
else:
|
|
714
|
+
detail = (up_res.stderr or up_res.stdout or "").strip()[:200]
|
|
715
|
+
print(f" {YELLOW}โ {RESET} npm upgrade failed: {detail}")
|
|
716
|
+
else:
|
|
717
|
+
print(f" {CYAN}โน{RESET} tokensafe not installed via npm โ skipping npm channel.")
|
|
718
|
+
except Exception as e:
|
|
719
|
+
print(f" {YELLOW}โ {RESET} npm update skipped: {e}")
|
|
720
|
+
else:
|
|
721
|
+
print(f" {YELLOW}โ {RESET} npm not found โ skipping npm channel.")
|
|
681
722
|
|
|
682
723
|
# 3. Check pip
|
|
683
724
|
pip_cmd = "pip3" if shutil.which("pip3") else ("pip" if shutil.which("pip") else None)
|
|
684
725
|
if pip_cmd:
|
|
685
726
|
try:
|
|
686
|
-
res = subprocess.run([pip_cmd, "list"], capture_output=True, text=True, timeout=
|
|
727
|
+
res = subprocess.run([pip_cmd, "list"], capture_output=True, text=True, timeout=15)
|
|
687
728
|
if "tokensafe" in res.stdout:
|
|
688
729
|
print(f" {CYAN}โ{RESET} Updating Python package ({pip_cmd} install --upgrade tokensafe)...")
|
|
689
|
-
up_res = subprocess.run([pip_cmd, "install", "--upgrade", "tokensafe"], capture_output=True, text=True, timeout=
|
|
730
|
+
up_res = subprocess.run([pip_cmd, "install", "--upgrade", "tokensafe"], capture_output=True, text=True, timeout=120)
|
|
690
731
|
if up_res.returncode == 0:
|
|
691
732
|
print(f" {GREEN}โ{RESET} Python package upgraded successfully.")
|
|
692
|
-
|
|
693
|
-
|
|
733
|
+
else:
|
|
734
|
+
detail = (up_res.stderr or up_res.stdout or "").strip()[:200]
|
|
735
|
+
print(f" {YELLOW}โ {RESET} pip upgrade failed: {detail}")
|
|
736
|
+
except Exception as e:
|
|
737
|
+
print(f" {YELLOW}โ {RESET} pip update skipped: {e}")
|
|
694
738
|
|
|
695
739
|
# 4. Re-synchronize all detected agents
|
|
696
740
|
print(f"\n {CYAN}โ{RESET} Re-synchronizing AI Agent MCP configs & rules...")
|
|
@@ -722,7 +766,8 @@ class AgentInstaller:
|
|
|
722
766
|
|
|
723
767
|
print(f"\n{BOLD}{GREEN}โ
Self-update complete!{RESET}")
|
|
724
768
|
print(f" Synchronized {synced_count} agent environments with zero-loss AST & God Nodes rules.")
|
|
725
|
-
print(f" Run {BOLD}tokensafe stats{RESET} to view token savings
|
|
769
|
+
print(f" Run {BOLD}tokensafe stats{RESET} to view token savings.")
|
|
770
|
+
print(f" {CYAN}โน{RESET} If your terminal still shows the old version, open a new window or run {BOLD}hash -r{RESET}.")
|
|
726
771
|
|
|
727
772
|
def main():
|
|
728
773
|
args = sys.argv[1:]
|
package/src/mcp_server.py
CHANGED
|
@@ -28,6 +28,8 @@ from src.metrics import MetricsTracker
|
|
|
28
28
|
from src.dashboard import Dashboard
|
|
29
29
|
from src.graph_engine import GraphEngine
|
|
30
30
|
from src.tokenizer import count_tokens
|
|
31
|
+
from src.history_compactor import HistoryCompactor
|
|
32
|
+
from src.team_cache import TeamCache
|
|
31
33
|
from src.agent_firewall import AgentFirewall
|
|
32
34
|
from src.diff_slicer import DiffSlicer
|
|
33
35
|
from src.guard import TokenSafeGuard
|
|
@@ -35,7 +37,7 @@ from src.scoped_search import ScopedSearch
|
|
|
35
37
|
|
|
36
38
|
SERVER_INFO = {
|
|
37
39
|
"name": "tokensafe-mcp",
|
|
38
|
-
"version": "1.
|
|
40
|
+
"version": "1.6.0"
|
|
39
41
|
}
|
|
40
42
|
|
|
41
43
|
TOOLS = [
|
|
@@ -85,6 +87,18 @@ TOOLS = [
|
|
|
85
87
|
"required": ["prompt"]
|
|
86
88
|
}
|
|
87
89
|
},
|
|
90
|
+
{
|
|
91
|
+
"name": "compact_conversation",
|
|
92
|
+
"description": "On-demand context compaction: folds a long agent conversation transcript into a compact Consolidated State Ledger. Use when the context window feels heavy or before starting a new subtask inside the same session.",
|
|
93
|
+
"inputSchema": {
|
|
94
|
+
"type": "object",
|
|
95
|
+
"properties": {
|
|
96
|
+
"transcript_path": {"type": "string", "description": "Path to the JSONL transcript of the current session"},
|
|
97
|
+
"invocation_num": {"type": "integer", "description": "Optional: current turn number (default 3; folding requires >= 3 turns)"}
|
|
98
|
+
},
|
|
99
|
+
"required": ["transcript_path"]
|
|
100
|
+
}
|
|
101
|
+
},
|
|
88
102
|
{
|
|
89
103
|
"name": "sanitize_command",
|
|
90
104
|
"description": "Rewrites shell commands (git diff, git log, pytest, grep) to prune lockfiles and unbounded logs.",
|
|
@@ -378,6 +392,42 @@ def _get_safe_tracker():
|
|
|
378
392
|
return _NoOpTracker()
|
|
379
393
|
|
|
380
394
|
|
|
395
|
+
def _team_skeleton_lookup(path: str, symbol: str) -> Optional[str]:
|
|
396
|
+
"""Team cache pre-warm lookup: returns a teammate's cached skeleton or None.
|
|
397
|
+
|
|
398
|
+
Never blocks the caller for more than ~250ms: the network fetch runs in a
|
|
399
|
+
daemon thread with a short join. Non-team installs skip the network entirely."""
|
|
400
|
+
try:
|
|
401
|
+
is_team, _ = TeamCache._is_team_tier()
|
|
402
|
+
if not is_team:
|
|
403
|
+
return None
|
|
404
|
+
box: dict = {}
|
|
405
|
+
|
|
406
|
+
def _fetch():
|
|
407
|
+
try:
|
|
408
|
+
box["value"] = TeamCache.get("SKELETON", f"{path}::{symbol or ''}")
|
|
409
|
+
except Exception:
|
|
410
|
+
pass
|
|
411
|
+
|
|
412
|
+
t = threading.Thread(target=_fetch, daemon=True)
|
|
413
|
+
t.start()
|
|
414
|
+
t.join(0.25)
|
|
415
|
+
return box.get("value")
|
|
416
|
+
except Exception:
|
|
417
|
+
return None
|
|
418
|
+
|
|
419
|
+
|
|
420
|
+
def _team_skeleton_prewarm(path: str, symbol: str, skeleton_text: str, tokens_saved: int):
|
|
421
|
+
"""Publishes a freshly built skeleton to the team cache (async, team tier only).
|
|
422
|
+
|
|
423
|
+
Teammate B's later smart_read_file on the same symbol hits the cache instead
|
|
424
|
+
of re-reading and re-skeletonizing the file."""
|
|
425
|
+
try:
|
|
426
|
+
TeamCache.put("SKELETON", f"{path}::{symbol or ''}", skeleton_text, tokens_saved=tokens_saved)
|
|
427
|
+
except Exception:
|
|
428
|
+
pass
|
|
429
|
+
|
|
430
|
+
|
|
381
431
|
def handle_tool_call(name: str, args: dict) -> dict:
|
|
382
432
|
if args is None or not isinstance(args, dict):
|
|
383
433
|
args = {}
|
|
@@ -454,6 +504,23 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
|
|
|
454
504
|
return {"content": [{"type": "text", "text": (prefetch_block or "") + content}]}
|
|
455
505
|
|
|
456
506
|
if symbol:
|
|
507
|
+
# Team pre-warm hit: a teammate already skeletonized this symbol
|
|
508
|
+
team_skel = _team_skeleton_lookup(path, symbol)
|
|
509
|
+
if team_skel:
|
|
510
|
+
with open(path, "r", encoding="utf-8", errors="replace") as f:
|
|
511
|
+
raw_code = f.read()
|
|
512
|
+
orig_t = count_tokens(raw_code)
|
|
513
|
+
skel_t = count_tokens(team_skel)
|
|
514
|
+
tracker.record_event(
|
|
515
|
+
session_id="mcp_session",
|
|
516
|
+
event_type="TEAM_CACHE_HIT",
|
|
517
|
+
original_tokens=orig_t,
|
|
518
|
+
optimized_tokens=skel_t,
|
|
519
|
+
details={"file": os.path.basename(path), "symbol": symbol, "source": "team_cache"}
|
|
520
|
+
)
|
|
521
|
+
header = f"// [TokenSafe Team-Cached Skeleton for '{symbol}' | shared by a teammate]\n"
|
|
522
|
+
return {"content": [{"type": "text", "text": (prefetch_block or "") + header + team_skel}]}
|
|
523
|
+
|
|
457
524
|
try:
|
|
458
525
|
graph, rel_path = GraphEngine.for_file(path)
|
|
459
526
|
inc_deps = bool(args.get("include_deps", True))
|
|
@@ -473,6 +540,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
|
|
|
473
540
|
)
|
|
474
541
|
dep_label = "Full body + 1-hop dependencies" if inc_deps else "Surgical single-symbol isolation"
|
|
475
542
|
header = f"// [TokenSafe Graph-Guided Skeleton for '{symbol}' | {dep_label}]\n"
|
|
543
|
+
_team_skeleton_prewarm(path, symbol, graph_skel, saved)
|
|
476
544
|
return {"content": [{"type": "text", "text": (prefetch_block or "") + header + graph_skel}]}
|
|
477
545
|
except Exception:
|
|
478
546
|
pass
|
|
@@ -504,6 +572,38 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
|
|
|
504
572
|
res = PromptCompactor.compact(prompt, enable_deepseek=True)
|
|
505
573
|
return {"content": [{"type": "text", "text": json.dumps(res, indent=2, ensure_ascii=False)}]}
|
|
506
574
|
|
|
575
|
+
elif name == "compact_conversation":
|
|
576
|
+
transcript_path = args.get("transcript_path", "")
|
|
577
|
+
try:
|
|
578
|
+
invocation_num = max(3, int(args.get("invocation_num", 3) or 3))
|
|
579
|
+
except (TypeError, ValueError):
|
|
580
|
+
invocation_num = 3
|
|
581
|
+
if not transcript_path or not os.path.exists(transcript_path):
|
|
582
|
+
return {"isError": True, "content": [{"type": "text", "text": f"Transcript not found: {transcript_path}"}]}
|
|
583
|
+
ledger, orig_t, folded_t, stats = HistoryCompactor.fold_transcript(transcript_path, invocation_num)
|
|
584
|
+
if not ledger:
|
|
585
|
+
return {"content": [{"type": "text", "text": json.dumps({
|
|
586
|
+
"compactable": False,
|
|
587
|
+
"reason": "Transcript too short to fold (needs >= 4 steps and >= 1000 history tokens)"
|
|
588
|
+
}, indent=2)}]}
|
|
589
|
+
saved = max(0, orig_t - folded_t)
|
|
590
|
+
tracker.record_event(
|
|
591
|
+
session_id="mcp_session",
|
|
592
|
+
event_type="HISTORY_FOLD",
|
|
593
|
+
original_tokens=orig_t,
|
|
594
|
+
optimized_tokens=folded_t,
|
|
595
|
+
details={"mode": "manual_compact_conversation", "turns": invocation_num, **stats}
|
|
596
|
+
)
|
|
597
|
+
return {"content": [{"type": "text", "text": json.dumps({
|
|
598
|
+
"compactable": True,
|
|
599
|
+
"ledger": ledger,
|
|
600
|
+
"original_tokens": orig_t,
|
|
601
|
+
"folded_tokens": folded_t,
|
|
602
|
+
"saved_tokens": saved,
|
|
603
|
+
"note": "Inject this ledger as a system message and start fresh context from it; savings are labeled estimated (digest injected, history not removed).",
|
|
604
|
+
"stats": stats
|
|
605
|
+
}, indent=2, ensure_ascii=False)}]}
|
|
606
|
+
|
|
507
607
|
elif name == "sanitize_command":
|
|
508
608
|
cmd = args.get("command", "")
|
|
509
609
|
# Step 1: TokenSafe Guard security inspection
|
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
|
-
|
|
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:
|
|
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
|
|
package/src/skeletonizer.py
CHANGED
|
@@ -173,7 +173,8 @@ class Skeletonizer:
|
|
|
173
173
|
@classmethod
|
|
174
174
|
def skeletonize_code(cls, code: str, file_ext: str, keep_symbols: Optional[Set[str]] = None) -> str:
|
|
175
175
|
"""Skeletons source code based on file extension, optionally preserving keep_symbols."""
|
|
176
|
-
ext = file_ext.lower()
|
|
176
|
+
ext = file_ext.lower().lstrip(".")
|
|
177
|
+
ext = f".{ext}" if ext else ""
|
|
177
178
|
if ext == ".py":
|
|
178
179
|
return cls._skeletonize_python(code, keep_symbols=keep_symbols)
|
|
179
180
|
elif ext in (
|
package/src/telemetry_sync.py
CHANGED
|
@@ -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
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
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.
|
|
267
|
+
"User-Agent": "TokenSafe-Sync/1.6.0"
|
|
253
268
|
}
|
|
254
269
|
if active_key:
|
|
255
270
|
headers["Authorization"] = f"Bearer {active_key}"
|
package/src/version_checker.py
CHANGED
|
@@ -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.
|
|
19
|
+
CURRENT_VERSION = "1.6.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
|
|
Binary file
|