tokensafe 2.3.0 → 2.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +197 -408
- package/hooks/pre_invocation.py +8 -1
- package/hooks/pre_tool_use.py +13 -3
- package/package.json +1 -1
- package/plugin.json +2 -2
- package/server.json +23 -3
- package/src/cli.py +3 -2
- package/src/environment_auditor.py +48 -5
- package/src/history_compactor.py +1 -1
- package/src/loop_detector.py +3 -1
- package/src/mcp_server.py +1 -1
- package/src/skeletonizer.py +2 -1
- package/src/slicer.py +5 -3
- package/src/telemetry_sync.py +1 -1
- package/src/version_checker.py +1 -1
- package/hooks/__pycache__/pre_invocation.cpython-313.pyc +0 -0
- package/hooks/__pycache__/pre_tool_use.cpython-313.pyc +0 -0
- package/hooks/__pycache__/session_start.cpython-313.pyc +0 -0
- package/hooks/__pycache__/stop_hook.cpython-313.pyc +0 -0
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,305 +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
|
-
|
|
68
|
+
Claude Desktop / Cursor MCP config:
|
|
56
69
|
|
|
57
|
-
```
|
|
58
|
-
|
|
70
|
+
```json
|
|
71
|
+
{
|
|
72
|
+
"mcpServers": {
|
|
73
|
+
"tokensafe": { "command": "npx", "args": ["-y", "tokensafe", "mcp"] }
|
|
74
|
+
}
|
|
75
|
+
}
|
|
59
76
|
```
|
|
60
77
|
|
|
61
|
-
|
|
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.
|
|
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**.
|
|
69
79
|
|
|
70
|
-
|
|
80
|
+
Full per-agent configuration, hook details, and the Codex/ChatGPT setup live in [docs/AGENT_SETUP.md](docs/AGENT_SETUP.md).
|
|
71
81
|
|
|
72
|
-
##
|
|
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.
|
|
82
|
+
## CLI Quickstart
|
|
88
83
|
|
|
89
|
-
|
|
84
|
+
```bash
|
|
85
|
+
# View live savings dashboard in your terminal
|
|
86
|
+
tokensafe stats
|
|
87
|
+
```
|
|
90
88
|
|
|
91
|
-
|
|
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)
|
|
92
94
|
|
|
93
|
-
|
|
94
|
-
|
|
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)
|
|
95
99
|
```
|
|
96
100
|
|
|
97
|
-
```
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
"used_estimated": 168000,
|
|
101
|
-
"used_pct": 84.0,
|
|
102
|
-
"breakdown": { "tools": 165000, "history": 2300, "prompts": 700, "other": 0 },
|
|
103
|
-
"threshold": "warning",
|
|
104
|
-
"recommendation": "Context is heavy. Prefer tokensafe:smart_read_file ... and consider tokensafe:compact_conversation."
|
|
105
|
-
}
|
|
106
|
-
```
|
|
101
|
+
```bash
|
|
102
|
+
# Audit your environment: MCP tool overhead, skills tax, risky settings
|
|
103
|
+
tokensafe doctor
|
|
107
104
|
|
|
108
|
-
|
|
109
|
-
|
|
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)).
|
|
105
|
+
# Recursive security & hygiene audit of a repository
|
|
106
|
+
tokensafe guard audit
|
|
112
107
|
|
|
113
|
-
|
|
108
|
+
# Preview prompt compaction on custom input
|
|
109
|
+
tokensafe test "fix the validate_token method in src/auth.py to check jwt expiration"
|
|
114
110
|
|
|
115
|
-
|
|
116
|
-
|
|
111
|
+
# Map architectural hotspots before multi-file changes
|
|
112
|
+
tokensafe graph
|
|
117
113
|
|
|
118
|
-
|
|
114
|
+
# Disable a heavy MCP server without editing JSON
|
|
115
|
+
tokensafe mcp disable <server>
|
|
119
116
|
|
|
120
|
-
|
|
117
|
+
# Compile and preview the Friday team ROI digest
|
|
118
|
+
tokensafe digest
|
|
121
119
|
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
"mcpServers": {
|
|
125
|
-
"tokensafe": {
|
|
126
|
-
"command": "npx",
|
|
127
|
-
"args": ["-y", "tokensafe", "mcp"]
|
|
128
|
-
}
|
|
129
|
-
}
|
|
130
|
-
}
|
|
120
|
+
# Activate a Team or Solo license key
|
|
121
|
+
tokensafe activate TS2.eyJlbWFpbCI6...
|
|
131
122
|
```
|
|
132
123
|
|
|
133
|
-
|
|
124
|
+
The full command reference (24 commands) is in [Reference](#reference).
|
|
125
|
+
|
|
126
|
+
## Why TokenSafe
|
|
134
127
|
|
|
135
|
-
|
|
128
|
+
Giving coding agents raw access to entire repositories creates three daily costs:
|
|
136
129
|
|
|
137
|
-
|
|
138
|
-
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.
|
|
139
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 .`.
|
|
140
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.
|
|
141
133
|
|
|
142
|
-
| Outcome | What changes for your team |
|
|
134
|
+
| Outcome | What changes for your team | How it is enforced |
|
|
143
135
|
|---|---|---|
|
|
144
|
-
| **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,
|
|
145
|
-
| **Zero leaked secrets in git** | Hardcoded password fallbacks, TLS bypasses, raw SQL interpolation, and `.env` commits are stopped before reaching disk or staging. | Deterministic
|
|
146
|
-
| **Predictable sprint velocity & ROI** |
|
|
147
|
-
|
|
148
|
-
---
|
|
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. |
|
|
149
139
|
|
|
150
|
-
|
|
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.
|
|
151
141
|
|
|
152
|
-
|
|
142
|
+
## Before and After
|
|
153
143
|
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
> 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.
|
|
157
145
|
|
|
158
146
|
| What breaks coding agents | How TokenSafe fixes it | The outcome |
|
|
159
147
|
| :--- | :--- | :--- |
|
|
160
|
-
| **"Lost in the Middle" context fade
|
|
161
|
-
| **Terminal log flooding
|
|
162
|
-
| **Infinite wait on background tests
|
|
163
|
-
| **5-attempt retry loops
|
|
164
|
-
| **
|
|
165
|
-
| **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. |
|
|
166
|
-
|
|
167
|
-
---
|
|
168
|
-
|
|
169
|
-
## Polyglot AST Engine (10+ Languages)
|
|
170
|
-
|
|
171
|
-
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.
|
|
172
|
-
|
|
173
|
-
### Supported Language Matrix
|
|
174
|
-
|
|
175
|
-
| Language / Framework | File Extensions | Preserved Structures | Folding Mechanism |
|
|
176
|
-
|---|---|---|---|
|
|
177
|
-
| **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 `{ /* ... */ };` |
|
|
178
|
-
| **Python** | `.py` | Classes, typed signatures, docstrings, decorators, `async def` | Native `ast.parse` tree pruning with `...` body replacement |
|
|
179
|
-
| **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 |
|
|
180
|
-
| **Rust** | `.rs` | `struct`, `enum`, `impl` blocks, `trait` blocks, `pub(crate) async fn`, `const fn` | `impl` containers stay open; method bodies folded into `{ /* ... */ }` |
|
|
181
|
-
| **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 |
|
|
182
|
-
| **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 |
|
|
183
|
-
| **PHP, Kotlin, Swift** | `.php`, `.kt`, `.kts`, `.swift` | Classes, `function`, `fun`, `func` declarations with visibility modifiers | Function bodies folded into `{ /* ... */ }` |
|
|
184
|
-
| **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` |
|
|
185
|
-
|
|
186
|
-
### Key Engine Guarantees
|
|
187
|
-
- **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.
|
|
188
|
-
- **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.
|
|
189
|
-
- **Directory Tree Optimization (`tokensafe:list_dir`)**: Replaces verbose `ls -la` output with a compact, depth-bounded tree without permissions, timestamps, or lockfiles.
|
|
190
|
-
- **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.
|
|
191
|
-
- **Comment & String Bracket Immunity**: Multi-line block comments (`/* ... */`, JSX `{/* ... */}`), template strings (`` `${...}` ``), and escaped quotes are tracked by `BraceLexer` so brackets never desynchronize.
|
|
192
|
-
- **Control-Flow Immunity**: Statements like `if (...)`, `catch (err) {`, `for (...)`, and `while (...)` are protected from folding.
|
|
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. |
|
|
193
153
|
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
## The Hidden Context Tax: MCP Tool Schema Bloat
|
|
197
|
-
|
|
198
|
-
Coding agent quotas (such as 5-hour session windows or monthly token budgets) often drain after a few prompts before real work starts.
|
|
199
|
-
|
|
200
|
-
### The Hidden System Prompt Tax
|
|
201
|
-
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:
|
|
202
155
|
|
|
203
156
|
```text
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
├────────────────────────────────────────────────────────────────────────┤
|
|
207
|
-
│ Base System Instructions ~1,500 tokens │
|
|
208
|
-
│ Active Workspace Skills & Prompts ~8,000 tokens │
|
|
209
|
-
│ Regular MCP Tools (context7, prisma, etc.) ~800 tokens │
|
|
210
|
-
│ [!] Heavy MCP Tools (200+ schemas from large servers) ~6,000 tokens │
|
|
211
|
-
├────────────────────────────────────────────────────────────────────────┤
|
|
212
|
-
│ TOTAL HIDDEN BASE TAX BEFORE YOUR FIRST LINE OF CODE: │
|
|
213
|
-
│ ~16,300 tokens PER TURN x 15 turns = 244,500 tokens burned │
|
|
214
|
-
└────────────────────────────────────────────────────────────────────────┘
|
|
157
|
+
🛡️ TokenSafe Guard: Blocked a hardcoded secret fallback in config.py.
|
|
158
|
+
Leave the default empty or read from os.environ at runtime.
|
|
215
159
|
```
|
|
216
160
|
|
|
217
|
-
|
|
218
|
-
- **1 server with 200+ tools** = **~5,000 to 10,000 tokens** per turn.
|
|
219
|
-
- Across a 15-turn coding session, **75,000 to 150,000 tokens** go solely to tool schemas.
|
|
220
|
-
|
|
221
|
-
### How TokenSafe Cuts MCP Overhead
|
|
222
|
-
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`.
|
|
223
|
-
2. **1-Click MCP Toggle**: Enable or disable heavy servers without manual JSON edits:
|
|
224
|
-
```bash
|
|
225
|
-
tokensafe mcp disable rea # Prunes heavy schemas from the system prompt
|
|
226
|
-
tokensafe mcp enable rea # Re-enables when needed
|
|
227
|
-
```
|
|
228
|
-
3. **Session Start Bloat Alerts**: Surfaces warning badges in chat when heavy MCP bloat is active.
|
|
229
|
-
4. **Telemetry Retention (`tokensafe prune` / `vacuum`)**: Compacts SQLite metrics with rolling-window rollups, reducing local database footprint by up to 40%.
|
|
230
|
-
|
|
231
|
-
---
|
|
232
|
-
|
|
233
|
-
## TokenSafe vs. Graphify: In-Flight Defense vs. Static Reports
|
|
234
|
-
|
|
235
|
-
How TokenSafe complements or replaces static graph tools like **Graphify** (`graphify-labs/graphify`):
|
|
236
|
-
|
|
237
|
-
| Capability | Graphify | TokenSafe |
|
|
238
|
-
|---|---|---|
|
|
239
|
-
| **Primary Focus** | Static knowledge graph reports & MCP queries | **In-flight real-time context slicing & security guardrails** |
|
|
240
|
-
| **Indexing Cost** | Requires LLM tokens / offline graph build | **0 tokens, deterministic local AST (< 30ms)** |
|
|
241
|
-
| **Execution Latency** | Offline CLI build step | **Sub-millisecond inline proxy & lifecycle hooks** |
|
|
242
|
-
| **Active Slicing** | Static report (`GRAPH_REPORT.md`) | **Dynamic call-graph skeletonization (85% to 92% fewer file tokens)** |
|
|
243
|
-
| **Multi-Project Workspace** | Manual directory targeting | **Detects project roots per file on the fly** |
|
|
244
|
-
| **Prompt Distillation** | None | **TOCP S-expression compaction (-40% to -70%)** |
|
|
245
|
-
| **Safety & Runaway Prevention** | None | **Guardrails, Output Guard, Loop Guard, secret redaction** |
|
|
246
|
-
|
|
247
|
-
> **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.
|
|
248
|
-
|
|
249
|
-
---
|
|
250
|
-
|
|
251
|
-
## TokenSafe Guard: Local Security and Hygiene Shield
|
|
252
|
-
|
|
253
|
-
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.
|
|
161
|
+
## What TokenSafe Does
|
|
254
162
|
|
|
255
|
-
**
|
|
163
|
+
**Clean context, better code**
|
|
256
164
|
|
|
257
|
-
|
|
258
|
-
-
|
|
259
|
-
-
|
|
260
|
-
-
|
|
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.
|
|
261
169
|
|
|
262
|
-
|
|
263
|
-
- Blocks `verify=False` in Python (`requests`, `httpx`, `aiohttp`, `urllib3`) and `rejectUnauthorized: false` or `NODE_TLS_REJECT_UNAUTHORIZED='0'` in Node.js non-test code.
|
|
170
|
+
**Local-first guardrails**
|
|
264
171
|
|
|
265
|
-
|
|
266
|
-
- Blocks
|
|
267
|
-
-
|
|
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.
|
|
268
176
|
|
|
269
|
-
|
|
270
|
-
- Intercepts configurations combining `Access-Control-Allow-Origin: *` with `Access-Control-Allow-Credentials: true`.
|
|
177
|
+
**Auditable team ROI**
|
|
271
178
|
|
|
272
|
-
|
|
273
|
-
-
|
|
274
|
-
-
|
|
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.
|
|
275
183
|
|
|
276
|
-
|
|
277
|
-
- **Destructive Deletion**: Blocks commands such as `rm -rf /`, `rm -rf ~`, `rm -rf *`, and `rm -rf --no-preserve-root`.
|
|
278
|
-
- **Network Exfiltration**: Blocks commands piping sensitive local files to remote URLs (such as `curl -d @.env https://...` or `wget --post-file=id_rsa`).
|
|
184
|
+
Deeper mechanics (language matrix, context tax math, cache tiers, governor) live in [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md).
|
|
279
185
|
|
|
280
|
-
|
|
281
|
-
- 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.
|
|
282
|
-
|
|
283
|
-
When an operation is blocked, TokenSafe Guard returns an explicit message:
|
|
284
|
-
`🛡️ **TokenSafe Guard**: <reason>`
|
|
285
|
-
|
|
286
|
-
---
|
|
287
|
-
|
|
288
|
-
## Prompt Distillation: Managed Cloud and Three-Tier Cache
|
|
289
|
-
|
|
290
|
-
TokenSafe distills verbose prompts into compact TOCP S-expressions (`-40% to -70%` tokens).
|
|
291
|
-
|
|
292
|
-
### 1. Zero-Config Managed Cloud vs. Self-Hosted Docker BYOK
|
|
293
|
-
|
|
294
|
-
| Deployment Mode | Supported Tier | Distillation Engine | Required API Keys | Setup |
|
|
295
|
-
|---|---|---|---|---|
|
|
296
|
-
| **TokenSafe Cloud (SaaS)** | **Engineering Team & Solo** | **Google Gemini Flash-Lite** (`gemini-flash-lite-latest`) | **None (Zero keys needed)** | Included in subscription, ready immediately |
|
|
297
|
-
| **Local Regex Compactor** | **Developer Sandbox (Free)** | **Deterministic Multilingual Regex** (9 languages) | **None** | Local execution only (`500,000` tokens/mo) |
|
|
298
|
-
| **Self-Hosted Docker** | **Enterprise & VPC** | **BYOK Multi-Provider** (Gemini, DeepSeek, OpenAI, Claude) | `GEMINI_API_KEY`, `DEEPSEEK_API_KEY`, etc. | Private VPC container deployment |
|
|
299
|
-
|
|
300
|
-
> **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.
|
|
301
|
-
|
|
302
|
-
### 2. Token Arbitrage Guard & Three-Tier Cache
|
|
303
|
-
|
|
304
|
-
To keep distillation overhead lower than the tokens it saves:
|
|
305
|
-
1. **Smart Gating (`llm_distill_min_tokens: 100`)**: Prompts under 100 tokens stay strictly local via regex heuristics ($0$ LLM tokens, $< 1\text{ms}$).
|
|
306
|
-
2. **Output Token Ceiling (`distill_max_tokens: 60`)**: Caps compiled output at 60 tokens to prevent compiler arbitrage loss.
|
|
307
|
-
3. **Three-Tier Cache**:
|
|
308
|
-
- **L1 (In-Memory LRU)**: Sub-millisecond hits inside active sessions.
|
|
309
|
-
- **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`).
|
|
310
|
-
- **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.
|
|
311
|
-
|
|
312
|
-
### 3. Provider & Cache Inspection
|
|
313
|
-
|
|
314
|
-
Inspect your active license tier, distillation mode, and cache stats anytime:
|
|
315
|
-
```bash
|
|
316
|
-
tokensafe providers
|
|
317
|
-
```
|
|
318
|
-
|
|
319
|
-
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`.
|
|
320
|
-
|
|
321
|
-
---
|
|
322
|
-
|
|
323
|
-
## Calibrated SWE-bench Benchmark Results
|
|
186
|
+
## Benchmarks
|
|
324
187
|
|
|
325
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):
|
|
326
189
|
|
|
@@ -328,18 +191,16 @@ Reference run across 8 production engineering scenarios (`131,552` baseline toke
|
|
|
328
191
|
|
|
329
192
|
| Benchmark Scenario | Task Complexity | Baseline Tokens | TokenSafe Tokens | Reduction | Turn Speedup | Accuracy |
|
|
330
193
|
|---|---|---|---|---|---|---|
|
|
331
|
-
| **Zero-Token Architecture Discovery** | Full repo
|
|
332
|
-
| **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 |
|
|
333
196
|
| **Monorepo Lockfile Grep Leak** | `git grep` across lockfiles | 10,111 | **491** | **-95.1%** | 2 turns | 100% Pass |
|
|
334
197
|
| **Monorepo Lockfile Git Diff** | Monorepo branch diff | 18,911 | **761** | **-96.0%** | 2 turns | 100% Pass |
|
|
335
198
|
| **Multi-Turn History Compaction** | 8-turn session history fold | 31,010 | **3,130** | **-89.9%** | 8 turns | 100% Pass |
|
|
336
|
-
| **Race Condition / Distributed Lock** | AST query & Redis redlock | 5,074 | **404** | **-92.0%** | **4
|
|
337
|
-
| **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 |
|
|
338
201
|
| **CI Test Failure Extraction** | Full test log & stack trace | 5,009 | **1,127** | **-77.5%** | 3 turns | 100% Pass |
|
|
339
202
|
|
|
340
|
-
> **How to read these numbers:**
|
|
341
|
-
|
|
342
|
-
---
|
|
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)).
|
|
343
204
|
|
|
344
205
|
## Metrics Honesty
|
|
345
206
|
|
|
@@ -348,9 +209,7 @@ TokenSafe labels every savings event as one of:
|
|
|
348
209
|
- **`measured`**: the model literally received fewer bytes than the tool produced (sliced file reads, filtered command output, AST skeletons).
|
|
349
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).
|
|
350
211
|
|
|
351
|
-
Totals
|
|
352
|
-
|
|
353
|
-
---
|
|
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)**.
|
|
354
213
|
|
|
355
214
|
## Pricing and 7-Day Team Trial
|
|
356
215
|
|
|
@@ -358,190 +217,120 @@ TokenSafe follows an open-core model: verify local context savings and guardrail
|
|
|
358
217
|
|
|
359
218
|
| Plan | Price | Monthly Allowance | Included Capabilities |
|
|
360
219
|
|---|---|---|---|
|
|
361
|
-
| **Developer Sandbox** | **$0** forever | **500,000 tokens / mo** | 9-
|
|
362
|
-
| **Engineering Team** *(Recommended)* | **$29 / seat / mo** *(~$24 / seat / mo billed $290/yr)* | **Unlimited** | **7-Day Free Trial**, **
|
|
363
|
-
| **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 |
|
|
364
223
|
|
|
365
224
|
*Working solo? [Individual Solo plans](https://tokensafe.dev#pricing) start at **$9 / mo** ($89 / yr).*
|
|
366
225
|
|
|
367
|
-
|
|
226
|
+
`7-Day Free Trial · Offline Ed25519 Seat Keys (TS2.*) · Zero Source Code Transmitted · Cancel anytime`
|
|
368
227
|
|
|
369
|
-
|
|
228
|
+
**[Start a 7-Day Team Trial](https://tokensafe.dev#pricing)** **[Run Free Locally](#install--agents)**
|
|
370
229
|
|
|
371
|
-
##
|
|
230
|
+
## FAQ
|
|
372
231
|
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
tokensafe stats
|
|
376
|
-
```
|
|
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.
|
|
377
234
|
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
│ ⚡ TOKENSAFE CONTEXT OPTIMIZER DASHBOARD ⚡ │
|
|
381
|
-
└────────────────────────────────────────────────────────────────────────┘
|
|
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.
|
|
382
237
|
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
Estimated Savings: $6.7865 USD
|
|
386
|
-
Context Traffic: 4,889,255 raw ➔ 370,574 optimized (2132 events)
|
|
387
|
-
|
|
388
|
-
── Breakdown by Source ──────────────────────────────────────────────────
|
|
389
|
-
• AST Skeletonizer (Signatures) : 3,509 tokens saved (2 events)
|
|
390
|
-
• Command Sanitizer (CLI) : 727,300 tokens saved (263 events)
|
|
391
|
-
• Context Governor : 5,800 tokens saved (29 events)
|
|
392
|
-
• Graph-Guided Slicer (Call-Graph) : 42,420 tokens saved (14 events)
|
|
393
|
-
• Architecture Graph (God Nodes) : 758,256 tokens saved (13 events)
|
|
394
|
-
• Multi-turn History Fold : 2,897,897 tokens saved (471 events)
|
|
395
|
-
• Output Token Guard (write_file) : 42,466 tokens saved (84 events)
|
|
396
|
-
• Prompt Compactor (TOCP + Cache) : 43,502 tokens saved (1255 events)
|
|
397
|
-
• File Line Slicer (AST) : 3,006 tokens saved (1 events)
|
|
398
|
-
|
|
399
|
-
Run `tokensafe test "<prompt>"` to test compression on custom input.
|
|
400
|
-
Run `tokensafe html` to view interactive browser dashboard.
|
|
401
|
-
```
|
|
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.
|
|
402
240
|
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
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).
|
|
406
243
|
|
|
407
|
-
|
|
408
|
-
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).
|
|
409
246
|
|
|
410
|
-
|
|
411
|
-
|
|
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.
|
|
412
249
|
|
|
413
|
-
|
|
414
|
-
tokensafe doctor
|
|
250
|
+
## Reference
|
|
415
251
|
|
|
416
|
-
|
|
417
|
-
|
|
252
|
+
<details>
|
|
253
|
+
<summary><b>Local MCP tools (12)</b></summary>
|
|
418
254
|
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
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>
|
|
429
270
|
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
tokensafe prune
|
|
271
|
+
<details>
|
|
272
|
+
<summary><b>Cloud MCP tools (13)</b></summary>
|
|
433
273
|
|
|
434
|
-
|
|
435
|
-
tokensafe digest
|
|
436
|
-
|
|
437
|
-
# Run the SWE-bench verification suite
|
|
438
|
-
tokensafe benchmark
|
|
439
|
-
|
|
440
|
-
# Run the unit test suite (compact failure report, full: --traceback / -v)
|
|
441
|
-
tokensafe tests
|
|
274
|
+
Endpoint: `https://api.tokensafe.dev/mcp`, auth `Authorization: Bearer <TS1./TS2. key>`.
|
|
442
275
|
|
|
443
|
-
|
|
444
|
-
|
|
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>
|
|
445
295
|
|
|
446
|
-
|
|
447
|
-
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
|
|
448
318
|
```
|
|
319
|
+
</details>
|
|
449
320
|
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
## Self-Hosted Docker Deployment
|
|
453
|
-
|
|
454
|
-
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`).
|
|
455
|
-
|
|
456
|
-
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).
|
|
457
|
-
|
|
458
|
-
---
|
|
459
|
-
|
|
460
|
-
## Security Architecture & Cloud API Endpoints
|
|
461
|
-
|
|
462
|
-
TokenSafe Cloud Backend enforces strict zero-trust boundaries across client and server requests:
|
|
463
|
-
|
|
464
|
-
### 1. Cryptographic Authentication & Licensing
|
|
465
|
-
- **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.
|
|
466
|
-
- **JWT Session Tokens**: Cloud endpoints verify sessions via HS256 JWT bearer tokens or Clerk session tokens.
|
|
467
|
-
- **Dual Bearer Support**: Client endpoints accept either a signed license key (`TS2.*` / `TS1.*`) or a JWT in `Authorization: Bearer <token>`.
|
|
468
|
-
- **Zero Hardcoded Secrets**: all server credentials load strictly from runtime environment variables — nothing is hardcoded in the codebase.
|
|
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)
|
|
469
322
|
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
| Method | Endpoint | Auth Required | Headers / Parameters | Description |
|
|
473
|
-
|---|---|---|---|---|
|
|
474
|
-
| `GET` | `/api/health` | Public | None | Healthcheck and service version status. |
|
|
475
|
-
| `GET` | `/api/events` | Public | SSE `text/event-stream` | Real-time Server-Sent Events stream for live dashboard telemetry. |
|
|
476
|
-
| `GET` | `/api/dashboard` | **Bearer Auth** | `Authorization: Bearer <jwt\|key>` or `?license=<key>` | Authenticated user metrics, token savings, and license status. |
|
|
477
|
-
| `GET` | `/api/digest/preview` | **Bearer Auth** | `Authorization: Bearer <jwt\|key>` or `?team_id=<id>` | Previews current weekly team ROI digest (HTML / JSON). |
|
|
478
|
-
| `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. |
|
|
479
|
-
| `POST` | `/api/team/seat/revoke` | **Bearer Auth** | `Authorization: Bearer <jwt\|key>`, JSON `{ owner_email, license_key }` | Revokes an active team seat license key. |
|
|
480
|
-
| `POST` | `/api/telemetry/sync` | **License Auth** | JSON `{ license_key, email, events: [...] }` | Syncs batch telemetry events (enforces max 50 events/batch). |
|
|
481
|
-
|
|
482
|
-
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).
|
|
483
|
-
|
|
484
|
-
---
|
|
323
|
+
## Development and License
|
|
485
324
|
|
|
486
|
-
|
|
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)).
|
|
487
326
|
|
|
488
327
|
```bash
|
|
489
|
-
|
|
328
|
+
# Run the unit test suite (compact failure report; full: --traceback / -v)
|
|
329
|
+
tokensafe tests
|
|
490
330
|
```
|
|
491
|
-
*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.*
|
|
492
|
-
|
|
493
|
-
---
|
|
494
|
-
|
|
495
|
-
## License
|
|
496
|
-
MIT License. Commercial licenses are available for self-hosted B2B and enterprise VPC deployments.
|
|
497
331
|
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
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)
|
|
501
335
|
|
|
502
|
-
|
|
503
|
-
agy-token-optimizer/
|
|
504
|
-
├── plugin.json # Antigravity plugin manifest
|
|
505
|
-
├── hooks.json # Lifecycle hook declarations (PreInvocation, PreToolUse, PostToolUse)
|
|
506
|
-
├── Dockerfile # Hardened multi-stage container deployment
|
|
507
|
-
├── docker-compose.yml # Production Docker compose with multi-provider routing
|
|
508
|
-
├── rules/
|
|
509
|
-
│ └── AGENTS.md # TOCP Protocol directives for LLM (prompt-cached)
|
|
510
|
-
├── skills/
|
|
511
|
-
│ └── token-optimizer/
|
|
512
|
-
│ └── SKILL.md # On-demand Antigravity skill
|
|
513
|
-
├── proto/
|
|
514
|
-
│ └── tocp.proto # Protocol Buffers contract
|
|
515
|
-
├── src/
|
|
516
|
-
│ ├── cli.py # Unified CLI dispatcher (npm, pip, standalone)
|
|
517
|
-
│ ├── cache_normalizer.py # Prompt Cache Prefix Normalizer (Anthropic & DeepSeek)
|
|
518
|
-
│ ├── governor.py # Context Window Governor & Token Ceiling (Cascading reduction)
|
|
519
|
-
│ ├── agent_firewall.py # Cross-Agent Deduplication Cache (Subagent Firewall)
|
|
520
|
-
│ ├── diff_slicer.py # AST Diff Slicer & Lockfile Stripper (`git diff -U2`)
|
|
521
|
-
│ ├── weekly_digest.py # Friday Team ROI Digest & Engineer Leaderboard
|
|
522
|
-
│ ├── environment_auditor.py # MCP Server & Skill context token tax auditor
|
|
523
|
-
│ ├── command_sanitizer.py # High-output terminal command sanitizer
|
|
524
|
-
│ ├── proxy.py # Multi-provider transparent AI proxy & SSE broadcaster
|
|
525
|
-
│ ├── graph_engine.py # Sub-30ms AST parser, call graphs & God Node centrality
|
|
526
|
-
│ ├── tokenizer.py # Zero-dependency calibrated BPE token counter
|
|
527
|
-
│ ├── compactor.py # Semantic compactor (Local Regex + Distillation -> TOCP S-Expr)
|
|
528
|
-
│ ├── distiller.py # Multi-provider LLM distillation engine (Gemini, DeepSeek, OpenAI)
|
|
529
|
-
│ ├── distiller_cache.py # Two-tier LRU + SQLite prompt distillation cache
|
|
530
|
-
│ ├── deepseek_distiller.py # DeepSeek-Flash semantic compiler with token arbitrage guard
|
|
531
|
-
│ ├── slicer.py # AST & Line windowing tool optimizer
|
|
532
|
-
│ ├── metrics.py # Persistent SQLite metrics engine
|
|
533
|
-
│ ├── dashboard.py # Visual ANSI terminal, Markdown & reactive SSE web dashboard
|
|
534
|
-
│ ├── license_manager.py # Ed25519 cryptographic license verification
|
|
535
|
-
│ ├── mcp_server.py # Native Model Context Protocol (MCP) server
|
|
536
|
-
│ ├── installer.py # Multi-IDE agent auto-installer & config wizard
|
|
537
|
-
├── hooks/
|
|
538
|
-
│ ├── pre_invocation.py # PreInvocation hook entry point
|
|
539
|
-
│ ├── pre_tool_use.py # PreToolUse hook entry point
|
|
540
|
-
│ └── post_tool_use.py # PostToolUse hook entry point
|
|
541
|
-
├── bin/
|
|
542
|
-
│ ├── tokensafe.js # Node.js npm launcher (npx tokensafe)
|
|
543
|
-
│ └── tokensafe # Python CLI launcher (pip / standalone)
|
|
544
|
-
├── tests/ # Unit test suite
|
|
545
|
-
├── install.sh # One-click installer for Antigravity
|
|
546
|
-
└── README.md
|
|
547
|
-
```
|
|
336
|
+
MIT License. Commercial licenses are available for self-hosted B2B and enterprise VPC deployments. Questions: [corp@tokensafe.dev](mailto:corp@tokensafe.dev) · [tokensafe.dev](https://tokensafe.dev)
|
package/hooks/pre_invocation.py
CHANGED
|
@@ -190,8 +190,15 @@ def main():
|
|
|
190
190
|
"• To inspect all exported types/interfaces: call 'tokensafe:get_api_surface(project_path)'.\n"
|
|
191
191
|
"• Prefer 'edit_file' over 'write_file' for existing files."
|
|
192
192
|
)
|
|
193
|
+
# systemMessage nested form (hooks.md contract): ephemeralMessage is
|
|
194
|
+
# deprecated and is converted to a hidden system message anyway. This
|
|
195
|
+
# reminder only fires on guard violations / fresh history folds, so
|
|
196
|
+
# persistence here is intentional reinforcement, not per-turn bloat.
|
|
193
197
|
inject_steps.append({
|
|
194
|
-
"
|
|
198
|
+
"systemMessage": {
|
|
199
|
+
"systemMessage": protocol_reminder,
|
|
200
|
+
"metadata": {}
|
|
201
|
+
}
|
|
195
202
|
})
|
|
196
203
|
|
|
197
204
|
# 5. Context Budget HUD warning: inject once per session when the
|
package/hooks/pre_tool_use.py
CHANGED
|
@@ -139,6 +139,13 @@ def main():
|
|
|
139
139
|
path = args.get("Path") or args.get("path") or args.get("FilePath") or ""
|
|
140
140
|
start_line = args.get("StartLine") or args.get("startLine")
|
|
141
141
|
end_line = args.get("EndLine") or args.get("endLine")
|
|
142
|
+
# The overwrite merge is shallow top-level key replacement — we must
|
|
143
|
+
# rewrite the SAME keys the agent actually sent, or a "path"/"FilePath"
|
|
144
|
+
# read would get the optimized content under a brand-new "Path" key
|
|
145
|
+
# while its original argument still points at the full file.
|
|
146
|
+
path_key = next((k for k in ("Path", "path", "FilePath") if k in args), "Path")
|
|
147
|
+
start_key = next((k for k in ("StartLine", "startLine") if k in args), "StartLine")
|
|
148
|
+
end_key = next((k for k in ("EndLine", "endLine") if k in args), "EndLine")
|
|
142
149
|
|
|
143
150
|
if is_quota_exceeded:
|
|
144
151
|
# Free tier quota reached: pass through raw read_file without AST skeletonization
|
|
@@ -167,7 +174,7 @@ def main():
|
|
|
167
174
|
skel_path, orig_t, skel_t = Skeletonizer.get_skeleton_file(path, target_symbol=target_sym)
|
|
168
175
|
if skel_path and orig_t > skel_t:
|
|
169
176
|
saved = orig_t - skel_t
|
|
170
|
-
response["overwrite"] = {
|
|
177
|
+
response["overwrite"] = {path_key: skel_path}
|
|
171
178
|
response["reason"] = f"Token Optimizer: Graph-guided AST view for '{target_sym}' (Saved ~{saved} tokens)"
|
|
172
179
|
tracker.record_event(
|
|
173
180
|
session_id=conversation_id,
|
|
@@ -184,7 +191,10 @@ def main():
|
|
|
184
191
|
return
|
|
185
192
|
|
|
186
193
|
if overwrite_args and metrics.get("saved_tokens", 0) > 0:
|
|
187
|
-
response["overwrite"] =
|
|
194
|
+
response["overwrite"] = {
|
|
195
|
+
start_key: overwrite_args["StartLine"],
|
|
196
|
+
end_key: overwrite_args["EndLine"],
|
|
197
|
+
}
|
|
188
198
|
response["reason"] = (
|
|
189
199
|
f"Token Optimizer: Sliced read window to lines "
|
|
190
200
|
f"{overwrite_args['StartLine']}-{overwrite_args['EndLine']} (Saved ~{metrics['saved_tokens']} tokens)"
|
|
@@ -209,7 +219,7 @@ def main():
|
|
|
209
219
|
skeleton_path, orig_t, skel_t = Skeletonizer.get_skeleton_file(path)
|
|
210
220
|
if skeleton_path and orig_t > skel_t:
|
|
211
221
|
saved = orig_t - skel_t
|
|
212
|
-
response["overwrite"] = {
|
|
222
|
+
response["overwrite"] = {path_key: skeleton_path}
|
|
213
223
|
response["reason"] = (
|
|
214
224
|
f"Token Optimizer: Provided AST skeleton view (Saved ~{saved} tokens). "
|
|
215
225
|
f"Call read_file with StartLine/EndLine to inspect specific method bodies."
|
package/package.json
CHANGED
package/plugin.json
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tokensafe",
|
|
3
3
|
"displayName": "TokenSafe",
|
|
4
|
-
"version": "2.
|
|
5
|
-
"description": "
|
|
4
|
+
"version": "2.4.1",
|
|
5
|
+
"description": "Local-first guardrails, focused context & auditable team ROI for AI coding agents. Agents read only the code they need, secrets get blocked before commit.",
|
|
6
6
|
"logo": "assets/logo.svg",
|
|
7
7
|
"author": {
|
|
8
8
|
"name": "Oleg Savelev",
|
package/server.json
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"name": "dev.tokensafe/tokensafe",
|
|
4
4
|
"title": "TokenSafe",
|
|
5
5
|
"description": "Cut AI coding agent token usage up to 90% via AST slicing, dependency graphs & security guards.",
|
|
6
|
-
"version": "2.
|
|
6
|
+
"version": "2.4.1",
|
|
7
7
|
"websiteUrl": "https://tokensafe.dev",
|
|
8
8
|
"repository": {
|
|
9
9
|
"url": "https://github.com/tokensafe-dev/tokensafe",
|
|
@@ -30,7 +30,7 @@
|
|
|
30
30
|
"registryType": "npm",
|
|
31
31
|
"registryBaseUrl": "https://registry.npmjs.org",
|
|
32
32
|
"identifier": "tokensafe",
|
|
33
|
-
"version": "2.
|
|
33
|
+
"version": "2.4.1",
|
|
34
34
|
"runtimeHint": "npx",
|
|
35
35
|
"transport": {
|
|
36
36
|
"type": "stdio"
|
|
@@ -46,7 +46,7 @@
|
|
|
46
46
|
"registryType": "pypi",
|
|
47
47
|
"registryBaseUrl": "https://pypi.org",
|
|
48
48
|
"identifier": "tokensafe",
|
|
49
|
-
"version": "2.
|
|
49
|
+
"version": "2.4.1",
|
|
50
50
|
"runtimeHint": "uvx",
|
|
51
51
|
"transport": {
|
|
52
52
|
"type": "stdio"
|
|
@@ -58,5 +58,25 @@
|
|
|
58
58
|
}
|
|
59
59
|
]
|
|
60
60
|
}
|
|
61
|
+
],
|
|
62
|
+
"remotes": [
|
|
63
|
+
{
|
|
64
|
+
"type": "streamable-http",
|
|
65
|
+
"url": "https://api.tokensafe.dev/mcp",
|
|
66
|
+
"headers": [
|
|
67
|
+
{
|
|
68
|
+
"name": "Authorization",
|
|
69
|
+
"value": "Bearer {tokensafe_license_key}",
|
|
70
|
+
"isSecret": true,
|
|
71
|
+
"variables": {
|
|
72
|
+
"tokensafe_license_key": {
|
|
73
|
+
"description": "TokenSafe license key (TS1./TS2.) from tokensafe.dev. Optional: public tools (stats, docs, setup) work without it.",
|
|
74
|
+
"isSecret": true,
|
|
75
|
+
"required": false
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
]
|
|
80
|
+
}
|
|
61
81
|
]
|
|
62
82
|
}
|
package/src/cli.py
CHANGED
|
@@ -32,7 +32,8 @@ def summarize_unittest_output(raw: str, full_traceback: bool = False) -> str:
|
|
|
32
32
|
s = ln.strip()
|
|
33
33
|
if s.startswith("Ran ") and " test" in s:
|
|
34
34
|
ran = s
|
|
35
|
-
elif s
|
|
35
|
+
elif s.startswith("OK") or s.startswith("FAILED"):
|
|
36
|
+
# "OK (skipped=N)" must count as success too, not just bare "OK".
|
|
36
37
|
status = s
|
|
37
38
|
# Failure blocks: one '=' * 70 line PER failure, then the title line,
|
|
38
39
|
# a '-' * 70 rule and the traceback — each block is self-contained.
|
|
@@ -80,7 +81,7 @@ def summarize_unittest_output(raw: str, full_traceback: bool = False) -> str:
|
|
|
80
81
|
tail = [l for l in lines if l.strip()][-15:]
|
|
81
82
|
return "\n".join(tail) if tail else "(no unittest output captured)"
|
|
82
83
|
|
|
83
|
-
if status
|
|
84
|
+
if status.startswith("OK"):
|
|
84
85
|
return f"\033[32m✓ {ran} — all tests passed\033[0m"
|
|
85
86
|
|
|
86
87
|
out = [f"\033[31m✗ {ran} — {status}\033[0m"]
|
|
@@ -52,23 +52,66 @@ class EnvironmentAuditor:
|
|
|
52
52
|
]
|
|
53
53
|
return [d for d in dirs if os.path.isdir(d)]
|
|
54
54
|
|
|
55
|
+
@classmethod
|
|
56
|
+
def get_plugins_dir(cls) -> str:
|
|
57
|
+
return os.path.join(os.path.expanduser("~"), ".gemini", "config", "plugins")
|
|
58
|
+
|
|
59
|
+
@classmethod
|
|
60
|
+
def get_enable_state_path(cls) -> str:
|
|
61
|
+
return os.path.join(os.path.expanduser("~"), ".gemini", "config", "config.json")
|
|
62
|
+
|
|
63
|
+
@classmethod
|
|
64
|
+
def _get_disabled_plugin_names(cls) -> set:
|
|
65
|
+
"""Plugin directory names that are switched off. plugins.md: the
|
|
66
|
+
enable-state lives in config.json under a `plugins` map keyed by the
|
|
67
|
+
plugin's directory name; a `plugin.json` `"disabled": true` also ships
|
|
68
|
+
a plugin switched off."""
|
|
69
|
+
disabled = set()
|
|
70
|
+
state_path = cls.get_enable_state_path()
|
|
71
|
+
if os.path.isfile(state_path):
|
|
72
|
+
try:
|
|
73
|
+
with open(state_path, "r", encoding="utf-8") as f:
|
|
74
|
+
plugins_state = json.load(f).get("plugins", {})
|
|
75
|
+
for name, state in plugins_state.items():
|
|
76
|
+
if isinstance(state, dict) and state.get("enabled") is False:
|
|
77
|
+
disabled.add(name)
|
|
78
|
+
except Exception:
|
|
79
|
+
pass
|
|
80
|
+
plugins_dir = cls.get_plugins_dir()
|
|
81
|
+
if os.path.isdir(plugins_dir):
|
|
82
|
+
for entry in os.listdir(plugins_dir):
|
|
83
|
+
manifest = os.path.join(plugins_dir, entry, "plugin.json")
|
|
84
|
+
if os.path.isfile(manifest):
|
|
85
|
+
try:
|
|
86
|
+
with open(manifest, "r", encoding="utf-8") as f:
|
|
87
|
+
if json.load(f).get("disabled") is True:
|
|
88
|
+
disabled.add(entry)
|
|
89
|
+
except Exception:
|
|
90
|
+
pass
|
|
91
|
+
return disabled
|
|
92
|
+
|
|
55
93
|
@classmethod
|
|
56
94
|
def get_configured_mcp_servers(cls) -> Dict[str, Any]:
|
|
57
95
|
configured: Dict[str, Any] = {}
|
|
96
|
+
# Merge EVERY present config file: both ~/.gemini/config and the
|
|
97
|
+
# antigravity dir can legitimately carry servers (they are merged by
|
|
98
|
+
# Antigravity too), so breaking on the first one undercounts.
|
|
58
99
|
for p in cls.get_config_paths():
|
|
59
100
|
if os.path.isfile(p):
|
|
60
101
|
try:
|
|
61
102
|
with open(p, "r", encoding="utf-8") as f:
|
|
62
|
-
|
|
63
|
-
configured.update(data.get("mcpServers", {}))
|
|
64
|
-
break
|
|
103
|
+
configured.update(json.load(f).get("mcpServers", {}))
|
|
65
104
|
except Exception:
|
|
66
105
|
continue
|
|
67
106
|
# Plugin-declared servers (plugins/<name>/mcp_config.json) are loaded
|
|
68
|
-
# by Antigravity together with the plugin — audit them too
|
|
69
|
-
|
|
107
|
+
# by Antigravity together with the plugin — audit them too, unless the
|
|
108
|
+
# plugin itself is disabled.
|
|
109
|
+
disabled = cls._get_disabled_plugin_names()
|
|
110
|
+
plugins_dir = cls.get_plugins_dir()
|
|
70
111
|
if os.path.isdir(plugins_dir):
|
|
71
112
|
for entry in sorted(os.listdir(plugins_dir)):
|
|
113
|
+
if entry in disabled or entry.endswith(".disabled"):
|
|
114
|
+
continue
|
|
72
115
|
plugin_cfg = os.path.join(plugins_dir, entry, "mcp_config.json")
|
|
73
116
|
if not os.path.isfile(plugin_cfg):
|
|
74
117
|
continue
|
package/src/history_compactor.py
CHANGED
|
@@ -61,7 +61,7 @@ class HistoryCompactor:
|
|
|
61
61
|
if p:
|
|
62
62
|
read_files.add(os.path.basename(p))
|
|
63
63
|
elif name in ("edit_file", "write_file"):
|
|
64
|
-
p = args.get("Path"
|
|
64
|
+
p = args.get("Path") or args.get("path") or args.get("FilePath") or ""
|
|
65
65
|
if p:
|
|
66
66
|
edited_files.add(os.path.basename(p))
|
|
67
67
|
elif name == "run_command":
|
package/src/loop_detector.py
CHANGED
|
@@ -10,10 +10,12 @@ import hashlib
|
|
|
10
10
|
from contextlib import contextmanager
|
|
11
11
|
from typing import Dict, Any, Tuple
|
|
12
12
|
|
|
13
|
+
from src.paths import resolve_data_dir
|
|
14
|
+
|
|
13
15
|
class LoopDetector:
|
|
14
16
|
"""Tracks tool invocation signatures to detect hallucination loops."""
|
|
15
17
|
|
|
16
|
-
STATE_FILE = os.path.join(
|
|
18
|
+
STATE_FILE = os.path.join(resolve_data_dir(), "loop_state.json")
|
|
17
19
|
MAX_IDENTICAL_REPEATS = 3
|
|
18
20
|
SESSION_TTL_SECONDS = 48 * 3600 # prune sessions idle for more than 2 days
|
|
19
21
|
|
package/src/mcp_server.py
CHANGED
package/src/skeletonizer.py
CHANGED
|
@@ -11,6 +11,7 @@ import hashlib
|
|
|
11
11
|
import json
|
|
12
12
|
from typing import Optional, Tuple, Set
|
|
13
13
|
from src.tokenizer import count_tokens
|
|
14
|
+
from src.paths import resolve_data_dir
|
|
14
15
|
|
|
15
16
|
CONTROL_KEYWORDS = {
|
|
16
17
|
'if', 'else', 'for', 'while', 'do', 'switch', 'case', 'default',
|
|
@@ -168,7 +169,7 @@ class Skeletonizer:
|
|
|
168
169
|
out.append("".join(res))
|
|
169
170
|
return out
|
|
170
171
|
|
|
171
|
-
CACHE_DIR = os.path.join(
|
|
172
|
+
CACHE_DIR = os.path.join(resolve_data_dir(), "skeletons")
|
|
172
173
|
|
|
173
174
|
@classmethod
|
|
174
175
|
def skeletonize_code(cls, code: str, file_ext: str, keep_symbols: Optional[Set[str]] = None) -> str:
|
package/src/slicer.py
CHANGED
|
@@ -79,9 +79,11 @@ class ToolSlicer:
|
|
|
79
79
|
If a file is large and no bounds are given, locates target symbol or applies windowing.
|
|
80
80
|
Returns: (modified_args_or_none, metrics_dict)
|
|
81
81
|
"""
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
82
|
+
# Tolerant arg keys: hooks keep proto casing ("Path"), but the
|
|
83
|
+
# view_file/lowercase variants may send "path"/"FilePath".
|
|
84
|
+
path = args.get("Path") or args.get("path") or args.get("FilePath") or ""
|
|
85
|
+
start_line = args.get("StartLine") or args.get("startLine")
|
|
86
|
+
end_line = args.get("EndLine") or args.get("endLine")
|
|
85
87
|
|
|
86
88
|
if not path or not os.path.isabs(path) or not os.path.exists(path):
|
|
87
89
|
return {}, {"saved_tokens": 0, "original_tokens": 0, "optimized_tokens": 0}
|
package/src/telemetry_sync.py
CHANGED
|
@@ -266,7 +266,7 @@ class TelemetrySync:
|
|
|
266
266
|
rollup_synced = bool(state.get("lifetime_rollup_synced", False))
|
|
267
267
|
headers = {
|
|
268
268
|
"Content-Type": "application/json",
|
|
269
|
-
"User-Agent": "TokenSafe-Sync/2.
|
|
269
|
+
"User-Agent": "TokenSafe-Sync/2.4.1"
|
|
270
270
|
}
|
|
271
271
|
if active_key:
|
|
272
272
|
headers["Authorization"] = f"Bearer {active_key}"
|
package/src/version_checker.py
CHANGED
|
@@ -16,7 +16,7 @@ import urllib.request
|
|
|
16
16
|
import urllib.error
|
|
17
17
|
from typing import Dict, Any, Optional, Tuple
|
|
18
18
|
|
|
19
|
-
CURRENT_VERSION = "2.
|
|
19
|
+
CURRENT_VERSION = "2.4.1"
|
|
20
20
|
CACHE_TTL = 86400 # 24 hours
|
|
21
21
|
# When the cloud is unreachable we must NOT cache the synthesized "up to date"
|
|
22
22
|
# answer for a full day — otherwise an update released right after an outage
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|