tokensafe 2.4.0 → 2.4.1

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
@@ -7,8 +7,8 @@
7
7
 
8
8
  <p align="center">
9
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>.
10
+ Stop paying for AI hallucinations and secret leaks. TokenSafe sits locally between your team's coding agents and your repositories: agents read only the code they need, exposed secrets and unsafe edits get blocked before commit, and engineering leads get an auditable per-seat ROI report every Friday.<br>
11
+ Built for teams using <b>Cursor, Claude Code, Codex, Windsurf, Google Antigravity, Gemini CLI, and ChatGPT</b>.
12
12
  </p>
13
13
 
14
14
  <p align="center">
@@ -22,337 +22,168 @@
22
22
  </p>
23
23
 
24
24
  <p align="center">
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;
25
+ <a href="#install--agents">Install</a> &bull;
26
+ <a href="#cli-quickstart">Quickstart</a> &bull;
27
+ <a href="#why-tokensafe">Why TokenSafe</a> &bull;
28
+ <a href="#benchmarks">Benchmarks</a> &bull;
30
29
  <a href="#pricing-and-7-day-team-trial">Pricing</a> &bull;
30
+ <a href="#faq">FAQ</a> &bull;
31
+ <a href="#reference">Reference</a> &bull;
31
32
  <a href="https://tokensafe.dev">Website &amp; Docs</a>
32
33
  </p>
33
34
 
34
35
  ---
35
36
 
36
- ## 1-Click Universal Install
37
+ ## Install & Agents
37
38
 
38
39
  Connect TokenSafe to the AI coding agents on your workstation in one command:
39
40
 
40
41
  ```bash
41
- # Option 1: Zero-Install via npx (Recommended for Cursor & Claude Desktop)
42
+ # Option 1: Zero-Install via npx (recommended)
42
43
  npx tokensafe
43
44
 
44
45
  # Option 2: Python / PyPI
45
46
  pip install tokensafe && tokensafe
46
47
 
47
- # Option 3: Direct Shell Script (macOS / Linux)
48
+ # Option 3: Direct shell script (macOS / Linux)
48
49
  curl -fsSL https://tokensafe.dev/install.sh | bash
49
50
  ```
50
51
 
51
- On **Google Antigravity**, the installer additionally symlinks the plugin into `~/.gemini/config/plugins/tokensafe` — Antigravity loads it automatically on startup (stale `agy-token-optimizer` symlinks from older versions are removed, since Antigravity keys plugin enable-state by folder name and would run every hook twice). Once the plugin ships its own `mcp_config.json`, any leftover user-level `tokensafe` MCP entry in Antigravity's configs is migrated away (backed up first) so the server is not registered twice.
52
+ The installer detects which agents live on your machine, registers the TokenSafe MCP server, injects project rules, and wires lifecycle hooks where the agent supports them.
52
53
 
53
- ### Optional Dependency: `cryptography` (Recommended)
54
+ | Agent | Integration |
55
+ |---|---|
56
+ | **Google Antigravity** | Plugin symlink + hooks + skills + MCP (loaded automatically on startup) |
57
+ | **Claude Code CLI** | MCP + `SessionStart` / `UserPromptSubmit` / `PreToolUse` hooks |
58
+ | **Cursor** | MCP + `beforeShellExecution` / `beforeReadFile` hooks |
59
+ | **Claude Desktop** | MCP registration (`claude_desktop_config.json`) |
60
+ | **Windsurf** | MCP registration + global rules |
61
+ | **OpenAI Codex** | MCP in `~/.codex/config.toml` (stdio + cloud HTTP natively) |
62
+ | **Cline / Roo Code** | MCP registration (VS Code) |
63
+ | **GitHub Copilot** | MCP registration |
64
+ | **Z.ai Code** | MCP registration |
65
+ | **ChatGPT** | Cloud connector, nothing to install |
66
+ | **Gemini CLI** | MCP registration |
54
67
 
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:
56
-
57
- ```bash
58
- pip install cryptography # or: brew install cryptography
59
- ```
60
-
61
- | Component | With `cryptography` | Without (pure-stdlib fallback) |
62
- |---|---|---|
63
- | Client: license verification | Instant Ed25519 fast-path | Pure-Python Ed25519 (~0.3s once, then cached) |
64
- | Client: everything else | Identical | Identical |
65
- | Cloud backend: Clerk session tokens | RS256 signature verified | **Rejected** (fail-closed: unsigned tokens are never accepted) |
66
- | Cloud backend: everything else | Identical | Identical |
67
-
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
-
70
- ---
71
-
72
- ## Universal Agent Hooks (Claude Code & Cursor)
73
-
74
- Beyond MCP, TokenSafe installs native lifecycle-hook adapters inside your agent loop via `tokensafe setup`:
75
-
76
- | Agent | Hook | What it does |
77
- |---|---|---|
78
- | **Claude Code** | `SessionStart` | Injects the TokenSafe protocol directives once per session as `additionalContext` (mirrors the Antigravity SessionStart hook) |
79
- | **Claude Code** | `UserPromptSubmit` | Compacts the prompt into a TOCP S-expression and injects it as `additionalContext` (labeled *estimated* per [METRICS.md](METRICS.md)) |
80
- | **Claude Code** | `PreToolUse` (Bash) | Blocks secret-bearing and destructive commands; prompts for confirmation on TLS-verification bypasses |
81
- | **Cursor** | `beforeShellExecution` | Same shell guard: blocks secret leaks and destructive actions, asks on `-k` or `--insecure` |
82
- | **Cursor** | `beforeReadFile` | Blocks raw lockfile, bundle, and `dist/` reads that would burn ~50k context tokens |
83
- | **Codex CLI** | None yet | Uses MCP and `AGENTS.md` directly |
84
-
85
- 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.
86
-
87
- For **team workspaces on Antigravity**, `tokensafe install --project --agents-plugin <path-to-tokensafe>` additionally declares the plugin in the project's `.agents/plugins.json`, so teammates load hooks, skills, and the MCP server straight from the shared repo without running the installer.
88
-
89
- ## Context Budget HUD & Governor
90
-
91
- Teams usually notice context exhaustion only when code quality drops mid-task. TokenSafe exposes live window usage as a native MCP tool:
92
-
93
- ```json
94
- { "tool": "tokensafe:context_budget", "args": { "model": "claude-x" } }
95
- ```
68
+ Claude Desktop / Cursor MCP config:
96
69
 
