tokensafe 1.5.0 → 1.7.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/claude_code_hook.py +92 -0
- package/hooks/cursor_hook.py +85 -0
- package/package.json +1 -1
- package/plugin.json +1 -1
- package/server.json +3 -3
- package/skills/token-optimizer/SKILL.md +2 -0
- package/src/adapter_core.py +167 -0
- package/src/benchmark.py +32 -0
- package/src/installer.py +133 -10
- package/src/mcp_server.py +101 -1
- package/src/skeletonizer.py +2 -1
- package/src/telemetry_sync.py +1 -1
- package/src/version_checker.py +1 -1
package/README.md
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
|
|
8
8
|
<p align="center">
|
|
9
9
|
<b>Autonomous Zero-Loss Token Economy & Context Optimizer for AI Coding Agents</b><br>
|
|
10
|
-
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>
|
|
11
11
|
Built for <b>Cursor, Claude Desktop, Google Antigravity, Windsurf & Cline</b>.
|
|
12
12
|
</p>
|
|
13
13
|
|
|
@@ -69,6 +69,20 @@ pure-Python path adds no measurable latency after the first hook invocation.
|
|
|
69
69
|
|
|
70
70
|
---
|
|
71
71
|
|
|
72
|
+
## 🪝 Universal Agent Hooks (Claude Code & Cursor)
|
|
73
|
+
|
|
74
|
+
Beyond MCP, TokenSafe ships **lifecycle-hook adapters** that run natively inside your agent's loop — installed automatically by `tokensafe setup`:
|
|
75
|
+
|
|
76
|
+
| Agent | Hook | What it does |
|
|
77
|
+
|---|---|---|
|
|
78
|
+
| **Claude Code** | `UserPromptSubmit` | Compacts the prompt into a TOCP S-expression and injects it as `additionalContext` (labeled *estimated* per [METRICS.md](METRICS.md)) |
|
|
79
|
+
| **Claude Code** | `PreToolUse` (Bash) | Denies secret-bearing and destructive commands; asks on TLS-verification bypasses |
|
|
80
|
+
| **Cursor** | `beforeShellExecution` | Same shell guard — deny secrets/destruction, ask on `-k`/`--insecure` |
|
|
81
|
+
| **Cursor** | `beforeReadFile` | Blocks lockfile/bundle/`dist/` dumps that would burn ~50k context tokens |
|
|
82
|
+
| **Codex CLI** | — | No lifecycle hooks yet; MCP + AGENTS.md remain the integration |
|
|
83
|
+
|
|
84
|
+
All adapters **fail open**: a crash never blocks the host agent (Cursor's block-on-invalid-JSON contract is explicitly honored — every error path prints valid allow-JSON).
|
|
85
|
+
|
|
72
86
|
## 🔌 Universal MCP Server Configuration
|
|
73
87
|
|
|
74
88
|
Connect TokenSafe directly to **Claude Desktop** (`claude_desktop_config.json`) or **Cursor** MCP Settings:
|
|
@@ -316,7 +330,9 @@ tokensafe providers
|
|
|
316
330
|
|
|
317
331
|
## 📊 Zero-Loss SWE-bench Benchmark Results
|
|
318
332
|
|
|
319
|
-
|
|
333
|
+
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**):
|
|
334
|
+
|
|
335
|
+
> 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).
|
|
320
336
|
|
|
321
337
|
| Benchmark Scenario | Task Complexity | Baseline Tokens | TokenSafe Tokens | Reduction | Turn Speedup | Accuracy |
|
|
322
338
|
|---|---|---|---|---|---|---|
|
|
@@ -519,11 +535,8 @@ TokenSafe Cloud Backend enforces enterprise zero-trust security across all commu
|
|
|
519
535
|
| `POST` | `/api/team/seat/revoke` | **Bearer Auth** | `Authorization: Bearer <jwt\|key>`, JSON `{ owner_email, license_key }` | Revokes an active team seat license key. |
|
|
520
536
|
| `POST` | `/api/telemetry/sync` | **License Auth** | JSON `{ license_key, email, events: [...] }` | Syncs batch telemetry events (enforces max 50 events/batch). |
|
|
521
537
|
| `POST` | `/webhook/stripe` | **HMAC Sig** | `Stripe-Signature: t=...,v1=...` | Verifies Stripe webhook payload against `STRIPE_WEBHOOK_SECRET`. |
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
| `POST` | `/api/admin/license/issue`| **Admin Only** | `X-Admin-Secret` or Admin JWT | Manually issues or provisions a custom tier license. |
|
|
525
|
-
| `POST` | `/api/admin/license/revoke`| **Admin Only**| `X-Admin-Secret` or Admin JWT | Immediately revokes a license. |
|
|
526
|
-
| `POST` | `/api/admin/license/extend`| **Admin Only**| `X-Admin-Secret` or Admin JWT | Extends an active license duration. |
|
|
538
|
+
|
|
539
|
+
> **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).
|
|
527
540
|
|
|
528
541
|
### 3. Server Configuration & Environment Variables
|
|
529
542
|
|
|
@@ -531,7 +544,7 @@ TokenSafe Cloud Backend enforces enterprise zero-trust security across all commu
|
|
|
531
544
|
|---|---|---|
|
|
532
545
|
| `TOKENSAFE_PRIVATE_KEY` | Production | 64-character hex Ed25519 seed for issuing `TS2.` licenses. |
|
|
533
546
|
| `ADMIN_SECRET_KEY` | Yes | High-entropy secret for administrative API access (`X-Admin-Secret`). |
|
|
534
|
-
| `ADMIN_EMAILS` | Optional | Comma-separated admin emails (e.g. `
|
|
547
|
+
| `ADMIN_EMAILS` | Optional | Comma-separated admin emails (e.g. `admin@yourcompany.com`). |
|
|
535
548
|
| `STRIPE_WEBHOOK_SECRET` | Production | Webhook secret (`whsec_...`) used to verify Stripe webhooks. |
|
|
536
549
|
| `SMTP_PASS` | Production | Password/token for transactional mail delivery via ImprovMX SMTP. |
|
|
537
550
|
| `JWT_SECRET` | Optional | Shared HMAC secret for verifying custom JWT tokens. Set a persistent value in production — otherwise sessions invalidate on every restart. |
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""
|
|
3
|
+
TokenSafe adapter for Claude Code lifecycle hooks.
|
|
4
|
+
|
|
5
|
+
Registered via ~/.claude/settings.json:
|
|
6
|
+
UserPromptSubmit -> compacts the prompt and INJECTS the TOCP form as
|
|
7
|
+
additionalContext (verified inject point in the
|
|
8
|
+
official Claude Code hooks schema).
|
|
9
|
+
PreToolUse (Bash) -> denies secret-bearing / destructive commands,
|
|
10
|
+
asks on TLS-verification bypasses.
|
|
11
|
+
|
|
12
|
+
Contract: stdin = one JSON payload, stdout = one JSON response.
|
|
13
|
+
Fail-open: any internal error emits `{}` (Claude treats empty stdout as allow).
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
import sys
|
|
17
|
+
import json
|
|
18
|
+
import os
|
|
19
|
+
|
|
20
|
+
HOOK_DIR = os.path.dirname(os.path.abspath(__file__))
|
|
21
|
+
PROJECT_ROOT = os.path.dirname(HOOK_DIR)
|
|
22
|
+
if PROJECT_ROOT not in sys.path:
|
|
23
|
+
sys.path.insert(0, PROJECT_ROOT)
|
|
24
|
+
|
|
25
|
+
from src.adapter_core import compact_for_injection, guard_command
|
|
26
|
+
|
|
27
|
+
AGENT = "claude_code"
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def handle(event: str, payload: dict) -> dict:
|
|
31
|
+
session_id = str(payload.get("session_id") or "") or f"hook_{AGENT}"
|
|
32
|
+
|
|
33
|
+
if event == "UserPromptSubmit":
|
|
34
|
+
prompt = str(payload.get("prompt") or "")
|
|
35
|
+
context, meta = compact_for_injection(prompt, AGENT, session_id)
|
|
36
|
+
if context and meta.get("compacted"):
|
|
37
|
+
return {
|
|
38
|
+
"hookSpecificOutput": {
|
|
39
|
+
"hookEventName": "UserPromptSubmit",
|
|
40
|
+
"additionalContext": (
|
|
41
|
+
f"{context}\n"
|
|
42
|
+
f"(TokenSafe: compacted ~{meta['saved_tokens']} prompt tokens, "
|
|
43
|
+
f"-{meta.get('reduction_pct', 0)}% — original intent preserved.)"
|
|
44
|
+
),
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
return {}
|
|
48
|
+
|
|
49
|
+
if event == "PreToolUse":
|
|
50
|
+
tool = str(payload.get("tool_name") or "")
|
|
51
|
+
tool_input = payload.get("tool_input") or {}
|
|
52
|
+
if tool in ("Bash", "Shell", "bash"):
|
|
53
|
+
command = str(tool_input.get("command") or "")
|
|
54
|
+
verdict = guard_command(command, AGENT, session_id)
|
|
55
|
+
if verdict["decision"] == "deny":
|
|
56
|
+
return {
|
|
57
|
+
"hookSpecificOutput": {
|
|
58
|
+
"hookEventName": "PreToolUse",
|
|
59
|
+
"permissionDecision": "deny",
|
|
60
|
+
"permissionDecisionReason": verdict["reason"],
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
if verdict["decision"] == "ask":
|
|
64
|
+
return {
|
|
65
|
+
"hookSpecificOutput": {
|
|
66
|
+
"hookEventName": "PreToolUse",
|
|
67
|
+
"permissionDecision": "ask",
|
|
68
|
+
"permissionDecisionReason": verdict["reason"],
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
return {}
|
|
72
|
+
|
|
73
|
+
return {}
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def main():
|
|
77
|
+
try:
|
|
78
|
+
raw = sys.stdin.read()
|
|
79
|
+
payload = json.loads(raw) if raw.strip() else {}
|
|
80
|
+
except Exception:
|
|
81
|
+
print(json.dumps({}))
|
|
82
|
+
return
|
|
83
|
+
event = str(payload.get("hook_event_name") or "")
|
|
84
|
+
try:
|
|
85
|
+
response = handle(event, payload if isinstance(payload, dict) else {})
|
|
86
|
+
except Exception:
|
|
87
|
+
response = {}
|
|
88
|
+
print(json.dumps(response))
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
if __name__ == "__main__":
|
|
92
|
+
main()
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""
|
|
3
|
+
TokenSafe adapter for Cursor agent hooks (~/.cursor/hooks.json).
|
|
4
|
+
|
|
5
|
+
Honest capability matrix (per official Cursor hooks docs):
|
|
6
|
+
beforeShellExecution -> allow/deny/ask: blocks secret-bearing,
|
|
7
|
+
destructive and TLS-bypassing commands.
|
|
8
|
+
beforeReadFile -> allow/deny: blocks lockfile/bundle/dist dumps
|
|
9
|
+
that would burn ~50k context tokens.
|
|
10
|
+
beforeSubmitPrompt -> allow/deny ONLY (no injection in Cursor yet):
|
|
11
|
+
records nothing, always allows. Kept as a no-op
|
|
12
|
+
so the hook wiring is future-proof.
|
|
13
|
+
stop / afterFileEdit -> observational no-ops.
|
|
14
|
+
|
|
15
|
+
IMPORTANT: Cursor BLOCKS the action when a hook prints invalid JSON.
|
|
16
|
+
Fail-open here means printing a valid per-event ALLOW response from the
|
|
17
|
+
exception handler, never an empty string.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
import sys
|
|
21
|
+
import json
|
|
22
|
+
import os
|
|
23
|
+
|
|
24
|
+
HOOK_DIR = os.path.dirname(os.path.abspath(__file__))
|
|
25
|
+
PROJECT_ROOT = os.path.dirname(HOOK_DIR)
|
|
26
|
+
if PROJECT_ROOT not in sys.path:
|
|
27
|
+
sys.path.insert(0, PROJECT_ROOT)
|
|
28
|
+
|
|
29
|
+
from src.adapter_core import guard_command, guard_read
|
|
30
|
+
|
|
31
|
+
AGENT = "cursor"
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _allow(event: str) -> dict:
|
|
35
|
+
if event == "beforeSubmitPrompt":
|
|
36
|
+
return {"continue": True}
|
|
37
|
+
return {"permission": "allow"}
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def handle(event: str, payload: dict) -> dict:
|
|
41
|
+
session_id = str(payload.get("conversation_id") or payload.get("session_id") or "") or f"hook_{AGENT}"
|
|
42
|
+
|
|
43
|
+
if event == "beforeShellExecution":
|
|
44
|
+
command = str(payload.get("command") or "")
|
|
45
|
+
verdict = guard_command(command, AGENT, session_id)
|
|
46
|
+
if verdict["decision"] == "deny":
|
|
47
|
+
return {"permission": "deny", "user_message": verdict["reason"]}
|
|
48
|
+
if verdict["decision"] == "ask":
|
|
49
|
+
return {"permission": "ask", "agent_message": verdict["reason"]}
|
|
50
|
+
return {"permission": "allow"}
|
|
51
|
+
|
|
52
|
+
if event == "beforeReadFile":
|
|
53
|
+
file_path = str(payload.get("file_path") or "")
|
|
54
|
+
verdict = guard_read(file_path, AGENT, session_id)
|
|
55
|
+
if verdict["decision"] == "deny":
|
|
56
|
+
return {"permission": "deny", "user_message": verdict["reason"]}
|
|
57
|
+
return {"permission": "allow"}
|
|
58
|
+
|
|
59
|
+
if event == "beforeSubmitPrompt":
|
|
60
|
+
# Cursor cannot inject context (allow/deny only). Nothing honest to
|
|
61
|
+
# record: the model still sees the full prompt. Always allow.
|
|
62
|
+
return {"continue": True}
|
|
63
|
+
|
|
64
|
+
return _allow(event)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def main():
|
|
68
|
+
try:
|
|
69
|
+
raw = sys.stdin.read()
|
|
70
|
+
payload = json.loads(raw) if raw.strip() else {}
|
|
71
|
+
except Exception:
|
|
72
|
+
print(json.dumps({}))
|
|
73
|
+
return
|
|
74
|
+
event = str(payload.get("hook_event_name") or "")
|
|
75
|
+
try:
|
|
76
|
+
response = handle(event, payload if isinstance(payload, dict) else {})
|
|
77
|
+
except Exception:
|
|
78
|
+
response = _allow(event)
|
|
79
|
+
if not isinstance(response, dict) or not response:
|
|
80
|
+
response = _allow(event)
|
|
81
|
+
print(json.dumps(response))
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
if __name__ == "__main__":
|
|
85
|
+
main()
|
package/package.json
CHANGED
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.7.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
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"name": "dev.tokensafe/tokensafe",
|
|
4
4
|
"title": "TokenSafe",
|
|
5
5
|
"description": "Cut AI coding agent token usage up to 90% via AST slicing, dependency graphs & security guards.",
|
|
6
|
-
"version": "1.
|
|
6
|
+
"version": "1.7.0",
|
|
7
7
|
"websiteUrl": "https://tokensafe.dev",
|
|
8
8
|
"repository": {
|
|
9
9
|
"url": "https://github.com/NekoSin4eG/tokensafe",
|
|
@@ -30,7 +30,7 @@
|
|
|
30
30
|
"registryType": "npm",
|
|
31
31
|
"registryBaseUrl": "https://registry.npmjs.org",
|
|
32
32
|
"identifier": "tokensafe",
|
|
33
|
-
"version": "1.
|
|
33
|
+
"version": "1.7.0",
|
|
34
34
|
"runtimeHint": "npx",
|
|
35
35
|
"transport": {
|
|
36
36
|
"type": "stdio"
|
|
@@ -46,7 +46,7 @@
|
|
|
46
46
|
"registryType": "pypi",
|
|
47
47
|
"registryBaseUrl": "https://pypi.org",
|
|
48
48
|
"identifier": "tokensafe",
|
|
49
|
-
"version": "1.
|
|
49
|
+
"version": "1.7.0",
|
|
50
50
|
"runtimeHint": "uvx",
|
|
51
51
|
"transport": {
|
|
52
52
|
"type": "stdio"
|
|
@@ -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**:
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Shared core for cross-agent lifecycle-hook adapters (Claude Code, Cursor, ZCode).
|
|
3
|
+
|
|
4
|
+
Design rules (see METRICS.md):
|
|
5
|
+
- Savings are only recorded for REAL reductions: injected TOCP prompts are
|
|
6
|
+
labeled estimated; blocked reads/commands are measured (the model never
|
|
7
|
+
receives the blocked bytes).
|
|
8
|
+
- Adapters ALWAYS fail open: an adapter crash must never block the host agent.
|
|
9
|
+
(Cursor additionally blocks on invalid JSON, so adapters return valid
|
|
10
|
+
allow-JSON from the exception handler.)
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
import os
|
|
14
|
+
import sys
|
|
15
|
+
import re
|
|
16
|
+
import json
|
|
17
|
+
from typing import Dict, Any, Optional, Tuple
|
|
18
|
+
|
|
19
|
+
PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
20
|
+
if PROJECT_ROOT not in sys.path:
|
|
21
|
+
sys.path.insert(0, PROJECT_ROOT)
|
|
22
|
+
|
|
23
|
+
# High-precision deny patterns: secrets and irreversible destruction only.
|
|
24
|
+
_SECRET_PATTERNS = [
|
|
25
|
+
r"sk_live_[0-9a-zA-Z]{10,}",
|
|
26
|
+
r"AKIA[0-9A-Z]{16}",
|
|
27
|
+
r"ghp_[0-9a-zA-Z]{30,}",
|
|
28
|
+
r"xox[baprs]-[0-9a-zA-Z-]{10,}",
|
|
29
|
+
r"-----BEGIN [A-Z ]*PRIVATE KEY-----",
|
|
30
|
+
]
|
|
31
|
+
_DESTRUCTIVE_PATTERNS = [
|
|
32
|
+
r"rm\s+(-[a-zA-Z]*\s+)*-?[rf]{2,}[a-zA-Z]*\s+(--\s+)?/(?:\s|$)", # rm -rf /
|
|
33
|
+
r"rm\s+(-[a-zA-Z]*\s+)*-?[rf]{2,}[a-zA-Z]*\s+~(?:/\s*)?(?:\s|$)", # rm -rf ~
|
|
34
|
+
r"dd\s+.*of=/dev/[sd]",
|
|
35
|
+
r"mkfs\.\w+",
|
|
36
|
+
r"chmod\s+-R\s+777\s+/(?:\s|$)",
|
|
37
|
+
r":\(\)\{.*\};:", # fork bomb
|
|
38
|
+
]
|
|
39
|
+
_TLS_BYPASS_PATTERNS = [
|
|
40
|
+
r"curl\s+(-[a-zA-Z]+\s+)*-k\b",
|
|
41
|
+
r"curl\s+.*--insecure",
|
|
42
|
+
r"NODE_TLS_REJECT_UNAUTHORIZED\s*=\s*0",
|
|
43
|
+
r"wget\s+.*--no-check-certificate",
|
|
44
|
+
]
|
|
45
|
+
|
|
46
|
+
# Lockfiles/junk that must never be dumped into an agent context.
|
|
47
|
+
_JUNK_READ_PATTERNS = [
|
|
48
|
+
r"(^|/)(bun\.lock|package-lock\.json|pnpm-lock\.yaml|yarn\.lock|Cargo\.lock|go\.sum|composer\.lock)$",
|
|
49
|
+
r"\.(min\.js|min\.css|bundle\.js|map)$",
|
|
50
|
+
r"(^|/)dist/",
|
|
51
|
+
r"(^|/)node_modules/",
|
|
52
|
+
]
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _get_tracker():
|
|
56
|
+
try:
|
|
57
|
+
from src.metrics import MetricsTracker
|
|
58
|
+
return MetricsTracker()
|
|
59
|
+
except Exception:
|
|
60
|
+
return None
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def compact_for_injection(prompt: str, agent: str, session_id: str) -> Tuple[str, Dict[str, Any]]:
|
|
64
|
+
"""Compacts a user prompt into its TOCP form for context injection.
|
|
65
|
+
|
|
66
|
+
Returns (context_text, meta). context_text is '' when compaction is not
|
|
67
|
+
worthwhile. Savings are recorded as estimated: the compressed form is
|
|
68
|
+
injected alongside the original (no verified replace in host agents)."""
|
|
69
|
+
meta: Dict[str, Any] = {"agent": agent, "compacted": False}
|
|
70
|
+
if not prompt or len(prompt.strip()) < 5:
|
|
71
|
+
return "", meta
|
|
72
|
+
try:
|
|
73
|
+
from src.compactor import PromptCompactor
|
|
74
|
+
from src.tokenizer import count_tokens
|
|
75
|
+
compaction = PromptCompactor.compact(prompt, enable_deepseek=False)
|
|
76
|
+
saved = compaction.get("saved_tokens", 0)
|
|
77
|
+
if saved < 5:
|
|
78
|
+
return "", meta
|
|
79
|
+
tracker = _get_tracker()
|
|
80
|
+
if tracker:
|
|
81
|
+
try:
|
|
82
|
+
tracker.record_event(
|
|
83
|
+
session_id=session_id or f"hook_{agent}",
|
|
84
|
+
event_type="PROMPT",
|
|
85
|
+
original_tokens=compaction["original_tokens"],
|
|
86
|
+
optimized_tokens=compaction["compact_tokens"],
|
|
87
|
+
details={"agent": agent, "mode": "hook_inject", "tier": compaction.get("tier", "REGEX")},
|
|
88
|
+
)
|
|
89
|
+
except Exception:
|
|
90
|
+
pass
|
|
91
|
+
meta.update({"compacted": True, "saved_tokens": saved, "reduction_pct": compaction.get("reduction_pct", 0)})
|
|
92
|
+
return f"[TOCP Compressed Intent]: {compaction['compact_text']}", meta
|
|
93
|
+
except Exception:
|
|
94
|
+
return "", meta
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def guard_command(command: str, agent: str, session_id: str = "") -> Dict[str, Any]:
|
|
98
|
+
"""Pre-execution shell guard. Returns:
|
|
99
|
+
{decision: allow|deny|ask, reason, saved_tokens} where saved_tokens is the
|
|
100
|
+
MEASURED mass of blocked output (0 for allowed commands)."""
|
|
101
|
+
result = {"decision": "allow", "reason": "", "saved_tokens": 0}
|
|
102
|
+
if not command or not command.strip():
|
|
103
|
+
return result
|
|
104
|
+
cmd = command.strip()
|
|
105
|
+
text = cmd
|
|
106
|
+
|
|
107
|
+
def blocked(kind: str, reason: str, decision: str = "deny"):
|
|
108
|
+
est = max(50, len(cmd) // 4) # blocked mass never reaches the model
|
|
109
|
+
tracker = _get_tracker()
|
|
110
|
+
if tracker:
|
|
111
|
+
try:
|
|
112
|
+
tracker.record_event(
|
|
113
|
+
session_id=session_id or f"hook_{agent}",
|
|
114
|
+
event_type=f"GUARD_{kind}",
|
|
115
|
+
original_tokens=est,
|
|
116
|
+
optimized_tokens=0,
|
|
117
|
+
details={"agent": agent, "command": cmd[:120]},
|
|
118
|
+
)
|
|
119
|
+
except Exception:
|
|
120
|
+
pass
|
|
121
|
+
result.update({"decision": decision, "reason": reason, "saved_tokens": est})
|
|
122
|
+
|
|
123
|
+
for pat in _SECRET_PATTERNS:
|
|
124
|
+
if re.search(pat, text):
|
|
125
|
+
blocked("SECRET", f"Blocked: command contains a hardcoded secret ({pat[:12]}... pattern)")
|
|
126
|
+
return result
|
|
127
|
+
for pat in _DESTRUCTIVE_PATTERNS:
|
|
128
|
+
if re.search(pat, text):
|
|
129
|
+
blocked("DESTRUCTIVE", "Blocked: irreversible/destructive operation")
|
|
130
|
+
return result
|
|
131
|
+
for pat in _TLS_BYPASS_PATTERNS:
|
|
132
|
+
if re.search(pat, text):
|
|
133
|
+
blocked("TLS_VERIFY_BYPASS", "Certificate verification disabled — confirm this is intentional", decision="ask")
|
|
134
|
+
return result
|
|
135
|
+
return result
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def guard_read(file_path: str, agent: str, session_id: str = "") -> Dict[str, Any]:
|
|
139
|
+
"""Pre-read guard: denies lockfiles/bundles/dist junk that would burn the
|
|
140
|
+
context window. Blocked reads are recorded as measured savings."""
|
|
141
|
+
result = {"decision": "allow", "reason": "", "saved_tokens": 0}
|
|
142
|
+
if not file_path:
|
|
143
|
+
return result
|
|
144
|
+
normalized = file_path.replace("\\", "/")
|
|
145
|
+
for pat in _JUNK_READ_PATTERNS:
|
|
146
|
+
if re.search(pat, normalized):
|
|
147
|
+
est = 4000 # typical lockfile dump size floor
|
|
148
|
+
tracker = _get_tracker()
|
|
149
|
+
if tracker:
|
|
150
|
+
try:
|
|
151
|
+
tracker.record_event(
|
|
152
|
+
session_id=session_id or f"hook_{agent}",
|
|
153
|
+
event_type="GUARD_JUNK_READ",
|
|
154
|
+
original_tokens=est,
|
|
155
|
+
optimized_tokens=0,
|
|
156
|
+
details={"agent": agent, "file": os.path.basename(normalized)},
|
|
157
|
+
)
|
|
158
|
+
except Exception:
|
|
159
|
+
pass
|
|
160
|
+
result.update({
|
|
161
|
+
"decision": "deny",
|
|
162
|
+
"reason": f"TokenSafe: '{os.path.basename(normalized)}' is machine-generated bulk "
|
|
163
|
+
f"(~{est // 1000}k tokens). Inspect it via 'tokensafe:scoped_search' or grep a symbol instead.",
|
|
164
|
+
"saved_tokens": est,
|
|
165
|
+
})
|
|
166
|
+
return result
|
|
167
|
+
return result
|
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/installer.py
CHANGED
|
@@ -135,6 +135,72 @@ class AgentInstaller:
|
|
|
135
135
|
}
|
|
136
136
|
return detected
|
|
137
137
|
|
|
138
|
+
@staticmethod
|
|
139
|
+
def _tokensafe_hook_command(script_name: str) -> str:
|
|
140
|
+
"""Shell command string for a bundled hook adapter (space-safe)."""
|
|
141
|
+
script = os.path.join(PROJECT_ROOT, "hooks", script_name)
|
|
142
|
+
return f"{shlex.quote(PYTHON_BIN)} {shlex.quote(script)}"
|
|
143
|
+
|
|
144
|
+
@classmethod
|
|
145
|
+
def install_hooks_config(cls, agent_key: str) -> Tuple[bool, str]:
|
|
146
|
+
"""Registers TokenSafe lifecycle-hook adapters with agents that support them.
|
|
147
|
+
Claude Code: UserPromptSubmit (TOCP injection) + PreToolUse (shell guard).
|
|
148
|
+
Cursor: beforeShellExecution / beforeReadFile guards.
|
|
149
|
+
Codex has no lifecycle hooks (MCP + AGENTS.md remain the integration)."""
|
|
150
|
+
if agent_key == "codex":
|
|
151
|
+
return False, "Codex CLI has no lifecycle hooks — MCP + AGENTS.md stay the integration"
|
|
152
|
+
if agent_key not in ("claude_code", "cursor"):
|
|
153
|
+
return False, "hooks not applicable for this agent"
|
|
154
|
+
|
|
155
|
+
claude_cmd = cls._tokensafe_hook_command("claude_code_hook.py")
|
|
156
|
+
cursor_cmd = cls._tokensafe_hook_command("cursor_hook.py")
|
|
157
|
+
|
|
158
|
+
if agent_key == "claude_code":
|
|
159
|
+
info = AGENTS_REGISTRY["claude_code"]
|
|
160
|
+
config_file = info.get("agents_md_path", "").replace("CLAUDE.md", "settings.json")
|
|
161
|
+
config_file = os.path.join(HOME, ".claude", "settings.json")
|
|
162
|
+
os.makedirs(os.path.dirname(config_file), exist_ok=True)
|
|
163
|
+
data: Dict[str, Any] = {}
|
|
164
|
+
if os.path.exists(config_file):
|
|
165
|
+
try:
|
|
166
|
+
with open(config_file, "r", encoding="utf-8") as f:
|
|
167
|
+
data = json.load(f)
|
|
168
|
+
except Exception:
|
|
169
|
+
data = {}
|
|
170
|
+
hooks = data.get("hooks") if isinstance(data.get("hooks"), dict) else {}
|
|
171
|
+
blob = json.dumps(hooks)
|
|
172
|
+
if "claude_code_hook.py" in blob:
|
|
173
|
+
return True, "TokenSafe Claude Code hooks already registered"
|
|
174
|
+
prompt_entry = {"hooks": [{"type": "command", "command": claude_cmd, "timeout": 10}]}
|
|
175
|
+
bash_entry = {"matcher": "Bash", "hooks": [{"type": "command", "command": claude_cmd, "timeout": 10}]}
|
|
176
|
+
hooks.setdefault("UserPromptSubmit", []).append(prompt_entry)
|
|
177
|
+
hooks.setdefault("PreToolUse", []).append(bash_entry)
|
|
178
|
+
data["hooks"] = hooks
|
|
179
|
+
cls._write_file_safely(config_file, json.dumps(data, indent=2))
|
|
180
|
+
return True, "hooks registered (UserPromptSubmit + PreToolUse guard)"
|
|
181
|
+
|
|
182
|
+
# cursor
|
|
183
|
+
config_file = os.path.join(HOME, ".cursor", "hooks.json")
|
|
184
|
+
os.makedirs(os.path.dirname(config_file), exist_ok=True)
|
|
185
|
+
data = {}
|
|
186
|
+
if os.path.exists(config_file):
|
|
187
|
+
try:
|
|
188
|
+
with open(config_file, "r", encoding="utf-8") as f:
|
|
189
|
+
data = json.load(f)
|
|
190
|
+
except Exception:
|
|
191
|
+
data = {}
|
|
192
|
+
hooks = data.get("hooks") if isinstance(data.get("hooks"), dict) else {}
|
|
193
|
+
blob = json.dumps(hooks)
|
|
194
|
+
if "cursor_hook.py" in blob:
|
|
195
|
+
return True, "TokenSafe Cursor hooks already registered"
|
|
196
|
+
shell_entry = {"command": cursor_cmd, "timeout": 10}
|
|
197
|
+
hooks.setdefault("beforeShellExecution", []).append(dict(shell_entry))
|
|
198
|
+
hooks.setdefault("beforeReadFile", []).append(dict(shell_entry))
|
|
199
|
+
hooks.setdefault("beforeSubmitPrompt", []).append(dict(shell_entry))
|
|
200
|
+
data["hooks"] = hooks
|
|
201
|
+
cls._write_file_safely(config_file, json.dumps(data, indent=2))
|
|
202
|
+
return True, "guards registered (shell + junk-read + prompt pipeline)"
|
|
203
|
+
|
|
138
204
|
@classmethod
|
|
139
205
|
def install_mcp_config(cls, agent_key: str) -> Tuple[bool, str]:
|
|
140
206
|
"""Injects TokenSafe MCP config into target agent."""
|
|
@@ -489,6 +555,10 @@ class AgentInstaller:
|
|
|
489
555
|
for key, info in agents.items():
|
|
490
556
|
if info["installed"] or force:
|
|
491
557
|
ok, msg = cls.install_mcp_config(key)
|
|
558
|
+
if ok:
|
|
559
|
+
h_ok, h_msg = cls.install_hooks_config(key)
|
|
560
|
+
if h_ok:
|
|
561
|
+
msg = f"{msg}; {h_msg}"
|
|
492
562
|
results[key] = {"name": info["name"], "success": ok, "message": msg}
|
|
493
563
|
# Also configure project rules
|
|
494
564
|
proj_res = cls.install_project(os.getcwd())
|
|
@@ -536,6 +606,10 @@ class AgentInstaller:
|
|
|
536
606
|
if is_sel:
|
|
537
607
|
name = agents[key]["name"]
|
|
538
608
|
ok, msg = cls.install_mcp_config(key)
|
|
609
|
+
if ok:
|
|
610
|
+
h_ok, h_msg = cls.install_hooks_config(key)
|
|
611
|
+
if h_ok:
|
|
612
|
+
msg = f"{msg}; {h_msg}"
|
|
539
613
|
if ok:
|
|
540
614
|
print(f" \033[32m✔\033[0m \033[1m{name}\033[0m: {msg}")
|
|
541
615
|
installed_count += 1
|
|
@@ -643,6 +717,36 @@ class AgentInstaller:
|
|
|
643
717
|
|
|
644
718
|
return restarted
|
|
645
719
|
|
|
720
|
+
@staticmethod
|
|
721
|
+
def _find_npm(home: Optional[str] = None) -> Optional[str]:
|
|
722
|
+
"""Locates an npm executable even in a clean non-interactive environment.
|
|
723
|
+
|
|
724
|
+
The updater dialog runs via `do shell script` + login shell, where .zshrc
|
|
725
|
+
(and therefore nvm) is never sourced; PATH-only discovery made the npm
|
|
726
|
+
channel silently skip updates. Falls back to well-known locations."""
|
|
727
|
+
found = shutil.which("npm")
|
|
728
|
+
if found:
|
|
729
|
+
return found
|
|
730
|
+
base = home or HOME
|
|
731
|
+
candidates: List[str] = []
|
|
732
|
+
nvm_dir = os.path.join(base, ".nvm", "versions", "node")
|
|
733
|
+
try:
|
|
734
|
+
if os.path.isdir(nvm_dir):
|
|
735
|
+
# Newest installed node version wins.
|
|
736
|
+
for version_dir in sorted(os.listdir(nvm_dir), reverse=True):
|
|
737
|
+
candidates.append(os.path.join(nvm_dir, version_dir, "bin", "npm"))
|
|
738
|
+
except OSError:
|
|
739
|
+
pass
|
|
740
|
+
candidates += [
|
|
741
|
+
"/opt/homebrew/bin/npm",
|
|
742
|
+
"/usr/local/bin/npm",
|
|
743
|
+
"/usr/bin/npm",
|
|
744
|
+
]
|
|
745
|
+
for cand in candidates:
|
|
746
|
+
if os.path.isfile(cand) and os.access(cand, os.X_OK):
|
|
747
|
+
return cand
|
|
748
|
+
return None
|
|
749
|
+
|
|
646
750
|
@classmethod
|
|
647
751
|
def self_update(cls):
|
|
648
752
|
"""
|
|
@@ -668,29 +772,43 @@ class AgentInstaller:
|
|
|
668
772
|
print(f" {YELLOW}⚠{RESET} Git pull skipped: {e}")
|
|
669
773
|
|
|
670
774
|
# 2. Check npm global
|
|
671
|
-
|
|
775
|
+
# The updater dialog runs via `do shell script` + login shell, which skips
|
|
776
|
+
# .zshrc — nvm is NOT on PATH there, so PATH-only discovery silently
|
|
777
|
+
# downgraded the npm channel (the active one for many installs).
|
|
778
|
+
npm_bin = cls._find_npm()
|
|
779
|
+
if npm_bin:
|
|
672
780
|
try:
|
|
673
|
-
res = subprocess.run([
|
|
781
|
+
res = subprocess.run([npm_bin, "list", "-g", "--depth=0", "tokensafe"], capture_output=True, text=True, timeout=15)
|
|
674
782
|
if "tokensafe@" in res.stdout:
|
|
675
783
|
print(f" {CYAN}→{RESET} Updating global npm package (npm install -g tokensafe@latest)...")
|
|
676
|
-
up_res = subprocess.run([
|
|
784
|
+
up_res = subprocess.run([npm_bin, "install", "-g", "tokensafe@latest"], capture_output=True, text=True, timeout=120)
|
|
677
785
|
if up_res.returncode == 0:
|
|
678
786
|
print(f" {GREEN}✔{RESET} npm package upgraded successfully.")
|
|
679
|
-
|
|
680
|
-
|
|
787
|
+
else:
|
|
788
|
+
detail = (up_res.stderr or up_res.stdout or "").strip()[:200]
|
|
789
|
+
print(f" {YELLOW}⚠{RESET} npm upgrade failed: {detail}")
|
|
790
|
+
else:
|
|
791
|
+
print(f" {CYAN}ℹ{RESET} tokensafe not installed via npm — skipping npm channel.")
|
|
792
|
+
except Exception as e:
|
|
793
|
+
print(f" {YELLOW}⚠{RESET} npm update skipped: {e}")
|
|
794
|
+
else:
|
|
795
|
+
print(f" {YELLOW}⚠{RESET} npm not found — skipping npm channel.")
|
|
681
796
|
|
|
682
797
|
# 3. Check pip
|
|
683
798
|
pip_cmd = "pip3" if shutil.which("pip3") else ("pip" if shutil.which("pip") else None)
|
|
684
799
|
if pip_cmd:
|
|
685
800
|
try:
|
|
686
|
-
res = subprocess.run([pip_cmd, "list"], capture_output=True, text=True, timeout=
|
|
801
|
+
res = subprocess.run([pip_cmd, "list"], capture_output=True, text=True, timeout=15)
|
|
687
802
|
if "tokensafe" in res.stdout:
|
|
688
803
|
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=
|
|
804
|
+
up_res = subprocess.run([pip_cmd, "install", "--upgrade", "tokensafe"], capture_output=True, text=True, timeout=120)
|
|
690
805
|
if up_res.returncode == 0:
|
|
691
806
|
print(f" {GREEN}✔{RESET} Python package upgraded successfully.")
|
|
692
|
-
|
|
693
|
-
|
|
807
|
+
else:
|
|
808
|
+
detail = (up_res.stderr or up_res.stdout or "").strip()[:200]
|
|
809
|
+
print(f" {YELLOW}⚠{RESET} pip upgrade failed: {detail}")
|
|
810
|
+
except Exception as e:
|
|
811
|
+
print(f" {YELLOW}⚠{RESET} pip update skipped: {e}")
|
|
694
812
|
|
|
695
813
|
# 4. Re-synchronize all detected agents
|
|
696
814
|
print(f"\n {CYAN}→{RESET} Re-synchronizing AI Agent MCP configs & rules...")
|
|
@@ -699,6 +817,10 @@ class AgentInstaller:
|
|
|
699
817
|
for key, info in agents.items():
|
|
700
818
|
if info["installed"]:
|
|
701
819
|
ok, msg = cls.install_mcp_config(key)
|
|
820
|
+
if ok:
|
|
821
|
+
h_ok, h_msg = cls.install_hooks_config(key)
|
|
822
|
+
if h_ok:
|
|
823
|
+
msg = f"{msg}; {h_msg}"
|
|
702
824
|
if ok:
|
|
703
825
|
print(f" {GREEN}✔{RESET} {info['name']}: {msg}")
|
|
704
826
|
synced_count += 1
|
|
@@ -722,7 +844,8 @@ class AgentInstaller:
|
|
|
722
844
|
|
|
723
845
|
print(f"\n{BOLD}{GREEN}✅ Self-update complete!{RESET}")
|
|
724
846
|
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
|
|
847
|
+
print(f" Run {BOLD}tokensafe stats{RESET} to view token savings.")
|
|
848
|
+
print(f" {CYAN}ℹ{RESET} If your terminal still shows the old version, open a new window or run {BOLD}hash -r{RESET}.")
|
|
726
849
|
|
|
727
850
|
def main():
|
|
728
851
|
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.7.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/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
|
@@ -264,7 +264,7 @@ class TelemetrySync:
|
|
|
264
264
|
rollup_synced = bool(state.get("lifetime_rollup_synced", False))
|
|
265
265
|
headers = {
|
|
266
266
|
"Content-Type": "application/json",
|
|
267
|
-
"User-Agent": "TokenSafe-Sync/1.
|
|
267
|
+
"User-Agent": "TokenSafe-Sync/1.7.0"
|
|
268
268
|
}
|
|
269
269
|
if active_key:
|
|
270
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.7.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
|