tokensafe 2.1.0 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,40 +1,41 @@
1
1
  <p align="center">
2
- <img src="assets/logo.svg" alt="TokenSafe Logo" width="100" height="100" />
2
+ <img src="assets/logo.svg" alt="TokenSafe Logo" width="88" height="88" />
3
3
  </p>
4
4
 
5
- <h1 align="center">⚡ TokenSafe</h1>
5
+ <h1 align="center">TokenSafe</h1>
6
6
  <!-- mcp-name: dev.tokensafe/tokensafe -->
7
7
 
8
8
  <p align="center">
9
- <b>Local-First AI Coding Guardrails, Context Precision &amp; 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 &amp; Codex</b>.
9
+ <b>Local-First AI Guardrails, Focused Context &amp; Auditable Team ROI</b><br>
10
+ Stop paying for AI hallucinations and secret leaks. Keep your team's coding agents focused on the right code, block exposed secrets before commit, and cut context bloat locally (up to <a href="METRICS.md">90%*</a>).<br>
11
+ Built for teams using <b>Cursor, Claude Code, Codex, Windsurf, and Google Antigravity</b>.
12
12
  </p>
13
13
 
14
14
  <p align="center">
15
- <a href="https://github.com/NekoSin4eG/tokensafe/actions/workflows/test.yml"><img src="https://img.shields.io/github/actions/workflow/status/NekoSin4eG/tokensafe/test.yml?branch=main&label=tests&style=flat-square" alt="Tests"></a>
16
- <a href="https://www.npmjs.com/package/tokensafe"><img src="https://img.shields.io/npm/v/tokensafe.svg?color=CB3837&style=flat-square" alt="npm"></a>
15
+ <a href="https://github.com/NekoSin4eG/tokensafe/actions/workflows/test.yml"><img src="https://img.shields.io/github/actions/workflow/status/NekoSin4eG/tokensafe/test.yml?branch=main&label=tests&style=flat-square&color=10B981" alt="Tests"></a>
16
+ <a href="https://www.npmjs.com/package/tokensafe"><img src="https://img.shields.io/npm/v/tokensafe.svg?color=38BDF8&style=flat-square" alt="npm"></a>
17
17
  <a href="https://www.npmjs.com/package/tokensafe"><img src="https://img.shields.io/npm/dw/tokensafe.svg?color=10B981&label=npm%20downloads&style=flat-square" alt="npm downloads"></a>
18
- <a href="https://pypi.org/project/tokensafe/"><img src="https://img.shields.io/pypi/v/tokensafe.svg?color=3775A9&style=flat-square" alt="PyPI"></a>
19
- <a href="https://github.com/NekoSin4eG/tokensafe/stargazers"><img src="https://img.shields.io/github/stars/NekoSin4eG/tokensafe?style=flat-square&color=yellow" alt="Stars"></a>
20
- <a href="https://opensource.org/licenses/MIT"><img src="https://img.shields.io/badge/License-MIT-emerald.svg?style=flat-square" alt="License"></a>
21
- <a href="https://tokensafe.dev#pricing"><img src="https://img.shields.io/badge/Trial-7_Days_Free-10B981.svg?style=flat-square" alt="Trial"></a>
18
+ <a href="https://pypi.org/project/tokensafe/"><img src="https://img.shields.io/pypi/v/tokensafe.svg?color=38BDF8&style=flat-square" alt="PyPI"></a>
19
+ <a href="https://github.com/NekoSin4eG/tokensafe/stargazers"><img src="https://img.shields.io/github/stars/NekoSin4eG/tokensafe?style=flat-square&color=334155" alt="Stars"></a>
20
+ <a href="https://opensource.org/licenses/MIT"><img src="https://img.shields.io/badge/License-MIT-0F766E?style=flat-square" alt="License"></a>
21
+ <a href="https://tokensafe.dev#pricing"><img src="https://img.shields.io/badge/Team_Trial-7_Days_Free-10B981?style=flat-square" alt="Trial"></a>
22
22
  </p>
23
23
 
24
24
  <p align="center">
25
- <a href="#-1-click-universal-install">Install</a> •
26
- <a href="#-universal-mcp-server-configuration">MCP Setup</a> •
27
- <a href="#-how-your-team-ships-cleaner-code-with-6090-less-bloat">How It Works</a> •
28
- <a href="#-tokensafe-guard-proactive-agent-security--hygiene-shield">TokenSafe Guard</a> •
29
- <a href="#-pricing--plans">Pricing</a> •
30
- <a href="https://tokensafe.dev">Official Website & Docs</a>
25
+ <a href="#1-click-universal-install">Install</a> &bull;
26
+ <a href="#three-outcomes-for-engineering-teams">Outcomes</a> &bull;
27
+ <a href="#tokensafe-guard-local-security-and-hygiene-shield">Guardrails</a> &bull;
28
+ <a href="#universal-mcp-server-configuration">MCP Setup</a> &bull;
29
+ <a href="#metrics-honesty">Metrics Honesty</a> &bull;
30
+ <a href="#pricing-and-7-day-team-trial">Pricing</a> &bull;
31
+ <a href="https://tokensafe.dev">Website &amp; Docs</a>
31
32
  </p>
32
33
 
33
34
  ---
34
35
 
35
- ## ⚡ 1-Click Universal Install
36
+ ## 1-Click Universal Install
36
37
 
37
- Connect TokenSafe to all detected AI coding agents on your machine in seconds:
38
+ Connect TokenSafe to the AI coding agents on your workstation in one command:
38
39
 
39
40
  ```bash
40
41
  # Option 1: Zero-Install via npx (Recommended for Cursor & Claude Desktop)
@@ -47,11 +48,11 @@ pip install tokensafe && tokensafe
47
48
  curl -fsSL https://tokensafe.dev/install.sh | bash
48
49
  ```
49
50
 
50
- ### Optional dependency: `cryptography` (recommended)
51
+ On **Google Antigravity**, the installer additionally symlinks the plugin into `~/.gemini/config/plugins/agy-token-optimizer` — Antigravity loads it automatically on startup.
51
52
 
52
- The TokenSafe engine itself is **standard-library only** and works out of the box.
53
- A single optional dependency — [`cryptography`](https://pypi.org/project/cryptography/) —
54
- is installed automatically by `install.sh` / `requirements.txt` when available:
53
+ ### Optional Dependency: `cryptography` (Recommended)
54
+
55
+ The local TokenSafe engine uses Python's standard library only and runs out of the box. One optional package, [`cryptography`](https://pypi.org/project/cryptography/), is installed automatically by `install.sh` and `requirements.txt` when available:
55
56
 
56
57
  ```bash
57
58
  pip install cryptography # or: brew install cryptography
@@ -59,33 +60,32 @@ pip install cryptography # or: brew install cryptography
59
60
 
60
61
  | Component | With `cryptography` | Without (pure-stdlib fallback) |
61
62
  |---|---|---|
62
- | Client: license verification | Instant Ed25519 fast-path | Pure-Python Ed25519 (~0.3s once, then cached — see below) |
63
+ | Client: license verification | Instant Ed25519 fast-path | Pure-Python Ed25519 (~0.3s once, then cached) |
63
64
  | Client: everything else | Identical | Identical |
64
- | Cloud backend: Clerk session tokens | RS256 signature verified | **Rejected** (fail-closed — unsigned tokens are never accepted) |
65
+ | Cloud backend: Clerk session tokens | RS256 signature verified | **Rejected** (fail-closed: unsigned tokens are never accepted) |
65
66
  | Cloud backend: everything else | Identical | Identical |
66
67
 
67
- The client caches a successful license verification for up to 1 hour, so even the
68
- pure-Python path adds no measurable latency after the first hook invocation.
68
+ The client caches a verified license for up to 1 hour, so even the 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)
72
+ ## Universal Agent Hooks (Claude Code & Cursor)
73
73
 
74
- Beyond MCP, TokenSafe ships **lifecycle-hook adapters** that run natively inside your agent's loop — installed automatically by `tokensafe setup`:
74
+ Beyond MCP, TokenSafe installs native lifecycle-hook adapters inside your agent loop via `tokensafe setup`:
75
75
 
76
76
  | Agent | Hook | What it does |
77
77
  |---|---|---|
78
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 |
79
+ | **Claude Code** | `PreToolUse` (Bash) | Blocks secret-bearing and destructive commands; prompts for confirmation on TLS-verification bypasses |
80
+ | **Cursor** | `beforeShellExecution` | Same shell guard: blocks secret leaks and destructive actions, asks on `-k` or `--insecure` |
81
+ | **Cursor** | `beforeReadFile` | Blocks raw lockfile, bundle, and `dist/` reads that would burn ~50k context tokens |
82
+ | **Codex CLI** | None yet | Uses MCP and `AGENTS.md` directly |
83
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).
84
+ All adapters **fail open**: an internal error never stalls the host agent. Cursor's strict valid-JSON response contract is preserved on every error path.
85
85
 
86
- ## 🧠 Context Budget HUD
86
+ ## Context Budget HUD & Governor
87
87
 
88
- Agents (and humans) usually discover context exhaustion by quality degradation — too late. TokenSafe exposes the remaining budget as a first-class MCP tool:
88
+ Teams usually notice context exhaustion only when code quality drops mid-task. TokenSafe exposes live window usage as a native MCP tool:
89
89
 
90
90
  ```json
91
91
  { "tool": "tokensafe:context_budget", "args": { "model": "claude-x" } }
@@ -102,25 +102,19 @@ Agents (and humans) usually discover context exhaustion by quality degradation
102
102
  }
