cheaplane 0.2.0__py3-none-any.whl

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,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,6 @@
1
+ cheaplane.py,sha256=fh7nXrdovjj60jTfcssEiBw-brLW1iIkme6YN94O0g0,11535
2
+ cheaplane-0.2.0.dist-info/METADATA,sha256=EALkxESRQXRD6gr1B7Hft2s6RQFi4G4hj0oFWJAdAIE,18247
3
+ cheaplane-0.2.0.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87
4
+ cheaplane-0.2.0.dist-info/entry_points.txt,sha256=2pa8z9gNUppD8WWFcj-gdIAD0PcXgdQU1WkSIP5SAxQ,45
5
+ cheaplane-0.2.0.dist-info/licenses/LICENSE,sha256=lgvqBUt5IxSZ4JgXJYdy3gU802WZrtf95zynlEIWjPk,1074
6
+ cheaplane-0.2.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.32.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ cheaplane = cheaplane:main
@@ -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.
cheaplane.py ADDED
@@ -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()