Skip to main content
Glama
README.md
<div align="center">

<img src="docs/banner.svg" alt="promptopt — stop burning tokens" width="100%" max-width="920px">

# the token-saving plugin for terminal AI agents

**Claude Code · Codex CLI · opencode · Gemini CLI · Claude Desktop · any MCP client**

[![npm](https://img.shields.io/npm/v/promptopt?color=7c5cff&label=npm)](https://www.npmjs.com/package/promptopt)
[![npm downloads](https://img.shields.io/npm/dt/promptopt?color=22d3ee)](https://www.npmjs.com/package/promptopt)
[![license](https://img.shields.io/badge/license-MIT-34d399)](LICENSE)
[![node](https://img.shields.io/node/v/promptopt?color=f59e0b)](package.json)
![offline](https://img.shields.io/badge/telemetry-none-black)
![keys](https://img.shields.io/badge/API%20keys-not%20needed-black)

*Your agent burns most of its tokens before it writes a single line of code.*
*promptopt plugs the leaks — locally, offline, for free.*

</div>

---

## ⚡ TL;DR

```bash
npx promptopt install        # one command. every detected CLI. done.
```

That single command registers an MCP server, injects a ~200-token discipline protocol, adds cheap-model subagents, and starts tracking your savings in a stylish HTML dashboard.

**Prefer checkboxes?** Installing via npm (`npm i promptopt`) or running [`promptopt init`](#-install) opens an interactive checklist - arrow keys to move, `space` to toggle the CLIs you want, `a` to check all, `enter` to configure them:

```text
promptopt - select the CLIs to configure:
  [x] claude
  > [ ] claude-desktop
  [x] codex
  [ ] opencode
  [ ] gemini
  [ ] generic
  space: toggle   a: check all   enter: continue   esc: cancel
```

It only appears on real interactive installs - never in CI, never during `npx` runs, never inside this repo itself (`PROMPTOPT_NO_INIT=1` disables it permanently).

```text
$ promptopt "Hey, could you please fix the bug in src/app.ts? Thanks!"

tokens: 15 -> 7 compressed (net -53.3%)
intent: fix (85% confidence)

--- optimized prompt ---
Fix the bug in src/app.ts

route: simple · gemini-2.5-flash ~$0.0032  (92% under flagship pricing)
```

---

## 🩸 The problem

| Token leak | What actually happens | promptopt's fix |
|---|---|---|
| 🔁 **Rework loops** | Agent guesses an ambiguous request wrong → you re-prompt → double spend | Asks ≤3 sharp questions when guessing is expensive; auto-assumes + states assumptions when it isn't |
| 🗣️ **Chatty prompts** | *"Hey, could you please maybe..."* | Rule-based compression: **15–55% off** typical prompts |
| 🏋️ **Wrong-size model** | Opus-grade reasoning spent on grep-level lookups | Tier classifier routes to the **cheapest capable** model/subagent |
| 📜 **Verbose sessions** | Restating tasks, narrating unchanged code, recaps | Behavior protocol rules 1–6 |

On three real prompts, promptopt spent **$0.078** where uncompressed-flagship would have spent **$0.300** — tracked live in its own report.

---

## 📦 Install

> **Requirement:** Node ≥ 18. No API keys. No accounts. Nothing leaves your machine.

### One command for everything

```bash
npx promptopt install
# or the interactive checklist, anytime:
npx promptopt init
```

Auto-detects which CLIs you have installed and configures each one. Add `-n` to preview first (`--dry-run`), `--all` to force every target.

### Pick your target

<details open>
<summary><b>🤖 Claude Code</b></summary>

```bash
npx promptopt install claude
```

Registers the MCP server in `.mcp.json` (project) or `~/.claude.json` (`--user` flag), injects the protocol into `CLAUDE.md`, and creates two real subagents:

- `promptopt-scout` → haiku — read-only lookups & searches, ≤5-line answers
- `promptopt-worker` → sonnet — well-scoped edits, diff-first output

Restart your Claude Code session → done.

> **Heads-up:** project-scope MCP servers need a one-time trust approval — start `claude` in the folder and accept the prompt (or run `/mcp`). Stuck at "Pending approval"? That's this. Install with `--user` instead and it's trusted in every project with zero prompts.
</details>

<details>
<summary><b>🖥️ Claude Desktop</b></summary>

Claude Desktop has no URL scheme for local servers, so pick one of these:

**Option A — one-click bundle (recommended):**
Download `promptopt-&lt;version&gt;.mcpb` from [Releases](../../releases) and drag it onto the Claude Desktop window. All dependencies are bundled — no Node tooling needed on the other end.

**Option B — installer:**

```bash
npx promptopt install claude-desktop     # writes claude_desktop_config.json for you
```

**Option C — manual:** paste into `%APPDATA%\Claude\claude_desktop_config.json` (Windows) or `~/Library/Application Support/Claude/claude_desktop_config.json` (macOS):

```json
{
  "mcpServers": {
    "promptopt": { "command": "npx", "args": ["-y", "promptopt", "mcp"] }
  }
}
```

Restart Claude Desktop → the tools appear in your chats.
</details>

<details>
<summary><b>⌨️ Codex CLI</b></summary>

```bash
npx promptopt install codex --user    # ~/.codex/config.toml + ~/.codex/AGENTS.md
npx promptopt install codex           # project AGENTS.md only
```
</details>

<details>
<summary><b>🔧 opencode / Gemini CLI / anything else</b></summary>

```bash
npx promptopt install opencode   # opencode.json + AGENTS.md
npx promptopt install gemini     # .gemini/settings.json + GEMINI.md
npx promptopt install generic    # any MCP client: AGENTS.md + printed snippet
```
</details>

### Verify & reverse

```bash
npx promptopt doctor       # health-check every registration
npx promptopt uninstall    # removes everything cleanly (marker-based, zero residue)
```

All instruction-file edits sit between `<!-- promptopt:start vX -->` and `<!-- promptopt:end -->` markers; JSON configs get `.bak` backups before touching them.

---

## 🧠 How it thinks

Injected once per session (~200 tokens) — the cheapest insurance you'll ever buy:

> **1. Think terse.** Plan in ≤3 short sentences before acting. Never restate the task.
> **2. Ask or assume.** If a request has ≥2 interpretations: adopt the assumption and say *"Assuming X"* in one line — unless a wrong guess forces a full rework, then ask ≤3 batched questions and stop.
> **3. Route cheap.** Trivial subtasks go to `promptopt-scout`. Never spend frontier tokens on grep-level work.
> **4. Batch.** Parallel tool calls. Read each file once. Never re-read unchanged files.
> **5. Output lean.** Diffs over full files. Stop when done — no recap.
> **6. Big jobs.** Before >5k output tokens of work, run `optimize_prompt` and follow its plan.

## ❓ Questions that answer themselves

Every prompt is intent-classified (**question / build / plan / fix / add**) and vague builds get *multiple-choice* menus instead of essay prompts:

```text
questions (1) - ask these before acting:
  1. What should be built?
     choices: feature inside the existing app | standalone script | CLI tool |
              library / package | service / API endpoint | full new app
     default if unanswered: a feature integrated into the existing project
```

Three modes: `hybrid` *(default — assume ≥70% confidence, ask the rest)* · `auto` *(assume everything)* · `ask` *(never assume)*.

## 🛠️ MCP tools

| Tool | Does |
|---|---|
| `optimize_prompt` | Intent → compression → auto-assumptions → choice-based blockers → routing → usage report |
| `route_prompt` | Cheapest capable model per provider, costed against always-flagship |
| `token_audit` | Offline BPE token count + compression opportunities for any text |
| `get_protocol` | Protocol text for agents that can't read instruction files |

## 💸 Model routing

| Tier | Claude | OpenAI | Gemini |
|---|---|---|---|
| trivial | claude-haiku-4-5 · $1/$5 | gpt-5.4-nano · $0.20/$1.25 | gemini-3.1-flash-lite · $0.25/$1.50 |
| standard | claude-sonnet-5 · $2/$10 | gpt-5.1 · $1.25/$10 | gemini-2.5-flash · $0.30/$2.50 |
| complex | claude-opus-5 · $5/$25 | o3 · $2/$8 | gemini-3-pro-preview · $2/$12 |

*Prices verified against the public LiteLLM registry on 2026-08-21. Prices drift — pin yours current:*

```bash
promptopt models --refresh   # re-syncs into ~/.promptopt/models.json (trusted 7 days)
```

Intent steers the tier: `question` demotes (explanations rarely need Opus), `plan` promotes to at least standard (wrong plans are the priciest mistake).

## 📊 Usage reports

Every optimize run writes to `./promptopt-report/` and prints the path:

```
report: C:\dev\myproject\promptopt-report\index.html
```

A dark-gradient, zero-JS, works-offline dashboard with stat cards and progress bars:

- tokens saved — this run and cumulative
- est. dollars saved vs the always-flagship baseline
- **budget used / % left** (local budget, default $10)
- the counterfactual bar: what you'd have burned without the plugin
- latest run's before/after, assumptions, choices asked, routing table, last 20 runs

```bash
promptopt budget                       # usage + % left
promptopt budget --set-usd 25 --set-tokens 2000000
promptopt report --open                # print (and open) the static report
promptopt dashboard                    # LIVE dashboard on http://localhost:4739
promptopt "..." --no-report            # optimize without recording
```

### Live dashboard

`promptopt dashboard` starts a local-only server (binds `127.0.0.1`, never exposed to your network), auto-opens your browser, and keeps the page **live**: a tiny poll script detects new optimize runs and reloads the page automatically — leave it open in a tab and watch savings accumulate while you work.

```bash
promptopt dashboard              # http://localhost:4739
promptopt dashboard -p 8080      # custom port (auto-falls forward if taken)
promptopt dashboard --no-open    # serve without opening the browser
```

Endpoints: `/` (dashboard), `/api/data` (usage snapshot JSON), `/api/ping`. The served page re-renders from the ledger on every request — there is no state to refresh manually.

Add `promptopt-report/` to `.gitignore` — local telemetry, your eyes only.

## ⌨️ CLI cheat sheet

```bash
promptopt "<prompt>"                     # optimize (hybrid mode + report)
promptopt init                           # interactive checkbox installer
promptopt "<prompt>" --mode ask          # all questions, zero assumptions
promptopt route "<prompt>"               # tier + cheapest model per provider
promptopt audit "$(cat big-log.txt)"     # token count + compression report
promptopt models                         # catalog + source
promptopt dashboard                      # live localhost usage dashboard
promptopt doctor                         # installation health check
```

## 🔒 Privacy & accuracy

- **Zero network calls at runtime.** The only network event ever is npm fetching the package itself. No keys, no telemetry, no accounts.
- Compression protects code blocks, URLs, and file paths verbatim; requirements are never dropped.
- Token counts use offline cl100k_base BPE — Claude/Gemini actual counts vary ~±10%. Costs are estimates from public registry prices, not invoices.

<details>
<summary><b>Why no URL link for Claude Desktop?</b></summary>

Claude Desktop accepts remote connectors by URL, but local stdio servers — like promptopt, which runs entirely on your machine — have no deep-link scheme. That's exactly why the <code>.mcpb</code> desktop-extension format exists: one file, double-click install, dependencies included.
</details>

## 🤝 Contributing

PRs welcome — new compression rules, model catalog updates, new agent targets. See [CONTRIBUTING.md](CONTRIBUTING.md).

```bash
git clone https://github.com/hawktuahcoin-hurhur/promptopt && cd promptopt
npm ci && npm run build && npm test && npm run test:smoke
```

[![CI](https://github.com/hawktuahcoin-hurhur/promptopt/actions/workflows/ci.yml/badge.svg)](https://github.com/hawktuahcoin-hurhur/promptopt/actions/workflows/ci.yml)

## 📄 License

[MIT](LICENSE) © promptopt contributors

<div align="center">
<br>
<sub>stop burning tokens — <code>npx promptopt install</code></sub>
</div>