97
70
  ```json
98
71
  {
99
- "window_tokens": 200000,
100
- "used_estimated": 168000,
101
- "used_pct": 84.0,
102
- "breakdown": { "tools": 165000, "history": 2300, "prompts": 700, "other": 0 },
103
- "threshold": "warning",
104
- "recommendation": "Context is heavy. Prefer tokensafe:smart_read_file ... and consider tokensafe:compact_conversation."
72
+ "mcpServers": {
73
+ "tokensafe": { "command": "npx", "args": ["-y", "tokensafe", "mcp"] }
74
+ }
105
75
  }
106
76
  ```
107
77
 
108
- - **Window resolution**: explicit argument, then `TOKENSAFE_CONTEXT_WINDOW`, then model-family default (Gemini 1M, Claude 200k, GPT 128k).
109
- - **80% session warning**: injected once per session by the `pre_invocation` hook when context usage approaches the threshold.
110
- - **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.
111
- - **Honest accounting**: counts only TokenSafe-instrumented flows and labels them `estimated` (a floor, never a fabricated total; see [METRICS.md](METRICS.md)).
112
-
113
- ## Per-Seat ROI & Persistent Diff-Aware Read-Cache
78
+ Cloud features (team metrics, managed distillation, shared team cache, billing) run on the remote endpoint `https://api.tokensafe.dev/mcp` with `Authorization: Bearer <TS2. license key>`. Four public tools work without a key, so ChatGPT connects with authentication set to **None**.
114
79
 
115
- - **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.
116
- - **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).
80
+ Full per-agent configuration, hook details, and the Codex/ChatGPT setup live in [docs/AGENT_SETUP.md](docs/AGENT_SETUP.md).
117
81
 
118
- ## Universal MCP Server Configuration
119
-
120
- Connect TokenSafe to **Claude Desktop** (`claude_desktop_config.json`) or **Cursor** MCP settings:
82
+ ## CLI Quickstart
121
83
 
122
- ```json
123
- {
124
- "mcpServers": {
125
- "tokensafe": {
126
- "command": "npx",
127
- "args": ["-y", "tokensafe", "mcp"]
128
- }
129
- }
130
- }
84
+ ```bash
85
+ # View live savings dashboard in your terminal
86
+ tokensafe stats
131
87
  ```
132
88
 
133
- ### Cloud MCP — team metrics & managed distillation
134
-
135
- The stdio server slices your local files. Cloud features (team savings metrics, license status, server-side prompt distillation, shared team cache, billing) live on the remote streamable-HTTP endpoint:
89
+ ```text
90
+ ⚡ TOKENSAFE CONTEXT OPTIMIZER DASHBOARD
91
+ Total Tokens Saved: 4,524,156 tokens
92
+ Efficiency Gain: [████████████████████████░░] 92.5%
93
+ Context Traffic: 4,889,255 raw → 370,574 optimized (2,132 events)
136
94
 
137
- ```
138
- https://api.tokensafe.dev/mcp
95
+ • Command Sanitizer (CLI) : 727,300 tokens saved (263 events)
96
+ • Architecture Graph : 758,256 tokens saved (13 events)
97
+ • Multi-turn History Fold : 2,897,897 tokens saved (471 events)
98
+ • Prompt Compactor (local+cache) : 43,502 tokens saved (1,255 events)
139
99
  ```
140
100
 