103
103
  ```
104
104
 
105
- - Window resolution: explicit arg → `TOKENSAFE_CONTEXT_WINDOW` env → model-family default (Gemini 1M, Claude 200k, GPT 128k).
106
- - **80% warning injected into the agent automatically** by the Antigravity/ZCode `pre_invocation` hook — once per session (marker-event guarded).
107
- - Honesty: counts only TokenSafe-instrumented flows (tool slices, skeletons, compacted prompts) — labeled `estimated`, a floor, never a fabricated total (see [METRICS.md](METRICS.md)).
108
-
109
- ## 💰 Per-Seat ROI (Team)
110
-
111
- Team owners pay per seat — now they see the return per seat. The dashboard's Team Seats table carries an **ROI column** per developer: saved tokens, USD equivalent, and the `metered/estimated` honesty split, computed in a single grouped query. Seats without activity render `—`, never a fabricated number.
112
-
113
- ## 💾 Persistent Diff-Aware Read-Cache
105
+ - **Window resolution**: explicit argument, then `TOKENSAFE_CONTEXT_WINDOW`, then model-family default (Gemini 1M, Claude 200k, GPT 128k).
106
+ - **80% session warning**: injected once per session by the `pre_invocation` hook when context usage approaches the threshold.
107
+ - **Cascading governor & prefix normalizer**: aligns prompt prefixes to 64-token boundaries (for Anthropic `cache_control` and DeepSeek caching) and progressively folds inactive bodies before overflowing.
108
+ - **Honest accounting**: counts only TokenSafe-instrumented flows and labels them `estimated` (a floor, never a fabricated total; see [METRICS.md](METRICS.md)).
114
109
 
115
- The subagent dedup cache (per-session) now has a persistent layer keyed by **sha256 of the file's raw bytes**:
110
+ ## Per-Seat ROI & Persistent Diff-Aware Read-Cache
116
111
 
117
- - Survives MCP-server restarts **and** `git checkout` (which resets mtime but not content — content is the only truth).
118
- - Any real edit changes the hash and invalidates the entry instantly.
119
- - Bounded: artifacts >256k chars are never cached; the layer prunes itself to the latest 500 entries (hourly amortized).
112
+ - **Per-Seat ROI (Team)**: the Team Seats dashboard table tracks saved tokens, derived USD impact, and the `measured` vs. `estimated` split per developer in one grouped query. Inactive seats show `—`, never guessed figures.
113
+ - **Diff-Aware Read-Cache (`SUBAGENT_DEDUP`)**: prevents subagent swarms from reading identical files repeatedly. Entries are keyed by **SHA-256 of raw file bytes**, so they survive MCP server restarts and `git checkout` while invalidating immediately on any real edit (bounded at 256k chars per artifact and 500 recent entries).
120
114
 
121
- ## 🔌 Universal MCP Server Configuration
115
+ ## Universal MCP Server Configuration
122
116
 
123
- Connect TokenSafe directly to **Claude Desktop** (`claude_desktop_config.json`) or **Cursor** MCP Settings:
117
+ Connect TokenSafe to **Claude Desktop** (`claude_desktop_config.json`) or **Cursor** MCP settings:
124
118
 
125
119
  ```json
