tokensafe 2.4.0 → 2.4.2
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 +192 -435
- package/hooks/claude_code_hook.py +57 -5
- package/hooks/pre_invocation.py +26 -14
- package/package.json +1 -1
- package/plugin.json +2 -2
- package/rules/AGENTS.md +1 -0
- package/server.json +3 -3
- package/skills/token-optimizer/SKILL.md +4 -0
- package/skills/token-optimizer/references/mcp-tools.md +24 -0
- package/src/adapter_core.py +2 -0
- package/src/cli.py +9 -0
- package/src/governor.py +32 -3
- package/src/history_compactor.py +111 -28
- package/src/mcp_server.py +29 -11
- package/src/telemetry_sync.py +1 -1
- package/src/version_checker.py +21 -9
package/README.md
CHANGED
|
@@ -7,8 +7,8 @@
|
|
|
7
7
|
|
|
8
8
|
<p align="center">
|
|
9
9
|
<b>Local-First AI Guardrails, Focused Context & Auditable Team ROI</b><br>
|
|
10
|
-
Stop paying for AI hallucinations and secret leaks.
|
|
11
|
-
Built for teams using <b>Cursor, Claude Code, Codex, Windsurf,
|
|
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="#
|
|
26
|
-
<a href="#
|
|
27
|
-
<a href="#tokensafe
|
|
28
|
-
<a href="#
|
|
29
|
-
<a href="#metrics-honesty">Metrics Honesty</a> •
|
|
25
|
+
<a href="#install--agents">Install</a> •
|
|
26
|
+
<a href="#cli-quickstart">Quickstart</a> •
|
|
27
|
+
<a href="#why-tokensafe">Why TokenSafe</a> •
|
|
28
|
+
<a href="#benchmarks">Benchmarks</a> •
|
|
30
29
|
<a href="#pricing-and-7-day-team-trial">Pricing</a> •
|
|
30
|
+
<a href="#faq">FAQ</a> •
|
|
31
|
+
<a href="#reference">Reference</a> •
|
|
31
32
|
<a href="https://tokensafe.dev">Website & Docs</a>
|
|
32
33
|
</p>
|
|
33
34
|
|
|
34
35
|
---
|
|
35
36
|
|
|
36
|
-
##
|
|
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 (
|
|
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
|
|
48
|
+
# Option 3: Direct shell script (macOS / Linux)
|
|
48
49
|
curl -fsSL https://tokensafe.dev/install.sh | bash
|
|
49
50
|
```
|
|
50
51
|
|
|
51
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
"
|
|
100
|
-
|
|
101
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
##
|
|
119
|
-
|
|
120
|
-
Connect TokenSafe to **Claude Desktop** (`claude_desktop_config.json`) or **Cursor** MCP settings:
|
|
82
|
+
## CLI Quickstart
|
|
121
83
|
|
|
122
|
-
```
|
|
123
|
-
|
|
124
|
-
|
|
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
|
-
|
|
134
|
-
|
|
135
|
-
|
|
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
|
-
|
|
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
|
-
|
|
101
|
+
```bash
|
|
102
|
+
# Audit your environment: MCP tool overhead, skills tax, risky settings
|
|
103
|
+
tokensafe doctor
|
|
142
104
|
|
|
143
|
-
|
|
105
|
+
# Recursive security & hygiene audit of a repository
|
|
106
|
+
tokensafe guard audit
|
|
144
107
|
|
|
145
|
-
|
|
146
|
-
|
|
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
|
-
|
|
111
|
+
# Map architectural hotspots before multi-file changes
|
|
112
|
+
tokensafe graph
|
|
150
113
|
|
|
151
|
-
|
|
114
|
+
# Disable a heavy MCP server without editing JSON
|
|
115
|
+
tokensafe mcp disable <server>
|
|
152
116
|
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
command = "npx"
|
|
156
|
-
args = ["-y", "tokensafe", "mcp"]
|
|
117
|
+
# Compile and preview the Friday team ROI digest
|
|
118
|
+
tokensafe digest
|
|
157
119
|
|
|
158
|
-
|
|
159
|
-
|
|
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
|
-
|
|
124
|
+
The full command reference (24 commands) is in [Reference](#reference).
|
|
164
125
|
|
|
165
|
-
|
|
126
|
+
## Why TokenSafe
|
|
166
127
|
|
|
167
|
-
|
|
128
|
+
Giving coding agents raw access to entire repositories creates three daily costs:
|
|
168
129
|
|
|
169
|
-
|
|
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 |
|
|
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,
|
|
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
|
|
178
|
-
| **Predictable sprint velocity & ROI** |
|
|
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
|
-
|
|
142
|
+
## Before and After
|
|
185
143
|
|
|
186
|
-
|
|
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
|
|
193
|
-
| **Terminal log flooding
|
|
194
|
-
| **Infinite wait on background tests
|
|
195
|
-
| **5-attempt retry loops
|
|
196
|
-
| **
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
163
|
+
**Clean context, better code**
|
|
333
164
|
|
|
334
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
347
|
-
```bash
|
|
348
|
-
tokensafe providers
|
|
349
|
-
```
|
|
177
|
+
**Auditable team ROI**
|
|
350
178
|
|
|
351
|
-
|
|
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
|
-
##
|
|
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
|
|
364
|
-
| **Graph-Guided AST Symbol Slicing** | Target function + 1-hop callees | 8,016 | **451** | **-94.4%** | **4
|
|
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
|
|
369
|
-
| **OAuth JWT Expiration Triage** | Controller bug investigation | 3,757 | **401** | **-89.3%** | **3
|
|
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:**
|
|
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
|
|
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-
|
|
394
|
-
| **Engineering Team** *(Recommended)* | **$29 / seat / mo** *(~$24 / seat / mo billed $290/yr)* | **Unlimited** | **7-Day Free Trial**, **
|
|
395
|
-
| **Enterprise & VPC** | **Custom** | **Unlimited** | Org
|
|
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
|
-
|
|
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)** **[Run Free Locally](#install--agents)**
|
|
402
229
|
|
|
403
|
-
##
|
|
230
|
+
## FAQ
|
|
404
231
|
|
|
405
|
-
|
|
406
|
-
|
|
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
|
-
|
|
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
|
-
|
|
416
|
-
|
|
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
|
-
|
|
436
|
-
|
|
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
|
-
|
|
440
|
-
tokensafe
|
|
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
|
-
|
|
443
|
-
|
|
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
|
-
|
|
446
|
-
tokensafe doctor
|
|
447
|
-
|
|
448
|
-
# List configured LLM distillation providers and models
|
|
449
|
-
tokensafe providers
|
|
250
|
+
## Reference
|
|
450
251
|
|
|
451
|
-
|
|
452
|
-
|
|
252
|
+
<details>
|
|
253
|
+
<summary><b>Local MCP tools (12)</b></summary>
|
|
453
254
|
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
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
|
-
|
|
463
|
-
|
|
464
|
-
tokensafe prune
|
|
271
|
+
<details>
|
|
272
|
+
<summary><b>Cloud MCP tools (13)</b></summary>
|
|
465
273
|
|
|
466
|
-
|
|
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
|
-
|
|
476
|
-
|
|
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
|
-
|
|
479
|
-
tokensafe
|
|
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
|
-
|
|
489
|
-
|
|
490
|
-
---
|
|
323
|
+
## Development and License
|
|
491
324
|
|
|
492
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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)
|