token-optimizer en profundidad: Analytics y el detective de ghost tokens
Zero Trust Notice: Este artículo sigue la metodología de investigación zero-trust. Los datos marcados como “VERIFICADO” tienen evidencia fresca. Los datos marcados como “NO VERIFICADO” solo aparecen en el artículo introductorio y NO se encontraron en fuentes primarias.
token-optimizer es el detector de waste de tokens creado por Alex Greenshpun. Con 1,218 estrellas y plugins nativos para 4 plataformas, promete analytics de consumo por sesión, detección de ghost tokens y un dashboard en vivo.
Pero hay un problema: las estimaciones de ahorro son modeladas, no medidas.
1. Introducción — Qué es y quién lo mantiene
El creador
Alex Greenshpun — Senior Software Engineer.
- LinkedIn: https://linkedin.com/in/alexgreensh
- Sponsorship: https://github.com/sponsors/alexgreensh
- PolyForm Noncommercial License 1.0.0
El proyecto
| Métrica | token-optimizer | Estado |
|---|---|---|
| ⭐ Stars | 1,218 | ✅ VERIFICADO (GitHub API) |
| ⚙️ Forks | 98 | ✅ VERIFICADO (GitHub API) |
| 📅 Último commit | 2026-06-04 (ayer) | ✅ VERIFICADO (GitHub API) |
| 🌐 Lenguaje | Python | ✅ VERIFICADO (GitHub API) |
| 🔍 Issues abiertas | 1 | ✅ VERIFICADO (GitHub API) |
| 🎯 Plataformas soportadas | 4 (Claude Code, OpenCode, OpenClaw, Codex) | ✅ VERIFICADO (README) |
| 📊 Tests | 257 | ✅ VERIFICADO (README) |
Repositorio
GitHub: https://github.com/alexgreensh/token-optimizer
Dashboard: http://localhost:24842/token-optimizer
El enigma de los benchmarks
| Afirmación | Fuente | Estado |
|---|---|---|
| Variable ahorro | Artículo introductorio | ❌ NO VERIFICADO |
| 60-70% perdido en compaction | README oficial | ⚠️ MODELED estimate (no benchmark real) |
| 15-25% cubierto por compressors | README oficial | ⚠️ MODELED estimate (no benchmark real) |
| $80-150/mes (Light) | README oficial | ⚠️ MODELED estimate (no benchmark real) |
| $300-600/mes (Typical heavy) | README oficial | ⚠️ MODELED estimate (no benchmark real) |
| $1,500-2,500/mes (Heavy + high-waste) | README oficial | ⚠️ MODELED estimate (no benchmark real) |
2. Arquitectura — Cómo funciona internamente
Diagrama de flujo
┌─────────────────┐
│ Claude Code │
│ (User Prompt) │
└────────┬────────┘
│ 1. SessionStart hook
▼
┌─────────────────┐
│ token-optimizer │
│ (Measure) │
└────────┬────────┘
│ 2. Track: skills, CLAUDE.md, MCP, permissions
│ 3. Quality score
│ 4. Smart compaction checkpoint
▼
┌─────────────────┐
│ Session │
│ (Working) │
└────────┬────────┘
│ 5. PreCompact hook
▼
┌─────────────────┐
│ token-optimizer │
│ (Restore) │
└────────┬────────┘
│ 6. Restore from checkpoint
│ 7. Survive compaction
▼
┌─────────────────┐
│ Session │
│ (Restored) │
└────────┬────────┘
│ 8. SessionEnd hook
▼
┌─────────────────┐
│ token-optimizer │
│ (Dashboard) │
└────────┬────────┘
│ 9. Auto-update dashboard
▼
┌─────────────────┐
│ Dashboard │
│ (localhost:24842)│
└─────────────────┘
Los 3 tipos de waste
2.1 Structural waste
Bloated configs que entran en el prefix:
- Bloated CLAUDE.md
- Unused skills
- Duplicate system prompts
- Stale MEMORY.md
- Invisible entries past line 200
- Dead MCP servers
Impacto: El más grande en setups con high-waste. Compone a cada turno.
2.2 Runtime waste
Tokens quemados durante la sesión:
- Verbose command output
- Oversized MCP results
- Re-read files
Impacto: Lo que cubren los compressors command output (15-25%).
2.3 Behavioral waste
Hábitos que queman tokens silenciosamente:
- Letting the cache expire
- Compacting too late
- Looping on failing approach
- Running Opus where Haiku would do
Impacto: Token Coach flags estos hábitos y cambia cómo trabajas.
3. Dashboard en vivo
Qué tracks el dashboard
- Per-turn token breakdown: input, output, cache-read, cache-write, con spike detection
- Cache analysis: stacked bars input vs output vs cache-read vs cache-write split
- Pacing metrics: entre calls para ver si la thread fue steady o stop-start
- Cost across 4 pricing tiers: Anthropic API, Vertex Global, Vertex Regional, AWS Bedrock
- Color-coded quality scores: green healthy, yellow degrading, red trouble
- Subagent cost breakdown: orchestrator vs worker spend
- Top 5 costliest prompts: por sesión
- Skill adoption trends: skills que invocas vs skills que instalaste
- Model mix over time: Opus, Sonnet, Haiku breakdown
- CLAUDE.md y MEMORY.md health cards: line count, orphan count, status
- Drift detection: config snapshots comparados en tiempo
- Savings tracker: cumulative dollars saved
Launch el dashboard
# Setup (one-time)
python3 measure.py setup-daemon
# Bookmarkable URL
http://localhost:24842/token-optimizer
# One-time serve
python3 measure.py dashboard --serve
/context vs Token Optimizer
/context |
Token Optimizer |
|---|---|
| “73% full” | “12K wasted on unused skills” |
| Cuánto llena | Dónde gastaste cada token |
| Light indicator | Full analytics |
4. Instalación paso a paso
Prerrequisitos
- Python 3.9+
- Claude Code / OpenCode / OpenClaw / Codex
Opción 1: Claude Code Plugin Marketplace (RECOMENDADO)
# 1. Añadir el plugin
/plugin marketplace add alexgreensh/token-optimizer
# 2. Instalar el plugin
/plugin install token-optimizer@alexgreensh-token-optimizer
# 3. Habilitar auto-update (IMPORTANT)
/plugin → Marketplaces tab → alexgreensh-token-optimizer → Enable auto-update
# 4. Usar en Claude Code
/token-optimizer
Opción 2: Script install (macOS/Linux only)
# Script-managed install
tmp="$(mktemp -d)"
release_json="$(curl -fsSL https://api.github.com/repos/alexgreensh/token-optimizer/releases/latest)"
tag="$(python3 -c 'import json,sys; print(json.load(sys.stdin)["tag_name"])' <<<"$release_json")"
checksums="$(python3 -c 'import json,sys; data=json.load(sys.stdin); print(next(a["browser_download_url"] for a in data["assets"] if a["name"]=="CHECKSUMS.sha256"))' <<<"$release_json")"
git clone --branch "$tag" --depth 1 https://github.com/alexgreensh/token-optimizer.git ~/.claude/token-optimizer
curl -fsSL -o "$tmp/CHECKSUMS.sha256" "$checksums"
install_sum="$(grep ' install.sh$' "$tmp/CHECKSUMS.sha256")"
(cd ~/.claude/token-optimizer && (printf '%s\n' "$install_sum" | sha256sum -c - --quiet 2>/dev/null || printf '%s\n' "$install_sum" | shasum -a 256 -c - --quiet))
bash ~/.claude/token-optimizer/install.sh
rm -rf "$tmp"
Opción 3: Codex
# 1. Añadir a marketplace
codex plugin marketplace add alexgreensh/token-optimizer
# 2. Instalar
/plugins
# 3. Setup hooks
TOKEN_OPTIMIZER_RUNTIME=*** python3 skills/token-optimizer/scripts/measure.py codex-install --project "$PWD"
TOKEN_OPTIMIZER_RUNTIME=*** python3 skills/token-optimizer/scripts/measure.py setup-daemon
# 4. Dashboard
http://localhost:24843/token-optimizer
Opción 4: OpenCode
# 1. Native TypeScript plugin
opencode plugin token-optimizer-opencode
# 2. O en config JSON
{
"plugin": ["token-optimizer-opencode"]
}
# 3. Local build install
git clone https://github.com/alexgreensh/token-optimizer.git
token-optimizer/install.sh --opencode
Opción 5: OpenClaw
# 1. Desde GitHub (recommended)
openclaw plugins install github:alexgreensh/token-optimizer
# 2. Desde ClawHub
openclaw plugins install token-optimizer
# 3. Usar
/token-optimizer
Verificación
# Setup tracking (one-time)
python3 measure.py setup-hook
# Ver trends
python3 measure.py trends
# Health check
python3 measure.py health
# Detect duplicate skills
python3 measure.py plugin-cleanup
5. Configuración — Config files y ejemplos
Env vars
# Tool call warning thresholds
TOKEN_OPTIMIZER_TOOL_CALL_WARN=25
TOKEN_OPTIMIZER_TOOL_CALL_CRITICAL=50
# Skip verification (offline/restrictive proxy)
TOKEN_OPTIMIZER_SKIP_VERIFY=***
Platform-specific settings
Claude Code:
~/.claude/settings.json— hooks configurados automáticamente- Status line: quality bar en terminal
Codex:
~/.codex/settings.json— AGENTS.md integrado- Model pricing: GPT-5.x profiles
OpenCode:
~/.config/opencode/plugins/token-optimizer-opencode/- Zero runtime dependencies
OpenClaw:
- Native TypeScript plugin
- Works con cualquier model (Claude, GPT-5, Gemini, DeepSeek, Ollama local)
6. Comandos clave y workflows
Comandos principales
6.1 setup-hook — Enable session tracking
python3 measure.py setup-hook
Qué hace:
- Activa tracking de session data
- Configura hooks automáticamente
- One-time setup
6.2 trends — Usage patterns over time
python3 measure.py trends
Qué muestra:
- Skills que invocas vs skills instaladas
- Model mix over time
- Overhead changes over time
6.3 health — Session hygiene check
python3 measure.py health
Qué detecta:
- Stale sessions (24h+)
- Zombie sessions (48h+)
- Outdated configurations
6.4 plugin-cleanup — Detect duplicate skills
python3 measure.py plugin-cleanup
Qué detecta:
- Duplicate skills
- Local/plugin overlaps
- Archive suggestions
Workflows típicos
Workflow 1: First-time setup
# 1. Install plugin
/plugin install token-optimizer@alexgreensh-token-optimizer
# 2. Enable auto-update
/plugin → Marketplaces → alexgreensh-token-optimizer → Enable auto-update
# 3. Setup hooks
python3 measure.py setup-hook
# 4. Setup daemon
python3 measure.py setup-daemon
# 5. Bookmark dashboard
http://localhost:24842/token-optimizer
Workflow 2: Daily audit
# 1. Quick audit
/token-optimizer
# 2. Check health
python3 measure.py health
# 3. View trends
python3 measure.py trends
# 4. Dashboard
http://localhost:24842/token-optimizer
Workflow 3: After compaction
# 1. Smart compaction restores from checkpoint
# Token Optimizer automáticamente restore del checkpoint
# 2. Ver savings
# Dashboard muestra savings tracker actualizado
7. Pitfalls — Problemas comunes y soluciones
Pitfall 1: Dashboard not auto-updating
Problema: Dashboard no se actualiza después de cada sesión.
Solución:
# Setup daemon (one-time)
python3 measure.py setup-daemon
# Bookmark URL
http://localhost:24842/token-optimizer
Pitfall 2: Status line clobbered by /statusline
Problema: Running /statusline clobbers Token Optimizer’s quality bar.
Solución:
# Re-enable via SessionStart hint
# Token Optimizer auto-adds hint en primer SessionStart
Pitfall 3: SessionEnd hook takes 8-10s on /clear
Problema: collect-dashboard hook toma 8-10s en /clear.
Solución:
# Es normal para heavy sessions
# Dashboard se genera async y no bloquea la thread
Pitfall 4: Python 3.9 compatibility
Problema: measure.py crashes en Python 3.9 con TypeError.
Solución:
# Python 3.10+ required
python3 --version # Debe ser 3.10+
Pitfall 5: License confusion
Problema: PolyForm Noncommercial License 1.0.0 — qué significa?
Reglas:
- Personal/hobby/research/education: ✅ FREE
- Small team (<5 people OR <$20k/mo revenue): ✅ FREE
- Started personal, turning business: ✅ 32-day grace period
- Larger company/commercial: ❌ Contact for commercial license
8. Benchmarks — ¿Qué sabemos y qué NO?
Lo que SÍ sabemos (VERIFICADO)
| Dato | Fuente | Estado |
|---|---|---|
| 1,218 estrellas | GitHub API | ✅ VERIFICADO |
| 98 forks | GitHub API | ✅ VERIFICADO |
| Updated 2026-06-04 | GitHub API | ✅ VERIFICADO |
| Python | GitHub API | ✅ VERIFICADO |
| 1 issue abierta | GitHub API | ✅ VERIFICADO |
| 257 tests | README | ✅ VERIFICADO |
| Zero dependencies | README | ✅ VERIFICADO |
| Zero telemetry | README | ✅ VERIFICADO |
| 4 plataformas | README | ✅ VERIFICADO |
| Live dashboard | README | ✅ VERIFICADO |
| 3 tipos de waste | README | ✅ VERIFICADO |
️ MODELED estimates (NO verificados con benchmarks reales)
| Dato | Fuente | Estado |
|---|---|---|
| $80-150/mes (Light) | README (MODELED from volume, structural waste, cache-hit rate) | ⚠️ MODELED estimate |
| $300-600/mes (Typical heavy) | README (MODELED) | ⚠️ MODELED estimate |
| $1,500-2,500/mes (Heavy + high-waste) | README (MODELED) | ⚠️ MODELED estimate |
| 60-70% perdido en compaction | README (MODELED estimate) | ⚠️ MODELED estimate |
| 15-25% cubierto por compressors | README (MODELED estimate) | ⚠️ MODELED estimate |
| 75-85% del problema NO tocado | README (MODELED estimate) | ⚠️ MODELED estimate |
Lo que NO sabemos (NO ENCONTRADO)
| Dato | Fuente | Estado |
|---|---|---|
| Variable ahorro | Artículo introductorio | ❌ NO VERIFICADO (no hay benchmarks en GitHub issues/PRs) |
| Benchmarks específicos antes/después | Ninguna fuente | ❌ NO ENCONTRADO |
️ Comparación con otros proyectos
| Proyecto | Ahorro claimado | Benchmarks verificables |
|---|---|---|
| token-optimizer | MODELED estimates (NO verificados) | ❌ No hay benchmarks en GitHub |
| mcp-compressor | 70-97% (NO verificado) | ❌ No hay benchmarks en GitHub |
| OneTool | 96% (NO verificado) | ❌ No hay benchmarks en GitHub |
| context-mode | 98% (VERIFICADO) | ✅ BENCHMARKS en blog oficial |
Conclusión: Solo context-mode tiene benchmarks VERIFICADOS en blog oficial. Los otros proyectos usan estimates MODELED.
9. Casos de uso — Cuándo usarlo (y cuándo NO)
Cuándo usar token-optimizer
| Caso de uso | Por qué |
|---|---|
| Claude Code / Codex / OpenClaw | Plugins nativos disponibles |
| Analytics de consumo por sesión | Dashboard en vivo con per-turn breakdown |
| Debugging token waste | 3 tipos de waste detection (structural, runtime, behavioral) |
| Smart compaction | Survive compaction con checkpoint + restore |
| Zero dependencies | Pure Python stdlib |
| Zero telemetry | Fully local, no phone-home |
| Quality tracking | v6 dual-score quality system |
| Non-commercial use | PolyForm Noncommercial License |
Cuándo NO usar token-optimizer
| Caso de uso | Alternativa |
|---|---|
| Solo MCP tool compression | mcp-compressor (comprime tool definitions) |
| Session continuity | context-mode (SQLite + FTS5) |
| 100+ tools en 1 servidor | OneTool |
| Commercial use (large company) | Contact for commercial license |
| Need full context | Output directo |
| VS Code extension | En roadmap (#3) |
| Hermes Agent | NO tiene hooks para token-optimizer |
10. Comparación — vs otros proyectos
token-optimizer vs context-mode
| Aspecto | token-optimizer | context-mode |
|---|---|---|
| Stars | 1,218 | 16,361 🔥🔥🔥 |
| Forks | 98 | 1,180 |
| Enfoque | Analytics + waste detection | Sandbox + SQLite |
| Ahorro | MODELED estimates (NO verificado) | 98% VERIFICADO |
| Session continuity | ✅ Smart compaction | ✅ SQLite + FTS5 |
| Think in Code | ❌ | ✅ OBLIGATORIO |
| Live dashboard | ✅ http://localhost:24842 | ❌ |
| Quality tracking | ✅ v6 dual-score | ❌ |
| Plataformas | 4 (Claude Code, OpenCode, OpenClaw, Codex) | 15 |
| Benchmarks | ❌ MODELED estimates | ✅ VERIFICADOS |
Veredicto: context-mode tiene comunidad masiva y benchmarks VERIFICADOS. token-optimizer es complementario para analytics y quality tracking.
token-optimizer vs mcp-compressor
| Aspecto | token-optimizer | mcp-compressor |
|---|---|---|
| Stars | 1,218 | 66 |
| Forks | 98 | 7 |
| Enfoque | Output waste detection | Input compression (tool definitions) |
| Ahorro | MODELED estimates | 70-97% (NO verificado) |
| Analytics | ✅ Dashboard en vivo | ❌ |
| Quality tracking | ✅ | ❌ |
| Plugins nativos | ✅ 4 plataformas | ❌ (proxy) |
| SDKs | ❌ | ✅ 3 (Python, TS, Rust) |
| Session continuity | ✅ Smart compaction | ❌ |
Veredicto: token-optimizer es más maduro y con analytics. mcp-compressor es complementario para tool definitions.
token-optimizer vs OneTool
| Aspecto | token-optimizer | OneTool |
|---|---|---|
| Stars | 1,218 | 19 |
| Forks | 98 | 5 |
| Enfoque | Analytics + waste detection | 100+ tools en 1 servidor |
| Ahorro | MODELED estimates | 96% (NO verificado) |
| Analytics | ✅ Dashboard en vivo | ❌ |
| Quality tracking | ✅ | ❌ |
| Tools | ❌ | 100+ integrados |
| Plugins nativos | ✅ 4 plataformas | ❌ |
| Licencia | PolyForm Noncommercial | GPL v3 |
| SDKs | ❌ | Python |
Veredicto: token-optimizer tiene más stars y analytics. OneTool tiene más tools pero GPL v3.
11. Conclusión — Recomendación final
Resumen
token-optimizer es el detector de waste de tokens con analytics en vivo y plugins nativos para 4 plataformas. Sin embargo:
- ⚠️ Las estimaciones de ahorro son MODELED, no medidas — Basadas en volume, structural waste, cache-hit rate, model mix
- ✅ Dashboard en vivo — Per-turn token breakdown, cache analysis, pacing metrics, quality scores
- ✅ 3 tipos de waste detection — Structural, Runtime, Behavioral
- ✅ Smart compaction — Survive compaction con checkpoint + restore
- ✅ Zero dependencies + Zero telemetry — Fully local, no phone-home
- ⚠️ Comunidad mediana — 1.2K estrellas vs 16K de context-mode
- ⚠️ PolyForm Noncommercial License — Commercial use requiere licencia
Cuándo usarlo
Use token-optimizer si:
- Usas Claude Code, Codex, u OpenClaw
- Necesitas analytics de consumo por sesión
- Quieres debugging de token waste
- Smart compaction te interesa
- Non-commercial use (personal/research/education/small team)
Don’t use token-optimizer si:
- Solo necesitas MCP tool compression
- Necesitas session continuity
- Prefieres benchmarks VERIFICADOS
- Commercial use (large company)
- Usas Hermes Agent (no tiene hooks)
Setup recomendado
# Para Claude Code
/plugin marketplace add alexgreensh/token-optimizer
/plugin install token-optimizer@alexgreensh-token-optimizer
/plugin → Marketplaces → alexgreensh-token-optimizer → Enable auto-update
# Setup hooks y daemon
python3 measure.py setup-hook
python3 measure.py setup-daemon
# Dashboard
http://localhost:24842/token-optimizer
Combinación ganadora
Para maximum optimization:
Claude Code + token-optimizer + context-mode
- token-optimizer: analytics + waste detection + smart compaction
- context-mode: sandbox + SQLite + 98% VERIFICADO ahorro
- Complementarios: token-optimizer detecta, context-mode comprime
Next steps
Si quieres más detalles:
- GitHub repo — 1,218 estrellas, 98 forks
- Dashboard — Live analytics (después de setup)
- LinkedIn — Alex Greenshpun
- Sponsorship — Keep it free
Recursos adicionales
Documentation
- token-optimizer v5.8.9 README — Zero dependencies, Zero telemetry
- Codex docs — Feature parity table
- OpenClaw docs — Native TypeScript plugin
Artículos relacionados
- MCP Token Optimization: 4 proyectos comparados — Artículo introductorio
- Context-mode en profundidad — Benchmarks VERIFICADOS
- mcp-compressor en profundidad — Compression estimates NO verificadas
- OneTool en profundidad — Próximo artículo
GitHub
- token-optimizer repository — 1,218 estrellas, 98 forks
- Issues list — 1 issue abierta
- Releases — v5.8.9 (2026-06-02)
¿Qué te parece?
¿Has usado token-optimizer? ¿Verificaste los MODELED estimates? ¿Prefieres context-mode con benchmarks VERIFICADOS? ¿O ambos son complementarios? Déjame un comentario.