141
- Auth: `Authorization: Bearer <TS1./TS2. license key>` (from [tokensafe.dev](https://tokensafe.dev)). Public tools — `get_public_stats`, `check_latest_version`, `get_setup_instructions`, `search_docs` — work without a key.
101
+ ```bash
102
+ # Audit your environment: MCP tool overhead, skills tax, risky settings
103
+ tokensafe doctor
142
104
 
143
- ### ChatGPT (custom connector — nothing to install)
105
+ # Recursive security & hygiene audit of a repository
106
+ tokensafe guard audit
144
107
 
145
- 1. **Settings → Connectors → Create**, paste `https://api.tokensafe.dev/mcp`
146
- 2. Authentication: **None** — the four public tools work immediately
147
- 3. Ask ChatGPT to "show TokenSafe public stats" or "search TokenSafe docs"
108
+ # Preview prompt compaction on custom input
109
+ tokensafe test "fix the validate_token method in src/auth.py to check jwt expiration"
148
110
 
149
- License-gated tools (team metrics, distillation) return a clear upgrade hint when called without a key — the funnel is intentional: see the value, then bring the same endpoint into Codex / Claude Code with your Bearer key to unlock the paid tools.
111
+ # Map architectural hotspots before multi-file changes
112
+ tokensafe graph
150
113
 
151
- ### Codex CLI (`~/.codex/config.toml`, shared with the IDE extension)
114
+ # Disable a heavy MCP server without editing JSON
115
+ tokensafe mcp disable <server>
152
116
 
153
- ```toml
154
- [mcp_servers.tokensafe] # local engine: AST slicing, guards
155
- command = "npx"
156
- args = ["-y", "tokensafe", "mcp"]
117
+ # Compile and preview the Friday team ROI digest
118
+ tokensafe digest
157
119
 
158
- [mcp_servers.tokensafe-cloud] # cloud features
159
- url = "https://api.tokensafe.dev/mcp"
160
- bearer_token_env_var = "TOKENSAFE_LICENSE"
120
+ # Activate a Team or Solo license key
121
+ tokensafe activate TS2.eyJlbWFpbCI6...
161
122
  ```
162
123
 
163
- Set `export TOKENSAFE_LICENSE="TS2.…"`, then run `get_setup_instructions` via any connected agent for per-agent snippets (cursor, claude_desktop, claude_code, codex, windsurf, antigravity, gemini_cli, chatgpt).
124
+ The full command reference (24 commands) is in [Reference](#reference).
164
125
 
165
- ---
126
+ ## Why TokenSafe
166
127
 
167
- ## Three Outcomes for Engineering Teams
128
+ Giving coding agents raw access to entire repositories creates three daily costs:
168
129
 
169
- Giving coding agents raw access to entire repositories creates three daily problems:
170
- 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.
130
+ 1. **Senior hours burned on AI PRs**: reading 2,000-line modules for a 10-line fix makes models forget imports, invent methods, and regress adjacent code.
171
131
  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 .`.
172
132
  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.
173
133
 
174
- | Outcome | What changes for your team | Local enforcement |
134
+ | Outcome | What changes for your team | How it is enforced |
175
135
  |---|---|---|
176
- | **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. |
177
- | **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. |
178
- | **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`). |
136
+ | **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 local AST skeletonizer, architecture graph, predictive signature prefetch, lockfile-stripping diff slicer, loop guard. |
137
+ | **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 on every tool call, output guard on large writes, local PII/key redaction. |
138
+ | **Predictable sprint velocity & ROI** | Teammates get warm cache hits, and CTOs receive a Friday ROI digest separating `measured` and `estimated` savings. | Shared team cache, live context budget HUD, per-seat dashboard. |
179
139
 
180
- ---
181
-
182
- ## Why Stripping Context Bloat Fixes AI Code Quality
140
+ A $29 seat pays for itself by saving one hour of senior code review or preventing one leaked key. Typical payback: **1 to 3 days** of team usage.
183
141
 
184
- TokenSafe started because of a **$400 monthly API bill** from running autonomous coding agents across active repositories.
142
+ ## Before and After
185
143
 
186
- 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.**
187
-
188
- > 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.
144
+ One contrast: an agent asked to change one helper in a 1,420-line file receives 94 lines of target logic and type contracts instead of the whole module. The same principle applies to terminal output, diffs, and session history.
189
145
 
190
146
  | What breaks coding agents | How TokenSafe fixes it | The outcome |
191
147
  | :--- | :--- | :--- |
192
- | **"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. |
193
- | **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. |
194
- | **Infinite wait on background tests**<br>An agent launches `yarn test` in the background and blocks forever: `--watchAll=false` no-ops against a watch-mode script, CRA turns watch on by default outside CI, or jest finishes but unclosed handles keep the process alive. | **Test-Runner Guard** (`src/command_sanitizer.py`) forces run-once mode on every JS test command — `CI=true`, `--watch=false`, `--forceExit` — and peeks at `<cwd>/package.json` (hook payload or MCP `cwd` argument) to identify the runner behind opaque `yarn/npm test` scripts. | **No more hangs.** The test run terminates with an exit code and the agent moves on. |
195
- | **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. |
196
- | **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")`. |
197
- | **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. |
198
-
199
- ---
200
-
201
- ## Polyglot AST Engine (10+ Languages)
148
+ | **"Lost in the Middle" context fade**: an agent reads a 2,000-line file to change one 10-line helper, forgets imports, and invents methods. | **AST skeletonizer** 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. |
149
+ | **Terminal log flooding**: `npm test` or `pytest` fails and dumps 4,000 lines of stack traces and lockfile diffs into context. | **Command sanitizer** strips lockfile noise and trims output to the failing assertion and stack frame. | Root-cause fixes instead of unrelated rewrites. |
150
+ | **Infinite wait on background tests**: `yarn test` hangs in watch mode, or jest finishes but unclosed handles keep the process alive. | **Test-runner guard** forces run-once mode (`CI=true`, `--watch=false`, `--forceExit`) and peeks at `<cwd>/package.json` to identify the runner behind opaque scripts. | The test run terminates with an exit code and the agent moves on. |
151
+ | **5-attempt retry loops**: an agent repeats the same broken edit until the context budget runs dry. | **Loop guard** detects repeated identical tool calls and halts the cycle. | Stuck loops stop before damaging working modules. |
152
+ | **Unsafe edits & secret leaks**: fallback keys, `verify=False`, SQL string interpolation, or `git add .` with `.env` present. | **TokenSafe Guard** audits writes and shell commands locally before execution. | Credentials, SQLi patterns, and destructive commands are blocked locally. |
202
153
 
203
- 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.
204
-
205
- ### Supported Language Matrix
206
-
207
- | Language / Framework | File Extensions | Preserved Structures | Folding Mechanism |
208
- |---|---|---|---|
209
- | **TypeScript / React** | `.ts`, `.tsx`, `.js`, `.jsx`, `.mjs`, `.cjs` | React components (`React.FC`, `memo`, `forwardRef`, multi-line destructuring), arrow functions, hooks, classes, interfaces | Target & 1-hop bodies kept full; non-target bodies folded into `{ /* ... */ };` |
210
- | **Python** | `.py` | Classes, typed signatures, docstrings, decorators, `async def` | Native `ast.parse` tree pruning with `...` body replacement |
211
- | **Go** | `.go` | Struct declarations, interfaces, methods `func (r *Recv) Method(...)`, generics `func Map[T any]` | Non-target functions folded; struct layouts and `select` blocks preserved |
212
- | **Rust** | `.rs` | `struct`, `enum`, `impl` blocks, `trait` blocks, `pub(crate) async fn`, `const fn` | `impl` containers stay open; method bodies folded into `{ /* ... */ }` |
213
- | **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 |
214
- | **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 |
215
- | **PHP, Kotlin, Swift** | `.php`, `.kt`, `.kts`, `.swift` | Classes, `function`, `fun`, `func` declarations with visibility modifiers | Function bodies folded into `{ /* ... */ }` |
216
- | **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` |
217
-
218
- ### Key Engine Guarantees
219
- - **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.
220
- - **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.
221
- - **Directory Tree Optimization (`tokensafe:list_dir`)**: Replaces verbose `ls -la` output with a compact, depth-bounded tree without permissions, timestamps, or lockfiles.
222
- - **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.
223
- - **Comment & String Bracket Immunity**: Multi-line block comments (`/* ... */`, JSX `{/* ... */}`), template strings (`` `${...}` ``), and escaped quotes are tracked by `BraceLexer` so brackets never desynchronize.
224
- - **Control-Flow Immunity**: Statements like `if (...)`, `catch (err) {`, `for (...)`, and `while (...)` are protected from folding.
225
-
226
- ---
227
-
228
- ## The Hidden Context Tax: MCP Tool Schema Bloat
229
-
230
- Coding agent quotas (such as 5-hour session windows or monthly token budgets) often drain after a few prompts before real work starts.
231
-
232
- ### The Hidden System Prompt Tax
233
- 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:
154
+ When an operation is blocked, the agent sees an explicit, constructive message:
234
155
 
235
156
  ```text
236
- ┌────────────────────────────────────────────────────────────────────────┐
237
- │ SYSTEM PROMPT ANATOMY (EVERY SINGLE TURN) │
238
- ├────────────────────────────────────────────────────────────────────────┤
239
- │ Base System Instructions ~1,500 tokens │
240
- │ Active Workspace Skills & Prompts ~8,000 tokens │
241
- │ Regular MCP Tools (context7, prisma, etc.) ~800 tokens │
242
- │ [!] Heavy MCP Tools (200+ schemas from large servers) ~6,000 tokens │
243
- ├────────────────────────────────────────────────────────────────────────┤
244
- │ TOTAL HIDDEN BASE TAX BEFORE YOUR FIRST LINE OF CODE: │
245
- │ ~16,300 tokens PER TURN x 15 turns = 244,500 tokens burned │
246
- └────────────────────────────────────────────────────────────────────────┘
157
+ 🛡️ TokenSafe Guard: Blocked a hardcoded secret fallback in config.py.
158
+ Leave the default empty or read from os.environ at runtime.
247
159
  ```
248
160
 
249
- - **1 server with 50 tools** = **~1,500 to 2,500 tokens** of static tax per turn.
250
- - **1 server with 200+ tools** = **~5,000 to 10,000 tokens** per turn.
251
- - Across a 15-turn coding session, **75,000 to 150,000 tokens** go solely to tool schemas.
252
-
253
- ### How TokenSafe Cuts MCP Overhead
254
- 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`.
255
- 2. **1-Click MCP Toggle**: Enable or disable heavy servers without manual JSON edits:
256
- ```bash
257
- tokensafe mcp disable rea # Prunes heavy schemas from the system prompt
258
- tokensafe mcp enable rea # Re-enables when needed
259
- ```
260
- 3. **Session Start Bloat Alerts**: Surfaces warning badges in chat when heavy MCP bloat is active.
261
- 4. **Telemetry Retention (`tokensafe prune` / `vacuum`)**: Compacts SQLite metrics with rolling-window rollups, reducing local database footprint by up to 40%.
262
-
263
- ---
264
-
265
- ## TokenSafe vs. Graphify: In-Flight Defense vs. Static Reports
266
-
267
- How TokenSafe complements or replaces static graph tools like **Graphify** (`graphify-labs/graphify`):
268
-
269
- | Capability | Graphify | TokenSafe |
270
- |---|---|---|
271
- | **Primary Focus** | Static knowledge graph reports & MCP queries | **In-flight real-time context slicing & security guardrails** |
272
- | **Indexing Cost** | Requires LLM tokens / offline graph build | **0 tokens, deterministic local AST (< 30ms)** |
273
- | **Execution Latency** | Offline CLI build step | **Sub-millisecond inline proxy & lifecycle hooks** |
274
- | **Active Slicing** | Static report (`GRAPH_REPORT.md`) | **Dynamic call-graph skeletonization (85% to 92% fewer file tokens)** |
275
- | **Multi-Project Workspace** | Manual directory targeting | **Detects project roots per file on the fly** |
276
- | **Prompt Distillation** | None | **TOCP S-expression compaction (-40% to -70%)** |
277
- | **Safety & Runaway Prevention** | None | **Guardrails, Output Guard, Loop Guard, secret redaction** |
278
-
279
- > **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.
280
-
281
- ---
282
-
283
- ## TokenSafe Guard: Local Security and Hygiene Shield
284
-
285
- 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.
286
-
287
- **TokenSafe Guard** (`src/guard.py`) audits tool calls locally before disk or git execution with zero token overhead:
288
-
289
- ### 1. Secret & Private Key Leak Prevention (Zero Hardcoded Fallbacks)
290
- - **Live Provider Secrets**: Blocks hardcoded Stripe live keys, AWS access keys, OpenAI project keys, Anthropic tokens, and GitHub personal access tokens.
291
- - **Default Fallback Hardcoding**: Rejects non-placeholder defaults such as `os.environ.get("DB_PASSWORD", "prod_secret_123")` or `process.env.JWT_SECRET || "production_secret"`.
292
- - **Raw Private Keys**: Blocks 64-character raw hex keys and raw PEM private key blocks in source files.
293
-
294
- ### 2. Insecure SSL/TLS Verification Bypass Shield
295
- - Blocks `verify=False` in Python (`requests`, `httpx`, `aiohttp`, `urllib3`) and `rejectUnauthorized: false` or `NODE_TLS_REJECT_UNAUTHORIZED='0'` in Node.js non-test code.
296
-
297
- ### 3. Raw SQL Injection Prevention
298
- - Blocks string interpolation inside query execution calls (`cursor.execute(f"SELECT ... {user_id}")`, `cursor.execute("SELECT ... %s" % val)`, `db.query(\`SELECT ... ${id}\`)`).
299
- - Enforces parameterized queries (`?`, `%s`, `$1`).
300
-
301
- ### 4. Dangerous CORS Wildcard with Credentials Shield
302
- - Intercepts configurations combining `Access-Control-Allow-Origin: *` with `Access-Control-Allow-Credentials: true`.
303
-
304
- ### 5. Git Staging Protection for Sensitive Files
305
- - **Explicit Staging**: Blocks `git add .env`, `git add .env.*`, `git add id_rsa`, and `git add *.pem`.
306
- - **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.
307
-
308
- ### 6. Destructive Shell & Data Exfiltration Prevention
309
- - **Destructive Deletion**: Blocks commands such as `rm -rf /`, `rm -rf ~`, `rm -rf *`, and `rm -rf --no-preserve-root`.
310
- - **Network Exfiltration**: Blocks commands piping sensitive local files to remote URLs (such as `curl -d @.env https://...` or `wget --post-file=id_rsa`).
311
-
312
- ### 7. Package Typosquatting Early Warning
313
- - 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.
314
-
315
- When an operation is blocked, TokenSafe Guard returns an explicit message:
316
- `🛡️ **TokenSafe Guard**: <reason>`
317
-
318
- ---
319
-
320
- ## Prompt Distillation: Managed Cloud and Three-Tier Cache
321
-
322
- TokenSafe distills verbose prompts into compact TOCP S-expressions (`-40% to -70%` tokens).
323
-
324
- ### 1. Zero-Config Managed Cloud vs. Self-Hosted Docker BYOK
325
-
326
- | Deployment Mode | Supported Tier | Distillation Engine | Required API Keys | Setup |
327
- |---|---|---|---|---|
328
- | **TokenSafe Cloud (SaaS)** | **Engineering Team & Solo** | **Google Gemini Flash-Lite** (`gemini-flash-lite-latest`) | **None (Zero keys needed)** | Included in subscription, ready immediately |
329
- | **Local Regex Compactor** | **Developer Sandbox (Free)** | **Deterministic Multilingual Regex** (9 languages) | **None** | Local execution only (`500,000` tokens/mo) |
330
- | **Self-Hosted Docker** | **Enterprise & VPC** | **BYOK Multi-Provider** (Gemini, DeepSeek, OpenAI, Claude) | `GEMINI_API_KEY`, `DEEPSEEK_API_KEY`, etc. | Private VPC container deployment |
161
+ ## What TokenSafe Does
331
162
 
332
- > **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.
163
+ **Clean context, better code**
333
164
 
334
- ### 2. Token Arbitrage Guard & Three-Tier Cache
165
+ - `tokensafe:smart_read_file` returns the target function plus its 1-hop dependencies instead of the whole file. 10+ languages, with CSS design tokens preserved so agents never invent colors or font rules.
166
+ - `tokensafe:graph` maps architectural hotspots and dependency topology in under 250 tokens instead of a full repository crawl.
167
+ - The command sanitizer strips lockfile noise and stack dumps down to the failing assertion, and forces JS test runners into run-once mode so background tests never hang.
168
+ - The loop guard halts agents stuck repeating the same broken edit.
335
169
 
336
- To keep distillation overhead lower than the tokens it saves:
337
- 1. **Smart Gating (`llm_distill_min_tokens: 100`)**: Prompts under 100 tokens stay strictly local via regex heuristics ($0$ LLM tokens, $< 1\text{ms}$).
338
- 2. **Output Token Ceiling (`distill_max_tokens: 60`)**: Caps compiled output at 60 tokens to prevent compiler arbitrage loss.
339
- 3. **Three-Tier Cache**:
340
- - **L1 (In-Memory LRU)**: Sub-millisecond hits inside active sessions.
341
- - **L2 (Persistent SQLite)**: Stores normalized SHA-256 prompt hashes in `~/.tokensafe/data/metrics.db` across restarts so repeated workflows (`git commit`, `run tests`, `fix lint`) cost 0 tokens. The directory is shared by all agents on the machine (override with `TOKENSAFE_DATA_DIR`; Docker uses `/app/data`).
342
- - **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.
170
+ **Local-first guardrails**
343
171
 
344
- ### 3. Provider & Cache Inspection
172
+ - Blocks live provider secrets, hardcoded fallback credentials, and raw private keys before they reach disk or git.
173
+ - Blocks TLS bypasses (`verify=False`, `rejectUnauthorized: false`), interpolated SQL, and CORS wildcards with credentials.
174
+ - Blocks `.env` and key files from staging, including blanket `git add .` when sensitive files exist in the working tree.
175
+ - Blocks destructive deletes and exfiltration pipes (`curl -d @.env https://...`), and warns on known typosquat packages.
345
176
 
346
- Inspect your active license tier, distillation mode, and cache stats anytime:
347
- ```bash
348
- tokensafe providers
349
- ```
177
+ **Auditable team ROI**
350
178
 
351
- 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`.
179
+ - The Context Budget HUD shows live window usage with a breakdown (tools / history / prompts) before quality drops.
180
+ - The shared L3 team cache gives teammates and CI runners warm 0ms hits on repeated reads and prompts.
181
+ - Managed cloud distillation compacts prompts with zero API keys for developers.
182
+ - The Friday per-seat ROI digest reports each engineer's savings with the `measured` / `estimated` split; inactive seats show `—`, never guessed figures.
352
183
 
353
- ---
184
+ Deeper mechanics (language matrix, context tax math, cache tiers, governor) live in [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md).
354
185
 
355
- ## Calibrated SWE-bench Benchmark Results
186
+ ## Benchmarks
356
187
 
357
188
  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):
358
189
 
@@ -360,18 +191,16 @@ Reference run across 8 production engineering scenarios (`131,552` baseline toke
360
191
 
361
192
  | Benchmark Scenario | Task Complexity | Baseline Tokens | TokenSafe Tokens | Reduction | Turn Speedup | Accuracy |
362
193
  |---|---|---|---|---|---|---|
363
- | **Zero-Token Architecture Discovery** | Full repo God Node indexing | 49,716 | **486** | **-99.0%** | **6 ➔ 1 turns (+83%)** | 100% Pass |
364
- | **Graph-Guided AST Symbol Slicing** | Target function + 1-hop callees | 8,016 | **451** | **-94.4%** | **4 ➔ 2 turns (+50%)** | 100% Pass |
194
+ | **Zero-Token Architecture Discovery** | Full repo hotspot indexing | 49,716 | **486** | **-99.0%** | **6 → 1 turns (+83%)** | 100% Pass |
195
+ | **Graph-Guided AST Symbol Slicing** | Target function + 1-hop callees | 8,016 | **451** | **-94.4%** | **4 → 2 turns (+50%)** | 100% Pass |
365
196
  | **Monorepo Lockfile Grep Leak** | `git grep` across lockfiles | 10,111 | **491** | **-95.1%** | 2 turns | 100% Pass |
366
197
  | **Monorepo Lockfile Git Diff** | Monorepo branch diff | 18,911 | **761** | **-96.0%** | 2 turns | 100% Pass |
367
198
  | **Multi-Turn History Compaction** | 8-turn session history fold | 31,010 | **3,130** | **-89.9%** | 8 turns | 100% Pass |
368
- | **Race Condition / Distributed Lock** | AST query & Redis redlock | 5,074 | **404** | **-92.0%** | **4 ➔ 3 turns (+25%)** | 100% Pass |
369
- | **OAuth JWT Expiration Triage** | Controller bug investigation | 3,757 | **401** | **-89.3%** | **3 ➔ 2 turns (+33%)** | 100% Pass |
199
+ | **Race Condition / Distributed Lock** | AST query & Redis redlock | 5,074 | **404** | **-92.0%** | **4 → 3 turns (+25%)** | 100% Pass |
200
+ | **OAuth JWT Expiration Triage** | Controller bug investigation | 3,757 | **401** | **-89.3%** | **3 → 2 turns (+33%)** | 100% Pass |
370
201
  | **CI Test Failure Extraction** | Full test log & stack trace | 5,009 | **1,127** | **-77.5%** | 3 turns | 100% Pass |
371
202
 
372
- > **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)).
373
-
374
- ---
203
+ > **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)).
375
204
 
376
205
  ## Metrics Honesty
377
206
 
@@ -380,9 +209,7 @@ TokenSafe labels every savings event as one of:
380
209
  - **`measured`**: the model literally received fewer bytes than the tool produced (sliced file reads, filtered command output, AST skeletons).
381
210
  - **`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).
382
211
 
383
- 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)**.
384
-
385
- ---
212
+ Totals 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)**.
386
213
 
