tokensafe 2.1.0 → 2.2.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 +183 -335
- package/bin/tokensafe.js +1 -0
- package/package.json +3 -3
- package/plugin.json +3 -3
- package/server.json +4 -4
- package/skills/token-optimizer/SKILL.md +4 -3
- package/src/adapter_core.py +17 -0
- package/src/cli.py +106 -1
- package/src/guard.py +3 -1
- package/src/installer.py +1 -1
- package/src/mcp_server.py +3 -2
- package/src/metrics.py +3 -1
- package/src/telemetry_sync.py +1 -1
- package/src/version_checker.py +1 -1
- package/src/weekly_digest.py +118 -42
package/README.md
CHANGED
|
@@ -1,40 +1,41 @@
|
|
|
1
1
|
<p align="center">
|
|
2
|
-
<img src="assets/logo.svg" alt="TokenSafe Logo" width="
|
|
2
|
+
<img src="assets/logo.svg" alt="TokenSafe Logo" width="88" height="88" />
|
|
3
3
|
</p>
|
|
4
4
|
|
|
5
|
-
<h1 align="center"
|
|
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
|
|
10
|
-
Stop paying for AI hallucinations and secret leaks
|
|
11
|
-
Built for teams
|
|
9
|
+
<b>Local-First AI Guardrails, Focused Context & 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/
|
|
16
|
-
<a href="https://www.npmjs.com/package/tokensafe"><img src="https://img.shields.io/npm/v/tokensafe.svg?color=
|
|
15
|
+
<a href="https://github.com/tokensafe-dev/tokensafe/actions/workflows/test.yml"><img src="https://img.shields.io/github/actions/workflow/status/tokensafe-dev/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=
|
|
19
|
-
<a href="https://github.com/
|
|
20
|
-
<a href="https://opensource.org/licenses/MIT"><img src="https://img.shields.io/badge/License-MIT-
|
|
21
|
-
<a href="https://tokensafe.dev#pricing"><img src="https://img.shields.io/badge/
|
|
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/tokensafe-dev/tokensafe/stargazers"><img src="https://img.shields.io/github/stars/tokensafe-dev/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="
|
|
26
|
-
<a href="
|
|
27
|
-
<a href="
|
|
28
|
-
<a href="
|
|
29
|
-
<a href="
|
|
30
|
-
<a href="
|
|
25
|
+
<a href="#1-click-universal-install">Install</a> •
|
|
26
|
+
<a href="#three-outcomes-for-engineering-teams">Outcomes</a> •
|
|
27
|
+
<a href="#tokensafe-guard-local-security-and-hygiene-shield">Guardrails</a> •
|
|
28
|
+
<a href="#universal-mcp-server-configuration">MCP Setup</a> •
|
|
29
|
+
<a href="#metrics-honesty">Metrics Honesty</a> •
|
|
30
|
+
<a href="#pricing-and-7-day-team-trial">Pricing</a> •
|
|
31
|
+
<a href="https://tokensafe.dev">Website & Docs</a>
|
|
31
32
|
</p>
|
|
32
33
|
|
|
33
34
|
---
|
|
34
35
|
|
|
35
|
-
##
|
|
36
|
+
## 1-Click Universal Install
|
|
36
37
|
|
|
37
|
-
Connect TokenSafe to
|
|
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
|
-
|
|
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
|
-
|
|
53
|
-
|
|
54
|
-
is installed automatically by `install.sh`
|
|
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
|
|
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
|
|
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
|
|
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
|
-
##
|
|
72
|
+
## Universal Agent Hooks (Claude Code & Cursor)
|
|
73
73
|
|
|
74
|
-
Beyond MCP, TokenSafe
|
|
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) |
|
|
80
|
-
| **Cursor** | `beforeShellExecution` | Same shell guard
|
|
81
|
-
| **Cursor** | `beforeReadFile` | Blocks lockfile
|
|
82
|
-
| **Codex CLI** |
|
|
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**:
|
|
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
|
-
##
|
|
86
|
+
## Context Budget HUD & Governor
|
|
87
87
|
|
|
88
|
-
|
|
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
|
|
106
|
-
- **80% warning injected
|
|
107
|
-
-
|
|
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
|
-
|
|
110
|
+
## Per-Seat ROI & Persistent Diff-Aware Read-Cache
|
|
116
111
|
|
|
117
|
-
-
|
|
118
|
-
-
|
|
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
|
-
##
|
|
115
|
+
## Universal MCP Server Configuration
|
|
122
116
|
|
|
123
|
-
Connect TokenSafe
|
|
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
|
-
##
|
|
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
|
-
|
|
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
|
-
|
|
145
|
+
---
|
|
172
146
|
|
|
173
|
-
|
|
147
|
+
## Why Stripping Context Bloat Fixes AI Code Quality
|
|
174
148
|
|
|
175
|
-
|
|
149
|
+
TokenSafe started because of a **$400 monthly API bill** from running autonomous coding agents across active repositories.
|
|
176
150
|
|
|
177
|
-
|
|
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
|
-
|
|
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
|
|
155
|
+
| What breaks coding agents | How TokenSafe fixes it | The outcome |
|
|
183
156
|
| :--- | :--- | :--- |
|
|
184
|
-
| **"Lost in the Middle"
|
|
185
|
-
| **Terminal
|
|
186
|
-
| **
|
|
187
|
-
| **
|
|
188
|
-
| **Unsafe
|
|
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
|
-
##
|
|
165
|
+
## Polyglot AST Engine (10+ Languages)
|
|
193
166
|
|
|
194
|
-
TokenSafe
|
|
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`)
|
|
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
|
|
211
|
-
- **Strict Arrow Function Parser**: Arrow functions
|
|
212
|
-
- **Directory Tree Optimization (`tokensafe:list_dir`)**: Replaces verbose
|
|
213
|
-
- **Graph-Guided Neighborhood Slicing**:
|
|
214
|
-
- **Comment & String Bracket Immunity**: Multi-line block comments (`/* ... */`, JSX `{/* ... */}`), template strings (`` `${...}` ``), and escaped quotes are tracked
|
|
215
|
-
- **Control-Flow
|
|
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
|
-
##
|
|
192
|
+
## The Hidden Context Tax: MCP Tool Schema Bloat
|
|
220
193
|
|
|
221
|
-
|
|
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
|
|
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
|
-
│
|
|
206
|
+
│ [!] Heavy MCP Tools (200+ schemas from large servers) ~6,000 tokens │
|
|
234
207
|
├────────────────────────────────────────────────────────────────────────┤
|
|
235
|
-
│ TOTAL HIDDEN BASE TAX BEFORE
|
|
236
|
-
│
|
|
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
|
|
241
|
-
- **1
|
|
242
|
-
-
|
|
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
|
|
245
|
-
1. **`tokensafe doctor` (
|
|
246
|
-
2. **1-Click MCP
|
|
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
|
|
249
|
-
tokensafe mcp enable rea # Re-enables when
|
|
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. **
|
|
252
|
-
4. **
|
|
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
|
-
##
|
|
229
|
+
## TokenSafe vs. Graphify: In-Flight Defense vs. Static Reports
|
|
257
230
|
|
|
258
|
-
How TokenSafe complements or
|
|
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
|
|
263
|
-
| **Indexing Cost** |
|
|
264
|
-
| **Execution Latency** | Offline
|
|
265
|
-
| **Active Slicing** | Static
|
|
266
|
-
| **Multi-Project Workspace** |
|
|
267
|
-
| **
|
|
268
|
-
| **Safety & Runaway Prevention** | None | **Output
|
|
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
|
|
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
|
-
##
|
|
247
|
+
## TokenSafe Guard: Local Security and Hygiene Shield
|
|
275
248
|
|
|
276
|
-
|
|
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`)
|
|
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
|
|
282
|
-
- **Default Fallback Hardcoding**:
|
|
283
|
-
- **Raw
|
|
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
|
-
-
|
|
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
|
|
291
|
-
|
|
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
|
|
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
|
|
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
|
|
305
|
-
- **Network Exfiltration**: Blocks
|
|
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
|
|
308
|
-
-
|
|
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
|
-
|
|
279
|
+
When an operation is blocked, TokenSafe Guard returns an explicit message:
|
|
312
280
|
`🛡️ **TokenSafe Guard**: <reason>`
|
|
313
281
|
|
|
314
282
|
---
|
|
315
283
|
|
|
316
|
-
##
|
|
284
|
+
## Prompt Distillation: Managed Cloud and Three-Tier Cache
|
|
317
285
|
|
|
318
|
-
TokenSafe
|
|
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 |
|
|
290
|
+
| Deployment Mode | Supported Tier | Distillation Engine | Required API Keys | Setup |
|
|
323
291
|
|---|---|---|---|---|
|
|
324
|
-
| **TokenSafe Cloud (SaaS)**
|
|
325
|
-
| **Local Regex Compactor** | **
|
|
326
|
-
| **Self-Hosted Docker**
|
|
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
|
-
|
|
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
|
-
|
|
298
|
+
### 2. Token Arbitrage Guard & Three-Tier Cache
|
|
333
299
|
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
- **
|
|
339
|
-
- **
|
|
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.
|
|
308
|
+
### 3. Provider & Cache Inspection
|
|
342
309
|
|
|
343
|
-
|
|
310
|
+
Inspect your active license tier, distillation mode, and cache stats anytime:
|
|
344
311
|
```bash
|
|
345
312
|
tokensafe providers
|
|
346
313
|
```
|
|
347
314
|
|
|
348
|
-
|
|
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
|
-
##
|
|
319
|
+
## Calibrated SWE-bench Benchmark Results
|
|
367
320
|
|
|
368
|
-
Reference run across 8
|
|
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
|
|
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:**
|
|
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
|
-
##
|
|
340
|
+
## Metrics Honesty
|
|
388
341
|
|
|
389
342
|
TokenSafe labels every savings event as one of:
|
|
390
343
|
|
|
391
|
-
- **`measured
|
|
392
|
-
- **`estimated
|
|
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
|
-
|
|
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
|
-
##
|
|
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
|
-
|
|
|
355
|
+
| Plan | Price | Monthly Allowance | Included Capabilities |
|
|
401
356
|
|---|---|---|---|
|
|
402
|
-
| **Developer Sandbox
|
|
403
|
-
| **Engineering Team** *(Recommended)* | **$29 / seat / mo** *(~$24 / seat / mo billed $290/yr)* | **Unlimited** | **7-Day Free Trial**, **Shared Team Cache (L3 Monorepo
|
|
404
|
-
| **Enterprise
|
|
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)
|
|
361
|
+
*Working solo? [Individual Solo plans](https://tokensafe.dev#pricing) start at **$9 / mo** ($89 / yr).*
|
|
407
362
|
|
|
408
|
-
|
|
363
|
+
**[Start a 7-Day Team Trial](https://tokensafe.dev#pricing)**
|
|
409
364
|
|
|
410
365
|
---
|
|
411
366
|
|
|
412
|
-
##
|
|
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
|
|
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
|
|
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
|
|
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
|
-
##
|
|
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
|
-
|
|
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
|
-
- **
|
|
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
|
-
##
|
|
456
|
+
## Security Architecture & Cloud API Endpoints
|
|
553
457
|
|
|
554
|
-
TokenSafe Cloud Backend enforces
|
|
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
|
|
558
|
-
- **JWT Session Tokens**: Cloud endpoints
|
|
559
|
-
- **Dual Bearer Support**: Client endpoints accept either a signed license key (`TS2.*` / `TS1.*`) or a JWT in
|
|
560
|
-
- **Zero Hardcoded Secrets**:
|
|
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
|
-
##
|
|
482
|
+
## Unit Testing
|
|
594
483
|
|
|
595
484
|
```bash
|
|
596
485
|
python3 -m unittest discover tests
|
|
597
486
|
```
|
|
598
|
-
*Zero mandatory runtime dependencies
|
|
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
|
-
##
|
|
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
|
-
##
|
|
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 #
|
|
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
|
|
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/ #
|
|
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
|
|
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+.
|