126
120
  {
@@ -135,63 +129,42 @@ Connect TokenSafe directly to **Claude Desktop** (`claude_desktop_config.json`)
135
129
 
136
130
  ---
137
131
 
138
- ## ⚡ How Your Team Ships Cleaner Code with 60%–90% Less Bloat
139
-
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
-
145
- ### TokenSafe Fixes All Three Locally:
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
- - **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
- - **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.
149
- - **Subagent Deduplication Firewall:** Detects repeated file reads across subagents and agent swarms, serving cached AST slices directly from SQLite session memory (`SUBAGENT_DEDUP`) with zero redundant overhead.
150
- - **AST Diff Slicer & Lockfile Stripper:** Compresses code review diffs by stripping noisy lockfiles (`package-lock.json`, `pnpm-lock.yaml`, `yarn.lock`, `Cargo.lock`) and minified assets, condensing diffs to 2 lines of context (`git diff -U2`) for up to 96% token savings.
151
- - **God Nodes & Architectural Hub Detection:** Calculates Degree Centrality to identify structural project hubs and injects topology awareness into agent sessions without expensive file crawling.
152
- - **TOCP Prompt Distillation:** Intercepts prompts and distills intent into lean S-Expressions (`-40% to -70%`). Solo & Team tiers include **Managed Cloud Distillation** out of the box via TokenSafe Cloud (`gemini-flash-lite-latest`) with **zero API keys required**. Free tier includes a zero-overhead 9-language Local Regex Compactor. Enterprise on-premise Docker deployments support custom private BYOK keys.
153
- - **Token Arbitrage Guard & Output Ceiling:** Eliminates LLM compiler arbitrage loss with a dual defense: inputs $< 100$ tokens route to instant zero-cost local regex heuristics ($0$ LLM tokens), while inputs $\ge 100$ tokens are clamped to a strict $60$-token max output ceiling.
154
- - **Three-Tier Distillation Cache:** Three-tier L1 In-Memory LRU + L2 Persistent SQLite cache (`metrics.db`) + L3 Shared Team Cloud Cache with normalized SHA-256 hashing guarantees sub-millisecond zero-cost replays for recurring developer commands.
155
- - **Shared Team Cache (L3 Cloud Monorepo Cache):** Synchronizes compiled prompt intents and AST skeletons across all developers and CI agents on an engineering team. Teammates querying the same files or command patterns get instant 0ms warm cache hits with zero LLM API calls.
156
- - **API Surface Map Generator:** Generates high-density `tokensafe-out/API_SURFACE.md` (~1.5k tokens) for instant agent codebase onboarding.
157
- - **Predictive Dependency Prefetcher:** Attaches imported symbol signatures to eliminate downstream exploratory `read_file` roundtrips.
158
- - **Live SSE Streaming Dashboard:** Real-time reactive Web UI streaming token reductions, live event logs, and USD savings via Server-Sent Events (`/api/events`).
159
- - **Friday Team ROI Digest:** Automatically aggregates 7-day token economics every Friday and emails team leads an executive HTML report with engineer savings leaderboards.
160
- - **Environment Overhead Auditor (`tokensafe doctor`):** Inspects active MCP servers and Antigravity skills, measuring system prompt token tax and pruning redundant tool schemas.
161
- - **MCP Tool Schema Bloat Guard:** Stops heavy MCP servers (50–200+ tools) from injecting 5,000–15,000 hidden schema tokens into every API turn. 1-click toggle (`tokensafe mcp disable <name>`) and real-time in-chat bloat alerts.
162
- - **Data Retention & Compact Rollups (`tokensafe prune` / `vacuum`):** Automated sliding-window log cleanup with lifetime metric rollups, cutting telemetry database disk footprint by up to 40%.
163
- - **TokenSafe Guard:** Proactive agent security & hygiene shield. Blocks hardcoded secret fallbacks in `os.environ` / `process.env`, SSL/TLS bypass (`verify=False`), raw SQL injection f-strings, insecure CORS credentials, blanket `git add .` on `.env` files, and destructive shell commands (`rm -rf /`).
164
- - **Local Secret Redactor:** Sanitizes Stripe, AWS, JWT, and database credentials before network transmission.
165
- - **Output Guard & Loop Guard:** Blocks destructive full-file rewrites on files $\ge 40$ lines and halts command loops.
132
+ ## Three Outcomes for Engineering Teams
166
133
 
167
- ---
134
+ Giving coding agents raw access to entire repositories creates three daily problems:
135
+ 1. **Broken edits in large files**: reading 2,000-line modules for a 10-line fix causes models to forget imports, invent methods, and regress adjacent code.
136
+ 2. **Secret leaks and unsafe shortcuts**: static prompt rules in `.cursorrules` wear off mid-session. Agents hardcode fallback credentials, disable TLS checks, or stage `.env` files with `git add .`.
137
+ 3. **Mid-sprint quota stops and blind spend**: bloated diffs, lockfiles, and verbose MCP schemas burn 5-hour limits while engineering leads lack per-seat ROI visibility.
168
138
 
169
- ## 🤯 The Accidental Side Effect: Your AI Stops Hallucinating
139
+ | Outcome | What changes for your team | Local enforcement |
140
+ |---|---|---|
141
+ | **Clean code on the first pass** | Agents read only target functions, design tokens, and 1-hop dependencies instead of 2,000 lines of noise. | Sub-30ms AST skeletonizer, `API_SURFACE.md` generator, predictive signature prefetcher, `git diff -U2` lockfile stripper, God Node detection, and Loop Guard. |
142
+ | **Zero leaked secrets in git** | Hardcoded password fallbacks, TLS bypasses, raw SQL interpolation, and `.env` commits are stopped before reaching disk or staging. | Deterministic `TokenSafe Guard`, Output Guard (`write_file >= 40 lines`), and local PII/key redaction. |
143
+ | **Predictable sprint velocity & ROI** | Shared L3 monorepo cache gives teammates warm 0ms hits, while CTOs receive a Friday ROI digest separating `measured` and `estimated` savings. | Three-tier cache (`L1` LRU, `L2` SQLite, `L3` Team pool), Token Arbitrage Guard (`< 100 tok` regex, `>= 100 tok` clamped to `60 tok`), and live SSE dashboard (`/api/events`). |
170
144
 
171
- We originally built TokenSafe for a purely selfish reason: **to stop getting $400 monthly LLM API bills** from running autonomous coding agents.
145
+ ---
172
146
 
173
- Then something unexpected happened during real-world dogfooding.
147
+ ## Why Stripping Context Bloat Fixes AI Code Quality
174
148
 
175
- Our agents didn't just get cheaper — **they wrote noticeably better code, stopped inventing imaginary methods, and eliminated cyclic regression bugs.**
149
+ TokenSafe started because of a **$400 monthly API bill** from running autonomous coding agents across active repositories.
176
150
 
177
- Turns out, there's a simple reason for this:
178
- > **Transformer models don't write bad code because they're stupid. They write bad code because we drown them in 15,000 lines of garbage.**
151
+ Once engineering teams tested it, lower bills turned out to be the secondary benefit. **Agents wrote cleaner patches, stopped inventing non-existent methods, and stopped looping on the same broken fix.**
179
152
 
180
- ### How stripping 90% of token noise fixes AI code quality:
153
+ > Models rarely write bad code because they lack capability. They write bad code when 15,000 lines of irrelevant context drown out the few contracts that matter.
181
154
 
182
- | What Usually Breaks the AI | How TokenSafe Fixes It | The Result |
155
+ | What breaks coding agents | How TokenSafe fixes it | The outcome |
183
156
  | :--- | :--- | :--- |
184
- | **"Lost in the Middle" Attention Fade**<br>Agent reads a 2,000-line file just to tweak a 10-line helper. The model loses track of imports and invents fictional methods. | **AST Skeletonizer** (`src/slicer.py`) collapses dead code into typed interfaces, keeping only target functions and 1-hop callees full. | **High-Density Signal.** The model sees 100% of the type contracts without drowning in unrelated loops. |
185
- | **Terminal Log Poisoning**<br>`npm test` or `pytest` fails and dumps 4,000 lines of stack traces and lockfile diffs. The model panics and rewrites unrelated code. | **Command Sanitizer** (`src/command_sanitizer.py`) snips the matrix down to the exact failing assertion line and call frame. | **Laser Focus.** The agent fixes the actual bug instead of hallucinating workarounds for log noise. |
186
- | **The 5-Attempt Doom Loop**<br>Agent tries a broken fix, fails, tries the exact same broken fix again, and oscillates until your session context limit catches fire. | **Anti-Stuck Loop Guard** (`src/loop_detector.py`) intercepts repeated tool calls and cyclic edits in flight. | **No Cascading Regressions.** The loop is halted before the agent can butcher working modules. |
187
- | **Vague Human Prompts**<br>*"Hey, fix the auth bug but don't break the cache or whatever."* The model takes creative liberties and breaks three other files. | **TOCP Intent Compactor** (`src/compactor.py`) distills messy instructions into explicit S-Expressions with hard constraint boundaries. | **Zero Ambiguity.** The model executes `(DEBUG auth.ts [jwt] "fix 401 token expiry")` with strict parameter bounds. |
188
- | **Unsafe Agent Actions & Secret Leaks**<br>Agent hardcodes fallback API keys, disables SSL validation (`verify=False`), uses SQL f-strings, or runs `git add .` staging `.env` files. | **TokenSafe Guard** (`src/guard.py`) audits and blocks hazardous code edits and terminal commands before execution. | **Zero-Leak Workspace.** Hardcoded credentials, SQLi, and catastrophic deletions (`rm -rf /`) are intercepted in real time. |
157
+ | **"Lost in the Middle" context fade**<br>An agent reads a 2,000-line file to change one 10-line helper, forgets imports, and invents methods. | **AST Skeletonizer** (`src/slicer.py`) folds inert bodies into typed signatures while keeping the target symbol and 1-hop callees intact. | **Focused signal.** The model keeps full type contracts without drowning in unrelated logic. |
158
+ | **Terminal log flooding**<br>`npm test` or `pytest` fails and dumps 4,000 lines of stack traces and lockfile diffs into context. | **Command Sanitizer** (`src/command_sanitizer.py`) strips lockfile noise and trims output to the failing assertion and stack frame. | **Root-cause fixes.** The agent repairs the actual bug instead of rewriting unrelated files. |
159
+ | **5-attempt retry loops**<br>An agent repeats the same broken edit five times in a row until the context budget runs dry. | **Loop Guard** (`src/loop_detector.py`) detects repeated identical tool calls and halts the cycle. | **Fewer regressions.** Stuck loops stop before damaging working modules. |
160
+ | **Verbose prompts & token arbitrage**<br>Loose phrasing like *"fix auth without breaking cache"* leads to wide, risky rewrites. | **TOCP Intent Compactor** (`src/compactor.py`) distills instructions into compact S-expressions (`-40% to -70%`) with strict scope bounds. | **Clear scope.** Example: `(DEBUG auth.ts [jwt] "fix 401 token expiry")`. |
161
+ | **Unsafe edits & secret leaks**<br>An agent hardcodes fallback keys, sets `verify=False`, builds SQL with f-strings, or runs `git add .` with `.env` present. | **TokenSafe Guard** (`src/guard.py`) audits writes and shell commands locally before execution. | **Protected repositories.** Credentials, SQLi patterns, and destructive commands are blocked locally. |
189
162
 
190
163
  ---
191
164
 
192
- ## 🌐 Polyglot Zero-Loss AST Engine (10+ Languages)
165
+ ## Polyglot AST Engine (10+ Languages)
193
166
 
194
- TokenSafe is built from the ground up to support modern polyglot monorepos. Its zero-LLM deterministic AST state machine folds non-target function bodies in **< 30ms** with zero external dependencies, while preserving active symbols and 1-hop dependencies with full executable bodies.
167
+ TokenSafe supports modern polyglot monorepos out of the box. Its deterministic local AST state machine folds non-target function bodies in **< 30ms** with zero external runtime dependencies, while preserving target symbols and 1-hop dependencies with full executable bodies.
195
168
 
196
169
  ### Supported Language Matrix
197
170
 
@@ -204,170 +177,150 @@ TokenSafe is built from the ground up to support modern polyglot monorepos. Its
204
177
  | **Java & C#** | `.java`, `.cs` | Classes, records, methods with access modifiers (`public`, `protected`, `static`, `async`, `override`), generic return types (`Task<T>`, `List<E>`), `throws` | Method bodies folded; classes and interfaces remain structural |
205
178
  | **C & C++** | `.c`, `.cpp`, `.cc`, `.cxx`, `.h`, `.hpp` | Classes, structs, namespaces, scoped methods `ClassName::method`, `const`, `noexcept`, `override`, destructors | Functions folded; namespace and class hierarchies preserved |
206
179
  | **PHP, Kotlin, Swift** | `.php`, `.kt`, `.kts`, `.swift` | Classes, `function`, `fun`, `func` declarations with visibility modifiers | Function bodies folded into `{ /* ... */ }` |
207
- | **CSS, SCSS, LESS, Tailwind** | `.css`, `.scss`, `.sass`, `.less` | **Design tokens (`:root`, `@theme`, CSS variables, `$var`, `@var`) 100% preserved**, container queries (`@media`, `@supports`, `@container`, `@layer`) kept open | Component selectors, `@keyframes`, and mixins folded into `{ /* ... */ }` unless matching `target_symbol` |
180
+ | **CSS, SCSS, LESS, Tailwind** | `.css`, `.scss`, `.sass`, `.less` | **Design tokens (`:root`, `@theme`, CSS variables, `$var`, `@var`) preserved in full**, container queries (`@media`, `@supports`, `@container`, `@layer`) kept open | Component selectors, `@keyframes`, and mixins folded into `{ /* ... */ }` unless matching `target_symbol` |
208
181
 
209
- ### Key Engine Guarantees:
210
- - **Design Token & Palette Preservation**: When skeletonizing stylesheets, TokenSafe **always preserves all design tokens** (`:root { ... }`, Tailwind v4 `@theme { ... }`, CSS variables `--*`, SCSS `$vars`) so agents never hallucinate colors, radii, or fonts, while pruning 90%+ of bloated component styles.
211
- - **Strict Arrow Function Parser**: Arrow functions strictly require `=>` before any `{` can be considered a function body; destructuring parameters (`({ a, b }: Props) =>`) and parenthesized ternary expressions (`const x = (flag) ? { a: 1 } : { b: 2 }`) are never corrupted.
212
- - **Directory Tree Optimization (`tokensafe:list_dir`)**: Replaces verbose and noisy terminal `ls -la` commands with a compact, depth-bounded markdown tree without permissions, timestamps, or lockfiles.
213
- - **Graph-Guided Neighborhood Slicing**: When your AI agent inspects a function or component (via `tokensafe:smart_read_file(path, symbol="Target")`), TokenSafe automatically keeps the full implementation of the target **and its 1-hop callees/callers**, while collapsing all unrelated code.
214
- - **Comment & String Bracket Immunity**: Multi-line block comments (`/* ... */`, JSX `{/* ... */}`), template strings (`` `${...}` ``), and escaped quotes are tracked in a dedicated token lexer (`BraceLexer`), guaranteeing zero bracket desynchronization.
215
- - **Control-Flow Statement Immunity**: Statements like `if (...)`, `catch (err) {`, `for (...)`, and `while (...)` are strictly protected and never corrupted into placeholders.
182
+ ### Key Engine Guarantees
183
+ - **Design Token & Palette Preservation**: When skeletonizing stylesheets, TokenSafe keeps design tokens (`:root { ... }`, Tailwind v4 `@theme { ... }`, CSS variables `--*`, SCSS `$vars`) intact so agents never invent colors, radii, or font rules.
184
+ - **Strict Arrow Function Parser**: Arrow functions require `=>` before any `{` counts as a function body. Destructuring parameters (`({ a, b }: Props) =>`) and parenthesized ternary expressions (`const x = (flag) ? { a: 1 } : { b: 2 }`) are left intact.
185
+ - **Directory Tree Optimization (`tokensafe:list_dir`)**: Replaces verbose `ls -la` output with a compact, depth-bounded tree without permissions, timestamps, or lockfiles.
186
+ - **Graph-Guided Neighborhood Slicing**: Calling `tokensafe:smart_read_file(path, symbol="Target")` preserves the target body **and its 1-hop callees/callers** while folding unrelated code.
187
+ - **Comment & String Bracket Immunity**: Multi-line block comments (`/* ... */`, JSX `{/* ... */}`), template strings (`` `${...}` ``), and escaped quotes are tracked by `BraceLexer` so brackets never desynchronize.
188
+ - **Control-Flow Immunity**: Statements like `if (...)`, `catch (err) {`, `for (...)`, and `while (...)` are protected from folding.
216
189
 
217
190
  ---
218
191
 
219
- ## 🛡️ The Hidden Context Killer: MCP Tool Schema Bloat
192
+ ## The Hidden Context Tax: MCP Tool Schema Bloat
220
193
 
221
- Why do AI coding agent quotas (like Antigravity's **5-Hour Limit** or Claude/OpenAI monthly token budgets) evaporate after just a few prompts?
194
+ Coding agent quotas (such as 5-hour session windows or monthly token budgets) often drain after a few prompts before real work starts.
222
195
 
223
196
  ### The Hidden System Prompt Tax
224
- Whenever an MCP server is configured in your editor (Cursor, Claude Desktop, Antigravity, Windsurf), **the complete JSON schema for every single tool is injected into the LLM's system prompt on EVERY API TURN** — even if you never use that tool!
197
+ Whenever an MCP server is enabled in an editor (Cursor, Claude Desktop, Antigravity, Windsurf), **the full JSON schema for every tool is injected into the system prompt on every turn**, even when unused:
225
198
 
226
- ```
199
+ ```text
227
200
  ┌────────────────────────────────────────────────────────────────────────┐
228
201
  │ SYSTEM PROMPT ANATOMY (EVERY SINGLE TURN) │
229
202
  ├────────────────────────────────────────────────────────────────────────┤
230
203
  │ Base System Instructions ~1,500 tokens │
231
204
  │ Active Workspace Skills & Prompts ~8,000 tokens │
232
205
  │ Regular MCP Tools (context7, prisma, etc.) ~800 tokens │
233
- │ 🚨 Heavy MCP Tools (200+ schemas from cloud/re tools) ~6,000 tokens │
206
+ │ [!] Heavy MCP Tools (200+ schemas from large servers) ~6,000 tokens │
234
207
  ├────────────────────────────────────────────────────────────────────────┤
235
- │ TOTAL HIDDEN BASE TAX BEFORE YOU TYPE A SINGLE CHARACTER: │
236
- │ 🔥 ~16,300 tokens PER TURN × 15 turns = 244,500 tokens burned! │
208
+ │ TOTAL HIDDEN BASE TAX BEFORE YOUR FIRST LINE OF CODE: │
209
+ │ ~16,300 tokens PER TURN x 15 turns = 244,500 tokens burned │
237
210
  └────────────────────────────────────────────────────────────────────────┘
238
211
  ```
239
212
 
240
- - **1 Server with 50 tools** = **~1,500 – 2,500 tokens** of static tax on every turn.
241
- - **1 Server with 200+ tools** = **~5,000 – 10,000 tokens** per turn!
242
- - In a 15-turn coding task, **75,000 to 150,000 tokens** are burned on tool schemas alone.
213
+ - **1 server with 50 tools** = **~1,500 to 2,500 tokens** of static tax per turn.
214
+ - **1 server with 200+ tools** = **~5,000 to 10,000 tokens** per turn.
215
+ - Across a 15-turn coding session, **75,000 to 150,000 tokens** go solely to tool schemas.
243
216
 
244
- ### How TokenSafe Eliminates MCP Bloat:
245
- 1. **`tokensafe doctor` (Context Tax Auditor)**: Scans all configured MCP servers and active skills, measures the exact token overhead per turn, and flags servers with $\ge 40$ tools as `CRITICAL BLOAT`.
246
- 2. **1-Click MCP Management**: Instantly toggle heavy servers without editing JSON files manually:
217
+ ### How TokenSafe Cuts MCP Overhead
218
+ 1. **`tokensafe doctor` (Environment Auditor)**: Scans configured MCP servers and skills, measures token overhead per turn, and flags servers with $\ge 40$ tools as `CRITICAL BLOAT`.
219
+ 2. **1-Click MCP Toggle**: Enable or disable heavy servers without manual JSON edits:
247
220
  ```bash
248
- tokensafe mcp disable rea # Prunes 208 schemas from system prompt
249
- tokensafe mcp enable rea # Re-enables when actively needed
221
+ tokensafe mcp disable rea # Prunes heavy schemas from the system prompt
222
+ tokensafe mcp enable rea # Re-enables when needed
250
223
  ```
251
- 3. **PreInvocation Bloat Alerts**: Live in-chat warning badges in the IDE when critical MCP bloat is detected on session start.
252
- 4. **Data Retention & Compact Rollups**: Automatic rolling-window event cleanup (`tokensafe prune` and `tokensafe vacuum`) prevents SQLite telemetry from ballooning on disk.
224
+ 3. **Session Start Bloat Alerts**: Surfaces warning badges in chat when heavy MCP bloat is active.
225
+ 4. **Telemetry Retention (`tokensafe prune` / `vacuum`)**: Compacts SQLite metrics with rolling-window rollups, reducing local database footprint by up to 40%.
253
226
 
254
227
  ---
255
228
 
256
- ## ⚡ TokenSafe vs. Graphify: Dynamic In-Flight Defense vs. Static Reports
229
+ ## TokenSafe vs. Graphify: In-Flight Defense vs. Static Reports
257
230
 
258
- How TokenSafe complements or supersedes static graph tools like **Graphify** (`graphify-labs/graphify`):
231
+ How TokenSafe complements or replaces static graph tools like **Graphify** (`graphify-labs/graphify`):
259
232
 
260
233
  | Capability | Graphify | TokenSafe |
261
234
  |---|---|---|
262
- | **Primary Focus** | Static knowledge graph reports & MCP queries | **In-flight real-time token compression & defense** |
263
- | **Indexing Cost** | Expensive LLM tokens / heavy graph extraction | **0 tokens, 100% deterministic local AST (< 30ms)** |
264
- | **Execution Latency** | Offline / CLI-initiated build | **Sub-millisecond inline proxy & lifecycle hooks** |
265
- | **Active Slicing** | Static file output (`GRAPH_REPORT.md`) | **Dynamic call-graph skeletonization (85–92% saved)** |
266
- | **Multi-Project Workspace** | Requires manual directory targeting | **Auto-detects project roots per file on the fly** |
267
- | **Agent Prompt Optimization** | None | **TOCP S-Expression prompt distillation (-40% to -70%)** |
268
- | **Safety & Runaway Prevention** | None | **Output rewrite guard, loop detector, secret scrubbing** |
235
+ | **Primary Focus** | Static knowledge graph reports & MCP queries | **In-flight real-time context slicing & security guardrails** |
236
+ | **Indexing Cost** | Requires LLM tokens / offline graph build | **0 tokens, deterministic local AST (< 30ms)** |
237
+ | **Execution Latency** | Offline CLI build step | **Sub-millisecond inline proxy & lifecycle hooks** |
238
+ | **Active Slicing** | Static report (`GRAPH_REPORT.md`) | **Dynamic call-graph skeletonization (85% to 92% fewer file tokens)** |
239
+ | **Multi-Project Workspace** | Manual directory targeting | **Detects project roots per file on the fly** |
240
+ | **Prompt Distillation** | None | **TOCP S-expression compaction (-40% to -70%)** |
241
+ | **Safety & Runaway Prevention** | None | **Guardrails, Output Guard, Loop Guard, secret redaction** |
269
242
 
270
- > **Complements & Replaces**: If you already use Graphify for repository mapping, TokenSafe works alongside it by compressing real-time agent tool reads on the wire. Or use TokenSafe standalone for a zero-configuration, zero-cost, sub-30ms architecture engine out of the box.
243
+ > **Complements & Replaces**: If you already maintain Graphify reports for architecture docs, TokenSafe still slices live file reads on the wire. Standalone, TokenSafe needs no pre-indexing step.
271
244
 
272
245
  ---
273
246
 
274
- ## 🛡️ TokenSafe Guard: Proactive Agent Security & Hygiene Shield
247
+ ## TokenSafe Guard: Local Security and Hygiene Shield
275
248
 
276
- Autonomous AI coding agents operate with powerful tool access—executing arbitrary shell commands, modifying critical source files, and interacting with remote systems. Without proactive guardrails, models frequently introduce subtle security vulnerabilities, bypass TLS safeguards, or leak sensitive credentials directly into git repositories.
249
+ Coding agents hold shell execution and file write access across your repositories. Passive prompt rules fade over multi-turn sessions, leaving code vulnerable to leaked keys, TLS bypasses, or unsafe staging.
277
250
 
278
- **TokenSafe Guard** (`src/guard.py`) intercepts and audits agent tool calls in real time before execution, enforcing strict code hygiene and repository safety with zero token overhead:
251
+ **TokenSafe Guard** (`src/guard.py`) audits tool calls locally before disk or git execution with zero token overhead:
279
252
 
280
253
  ### 1. Secret & Private Key Leak Prevention (Zero Hardcoded Fallbacks)
281
- - **Live Provider Secrets**: Blocks hardcoded Stripe live keys, AWS access keys, OpenAI project keys, Anthropic tokens, and GitHub personal access tokens anywhere in code.
282
- - **Default Fallback Hardcoding**: AI models frequently write `os.environ.get("DB_PASSWORD", "prod_secret_123")` or `process.env.JWT_SECRET || "production_secret"`. TokenSafe Guard strictly blocks non-placeholder fallbacks for sensitive environment variable names.
283
- - **Raw Hexadecimal Private Keys**: Blocks 64-character raw hex private keys and raw PEM private key blocks assigned directly in source code.
254
+ - **Live Provider Secrets**: Blocks hardcoded Stripe live keys, AWS access keys, OpenAI project keys, Anthropic tokens, and GitHub personal access tokens.
255
+ - **Default Fallback Hardcoding**: Rejects non-placeholder defaults such as `os.environ.get("DB_PASSWORD", "prod_secret_123")` or `process.env.JWT_SECRET || "production_secret"`.
256
+ - **Raw Private Keys**: Blocks 64-character raw hex keys and raw PEM private key blocks in source files.
284
257
 
285
258
  ### 2. Insecure SSL/TLS Verification Bypass Shield
286
- - AI models frequently add `verify=False` in Python (`requests`, `httpx`, `aiohttp`, `urllib3`) or `rejectUnauthorized: false` / `NODE_TLS_REJECT_UNAUTHORIZED='0'` in Node.js when troubleshooting local or self-signed API connections.
287
- - TokenSafe Guard blocks SSL/TLS verification bypasses in production and non-test code, preventing Man-in-the-Middle (MitM) exposure.
259
+ - Blocks `verify=False` in Python (`requests`, `httpx`, `aiohttp`, `urllib3`) and `rejectUnauthorized: false` or `NODE_TLS_REJECT_UNAUTHORIZED='0'` in Node.js non-test code.
288
260
 
289
261
  ### 3. Raw SQL Injection Prevention
290
- - Blocks dynamic string interpolation inside query execution calls:
291
- - Python: `cursor.execute(f"SELECT ... {user_id}")` and `cursor.execute("SELECT ... %s" % val)`
292
- - JavaScript / TypeScript: `db.query(\`SELECT ... ${id}\`)`
293
- - Enforces parameterized queries with bound placeholders (`?`, `%s`, `$1`).
262
+ - Blocks string interpolation inside query execution calls (`cursor.execute(f"SELECT ... {user_id}")`, `cursor.execute("SELECT ... %s" % val)`, `db.query(\`SELECT ... ${id}\`)`).
263
+ - Enforces parameterized queries (`?`, `%s`, `$1`).
294
264
 
295
265
  ### 4. Dangerous CORS Wildcard with Credentials Shield
296
- - Intercepts fatal CORS misconfigurations combining `Access-Control-Allow-Origin: *` with `Access-Control-Allow-Credentials: true`.
297
- - Browsers reject this combination by specification, and it creates severe cross-origin security exposures.
266
+ - Intercepts configurations combining `Access-Control-Allow-Origin: *` with `Access-Control-Allow-Credentials: true`.
298
267
 
299
268
  ### 5. Git Staging Protection for Sensitive Files
300
269
  - **Explicit Staging**: Blocks `git add .env`, `git add .env.*`, `git add id_rsa`, and `git add *.pem`.
301
- - **Blanket Staging Shield**: Intercepts blanket `git add .`, `git add -A`, and `git commit -a` commands whenever unignored `.env` files or private keys are present in the working tree.
270
+ - **Blanket Staging Shield**: Intercepts `git add .`, `git add -A`, and `git commit -a` whenever unignored `.env` files or private keys exist in the working tree.
302
271
 
303
272
  ### 6. Destructive Shell & Data Exfiltration Prevention
304
- - **Destructive Deletion**: Blocks catastrophic commands like `rm -rf /`, `rm -rf ~`, `rm -rf *`, and `rm -rf --no-preserve-root`.
305
- - **Network Exfiltration**: Blocks shell commands piping sensitive local files to remote endpoints (e.g. `curl -d @.env https://...` or `wget --post-file=id_rsa`).
273
+ - **Destructive Deletion**: Blocks commands such as `rm -rf /`, `rm -rf ~`, `rm -rf *`, and `rm -rf --no-preserve-root`.
274
+ - **Network Exfiltration**: Blocks commands piping sensitive local files to remote URLs (such as `curl -d @.env https://...` or `wget --post-file=id_rsa`).
306
275
 
307
- ### 7. Package Typosquatting & Hallucination Early Warning
308
- - Analyzes `pip install`, `npm install`, `pnpm add`, `yarn add`, and `bun add` commands for known malicious typosquats (e.g., `python-crypto`, `loadsh`, `coookie-parser`, `mongose`).
309
- - Emits proactive in-chat warning badges (`⚠️ TokenSafe Guard Warning: ...`) without blocking custom packages, preserving developer velocity.
276
+ ### 7. Package Typosquatting Early Warning
277
+ - Checks `pip install`, `npm install`, `pnpm add`, `yarn add`, and `bun add` for known typosquat packages (`python-crypto`, `loadsh`, `coookie-parser`, `mongose`) and prints a `TokenSafe Guard Warning` badge.
310
278
 
311
- Whenever a dangerous operation is blocked, TokenSafe Guard emits an actionable notification:
279
+ When an operation is blocked, TokenSafe Guard returns an explicit message:
312
280
  `🛡️ **TokenSafe Guard**: <reason>`
313
281
 
314
282
  ---
315
283
 
316
- ## 🤖 Prompt Distillation: Managed Cloud & Three-Tier Cache Architecture
284
+ ## Prompt Distillation: Managed Cloud and Three-Tier Cache
317
285
 
318
- TokenSafe features an intelligent prompt compiler that distills verbose developer prompts into lean TOCP S-Expressions (`-40% to -70% tokens`).
286
+ TokenSafe distills verbose prompts into compact TOCP S-expressions (`-40% to -70%` tokens).
319
287
 
320
288
  ### 1. Zero-Config Managed Cloud vs. Self-Hosted Docker BYOK
321
289
 
322
- | Deployment Mode | Supported Tier | Distillation Engine | Required API Keys | Cost & Setup |
290
+ | Deployment Mode | Supported Tier | Distillation Engine | Required API Keys | Setup |
323
291
  |---|---|---|---|---|
324
- | **TokenSafe Cloud (SaaS)** ⚡ | **Solo Developer & Team** | **Google Gemini Flash-Lite** (`gemini-flash-lite-latest`) | **None (Zero Keys Required)** | **Included in subscription** (0ms config, unlimited neural distillation) |
325
- | **Local Regex Compactor** | **Community (Free)** | **Deterministic Multilingual Regex** (9 languages) | **None** | **100% Free** (0ms latency, 0 external tokens, 500k tokens/mo) |
326
- | **Self-Hosted Docker** 🐳 | **Enterprise / Team** | **BYOK Multi-Provider** (Gemini, DeepSeek, OpenAI, Claude) | `GEMINI_API_KEY`, `DEEPSEEK_API_KEY`, etc. | Private VPC on-premise container deployment |
327
-
328
- > **Zero Configuration for Solo & Team**: You do not need to register for Google AI Studio, OpenAI, or DeepSeek API accounts. TokenSafe Cloud handles high-throughput neural distillation automatically with enterprise-grade sub-second turnaround.
292
+ | **TokenSafe Cloud (SaaS)** | **Engineering Team & Solo** | **Google Gemini Flash-Lite** (`gemini-flash-lite-latest`) | **None (Zero keys needed)** | Included in subscription, ready immediately |
293
+ | **Local Regex Compactor** | **Developer Sandbox (Free)** | **Deterministic Multilingual Regex** (9 languages) | **None** | Local execution only (`500,000` tokens/mo) |
294
+ | **Self-Hosted Docker** | **Enterprise & VPC** | **BYOK Multi-Provider** (Gemini, DeepSeek, OpenAI, Claude) | `GEMINI_API_KEY`, `DEEPSEEK_API_KEY`, etc. | Private VPC container deployment |
329
295
 
330
- ### 2. Token Arbitrage Guard & Three-Tier Cache Architecture
296
+ > **Zero External Keys for Team & Solo**: Developers never have to create or manage personal Google, OpenAI, or DeepSeek billing accounts to use cloud prompt distillation.
331
297
 
332
- To prevent compiler cost overhead from exceeding token savings, TokenSafe applies a 3-stage defense:
298
+ ### 2. Token Arbitrage Guard & Three-Tier Cache
333
299
 
334
- 1. **Smart Gating Threshold (`llm_distill_min_tokens: 100`)**: Prompts under 100 tokens bypass cloud calls entirely and use instant zero-cost local regex heuristics ($0$ tokens, $< 1\text{ms}$).
335
- 2. **Output Token Ceiling (`distill_max_tokens: 60`)**: Caps distillation output at 60 tokens, eliminating verbose chain-of-thought inflation and token arbitrage loss.
336
- 3. **Three-Tier Distillation Cache Hierarchy**:
337
- - **L1 (In-Memory LRU)**: Sub-millisecond instant hit for active developer session loops.
338
- - **L2 (Persistent SQLite)**: Stores SHA-256 normalized prompt hashes in `data/metrics.db` across agent restarts. Recurring commands (`git commit`, `run tests`, `fix lint`) cost 0 tokens.
339
- - **L3 (Shared Team Cache)**: *Team Tier.* Synchronizes compiled prompt intents and AST skeletons to TokenSafe Cloud (`/api/team/cache`). When one engineer or CI runner executes a prompt or reads a file, all teammates immediately hit warm 0ms cache.
300
+ To keep distillation overhead lower than the tokens it saves:
301
+ 1. **Smart Gating (`llm_distill_min_tokens: 100`)**: Prompts under 100 tokens stay strictly local via regex heuristics ($0$ LLM tokens, $< 1\text{ms}$).
302
+ 2. **Output Token Ceiling (`distill_max_tokens: 60`)**: Caps compiled output at 60 tokens to prevent compiler arbitrage loss.
303
+ 3. **Three-Tier Cache**:
304
+ - **L1 (In-Memory LRU)**: Sub-millisecond hits inside active sessions.
305
+ - **L2 (Persistent SQLite)**: Stores normalized SHA-256 prompt hashes in `data/metrics.db` across restarts so repeated workflows (`git commit`, `run tests`, `fix lint`) cost 0 tokens.
306
+ - **L3 (Shared Team Cache)**: *Team Tier.* Syncs distilled intents and AST skeletons across teammates and CI runners (`/api/team/cache`) for warm 0ms team cache hits.
340
307
 
341
- ### 3. Configuration & Provider Inspection
308
+ ### 3. Provider & Cache Inspection
342
309
 
343
- Check your license status, active distillation mode, and cache stats anytime:
310
+ Inspect your active license tier, distillation mode, and cache stats anytime:
344
311
  ```bash
345
312
  tokensafe providers
346
313
  ```
347
314
 
348
- For custom self-hosted environments (`TOKENSAFE_SELF_HOSTED=1`), configure your preferred provider in `data/config.json`:
349
- ```json
350
- {
351
- "preferred_provider": "gemini",
352
- "gemini_api_key": "YOUR_GEMINI_API_KEY",
353
- "gemini_model": "gemini-flash-lite-latest",
354
- "llm_distill_min_tokens": 100,
355
- "distill_max_tokens": 60
356
- }
357
- ```
358
-
359
- Check active providers and cache stats anytime:
360
- ```bash
361
- tokensafe providers
362
- ```
315
+ Self-hosted VPC deployment (BYOK provider keys, zero-telemetry / air-gapped isolation) is part of the **Enterprise & VPC** plan — deployment and support are handled by the TokenSafe engineering team. Contact `corp@tokensafe.dev`.
363
316
 
364
317
  ---
365
318
 
366
- ## 📊 Zero-Loss SWE-bench Benchmark Results
319
+ ## Calibrated SWE-bench Benchmark Results
367
320
 
368
- 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**):
321
+ Reference run across 8 production engineering scenarios (`131,552` baseline tokens down to `7,263` tokens, `-94.5%` net token reduction, `+28.1%` turn latency speedup with `100%` accuracy retention):
369
322
 
370
- > 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).
323
+ > Token counts vary by ±1% between runs because prompt compaction is **measured live** on every run while baseline sizes are modeled constants. See [METRICS.md](METRICS.md) for the full simulation disclosure and measured-vs-modeled breakdown.
371
324
 
372
325
  | Benchmark Scenario | Task Complexity | Baseline Tokens | TokenSafe Tokens | Reduction | Turn Speedup | Accuracy |
373
326
  |---|---|---|---|---|---|---|
@@ -380,36 +333,38 @@ Reference run across 8 real-world production software engineering scenarios (131
380
333
  | **OAuth JWT Expiration Triage** | Controller bug investigation | 3,757 | **401** | **-89.3%** | **3 ➔ 2 turns (+33%)** | 100% Pass |
381
334
  | **CI Test Failure Extraction** | Full test log & stack trace | 5,009 | **1,127** | **-77.5%** | 3 turns | 100% Pass |
382
335
 
383
- > **How to read these numbers:** the benchmark is a **simulated** harness — the compression ratios are real, deterministic tool-output deltas on real files, while the "turn speedup" column models agent behavior. We never present simulated numbers as metered ones. Every production event TokenSafe records is labeled `measured` (literally metered I/O reduction) or `estimated` (counterfactual baseline) — see **[METRICS.md](METRICS.md)** for the full methodology, and the dashboard exposes the `measured` / `estimated` split alongside every total.
336
+ > **How to read these numbers:** This benchmark is a **simulated** harness. Compression ratios are real, deterministic tool-output deltas on real files, while the "turn speedup" column models agent behavior. Production events in TokenSafe are explicitly labeled `measured` or `estimated` (see [METRICS.md](METRICS.md)).
384
337
 
385
338
  ---
386
339
 
387
- ## 📐 Metrics Honesty
340
+ ## Metrics Honesty
388
341
 
389
342
  TokenSafe labels every savings event as one of:
390
343
 
391
- - **`measured`** — the model literally received fewer bytes than the tool produced (sliced file reads, filtered command output, skeletons). The delta is a fact.
392
- - **`estimated`** — the model received a compact artifact and "saved" is counted against a reasonable alternative (architecture graph vs. a full crawl; folded history digest, which is *injected* while the raw history remains in context).
344
+ - **`measured`**: the model literally received fewer bytes than the tool produced (sliced file reads, filtered command output, AST skeletons).
345
+ - **`estimated`**: the model received a compact artifact and saved tokens are counted against a reasonable baseline (architecture graph vs. a full repo crawl; folded history digest injected while raw history stays in context).
393
346
 
394
- Sums on the dashboard and landing page always show the split (`X metered · Y est.`). When a live number is unavailable we render `—`, never a fabricated constant. USD figures are derived estimates (`tokens × $1.5 / 1M`), not invoices. Details: **[METRICS.md](METRICS.md)**.
347
+ Totals on the dashboard and landing page always display the split (`X metered · Y est.`). When a live metric is missing, the UI shows `—` rather than a placeholder number. USD figures are derived approximations (`tokens × $1.5 / 1M`), not provider invoices. Full contract: **[METRICS.md](METRICS.md)**.
395
348
 
396
349
  ---
397
350
 
398
- ## 💎 Pricing & 7-Day Team Trial
351
+ ## Pricing and 7-Day Team Trial
352
+
353
+ TokenSafe follows an open-core model: verify local context savings and guardrails on your own repo first, then roll out team caching, org policies, and per-seat ROI.
399
354
 
400
- | Tier | Price | Monthly Token Savings | Highlights |
355
+ | Plan | Price | Monthly Allowance | Included Capabilities |
401
356
  |---|---|---|---|
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 |
357
+ | **Developer Sandbox** | **$0** forever | **500,000 tokens / mo** | 9-Language Local Regex Compactor, Local AST Slicer CLI, Local Secret & `.env` Guard, SQLite & Terminal Dashboard |
358
+ | **Engineering Team** *(Recommended)* | **$29 / seat / mo** *(~$24 / seat / mo billed $290/yr)* | **Unlimited** | **7-Day Free Trial**, **Shared Team Cache (L3 Monorepo Hits)**, Org-Wide Guard & Git Leak Shield, Friday Per-Seat ROI Digest, Centralized Ed25519 Seat Provisioning & Revoke, Managed Cloud Distillation (zero keys needed) |
359
+ | **Enterprise & VPC** | **Custom** | **Unlimited** | Org Audit Log (Guard forensics: who / what / when, CSV & SIEM export), Central Guard Policies, Self-Hosted VPC Proxy (Private BYOK), Zero-Telemetry / Air-Gapped Mode, SAML / OIDC SSO, Dedicated Onboarding & SLA |
405
360
 
406
- *Working solo? [Individual Solo plans](https://tokensafe.dev#pricing) are available from **$9 / mo** ($89 / yr).*
361
+ *Working solo? [Individual Solo plans](https://tokensafe.dev#pricing) start at **$9 / mo** ($89 / yr).*
407
362
 
408
- 👉 **[Start your 7-Day Free Trial on our website](https://tokensafe.dev#pricing)**
363
+ **[Start a 7-Day Team Trial](https://tokensafe.dev#pricing)**
409
364
 
410
365
  ---
411
366
 
412
- ## 🛠️ CLI Quickstart
367
+ ## CLI Quickstart
413
368
 
414
369
  ```bash
415
370
  # View live savings dashboard in your terminal
@@ -442,9 +397,12 @@ Run `tokensafe html` to view interactive browser dashboard.
442
397
  ```
443
398
 
444
399
  ```bash
445
- # Open interactive local Apple dark-mode browser dashboard
400
+ # Open interactive local dark-mode browser dashboard
446
401
  tokensafe html
447
402
 
403
+ # Export a markdown savings report
404
+ tokensafe markdown
405
+
448
406
  # Test prompt compression on custom input in real time
449
407
  tokensafe test "please fix the validate_token method in src/auth.py so that it checks jwt expiration and returns boolean"
450
408
 
@@ -472,92 +430,38 @@ tokensafe prune
472
430
  # Generate or preview Friday team ROI digest email
473
431
  tokensafe digest
474
432
 
475
- # Run the SWE-bench zero-loss verification suite
433
+ # Run the SWE-bench verification suite
476
434
  tokensafe benchmark
477
435
 
436
+ # Run the unit test suite (compact failure report, full: --traceback / -v)
437
+ tokensafe tests
438
+
478
439
  # Run the local transparent AI proxy (0.0.0.0:8765/v1)
479
440
  tokensafe proxy
480
441
 
481
- # Activate your Pro License key (TS2 Asymmetric Ed25519 Key)
442
+ # Activate your Team or Solo license key (TS2 Asymmetric Ed25519 Key)
482
443
  tokensafe activate TS2.eyJlbWFpbCI6...
483
444
  ```
484
445
 
485
446
  ---
486
447
 
487
- ## 🐳 Docker Deployment (Multi-Provider Support)
488
-
489
- TokenSafe is fully containerized with a hardened multi-stage production Docker image, non-root security (`uid: 1000`), and native multi-provider LLM routing.
490
-
491
- ### 1. Multi-Provider Environment Keys
492
-
493
- You can configure any or all of your preferred LLM provider keys:
494
-
495
- | Environment Variable | Provider Supported | Default Model |
496
- |---|---|---|
497
- | `GEMINI_API_KEY` | Google Gemini (Fastest / Lowest Cost) | `gemini-flash-lite-latest` |
498
- | `PREFERRED_PROVIDER` | Explicit provider priority (`gemini`, `deepseek`, etc.) | `gemini` |
499
- | `DEEPSEEK_API_KEY` | DeepSeek API | `deepseek-chat` |
500
- | `OPENAI_API_KEY` | OpenAI API | `gpt-4o-mini` |
501
- | `ANTHROPIC_API_KEY` | Anthropic Claude | `claude-3-5-haiku-20241022` |
502
- | `TOKENSAFE_UPSTREAM_KEY` | Unified / Custom Gateway | Custom Upstream |
503
-
504
- ### 2. Docker Compose Quickstart
505
-
506
- Run TokenSafe as a centralized microservice or team gateway:
507
-
508
- ```yaml
509
- version: '3.8'
510
-
511
- services:
512
- tokensafe:
513
- build:
514
- context: .
515
- dockerfile: Dockerfile
516
- container_name: tokensafe
517
- restart: unless-stopped
518
- ports:
519
- - "8765:8765"
520
- environment:
521
- - TOKENSAFE_HOST=0.0.0.0
522
- - TOKENSAFE_PORT=8765
523
- - TOKENSAFE_DATA_DIR=/app/data
524
- # Choose your provider(s):
525
- - DEEPSEEK_API_KEY=${DEEPSEEK_API_KEY:-}
526
- - OPENAI_API_KEY=${OPENAI_API_KEY:-}
527
- - ANTHROPIC_API_KEY=${ANTHROPIC_API_KEY:-}
528
- - GEMINI_API_KEY=${GEMINI_API_KEY:-}
529
- - TOKENSAFE_LICENSE_KEY=${TOKENSAFE_LICENSE_KEY:-}
530
- volumes:
531
- - ./data:/app/data
532
- healthcheck:
533
- test: ["CMD", "python3", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8765/api/health')"]
534
- interval: 30s
535
- timeout: 5s
536
- retries: 3
537
- ```
538
-
539
- Start the container in detached mode:
540
- ```bash
541
- docker compose up -d
542
- ```
448
+ ## Self-Hosted Docker Deployment
543
449
 
544
- ### 3. Verification & Live SSE Streaming
450
+ The repository ships a hardened multi-stage `Dockerfile` (non-root `uid: 1000`) and a `docker-compose.yml` for containerized runs, and the local proxy is available directly via `tokensafe proxy` (`0.0.0.0:8765/v1`).
545
451
 
546
- - **Health check**: `curl http://localhost:8765/api/health`
547
- - **Live SSE Event Stream**: `curl -N http://localhost:8765/api/events`
548
- - **Point your AI Agents**: Configure your IDE or Agent to use `http://localhost:8765/v1` as the upstream base URL.
452
+ Supported, production-grade self-hosting — private VPC, BYOK provider keys (Gemini, DeepSeek, OpenAI, Claude), zero-telemetry / air-gapped mode, SAML/OIDC SSO — is part of the **Enterprise & VPC** plan and is deployed together with our engineering team: [corp@tokensafe.dev](mailto:corp@tokensafe.dev).
549
453
 
550
454
  ---
551
455
 
552
- ## 🔒 Security Architecture & Cloud API Endpoints
456
+ ## Security Architecture & Cloud API Endpoints
553
457
 
554
- TokenSafe Cloud Backend enforces enterprise zero-trust security across all communications:
458
+ TokenSafe Cloud Backend enforces strict zero-trust boundaries across client and server requests:
555
459
 
556
460
  ### 1. Cryptographic Authentication & Licensing
557
- - **Asymmetric RFC 8032 Ed25519 Signatures (`TS2.*`)**: Client instances verify digital signatures offline using an embedded 32-byte public key. The private signing key never leaves the secure cloud enclave.
558
- - **JWT Session Tokens**: Cloud endpoints authenticate sessions via standard HS256 JWT bearer tokens or Clerk session tokens.
559
- - **Dual Bearer Support**: Client endpoints accept either a signed license key (`TS2.*` / `TS1.*`) or a JWT in the `Authorization: Bearer <token>` header.
560
- - **Zero Hardcoded Secrets**: All SMTP, Stripe, Admin, and signing keys are strictly injected via environment variables.
461
+ - **Asymmetric RFC 8032 Ed25519 Signatures (`TS2.*`)**: Client instances verify digital signatures offline using an embedded 32-byte public key. The private signing key never leaves the cloud environment.
462
+ - **JWT Session Tokens**: Cloud endpoints verify sessions via HS256 JWT bearer tokens or Clerk session tokens.
463
+ - **Dual Bearer Support**: Client endpoints accept either a signed license key (`TS2.*` / `TS1.*`) or a JWT in `Authorization: Bearer <token>`.
464
+ - **Zero Hardcoded Secrets**: all server credentials load strictly from runtime environment variables — nothing is hardcoded in the codebase.
561
465
 
562
466
  ### 2. Cloud API Endpoint Reference
563
467
 
@@ -570,62 +474,26 @@ TokenSafe Cloud Backend enforces enterprise zero-trust security across all commu
570
474
  | `POST` | `/api/team/seat/create` | **Bearer Auth** | `Authorization: Bearer <jwt\|key>`, JSON `{ owner_email, member_email }` | Generates a cryptographically signed seat license for a team member. |
571
475
  | `POST` | `/api/team/seat/revoke` | **Bearer Auth** | `Authorization: Bearer <jwt\|key>`, JSON `{ owner_email, license_key }` | Revokes an active team seat license key. |
572
476
  | `POST` | `/api/telemetry/sync` | **License Auth** | JSON `{ license_key, email, events: [...] }` | Syncs batch telemetry events (enforces max 50 events/batch). |
573
- | `POST` | `/webhook/stripe` | **HMAC Sig** | `Stripe-Signature: t=...,v1=...` | Verifies Stripe webhook payload against `STRIPE_WEBHOOK_SECRET`. |
574
-
575
- > **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).
576
-
577
- ### 3. Server Configuration & Environment Variables
578
-
579
- | Variable | Required | Default / Description |
580
- |---|---|---|
581
- | `TOKENSAFE_PRIVATE_KEY` | Production | 64-character hex Ed25519 seed for issuing `TS2.` licenses. |
582
- | `ADMIN_SECRET_KEY` | Yes | High-entropy secret for administrative API access (`X-Admin-Secret`). |
583
- | `ADMIN_EMAILS` | Optional | Comma-separated admin emails (e.g. `admin@yourcompany.com`). |
584
- | `STRIPE_WEBHOOK_SECRET` | Production | Webhook secret (`whsec_...`) used to verify Stripe webhooks. |
585
- | `SMTP_PASS` | Production | Password/token for transactional mail delivery via ImprovMX SMTP. |
586
- | `JWT_SECRET` | Optional | Shared HMAC secret for verifying custom JWT tokens. Set a persistent value in production — otherwise sessions invalidate on every restart. |
587
- | `CLERK_JWT_KEY` | Production (web) | Clerk public key (PEM) or HMAC key for verifying Clerk session tokens. Without it — or without the `cryptography` package — Clerk tokens are rejected (fail-closed). |
588
- | `TOKENSAFE_TELEMETRY_DISABLED` | Optional | Set to `1` to fully disable cloud telemetry sync (privacy / offline / CI). |
589
477
 
478
+ Seat and license management is available through the [dashboard](https://dashboard.tokensafe.dev). Privacy controls (e.g. `TOKENSAFE_TELEMETRY_DISABLED=1` to disable cloud telemetry sync) are documented in [METRICS.md](METRICS.md).
590
479
 
591
480
  ---
592
481
 
593
- ## 🧪 Unit Testing
482
+ ## Unit Testing
594
483
 
595
484
  ```bash
596
485
  python3 -m unittest discover tests
597
486
  ```
598
- *Zero mandatory runtime dependencies — runs on standard Python 3.10+. The optional `cryptography` package (`requirements.txt`) accelerates Ed25519 license verification and enables fail-closed RS256 Clerk verification on the cloud backend.*
487
+ *Zero mandatory runtime dependencies: runs on standard Python 3.10+. The optional `cryptography` package (`requirements.txt`) accelerates Ed25519 license verification and enables fail-closed RS256 Clerk verification on the cloud backend.*
599
488
 
600
489
  ---
601
490
 
602
- ## 💎 Pricing & Plans
603
-
604
- TokenSafe is built on an **Open-Core** model designed to give every developer immediate zero-friction value while offering unlimited throughput and centralized governance for professionals and teams:
605
-
606
- | Plan | Price | Monthly Token Savings | Capabilities |
607
- | :--- | :---: | :---: | :--- |
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 |
612
-
613
- > [!TIP]
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>`.
491
+ ## License
492
+ MIT License. Commercial licenses are available for self-hosted B2B and enterprise VPC deployments.
615
493
 
616
494
  ---
617
495
 
618
- ## 📄 License
619
- MIT License. Commercial enterprise licenses available for on-premise B2B deployments.
620
-
621
- ### Export Markdown Report
622
- ```bash
623
- tokensafe markdown
624
- ```
625
-
626
- ---
627
-
628
- ## 📂 Project Structure
496
+ ## Project Structure
629
497
 
630
498
  ```text
631
499
  agy-token-optimizer/
@@ -652,7 +520,7 @@ agy-token-optimizer/
652
520
  │ ├── proxy.py # Multi-provider transparent AI proxy & SSE broadcaster
653
521
  │ ├── graph_engine.py # Sub-30ms AST parser, call graphs & God Node centrality
654
522
  │ ├── tokenizer.py # Zero-dependency calibrated BPE token counter
655
- │ ├── compactor.py # Enhanced semantic compactor (Local Regex + Distillation -> TOCP S-Expr)
523
+ │ ├── compactor.py # Semantic compactor (Local Regex + Distillation -> TOCP S-Expr)
656
524
  │ ├── distiller.py # Multi-provider LLM distillation engine (Gemini, DeepSeek, OpenAI)
657
525
  │ ├── distiller_cache.py # Two-tier LRU + SQLite prompt distillation cache
658
526
  │ ├── deepseek_distiller.py # DeepSeek-Flash semantic compiler with token arbitrage guard
@@ -663,36 +531,16 @@ agy-token-optimizer/
663
531
  │ ├── mailer.py # Transactional email & Friday ROI digest dispatcher
664
532
  │ ├── mcp_server.py # Native Model Context Protocol (MCP) server
665
533
  │ ├── installer.py # Multi-IDE agent auto-installer & config wizard
666
- │ └── cloud_backend.py # Cloud REST backend, telemetry sync & Stripe webhooks
534
+ │ └── cloud_backend.py # Cloud REST backend & team telemetry API
667
535
  ├── hooks/
668
536
  │ ├── pre_invocation.py # PreInvocation hook entry point
669
537
  │ ├── pre_tool_use.py # PreToolUse hook entry point
670
538
  │ └── post_tool_use.py # PostToolUse hook entry point
671
- ├── frontend/ # Modern React / Vite / Tailwind Web App & Dashboard
539
+ ├── frontend/ # React / Vite / Tailwind Web App & Dashboard
672
540
  ├── bin/
673
541
  │ ├── tokensafe.js # Node.js npm launcher (npx tokensafe)
674
542
  │ └── tokensafe # Python CLI launcher (pip / standalone)
675
- ├── tests/ # Unit test suite (100% passing)
543
+ ├── tests/ # Unit test suite
676
544
  ├── install.sh # One-click installer for Antigravity
677
545
  └── README.md
678
546
  ```
679
-
680
- ---
681
-
682
- ## 🛠️ Installation & Antigravity Setup
683
-
684
- Run the installer:
685
- ```bash
686
- ./install.sh
687
- ```
688
- This symlinks the plugin directly into `~/.gemini/config/plugins/agy-token-optimizer`.
689
- Antigravity automatically loads it on startup.
690
-
691
- ---
692
-
693
- ## 🧪 Running Unit Tests
694
-
695
- ```bash
696
- python3 -m unittest discover tests
697
- ```
698
- No external packages required — runs on standard Python 3.10+.