ultra-claude-token-saver
v2.0.4
Published
All-in-one Claude Code token optimization: 17 strategies from LLMLingua, RouteLLM, GPTCache, tokencost, Aider, Letta, SWE-Pruner, AgentDiet, Portkey, Helicone, ccusage, claude-code-router, claude-mem, caveman, ruflo, and gstack. Save 80-95% on tokens.
Maintainers
Keywords
Readme
⚡ ultra-claude-token-saver v2.0
Save 80–95% on Claude Code tokens. 99 slash commands. 17 optimization stages. 59 files. Zero dependencies.
One npm install replaces juggling 16 separate repos. One ucts init installs everything into Claude Code — skills, hooks, executable scripts, and the full token-saving pipeline.
npm install -g ultra-claude-token-saver
ucts initBuilt from: ccusage · claude-code-router · claude-mem · caveman · ruflo · gstack · LLMLingua · RouteLLM · GPTCache · tokencost · Aider · Letta · Portkey · Helicone · Langfuse · NotDiamond
🧭 /ucts guide — The Killer Feature
Don't memorize 93 commands. Just describe your task. Claude reasons about the optimal strategy for you.
You: /ucts guide build a distributed payment microservice with Stripe
Claude: ╔══════════════════════════════════════════════════════════════╗
║ 🧭 UCTS SMART GUIDE — Optimal Strategy for Your Task ║
╚══════════════════════════════════════════════════════════════╝
📋 Task: build a distributed payment microservice with Stripe
📊 Classification: massive feature | full-repo | risk: critical
⏱️ Estimated: 1-3 days | ~800,000 tokens unoptimized
🎯 Combo: caveman:off + LLMLingua + RouteLLM + AgentDiet + Swarm + SPARC + /careful
💰 Estimated Savings: 95% fewer tokens (~760,000 saved, ~$2.28 saved)
━━━ EXECUTION PLAN ━━━
1. ▶ /careful — Safety guardrails (critical risk)
2. ▶ /repo-map — Compressed project outline
3. ⏸ /office-hours — Define the problem first
4. ⏸ /sparc — Spec → Pseudo → Arch → Refine → Complete
5. ▶ /context-save — Save state before risky changes
6. ⏸ /swarm init — Multi-agent: coder + reviewer + tester
7. ▶ # === BEGIN WORK === — All optimizations active
8. ⏸ /cso — Security audit after implementation
9. ⏸ /review — Code review with auto-fix
10. ⏸ /ship — Tests + PR
Type "approve" to auto-execute this plan.It adapts to any task:
| You Say | Guide Prescribes |
|---------|-----------------|
| "build a todo list" | caveman:ultra + Exact Cache — done in 2 min |
| "fix the flaky auth test" | caveman:full + /investigate + Fast Transform |
| "add OAuth login with Google" | caveman:full + LLMLingua + RouteLLM + /careful + Repo Map |
| "refactor API layer to tRPC" | caveman:lite + LLMLingua + SWE-Pruner + AgentDiet + SPARC + /context-save |
| "write API docs" | caveman:ultra + Monitor — minimal tools |
| "redesign to microservices" | Full arsenal: Swarm + SPARC + LLMLingua + AgentDiet + Hierarchical Memory + Observability |
How it works:
- Classifies your task by complexity (trivial→massive), domain (code, debug, architecture, security...), scope (single-file→multi-repo), and risk (none→critical)
- Prescribes the optimal combination from all 17 optimization strategies
- Generates an executable command plan with auto-execute (▶) and approval gates (⏸)
- Say "approve" → it runs the plan. Say "skip the swarm" → it adjusts.
🤖 5 Killer Features Nobody Else Has
/ucts autopilot — Budget-Aware Autonomous Execution
Describe your task + set a budget. UCTS auto-executes the entire plan. If budget runs low, it auto-switches to caveman:ultra and downgrades to haiku. If budget is exceeded, it stops gracefully.
You: /ucts autopilot build a REST API with auth --budget $0.50
UCTS: 🤖 AUTOPILOT — EXECUTING
🟢 ████████░░░░░░░░░░░░░░░░ 35% budget
💰 $0.17 / $0.50 ($0.33 left)
✅ /caveman full
✅ /repo-map ($0.002)
🔄 Implementing... ($0.16)
⬜ /review
⬜ /ship
[auto-adjusted] Budget 72% → caveman: full → ultra
[auto-adjusted] Budget 72% → model: sonnet → haiku/ucts diff — Token Cost Impact Per PR
Before merging, see how your code changes affect the token budget:
You: /ucts diff
📊 Token Diff — Cost Impact of Current Changes
Files changed: 7 (+340, -89)
Token delta: +1,247 tokens/session
Cost impact: +$0.004/session
💚 But: new cache layer saves ~3,200 tokens/session
💚 Verdict: SAVES — net -$0.006/session
💡 New file api/handlers.ts adds 800 tokens — consider splitting/ucts replay — "Where Did My Money Go?"
The Wireshark for LLM spending. Replay any session with per-message cost annotations:
You: /ucts replay
#1 👤 User: "Fix the auth bug"
→ haiku | 500in/0out | $0.0001 | no optimizations
#2 🤖 Assistant: [347 tokens → caveman compressed to 198]
→ haiku | 0in/198out | $0.0002 | caveman(-149tok)
#3 👤 User: "Now add tests"
→ haiku | 400in/0out | $0.0000 | 💾 CACHE HIT (saved $0.003!)
Total: $0.012 (would be $0.089 without UCTS → 87% saved)/ucts hotpath — Find Your Expensive Patterns
Analyzes your last 30 days and shows the top token drains with one-command fixes:
You: /ucts hotpath
🔴 #1: Caveman mode disabled (23 sessions)
Waste: 450K tokens | Fix: /caveman full
🔴 #2: Always using expensive model
Waste: 380K tokens | Fix: ucts config set routellm.enabled true
🟡 #3: Cache never hits
Waste: 115K tokens | Fix: ucts config set semanticCache.similarityThreshold 0.75
⚡ Quick wins: Fix #1 + #2 → save ~$2.50/month/ucts proxy — Works With ANY Tool
Transparent HTTP proxy. One command → all 17 optimization stages apply to Cursor, Continue, Aider, custom code — anything that speaks OpenAI API:
# Start the proxy
ucts proxy --port 3456
# Point any client at it
export ANTHROPIC_BASE_URL=http://127.0.0.1:3456
cursor . # Cursor now optimized
aider --model claude-sonnet # Aider now optimized
python my_app.py # Custom code now optimizedEvery request gets: RouteLLM routing, semantic caching, LLMLingua compression, caveman output, cost tracking — automatically.
🎨 Real-Time Visualization
Watch your tokens flow through all 17 pipeline stages in real-time. Three visualization modes:
cd visualization && npm install && npm run dev
# Open http://localhost:5173🔮 Pipeline View — React Flow DAG
Interactive node graph of all 17 stages with animated token-flow edges:
┌──────────┐ ✨ ┌──────────────┐ ┌───────────┐
│ ⚡Booster │═══════▶│ 🧠 Sem.Cache │════════▶│ 📦 Cache │
│ ○ idle │ │ ✅ HIT! 87% │ │ ○ miss │
│ 0 saved │ │ -3.2K tok │ │ 0 saved │
└──────────┘ └──────────────┘ └───────────┘- Nodes glow when active. Green = cache hit. Pulse animation on active stages.
- Edge thickness ∝ token count (Sankey-like). Animated dash flow.
- Badge on edges: "✅ HIT", "-2.4K tok", "→ haiku"
- MiniMap + zoom/pan controls
🏢 Office View — Pixel Art Canvas
Top-down pixel-art office where agents walk between pipeline "desks":
🟢 Booster 🟢 Sem.Cache 🟢 Cache
[desk] [desk] ←🚶 [desk]
✨✨✨
🔵 RouteLLM 🔵 LLMLingua 🔵 SWE
[desk] [desk] [desk]
Budget: ████████░░░░ 62% $0.31/$0.50- 17 desks arranged in grid, one per pipeline stage
- Agent sprites (Coder 🟡, Reviewer 🔵, Tester 🟢) walk between desks
- Green particle sparkles when tokens are saved
- Active stage desks glow with color border
- Budget bar at bottom with live percentage
📊 Dashboard — Metrics Panels
Real-time metrics grid:
- Budget Gauge — Circular SVG gauge with % used, color-coded (🟢→🟡→🔴)
- Savings Breakdown — Horizontal bar chart per stage (LLMLingua 28%, Router 21%...)
- Model Usage — Pie chart showing % requests per model with cost
- Cache Hit Rate — Ring gauge with hit/miss counts
- Session Stats — Uptime, requests, tokens in/out, cost
- Command Log — Scrolling log with timestamp, command, tokens saved, cost
Tech Stack
| Layer | Technology | |-------|-----------| | Framework | React 19 + TypeScript | | Build | Vite 6 | | Pipeline Graph | @xyflow/react 12 (React Flow) | | Office Renderer | HTML5 Canvas 2D (pixel-agents pattern) | | State | Zustand (planned) + React useState | | Charts | Hand-rolled SVG (zero chart library deps) | | Demo Mode | Built-in simulation — works without live UCTS connection |
Architecture
visualization/
├── src/
│ ├── App.tsx ← Tab shell: Pipeline | Office | Dashboard
│ ├── store/
│ │ ├── uctsStore.ts ← 17 stage definitions, types, positions
│ │ └── demoSimulation.ts ← Fake data generator for demo mode
│ ├── pipeline/
│ │ ├── PipelineView.tsx ← React Flow canvas
│ │ ├── StageNode.tsx ← Stage card node (icon, name, status, hit rate bar)
│ │ └── TokenFlowEdge.tsx ← Animated edge with token badge
│ ├── office/
│ │ └── OfficeView.tsx ← Canvas 2D pixel art (inline sprites, no assets)
│ ├── dashboard/
│ │ └── DashboardView.tsx ← 6 metric widgets (budget, savings, models, cache, session, log)
│ └── shared/
│ └── theme.ts ← Colors, formatters, model color map
├── index.html
├── package.json
└── vite.config.tsInspired by pixel-agents (Canvas 2D pixel art) and the-delegation (React Flow + Zustand state architecture).
Works on 15 AI Coding Agents — Not Just Claude
UCTS auto-detects which agents you have installed and deploys skills to all of them:
# Auto-detect and install to all agents
./setup --all
# Or target a specific agent
ucts install --host codex
ucts install --host cursor
ucts install --host openclaw| Agent | Flag | Skills Install To | Slash Commands | Hooks |
|-------|------|-------------------|:--------------:|:-----:|
| Claude Code | --host claude | ~/.claude/skills/ucts/ | ✅ 94 | ✅ |
| OpenClaw | --host openclaw | ACP dispatch → AGENTS.md | via Claude Code | — |
| OpenAI Codex CLI | --host codex | ~/.codex/skills/ucts/ | ✅ | — |
| Cursor | --host cursor | ~/.cursor/skills/ucts/ | rules file | — |
| Windsurf | --host windsurf | ~/.windsurf/skills/ucts/ | rules file | — |
| Kiro | --host kiro | ~/.kiro/skills/ucts/ | ✅ | — |
| OpenCode | --host opencode | ~/.config/opencode/skills/ucts/ | ✅ | — |
| Factory Droid | --host factory | ~/.factory/skills/ucts/ | ✅ | — |
| Hermes | --host hermes | ACP dispatch → AGENTS.md | via Claude Code | — |
| Slate | --host slate | ~/.slate/skills/ucts/ | ✅ | — |
| GBrain | --host gbrain | ~/.gbrain/skills/ucts/ | ✅ | — |
| Roo Code | --host roo-code | ~/.roo/skills/ucts/ | ✅ | — |
| Gemini CLI | --host gemini-cli | ~/.gemini/skills/ucts/ | — | — |
| gptme | --host gptme | ~/.config/gptme/skills/ucts/ | — | — |
| Aider | --host aider | ~/.aider/skills/ucts/ | — | — |
OpenClaw Integration
OpenClaw spawns Claude Code sessions via ACP, so every UCTS skill just works when Claude Code has UCTS installed. Paste this to your OpenClaw agent:
Install UCTS: run
npm install -g ultra-claude-token-saver && ucts initto install UCTS for Claude Code. Then add a "Coding Tasks" section to AGENTS.md that says: when spawning Claude Code sessions for coding work, tell the session to use UCTS skills. Include these examples — security audit: "Load UCTS. Run /cso", code review: "Load UCTS. Run /review", QA test a URL: "Load UCTS. Run /qa https://...", build a feature: "Load UCTS. Run /ucts guide , approve, then /ship", plan before building: "Load UCTS. Run /ucts guide , then /office-hours → /autoplan. Save the plan, don't implement."
After setup, just talk to your OpenClaw agent naturally:
| You Say | What Happens |
|---------|-------------|
| "Fix the typo in README" | Simple — Claude Code session, no special skills needed |
| "Run a security audit on this repo" | Spawns Claude Code with Run /cso |
| "Build me a notifications feature" | Spawns Claude Code with /ucts guide notifications feature, approve → implement → /ship |
| "Help me plan the v2 API redesign" | Spawns Claude Code with /ucts guide v2 API redesign → /office-hours → /autoplan. Saves plan. |
| "Debug the flaky payment test" | Spawns Claude Code with /investigate flaky payment test |
Native OpenClaw Skills (via ClawHub)
Four methodology skills that work directly in your OpenClaw agent — no Claude Code session needed:
clawhub install ucts-openclaw-guide ucts-openclaw-office-hours ucts-openclaw-investigate ucts-openclaw-retro| Skill | What It Does |
|-------|-------------|
| ucts-openclaw-guide | Smart task analysis → prescribes optimal Claude Code session config |
| ucts-openclaw-office-hours | Product interrogation with 6 forcing questions |
| ucts-openclaw-investigate | Root cause debugging methodology |
| ucts-openclaw-retro | Weekly engineering retrospective |
These are conversational skills. Your OpenClaw agent runs them directly via chat.
Detect Your Agents
ucts detect # or: ./setup --detectAgent Version Skills Path UCTS
───── ─────── ─────────── ────
Claude Code 1.0.32 ~/.claude/skills ✅
OpenAI Codex CLI 0.1.8 ~/.codex/skills ✅
Cursor 0.48.1 ~/.cursor/skills ❌
Kiro 1.2.0 ~/.kiro/skills ❌
Not detected: Windsurf, Factory, Hermes, Slate, GBrain, Roo CodeWhat Gets Installed
After ucts init, this is what lives in your Claude Code environment:
~/.claude/
├── skills/
│ ├── ucts-token-saver.md ← 93 slash command definitions (18KB)
│ └── ucts/
│ ├── hooks/
│ │ ├── statusline.sh ← ⚡UCTS:ultra in status bar
│ │ ├── session-start.sh ← Injects memory context on session start
│ │ ├── careful-guard.sh ← Blocks rm -rf, DROP TABLE, force-push
│ │ ├── post-tool-observe.sh ← Logs tool usage to memory system
│ │ └── hooks-config.sh ← Generates Claude Code hooks config
│ └── commands/
│ ├── repo-map.sh ← Scans project → classes/exports/functions
│ ├── security-scan.sh ← Finds secrets, SQLi, eval, CORS issues
│ ├── perf-analyze.sh ← LOC, deps, bundle size, complexity
│ ├── context-save.sh ← Saves git state + modified files to JSON
│ └── context-restore.sh ← Restores most recent saved session
├── hooks/ ← Claude Code hooks directory (ready)
CLAUDE.md ← Updated with command reference
~/.ultra-claude-token-saver/
├── config.json ← Configuration (auto-created)
├── memory/ ← Persistent memory storage
│ ├── memory.json ← Observations + summaries
│ └── hierarchical-memory.json ← Core/recall/archival tiers
├── sessions/ ← Saved session states
└── usage.jsonl ← Token usage history93 Slash Commands
Every command works in Claude Code after ucts init. Type the command and Claude follows the instructions.
⚡ Token Optimization (10 commands)
| Command | What It Does | Source |
|---------|-------------|--------|
| /ucts | Activate all token-saving strategies for the session | core |
| /ucts status | Show input/output tokens, cost, savings breakdown | ccusage |
| /ucts report | 7-day usage report with per-stage savings bars | ccusage |
| /ucts benchmark | Run savings demo across all strategies | core |
| /ucts doctor | Health check: config, memory, skills, Node.js | core |
| /ucts cache clear | Clear response cache | core |
| /ucts config | Show full configuration as JSON | core |
| /ucts config set | Set config value: ucts config set caveman.enabled true | core |
| /model cheap | Force cheapest model for the rest of the conversation | claude-code-router |
| /model auto | Re-enable automatic difficulty-based routing | claude-code-router |
🦴 Caveman Mode (9 commands)
| Command | What It Does | Source |
|---------|-------------|--------|
| /caveman | Activate full caveman: drop articles, fragments OK, short synonyms | caveman |
| /caveman lite | No filler/hedging, keep full sentences | caveman |
| /caveman full | Classic: drop articles, fragments OK | caveman |
| /caveman ultra | Maximum: abbreviate (DB/auth/fn/impl), arrows for causality | caveman |
| /caveman off | Deactivate, return to normal responses | caveman |
| /caveman-compress <file> | Compress a .md file into caveman-speak, backup original | caveman |
| /caveman-commit | Terse conventional commit: feat(api): add auth ≤50 chars | caveman |
| /caveman-review | One-line code review: 🔴 bug: L42: null check missing. Add ?. | caveman |
| /caveman-help | Quick reference card for all caveman modes | caveman |
🧠 Memory (7 commands)
| Command | What It Does | Source |
|---------|-------------|--------|
| /mem-search <query> | Search past session observations | claude-mem |
| /mem-stats | Observations, summaries, tokens stored, compression ratio | claude-mem |
| /mem-clear | Clear all persistent memory | claude-mem |
| /mem-core set <key> <val> | Set always-loaded core memory block | letta |
| /mem-core show | Show all core memory blocks | letta |
| /mem-recall <query> | Search recent conversation history | letta |
| /mem-archive <query> | Search long-term archival memory | letta |
🔀 Model Routing (4 commands)
| Command | What It Does | Source |
|---------|-------------|--------|
| /model <provider>,<model> | Switch model: /model deepseek,deepseek-chat | claude-code-router |
| /model status | Show routing config: default, background, think, longContext | claude-code-router |
| /model cheap | Force cheapest available model | claude-code-router |
| /model auto | Re-enable automatic routing | claude-code-router |
📋 Planning & Review (6 commands)
| Command | What It Does | Source |
|---------|-------------|--------|
| /office-hours | Product session: 6 forcing questions, challenge premises, 3 approaches | gstack |
| /plan-ceo-review | CEO review: 10-section strategic review, 4 scope modes | gstack |
| /plan-eng-review | Eng review: architecture diagrams, test matrix, failure modes | gstack |
| /plan-design-review | Design review: rate each dimension 0-10, AI slop detection | gstack |
| /plan-devex-review | DX review: explore personas, benchmark TTHW, trace friction | gstack |
| /autoplan | Run all reviews automatically: CEO → Design → Eng → DX | gstack |
🔍 Code Review & QA (7 commands)
| Command | What It Does | Source |
|---------|-------------|--------|
| /review | Staff engineer review: find production bugs, auto-fix obvious ones | gstack |
| /qa <url> | QA testing: open browser, click through flows, find + fix bugs | gstack |
| /qa-only | Same as /qa but report-only, no code changes | gstack |
| /investigate <bug> | Root-cause debugging: trace data flow, test hypotheses | gstack |
| /cso | Security audit: OWASP Top 10 + STRIDE, concrete exploit scenarios | gstack |
| /design-review | Design audit then fix with atomic commits | gstack |
| /devex-review | Live DX audit: test onboarding, time TTHW, screenshot errors | gstack |
🚀 Shipping & Deploy (5 commands)
| Command | What It Does | Source |
|---------|-------------|--------|
| /ship | Sync main, run tests, audit coverage, push, open PR | gstack |
| /land-and-deploy | Merge PR, wait for CI, deploy, verify production health | gstack |
| /canary | Post-deploy monitoring loop for errors and regressions | gstack |
| /benchmark | Performance regression detection: load times, Core Web Vitals | gstack |
| /document-release | Generate release notes from git log since last tag | gstack |
🎨 Design (3 commands)
| Command | What It Does | Source |
|---------|-------------|--------|
| /design-consultation | Build complete design system, research landscape, propose creative risks | gstack |
| /design-shotgun | Generate 4-6 mockup variants, comparison board, iterate on feedback | gstack |
| /design-html | Turn mockup into production HTML. 30KB, zero deps, detects React/Svelte/Vue | gstack |
🤖 Agent Orchestration — ruflo/claude-flow (30 commands)
| Command | What It Does | Source |
|---------|-------------|--------|
| /agent spawn <type> | Spawn specialized agent: coder, researcher, reviewer, tester, planner, architect | ruflo |
| /agent list | List all active agents with status and tasks | ruflo |
| /agent terminate <id> | Terminate an agent | ruflo |
| /swarm init | Start multi-agent swarm (hierarchical/mesh/ring/star topology) | ruflo |
| /swarm status | Show swarm status: agent count, tasks, consensus state | ruflo |
| /swarm scale <n> | Scale swarm up or down | ruflo |
| /sparc | SPARC workflow: Specification → Pseudocode → Architecture → Refinement → Completion | ruflo |
| /sparc spec | Run just the Specification phase | ruflo |
| /sparc pseudo | Run just the Pseudocode phase | ruflo |
| /sparc arch | Run just the Architecture phase | ruflo |
| /hive-mind | Byzantine fault-tolerant collective decision making | ruflo |
| /hive-mind status | Show hive-mind: queen type, workers, consensus state | ruflo |
| /hooks status | Show automation hooks status | ruflo |
| /hooks intelligence | Show self-learning intelligence: SONA, reasoning bank, patterns | ruflo |
| /neural init | Initialize neural learning module | ruflo |
| /neural train | Trigger training cycle from recent successful patterns | ruflo |
| /neural status | Show neural module: patterns learned, routing accuracy | ruflo |
| /coder | Activate Coder Agent: code generation, refactoring, optimization | ruflo |
| /researcher | Activate Researcher Agent: deep research, pattern recognition | ruflo |
| /reviewer-agent | Activate Reviewer Agent: code review, security, performance | ruflo |
| /tester-agent | Activate Tester Agent: unit, integration, E2E, security testing | ruflo |
| /planner-agent | Activate Planner Agent: task decomposition, timeline, risk assessment | ruflo |
| /architect-agent | Activate Architect Agent: system design, scalability, tech selection | ruflo |
| /memory search <q> | Search vector memory (HNSW, 150x-12,500x faster retrieval) | ruflo |
| /memory store <k> <v> | Store pattern in persistent memory | ruflo |
| /memory status | Show memory: entries, vector index size, search latency | ruflo |
| /pair [mode] | Pair programming: driver, navigator, tdd, debug, mentor modes | ruflo |
| /security-scan | Full security scan: input validation, CVE detection, path traversal | ruflo |
| /perf-analyze | Performance analysis: bottleneck detection, profiling, recommendations | ruflo |
| /workflow <name> | Run automated workflow: ci-pipeline, release, review-and-ship | ruflo |
🌐 Browser & Tools (4 commands)
| Command | What It Does | Source |
|---------|-------------|--------|
| /browse <url> | Headless browser: navigate, click, screenshot (~100ms per command) | gstack |
| /connect-chrome | Launch AI-controlled Chromium with live sidebar | gstack |
| /pair-agent | Share browser with another AI agent (OpenClaw, Codex, Cursor) | gstack |
| /codex | OpenAI Codex second opinion: review, challenge, or consult modes | gstack |
🛡️ Safety & Session (8 commands)
| Command | What It Does | Source |
|---------|-------------|--------|
| /careful | Safety guardrails: warn before rm -rf, DROP TABLE, force-push | gstack |
| /freeze | Lock architecture: reject data model, API surface, file structure changes | gstack |
| /unfreeze | Remove architecture lock | gstack |
| /guard | Permission guard: ask before every destructive operation | gstack |
| /context-save | Save git state, modified files, recent commits to JSON | gstack |
| /context-restore | Restore most recent saved session state | gstack |
| /retro | Weekly engineering retrospective: shipped, broke, improve, action items | gstack |
| /learn | Record lesson learned, persists to memory for future sessions | gstack |
📊 Repo Context (2 commands)
| Command | What It Does | Source |
|---------|-------------|--------|
| /repo-map | Generate compressed project outline: files → classes → functions → exports | aider |
| /repo-map focus <files> | Generate focused map for specific files only | aider |
The 17-Stage Optimization Pipeline
Request
│
├─[1] Fast Transform ──────── Handle var→const, remove-console locally in <1ms
├─[2] Semantic Cache ─────── Cosine-similarity match on past queries
├─[3] Exact Cache ────────── Normalized key match on past queries
├─[4] RouteLLM Router ───── Heuristic difficulty scoring → cheap or strong model
├─[5] Rule Router ────────── Heuristic rules (background, file-ops, simple)
├─[6] LLMLingua ──────────── Heuristic token importance → drop non-essential tokens
├─[7] SWE-Pruner ─────────── Task-aware relevance → drop irrelevant turns
├─[8] AgentDiet ──────────── Remove failed retries, dedup file reads, summarize old
├─[9] Context Pruner ─────── Deduplicate tools, collapse errors, sliding window
├─[10] Repo Map ───────────── Inject compressed codebase outline (50K→2K)
├─[11] Hierarchical Memory ── Core/recall/archival context injection
├─[12] Session Memory ─────── Compressed observation injection
├─[13] Provider Gateway ───── Failover, retries, health checks
│
└─→ [LLM CALL] →
│
├─[14] Caveman Compress ──── Strip filler/articles/hedging (50-75%)
├─[15] Cache Store ────────── Store for semantic + exact cache
├─[16] TokenCost ──────────── Accurate cost tracking (60+ models)
└─[17] Observability Hub ──── Trace, aggregate, recommend
│
ResponseQuick Start
# Install globally
npm install -g ultra-claude-token-saver
# Initialize everything (config + skills + hooks + scripts)
ucts init
# See savings demo
ucts benchmark
# Enable maximum compression
ucts caveman ultra
# Check health
ucts doctorIn Claude Code — Try These First
/ucts — Activate all token-saving
/caveman ultra — Maximum response compression
/office-hours — Product strategy session
/review — Code review with auto-fix
/ship — Run tests + open PR
/cso — Security audit
/agent spawn coder — Spawn coding agent
/swarm init — Multi-agent swarm
/sparc — SPARC development workflow
/repo-map — Compressed project outline
/pair — Pair programming mode
/careful — Safety guardrails onExecutable Hook Scripts
These scripts run automatically during Claude Code sessions:
Hooks (auto-triggered)
| Script | Trigger | What It Does |
|--------|---------|-------------|
| statusline.sh | Every keystroke | Shows ⚡UCTS:ultra or 🔥UCTS:ultra in the status bar |
| session-start.sh | Session start | Loads memory context, shows active mode, announces 93 commands |
| careful-guard.sh | Before Bash commands | Blocks rm -rf, DROP TABLE, git push --force, kubectl delete, etc. when /careful is active |
| post-tool-observe.sh | After every tool call | Logs tool name and output length to memory for pattern learning |
Commands (user-triggered)
| Script | Slash Command | What It Does |
|--------|-------------|-------------|
| repo-map.sh | /repo-map | Scans directory tree, extracts classes/exports/functions per file, outputs compressed outline |
| security-scan.sh | /security-scan | Checks for hardcoded secrets, SQL injection, eval/exec, CORS wildcards, path traversal, deprecated deps |
| perf-analyze.sh | /perf-analyze | Counts source files/lines, dependency count, node_modules size, largest files, TODO/FIXME count |
| context-save.sh | /context-save | Saves git branch, commit, modified/staged files, recent commits to JSON in ~/.ultra-claude-token-saver/sessions/ |
| context-restore.sh | /context-restore | Finds most recent save, shows branch, commit, modified files, warns if on different branch |
CLI Reference
ucts init # Install everything: config + skills + hooks + scripts
ucts status # Current session stats
ucts report [--days N] # Usage report (default: 7 days)
ucts config # Show full config
ucts config set KEY VALUE # Set value (dot-notation)
ucts config get KEY # Get value
ucts caveman [off|lite|full|ultra] # Set compression level
ucts cache # Cache stats
ucts cache clear # Clear cache
ucts memory search <query> # Search past observations
ucts memory stats # Memory statistics
ucts memory clear # Clear all memory
ucts install # Re-install Claude Code hooks
ucts benchmark # Run savings demo
ucts doctor # Health checkProgrammatic API
Core Pipeline
import { TokenSaver } from 'ultra-claude-token-saver';
const saver = new TokenSaver();
// Process request through all 17 stages
const result = saver.processRequest([
{ role: 'user', content: 'What does this function do?' }
]);
console.log(result.model); // 'claude-haiku-3' (routed to cheap model)
console.log(result.boosted); // false
console.log(result.cached); // false
console.log(result.savings); // { routerSavings: 1, pruneSavings: 0, ... }v2.0 Integrations — Each Module Works Standalone
// ── Neural Prompt Compression (LLMLingua) ──────────────────
import { LinguaCompressor } from 'ultra-claude-token-saver';
const lingua = new LinguaCompressor({ targetRatio: 0.5 });
const result = lingua.compress(longPrompt);
// result.ratio = 0.48, result.tokensRemoved = 523
// ── Heuristic Router (RouteLLM) ───────────────────────────
import { RouteLLMRouter } from 'ultra-claude-token-saver';
const router = new RouteLLMRouter({ costThreshold: 0.5 });
const { model, difficulty } = router.route('Explain OAuth2 PKCE flow');
// model = 'claude-sonnet-4', difficulty = 0.72
// ── Semantic Cache (GPTCache) ──────────────────────────────
import { SemanticCache } from 'ultra-claude-token-saver';
const cache = new SemanticCache({ similarityThreshold: 0.85 });
cache.set('How to install TypeScript?', 'Run npm install -g typescript');
cache.get('How do I install TypeScript?'); // hit! similarity = 0.92
// ── Repo Map (Aider) ──────────────────────────────────────
import { RepoMapper } from 'ultra-claude-token-saver';
const map = new RepoMapper().generateMap('/path/to/project');
// map.tokens = 1,847 (vs 52,000 for full source)
// ── Task-Aware Pruning (SWE-Pruner) ───────────────────────
import { SWEPruner } from 'ultra-claude-token-saver';
const pruned = new SWEPruner({ maxTokens: 50000 }).prune(messages, 'fix auth bug');
// pruned.savings = 23,400 tokens
// ── Trajectory Reduction (AgentDiet) ───────────────────────
import { AgentDiet } from 'ultra-claude-token-saver';
const reduced = new AgentDiet().reduce(longConversation);
// reduced.actions = ['Removed 3 failed retries', 'Summarized old messages']
// ── Hierarchical Memory (Letta) ────────────────────────────
import { HierarchicalMemory } from 'ultra-claude-token-saver';
const mem = new HierarchicalMemory({ dataDir: '/tmp/mem', coreMaxTokens: 500, recallMaxEntries: 200, archivalMaxEntries: 1000 });
mem.setCoreBlock('persona', 'Senior TypeScript developer');
mem.getContextInjection('auth bug', 2000); // ~500 tokens instead of 5000
// ── Provider Gateway (Portkey) ─────────────────────────────
import { ProviderGateway } from 'ultra-claude-token-saver';
const gw = new ProviderGateway({ failover: true });
gw.addProvider({ name: 'anthropic', baseUrl: '...', apiKey: '...', models: ['claude-sonnet-4'] });
gw.findProvider('claude-sonnet-4'); // auto-failover on errors
// ── Live Cost Tracking (TokenCost) ─────────────────────────
import { calculateCost, calculateSavings } from 'ultra-claude-token-saver';
calculateCost('claude-sonnet-4-20250514', 50000, 10000); // $0.30
calculateSavings('claude-opus-4-20250514', 'claude-haiku-3-20250310', 50000, 10000);
// { savedDollars: $0.87, savingsPercent: 97.5% }
// ── Observability (Helicone/Langfuse) ──────────────────────
import { ObservabilityHub } from 'ultra-claude-token-saver';
const hub = new ObservabilityHub();
hub.startTrace().setTokens(5000, 2000, 3500).setModel('haiku').finish();
hub.getAggregateStats().recommendations;
// ['💡 Semantic cache hit rate is low. Lower similarityThreshold.']Caveman Mode
| Level | What Changes | Example | |-------|-------------|---------| | off | Normal responses | "Sure! I'd be happy to help. The issue is a misconfigured authentication middleware." | | lite | No filler/hedging, full sentences | "The issue is a misconfigured authentication middleware." | | full | Drop articles, fragments OK, short synonyms | "Issue: misconfigured auth middleware." | | ultra | Abbreviate, arrows for causality | "Misconfigured auth middleware → token expiry bug. Fix:" |
Auto-Clarity: Reverts to normal for security warnings, irreversible actions, destructive ops.
Model Routing
Two routing engines work together:
RouteLLM (Heuristic): Scores prompt difficulty 0.0–1.0 using word complexity, technical terms, code presence, question complexity, reasoning depth. Auto-calibrates threshold.
Rule Router (Heuristic):
| Scenario | Target | Priority | |----------|--------|----------| | Long context (>60K tokens) | Gemini 2.5 Pro | 100 | | Background/subagent tasks | Haiku | 90 | | Thinking/reasoning tasks | Sonnet (thinking) | 80 | | File operations (ls, cat) | Haiku | 70 | | Simple queries (<200 chars) | Haiku | 50 | | Everything else | Sonnet | default |
TokenCost — 60+ Models, 10 Providers
| Provider | Models | Input $/1M | Output $/1M | |----------|--------|-----------|-------------| | Anthropic | Opus 4, Sonnet 4, Haiku 3.5 | $0.25–$15 | $1.25–$75 | | OpenAI | GPT-5, GPT-4.1, o3, o4-mini | $0.10–$150 | $0.40–$600 | | Google | Gemini 2.5 Pro/Flash | $0.075–$1.25 | $0.30–$10 | | DeepSeek | Chat, Reasoner, Coder | $0.14–$0.55 | $0.28–$2.19 | | Meta | Llama 4, Llama 3.3 | $0.05–$3.0 | $0.08–$3.0 | | Mistral | Large, Small, Codestral | $0.10–$2.0 | $0.30–$6.0 | | xAI | Grok 3, Grok 3 Mini | $0.30–$3.0 | $0.50–$15 | | + Cohere, Qwen, Amazon | Various | $0.035–$2.5 | $0.14–$10 | | Ollama/Local | Any | Free | Free |
Configuration
Config at ~/.ultra-claude-token-saver/config.json (auto-created on ucts init):
{
"router": { "enabled": true, "default": "claude-sonnet-4-20250514", "background": "claude-haiku-3-20250310", "longContext": "gemini-2.5-pro", "longContextThreshold": 60000 },
"memory": { "enabled": true, "maxObservations": 1000, "compressionLevel": "aggressive" },
"caveman": { "enabled": false, "defaultLevel": "full", "autoClarity": true },
"context": { "enabled": true, "maxTokens": 100000, "deduplicateTools": true, "collapseErrors": true },
"cache": { "enabled": true, "maxEntries": 500, "ttlSeconds": 300 },
"booster": { "enabled": true, "intents": ["var-to-const", "add-types", "add-error-handling", "async-await", "add-logging", "remove-console"] },
"monitoring": { "enabled": true, "warnThreshold": 500000, "sessionBudget": 0 }
}Fast Transform
Handles transforms in <1ms — no LLM call:
| Intent | Trigger | What It Does |
|--------|---------|--------------|
| var-to-const | "convert var to const" | var x = 1 → const x = 1 |
| remove-console | "remove console.log" | Strips all console.* |
| add-logging | "add logging" | Adds debug logs to functions |
| format-json | "format json" | Pretty-prints JSON |
| sort-imports | "sort imports" | Sorts by builtin→package→relative |
| add-error-handling | "add try catch" | Wraps in try/catch |
| add-types | "add types" | Basic TypeScript annotations |
Package Stats
📦 Package: ultra-claude-token-saver v2.0.0
📁 Repository files: 58 files (273.6 KB)
📄 TypeScript: 26 source files (6,084 lines)
🔧 Shell scripts: 10 executable hooks + commands
📝 Skill file: 1 file, 99 slash commands (18.1 KB)
✅ Tests: 114/114 passing (29 test suites)
🔗 Dependencies: 0 (zero external deps!)
⚙️ Node.js: >= 18.0.0How It Compares
| Feature | UCTS v2 | ccusage | claude-code-router | claude-mem | caveman | ruflo | LLMLingua | RouteLLM | GPTCache | |---------|:-------:|:-------:|:------------------:|:----------:|:-------:|:-----:|:---------:|:--------:|:--------:| | Slash commands (93) | ✅ | ❌ | ❌ | ❌ | 9 | 30 | ❌ | ❌ | ❌ | | Executable hooks | ✅ | ❌ | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ | ❌ | | Usage monitoring | ✅ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | | Heuristic routing | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ❌ | | Heuristic compression | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ❌ | ❌ | | Response compression | ✅ | ❌ | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ | ❌ | | Semantic cache | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | | Hierarchical memory | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | | Task-aware pruning | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | | Trajectory reduction | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | | Repo map outlines | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | | WASM transforms | ✅ | ❌ | ❌ | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ | | Provider gateway | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | | Observability | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | | Live cost tracking | ✅ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | | Zero dependencies | ✅ | ❌ | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ | ❌ | | Single npm install | ✅ | ✅ | ✅ | ✅ | ❌ | ❌ | ✅ | ✅ | ✅ |
Credits
Core (v1.0)
- ccusage — Token usage monitoring
- claude-code-router by @musistudio — Multi-model routing
- claude-mem by @thedotmack — Memory compression
- caveman by @juliusbrussee — Communication compression
- ruflo by @ruvnet — Agent orchestration, WASM transforms, swarms
- gstack by @garrytan — Sprint skills, caching, QA
- rtk — CLI context filtering
Integrations (v2.0)
- LLMLingua by Microsoft Research — LLMLingua-inspired heuristic compression (EMNLP 2023, ACL 2024)
- RouteLLM by LMSYS — ML-trained model routing (paper)
- GPTCache by Zilliz — Semantic response caching
- tokencost by AgentOps — LLM pricing database
- Aider by Paul Gauthier — Repo map concept
- Letta (MemGPT) — Hierarchical memory architecture
- Portkey — Universal LLM gateway
- Helicone — LLM observability
- Langfuse — Open-source LLM tracing
- NotDiamond — AI meta-routing
Research Papers
- SWE-Pruner (91 upvotes) — Self-adaptive context pruning for coding agents
- AgentDiet — Trajectory reduction for LLM agent systems
- LLMLingua-2 — Data-distilled prompt compression
- Focus Agent — Active context compression
License
MIT
