tokensafe 2.0.0 → 2.1.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 +20 -18
- package/bin/tokensafe.js +1 -1
- package/hooks/pre_tool_use.py +11 -6
- package/package.json +4 -3
- package/plugin.json +1 -1
- package/server.json +3 -3
- package/skills/token-optimizer/SKILL.md +14 -7
- package/src/__init__.py +1 -1
- package/src/adapter_core.py +20 -3
- package/src/cli.py +22 -1
- package/src/command_sanitizer.py +264 -120
- package/src/dashboard.py +1 -1
- package/src/diff_slicer.py +18 -2
- package/src/installer.py +1 -1
- package/src/mcp_server.py +65 -3
- package/src/metrics.py +14 -1
- package/src/slicer.py +69 -3
- package/src/telemetry_sync.py +1 -1
- package/src/version_checker.py +38 -9
package/README.md
CHANGED
|
@@ -6,9 +6,9 @@
|
|
|
6
6
|
<!-- mcp-name: dev.tokensafe/tokensafe -->
|
|
7
7
|
|
|
8
8
|
<p align="center">
|
|
9
|
-
<b>
|
|
10
|
-
|
|
11
|
-
Built for <b>Cursor, Claude
|
|
9
|
+
<b>Local-First AI Coding Guardrails, Context Precision & Team ROI for Engineering Orgs</b><br>
|
|
10
|
+
Stop paying for AI hallucinations and secret leaks — cut context bloat by <b>up to [90%*](METRICS.md)</b> locally.<br>
|
|
11
|
+
Built for teams on <b>Cursor, Claude Code, Google Antigravity, Windsurf & Codex</b>.
|
|
12
12
|
</p>
|
|
13
13
|
|
|
14
14
|
<p align="center">
|
|
@@ -24,7 +24,7 @@
|
|
|
24
24
|
<p align="center">
|
|
25
25
|
<a href="#-1-click-universal-install">Install</a> •
|
|
26
26
|
<a href="#-universal-mcp-server-configuration">MCP Setup</a> •
|
|
27
|
-
<a href="#-
|
|
27
|
+
<a href="#-how-your-team-ships-cleaner-code-with-6090-less-bloat">How It Works</a> •
|
|
28
28
|
<a href="#-tokensafe-guard-proactive-agent-security--hygiene-shield">TokenSafe Guard</a> •
|
|
29
29
|
<a href="#-pricing--plans">Pricing</a> •
|
|
30
30
|
<a href="https://tokensafe.dev">Official Website & Docs</a>
|
|
@@ -135,14 +135,14 @@ Connect TokenSafe directly to **Claude Desktop** (`claude_desktop_config.json`)
|
|
|
135
135
|
|
|
136
136
|
---
|
|
137
137
|
|
|
138
|
-
##
|
|
138
|
+
## ⚡ How Your Team Ships Cleaner Code with 60%–90% Less Bloat
|
|
139
139
|
|
|
140
|
-
|
|
141
|
-
1. **
|
|
142
|
-
2. **
|
|
143
|
-
3. **
|
|
140
|
+
Giving coding agents raw access to entire repos creates three daily bottlenecks:
|
|
141
|
+
1. **Hallucinations in Large Files:** Reading 2,000-line modules just to tweak a 10-line helper causes models to lose track of imports and break adjacent code.
|
|
142
|
+
2. **Secret & Security Leaks:** Static text rules fade over multi-turn chats—agents hardcode secret fallbacks, skip TLS verification, or run `git add .` with `.env` files.
|
|
143
|
+
3. **Mid-Sprint Quota Walls & Blind Spend:** Verbose prompts, lockfile diffs, and unused MCP tool schemas exhaust 5-hour limits while leadership lacks per-seat ROI visibility.
|
|
144
144
|
|
|
145
|
-
### TokenSafe
|
|
145
|
+
### TokenSafe Fixes All Three Locally:
|
|
146
146
|
- **Graph-Guided AST Skeletonization:** Folds inactive function bodies into signatures, keeping target functions and 1-hop dependencies full while collapsing unrelated code (`-85% to -92%`).
|
|
147
147
|
- **Prompt Cache Prefix Normalizer:** Strips volatile timestamps and aligns system prompts to 64-token boundaries. Injects Anthropic ephemeral breakpoints (`cache_control: {"type": "ephemeral"}`) and DeepSeek chunking for 100% provider cache hits and 90% cost discounts.
|
|
148
148
|
- **Context Window Governor & Token Ceiling:** Enforces deterministic token budgets via 3-stage cascading autothrottling (AST skeletonization ➔ TOCP user message history compaction ➔ sliding state ledger) to prevent catastrophic context overflows.
|
|
@@ -395,14 +395,15 @@ Sums on the dashboard and landing page always show the split (`X metered · Y es
|
|
|
395
395
|
|
|
396
396
|
---
|
|
397
397
|
|
|
398
|
-
## 💎 Pricing & 7-Day
|
|
398
|
+
## 💎 Pricing & 7-Day Team Trial
|
|
399
399
|
|
|
400
400
|
| Tier | Price | Monthly Token Savings | Highlights |
|
|
401
401
|
|---|---|---|---|
|
|
402
|
-
| **
|
|
403
|
-
| **
|
|
404
|
-
| **
|
|
405
|
-
|
|
402
|
+
| **Developer Sandbox (Community)** | **$0** (Free Forever) | **500,000 tokens / mo** | 9-Language Local Regex Compactor, Local AST Slicer CLI, Local Secret Guard, SQLite & Terminal Dashboard |
|
|
403
|
+
| **Engineering Team** *(Recommended)* | **$29 / seat / mo** *(~$24 / seat / mo billed $290/yr)* | **Unlimited** | **7-Day Free Trial**, **Shared Team Cache (L3 Monorepo Pool)**, Org Guard & Git Leak Shield, Friday Per-Seat ROI Digest, Centralized Ed25519 Seat Control, Managed Cloud Distillation (Zero Keys), Self-Hosted Docker Proxy |
|
|
404
|
+
| **Enterprise / VPC** | **Custom** | **Unlimited** | On-Premise Nuitka C-compiled Docker Proxy (Private BYOK), Zero-Telemetry / Air-Gapped Mode, SAML SSO, Custom Compliance & SLA |
|
|
405
|
+
|
|
406
|
+
*Working solo? [Individual Solo plans](https://tokensafe.dev#pricing) are available from **$9 / mo** ($89 / yr).*
|
|
406
407
|
|
|
407
408
|
👉 **[Start your 7-Day Free Trial on our website](https://tokensafe.dev#pricing)**
|
|
408
409
|
|
|
@@ -604,9 +605,10 @@ TokenSafe is built on an **Open-Core** model designed to give every developer im
|
|
|
604
605
|
|
|
605
606
|
| Plan | Price | Monthly Token Savings | Capabilities |
|
|
606
607
|
| :--- | :---: | :---: | :--- |
|
|
607
|
-
| **
|
|
608
|
-
| **
|
|
609
|
-
| **
|
|
608
|
+
| **Developer Sandbox (Free)** | **$0** forever | **500,000 tokens / mo** | Multilingual Local Regex Compactor (9 languages), AST Slicer, Output Guard, Loop Guard, Local SQLite & HTML Dashboard |
|
|
609
|
+
| **Engineering Team** *(Recommended)* | **$29 / seat / mo** *(~$24 / seat / mo billed $290/yr)* | **Unlimited** | **Shared Team Cache (L3 Monorepo Pool)**, Org Guard & Git Leak Shield, Friday Per-Seat ROI Digest, Seat Quota & Revoke Console, Managed Cloud Distillation, Self-Hosted Docker Proxy |
|
|
610
|
+
| **Enterprise / VPC** | **Custom** | **Unlimited** | On-Premise Docker Proxy (Private BYOK), Zero-Telemetry / Air-Gapped Mode, SAML SSO, Custom SLA |
|
|
611
|
+
| **Solo Developer** | **$9 / mo** *($89/yr)* | **Unlimited** | Individual Unlimited Compression, Managed Cloud Distillation, Subagent Firewall, Cascading Governor |
|
|
610
612
|
|
|
611
613
|
> [!TIP]
|
|
612
614
|
> **500,000 free tokens / month** are included out of the box with zero registration. When your monthly community limit is reached, basic regex compaction continues safely, and you can unlock unlimited Solo optimization anytime at [tokensafe.dev](https://tokensafe.dev/#pricing) or activate via `tokensafe activate <key>`.
|
package/bin/tokensafe.js
CHANGED
|
@@ -36,7 +36,7 @@ const firstArg = args[0] || '';
|
|
|
36
36
|
|
|
37
37
|
if (firstArg === 'help' || firstArg === '--help' || firstArg === '-h') {
|
|
38
38
|
console.log(`
|
|
39
|
-
⚡ TokenSafe -
|
|
39
|
+
⚡ TokenSafe - Local-First AI Coding Guardrails & Context Optimizer
|
|
40
40
|
Website: https://tokensafe.dev
|
|
41
41
|
|
|
42
42
|
Usage:
|
package/hooks/pre_tool_use.py
CHANGED
|
@@ -251,14 +251,19 @@ def main():
|
|
|
251
251
|
print(json.dumps(response))
|
|
252
252
|
return
|
|
253
253
|
|
|
254
|
-
# Check AST Diff Slicer first
|
|
254
|
+
# Check AST Diff Slicer first (per-stage rewrite of git diff stages),
|
|
255
|
+
# then run the Command Sanitizer on the result so other stages
|
|
256
|
+
# (git log, pytest, rg, ...) in the same compound command still
|
|
257
|
+
# get their rules applied.
|
|
255
258
|
diff_cmd, diff_saved, diff_reason = DiffSlicer.optimize_git_diff_command(cmd)
|
|
256
259
|
if diff_cmd:
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
260
|
+
cmd = diff_cmd
|
|
261
|
+
new_cmd, san_saved, san_reason = CommandSanitizer.sanitize(cmd)
|
|
262
|
+
if new_cmd:
|
|
263
|
+
est_saved = san_saved + (diff_saved if diff_cmd else 0)
|
|
264
|
+
reason = (f"{diff_reason}; {san_reason}" if diff_cmd else san_reason)
|
|
265
|
+
elif diff_cmd:
|
|
266
|
+
new_cmd, est_saved, reason = diff_cmd, diff_saved, diff_reason
|
|
262
267
|
|
|
263
268
|
if new_cmd and est_saved > 0:
|
|
264
269
|
response["overwrite"] = {"CommandLine": new_cmd}
|
package/package.json
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tokensafe",
|
|
3
3
|
"mcpName": "dev.tokensafe/tokensafe",
|
|
4
|
-
"version": "2.
|
|
5
|
-
"description": "
|
|
4
|
+
"version": "2.1.0",
|
|
5
|
+
"description": "Local-first AI coding guardrails, context slicing, and team ROI telemetry for AI coding agents",
|
|
6
6
|
"main": "bin/tokensafe.js",
|
|
7
7
|
"bin": {
|
|
8
8
|
"tokensafe": "bin/tokensafe.js"
|
|
@@ -57,5 +57,6 @@
|
|
|
57
57
|
"bugs": {
|
|
58
58
|
"url": "https://github.com/NekoSin4eG/tokensafe/issues"
|
|
59
59
|
},
|
|
60
|
-
"homepage": "https://tokensafe.dev"
|
|
60
|
+
"homepage": "https://tokensafe.dev",
|
|
61
|
+
"packageManager": "yarn@1.22.22+sha512.a6b2f7906b721bba3d67d4aff083df04dad64c399707841b7acf00f6b133b7ac24255f2652fa22ae3534329dc6180534e98d17432037ff6fd140556e2bb3137e"
|
|
61
62
|
}
|
package/plugin.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "agy-token-optimizer",
|
|
3
3
|
"displayName": "TokenSafe",
|
|
4
|
-
"version": "2.
|
|
4
|
+
"version": "2.1.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": "2.
|
|
6
|
+
"version": "2.1.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": "2.
|
|
33
|
+
"version": "2.1.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": "2.
|
|
49
|
+
"version": "2.1.0",
|
|
50
50
|
"runtimeHint": "uvx",
|
|
51
51
|
"transport": {
|
|
52
52
|
"type": "stdio"
|
|
@@ -53,13 +53,13 @@ All tools are exposed via Model Context Protocol (stdio JSON-RPC 2.0).
|
|
|
53
53
|
| `tokensafe:list_dir` | Token-efficient directory tree without lockfiles, timestamps, or ignored folders (node_modules, .git, dist, .env). Replaces `ls -la`. | **-90%** vs verbose `ls` |
|
|
54
54
|
| `tokensafe:get_architecture_graph` | Computes dependency topology, hub centrality, and identifies top God Nodes for `project_path`. | **~200 tokens** (replaces 50k crawl) |
|
|
55
55
|
| `tokensafe:get_api_surface` | Generates a compact markdown map of all exported types, interfaces, and classes. | **~500 tokens** for entire project |
|
|
56
|
-
| `tokensafe:sanitize_command` |
|
|
56
|
+
| `tokensafe:sanitize_command` | Per-stage command rewrites: lockfile diffs, unbounded `git log`/`git show`/`git blame`/`rg`, docker/kubectl log caps, quiet npm/pip installs, bounded `cat`/`curl` output. Compound commands (`a && b ; c`) are optimized per stage without breaking operators. | 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
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 |
|
|
60
60
|
| `tokensafe:context_budget` | Context Budget HUD: estimated window usage (`model`/`window_tokens`/`session_id`) with tools/history/prompts breakdown and 50/80/95% thresholds. Call before deciding to compact. | Floor estimate, always labeled estimated |
|
|
61
|
-
| `tokensafe:guard_inspect` | Pre-flight security & hygiene audit
|
|
62
|
-
| `tokensafe:get_token_savings_metrics` | Returns cumulative analytics: tokens saved, context ratio, USD value, and optimization source breakdown. | Persistent SQLite analytics |
|
|
61
|
+
| `tokensafe:guard_inspect` | Pre-flight security & hygiene audit: denies literal secrets/destructive commands in shell lines (secrets, TLS, SQLi, raw grep); advisory for never-terminating streams (`tail -f`, `watch`, `docker attach`) and TLS bypasses. | **Zero-Risk** pre-flight gate |
|
|
62
|
+
| `tokensafe:get_token_savings_metrics` | Returns cumulative analytics: tokens saved (measured/estimated split), context ratio, ≈USD value (derived), and optimization source breakdown. | Persistent SQLite analytics |
|
|
63
63
|
|
|
64
64
|
---
|
|
65
65
|
|
|
@@ -160,6 +160,9 @@ TokenSafe Guard automatically intercepts dangerous operations in `PreToolUse`:
|
|
|
160
160
|
| **DESTRUCTIVE_RM** | `rm -rf /`, `rm -rf ~`, `rm -rf *` | **Blocked** (`decision: deny`), prevents catastrophic deletion |
|
|
161
161
|
| **DATA_EXFILTRATION** | Piping `.env` or private keys to `curl`/`wget` | **Blocked** (`decision: deny`), prevents secret leakage |
|
|
162
162
|
| **PACKAGE_TYPOSQUAT** | Installing known typosquatted packages | **Warning** injected into turn context |
|
|
163
|
+
| **INFINITE_STREAM** (adapters) | Never-terminating commands: `tail -f`, `watch`, `docker attach`, `docker/kubectl logs -f` | **Asked** (`decision: ask`) — intentional runs proceed via confirmation |
|
|
164
|
+
|
|
165
|
+
Adapter-level checks (Claude Code / Cursor / ZCode hooks) classify command-level TLS bypass (`curl -k`, `git -c http.sslVerify=false`, `GIT_SSL_NO_VERIFY=1`) and infinite streams as `ask` — TokenSafe Guard's code-level checks above remain `deny`.
|
|
163
166
|
|
|
164
167
|
---
|
|
165
168
|
|
|
@@ -185,10 +188,12 @@ For long-running autonomous sessions, TokenSafe actively manages context bloat:
|
|
|
185
188
|
Run standalone in the terminal or invoke via agent:
|
|
186
189
|
|
|
187
190
|
```bash
|
|
191
|
+
tokensafe --version # Print version and exit (no metrics side effects)
|
|
192
|
+
|
|
188
193
|
# Telemetry & Economics
|
|
189
194
|
tokensafe stats # View terminal report with tokens saved & USD ROI
|
|
190
195
|
tokensafe html # Launch interactive Apple-style HTML dashboard
|
|
191
|
-
tokensafe benchmark # Run zero-loss SWE-bench
|
|
196
|
+
tokensafe benchmark # Run the zero-context-loss benchmark suite (simulated SWE-bench harness; see BENCHMARK_REPORT.md)
|
|
192
197
|
|
|
193
198
|
# Code Intelligence & Architecture
|
|
194
199
|
tokensafe graph [path] # Inspect God Nodes and centrality ranking
|
|
@@ -211,8 +216,10 @@ tokensafe test "<prompt>" # Test TOCP S-expression prompt compaction
|
|
|
211
216
|
|
|
212
217
|
---
|
|
213
218
|
|
|
214
|
-
## Proof-of-Savings Turn Footer
|
|
219
|
+
## Proof-of-Savings Turn Footer (always in English)
|
|
220
|
+
|
|
221
|
+
At the end of any response where tools were executed, files were inspected, commands were sanitized, or prompts were compacted, append a compact 1-line footer in English:
|
|
222
|
+
`⚡ **TokenSafe Turn Savings**: +<tokens> tokens saved on this turn (<breakdown>) | Cumulative Total: <total> tokens (≈$<usd> approx)`
|
|
215
223
|
|
|
216
|
-
|
|
217
|
-
`⚡ **TokenSafe Turn Savings**: +<tokens> tokens saved on this turn (<breakdown>) | Cumulative Total: <total> tokens ($<usd>)`
|
|
224
|
+
The USD figure is **derived** (tokens × $1.5/M blended rate) — an approximation for planning, never a bill. Cumulative analytics distinguish `measured` (metered I/O delta) from `estimated` (counterfactual baseline) savings — see METRICS.md.
|
|
218
225
|
|
package/src/__init__.py
CHANGED
package/src/adapter_core.py
CHANGED
|
@@ -2,9 +2,11 @@
|
|
|
2
2
|
Shared core for cross-agent lifecycle-hook adapters (Claude Code, Cursor, ZCode).
|
|
3
3
|
|
|
4
4
|
Design rules (see METRICS.md):
|
|
5
|
-
- Savings are only recorded for REAL reductions
|
|
6
|
-
|
|
7
|
-
|
|
5
|
+
- Savings are only recorded for REAL reductions. Blocked reads/commands never
|
|
6
|
+
reach the model, but their "would-have-been" mass is a heuristic guess, so
|
|
7
|
+
PROMPT injections and GUARD_*/COMMAND_FILTER/LOOP_GUARD events are labeled
|
|
8
|
+
estimated; events whose original/optimized tokens come from real bytes or
|
|
9
|
+
metered I/O stay measured.
|
|
8
10
|
- Adapters ALWAYS fail open: an adapter crash must never block the host agent.
|
|
9
11
|
(Cursor additionally blocks on invalid JSON, so adapters return valid
|
|
10
12
|
allow-JSON from the exception handler.)
|
|
@@ -41,6 +43,17 @@ _TLS_BYPASS_PATTERNS = [
|
|
|
41
43
|
r"curl\s+.*--insecure",
|
|
42
44
|
r"NODE_TLS_REJECT_UNAUTHORIZED\s*=\s*0",
|
|
43
45
|
r"wget\s+.*--no-check-certificate",
|
|
46
|
+
r"git\s+-c\s+[a-z.]*sslVerify\s*=\s*false",
|
|
47
|
+
r"GIT_SSL_NO_VERIFY\s*=\s*(?:true|1)",
|
|
48
|
+
]
|
|
49
|
+
# Commands that never terminate on their own — an agent burning a turn on them
|
|
50
|
+
# stalls until timeout. Intentional runs can still proceed via the "ask" path.
|
|
51
|
+
_INFINITE_PATTERNS = [
|
|
52
|
+
r"\btail\b[^|;&]*\s-f\b",
|
|
53
|
+
r"\bwatch\s+",
|
|
54
|
+
r"\bdocker\s+logs\b[^|;&]*\s(?:-f\b|--follow)",
|
|
55
|
+
r"\bkubectl\s+logs\b[^|;&]*\s-f\b",
|
|
56
|
+
r"\bdocker\s+attach\b",
|
|
44
57
|
]
|
|
45
58
|
|
|
46
59
|
# Lockfiles/junk that must never be dumped into an agent context.
|
|
@@ -132,6 +145,10 @@ def guard_command(command: str, agent: str, session_id: str = "") -> Dict[str, A
|
|
|
132
145
|
if re.search(pat, text):
|
|
133
146
|
blocked("TLS_VERIFY_BYPASS", "Certificate verification disabled — confirm this is intentional", decision="ask")
|
|
134
147
|
return result
|
|
148
|
+
for pat in _INFINITE_PATTERNS:
|
|
149
|
+
if re.search(pat, text):
|
|
150
|
+
blocked("INFINITE", "Command never terminates on its own (follow/streaming) — run it in the background or confirm intent", decision="ask")
|
|
151
|
+
return result
|
|
135
152
|
return result
|
|
136
153
|
|
|
137
154
|
|
package/src/cli.py
CHANGED
|
@@ -458,8 +458,29 @@ def main():
|
|
|
458
458
|
print("Reset cancelled.")
|
|
459
459
|
|
|
460
460
|
else:
|
|
461
|
+
if command in ("--help", "-h", "help"):
|
|
462
|
+
print("TokenSafe CLI — usage: tokensafe <command> [args]\n")
|
|
463
|
+
print("Commands:")
|
|
464
|
+
print(" stats / markdown / html Savings analytics (terminal / .md report / dashboard)")
|
|
465
|
+
print(" benchmark Zero-context-loss benchmark suite (simulated SWE-bench harness)")
|
|
466
|
+
print(" graph / map / skeleton Architecture graph / API surface / AST skeleton of a file")
|
|
467
|
+
print(" test <prompt> Preview TOCP S-expression prompt compaction")
|
|
468
|
+
print(" digest [--send] [--email=...] Compile (and optionally dispatch) the weekly team digest")
|
|
469
|
+
print(" guard <command> Pre-flight safety check for a shell command")
|
|
470
|
+
print(" doctor Audit MCP tool overhead and token tax")
|
|
471
|
+
print(" prune [--days N | --max N] Compact metrics database (roll old events)")
|
|
472
|
+
print(" vacuum Reclaim SQLite disk space")
|
|
473
|
+
print(" reset Reset all local token metrics")
|
|
474
|
+
print(" install | setup [--all] Configure detected agent environments")
|
|
475
|
+
print(" update | upgrade Self-update npm/PyPI package and re-sync agents")
|
|
476
|
+
print(" check-update Check for a newer published version")
|
|
477
|
+
print(" activate / license License activation and status")
|
|
478
|
+
print(" sync Sync telemetry with the cloud backend")
|
|
479
|
+
print(" providers / proxy / mcp Providers info / proxy server / MCP stdio server")
|
|
480
|
+
print(" --version Print version and exit")
|
|
481
|
+
sys.exit(0)
|
|
461
482
|
print(f"Unknown command: {command}")
|
|
462
|
-
print("Available commands: stats, sync, html, test, doctor, providers, mcp, benchmark, proxy, graph, map, vacuum, prune, digest, activate, license, markdown, setup, reset")
|
|
483
|
+
print("Available commands: stats, sync, html, test, doctor, providers, mcp, benchmark, proxy, graph, map, skeleton, guard, vacuum, prune, digest, activate, license, markdown, install, setup, update, check-update, reset. Run 'tokensafe help' for details.")
|
|
463
484
|
sys.exit(1)
|
|
464
485
|
|
|
465
486
|
if __name__ == "__main__":
|
package/src/command_sanitizer.py
CHANGED
|
@@ -2,6 +2,11 @@
|
|
|
2
2
|
Command Sanitizer: Intercepts and rewrites shell commands in PreToolUse
|
|
3
3
|
to prevent context window poisoning from lockfile diffs, unconstrained logs,
|
|
4
4
|
and verbose test output.
|
|
5
|
+
|
|
6
|
+
Every rule operates per-stage: compound commands (a && b ; c | d) are split
|
|
7
|
+
quote-aware, each stage is optimized independently, and the result is rejoined
|
|
8
|
+
so rewrites never leak pathspecs into an unrelated stage (e.g. lockfile
|
|
9
|
+
excludes landing on `npm test` after `git diff && npm test`).
|
|
5
10
|
"""
|
|
6
11
|
|
|
7
12
|
import re
|
|
@@ -10,18 +15,57 @@ from typing import Tuple, Dict, Any, List, Optional
|
|
|
10
15
|
class CommandSanitizer:
|
|
11
16
|
"""Optimizes terminal command lines to eliminate token waste."""
|
|
12
17
|
|
|
18
|
+
# Lockfiles and binary patterns that should never be dumped in git diffs or searches
|
|
19
|
+
LOCKFILE_EXCLUDES = [
|
|
20
|
+
"':!package-lock.json'",
|
|
21
|
+
"':!pnpm-lock.yaml'",
|
|
22
|
+
"':!yarn.lock'",
|
|
23
|
+
"':!bun.lock'",
|
|
24
|
+
"':!bun.lockb'",
|
|
25
|
+
"':!Cargo.lock'",
|
|
26
|
+
"':!go.sum'",
|
|
27
|
+
"':!composer.lock'",
|
|
28
|
+
"':!*.lock'",
|
|
29
|
+
"':!*.min.js'",
|
|
30
|
+
"':!*.min.css'",
|
|
31
|
+
"':!*.bundle.js'",
|
|
32
|
+
"':!*.map'",
|
|
33
|
+
]
|
|
34
|
+
|
|
35
|
+
# Files whose `cat` dumps thousands of near-useless tokens into context
|
|
36
|
+
_CAT_JUNK_RE = re.compile(
|
|
37
|
+
r"(^|/)(package-lock\.json|pnpm-lock\.yaml|yarn\.lock|bun\.lock|bun\.lockb"
|
|
38
|
+
r"|Cargo\.lock|go\.sum|composer\.lock|poetry\.lock|Gemfile\.lock"
|
|
39
|
+
r"|.*\.min\.js|.*\.min\.css|.*\.bundle\.js|.*\.map)$"
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
# Output limiters that make an extra `| head` at the end redundant
|
|
43
|
+
_LIMITER_RE = re.compile(r"\b(head|tail|less|wc|jq)\b")
|
|
44
|
+
|
|
45
|
+
# (unit, limit) specs for end-of-command output caps
|
|
46
|
+
_CAP_LINES_30 = ("n", 30)
|
|
47
|
+
_CAP_LINES_200 = ("n", 200)
|
|
48
|
+
_CAP_BYTES_4K = ("c", 4096)
|
|
49
|
+
|
|
13
50
|
@staticmethod
|
|
14
|
-
def
|
|
51
|
+
def split_stages(cmd: str) -> List[Tuple[str, str]]:
|
|
15
52
|
"""
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
53
|
+
Quote-aware split of a shell command into (operator, stage) pairs.
|
|
54
|
+
Operators: '' (first stage), '|', '||', '&&', ';'. Stages are stripped;
|
|
55
|
+
rejoining with join_stages() yields an equivalent command line.
|
|
19
56
|
"""
|
|
20
|
-
|
|
57
|
+
pairs: List[Tuple[str, str]] = []
|
|
21
58
|
buf: List[str] = []
|
|
22
59
|
quote = ""
|
|
60
|
+
pending_op = "" # operator preceding the stage being collected
|
|
23
61
|
i = 0
|
|
24
62
|
n = len(cmd)
|
|
63
|
+
|
|
64
|
+
def flush():
|
|
65
|
+
stage = "".join(buf).strip()
|
|
66
|
+
buf.clear()
|
|
67
|
+
pairs.append((pending_op, stage))
|
|
68
|
+
|
|
25
69
|
while i < n:
|
|
26
70
|
ch = cmd[i]
|
|
27
71
|
if quote:
|
|
@@ -36,140 +80,240 @@ class CommandSanitizer:
|
|
|
36
80
|
elif ch in ("'", '"', "`"):
|
|
37
81
|
quote = ch
|
|
38
82
|
buf.append(ch)
|
|
83
|
+
elif ch == "&" and i + 1 < n and cmd[i + 1] == "&":
|
|
84
|
+
flush()
|
|
85
|
+
pending_op = "&&"
|
|
86
|
+
i += 2
|
|
87
|
+
continue
|
|
88
|
+
elif ch == "|" and i + 1 < n and cmd[i + 1] == "|":
|
|
89
|
+
flush()
|
|
90
|
+
pending_op = "||"
|
|
91
|
+
i += 2
|
|
92
|
+
continue
|
|
39
93
|
elif ch == "|":
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
buf = []
|
|
94
|
+
flush()
|
|
95
|
+
pending_op = "|"
|
|
96
|
+
elif ch == ";":
|
|
97
|
+
flush()
|
|
98
|
+
pending_op = ";"
|
|
46
99
|
else:
|
|
47
100
|
buf.append(ch)
|
|
48
101
|
i += 1
|
|
49
|
-
|
|
102
|
+
flush()
|
|
103
|
+
# Drop empty stages but keep at least one slot so rejoin stays valid
|
|
104
|
+
cleaned = [(op, s) for op, s in pairs if s]
|
|
105
|
+
if not cleaned:
|
|
106
|
+
cleaned = [("", "")]
|
|
107
|
+
return cleaned
|
|
108
|
+
|
|
109
|
+
@staticmethod
|
|
110
|
+
def join_stages(pairs: List[Tuple[str, str]]) -> str:
|
|
111
|
+
"""Rejoins (operator, stage) pairs from split_stages into a command line."""
|
|
112
|
+
out = ""
|
|
113
|
+
for op, stage in pairs:
|
|
114
|
+
if not out:
|
|
115
|
+
out = stage
|
|
116
|
+
elif op == "|":
|
|
117
|
+
out += f" | {stage}"
|
|
118
|
+
else:
|
|
119
|
+
out += f" {op} {stage}"
|
|
120
|
+
return out
|
|
121
|
+
|
|
122
|
+
@staticmethod
|
|
123
|
+
def _split_pipeline_stages(cmd: str) -> List[str]:
|
|
124
|
+
"""
|
|
125
|
+
Splits a shell command on single '|' pipe operators while respecting
|
|
126
|
+
quoting ('...', "...", `...`) and '||' logical OR, so regex patterns like
|
|
127
|
+
grep "foo|bar" are never torn apart mid-string.
|
|
128
|
+
"""
|
|
129
|
+
pairs = CommandSanitizer.split_stages(cmd)
|
|
130
|
+
# Legacy contract: only pipe boundaries split; '&&'/';'/'||' stay inside stages.
|
|
131
|
+
stages: List[str] = []
|
|
132
|
+
pipe_open = False
|
|
133
|
+
for op, stage in pairs:
|
|
134
|
+
if op in ("", "|"):
|
|
135
|
+
if pipe_open and stages:
|
|
136
|
+
stages[-1] = f"{stages[-1]} | {stage}"
|
|
137
|
+
else:
|
|
138
|
+
stages.append(stage)
|
|
139
|
+
pipe_open = op == "|"
|
|
140
|
+
else:
|
|
141
|
+
# Non-pipe operator: glue operator + stage back into current stage
|
|
142
|
+
if stages:
|
|
143
|
+
stages[-1] = f"{stages[-1]} {op} {stage}"
|
|
144
|
+
else:
|
|
145
|
+
stages.append(stage)
|
|
50
146
|
return [s for s in (st.strip() for st in stages) if s]
|
|
51
147
|
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
"
|
|
55
|
-
"
|
|
56
|
-
"':!yarn.lock'",
|
|
57
|
-
"':!bun.lock'",
|
|
58
|
-
"':!bun.lockb'",
|
|
59
|
-
"':!Cargo.lock'",
|
|
60
|
-
"':!go.sum'",
|
|
61
|
-
"':!composer.lock'",
|
|
62
|
-
"':!*.lock'",
|
|
63
|
-
"':!*.min.js'",
|
|
64
|
-
"':!*.min.css'",
|
|
65
|
-
"':!*.bundle.js'",
|
|
66
|
-
"':!*.map'",
|
|
67
|
-
]
|
|
148
|
+
@staticmethod
|
|
149
|
+
def _has_redirect(stage: str) -> bool:
|
|
150
|
+
"""True if the stage redirects stdout somewhere (> , >>, 2>, &>)."""
|
|
151
|
+
return bool(re.search(r"(^|\s)[0-9&]*>{1,2}", stage))
|
|
68
152
|
|
|
69
153
|
@classmethod
|
|
70
|
-
def
|
|
154
|
+
def _optimize_stage(cls, stage: str) -> Optional[Tuple[str, int, str, Optional[Tuple[str, int]]]]:
|
|
71
155
|
"""
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
156
|
+
Applies one rewrite rule to a single stage.
|
|
157
|
+
Returns (new_stage, est_saved, reason, cap_spec) or None.
|
|
158
|
+
cap_spec = (unit, limit) marks rules whose unbounded output must be
|
|
159
|
+
capped; the cap is appended to the END of the whole command (never
|
|
160
|
+
mid-compound), so `||` / `&&` exit-status semantics are untouched.
|
|
161
|
+
new_stage may equal stage for cap-only rules (git show, blame, curl).
|
|
75
162
|
"""
|
|
76
|
-
if not command or not command.strip():
|
|
77
|
-
return None, 0, ""
|
|
78
|
-
|
|
79
|
-
cmd = command.strip()
|
|
80
|
-
has_compound_operators = bool(re.search(r"(&&|\|\||;)", cmd))
|
|
81
163
|
|
|
82
|
-
#
|
|
83
|
-
if re.search(r"\bgit\s+diff\b",
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
tokens = cmd.split()[2:] # args after git diff
|
|
164
|
+
# git diff: exclude lockfiles/bundles when diffing unscoped repository
|
|
165
|
+
if re.search(r"\bgit\s+diff\b", stage):
|
|
166
|
+
if ":!package-lock" not in stage and ":!*.lock" not in stage and ":!" not in stage:
|
|
167
|
+
tokens = stage.split()[2:] # args after git diff
|
|
87
168
|
has_path = any(not t.startswith('-') and not re.match(r'^(HEAD(~[0-9]+)?|main|master|[0-9a-f]{7,40})$', t) for t in tokens)
|
|
88
169
|
if not has_path:
|
|
89
170
|
excludes_str = " ".join(cls.LOCKFILE_EXCLUDES)
|
|
90
|
-
if " -- " in
|
|
91
|
-
|
|
171
|
+
if " -- " in stage:
|
|
172
|
+
new_stage = f"{stage} {excludes_str}"
|
|
92
173
|
else:
|
|
93
|
-
|
|
174
|
+
new_stage = f"{stage} -- {excludes_str}"
|
|
175
|
+
return new_stage, 3500, "Excluded lockfiles/bundles from git diff", None
|
|
94
176
|
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
# 2. git log optimization (Cap unbounded commit history)
|
|
99
|
-
if re.search(r"\bgit\s+log\b", cmd):
|
|
100
|
-
# Check if already limited by -n, -[0-9], or --max-count
|
|
101
|
-
has_limit = re.search(r"(\s-[0-9]+|\s-n\s*\d+|\s--max-count[=\s]\d+)", cmd)
|
|
177
|
+
# git log: cap unbounded commit history
|
|
178
|
+
if re.search(r"\bgit\s+log\b", stage):
|
|
179
|
+
has_limit = re.search(r"(\s-[0-9]+|\s-n\s*\d+|\s--max-count[=\s]\d+)", stage)
|
|
102
180
|
if not has_limit:
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
new_cmd = re.sub(r"\bgit\s+log\b", "git log -n 10 --oneline", cmd, count=1)
|
|
181
|
+
if "--oneline" not in stage:
|
|
182
|
+
new_stage = re.sub(r"\bgit\s+log\b", "git log -n 10 --oneline", stage, count=1)
|
|
106
183
|
else:
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
return new_cmd, est_saved, "Capped unbounded git log to 10 entries"
|
|
184
|
+
new_stage = re.sub(r"\bgit\s+log\b", "git log -n 10", stage, count=1)
|
|
185
|
+
return new_stage, 1200, "Capped unbounded git log to 10 entries", None
|
|
110
186
|
|
|
111
|
-
#
|
|
112
|
-
if re.search(r"\bpytest\b",
|
|
113
|
-
has_tb = "--tb=" in
|
|
187
|
+
# pytest: compact quiet traceback
|
|
188
|
+
if re.search(r"\bpytest\b", stage):
|
|
189
|
+
has_tb = "--tb=" in stage or "-q" in stage
|
|
114
190
|
if not has_tb:
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
# 5. git grep search (Exclude lockfiles & directories via pathspecs)
|
|
127
|
-
if re.search(r"\bgit\b.*?\bgrep\b", cmd):
|
|
128
|
-
if ":!*.lock" not in cmd and ":!bun.lock" not in cmd:
|
|
191
|
+
return f"{stage} -q --tb=short", 800, "Applied short traceback to pytest", None
|
|
192
|
+
|
|
193
|
+
# find: prune unbounded recursion
|
|
194
|
+
if re.search(r"\bfind\s+(\.|\/|\w+)\s*$", stage) or re.search(r"\bfind\s+\.\s+-name\b", stage):
|
|
195
|
+
if "node_modules" not in stage and ".git" not in stage:
|
|
196
|
+
new_stage = f"{stage} -not -path '*/.*' -not -path '*/node_modules/*' -not -path '*/venv/*'"
|
|
197
|
+
return new_stage, 1500, "Pruned .git, node_modules, and venv from find", None
|
|
198
|
+
|
|
199
|
+
# git grep: exclude lockfiles & generated dirs via pathspecs
|
|
200
|
+
if re.search(r"\bgit\b.*?\bgrep\b", stage):
|
|
201
|
+
if ":!*.lock" not in stage and ":!bun.lock" not in stage:
|
|
129
202
|
git_excludes = "':!*.lock' ':!bun.lock' ':!bun.lockb' ':!package-lock.json' ':!dist' ':!build' ':!node_modules'"
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
stages[i] = f"{left} || {right.strip()}"
|
|
141
|
-
elif " -- " in stage:
|
|
142
|
-
stages[i] = f"{stage} {git_excludes}"
|
|
143
|
-
else:
|
|
144
|
-
stages[i] = f"{stage} -- . {git_excludes}"
|
|
145
|
-
new_cmd = " | ".join(stages)
|
|
146
|
-
has_limiter = any(re.search(r'\b(head|tail|less)\b', s) for s in stages)
|
|
147
|
-
if not has_limiter:
|
|
148
|
-
new_cmd = f"{new_cmd} | head -n 30"
|
|
149
|
-
est_saved = 3500
|
|
150
|
-
return new_cmd, est_saved, "Excluded lockfiles from git grep and capped output"
|
|
151
|
-
|
|
152
|
-
# 6. grep / ripgrep unbounded search (only when recursive or scanning directory)
|
|
153
|
-
if re.search(r"\b(grep|egrep)\b", cmd) and not re.search(r"\bgit\b.*?\bgrep\b", cmd):
|
|
154
|
-
is_recursive = bool(re.search(r"\b(grep|egrep)\b.*?\s-[a-zA-Z]*[rR]", cmd))
|
|
155
|
-
if is_recursive and "--exclude-dir" not in cmd and "node_modules" not in cmd:
|
|
203
|
+
if " -- " in stage:
|
|
204
|
+
new_stage = f"{stage} {git_excludes}"
|
|
205
|
+
else:
|
|
206
|
+
new_stage = f"{stage} -- . {git_excludes}"
|
|
207
|
+
return new_stage, 3500, "Excluded lockfiles from git grep and capped output", cls._CAP_LINES_30
|
|
208
|
+
|
|
209
|
+
# grep / egrep recursive search: exclude junk dirs and cap output
|
|
210
|
+
if re.search(r"\b(grep|egrep)\b", stage) and not re.search(r"\bgit\b.*?\bgrep\b", stage):
|
|
211
|
+
is_recursive = bool(re.search(r"\b(grep|egrep)\b.*?\s-[a-zA-Z]*[rR]", stage))
|
|
212
|
+
if is_recursive and "--exclude-dir" not in stage and "node_modules" not in stage:
|
|
156
213
|
excludes = "--exclude='*.lock' --exclude='*.lockb' --exclude-dir={dist,build,node_modules,.git,coverage,__pycache__,.next,data}"
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
if
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
214
|
+
return f"{stage} {excludes}", 2500, "Sanitized grep directories and capped output to 30 matches", cls._CAP_LINES_30
|
|
215
|
+
|
|
216
|
+
# ripgrep: cap per-command output; add ignore excludes only for --no-ignore runs
|
|
217
|
+
if re.search(r"(^|\s|\()rg\b", stage) and "-- " not in stage:
|
|
218
|
+
if "-m " not in stage and "--max-count" not in stage and "-g " not in stage:
|
|
219
|
+
new_stage = stage
|
|
220
|
+
if "--no-ignore" in stage:
|
|
221
|
+
new_stage += " -g '!node_modules' -g '!.git' -g '!dist' -g '!build'"
|
|
222
|
+
return new_stage, 2500, "Capped rg output to 30 matches and excluded junk dirs", cls._CAP_LINES_30
|
|
223
|
+
|
|
224
|
+
# git show: full patch dumps are capped
|
|
225
|
+
if re.search(r"\bgit\s+show\b", stage):
|
|
226
|
+
if not re.search(r"--stat|--name-only|--name-status|\s-s\b|--oneline", stage):
|
|
227
|
+
return stage, 1500, "Capped git show patch output", cls._CAP_LINES_200
|
|
228
|
+
|
|
229
|
+
# git blame: one output line per file line — huge on big files unless -L limited
|
|
230
|
+
if re.search(r"\bgit\s+blame\b", stage):
|
|
231
|
+
if "-L" not in stage:
|
|
232
|
+
return stage, 1500, "Capped git blame output", cls._CAP_LINES_200
|
|
233
|
+
|
|
234
|
+
# docker logs: bound container log dumps
|
|
235
|
+
if re.search(r"\bdocker\s+(container\s+)?logs\b", stage):
|
|
236
|
+
if "--tail" not in stage and not re.search(r"\s-n\s*\d+", stage):
|
|
237
|
+
return f"{stage} --tail 100", 2000, "Capped docker logs to last 100 lines", None
|
|
238
|
+
|
|
239
|
+
# kubectl logs: bound pod log dumps
|
|
240
|
+
if re.search(r"\bkubectl\s+logs\b", stage):
|
|
241
|
+
if "--tail" not in stage:
|
|
242
|
+
return f"{stage} --tail=100", 2000, "Capped kubectl logs to last 100 lines", None
|
|
243
|
+
|
|
244
|
+
# npm installs: suppress progress bars, funding and audit noise
|
|
245
|
+
if re.search(r"\bnpm\s+(install|i|ci|add)\b", stage):
|
|
246
|
+
if "--no-audit" not in stage:
|
|
247
|
+
return f"{stage} --no-progress --no-fund --no-audit", 600, "Silenced npm install progress/audit output", None
|
|
248
|
+
|
|
249
|
+
# pip installs: quiet mode keeps dependency walls out of context
|
|
250
|
+
if re.search(r"\bpip3?\s+install\b", stage):
|
|
251
|
+
if not re.search(r"\s-q\b|--quiet", stage):
|
|
252
|
+
return f"{stage} -q", 400, "Applied quiet mode to pip install", None
|
|
253
|
+
|
|
254
|
+
# cat on lockfiles/minified bundles: switch to a bounded head window
|
|
255
|
+
if re.match(r"\bcat\s", stage):
|
|
256
|
+
if not cls._has_redirect(stage):
|
|
257
|
+
parts = stage.split()
|
|
258
|
+
paths = parts[1:]
|
|
259
|
+
if paths and all(not p.startswith("-") for p in paths):
|
|
260
|
+
if any(cls._CAT_JUNK_RE.search(p) for p in paths):
|
|
261
|
+
return f"head -n 120 {' '.join(paths)}", 3000, "Replaced cat of lockfile/bundle with bounded head", None
|
|
262
|
+
|
|
263
|
+
# curl printing to stdout (JSON/HTML dumps land in context): bounded byte cap
|
|
264
|
+
if re.search(r"\bcurl\b", stage):
|
|
265
|
+
if not re.search(r"-o\s|-O\b|--output|-F\b|--form|-T\b|--upload-file|-I\b|--head", stage):
|
|
266
|
+
return stage, 3000, "Capped curl stdout to 4096 bytes", cls._CAP_BYTES_4K
|
|
267
|
+
|
|
268
|
+
# ls: replace verbose permissions/timestamps with compact single-column format
|
|
269
|
+
if re.search(r"\bls\b", stage):
|
|
270
|
+
if re.search(r"\bls\s+-[a-zA-Z]*(l|a)[a-zA-Z]*\b", stage):
|
|
271
|
+
new_stage = re.sub(r"\bls\s+-[a-zA-Z]+\b", "ls -1 -p", stage)
|
|
272
|
+
return new_stage, 380, "Replaced verbose ls flags with compact, secret-safe format (-1 -p)", None
|
|
273
|
+
|
|
274
|
+
return None
|
|
275
|
+
|
|
276
|
+
@classmethod
|
|
277
|
+
def sanitize(cls, command: str) -> Tuple[Optional[str], int, str]:
|
|
278
|
+
"""
|
|
279
|
+
Analyzes a shell command stage by stage. If any stage creates massive
|
|
280
|
+
token waste, returns (rewritten_command, est_tokens_saved, reason).
|
|
281
|
+
If no change is needed, returns (None, 0, "").
|
|
282
|
+
"""
|
|
283
|
+
if not command or not command.strip():
|
|
284
|
+
return None, 0, ""
|
|
285
|
+
|
|
286
|
+
pairs = cls.split_stages(command.strip())
|
|
287
|
+
string_changed = False
|
|
288
|
+
total_saved = 0
|
|
289
|
+
reasons: List[str] = []
|
|
290
|
+
cap_spec: Optional[Tuple[str, int]] = None
|
|
291
|
+
|
|
292
|
+
for i, (op, stage) in enumerate(pairs):
|
|
293
|
+
res = cls._optimize_stage(stage)
|
|
294
|
+
if not res:
|
|
295
|
+
continue
|
|
296
|
+
new_stage, saved, reason, rule_cap = res
|
|
297
|
+
if new_stage != stage:
|
|
298
|
+
pairs[i] = (op, new_stage)
|
|
299
|
+
string_changed = True
|
|
300
|
+
total_saved += saved
|
|
301
|
+
reasons.append(reason)
|
|
302
|
+
# Only the FINAL stage may request the end-of-command cap: an
|
|
303
|
+
# earlier stage's cap would land after unrelated trailing stages
|
|
304
|
+
# (e.g. capping `npm test` instead of the `git grep` that fed it).
|
|
305
|
+
if rule_cap and i == len(pairs) - 1:
|
|
306
|
+
cap_spec = rule_cap
|
|
307
|
+
|
|
308
|
+
cap_applied = False
|
|
309
|
+
if cap_spec:
|
|
310
|
+
last_stage = pairs[-1][1]
|
|
311
|
+
if not cls._LIMITER_RE.search(last_stage) and not cls._has_redirect(last_stage):
|
|
312
|
+
unit, limit = cap_spec
|
|
313
|
+
pairs[-1] = (pairs[-1][0], f"{last_stage} | head -{unit} {limit}")
|
|
314
|
+
cap_applied = True
|
|
315
|
+
|
|
316
|
+
if not (string_changed or cap_applied):
|
|
317
|
+
return None, 0, ""
|
|
318
|
+
|
|
319
|
+
return cls.join_stages(pairs), total_saved, "; ".join(reasons)
|
package/src/dashboard.py
CHANGED
|
@@ -314,7 +314,7 @@ class Dashboard:
|
|
|
314
314
|
<div class="header">
|
|
315
315
|
<div>
|
|
316
316
|
<h1 class="title">⚡ TokenSafe</h1>
|
|
317
|
-
<p class="subtitle">
|
|
317
|
+
<p class="subtitle">Local-First AI Coding Guardrails & Context Telemetry</p>
|
|
318
318
|
</div>
|
|
319
319
|
<div id="live-pill" class="subtitle" style="display: flex; align-items: center; gap: 6px;">
|
|
320
320
|
<span style="color: #10b981;">●</span> Live SQLite Tracking
|
package/src/diff_slicer.py
CHANGED
|
@@ -106,6 +106,9 @@ class DiffSlicer:
|
|
|
106
106
|
def optimize_git_diff_command(cls, cmd: str) -> Tuple[Optional[str], int, str]:
|
|
107
107
|
"""
|
|
108
108
|
Rewrites git diff commands to enforce 2-line unified diffs and ignore lockfiles.
|
|
109
|
+
Per-stage: excludes are appended to each `git diff` stage itself, never
|
|
110
|
+
to the tail of a compound command (which would leak pathspecs into an
|
|
111
|
+
unrelated trailing command like `npm test`).
|
|
109
112
|
"""
|
|
110
113
|
clean_cmd = cmd.strip()
|
|
111
114
|
if not re.search(r"\bgit\s+diff\b", clean_cmd):
|
|
@@ -114,7 +117,20 @@ class DiffSlicer:
|
|
|
114
117
|
if "--unified=" in clean_cmd or "-U" in clean_cmd:
|
|
115
118
|
return None, 0, ""
|
|
116
119
|
|
|
120
|
+
from src.command_sanitizer import CommandSanitizer
|
|
121
|
+
pairs = CommandSanitizer.split_stages(clean_cmd)
|
|
117
122
|
lockfile_excludes = " ':!*lock*' ':!*.min.*' ':!*.map'"
|
|
118
|
-
|
|
123
|
+
changed = False
|
|
124
|
+
for i, (op, stage) in enumerate(pairs):
|
|
125
|
+
if not re.search(r"\bgit\s+diff\b", stage):
|
|
126
|
+
continue
|
|
127
|
+
if ":!" in stage:
|
|
128
|
+
continue # caller already manages pathspec excludes
|
|
129
|
+
pairs[i] = (op, stage.replace("git diff", "git diff -U2", 1) + lockfile_excludes)
|
|
130
|
+
changed = True
|
|
131
|
+
|
|
132
|
+
if not changed:
|
|
133
|
+
return None, 0, ""
|
|
134
|
+
|
|
119
135
|
est_saved = 4000
|
|
120
|
-
return
|
|
136
|
+
return CommandSanitizer.join_stages(pairs), est_saved, "Enforced 2-line AST diff window and excluded lockfiles"
|
package/src/installer.py
CHANGED
|
@@ -40,7 +40,7 @@ UNIFIED_TOKENSAFE_RULE = (
|
|
|
40
40
|
"2. **Mandatory Symbol & Component Inspection**: Whenever locating or reading a function, class, component, or method, ALWAYS call `tokensafe:smart_read_file` with `path` and `symbol`. It preserves the full executable target and 1-hop dependencies while folding inert code into signatures (-85% to -92% tokens).\n"
|
|
41
41
|
"3. **Architecture Discovery**: Always call `tokensafe:get_architecture_graph(project_path)` before exploratory multi-file reading. Returns project God Nodes and key dependency hubs in < 250 tokens without file crawling.\n"
|
|
42
42
|
"4. **API Surface Map**: Use `tokensafe:get_api_surface(project_path)` to get all exported classes, types, and interfaces in a single markdown map.\n"
|
|
43
|
-
"5. **Command Sanitization**: Use `sanitize_command` on high-output terminal commands (`git diff`, `
|
|
43
|
+
"5. **Command Sanitization**: Use `sanitize_command` on high-output terminal commands (`git diff/log/show/blame`, `rg`, `find`, `grep`, `docker`/`kubectl logs`, `npm`/`pip install`, `cat` of lockfiles, `curl`) — compound commands (`a && b ; c`) are rewritten per stage.\n"
|
|
44
44
|
"6. **Proof-of-Savings Turn Footer (always in English)**:\n"
|
|
45
45
|
"At the end of your response for any turn where tools were executed, files were inspected, commands were sanitized, or prompts were compacted, append a compact 1-line footer in English:\n"
|
|
46
46
|
"`⚡ **TokenSafe Turn Savings**: +<tokens> tokens saved on this turn (<breakdown>) | Cumulative Total: <total> tokens (≈$<usd> approx)`\n"
|
package/src/mcp_server.py
CHANGED
|
@@ -39,7 +39,7 @@ from src.scoped_search import ScopedSearch
|
|
|
39
39
|
|
|
40
40
|
SERVER_INFO = {
|
|
41
41
|
"name": "tokensafe-mcp",
|
|
42
|
-
"version": "2.
|
|
42
|
+
"version": "2.1.0"
|
|
43
43
|
}
|
|
44
44
|
|
|
45
45
|
# MCP client attribution: the initialize handshake carries clientInfo, which
|
|
@@ -128,7 +128,9 @@ TOOLS = [
|
|
|
128
128
|
},
|
|
129
129
|
{
|
|
130
130
|
"name": "sanitize_command",
|
|
131
|
-
"description": "
|
|
131
|
+
"description": "Per-stage shell command rewrites: prunes lockfiles, caps unbounded git log/show/blame/rg "
|
|
132
|
+
"and docker/kubectl logs, quiets npm/pip installs, bounds cat/curl output. Compound commands "
|
|
133
|
+
"(a && b ; c) are optimized per stage without breaking operators.",
|
|
132
134
|
"inputSchema": {
|
|
133
135
|
"type": "object",
|
|
134
136
|
"properties": {
|
|
@@ -159,7 +161,7 @@ TOOLS = [
|
|
|
159
161
|
},
|
|
160
162
|
{
|
|
161
163
|
"name": "guard_inspect",
|
|
162
|
-
"description": "Pre-flight security & hygiene audit for commands or code snippets. Detects secret leaks, SQL injection, TLS bypass, CORS wildcard, destructive commands, and
|
|
164
|
+
"description": "Pre-flight security & hygiene audit for commands or code snippets. Detects secret leaks, SQL injection, TLS bypass (incl. git-level), CORS wildcard, destructive commands, raw grep, and never-terminating streams (tail -f, watch, docker attach).",
|
|
163
165
|
"inputSchema": {
|
|
164
166
|
"type": "object",
|
|
165
167
|
"properties": {
|
|
@@ -703,6 +705,66 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
|
|
|
703
705
|
optimized_tokens=0,
|
|
704
706
|
details={"cmd": cmd[:100], "reason": c_res.reason}
|
|
705
707
|
)
|
|
708
|
+
else:
|
|
709
|
+
# Adapter-level command checks (v2.1.0): TokenSafeGuard's
|
|
710
|
+
# command audit does not scan for literal credentials, so
|
|
711
|
+
# deny-level secrets/destruction come from the adapter core —
|
|
712
|
+
# the same patterns the Claude Code / Cursor shell guards use.
|
|
713
|
+
try:
|
|
714
|
+
from src.adapter_core import (_SECRET_PATTERNS, _DESTRUCTIVE_PATTERNS,
|
|
715
|
+
_INFINITE_PATTERNS, _TLS_BYPASS_PATTERNS)
|
|
716
|
+
hit = None
|
|
717
|
+
for pat in _SECRET_PATTERNS:
|
|
718
|
+
if re.search(pat, cmd):
|
|
719
|
+
hit = ("SECRET", "Blocked: command contains a hardcoded secret", True)
|
|
720
|
+
break
|
|
721
|
+
if hit is None:
|
|
722
|
+
for pat in _DESTRUCTIVE_PATTERNS:
|
|
723
|
+
if re.search(pat, cmd):
|
|
724
|
+
hit = ("DESTRUCTIVE", "Blocked: irreversible/destructive operation", True)
|
|
725
|
+
break
|
|
726
|
+
if hit:
|
|
727
|
+
results.append({
|
|
728
|
+
"target": "command",
|
|
729
|
+
"input": cmd,
|
|
730
|
+
"allowed": False,
|
|
731
|
+
"blocked": True,
|
|
732
|
+
"check_name": hit[0],
|
|
733
|
+
"reason": hit[1],
|
|
734
|
+
"warning_only": False
|
|
735
|
+
})
|
|
736
|
+
tracker.record_event(
|
|
737
|
+
session_id=_mcp_session_id(),
|
|
738
|
+
event_type=f"GUARD_{hit[0]}",
|
|
739
|
+
original_tokens=count_tokens(cmd),
|
|
740
|
+
optimized_tokens=0,
|
|
741
|
+
details={"cmd": cmd[:100], "reason": hit[1]}
|
|
742
|
+
)
|
|
743
|
+
else:
|
|
744
|
+
# Advisory tier: infinite streams and TLS bypass never
|
|
745
|
+
# block an inspection, and inspections write no events.
|
|
746
|
+
advisory = None
|
|
747
|
+
for pat in _INFINITE_PATTERNS:
|
|
748
|
+
if re.search(pat, cmd):
|
|
749
|
+
advisory = ("INFINITE_STREAM", "Command never terminates on its own (follow/streaming) — run it in the background or confirm intent")
|
|
750
|
+
break
|
|
751
|
+
if advisory is None:
|
|
752
|
+
for pat in _TLS_BYPASS_PATTERNS:
|
|
753
|
+
if re.search(pat, cmd):
|
|
754
|
+
advisory = ("TLS_VERIFY_BYPASS", "Certificate verification disabled — confirm this is intentional")
|
|
755
|
+
break
|
|
756
|
+
if advisory:
|
|
757
|
+
results.append({
|
|
758
|
+
"target": "command",
|
|
759
|
+
"input": cmd,
|
|
760
|
+
"allowed": True,
|
|
761
|
+
"blocked": False,
|
|
762
|
+
"check_name": advisory[0],
|
|
763
|
+
"reason": advisory[1],
|
|
764
|
+
"warning_only": True
|
|
765
|
+
})
|
|
766
|
+
except Exception:
|
|
767
|
+
pass
|
|
706
768
|
|
|
707
769
|
if code is not None:
|
|
708
770
|
w_res = TokenSafeGuard.inspect_file_write(file_path, code)
|
package/src/metrics.py
CHANGED
|
@@ -24,11 +24,21 @@ USD_PER_TOKEN = 1.50 / 1_000_000.0
|
|
|
24
24
|
# replace-mode is verified end-to-end.
|
|
25
25
|
# ROLLUP_LIFETIME: pruned-and-rolled-up historical mass of mixed provenance;
|
|
26
26
|
# conservatively labelled estimated.
|
|
27
|
+
# Counterfactual event types: their original_tokens are heuristic guesses of
|
|
28
|
+
# output that WOULD have entered context (command rewrites, blocked calls,
|
|
29
|
+
# prompt compaction), not metered I/O deltas. See METRICS.md.
|
|
27
30
|
ESTIMATED_EVENT_TYPES = frozenset({
|
|
28
31
|
"GRAPH_TOPOLOGY",
|
|
29
32
|
"HISTORY_FOLD",
|
|
30
33
|
"PROMPT",
|
|
31
34
|
"ROLLUP_LIFETIME",
|
|
35
|
+
"COMMAND_FILTER",
|
|
36
|
+
"LOOP_GUARD",
|
|
37
|
+
"GUARD_SECRET",
|
|
38
|
+
"GUARD_DESTRUCTIVE",
|
|
39
|
+
"GUARD_TLS_VERIFY_BYPASS",
|
|
40
|
+
"GUARD_JUNK_READ",
|
|
41
|
+
"GUARD_INFINITE",
|
|
32
42
|
})
|
|
33
43
|
|
|
34
44
|
def resolve_measurement(event_type: str, explicit: Optional[str] = None) -> str:
|
|
@@ -163,7 +173,10 @@ class MetricsTracker:
|
|
|
163
173
|
cursor.execute(
|
|
164
174
|
"UPDATE events SET measurement = 'estimated' "
|
|
165
175
|
"WHERE measurement = 'measured' AND event_type IN "
|
|
166
|
-
"('GRAPH_TOPOLOGY', 'HISTORY_FOLD', 'PROMPT', 'ROLLUP_LIFETIME'
|
|
176
|
+
"('GRAPH_TOPOLOGY', 'HISTORY_FOLD', 'PROMPT', 'ROLLUP_LIFETIME', "
|
|
177
|
+
"'COMMAND_FILTER', 'LOOP_GUARD', 'GUARD_SECRET', "
|
|
178
|
+
"'GUARD_DESTRUCTIVE', 'GUARD_TLS_VERIFY_BYPASS', "
|
|
179
|
+
"'GUARD_JUNK_READ', 'GUARD_INFINITE');"
|
|
167
180
|
)
|
|
168
181
|
cursor.execute("""
|
|
169
182
|
CREATE TABLE IF NOT EXISTS lifetime_aggregates (
|
package/src/slicer.py
CHANGED
|
@@ -5,7 +5,7 @@ Prevents context window bloat from full-file reads (800+ lines) and noisy termin
|
|
|
5
5
|
|
|
6
6
|
import os
|
|
7
7
|
import re
|
|
8
|
-
from typing import Dict, Any, Optional, Tuple
|
|
8
|
+
from typing import Dict, Any, List, Optional, Tuple
|
|
9
9
|
from src.tokenizer import count_tokens
|
|
10
10
|
|
|
11
11
|
class ToolSlicer:
|
|
@@ -14,6 +14,64 @@ class ToolSlicer:
|
|
|
14
14
|
# Default max lines to read when no range is specified on large files
|
|
15
15
|
DEFAULT_MAX_WINDOW = 350
|
|
16
16
|
|
|
17
|
+
# When a target symbol is found, the slice must contain the WHOLE
|
|
18
|
+
# enclosing definition — a fixed tail used to cut long function bodies in
|
|
19
|
+
# half. Definitions longer than this cap are better served by the AST
|
|
20
|
+
# skeleton path, so the window stays bounded.
|
|
21
|
+
MAX_SYMBOL_WINDOW = 400
|
|
22
|
+
|
|
23
|
+
@classmethod
|
|
24
|
+
def _find_definition_end(cls, lines: List[str], def_line_no: int) -> Optional[int]:
|
|
25
|
+
"""
|
|
26
|
+
Returns the 1-based last line of the definition whose declaration sits
|
|
27
|
+
on def_line_no, or None when it cannot be determined reliably.
|
|
28
|
+
|
|
29
|
+
Python (def/class): the body ends at the last non-blank line before a
|
|
30
|
+
line dedented to <= the declaration's indent.
|
|
31
|
+
C-family (function/const/func/fn/impl/struct/...): brace balance from
|
|
32
|
+
the first '{' within the declaration or the next 10 lines. Naive
|
|
33
|
+
counting is safe here: a brace inside a string can only skew the end
|
|
34
|
+
within the cap, and the caller keeps the legacy tail as a floor.
|
|
35
|
+
"""
|
|
36
|
+
if def_line_no < 1 or def_line_no > len(lines):
|
|
37
|
+
return None
|
|
38
|
+
def_line = lines[def_line_no - 1]
|
|
39
|
+
|
|
40
|
+
py_match = re.match(r"^(\s*)(?:async\s+)?(?:def|class)\b", def_line)
|
|
41
|
+
if py_match:
|
|
42
|
+
base_indent = len(py_match.group(1).expandtabs(8))
|
|
43
|
+
end = def_line_no
|
|
44
|
+
for idx in range(def_line_no, len(lines)):
|
|
45
|
+
line = lines[idx]
|
|
46
|
+
if not line.strip():
|
|
47
|
+
continue
|
|
48
|
+
expanded = line.expandtabs(8)
|
|
49
|
+
indent = len(expanded) - len(expanded.lstrip())
|
|
50
|
+
if indent <= base_indent:
|
|
51
|
+
break
|
|
52
|
+
end = idx + 1
|
|
53
|
+
return end
|
|
54
|
+
|
|
55
|
+
# C-family: locate the opening brace within the declaration head
|
|
56
|
+
# (first 10 lines), then balance braces across the capped window.
|
|
57
|
+
window_end = min(len(lines), def_line_no - 1 + cls.MAX_SYMBOL_WINDOW)
|
|
58
|
+
text = "".join(lines[def_line_no - 1:window_end])
|
|
59
|
+
head = "".join(lines[def_line_no - 1:min(len(lines), def_line_no + 10)])
|
|
60
|
+
offset = head.find("{")
|
|
61
|
+
if offset == -1:
|
|
62
|
+
return None
|
|
63
|
+
|
|
64
|
+
depth = 0
|
|
65
|
+
for i, ch in enumerate(text[offset:]):
|
|
66
|
+
if ch == "{":
|
|
67
|
+
depth += 1
|
|
68
|
+
elif ch == "}":
|
|
69
|
+
depth -= 1
|
|
70
|
+
if depth == 0:
|
|
71
|
+
return def_line_no + text[:offset + i + 1].count("\n")
|
|
72
|
+
# Unbalanced within the cap: report the cap boundary as the end
|
|
73
|
+
return window_end
|
|
74
|
+
|
|
17
75
|
@classmethod
|
|
18
76
|
def optimize_read_file(cls, args: Dict[str, Any], context_hint: str = "") -> Tuple[Dict[str, Any], Dict[str, Any]]:
|
|
19
77
|
"""
|
|
@@ -58,7 +116,7 @@ class ToolSlicer:
|
|
|
58
116
|
# regex scans per read_file hook call on large files).
|
|
59
117
|
unique_candidates = list(dict.fromkeys(candidates))
|
|
60
118
|
combined = re.compile(
|
|
61
|
-
r'\b(?:def|function|class|const|let|var|type|interface)\s+('
|
|
119
|
+
r'\b(?:def|function|class|const|let|var|type|interface|func|fn|impl|struct|enum|trait)\s+('
|
|
62
120
|
+ "|".join(re.escape(c) for c in unique_candidates) + r')\b'
|
|
63
121
|
)
|
|
64
122
|
first_hit: Dict[str, int] = {}
|
|
@@ -77,9 +135,17 @@ class ToolSlicer:
|
|
|
77
135
|
new_end = total_lines
|
|
78
136
|
|
|
79
137
|
if found_line:
|
|
80
|
-
# Slice: 20
|
|
138
|
+
# Slice: 20-line lead-in before the declaration, then enough tail
|
|
139
|
+
# to contain the WHOLE enclosing definition (short definitions keep
|
|
140
|
+
# the legacy 80-line tail; long ones extend to their real end).
|
|
81
141
|
new_start = max(1, found_line - 20)
|
|
82
142
|
new_end = min(total_lines, found_line + 80)
|
|
143
|
+
def_end = cls._find_definition_end(lines, found_line)
|
|
144
|
+
if def_end:
|
|
145
|
+
new_end = min(
|
|
146
|
+
total_lines,
|
|
147
|
+
max(new_end, min(def_end, found_line + cls.MAX_SYMBOL_WINDOW)),
|
|
148
|
+
)
|
|
83
149
|
|
|
84
150
|
# If no symbol found and file is large (> 400 lines), apply safety window
|
|
85
151
|
if not target_symbol and total_lines > 400 and (end_line is None or end_line > cls.DEFAULT_MAX_WINDOW):
|
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/2.
|
|
267
|
+
"User-Agent": "TokenSafe-Sync/2.1.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 = "2.
|
|
19
|
+
CURRENT_VERSION = "2.1.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
|
|
@@ -331,15 +331,44 @@ class VersionChecker:
|
|
|
331
331
|
if not force and last_notified_ver == latest and (now - last_notified_at) < CACHE_TTL:
|
|
332
332
|
return False
|
|
333
333
|
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
334
|
+
# Cross-process claim: several agent hook processes can pass the 24h
|
|
335
|
+
# cache check simultaneously (Antigravity + ZCode + adapters), which
|
|
336
|
+
# rendered the update dialog TWICE. Only the process that wins the
|
|
337
|
+
# O_EXCL claim shows the dialog; the claim self-expires.
|
|
338
|
+
claim_path = os.path.join(DATA_DIR, ".update_dialog.claim")
|
|
339
|
+
try:
|
|
340
|
+
if os.path.exists(claim_path):
|
|
341
|
+
if (now - os.path.getmtime(claim_path)) < 60:
|
|
342
|
+
return False
|
|
343
|
+
os.remove(claim_path) # stale claim: safe to reclaim (O_EXCL guards the race)
|
|
344
|
+
fd = os.open(claim_path, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
|
|
345
|
+
os.write(fd, str(os.getpid()).encode("utf-8"))
|
|
346
|
+
os.close(fd)
|
|
347
|
+
except FileExistsError:
|
|
348
|
+
return False
|
|
349
|
+
except OSError:
|
|
350
|
+
pass # claim is best-effort; never block the dialog entirely on fs errors
|
|
351
|
+
|
|
352
|
+
try:
|
|
353
|
+
cached["last_os_notify_version"] = latest
|
|
354
|
+
cached["last_os_notify_at"] = now
|
|
355
|
+
cls.save_cache(cached)
|
|
356
|
+
except Exception:
|
|
357
|
+
pass
|
|
337
358
|
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
359
|
+
try:
|
|
360
|
+
dispatched = cls.show_os_dialog(
|
|
361
|
+
current_version=current_version,
|
|
362
|
+
latest_version=latest,
|
|
363
|
+
update_command=cmd
|
|
364
|
+
)
|
|
365
|
+
return dispatched
|
|
366
|
+
finally:
|
|
367
|
+
# Release the dialog claim so a future version can notify again.
|
|
368
|
+
try:
|
|
369
|
+
os.remove(claim_path)
|
|
370
|
+
except OSError:
|
|
371
|
+
pass
|
|
343
372
|
|
|
344
373
|
@classmethod
|
|
345
374
|
def notify_os_update_background(
|