cheaplane 0.2.0__tar.gz

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.
@@ -0,0 +1,10 @@
1
+ .venv/
2
+ __pycache__/
3
+ *.pyc
4
+ # Local wiring (machine-absolute paths) — commit only .mcp.json.example
5
+ .mcp.json
6
+ # your real proxy config may hold API keys; only litellm.yaml.example is shipped
7
+ litellm.yaml
8
+ dist/
9
+ build/
10
+ *.egg-info/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Cheaplane authors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,322 @@
1
+ Metadata-Version: 2.5
2
+ Name: cheaplane
3
+ Version: 0.2.0
4
+ Summary: Offload grunt work from your subscription LLM to cheap models via MCP — auto-routing, a savings ledger, and billing isolation.
5
+ Project-URL: Homepage, https://github.com/millennialdreamer/cheaplane
6
+ Project-URL: Repository, https://github.com/millennialdreamer/cheaplane
7
+ Project-URL: Issues, https://github.com/millennialdreamer/cheaplane/issues
8
+ Author-email: millennialdreamer <269377871+millennialdreamer@users.noreply.github.com>
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: claude,claude-code,cost-optimization,deepseek,litellm,llm,mcp,model-context-protocol
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Environment :: Console
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Operating System :: MacOS
16
+ Classifier: Operating System :: POSIX :: Linux
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Programming Language :: Python :: 3.13
22
+ Classifier: Topic :: Software Development :: Code Generators
23
+ Classifier: Topic :: Utilities
24
+ Requires-Python: >=3.10
25
+ Requires-Dist: mcp>=1.2
26
+ Description-Content-Type: text/markdown
27
+
28
+ <p align="center">
29
+ <img src="assets/hero-banner.png" alt="Cheaplane — keep your premium model on the main thread, offload the grunt work to cheap models with billing that can't cross" width="880">
30
+ </p>
31
+
32
+ # Cheaplane 🛣️
33
+
34
+ > **Keep your premium subscription on the main thread. Offload the grunt work to cheap models — Cheaplane even picks the right one for you. Stop burning premium tokens on boilerplate.**
35
+
36
+ ![License](https://img.shields.io/badge/license-MIT-green)
37
+ ![Python](https://img.shields.io/badge/python-3.10%2B-blue)
38
+ ![MCP](https://img.shields.io/badge/MCP-compatible-purple)
39
+ ![Deps](https://img.shields.io/badge/deps-just%20mcp-lightgrey)
40
+ ![PRs](https://img.shields.io/badge/PRs-welcome-brightgreen)
41
+
42
+ Cheaplane is a tiny single-file MCP server (~250 lines, stdlib + `mcp` only) that gives your main agent — e.g. **Claude Code on a Max subscription** — one extra tool: **`delegate`**. Your agent keeps doing the thinking (planning, architecture, final review) and hands *replaceable grunt work* — boilerplate code, formatting, translation, summarizing long docs — to cheap models behind a local [LiteLLM](https://github.com/BerriAI/litellm) proxy (DeepSeek, Kimi, Qwen, …). Think of it as **a cheap intern for your premium agent** — it churns out the boring parts while you keep thinking.
43
+
44
+ The trick that makes it *safe*: **the delegated calls and your subscription live in physically separate processes and never share credentials.** ([why that matters ⬇️](#billing-isolation-the-whole-point))
45
+
46
+ The trick that makes it *effortless*: **auto-routing.** `delegate(task)` picks the right cheap model from the task itself — code → DeepSeek, long docs → Kimi, Chinese → Qwen. ([how ⬇️](#using-delegate))
47
+
48
+ The trick that makes it *stick*: **a per-turn reminder hook so your agent doesn't forget the tool exists** — [the part most "delegate" tools skip](#make-your-agent-actually-use-it). And a **savings ledger** shows you [what it kept off your quota](#see-what-you-saved).
49
+
50
+ **See it in action** — your agent hands a chore over; auto-routing sends it to the cheap code model:
51
+
52
+ ```text
53
+ delegate("convert to a TypeScript interface: {id, name, email, isAdmin, roles[]}")
54
+ ```
55
+
56
+ ```ts
57
+ interface User {
58
+ id: number;
59
+ name: string;
60
+ email: string;
61
+ isAdmin: boolean;
62
+ roles: string[];
63
+ }
64
+ ```
65
+
66
+ <sub>↑ a real call's output — not a mockup, and no model picked by hand. That token cost **~90× less** than your premium model, and your subscription quota never moved.</sub>
67
+
68
+ ## The problem
69
+
70
+ Premium models earn their price on hard problems — but every token counts against your plan, and you burn through quota on *churn*: reformatting JSON, translating UI strings, summarizing a doc you'll read once. The usual "just use a cheap model" setups force an ugly choice:
71
+
72
+ - **Downgrade the whole agent** → you lose main-thread quality on the work that actually matters.
73
+ - **Route everything through an API key** → you stop using the subscription you're already paying for.
74
+
75
+ Cheaplane keeps the sweet spot: **premium main thread for judgment + cheap models for the churn + billing that physically can't cross.**
76
+
77
+ ## How Cheaplane compares
78
+
79
+ The popular 2026 move is to swap your *whole* agent onto a cheap model (DeepClaude-style). Great for raw cost — but it downgrades the thread you actually think with, **breaks your other MCP tools**, and doesn't even apply if you're on a Pro/Max subscription. Cheaplane takes the opposite bet:
80
+
81
+ | | Swap whole agent → cheap model *(DeepClaude-style)* | Everything via one API key | **Cheaplane** |
82
+ |---|:---:|:---:|:---:|
83
+ | Main thread | ⬇️ downgraded | ⬇️ no more subscription | ✅ stays premium |
84
+ | Your other MCP tools | ❌ break | ✅ | ✅ *(it **is** an MCP server)* |
85
+ | Works on a Pro/Max subscription | ❌ API-key only | ❌ replaces it | ✅ built for it |
86
+ | Picks the cheap model for you | ❌ one model for everything | ❌ | ✅ `auto` routing |
87
+ | Shows what you saved | ❌ | ❌ | ✅ `savings` ledger |
88
+ | Billing | merged into one | one per-token bill | 🔒 subscription + cheap, **isolated** |
89
+
90
+ <sub>Comparison reflects how backend-swap setups (DeepClaude-style) behaved per public reports in mid-2026; specifics vary by tool and can change.</sub>
91
+
92
+ ## How cheap is "cheap"?
93
+
94
+ The grunt work is the *easy* part — paying premium rates for it is pure waste. Per **million tokens** (public list prices, mid-2026):
95
+
96
+ | Model | Input | Output | Best for |
97
+ |---|--:|--:|---|
98
+ | Claude Opus *(API, for reference)* | $5.00 | **$25.00** | the judgment work you keep |
99
+ | DeepSeek V4 Flash | $0.14 | **$0.28** | code / formatting |
100
+ | Kimi K2 | $0.60–0.95 | $2.50–4.00 | long docs (very large context) |
101
+ | Qwen | $0.05–0.40 | $0.20–1.20 | Chinese copy |
102
+
103
+ That's an output token costing **~$25 on Opus vs ~$0.28 on DeepSeek — about 90× more for work that doesn't need the smarts.** You're on a *subscription*, so you don't pay that $25 directly — your main thread spends *quota*, not dollars. That's the whole point: every routine task you offload is premium quota you keep for the hard problems. *(Summarizing a 40-page doc on DeepSeek Flash runs ~$0.005 — your quota never even notices.)*
104
+
105
+ <sub>Prices are public list rates, mid-2026, and vary by tier/caching — check each provider. The stable takeaway is the order-of-magnitude gap, not an exact dollar saving.</sub>
106
+
107
+ ## Billing isolation (the whole point)
108
+
109
+ Most "save money" hacks blur your bills together. Cheaplane keeps them physically apart:
110
+
111
+ ```mermaid
112
+ flowchart LR
113
+ A["Main agent<br/>premium subscription"] -->|"delegate(task)"| B["Cheaplane MCP<br/>own process, own key"]
114
+ B -->|HTTP| C["LiteLLM proxy<br/>localhost:4000"]
115
+ C --> D["DeepSeek / Kimi / Qwen<br/>cheap, pay-per-use"]
116
+ ```
117
+
118
+ The Cheaplane process **never imports your subscription provider's SDK, never reads its auth, never touches its OAuth token.** It knows exactly one thing: an HTTP endpoint (your proxy) and its key. Your main thread bills to your subscription; delegated calls bill to your cheap proxy. **The two can't cross — not by policy, by architecture.**
119
+
120
+ ## Quick start
121
+
122
+ **Fastest path** — Claude Code, one script:
123
+
124
+ ```bash
125
+ git clone https://github.com/millennialdreamer/cheaplane && cd cheaplane
126
+ cp litellm.yaml.example litellm.yaml # then: export DEEPSEEK_API_KEY=sk-...
127
+ litellm --config litellm.yaml & # start the cheap-model proxy on :4000
128
+ bash setup.sh # deps + register MCP + reminder hook + verify
129
+ ```
130
+
131
+ `setup.sh` is idempotent (safe to re-run): it installs deps, registers the `delegate` MCP server with Claude Code, installs the per-turn reminder hook, and verifies the chain end-to-end. Then start a fresh Claude Code session — done.
132
+
133
+ <p align="center"><img src="assets/setup.png" alt="bash setup.sh — installs deps, registers the MCP server with Claude Code, installs the reminder hook, and verifies the chain end-to-end" width="760"></p>
134
+
135
+ <details>
136
+ <summary><b>Manual setup / what <code>setup.sh</code> does under the hood</b></summary>
137
+
138
+ <br>
139
+
140
+ **1. Get an OpenAI-compatible endpoint for the cheap models.** Most people run [LiteLLM](https://github.com/BerriAI/litellm) locally as a proxy in front of DeepSeek / Kimi / Qwen. A minimal config is ~5 lines:
141
+
142
+ ```yaml
143
+ # litellm.yaml — exposes DeepSeek under the model_name "deepseek"
144
+ model_list:
145
+ - model_name: deepseek
146
+ litellm_params:
147
+ model: deepseek/deepseek-chat # swap for any provider/model LiteLLM supports
148
+ api_key: os.environ/DEEPSEEK_API_KEY
149
+ ```
150
+
151
+ ```bash
152
+ pip install 'litellm[proxy]'
153
+ litellm --config litellm.yaml # serves http://localhost:4000
154
+ ```
155
+
156
+ That `model_name: deepseek` lines up with Cheaplane's default alias, so it works out of the box. (`deepseek` is a built-in LiteLLM provider — no `api_base` needed; you'd add one only for a custom or self-hosted endpoint.) Already have an OpenAI-compatible endpoint (LiteLLM, OpenRouter, Ollama, vLLM…)? Skip this and just point `DELEGATE_BASE_URL` at it.
157
+
158
+ **2. Install Cheaplane:**
159
+
160
+ ```bash
161
+ git clone https://github.com/millennialdreamer/cheaplane && cd cheaplane
162
+ uv sync # or: python -m venv .venv && .venv/bin/pip install mcp
163
+ ```
164
+
165
+ **3. Register it with your MCP client** — copy `.mcp.json.example` to `.mcp.json` in the repo root and fix the path (or use `claude mcp add`):
166
+
167
+ ```json
168
+ {
169
+ "mcpServers": {
170
+ "delegate": {
171
+ "command": "uv",
172
+ "args": ["run", "--directory", "/ABSOLUTE/PATH/TO/cheaplane", "python", "server.py"]
173
+ }
174
+ }
175
+ }
176
+ ```
177
+
178
+ **4. Verify it end-to-end** — with your proxy from step 1 running (handshake → list tools → a real delegated call):
179
+
180
+ ```bash
181
+ uv run python probe.py
182
+ # ✅ chain works (main → MCP → cheap model → back)
183
+ ```
184
+
185
+ </details>
186
+
187
+ ## Using `delegate`
188
+
189
+ Your agent now has `delegate(task)` — **routing is automatic**; override only when you want to:
190
+
191
+ ```text
192
+ delegate("convert this JSON to a TypeScript interface: …") # auto → deepseek (code)
193
+ delegate("summarize this 40-page contract: …") # auto → kimi (very long input)
194
+ delegate("…Chinese text in the task auto-routes here…") # auto → qwen (Chinese copy)
195
+ delegate("translate these UI strings to Japanese", "flash") # explicit alias still wins
196
+ ```
197
+
198
+ | alias | good for |
199
+ |---|---|
200
+ | `auto` | **default** — picks one of the below from the task itself |
201
+ | `deepseek` | code / balanced |
202
+ | `mimo` | reasoning / multi-step |
203
+ | `flash` | fast / formatting / translation |
204
+ | `kimi` | long documents (very large context) |
205
+ | `qwen` | Chinese copywriting |
206
+
207
+ Aliases map to your LiteLLM `model_name`s. Point them at your proxy **without editing code** — set the `DELEGATE_MODEL_MAP` env var (a JSON object), or drop a `~/.claude/delegate-model-map.json` (hot-reloaded — no restart needed); editing `MODEL_ALIASES` in `server.py` also works.
208
+
209
+ <details>
210
+ <summary><b>What to delegate vs keep (rule of thumb)</b></summary>
211
+
212
+ <br>
213
+
214
+ **Delegate** (let the cheap model do it):
215
+ - boilerplate / scaffolding from a clear spec
216
+ - mechanical refactors, formatting, lint fixes
217
+ - translation; summarizing or extracting facts from long docs
218
+ - routine prose: changelogs, docstrings, commit messages
219
+
220
+ **Keep** (you do it yourself):
221
+ - planning, architecture, technical trade-offs
222
+ - **final review of delegated output — always you**
223
+ - talking to the user; judgment calls
224
+ - anything where being subtly wrong is expensive
225
+
226
+ The delegated model sees **only your `task` string** — it has no access to your conversation. Make each task self-contained: spec + the actual input + the exact output format you want.
227
+
228
+ </details>
229
+
230
+ ## See what you saved
231
+
232
+ Every delegated call appends one line of **metadata only — never the task content** — to `~/.cheaplane/usage.jsonl`. Ask your agent for `savings` any time (sample output):
233
+
234
+ ```text
235
+ Cheaplane savings — all time
236
+ delegated calls : 184
237
+ tokens offloaded: ~412,300 in / ~365,800 out
238
+ premium cost avoided (Opus list): ~$11.21
239
+ actually spent (DeepSeek-class) : ~$0.16 (≈70× cheaper, in+out blended)
240
+ last 7 days : 31 calls, ~$2.04 avoided
241
+ ```
242
+
243
+ Numbers are estimates at public list prices — the real win is the premium **quota** that never left your subscription. The ledger records token counts and model names only; delete the file any time, or set `DELEGATE_NO_LOG=1` to turn logging off entirely.
244
+
245
+ ## Make your agent actually use it
246
+
247
+ Here's the dirty secret of every "delegate to a cheap model" tool: **installing it isn't the hard part — getting your agent to actually *use* it is.** Drop a tool into an agent and, a few turns into a real task, it forgets the tool exists and grinds through the grunt work itself on premium tokens. The instruction sinks down the context; attention moves on.
248
+
249
+ Cheaplane ships the fix in the box — three layers you can stack:
250
+
251
+ 1. **Skill** (`SKILL.md`) — teaches the agent *when* to delegate. Works on any client; passive, so treat it as the baseline.
252
+ 2. **A one-line default** in your `CLAUDE.md` / system prompt: *"Before doing replaceable grunt work yourself, delegate it."* Stronger — but a static instruction still drifts down a long conversation.
253
+ 3. **A per-turn reminder hook** — the reliable one (Claude Code). It re-injects the nudge on **every** prompt, so the habit never sinks out of view. This is what turns an *installed* tool into a *used* one.
254
+
255
+ **On other MCP clients** (no `UserPromptSubmit` hook system), use layers 1–2 — wire the one-liner into whatever system prompt your client supports.
256
+
257
+ Install the hook — safe and idempotent (backs up your settings, **merges** instead of overwriting, de-dupes on re-run):
258
+
259
+ ```bash
260
+ bash install-hook.sh # registers hooks/delegate-reminder.sh as a UserPromptSubmit hook
261
+ # verify it's wired up:
262
+ python3 -c "import json,os;s=json.load(open(os.path.expanduser('~/.claude/settings.json')));print([h['command'] for e in s.get('hooks',{}).get('UserPromptSubmit',[]) for h in e.get('hooks',[])])"
263
+ ```
264
+
265
+ Start a fresh session, and your agent self-checks every turn: *"is this replaceable grunt work? → delegate it."*
266
+
267
+ <sub>The reminder costs ~60 tokens per turn — trivially less than the hundreds of premium tokens a single forgotten delegation burns. The hook uses Claude Code's <code>UserPromptSubmit</code> mechanism.</sub>
268
+
269
+ ## Config
270
+
271
+ | Env var | Default | Meaning |
272
+ |---|---|---|
273
+ | `DELEGATE_BASE_URL` | `http://localhost:4000` | OpenAI-compatible endpoint (your proxy) |
274
+ | `DELEGATE_API_KEY` | `sk-litellm` | key for that endpoint |
275
+ | `DELEGATE_TIMEOUT` | `120` | per-call timeout (seconds) |
276
+ | `DELEGATE_MODEL_MAP` | *(none)* | JSON remapping aliases, e.g. `{"deepseek":"deepseek-v4-flash"}` — overrides defaults, no code edit |
277
+ | `DELEGATE_LOG` | `~/.cheaplane/usage.jsonl` | where the savings ledger lives |
278
+ | `DELEGATE_NO_LOG` | *(unset)* | set to `1` to disable the ledger entirely |
279
+
280
+ ## FAQ
281
+
282
+ **Will this leak my subscription credentials?**
283
+ No. The `delegate` tool runs in its own process and only ever makes a plain HTTP call to the endpoint *you* configure. It never imports your subscription SDK and never sees its auth — see [Billing isolation](#billing-isolation-the-whole-point).
284
+
285
+ **What exactly does the savings ledger record?**
286
+ One JSON line per call: timestamp, alias, model name, and token/character counts. **Never the task text, never the model's output.** Delete `~/.cheaplane/usage.jsonl` any time, or set `DELEGATE_NO_LOG=1`.
287
+
288
+ **How does `auto` decide which model to use?**
289
+ A small deterministic heuristic in `server.py` (`_pick_model`, ~20 lines you can read and tweak): code signals → `deepseek`, very long input → `kimi`, Chinese-heavy → `qwen`, multi-step language → `mimo`, short mechanical chores → `flash`. An explicit alias always overrides it.
290
+
291
+ **How is this different from just using one API key for everything?**
292
+ With a single API key you stop using your subscription entirely and pay per token for *all* work — including the hard parts. Cheaplane keeps your subscription as the premium main thread and sends only the cheap, replaceable churn elsewhere.
293
+
294
+ **Does it work with anything besides Claude Code?**
295
+ Yes — any MCP-compatible client (Cursor, Cline, Windsurf, …). The main agent just needs to support MCP tools; see Manual setup for the generic JSON config.
296
+
297
+ **Do I have to use DeepSeek / Kimi / Qwen?**
298
+ No. Anything reachable through an OpenAI-compatible endpoint works; the aliases are just convenience labels you can remap with `DELEGATE_MODEL_MAP`.
299
+
300
+ **Why a proxy instead of calling providers directly?**
301
+ One endpoint, one key, usage logging, and easy model swaps — and it keeps provider keys out of the MCP server entirely.
302
+
303
+ ## Roadmap & ideas (help wanted)
304
+
305
+ Cheaplane's core stays deliberately tiny — but the surface it opens up is big. Shipped so far: ✅ auto-routing (v0.2), ✅ savings ledger (v0.2). Still worth building — proposals and PRs welcome, and most are small enough to be good first issues:
306
+
307
+ - **Smarter routing** — the current router is a readable heuristic; better signals (or a learned router) are an open playground.
308
+ - **Richer savings dashboard** — the ledger is plain JSONL; a `cheaplane stats` HTML view would be lovely.
309
+ - **Result cache** — skip re-delegating identical tasks.
310
+ - **Auto-review** — lint/test code that comes back before you trust it.
311
+ - **Batch / parallel delegate** — hand off several chores in one call.
312
+ - **More client adoption recipes** — the reminder hook targets Claude Code's `UserPromptSubmit`; Cursor / Cline / others want their own nudge.
313
+
314
+ > Design rule: **keep the core single-file and dependency-light — that's the whole point.** Build extensions as opt-in, so the 5-minute read stays a 5-minute read.
315
+
316
+ ## Contributing
317
+
318
+ Issues and PRs welcome — it's ~250 lines of single-file Python with no heavy deps, easy to hack on. Add a useful model alias, a routing signal, or a client recipe and send it over.
319
+
320
+ ## License
321
+
322
+ MIT — see [LICENSE](LICENSE).
@@ -0,0 +1,295 @@
1
+ <p align="center">
2
+ <img src="assets/hero-banner.png" alt="Cheaplane — keep your premium model on the main thread, offload the grunt work to cheap models with billing that can't cross" width="880">
3
+ </p>
4
+
5
+ # Cheaplane 🛣️
6
+
7
+ > **Keep your premium subscription on the main thread. Offload the grunt work to cheap models — Cheaplane even picks the right one for you. Stop burning premium tokens on boilerplate.**
8
+
9
+ ![License](https://img.shields.io/badge/license-MIT-green)
10
+ ![Python](https://img.shields.io/badge/python-3.10%2B-blue)
11
+ ![MCP](https://img.shields.io/badge/MCP-compatible-purple)
12
+ ![Deps](https://img.shields.io/badge/deps-just%20mcp-lightgrey)
13
+ ![PRs](https://img.shields.io/badge/PRs-welcome-brightgreen)
14
+
15
+ Cheaplane is a tiny single-file MCP server (~250 lines, stdlib + `mcp` only) that gives your main agent — e.g. **Claude Code on a Max subscription** — one extra tool: **`delegate`**. Your agent keeps doing the thinking (planning, architecture, final review) and hands *replaceable grunt work* — boilerplate code, formatting, translation, summarizing long docs — to cheap models behind a local [LiteLLM](https://github.com/BerriAI/litellm) proxy (DeepSeek, Kimi, Qwen, …). Think of it as **a cheap intern for your premium agent** — it churns out the boring parts while you keep thinking.
16
+
17
+ The trick that makes it *safe*: **the delegated calls and your subscription live in physically separate processes and never share credentials.** ([why that matters ⬇️](#billing-isolation-the-whole-point))
18
+
19
+ The trick that makes it *effortless*: **auto-routing.** `delegate(task)` picks the right cheap model from the task itself — code → DeepSeek, long docs → Kimi, Chinese → Qwen. ([how ⬇️](#using-delegate))
20
+
21
+ The trick that makes it *stick*: **a per-turn reminder hook so your agent doesn't forget the tool exists** — [the part most "delegate" tools skip](#make-your-agent-actually-use-it). And a **savings ledger** shows you [what it kept off your quota](#see-what-you-saved).
22
+
23
+ **See it in action** — your agent hands a chore over; auto-routing sends it to the cheap code model:
24
+
25
+ ```text
26
+ delegate("convert to a TypeScript interface: {id, name, email, isAdmin, roles[]}")
27
+ ```
28
+
29
+ ```ts
30
+ interface User {
31
+ id: number;
32
+ name: string;
33
+ email: string;
34
+ isAdmin: boolean;
35
+ roles: string[];
36
+ }
37
+ ```
38
+
39
+ <sub>↑ a real call's output — not a mockup, and no model picked by hand. That token cost **~90× less** than your premium model, and your subscription quota never moved.</sub>
40
+
41
+ ## The problem
42
+
43
+ Premium models earn their price on hard problems — but every token counts against your plan, and you burn through quota on *churn*: reformatting JSON, translating UI strings, summarizing a doc you'll read once. The usual "just use a cheap model" setups force an ugly choice:
44
+
45
+ - **Downgrade the whole agent** → you lose main-thread quality on the work that actually matters.
46
+ - **Route everything through an API key** → you stop using the subscription you're already paying for.
47
+
48
+ Cheaplane keeps the sweet spot: **premium main thread for judgment + cheap models for the churn + billing that physically can't cross.**
49
+
50
+ ## How Cheaplane compares
51
+
52
+ The popular 2026 move is to swap your *whole* agent onto a cheap model (DeepClaude-style). Great for raw cost — but it downgrades the thread you actually think with, **breaks your other MCP tools**, and doesn't even apply if you're on a Pro/Max subscription. Cheaplane takes the opposite bet:
53
+
54
+ | | Swap whole agent → cheap model *(DeepClaude-style)* | Everything via one API key | **Cheaplane** |
55
+ |---|:---:|:---:|:---:|
56
+ | Main thread | ⬇️ downgraded | ⬇️ no more subscription | ✅ stays premium |
57
+ | Your other MCP tools | ❌ break | ✅ | ✅ *(it **is** an MCP server)* |
58
+ | Works on a Pro/Max subscription | ❌ API-key only | ❌ replaces it | ✅ built for it |
59
+ | Picks the cheap model for you | ❌ one model for everything | ❌ | ✅ `auto` routing |
60
+ | Shows what you saved | ❌ | ❌ | ✅ `savings` ledger |
61
+ | Billing | merged into one | one per-token bill | 🔒 subscription + cheap, **isolated** |
62
+
63
+ <sub>Comparison reflects how backend-swap setups (DeepClaude-style) behaved per public reports in mid-2026; specifics vary by tool and can change.</sub>
64
+
65
+ ## How cheap is "cheap"?
66
+
67
+ The grunt work is the *easy* part — paying premium rates for it is pure waste. Per **million tokens** (public list prices, mid-2026):
68
+
69
+ | Model | Input | Output | Best for |
70
+ |---|--:|--:|---|
71
+ | Claude Opus *(API, for reference)* | $5.00 | **$25.00** | the judgment work you keep |
72
+ | DeepSeek V4 Flash | $0.14 | **$0.28** | code / formatting |
73
+ | Kimi K2 | $0.60–0.95 | $2.50–4.00 | long docs (very large context) |
74
+ | Qwen | $0.05–0.40 | $0.20–1.20 | Chinese copy |
75
+
76
+ That's an output token costing **~$25 on Opus vs ~$0.28 on DeepSeek — about 90× more for work that doesn't need the smarts.** You're on a *subscription*, so you don't pay that $25 directly — your main thread spends *quota*, not dollars. That's the whole point: every routine task you offload is premium quota you keep for the hard problems. *(Summarizing a 40-page doc on DeepSeek Flash runs ~$0.005 — your quota never even notices.)*
77
+
78
+ <sub>Prices are public list rates, mid-2026, and vary by tier/caching — check each provider. The stable takeaway is the order-of-magnitude gap, not an exact dollar saving.</sub>
79
+
80
+ ## Billing isolation (the whole point)
81
+
82
+ Most "save money" hacks blur your bills together. Cheaplane keeps them physically apart:
83
+
84
+ ```mermaid
85
+ flowchart LR
86
+ A["Main agent<br/>premium subscription"] -->|"delegate(task)"| B["Cheaplane MCP<br/>own process, own key"]
87
+ B -->|HTTP| C["LiteLLM proxy<br/>localhost:4000"]
88
+ C --> D["DeepSeek / Kimi / Qwen<br/>cheap, pay-per-use"]
89
+ ```
90
+
91
+ The Cheaplane process **never imports your subscription provider's SDK, never reads its auth, never touches its OAuth token.** It knows exactly one thing: an HTTP endpoint (your proxy) and its key. Your main thread bills to your subscription; delegated calls bill to your cheap proxy. **The two can't cross — not by policy, by architecture.**
92
+
93
+ ## Quick start
94
+
95
+ **Fastest path** — Claude Code, one script:
96
+
97
+ ```bash
98
+ git clone https://github.com/millennialdreamer/cheaplane && cd cheaplane
99
+ cp litellm.yaml.example litellm.yaml # then: export DEEPSEEK_API_KEY=sk-...
100
+ litellm --config litellm.yaml & # start the cheap-model proxy on :4000
101
+ bash setup.sh # deps + register MCP + reminder hook + verify
102
+ ```
103
+
104
+ `setup.sh` is idempotent (safe to re-run): it installs deps, registers the `delegate` MCP server with Claude Code, installs the per-turn reminder hook, and verifies the chain end-to-end. Then start a fresh Claude Code session — done.
105
+
106
+ <p align="center"><img src="assets/setup.png" alt="bash setup.sh — installs deps, registers the MCP server with Claude Code, installs the reminder hook, and verifies the chain end-to-end" width="760"></p>
107
+
108
+ <details>
109
+ <summary><b>Manual setup / what <code>setup.sh</code> does under the hood</b></summary>
110
+
111
+ <br>
112
+
113
+ **1. Get an OpenAI-compatible endpoint for the cheap models.** Most people run [LiteLLM](https://github.com/BerriAI/litellm) locally as a proxy in front of DeepSeek / Kimi / Qwen. A minimal config is ~5 lines:
114
+
115
+ ```yaml
116
+ # litellm.yaml — exposes DeepSeek under the model_name "deepseek"
117
+ model_list:
118
+ - model_name: deepseek
119
+ litellm_params:
120
+ model: deepseek/deepseek-chat # swap for any provider/model LiteLLM supports
121
+ api_key: os.environ/DEEPSEEK_API_KEY
122
+ ```
123
+
124
+ ```bash
125
+ pip install 'litellm[proxy]'
126
+ litellm --config litellm.yaml # serves http://localhost:4000
127
+ ```
128
+
129
+ That `model_name: deepseek` lines up with Cheaplane's default alias, so it works out of the box. (`deepseek` is a built-in LiteLLM provider — no `api_base` needed; you'd add one only for a custom or self-hosted endpoint.) Already have an OpenAI-compatible endpoint (LiteLLM, OpenRouter, Ollama, vLLM…)? Skip this and just point `DELEGATE_BASE_URL` at it.
130
+
131
+ **2. Install Cheaplane:**
132
+
133
+ ```bash
134
+ git clone https://github.com/millennialdreamer/cheaplane && cd cheaplane
135
+ uv sync # or: python -m venv .venv && .venv/bin/pip install mcp
136
+ ```
137
+
138
+ **3. Register it with your MCP client** — copy `.mcp.json.example` to `.mcp.json` in the repo root and fix the path (or use `claude mcp add`):
139
+
140
+ ```json
141
+ {
142
+ "mcpServers": {
143
+ "delegate": {
144
+ "command": "uv",
145
+ "args": ["run", "--directory", "/ABSOLUTE/PATH/TO/cheaplane", "python", "server.py"]
146
+ }
147
+ }
148
+ }
149
+ ```
150
+
151
+ **4. Verify it end-to-end** — with your proxy from step 1 running (handshake → list tools → a real delegated call):
152
+
153
+ ```bash
154
+ uv run python probe.py
155
+ # ✅ chain works (main → MCP → cheap model → back)
156
+ ```
157
+
158
+ </details>
159
+
160
+ ## Using `delegate`
161
+
162
+ Your agent now has `delegate(task)` — **routing is automatic**; override only when you want to:
163
+
164
+ ```text
165
+ delegate("convert this JSON to a TypeScript interface: …") # auto → deepseek (code)
166
+ delegate("summarize this 40-page contract: …") # auto → kimi (very long input)
167
+ delegate("…Chinese text in the task auto-routes here…") # auto → qwen (Chinese copy)
168
+ delegate("translate these UI strings to Japanese", "flash") # explicit alias still wins
169
+ ```
170
+
171
+ | alias | good for |
172
+ |---|---|
173
+ | `auto` | **default** — picks one of the below from the task itself |
174
+ | `deepseek` | code / balanced |
175
+ | `mimo` | reasoning / multi-step |
176
+ | `flash` | fast / formatting / translation |
177
+ | `kimi` | long documents (very large context) |
178
+ | `qwen` | Chinese copywriting |
179
+
180
+ Aliases map to your LiteLLM `model_name`s. Point them at your proxy **without editing code** — set the `DELEGATE_MODEL_MAP` env var (a JSON object), or drop a `~/.claude/delegate-model-map.json` (hot-reloaded — no restart needed); editing `MODEL_ALIASES` in `server.py` also works.
181
+
182
+ <details>
183
+ <summary><b>What to delegate vs keep (rule of thumb)</b></summary>
184
+
185
+ <br>
186
+
187
+ **Delegate** (let the cheap model do it):
188
+ - boilerplate / scaffolding from a clear spec
189
+ - mechanical refactors, formatting, lint fixes
190
+ - translation; summarizing or extracting facts from long docs
191
+ - routine prose: changelogs, docstrings, commit messages
192
+
193
+ **Keep** (you do it yourself):
194
+ - planning, architecture, technical trade-offs
195
+ - **final review of delegated output — always you**
196
+ - talking to the user; judgment calls
197
+ - anything where being subtly wrong is expensive
198
+
199
+ The delegated model sees **only your `task` string** — it has no access to your conversation. Make each task self-contained: spec + the actual input + the exact output format you want.
200
+
201
+ </details>
202
+
203
+ ## See what you saved
204
+
205
+ Every delegated call appends one line of **metadata only — never the task content** — to `~/.cheaplane/usage.jsonl`. Ask your agent for `savings` any time (sample output):
206
+
207
+ ```text
208
+ Cheaplane savings — all time
209
+ delegated calls : 184
210
+ tokens offloaded: ~412,300 in / ~365,800 out
211
+ premium cost avoided (Opus list): ~$11.21
212
+ actually spent (DeepSeek-class) : ~$0.16 (≈70× cheaper, in+out blended)
213
+ last 7 days : 31 calls, ~$2.04 avoided
214
+ ```
215
+
216
+ Numbers are estimates at public list prices — the real win is the premium **quota** that never left your subscription. The ledger records token counts and model names only; delete the file any time, or set `DELEGATE_NO_LOG=1` to turn logging off entirely.
217
+
218
+ ## Make your agent actually use it
219
+
220
+ Here's the dirty secret of every "delegate to a cheap model" tool: **installing it isn't the hard part — getting your agent to actually *use* it is.** Drop a tool into an agent and, a few turns into a real task, it forgets the tool exists and grinds through the grunt work itself on premium tokens. The instruction sinks down the context; attention moves on.
221
+
222
+ Cheaplane ships the fix in the box — three layers you can stack:
223
+
224
+ 1. **Skill** (`SKILL.md`) — teaches the agent *when* to delegate. Works on any client; passive, so treat it as the baseline.
225
+ 2. **A one-line default** in your `CLAUDE.md` / system prompt: *"Before doing replaceable grunt work yourself, delegate it."* Stronger — but a static instruction still drifts down a long conversation.
226
+ 3. **A per-turn reminder hook** — the reliable one (Claude Code). It re-injects the nudge on **every** prompt, so the habit never sinks out of view. This is what turns an *installed* tool into a *used* one.
227
+
228
+ **On other MCP clients** (no `UserPromptSubmit` hook system), use layers 1–2 — wire the one-liner into whatever system prompt your client supports.
229
+
230
+ Install the hook — safe and idempotent (backs up your settings, **merges** instead of overwriting, de-dupes on re-run):
231
+
232
+ ```bash
233
+ bash install-hook.sh # registers hooks/delegate-reminder.sh as a UserPromptSubmit hook
234
+ # verify it's wired up:
235
+ python3 -c "import json,os;s=json.load(open(os.path.expanduser('~/.claude/settings.json')));print([h['command'] for e in s.get('hooks',{}).get('UserPromptSubmit',[]) for h in e.get('hooks',[])])"
236
+ ```
237
+
238
+ Start a fresh session, and your agent self-checks every turn: *"is this replaceable grunt work? → delegate it."*
239
+
240
+ <sub>The reminder costs ~60 tokens per turn — trivially less than the hundreds of premium tokens a single forgotten delegation burns. The hook uses Claude Code's <code>UserPromptSubmit</code> mechanism.</sub>
241
+
242
+ ## Config
243
+
244
+ | Env var | Default | Meaning |
245
+ |---|---|---|
246
+ | `DELEGATE_BASE_URL` | `http://localhost:4000` | OpenAI-compatible endpoint (your proxy) |
247
+ | `DELEGATE_API_KEY` | `sk-litellm` | key for that endpoint |
248
+ | `DELEGATE_TIMEOUT` | `120` | per-call timeout (seconds) |
249
+ | `DELEGATE_MODEL_MAP` | *(none)* | JSON remapping aliases, e.g. `{"deepseek":"deepseek-v4-flash"}` — overrides defaults, no code edit |
250
+ | `DELEGATE_LOG` | `~/.cheaplane/usage.jsonl` | where the savings ledger lives |
251
+ | `DELEGATE_NO_LOG` | *(unset)* | set to `1` to disable the ledger entirely |
252
+
253
+ ## FAQ
254
+
255
+ **Will this leak my subscription credentials?**
256
+ No. The `delegate` tool runs in its own process and only ever makes a plain HTTP call to the endpoint *you* configure. It never imports your subscription SDK and never sees its auth — see [Billing isolation](#billing-isolation-the-whole-point).
257
+
258
+ **What exactly does the savings ledger record?**
259
+ One JSON line per call: timestamp, alias, model name, and token/character counts. **Never the task text, never the model's output.** Delete `~/.cheaplane/usage.jsonl` any time, or set `DELEGATE_NO_LOG=1`.
260
+
261
+ **How does `auto` decide which model to use?**
262
+ A small deterministic heuristic in `server.py` (`_pick_model`, ~20 lines you can read and tweak): code signals → `deepseek`, very long input → `kimi`, Chinese-heavy → `qwen`, multi-step language → `mimo`, short mechanical chores → `flash`. An explicit alias always overrides it.
263
+
264
+ **How is this different from just using one API key for everything?**
265
+ With a single API key you stop using your subscription entirely and pay per token for *all* work — including the hard parts. Cheaplane keeps your subscription as the premium main thread and sends only the cheap, replaceable churn elsewhere.
266
+
267
+ **Does it work with anything besides Claude Code?**
268
+ Yes — any MCP-compatible client (Cursor, Cline, Windsurf, …). The main agent just needs to support MCP tools; see Manual setup for the generic JSON config.
269
+
270
+ **Do I have to use DeepSeek / Kimi / Qwen?**
271
+ No. Anything reachable through an OpenAI-compatible endpoint works; the aliases are just convenience labels you can remap with `DELEGATE_MODEL_MAP`.
272
+
273
+ **Why a proxy instead of calling providers directly?**
274
+ One endpoint, one key, usage logging, and easy model swaps — and it keeps provider keys out of the MCP server entirely.
275
+
276
+ ## Roadmap & ideas (help wanted)
277
+
278
+ Cheaplane's core stays deliberately tiny — but the surface it opens up is big. Shipped so far: ✅ auto-routing (v0.2), ✅ savings ledger (v0.2). Still worth building — proposals and PRs welcome, and most are small enough to be good first issues:
279
+
280
+ - **Smarter routing** — the current router is a readable heuristic; better signals (or a learned router) are an open playground.
281
+ - **Richer savings dashboard** — the ledger is plain JSONL; a `cheaplane stats` HTML view would be lovely.
282
+ - **Result cache** — skip re-delegating identical tasks.
283
+ - **Auto-review** — lint/test code that comes back before you trust it.
284
+ - **Batch / parallel delegate** — hand off several chores in one call.
285
+ - **More client adoption recipes** — the reminder hook targets Claude Code's `UserPromptSubmit`; Cursor / Cline / others want their own nudge.
286
+
287
+ > Design rule: **keep the core single-file and dependency-light — that's the whole point.** Build extensions as opt-in, so the 5-minute read stays a 5-minute read.
288
+
289
+ ## Contributing
290
+
291
+ Issues and PRs welcome — it's ~250 lines of single-file Python with no heavy deps, easy to hack on. Add a useful model alias, a routing signal, or a client recipe and send it over.
292
+
293
+ ## License
294
+
295
+ MIT — see [LICENSE](LICENSE).
@@ -0,0 +1,34 @@
1
+ ---
2
+ name: cheaplane-delegate
3
+ description: Use the `delegate` MCP tool to offload replaceable grunt work (boilerplate code, mechanical refactors, formatting, translation, summarizing long documents) to cheap models, so you keep your premium tokens for judgment work. Trigger whenever a subtask is mechanical, well-specified, and doesn't need your full reasoning.
4
+ ---
5
+
6
+ # Delegating grunt work with `delegate`
7
+
8
+ You have an MCP tool `delegate(task)` backed by cheap models behind a local proxy. Use it to spend premium tokens only where your judgment matters.
9
+
10
+ ## Delegate it (let the cheap model do it)
11
+ - Boilerplate / scaffolding code from a clear spec
12
+ - Mechanical refactors, formatting, lint fixes
13
+ - Translation; summarizing or extracting facts from long documents
14
+ - Routine prose: changelogs, docstrings, commit messages
15
+ - Anything you'd describe as "just churn this out"
16
+
17
+ ## Do NOT delegate (you do it yourself)
18
+ - Planning, architecture, technical trade-offs
19
+ - **Final review of delegated output — always you**
20
+ - Talking to the user; judgment calls
21
+ - Anything where being subtly wrong is expensive
22
+
23
+ ## Write a good `task`
24
+ The cheap model sees ONLY your `task` string — it has **no access to this conversation**. Make it self-contained: include the spec, the actual input, and the exact output format you want.
25
+ - ❌ "fix the bug"
26
+ - ✅ "Here is a Python function: <code>. It raises KeyError on an empty dict. Return a corrected version that returns 0 instead, code only."
27
+
28
+ ## Picking a model
29
+ You usually don't: the default `model="auto"` routes by task — code → `deepseek`, long docs → `kimi`, Chinese copy → `qwen`, multi-step → `mimo`, quick chores → `flash`. Override with an explicit alias only when you know better (e.g. force `kimi` for a huge document).
30
+
31
+ ## Review what comes back
32
+ Delegated output is a **draft from a cheaper model** — skim it before you rely on it. If it starts with `[delegate-error]`, the call failed: read the message, then retry, switch model, or just do it yourself. You own the final result.
33
+
34
+ Occasionally call `savings` to see how much premium quota delegation has kept off the main thread.
@@ -0,0 +1,26 @@
1
+ #!/usr/bin/env bash
2
+ # Cheaplane — re-injects the "use delegate" reminder on every prompt.
3
+ #
4
+ # Why this exists: an agent forgets a tool once the conversation grows — the
5
+ # instruction sinks down the context and attention moves to the task at hand.
6
+ # Re-injecting a short reminder every turn is what turns an *installed* tool into
7
+ # a *used* one. Install with `bash install-hook.sh` (or wire it into settings.json
8
+ # by hand — see the README section "Make your agent actually use it").
9
+ #
10
+ # This hook fires on every prompt and always injects the same reminder, so it
11
+ # ignores the prompt payload; draining stdin just keeps strict shells happy.
12
+ cat >/dev/null 2>&1
13
+ python3 <<'PY'
14
+ import json
15
+ msg = (
16
+ "You have a delegate(task, model) MCP tool (Cheaplane) that offloads work to "
17
+ "cheaper models behind your local proxy. Before doing any REPLACEABLE GRUNT WORK "
18
+ "yourself — boilerplate, formatting, translation, summarizing long docs, "
19
+ "mechanical refactors, routine copy — delegate it to save your premium tokens/quota. "
20
+ "Keep JUDGMENT WORK (architecture, technical trade-offs, final review, talking to "
21
+ "the user) for yourself. Always review delegated output; make each task self-contained."
22
+ )
23
+ print(json.dumps({"hookSpecificOutput": {
24
+ "hookEventName": "UserPromptSubmit", "additionalContext": msg
25
+ }}))
26
+ PY
@@ -0,0 +1,70 @@
1
+ #!/usr/bin/env bash
2
+ # Cheaplane — one-shot installer for the "use delegate" reminder hook.
3
+ #
4
+ # Registers hooks/delegate-reminder.sh as a Claude Code UserPromptSubmit hook, so
5
+ # your agent is reminded to use `delegate` on every turn. An *installed* tool isn't
6
+ # a *used* tool until something keeps the habit fresh — this is that something.
7
+ #
8
+ # Safe & idempotent:
9
+ # - backs up your settings.json before touching it
10
+ # - MERGES into existing hooks (never overwrites what you already have)
11
+ # - de-dupes by script name, so re-running (or moving the repo) never piles up
12
+ # - writes atomically (temp file + validate + rename)
13
+ #
14
+ # Usage: bash install-hook.sh
15
+ # Target: $HOME/.claude/settings.json (override with CLAUDE_SETTINGS=/path)
16
+ set -euo pipefail
17
+
18
+ HOOK="$(cd "$(dirname "$0")" && pwd)/hooks/delegate-reminder.sh"
19
+ [ -f "$HOOK" ] || { echo "error: hook not found at $HOOK"; exit 1; }
20
+ chmod +x "$HOOK"
21
+
22
+ SETTINGS="${CLAUDE_SETTINGS:-$HOME/.claude/settings.json}"
23
+
24
+ HOOK_PATH="$HOOK" SETTINGS_PATH="$SETTINGS" python3 <<'PY'
25
+ import json, os, shutil, time
26
+
27
+ settings = os.environ["SETTINGS_PATH"]
28
+ hook = os.environ["HOOK_PATH"]
29
+ parent = os.path.dirname(settings)
30
+ if parent:
31
+ os.makedirs(parent, exist_ok=True)
32
+
33
+ try:
34
+ with open(settings) as f:
35
+ data = json.load(f)
36
+ except (OSError, ValueError):
37
+ data = {}
38
+
39
+ ups = data.setdefault("hooks", {}).setdefault("UserPromptSubmit", [])
40
+
41
+ def is_ours(h):
42
+ cmd = h.get("command")
43
+ return isinstance(cmd, str) and os.path.basename(cmd) == "delegate-reminder.sh"
44
+
45
+ # Idempotent by SCRIPT, not just by path: if the only delegate-reminder entry is
46
+ # already this exact path, do nothing; otherwise rebuild cleanly (handles a moved
47
+ # or re-cloned repo without leaving a duplicate or a dead path behind).
48
+ existing = [h for entry in ups for h in entry.get("hooks", []) if is_ours(h)]
49
+ if len(existing) == 1 and existing[0].get("command") == hook:
50
+ print("✓ already installed — nothing to do.")
51
+ else:
52
+ if os.path.exists(settings):
53
+ bak = settings + ".bak-" + time.strftime("%Y%m%d-%H%M%S")
54
+ shutil.copy2(settings, bak)
55
+ print("backed up settings →", bak)
56
+ # Drop any prior delegate-reminder entry (dedupe / fix a moved repo path)...
57
+ for entry in ups:
58
+ entry["hooks"] = [h for h in entry.get("hooks", []) if not is_ours(h)]
59
+ ups[:] = [e for e in ups if e.get("hooks")]
60
+ # ...then register exactly one pointing at the current location.
61
+ ups.append({"hooks": [{"type": "command", "command": hook}]})
62
+ tmp = settings + ".tmp"
63
+ with open(tmp, "w") as f:
64
+ json.dump(data, f, indent=2, ensure_ascii=False)
65
+ with open(tmp) as f: # validate the temp file before swapping it in
66
+ json.load(f)
67
+ os.replace(tmp, settings)
68
+ print("✓ installed delegate reminder hook →", settings)
69
+ print(" start a new Claude Code session for it to take effect.")
70
+ PY
@@ -0,0 +1,12 @@
1
+ # Cheaplane — minimal LiteLLM proxy config.
2
+ # 1) copy to litellm.yaml 2) export DEEPSEEK_API_KEY=... 3) litellm --config litellm.yaml
3
+ # Serves http://localhost:4000. The model_name "deepseek" matches Cheaplane's default
4
+ # alias, so delegate("...", "deepseek") works out of the box.
5
+ model_list:
6
+ - model_name: deepseek
7
+ litellm_params:
8
+ model: deepseek/deepseek-chat # V4 Flash alias (deprecates 2026-07-24); or any provider/model LiteLLM supports
9
+ api_key: os.environ/DEEPSEEK_API_KEY
10
+
11
+ # Add more cheap models the same way, then point Cheaplane's aliases at them via the
12
+ # DELEGATE_MODEL_MAP env var. Provider list: https://docs.litellm.ai/docs/providers
@@ -0,0 +1,40 @@
1
+ #!/usr/bin/env python3
2
+ """End-to-end probe: connect to server.py over the real MCP protocol (stdio),
3
+ handshake -> list tools -> call delegate with auto-routing, and print what the
4
+ cheap model returns. Verifies the whole "main agent -> MCP tool -> cheap model"
5
+ chain actually works."""
6
+ import os
7
+ import sys
8
+ import asyncio
9
+ from mcp import ClientSession, StdioServerParameters
10
+ from mcp.client.stdio import stdio_client
11
+
12
+ # Launch the server with the current interpreter (this probe's venv python): portable, no hard-coded absolute path
13
+ PY = sys.executable
14
+ SERVER = os.path.join(os.path.dirname(os.path.abspath(__file__)), "server.py")
15
+
16
+
17
+ async def main():
18
+ # Pass our env through so DELEGATE_* overrides apply to the spawned server too
19
+ # (the MCP SDK only forwards a minimal default env unless told otherwise).
20
+ params = StdioServerParameters(command=PY, args=[SERVER], env=dict(os.environ))
21
+ async with stdio_client(params) as (read, write):
22
+ async with ClientSession(read, write) as session:
23
+ await session.initialize()
24
+ tools = await session.list_tools()
25
+ print("1. handshake OK; tools exposed =", [t.name for t in tools.tools])
26
+
27
+ print("2. calling delegate() with auto-routing: ask the cheap model for one short line…")
28
+ r = await session.call_tool(
29
+ "delegate",
30
+ {"task": "In one short sentence, tell me which model you are."},
31
+ )
32
+ text = r.content[0].text if r.content else "(empty)"
33
+ print(" cheap model says >>>", text[:400])
34
+
35
+ ok = not text.startswith("[delegate-error]") and text.strip()
36
+ print("\n3. end-to-end result:", "✅ chain works (main → MCP → cheap model → back)" if ok else "❌ failed, see error above")
37
+
38
+
39
+ if __name__ == "__main__":
40
+ asyncio.run(main())
@@ -0,0 +1,53 @@
1
+ [project]
2
+ name = "cheaplane"
3
+ version = "0.2.0"
4
+ description = "Offload grunt work from your subscription LLM to cheap models via MCP — auto-routing, a savings ledger, and billing isolation."
5
+ readme = "README.md"
6
+ requires-python = ">=3.10"
7
+ dependencies = ["mcp>=1.2"]
8
+ license = "MIT"
9
+ license-files = ["LICENSE"]
10
+ authors = [
11
+ { name = "millennialdreamer", email = "269377871+millennialdreamer@users.noreply.github.com" },
12
+ ]
13
+ keywords = ["mcp", "model-context-protocol", "llm", "claude", "claude-code", "litellm", "cost-optimization", "deepseek"]
14
+ classifiers = [
15
+ "Development Status :: 4 - Beta",
16
+ "Environment :: Console",
17
+ "Intended Audience :: Developers",
18
+ "Operating System :: MacOS",
19
+ "Operating System :: POSIX :: Linux",
20
+ "Programming Language :: Python :: 3",
21
+ "Programming Language :: Python :: 3.10",
22
+ "Programming Language :: Python :: 3.11",
23
+ "Programming Language :: Python :: 3.12",
24
+ "Programming Language :: Python :: 3.13",
25
+ "Topic :: Software Development :: Code Generators",
26
+ "Topic :: Utilities",
27
+ ]
28
+
29
+ [project.urls]
30
+ Homepage = "https://github.com/millennialdreamer/cheaplane"
31
+ Repository = "https://github.com/millennialdreamer/cheaplane"
32
+ Issues = "https://github.com/millennialdreamer/cheaplane/issues"
33
+
34
+ [project.scripts]
35
+ cheaplane = "cheaplane:main"
36
+
37
+ [build-system]
38
+ requires = ["hatchling"]
39
+ build-backend = "hatchling.build"
40
+
41
+ # The repo stays a "clone and run" project — server.py sits at the root so
42
+ # `python server.py` and setup.sh keep working untouched. The wheel ships that
43
+ # same single file as the top-level `cheaplane` module.
44
+ [tool.hatch.build.targets.wheel]
45
+ force-include = { "server.py" = "cheaplane.py" }
46
+
47
+ [tool.hatch.build.targets.sdist]
48
+ include = ["server.py", "probe.py", "setup.sh", "install-hook.sh", "hooks", "litellm.yaml.example", "README.md", "LICENSE", "SKILL.md"]
49
+
50
+ # Keep `uv sync` installing dependencies only, without building the project —
51
+ # contributors run the checkout directly rather than an installed copy.
52
+ [tool.uv]
53
+ package = false
@@ -0,0 +1,256 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ Cheaplane — delegate MCP server
4
+ ===============================
5
+ Gives a main agent (e.g. Claude Code on a premium subscription) one extra tool to
6
+ offload *replaceable grunt work* to cheaper models, while it keeps the judgment
7
+ work (planning, architecture, final review) for itself — saving premium quota
8
+ without losing main-thread quality.
9
+
10
+ ⭐ Billing isolation (the core idea): this process makes a plain HTTP call to a
11
+ local OpenAI-compatible proxy with its own key. It never shares a process or
12
+ credentials with the main agent's subscription auth — the two are physically
13
+ isolated and can't cross.
14
+
15
+ ⭐ Auto-routing (v0.2): with model="auto" (the default) Cheaplane picks the right
16
+ cheap model from the task itself — code → deepseek, very long input → kimi,
17
+ Chinese → qwen, multi-step → mimo, quick chores → flash. An explicit alias
18
+ always wins.
19
+
20
+ ⭐ Savings ledger (v0.2): each delegated call appends one line of METADATA ONLY
21
+ (never the task content) to ~/.cheaplane/usage.jsonl, so the `savings` tool
22
+ can show what you've kept off your premium quota. Opt out: DELEGATE_NO_LOG=1.
23
+
24
+ Dependencies: just the mcp SDK (1.x or 2.x); everything else is the Python stdlib.
25
+ """
26
+ import os
27
+ import json
28
+ import time
29
+ import urllib.request
30
+ import urllib.error
31
+
32
+ try:
33
+ # mcp >= 2.0 renamed FastMCP to MCPServer; the constructor, @tool() and run() are unchanged.
34
+ from mcp.server.mcpserver import MCPServer as _Server
35
+ except ImportError: # mcp 1.x
36
+ from mcp.server.fastmcp import FastMCP as _Server
37
+
38
+ # Upstream = local LiteLLM proxy by default; override via env to target any OpenAI-compatible endpoint
39
+ BASE_URL = os.environ.get("DELEGATE_BASE_URL", "http://localhost:4000")
40
+ API_KEY = os.environ.get("DELEGATE_API_KEY", "sk-litellm") # a local proxy ignores the key; set a real one for real endpoints
41
+ TIMEOUT = int(os.environ.get("DELEGATE_TIMEOUT", "120")) # per-call timeout (seconds); raise for long docs
42
+
43
+ # Savings ledger (metadata only — never task content). Opt out with DELEGATE_NO_LOG=1.
44
+ NO_LOG = os.environ.get("DELEGATE_NO_LOG") == "1"
45
+ LOG_PATH = os.path.expanduser(os.environ.get("DELEGATE_LOG", "~/.cheaplane/usage.jsonl"))
46
+
47
+ # Public list prices per 1M tokens (mid-2026) — used ONLY for the savings estimate.
48
+ PREMIUM_IN, PREMIUM_OUT = 5.00, 25.00 # Claude Opus API, for reference
49
+ CHEAP_IN, CHEAP_OUT = 0.14, 0.28 # DeepSeek-class
50
+
51
+ # Friendly aliases -> the model_name your proxy exposes for each cheap model.
52
+ # Defaults are the alias names themselves; remap without touching code via the
53
+ # DELEGATE_MODEL_MAP env var (JSON), e.g. '{"deepseek": "deepseek-v4-flash"}',
54
+ # or the hot-reload file below. A raw proxy model_name also works directly.
55
+ MODEL_ALIASES = {
56
+ "deepseek": "deepseek", # code / balanced
57
+ "mimo": "mimo", # reasoning / multi-step
58
+ "flash": "flash", # fast / formatting / translation
59
+ "kimi": "kimi", # long documents, very large context
60
+ "qwen": "qwen", # Chinese copywriting
61
+ }
62
+
63
+ _env_map = os.environ.get("DELEGATE_MODEL_MAP")
64
+ if _env_map:
65
+ try:
66
+ MODEL_ALIASES.update(json.loads(_env_map))
67
+ except (ValueError, TypeError):
68
+ pass # malformed JSON -> keep the defaults above
69
+
70
+ # Hot-reload config file: re-read on every call so edits apply to all running
71
+ # sessions without a restart. Takes priority over env var + defaults.
72
+ _MAP_FILE = os.path.expanduser("~/.claude/delegate-model-map.json")
73
+
74
+ def _get_aliases() -> dict:
75
+ """Return the alias map, preferring the hot-reload file over startup-time defaults."""
76
+ try:
77
+ with open(_MAP_FILE) as f:
78
+ return {**MODEL_ALIASES, **json.load(f)}
79
+ except (OSError, ValueError):
80
+ return MODEL_ALIASES
81
+
82
+
83
+ def _pick_model(task: str) -> str:
84
+ """Heuristic router for model='auto' — cheap, deterministic, explainable.
85
+
86
+ Order matters: code beats length (code models handle long code), length beats
87
+ language (long Chinese docs still want the long-context model), and the final
88
+ fallback is the balanced code model.
89
+ """
90
+ t = task.lower()
91
+ if any(s in t for s in ("```", "def ", "class ", "function", "refactor", "regex",
92
+ "stack trace", "compile", "typescript", "interface", "sql",
93
+ "json", "yaml", "unit test", "bug", "lint", "docstring")):
94
+ return "deepseek"
95
+ if len(task) > 12000:
96
+ return "kimi"
97
+ han = sum(1 for c in task if "\u4e00" <= c <= "\u9fff")
98
+ if han > max(20, len(task) * 0.15):
99
+ return "qwen"
100
+ if any(s in t for s in ("step by step", "multi-step", "pipeline", "workflow",
101
+ "orchestrate", "subtasks", "break this down")):
102
+ return "mimo"
103
+ if len(task) < 600 and any(s in t for s in ("translate", "format", "reword", "rewrite",
104
+ "fix typo", "rename", "bullet", "summarize")):
105
+ return "flash"
106
+ return "deepseek"
107
+
108
+
109
+ def _log(alias: str, real_model: str, usage: dict, task_chars: int, out_chars: int) -> None:
110
+ """Append one metadata-only line to the savings ledger. Never logs content."""
111
+ if NO_LOG:
112
+ return
113
+ try:
114
+ parent = os.path.dirname(LOG_PATH)
115
+ if parent:
116
+ os.makedirs(parent, exist_ok=True)
117
+ rec = {"ts": int(time.time()), "alias": alias, "model": real_model,
118
+ "in_tok": usage.get("prompt_tokens"), "out_tok": usage.get("completion_tokens"),
119
+ "task_chars": task_chars, "out_chars": out_chars}
120
+ with open(LOG_PATH, "a", encoding="utf-8") as f:
121
+ f.write(json.dumps(rec) + "\n")
122
+ except Exception:
123
+ pass # bookkeeping must never break a delegation
124
+
125
+
126
+ mcp = _Server("delegate")
127
+
128
+
129
+ @mcp.tool()
130
+ def delegate(task: str, model: str = "auto", max_tokens: int = 4000) -> str:
131
+ """Offload a self-contained subtask to a cheaper model and return its output.
132
+
133
+ WHEN TO USE: hand off *replaceable grunt work* to save your premium tokens —
134
+ boilerplate code, small bug fixes, formatting, translation, reading/summarizing
135
+ long documents, drafting routine copy. Do NOT delegate judgment work (planning,
136
+ architecture, final review, talking to the user) — keep that for yourself.
137
+
138
+ The delegated model sees ONLY the `task` string and has NO access to this
139
+ conversation. So make `task` fully self-contained (include all needed context).
140
+
141
+ Args:
142
+ task: Complete, self-contained instruction for the cheap model.
143
+ model: "auto" (default) routes by task — code→deepseek, long docs→kimi,
144
+ Chinese→qwen, multi-step→mimo, quick chores→flash. Or force an
145
+ alias (deepseek/mimo/flash/kimi/qwen) or a raw proxy model_name.
146
+ max_tokens: Output cap. Default 4000 (kept large so reasoning models that
147
+ spend budget on hidden thinking still return non-empty text).
148
+
149
+ Note: a call typically takes ~10-60s (longer for big inputs) and blocks until
150
+ the cheap model returns, so prefer one focused task per call.
151
+
152
+ Returns:
153
+ The model's text output, or a string starting with "[delegate-error]" on failure.
154
+ """
155
+ if not task.strip():
156
+ return "[delegate-error] empty task — pass the full, self-contained instruction."
157
+ aliases = _get_aliases()
158
+ alias = _pick_model(task) if model.lower() == "auto" else model
159
+ real_model = aliases.get(alias.lower(), alias)
160
+ body = json.dumps({
161
+ "model": real_model,
162
+ "messages": [{"role": "user", "content": task}],
163
+ "max_tokens": max_tokens,
164
+ }).encode()
165
+ req = urllib.request.Request(
166
+ f"{BASE_URL}/v1/chat/completions",
167
+ data=body,
168
+ headers={
169
+ "Content-Type": "application/json",
170
+ "Authorization": f"Bearer {API_KEY}",
171
+ },
172
+ )
173
+ try:
174
+ with urllib.request.urlopen(req, timeout=TIMEOUT) as r:
175
+ d = json.load(r)
176
+ except urllib.error.HTTPError as e:
177
+ detail = e.read()[:300].decode("utf-8", "replace")
178
+ return f"[delegate-error] HTTP {e.code} from {real_model}: {detail}"
179
+ except Exception as e:
180
+ return f"[delegate-error] {type(e).__name__}: {e} (is your proxy up at {BASE_URL}?)"
181
+
182
+ ch = (d.get("choices") or [{}])[0]
183
+ text = (ch.get("message") or {}).get("content") or ""
184
+ if not text.strip():
185
+ # A reasoning model may spend its budget on hidden thinking: content comes
186
+ # back empty though the model is alive — hint to raise the cap.
187
+ return (f"[delegate-error] empty output from {real_model} "
188
+ f"(finish={ch.get('finish_reason')}); try a larger max_tokens.")
189
+ _log(alias, real_model, d.get("usage") or {}, len(task), len(text))
190
+ return text
191
+
192
+
193
+ @mcp.tool()
194
+ def savings() -> str:
195
+ """Show what delegating has kept off your premium quota (estimates, list prices)."""
196
+ try:
197
+ with open(LOG_PATH, encoding="utf-8") as f:
198
+ lines = f.read().splitlines()
199
+ except OSError:
200
+ return ("No delegations logged yet — run a few delegate() calls first. "
201
+ "(Logging disabled? unset DELEGATE_NO_LOG.)")
202
+ now = time.time()
203
+ tot = {"n": 0, "in": 0, "out": 0}
204
+ week = {"n": 0, "in": 0, "out": 0}
205
+ for ln in lines:
206
+ try:
207
+ r = json.loads(ln)
208
+ except ValueError:
209
+ continue # skip a corrupt line rather than fail the report
210
+ it, ot = r.get("in_tok"), r.get("out_tok")
211
+ i = it if isinstance(it, int) else max(1, r.get("task_chars", 0) // 4) # ~4 chars/token fallback
212
+ o = ot if isinstance(ot, int) else max(1, r.get("out_chars", 0) // 4)
213
+ tot["n"] += 1; tot["in"] += i; tot["out"] += o
214
+ if now - r.get("ts", 0) <= 7 * 86400:
215
+ week["n"] += 1; week["in"] += i; week["out"] += o
216
+ if not tot["n"]:
217
+ return "No delegations logged yet — run a few delegate() calls first."
218
+
219
+ def cost(b, in_rate, out_rate):
220
+ return (b["in"] * in_rate + b["out"] * out_rate) / 1e6
221
+
222
+ prem = cost(tot, PREMIUM_IN, PREMIUM_OUT)
223
+ cheap = cost(tot, CHEAP_IN, CHEAP_OUT)
224
+ week_prem = cost(week, PREMIUM_IN, PREMIUM_OUT)
225
+ mult = (prem / cheap) if cheap else 0.0
226
+ return (f"Cheaplane savings — all time\n"
227
+ f" delegated calls : {tot['n']}\n"
228
+ f" tokens offloaded: ~{tot['in']:,} in / ~{tot['out']:,} out\n"
229
+ f" premium cost avoided (Opus list): ~${prem:,.2f}\n"
230
+ f" actually spent (DeepSeek-class) : ~${cheap:,.2f} (≈{mult:.0f}× cheaper, in+out blended)\n"
231
+ f" last 7 days : {week['n']} calls, ~${week_prem:,.2f} avoided\n"
232
+ f"(estimates from logged token counts at public list prices; your main thread\n"
233
+ f" runs on subscription quota — the real win is the quota you kept)")
234
+
235
+
236
+ @mcp.tool()
237
+ def list_models() -> str:
238
+ """List the model aliases available to delegate(), with their best use."""
239
+ notes = {
240
+ "auto": "DEFAULT — routes by task (code→deepseek, long→kimi, zh→qwen, multi-step→mimo, chores→flash)",
241
+ "deepseek": "code / balanced",
242
+ "mimo": "reasoning / multi-step agent chains",
243
+ "flash": "fast / formatting / translation",
244
+ "kimi": "long documents, very large context",
245
+ "qwen": "Chinese copywriting",
246
+ }
247
+ return json.dumps(notes, ensure_ascii=False, indent=2)
248
+
249
+
250
+ def main() -> None:
251
+ """Console-script entry point (`cheaplane`), also used by `python server.py`."""
252
+ mcp.run()
253
+
254
+
255
+ if __name__ == "__main__":
256
+ main()
@@ -0,0 +1,59 @@
1
+ #!/usr/bin/env bash
2
+ # Cheaplane — one-command setup for Claude Code.
3
+ # Wires the `delegate` tool + the reminder hook into Claude Code, end to end.
4
+ # Safe to re-run: every step is idempotent.
5
+ #
6
+ # bash setup.sh
7
+ #
8
+ # Prereq: a cheap-model proxy on http://localhost:4000 (see step 2 / litellm.yaml.example).
9
+ set -euo pipefail
10
+ cd "$(dirname "$0")"
11
+ ROOT="$(pwd)"
12
+
13
+ echo "▸ 1/4 Python deps"
14
+ if command -v uv >/dev/null 2>&1; then
15
+ uv sync >/dev/null
16
+ PYBIN="$ROOT/.venv/bin/python"
17
+ else
18
+ [ -d .venv ] || python3 -m venv .venv
19
+ .venv/bin/pip install -q mcp
20
+ PYBIN="$ROOT/.venv/bin/python"
21
+ fi
22
+ echo " ✓ $PYBIN"
23
+
24
+ BASE="${DELEGATE_BASE_URL:-http://localhost:4000}"
25
+ echo "▸ 2/4 cheap-model proxy at $BASE"
26
+ if curl -sf --max-time 3 "$BASE/health/liveliness" >/dev/null 2>&1 || curl -sf --max-time 3 "$BASE/v1/models" >/dev/null 2>&1; then
27
+ echo " ✓ proxy is up"
28
+ else
29
+ echo " ! no proxy yet — start one in 3 steps:"
30
+ echo " cp litellm.yaml.example litellm.yaml"
31
+ echo " export DEEPSEEK_API_KEY=sk-..."
32
+ echo " litellm --config litellm.yaml"
33
+ fi
34
+
35
+ echo "▸ 3/4 register the MCP server with Claude Code"
36
+ if command -v claude >/dev/null 2>&1; then
37
+ if claude mcp list 2>/dev/null | grep -qi '\bdelegate\b'; then
38
+ echo " • 'delegate' already registered — skipping"
39
+ else
40
+ claude mcp add delegate -s user -- "$PYBIN" "$ROOT/server.py" \
41
+ && echo " ✓ registered (user scope)" \
42
+ || echo " • couldn't auto-register — add it manually (README → Quick start)"
43
+ fi
44
+ else
45
+ echo " • Claude Code CLI not found — register manually (README → Quick start)"
46
+ fi
47
+
48
+ echo "▸ 4/4 install the 'use delegate' reminder hook"
49
+ bash install-hook.sh
50
+
51
+ echo "▸ verify end-to-end"
52
+ # a just-started proxy needs a moment — wait up to ~10s for it before probing
53
+ for _ in $(seq 1 10); do
54
+ if curl -sf --max-time 2 "$BASE/health/liveliness" >/dev/null 2>&1 || curl -sf --max-time 2 "$BASE/v1/models" >/dev/null 2>&1; then break; fi
55
+ sleep 1
56
+ done
57
+ "$PYBIN" probe.py || echo " (probe failed — is the proxy at $BASE up? see step 2)"
58
+
59
+ echo "✓ done — start a NEW Claude Code session and your agent will offload grunt work to cheap models."