387
214
  ## Pricing and 7-Day Team Trial
388
215
 
@@ -390,190 +217,120 @@ TokenSafe follows an open-core model: verify local context savings and guardrail
390
217
 
391
218
  | Plan | Price | Monthly Allowance | Included Capabilities |
392
219
  |---|---|---|---|
393
- | **Developer Sandbox** | **$0** forever | **500,000 tokens / mo** | 9-Language Local Regex Compactor, Local AST Slicer CLI, Local Secret & `.env` Guard, SQLite & Terminal Dashboard |
394
- | **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) |
395
- | **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 |
220
+ | **Developer Sandbox** | **$0** forever | **500,000 tokens / mo** | 9-language local regex compactor, local AST slicer CLI, local secret & `.env` guard, SQLite & terminal dashboard |
221
+ | **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 seat provisioning & revoke, managed cloud distillation (zero keys needed) |
222
+ | **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 |
396
223
 
397
224
  *Working solo? [Individual Solo plans](https://tokensafe.dev#pricing) start at **$9 / mo** ($89 / yr).*
398
225
 
399
- **[Start a 7-Day Team Trial](https://tokensafe.dev#pricing)**
226
+ `7-Day Free Trial · Offline Ed25519 Seat Keys (TS2.*) · Zero Source Code Transmitted · Cancel anytime`
400
227
 
401
- ---
228
+ **[Start a 7-Day Team Trial](https://tokensafe.dev#pricing)** &nbsp;&nbsp; **[Run Free Locally](#install--agents)**
402
229
 
403
- ## CLI Quickstart
230
+ ## FAQ
404
231
 
405
- ```bash
406
- # View live savings dashboard in your terminal
407
- tokensafe stats
408
- ```
232
+ **Does my source code leave my machine?**
233
+ No. Slicing, guarding, compaction, and metrics run locally. The cloud receives only counters (token totals and event types), never file contents or prompts. Set `TOKENSAFE_TELEMETRY_DISABLED=1` to disable all telemetry sync; local features keep working.
409
234
 
410
- ```text
411
- ┌────────────────────────────────────────────────────────────────────────┐
412
- │ ⚡ TOKENSAFE CONTEXT OPTIMIZER DASHBOARD ⚡ │
413
- └────────────────────────────────────────────────────────────────────────┘
235
+ **How does offline license verification work?**
236
+ License keys are `TS2.*` tokens signed with Ed25519. Your client verifies the signature offline against an embedded public key and caches the result for up to an hour. Enforcement never requires a network round trip.
414
237
 
415
- Total Tokens Saved: 4,524,156 tokens
416
- Efficiency Gain: [████████████████████████████░░] 92.5%
417
- Estimated Savings: $6.7865 USD
418
- Context Traffic: 4,889,255 raw ➔ 370,574 optimized (2132 events)
419
-
420
- ── Breakdown by Source ──────────────────────────────────────────────────
421
- • AST Skeletonizer (Signatures) : 3,509 tokens saved (2 events)
422
- • Command Sanitizer (CLI) : 727,300 tokens saved (263 events)
423
- • Context Governor : 5,800 tokens saved (29 events)
424
- • Graph-Guided Slicer (Call-Graph) : 42,420 tokens saved (14 events)
425
- • Architecture Graph (God Nodes) : 758,256 tokens saved (13 events)
426
- • Multi-turn History Fold : 2,897,897 tokens saved (471 events)
427
- • Output Token Guard (write_file) : 42,466 tokens saved (84 events)
428
- • Prompt Compactor (TOCP + Cache) : 43,502 tokens saved (1255 events)
429
- • File Line Slicer (AST) : 3,006 tokens saved (1 events)
430
-
431
- Run `tokensafe test "<prompt>"` to test compression on custom input.
432
- Run `tokensafe html` to view interactive browser dashboard.
433
- ```
238
+ **What do `measured` and `estimated` mean?**
239
+ `measured` means the model literally received fewer bytes than the tool produced. `estimated` means savings are counted against a reasonable modeled baseline. The dashboard always shows the split and never invents numbers for missing data.
434
240
 
435
- ```bash
436
- # Open interactive local dark-mode browser dashboard
437
- tokensafe html
241
+ **What exactly does the $29/seat plan include?**
242
+ Unlimited compaction and managed cloud distillation (zero API keys for developers), the shared L3 monorepo cache, org-wide guard policies, the Friday per-seat ROI digest, and centralized seat provisioning and revocation. Billed annually it is $290/seat/year (~$24/seat/mo).
438
243
 
439
- # Export a markdown savings report
440
- tokensafe markdown
244
+ **Can we self-host?**
245
+ The Enterprise & VPC plan covers a private VPC Docker proxy with BYOK provider keys, zero-telemetry / air-gapped mode, and SAML/OIDC SSO, deployed together with the TokenSafe engineering team: [corp@tokensafe.dev](mailto:corp@tokensafe.dev).
441
246
 
442
- # Test prompt compression on custom input in real time
443
- tokensafe test "please fix the validate_token method in src/auth.py so that it checks jwt expiration and returns boolean"
247
+ **What happens if a hook fails?**
248
+ All hook adapters fail open: an internal error never stalls your agent. Failures are logged locally so they can be reported and fixed, not silently swallowed.
444
249
 
445
- # Audit environment and context token tax (MCP & skills)
446
- tokensafe doctor
447
-
448
- # List configured LLM distillation providers and models
449
- tokensafe providers
250
+ ## Reference
450
251
 
451
- # Analyze repository God Nodes and dependency topology
452
- tokensafe graph
252
+ <details>
253
+ <summary><b>Local MCP tools (12)</b></summary>
453
254
 
454
- # Generate compact tokensafe-out/API_SURFACE.md interface snapshot
455
- tokensafe map
456
-
457
- # Manage or disable high-overhead MCP tools
458
- tokensafe mcp list
459
- tokensafe mcp disable <server>
460
- tokensafe mcp enable <server>
255
+ | Tool | What it does |
256
+ |---|---|
257
+ | `get_architecture_graph` | Architectural hotspots and dependency topology before multi-file reading |
258
+ | `get_api_surface` | Compact markdown map of all exported interfaces, classes, and types |
259
+ | `smart_read_file` | AST-skeletonized file read preserving a target symbol and 1-hop dependencies |
260
+ | `scoped_search` | Token-bounded symbol and text search with line-numbered matches |
261
+ | `list_dir` | Clean directory tree without permissions, timestamps, or lockfiles |
262
+ | `slice_diff` | Unified diff slicing omitting lockfiles and minimizing context lines |
263
+ | `sanitize_command` | Per-stage shell command rewrites with bounded output |
264
+ | `guard_inspect` | Pre-flight security and hygiene audit for commands or code snippets |
265
+ | `context_budget` | Context window usage estimate with thresholds and recommendations |
266
+ | `compress_prompt` | Compiles a verbose developer prompt into a compact S-expression |
267
+ | `compact_conversation` | Folds a long agent transcript into a compact state ledger |
268
+ | `get_token_savings_metrics` | Cumulative token and cost savings analytics |
269
+ </details>
461
270
 
462
- # Optimize SQLite metrics storage
463
- tokensafe vacuum
464
- tokensafe prune
271
+ <details>
272
+ <summary><b>Cloud MCP tools (13)</b></summary>
465
273
 
466
- # Generate or preview Friday team ROI digest email
467
- tokensafe digest
468
-
469
- # Run the SWE-bench verification suite
470
- tokensafe benchmark
471
-
472
- # Run the unit test suite (compact failure report, full: --traceback / -v)
473
- tokensafe tests
274
+ Endpoint: `https://api.tokensafe.dev/mcp`, auth `Authorization: Bearer <TS1./TS2. key>`.
474
275
 
475
- # Run the local transparent AI proxy (0.0.0.0:8765/v1)
476
- tokensafe proxy
276
+ | Tool | Access | What it does |
277
+ |---|---|---|
278
+ | `get_public_stats` | Public | Aggregate product statistics |
279
+ | `check_latest_version` | Public | Latest published version and update banner |
280
+ | `get_setup_instructions` | Public | Copy-paste MCP snippets per agent |
281
+ | `search_docs` | Public | Search public documentation |
282
+ | `get_license_status` | Licensed | Active tier, seat, and trial state |
283
+ | `get_team_metrics` | Licensed | Team savings metrics with `measured` / `estimated` split |
284
+ | `distill_prompt` | Licensed | Managed cloud prompt distillation (zero API keys) |
285
+ | `team_cache_lookup` | Licensed | Shared L3 team cache lookup |
286
+ | `team_cache_store` | Licensed | Shared L3 team cache store |
287
+ | `list_invoices` | Licensed | Billing history |
288
+ | `generate_team_seat` | Licensed | Provision a signed `TS2.*` seat key |
289
+ | `revoke_team_seat` | Licensed | Revoke an active seat key |
290
+ | `preview_weekly_digest` | Licensed | Preview the Friday team ROI digest |
291
+ </details>
292
+
293
+ <details>
294
+ <summary><b>Full CLI reference (24 commands)</b></summary>
477
295
 
478
- # Activate your Team or Solo license key (TS2 Asymmetric Ed25519 Key)
479
- tokensafe activate TS2.eyJlbWFpbCI6...
296
+ ```text
297
+ tokensafe stats / markdown / html Savings analytics (terminal / .md report / dashboard)
298
+ tokensafe benchmark Zero-context-loss benchmark suite (simulated harness)
299
+ tokensafe graph / map / skeleton Architecture graph / API surface / AST skeleton of a file
300
+ tokensafe test "<prompt>" Preview prompt compaction on custom input
301
+ tokensafe guard "<command>" Pre-flight safety check for a shell command
302
+ tokensafe guard audit [path] Recursive source audit for secrets & vulnerabilities
303
+ tokensafe doctor Audit MCP tool overhead and context token tax
304
+ tokensafe digest [--send] Compile (and optionally dispatch) the weekly team digest
305
+ tokensafe mcp list|disable|enable Manage configured MCP servers
306
+ tokensafe proxy [port] Local transparent AI proxy (0.0.0.0:8765/v1)
307
+ tokensafe install / setup [--all] Configure detected agent environments
308
+ tokensafe update / check-update Self-update / check for a newer version
309
+ tokensafe activate <KEY> Activate a Team or Solo license key
310
+ tokensafe license Show active tier and trial state
311
+ tokensafe providers List distillation providers and active mode
312
+ tokensafe sync Sync local telemetry with the cloud dashboard
313
+ tokensafe prune [--days N] Compact metrics database (roll old events)
314
+ tokensafe vacuum Reclaim SQLite disk space
315
+ tokensafe tests [pytest] Run the unit test suite (compact failure report)
316
+ tokensafe reset Reset all local token metrics
317
+ tokensafe --version Print version and exit
480
318
  ```
319
+ </details>
481
320
 
482
- ---
483
-
484
- ## Self-Hosted Docker Deployment
485
-
486
- 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`).
321
+ More documentation: [docs/AGENT_SETUP.md](docs/AGENT_SETUP.md) · [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) · [docs/API.md](docs/API.md) · [METRICS.md](METRICS.md) · [BENCHMARK_REPORT.md](BENCHMARK_REPORT.md)
487
322
 
488
- 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).
489
-
490
- ---
323
+ ## Development and License
491
324
 
492
- ## Security Architecture & Cloud API Endpoints
493
-
494
- TokenSafe Cloud Backend enforces strict zero-trust boundaries across client and server requests:
495
-
496
- ### 1. Cryptographic Authentication & Licensing
497
- - **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.
498
- - **JWT Session Tokens**: Cloud endpoints verify sessions via HS256 JWT bearer tokens or Clerk session tokens.
499
- - **Dual Bearer Support**: Client endpoints accept either a signed license key (`TS2.*` / `TS1.*`) or a JWT in `Authorization: Bearer <token>`.
500
- - **Zero Hardcoded Secrets**: all server credentials load strictly from runtime environment variables — nothing is hardcoded in the codebase.
501
-
502
- ### 2. Cloud API Endpoint Reference
503
-
504
- | Method | Endpoint | Auth Required | Headers / Parameters | Description |
505
- |---|---|---|---|---|
506
- | `GET` | `/api/health` | Public | None | Healthcheck and service version status. |
507
- | `GET` | `/api/events` | Public | SSE `text/event-stream` | Real-time Server-Sent Events stream for live dashboard telemetry. |
508
- | `GET` | `/api/dashboard` | **Bearer Auth** | `Authorization: Bearer <jwt\|key>` or `?license=<key>` | Authenticated user metrics, token savings, and license status. |
509
- | `GET` | `/api/digest/preview` | **Bearer Auth** | `Authorization: Bearer <jwt\|key>` or `?team_id=<id>` | Previews current weekly team ROI digest (HTML / JSON). |
510
- | `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. |
511
- | `POST` | `/api/team/seat/revoke` | **Bearer Auth** | `Authorization: Bearer <jwt\|key>`, JSON `{ owner_email, license_key }` | Revokes an active team seat license key. |
512
- | `POST` | `/api/telemetry/sync` | **License Auth** | JSON `{ license_key, email, events: [...] }` | Syncs batch telemetry events (enforces max 50 events/batch). |
513
-
514
- 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).
515
-
516
- ---
517
-
518
- ## Unit Testing
325
+ The client runs on standard Python 3.10+ with zero mandatory runtime dependencies. An optional `cryptography` package accelerates license verification ([details](docs/AGENT_SETUP.md#6-optional-dependency-cryptography)).
519
326
 
520
327
  ```bash
521
- python3 -m unittest discover tests
328
+ # Run the unit test suite (compact failure report; full: --traceback / -v)
329
+ tokensafe tests
522
330
  ```
523
- *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.*
524
-
525
- ---
526
-
527
- ## License
528
- MIT License. Commercial licenses are available for self-hosted B2B and enterprise VPC deployments.
529
331
 
530
- ---
531
-
532
- ## Project Structure
332
+ - Contributing: [CONTRIBUTING.md](CONTRIBUTING.md)
333
+ - Security policy and vulnerability reporting: [SECURITY.md](SECURITY.md)
334
+ - Metrics and honesty contract: [METRICS.md](METRICS.md)
533
335
 
534
- ```text
535
- agy-token-optimizer/
536
- ├── plugin.json # Antigravity plugin manifest
537
- ├── hooks.json # Lifecycle hook declarations (PreInvocation, PreToolUse, PostToolUse)
538
- ├── Dockerfile # Hardened multi-stage container deployment
539
- ├── docker-compose.yml # Production Docker compose with multi-provider routing
540
- ├── rules/
541
- │ └── AGENTS.md # TOCP Protocol directives for LLM (prompt-cached)
542
- ├── skills/
543
- │ └── token-optimizer/
544
- │ └── SKILL.md # On-demand Antigravity skill
545
- ├── proto/
546
- │ └── tocp.proto # Protocol Buffers contract
547
- ├── src/
548
- │ ├── cli.py # Unified CLI dispatcher (npm, pip, standalone)
549
- │ ├── cache_normalizer.py # Prompt Cache Prefix Normalizer (Anthropic & DeepSeek)
550
- │ ├── governor.py # Context Window Governor & Token Ceiling (Cascading reduction)
551
- │ ├── agent_firewall.py # Cross-Agent Deduplication Cache (Subagent Firewall)
552
- │ ├── diff_slicer.py # AST Diff Slicer & Lockfile Stripper (`git diff -U2`)
553
- │ ├── weekly_digest.py # Friday Team ROI Digest & Engineer Leaderboard
554
- │ ├── environment_auditor.py # MCP Server & Skill context token tax auditor
555
- │ ├── command_sanitizer.py # High-output terminal command sanitizer
556
- │ ├── proxy.py # Multi-provider transparent AI proxy & SSE broadcaster
557
- │ ├── graph_engine.py # Sub-30ms AST parser, call graphs & God Node centrality
558
- │ ├── tokenizer.py # Zero-dependency calibrated BPE token counter
559
- │ ├── compactor.py # Semantic compactor (Local Regex + Distillation -> TOCP S-Expr)
560
- │ ├── distiller.py # Multi-provider LLM distillation engine (Gemini, DeepSeek, OpenAI)
561
- │ ├── distiller_cache.py # Two-tier LRU + SQLite prompt distillation cache
562
- │ ├── deepseek_distiller.py # DeepSeek-Flash semantic compiler with token arbitrage guard
563
- │ ├── slicer.py # AST & Line windowing tool optimizer
564
- │ ├── metrics.py # Persistent SQLite metrics engine
565
- │ ├── dashboard.py # Visual ANSI terminal, Markdown & reactive SSE web dashboard
566
- │ ├── license_manager.py # Ed25519 cryptographic license verification
567
- │ ├── mcp_server.py # Native Model Context Protocol (MCP) server
568
- │ ├── installer.py # Multi-IDE agent auto-installer & config wizard
569
- ├── hooks/
570
- │ ├── pre_invocation.py # PreInvocation hook entry point
571
- │ ├── pre_tool_use.py # PreToolUse hook entry point
572
- │ └── post_tool_use.py # PostToolUse hook entry point
573
- ├── bin/
574
- │ ├── tokensafe.js # Node.js npm launcher (npx tokensafe)
575
- │ └── tokensafe # Python CLI launcher (pip / standalone)
576
- ├── tests/ # Unit test suite
577
- ├── install.sh # One-click installer for Antigravity
578
- └── README.md
579
- ```
336
+ MIT License. Commercial licenses are available for self-hosted B2B and enterprise VPC deployments. Questions: [corp@tokensafe.dev](mailto:corp@tokensafe.dev) · [tokensafe.dev](https://tokensafe.dev)
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "tokensafe",
3
3
  "mcpName": "dev.tokensafe/tokensafe",
4
- "version": "2.4.0",
4
+ "version": "2.4.1",
5
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": {
package/plugin.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "tokensafe",
3
3
  "displayName": "TokenSafe",
4
- "version": "2.4.0",
5
- "description": "Zero-Loss Token Economy & Context Optimizer for AI Agents. Compresses prompts, slices AST/tool outputs, and prevents stuck loops.",
4
+ "version": "2.4.1",
5
+ "description": "Local-first guardrails, focused context & auditable team ROI for AI coding agents. Agents read only the code they need, secrets get blocked before commit.",
6
6
  "logo": "assets/logo.svg",
7
7
  "author": {
8
8
  "name": "Oleg Savelev",
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.4.0",
6
+ "version": "2.4.1",
7
7
  "websiteUrl": "https://tokensafe.dev",
8
8
  "repository": {
9
9
  "url": "https://github.com/tokensafe-dev/tokensafe",
@@ -30,7 +30,7 @@
30
30
  "registryType": "npm",
31
31
  "registryBaseUrl": "https://registry.npmjs.org",
32
32
  "identifier": "tokensafe",
33
- "version": "2.4.0",
33
+ "version": "2.4.1",
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.4.0",
49
+ "version": "2.4.1",
50
50
  "runtimeHint": "uvx",
51
51
  "transport": {
52
52
  "type": "stdio"
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.4.0"
42
+ "version": "2.4.1"
43
43
  }
44
44
 
45
45
  # MCP client attribution: the initialize handshake carries clientInfo, which
@@ -266,7 +266,7 @@ class TelemetrySync:
266
266
  rollup_synced = bool(state.get("lifetime_rollup_synced", False))
267
267
  headers = {
268
268
  "Content-Type": "application/json",
269
- "User-Agent": "TokenSafe-Sync/2.4.0"
269
+ "User-Agent": "TokenSafe-Sync/2.4.1"
270
270
  }
271
271
  if active_key:
272
272
  headers["Authorization"] = f"Bearer {active_key}"
@@ -16,7 +16,7 @@ import urllib.request
16
16
  import urllib.error
17
17
  from typing import Dict, Any, Optional, Tuple
18
18
 
19
- CURRENT_VERSION = "2.4.0"
19
+ CURRENT_VERSION = "2.4.1"
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