The 80B Qwen3-Coder-Next on a 16 GB Mac, about 13 tok/s, fully offline. A mixture-of-experts inference engine for Apple silicon.
Rust
0.5.2 docs: README front cut to install, size, time, tok/s; the crew app under docs/crew; 0.5.2 notes (tester's numbers to fill)
1picassoai80e1a83f86c4
diff --git a/README.md b/README.mdindex 06980c9..0d24691 100644--- a/README.md+++ b/README.md@@ -7,58 +7,39 @@# Coachwhip-**The 80-billion-parameter Qwen3-Coder-Next on a 16 GB Mac, at 11.5 to 13.4 tok/s. Fully offline. Nothing leaves your machine.**+## **Qwen3.6-35B on a 16 GB Mac. {TPS35} tok/s. Fully offline.**-**Requirements:** Apple silicon Mac (M1 to M4; M4 measured, earlier chips slower), 16 GB unified memory, macOS 15 or later, about 35 GB of free disk.+**Install: under a minute. Model: 14.2 GB, about five minutes on a fast line. Then it runs.**-**Install the binary:**+Apple silicon, 16 GB, macOS 15 or later, 35 GB of free disk.++**1. Install**```shcurl -fsSL https://raw.githubusercontent.com/1picassoai/coachwhip/main/install.sh | bash```-**Download the pre-squeezed model (29 GB) and the tokenizer:**+**2. Download the model** (14.2 GB, ready-squeezed)```shmkdir -p ~/coachwhip/models && cd ~/coachwhip/models-curl -L -O https://huggingface.co/vinnj/coachwhip-models/resolve/main/Qwen3-Coder-Next.Q2X.gguf-curl -L -O https://huggingface.co/Qwen/Qwen3-Coder-Next/resolve/main/tokenizer.json-```--sha256 of the model file: `cdc0584c1e4d30134cbb83f18e4c7607af90bd1145a64940c7a357b02a0216af` (`shasum -a 256 Qwen3-Coder-Next.Q2X.gguf`). It was squeezed once from [MaziyarPanahi's Q3_K_M](https://huggingface.co/MaziyarPanahi/Qwen3-Coder-Next-GGUF) with the `coachwhip-prepare` tool that ships in the install; the squeeze is reproducible, same bytes every time.--**Start the chat in your browser:**--```sh-~/coachwhip/coachwhip.sh ~/coachwhip/models/Qwen3-Coder-Next.Q2X.gguf ~/coachwhip/models/tokenizer.json 109 8090 --parallel --flash-reads --stand-ins+curl -L -O https://huggingface.co/vinnj/coachwhip-models/resolve/main/Qwen3.6-35B-A3B.Q2X.gguf+curl -L -O https://huggingface.co/Qwen/Qwen3.6-35B-A3B/resolve/main/tokenizer.json```-The chat opens at http://127.0.0.1:8090. Measured on a Mac mini M4 with 16 GB: 12.8 to 13.4 tok/s on short prompts, 11.5 tok/s with a 13,000-token prompt, three runs each, with 3 GB of memory left for macOS at its tightest. Drop `--stand-ins` for every expert read exactly, at about 5 tok/s. Numbers and the quality check: [release notes](docs/releases/0.5.1.md).--<p align="center"><img src="docs/coachwhip-demo-coder.gif" alt="The 80B Qwen3-Coder-Next writing a TypeScript function in the Coachwhip chat on a 16 GB Mac mini, in real time, at 13 tok/s" width="720"></p>--**Use it from coding tools, through the local OpenAI API:**--| Setting | Value |-|---|---|-| Base URL | `http://127.0.0.1:8090/v1` |-| API key | anything; it is ignored |-| Model | `Qwen3-Coder-Next.Q2X.gguf` |--Aider in the terminal:+**3. Run** (the chat opens in your browser)```sh-aider --openai-api-base http://127.0.0.1:8090/v1 --openai-api-key anything --model openai/Qwen3-Coder-Next.Q2X.gguf --map-tokens 0 src/queue.ts+~/coachwhip/coachwhip.sh ~/coachwhip/models/Qwen3.6-35B-A3B.Q2X.gguf ~/coachwhip/models/tokenizer.json 68 8090 --parallel --flash-reads --stand-ins```-**How it works:**+**Next**-- Keeps the part of the model every word needs on the GPU, and streams the experts each word asks for from the SSD.-- Guesses the next layers' experts with the model's own routers and reads them in while the GPU is busy on this one.-- Reads experts straight from the SSD, past the page cache (`--flash-reads`), into memory the GPU reads directly; no copies.-- Other models, gpt-oss-120b among them, and what each needs: [docs/MODELS.md](docs/MODELS.md).+- Your tools: OpenAI API on `http://127.0.0.1:8090/v1`, any key, model `Qwen3.6-35B-A3B.Q2X`. Aider: `aider --openai-api-base http://127.0.0.1:8090/v1 --openai-api-key anything --model openai/Qwen3.6-35B-A3B.Q2X --map-tokens 0`+- Bigger models: the 80B coder and gpt-oss-120b, on the [models page](docs/MODELS.md).+- Numbers and how they were measured: [release notes](docs/releases/0.5.2.md).-License: Apache-2.0 (see [LICENSE](LICENSE)).+Measured on a Mac mini M4 with 16 GB; your Mac moves the number. Model sha256 `8b919b5eb649f74a9c1d528a4c00aef3a633017032b94848b04b1f2fb312b9ad`, squeezed once from [unsloth's UD-Q4_K_M](https://huggingface.co/unsloth/Qwen3.6-35B-A3B-GGUF) with the tool in the install.---diff --git a/docs/crew/README.md b/docs/crew/README.mdnew file mode 100644index 0000000..a9a2498--- /dev/null+++ b/docs/crew/README.md@@ -0,0 +1,13 @@+# Coachwhip Crew++Four CrewAI agents (analyst, architect, developer, tester) work a coding task through Coachwhip's local OpenAI door, on one screen, every word streaming. A runner (no AI) executes the developer's code; a judge runs a fixed set of checks the agents never see.++- `crew_app.py` — the server and the crew. `python crew_app.py`, then open http://127.0.0.1:8072/ and press Run. Needs `crewai` (`pip install crewai`) and, for the runner and judge, Node with `npx tsx`.+- `crew_app.html` — the page.+- `task_lru.txt` — the task. Change it for your own work.+- `judge_lru.ts` — the judge: eight executed checks for the LRU task. Write your own for your task; it imports `./main`, the developer's code.+- `record_app.py` — records a run to MP4 at 1280x720 (needs `playwright` and its Chromium).++Env: `COACHWHIP_BASE` (default `http://127.0.0.1:8090/v1`), `CREW_PORT` (8072), `CREW_MAX_TOKENS` (3000). For a cloud door: `CREW_CLOUD=1`, `CREW_CLOUD_BASE`, `CREW_CLOUD_MODEL`, `CREW_CLOUD_KEY_FILE` (a file holding the key; never the key itself), `CREW_PRICE_IN` / `CREW_PRICE_OUT` in dollars per million tokens for the cost chip.++Nothing leaves your machine on the local door: the page listens on 127.0.0.1 only.diff --git a/docs/crew/crew_app.html b/docs/crew/crew_app.htmlnew file mode 100644index 0000000..700e733--- /dev/null+++ b/docs/crew/crew_app.html@@ -0,0 +1,160 @@+<!doctype html>+<html lang="en">+<head>+<meta charset="utf-8">+<meta name="viewport" content="width=device-width, initial-scale=1">+<title>Coachwhip Crew</title>+<link rel="preconnect" href="https://fonts.googleapis.com"><link href="https://fonts.googleapis.com/css2?family=Inter:wght@500;700;800&family=JetBrains+Mono:wght@400;600&display=swap" rel="stylesheet">+<style>+ :root { --bg:#070912; --panel:rgba(18,22,34,.72); --line:rgba(255,255,255,.07); --text:#eef1f8; --muted:#8e97ad; --mono:"JetBrains Mono", ui-monospace, Menlo, Consolas, monospace;+ --ba:#64b5ff; --arch:#c48bff; --dev:#58e39b; --tester:#ffb454; --bad:#ff6b7a; }+ * { box-sizing:border-box; }+ body { margin:0; color:var(--text); font:14px/1.45 Inter, -apple-system, "Segoe UI", sans-serif; overflow:hidden; min-height:100vh;+ background: radial-gradient(1200px 600px at 15% -10%, rgba(100,181,255,.14), transparent 60%), radial-gradient(900px 500px at 95% 110%, rgba(88,227,155,.12), transparent 60%), radial-gradient(700px 400px at 60% 40%, rgba(196,139,255,.07), transparent 60%), var(--bg); }+ body::before { content:""; position:fixed; inset:0; background-image: linear-gradient(rgba(255,255,255,.035) 1px, transparent 1px), linear-gradient(90deg, rgba(255,255,255,.035) 1px, transparent 1px); background-size: 36px 36px; mask-image: radial-gradient(ellipse at center, #000 30%, transparent 85%); pointer-events:none; }+ header { position:relative; display:flex; align-items:center; gap:14px; padding:12px 22px; border-bottom:1px solid var(--line); backdrop-filter: blur(8px); }+ .brand { font-weight:800; font-size:19px; letter-spacing:-.2px; white-space:nowrap; } .brand span { background:linear-gradient(90deg,var(--dev),var(--ba)); -webkit-background-clip:text; background-clip:text; color:transparent; }+ .meta { color:var(--muted); font-family:var(--mono); font-size:12px; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; max-width:380px; }+ .right { margin-left:auto; display:flex; gap:8px; align-items:center; }+ .chip { font-size:11.5px; padding:4px 10px; border-radius:999px; border:1px solid var(--line); background:rgba(255,255,255,.03); color:var(--muted); font-family:var(--mono); white-space:nowrap; }+ .chip.on { border-color:rgba(88,227,155,.5); color:var(--dev); background:rgba(88,227,155,.08); box-shadow: 0 0 14px rgba(88,227,155,.15); }+ .chip.warn { border-color:rgba(255,180,84,.5); color:var(--tester); background:rgba(255,180,84,.08); }+ main { position:relative; padding:12px 22px 0; }+ .task { display:flex; gap:10px; align-items:center; margin-bottom:12px; }+ .task .text { flex:1; background:var(--panel); border:1px solid var(--line); border-radius:12px; padding:9px 14px; font:12.5px/1.4 var(--mono); color:#c9d0de; height:42px; overflow:hidden; white-space:nowrap; text-overflow:ellipsis; }+ .task button { background:linear-gradient(135deg, var(--dev), #37c8ff); color:#06231a; border:0; border-radius:12px; height:42px; padding:0 22px; font-weight:800; font-size:14px; cursor:pointer; box-shadow: 0 6px 20px rgba(88,227,155,.25); }+ .task button:disabled { opacity:.45; cursor:default; box-shadow:none; }+ .flow { display:grid; grid-template-columns: 1fr 48px 1fr 48px 1fr 48px 1fr; align-items:stretch; margin-bottom:12px; }+ .node { --c: var(--muted); background:var(--panel); border:1px solid var(--line); border-radius:16px; padding:12px 14px 10px; position:relative; min-height:160px; transition: border-color .3s, box-shadow .3s, transform .3s; backdrop-filter: blur(6px); }+ #n-ba { --c: var(--ba); } #n-arch { --c: var(--arch); } #n-dev { --c: var(--dev); } #n-tester { --c: var(--tester); }+ .node::before { content:""; position:absolute; left:0; top:0; width:100%; height:3px; border-radius:16px 16px 0 0; background:var(--c); opacity:.25; }+ .node.active { border-color:var(--c); box-shadow: 0 0 0 1px color-mix(in srgb, var(--c) 35%, transparent), 0 10px 40px color-mix(in srgb, var(--c) 22%, transparent); transform: translateY(-2px); }+ .node.active::before { opacity:1; box-shadow: 0 0 18px var(--c); }+ .node.done { border-color: color-mix(in srgb, var(--c) 40%, transparent); } .node.done::before { opacity:.7; }+ .node .top { display:flex; align-items:center; gap:12px; }+ .node .name { font-weight:800; font-size:14.5px; letter-spacing:-.1px; }+ .node .role { color:var(--muted); font-size:11.5px; font-family:var(--mono); }+ .node .st { margin-left:auto; font-family:var(--mono); font-size:11px; color:var(--muted); }+ .node.active .st { color:var(--c); } .node.done .st { color:var(--c); opacity:.8; }+ .node.active .st::before { content:"●"; margin-right:5px; animation:blink 1s infinite; }+ @keyframes blink { 50% { opacity:.15; } }+ .bot { width:48px; height:48px; flex:none; filter: drop-shadow(0 4px 10px rgba(0,0,0,.4)); }+ .bot .body { fill:#161b2a; stroke:#3b4461; stroke-width:1.5; }+ .bot .eye { fill:#3b4461; stroke:#3b4461; }+ .bot .ant { stroke:#3b4461; stroke-width:2; fill:none; }+ .node.active .bot .body { stroke:var(--c); fill: color-mix(in srgb, var(--c) 12%, #161b2a); }+ .node.active .bot .eye { fill:var(--c); stroke:var(--c); animation: eyes 1.2s infinite; filter: drop-shadow(0 0 6px var(--c)); }+ .node.active .bot .ant { stroke:var(--c); }+ .node.active .bot { animation: bob 1.4s ease-in-out infinite; }+ .node.done .bot .eye { fill:var(--c); stroke:var(--c); opacity:.75; } .node.done .bot .body { stroke: color-mix(in srgb, var(--c) 60%, #3b4461); }+ @keyframes bob { 50% { transform: translateY(-4px) rotate(-2deg); } }+ @keyframes eyes { 0%,100% { opacity:1 } 50% { opacity:.3 } }+ .screen { margin-top:10px; background:#070a12; border:1px solid rgba(255,255,255,.06); border-radius:10px; height:78px; overflow:hidden; padding:7px 9px; font:11px/1.35 var(--mono); color:#aeb6c8; white-space:pre-wrap; position:relative; }+ .screen::after { content:""; position:absolute; left:0; right:0; top:0; height:20px; background:linear-gradient(#070a12, transparent); }+ .node.active .screen { border-color: color-mix(in srgb, var(--c) 35%, transparent); }+ .node.active .screen::before { content:"▍"; position:absolute; right:8px; bottom:6px; color:var(--c); animation: blink .8s infinite; }+ .foot { margin-top:7px; font-family:var(--mono); font-size:11px; color:var(--muted); min-height:14px; }+ .node.done .foot { color:var(--c); }+ .link { position:relative; }+ .link::before { content:""; position:absolute; left:6px; right:6px; top:50%; height:2px; background:rgba(255,255,255,.08); border-radius:2px; }+ .link .dot { position:absolute; top:50%; left:6px; width:9px; height:9px; margin-top:-4px; border-radius:50%; background:#fff; box-shadow:0 0 12px #fff; opacity:0; }+ .link.on .dot { animation: travel 1s linear infinite; }+ @keyframes travel { 0% { left:6px; opacity:0 } 15% { opacity:1 } 85% { opacity:1 } 100% { left:calc(100% - 14px); opacity:0 } }+ .link.done::before { background:linear-gradient(90deg, rgba(88,227,155,.6), rgba(88,227,155,.25)); }+ .bottom { display:grid; grid-template-columns: 1.6fr 1fr 1fr; gap:12px; }+ .panel { background:var(--panel); border:1px solid var(--line); border-radius:16px; overflow:hidden; display:flex; flex-direction:column; height:318px; backdrop-filter: blur(6px); }+ .panel h3 { margin:0; padding:10px 14px; font-size:12.5px; border-bottom:1px solid var(--line); display:flex; align-items:center; gap:8px; color:#d6dbe8; font-weight:700; }+ .panel h3 .st { margin-left:auto; font-family:var(--mono); font-size:11px; color:var(--muted); font-weight:400; }+ .panel .out { flex:1; overflow:auto; padding:10px 14px; font:12px/1.5 var(--mono); white-space:pre-wrap; color:#d7dbe4; }+ .score { font-size:52px; font-weight:800; line-height:1; margin:4px 0 6px; font-family:var(--mono); letter-spacing:-1px; }+ .score.ok { color:var(--dev); text-shadow: 0 0 24px rgba(88,227,155,.45); } .score.bad { color:var(--bad); text-shadow: 0 0 24px rgba(255,107,122,.4); } .score.wait { color:#232a3b; }+ .judge .out { font-size:11.5px; }+ .verdict { padding:9px 14px; border-top:1px solid var(--line); font-size:12px; font-family:var(--mono); color:var(--muted); min-height:38px; }+ .verdict.ok { color:var(--dev); } .verdict.bad { color:var(--bad); }+</style>+</head>+<body>+<header>+ <div class="brand">coachwhip <span>crew</span></div>+ <div class="meta" id="meta">model: waiting for the door</div>+ <div class="right">+ <span class="chip" id="speed">tok/s: measuring</span>+ <span class="chip on" id="bytes">bytes to the internet: 0</span>+ <span class="chip" id="cost">cost: $0.00</span>+ <span class="chip on" id="local">127.0.0.1 only</span>+ <span class="chip on">no telemetry</span>+ <span class="chip" id="clock">00:00</span>+ </div>+</header>+<main>+ <div class="task">+ <div class="text" id="tasktext" title=""></div>+ <button id="go">Run the crew</button>+ </div>+ <div class="flow">+ <div class="node" id="n-ba"><div class="top">+ <svg class="bot" viewBox="0 0 44 44"><path class="ant" d="M22 4v6"/><circle class="ant" cx="22" cy="4" r="2"/><rect class="body" x="7" y="10" width="30" height="24" rx="7"/><circle class="eye" cx="16" cy="21" r="3"/><circle class="eye" cx="28" cy="21" r="3"/><rect class="body" x="14" y="34" width="16" height="6" rx="2"/></svg>+ <div><div class="name">Analyst</div><div class="role">requirements</div></div><div class="st" id="st-ba">waiting</div></div>+ <div class="screen" id="sc-ba"></div><div class="foot" id="ft-ba"></div></div>+ <div class="link" id="l1"><div class="dot"></div></div>+ <div class="node" id="n-arch"><div class="top">+ <svg class="bot" viewBox="0 0 44 44"><path class="ant" d="M22 4v6"/><circle class="ant" cx="22" cy="4" r="2"/><rect class="body" x="7" y="10" width="30" height="24" rx="7"/><rect class="eye" x="12" y="18" width="8" height="6" rx="1.5"/><rect class="eye" x="24" y="18" width="8" height="6" rx="1.5"/><rect class="body" x="14" y="34" width="16" height="6" rx="2"/></svg>+ <div><div class="name">Architect</div><div class="role">design</div></div><div class="st" id="st-arch">waiting</div></div>+ <div class="screen" id="sc-arch"></div><div class="foot" id="ft-arch"></div></div>+ <div class="link" id="l2"><div class="dot"></div></div>+ <div class="node" id="n-dev"><div class="top">+ <svg class="bot" viewBox="0 0 44 44"><path class="ant" d="M22 4v6"/><circle class="ant" cx="22" cy="4" r="2"/><rect class="body" x="7" y="10" width="30" height="24" rx="7"/><circle class="eye" cx="16" cy="21" r="3.5"/><circle class="eye" cx="28" cy="21" r="3.5"/><rect class="body" x="14" y="34" width="16" height="6" rx="2"/></svg>+ <div><div class="name">Developer</div><div class="role">code</div></div><div class="st" id="st-dev">waiting</div></div>+ <div class="screen" id="sc-dev"></div><div class="foot" id="ft-dev"></div></div>+ <div class="link" id="l3"><div class="dot"></div></div>+ <div class="node" id="n-tester"><div class="top">+ <svg class="bot" viewBox="0 0 44 44"><path class="ant" d="M22 4v6"/><circle class="ant" cx="22" cy="4" r="2"/><rect class="body" x="7" y="10" width="30" height="24" rx="7"/><path class="eye" d="M12 19l4 4 4-4" fill="none" stroke-width="2.5"/><path class="eye" d="M24 19l4 4 4-4" fill="none" stroke-width="2.5"/><rect class="body" x="14" y="34" width="16" height="6" rx="2"/></svg>+ <div><div class="name">Tester</div><div class="role">review</div></div><div class="st" id="st-tester">waiting</div></div>+ <div class="screen" id="sc-tester"></div><div class="foot" id="ft-tester"></div></div>+ </div>+ <div class="bottom">+ <div class="panel"><h3>live output <span class="st" id="live-who">—</span></h3><div class="out" id="live"></div></div>+ <div class="panel"><h3>▶ runner · executes the code, no AI <span class="st" id="st-run">waiting</span></h3><div class="out" id="out-run"></div></div>+ <div class="panel judge"><h3>⚖ judge · 8 executed checks, same for every run <span class="st" id="st-judge">waiting</span></h3>+ <div class="out"><div class="score wait" id="score">– / 8</div><div id="out-judge"></div></div>+ <div class="verdict" id="verdict"></div></div>+ </div>+</main>+<script>+const $ = id => document.getElementById(id);+const SEATS = ['ba','arch','dev','tester'];+const LINKS = {ba:null, arch:'l1', dev:'l2', tester:'l3'};+const buf = {};+let t0=null, timer=null, live=null;+function tick(){ if(!t0) return; const s=Math.floor((Date.now()-t0)/1000); $('clock').textContent=String(Math.floor(s/60)).padStart(2,'0')+':'+String(s%60).padStart(2,'0'); }+function reset(){ for(const k of SEATS){ buf[k]=''; $('sc-'+k).textContent=''; $('ft-'+k).textContent=''; $('st-'+k).textContent='waiting'; $('n-'+k).className='node'; }+ for(const l of ['l1','l2','l3']) $(l).className='link'; $('live').textContent=''; $('live-who').textContent='—';+ $('out-run').textContent=''; $('st-run').textContent='waiting'; $('score').textContent='– / 8'; $('score').className='score wait'; $('out-judge').textContent=''; $('st-judge').textContent='waiting';+ $('verdict').textContent=''; $('verdict').className='verdict'; $('speed').textContent='tok/s: measuring'; $('speed').className='chip'; $('cost').textContent='cost: $0.00'; }+const es = new EventSource('/events');+es.onmessage = e => {+ const ev = JSON.parse(e.data);+ if (ev.kind==='model'){ $('meta').textContent='model: '+ev.model+' · '+ev.where; if (ev.task){ $('tasktext').textContent=ev.task; $('tasktext').title=ev.task; }+ if (ev.local){ $('local').textContent='127.0.0.1 only'; $('local').className='chip on'; $('bytes').textContent='bytes to the internet: 0'; $('bytes').className='chip on'; }+ else { $('local').textContent='cloud: '+ev.host; $('local').className='chip warn'; $('bytes').className='chip warn'; } }+ else if (ev.kind==='start'){ $('n-'+ev.seat).className='node active'; $('st-'+ev.seat).textContent='working'; live=ev.seat; $('live-who').textContent=$('n-'+ev.seat).querySelector('.name').textContent; $('live').textContent=''; const l=LINKS[ev.seat]; if(l){ $(l).className='link on'; } }+ else if (ev.kind==='chunk'){ buf[ev.seat]=(buf[ev.seat]||'')+ev.text; $('sc-'+ev.seat).textContent=buf[ev.seat].slice(-420); if(live===ev.seat){ $('live').textContent=buf[ev.seat]; $('live').scrollTop=$('live').scrollHeight; } }+ else if (ev.kind==='done'){ $('n-'+ev.seat).className='node done'; $('st-'+ev.seat).textContent='done'; const l=LINKS[ev.seat]; if(l) $(l).className='link done';+ $('ft-'+ev.seat).textContent = ev.secs+' s'+(ev.tps?' · wrote '+ev.tokens+' at '+ev.tps+' tok/s':'')+(ev.rps?' · read '+ev.ptokens+' at '+ev.rps+' tok/s':'');+ if (ev.seat==='dev' && ev.tps){ $('speed').textContent=ev.tps+' tok/s measured'; $('speed').className='chip on'; }+ if (!buf[ev.seat] && ev.output){ $('sc-'+ev.seat).textContent=ev.output.slice(-420); if(live===ev.seat) $('live').textContent=ev.output; } }+ else if (ev.kind==='bytes'){ $('bytes').textContent='bytes to the internet: '+ev.bytes.toLocaleString(); }+ else if (ev.kind==='cost'){ $('cost').textContent='cost: $'+ev.usd.toFixed(4); }+ else if (ev.kind==='run_start'){ $('st-run').textContent='running '+(ev.lang||''); }+ else if (ev.kind==='run_done'){ $('st-run').textContent= ev.ok===null?'skipped':(ev.ok?'exit 0':'failed'); $('out-run').textContent=ev.output; }+ else if (ev.kind==='judge'){ $('st-judge').textContent='scored'; $('score').textContent=ev.pass+' / '+ev.total; $('score').className='score '+(ev.pass===ev.total?'ok':'bad'); $('out-judge').textContent=ev.lines; }+ else if (ev.kind==='verdict'){ $('verdict').textContent=(ev.met?'tester: ALL REQUIREMENTS MET':'tester: '+ev.text.split('\n')[0].slice(0,140)); $('verdict').className='verdict '+(ev.met?'ok':'bad'); }+ else if (ev.kind==='error'){ $('verdict').textContent=ev.text; $('verdict').className='verdict bad'; }+ else if (ev.kind==='end'){ $('go').disabled=false; clearInterval(timer); tick(); }+};+$('go').onclick = async () => { reset(); $('go').disabled=true; t0=Date.now(); timer=setInterval(tick,500);+ const r = await fetch('/run',{method:'POST'}); if (r.status!==202) $('go').disabled=false; };+fetch('/task').then(r=>r.json()).then(j=>{ $('tasktext').textContent=j.task; $('tasktext').title=j.task; });+</script>+</body>+</html>diff --git a/docs/crew/crew_app.py b/docs/crew/crew_app.pynew file mode 100644index 0000000..3aa2b3d--- /dev/null+++ b/docs/crew/crew_app.py@@ -0,0 +1,259 @@+"""Coachwhip Crew — four CrewAI agents (Analyst -> Architect -> Developer -> Tester) build and review a piece+of code through an OpenAI-compatible door, shown as a pipeline of robots on one screen, every word streaming.+Then the code is RUN (a runner, no AI) and SCORED by a judge: seven executed checks, the same file for every run.++ python crew_app.py then open http://127.0.0.1:8072/++Doors:+ local (default) COACHWHIP_BASE=http://127.0.0.1:8090/v1 — a Coachwhip door; bytes to the internet: 0.+ cloud CREW_CLOUD=1 CREW_CLOUD_BASE=https://api.openai.com/v1 CREW_CLOUD_MODEL=<name>+ CREW_CLOUD_KEY_FILE=<path to a file holding the key> — the key is read inside, never printed.+ CREW_PRICE_IN / CREW_PRICE_OUT: $ per million tokens, for the cost chip.+Task: CREW_TASK_FILE (default task_lru.txt). Judge: judge_lru.ts (expects `export class LruCache` in the code).+Nothing leaves this machine on the local door: the page listens on 127.0.0.1 only.+"""+import json, os, re, sys, time, threading, queue, subprocess, tempfile, shutil+from http.server import ThreadingHTTPServer, BaseHTTPRequestHandler+from urllib.parse import urlparse++from crewai import Agent, Task, Crew, Process, LLM+from crewai.events import BaseEventListener+from crewai.events.types.llm_events import LLMStreamChunkEvent, LLMCallStartedEvent, LLMCallCompletedEvent+from crewai.events.types.agent_events import AgentExecutionStartedEvent, AgentExecutionCompletedEvent++HERE = os.path.dirname(os.path.abspath(__file__))+CLOUD = os.environ.get("CREW_CLOUD") == "1"+BASE = os.environ.get("CREW_CLOUD_BASE", "https://api.openai.com/v1") if CLOUD else os.environ.get("COACHWHIP_BASE", "http://127.0.0.1:8090/v1")+PORT = int(os.environ.get("CREW_PORT", "8072"))+MAX_TOKENS = int(os.environ.get("CREW_MAX_TOKENS", "3000"))+PRICE_IN = float(os.environ.get("CREW_PRICE_IN", "0"))+PRICE_OUT = float(os.environ.get("CREW_PRICE_OUT", "0"))+TASK_FILE = os.environ.get("CREW_TASK_FILE", os.path.join(HERE, "task_lru.txt"))+JUDGE_FILE = os.environ.get("CREW_JUDGE_FILE", os.path.join(HERE, "judge_lru.ts"))+HOST = urlparse(BASE).hostname or ""+LOCAL = HOST in ("127.0.0.1", "localhost")++events: "queue.Queue[dict]" = queue.Queue()+state = {"running": False, "model": os.environ.get("CREW_CLOUD_MODEL") if CLOUD else os.environ.get("COACHWHIP_MODEL"),+ "seat": None, "started": {}, "chars": {}, "tps": {}, "first": {}, "call_t0": None, "tok_in": 0, "tok_out": 0}++SEATS = {"Business Analyst": "ba", "Software Architect": "arch", "Senior Developer": "dev", "Strict Tester": "tester"}+++def emit(**kw):+ kw["t"] = time.time()+ events.put(kw)+++def api_key():+ if not CLOUD:+ return "anything"+ path = os.environ.get("CREW_CLOUD_KEY_FILE", "")+ return open(path, encoding="utf-8").read().strip()+++def model_name():+ if state["model"]:+ return state["model"]+ import urllib.request+ opener = urllib.request.build_opener(urllib.request.ProxyHandler({})) # never a system proxy for a loopback door+ req = urllib.request.Request(BASE.rstrip("/") + "/models", headers={"Host": "127.0.0.1:8090"})+ with opener.open(req, timeout=10) as r:+ data = json.load(r)+ state["model"] = data["data"][0]["id"]+ return state["model"]+++def task_text():+ return open(TASK_FILE, encoding="utf-8").read().strip()+++class Streamer(BaseEventListener):+ def setup_listeners(self, bus):+ @bus.on(AgentExecutionStartedEvent)+ def started(source, event):+ role = getattr(event.agent, "role", None) if hasattr(event, "agent") else None+ seat = SEATS.get(role)+ if seat:+ state["seat"] = seat+ state["started"][seat] = time.time()+ state["chars"][seat] = 0+ state["tps"].pop(seat, None)+ state["first"].pop(seat, None)+ emit(kind="start", seat=seat)++ @bus.on(LLMStreamChunkEvent)+ def chunk(source, event):+ seat = SEATS.get(getattr(event, "agent_role", None)) or state["seat"]+ if seat and event.chunk:+ if state["chars"].get(seat, 0) == 0:+ state["first"][seat] = time.time() # the first word: everything before it was reading the prompt+ state["chars"][seat] = state["chars"].get(seat, 0) + len(event.chunk)+ emit(kind="chunk", seat=seat, text=event.chunk)++ @bus.on(LLMCallStartedEvent)+ def call_started(source, event):+ seat = SEATS.get(getattr(event, "agent_role", None)) or state["seat"]+ if seat:+ state["call_t0"] = (seat, time.time())++ @bus.on(LLMCallCompletedEvent)+ def call_done(source, event):+ # Measured, not estimated: completion tokens reported for the call over the call's wall time.+ seat = SEATS.get(getattr(event, "agent_role", None)) or state["seat"]+ t0 = state.get("call_t0")+ usage = getattr(event, "usage", None) or {}+ if not isinstance(usage, dict):+ usage = {}+ toks = usage.get("completion_tokens")+ if seat and t0 and t0[0] == seat and toks:+ now = time.time()+ first = state["first"].get(seat) or t0[1]+ state["tps"][seat] = (toks, now - t0[1], usage.get("prompt_tokens") or 0, first - t0[1], now - first)+ state["tok_in"] += usage.get("prompt_tokens") or 0+ state["tok_out"] += toks or 0+ if not LOCAL:+ # Rough bytes sent: prompt tokens ~ 4 bytes each; the real wire count is higher, never lower.+ emit(kind="bytes", bytes=state["tok_in"] * 4)+ emit(kind="cost", usd=(state["tok_in"] * PRICE_IN + state["tok_out"] * PRICE_OUT) / 1e6)++ @bus.on(AgentExecutionCompletedEvent)+ def done(source, event):+ role = getattr(event.agent, "role", None) if hasattr(event, "agent") else None+ seat = SEATS.get(role)+ if seat:+ secs = time.time() - state["started"].get(seat, time.time())+ toks, csecs, ptoks, read_s, write_s = state["tps"].get(seat, (None, None, 0, 0, 0))+ tps = round(toks / write_s, 1) if toks and write_s and write_s > 0.5 else None+ rps = round(ptoks / read_s, 1) if ptoks and read_s and read_s > 0.2 else None+ emit(kind="done", seat=seat, secs=round(secs, 1), tokens=toks, tps=tps, ptokens=ptoks, rps=rps, output=str(getattr(event, "output", "")))+++def extract_code(text):+ m = re.search(r"```(\w+)?\s*\n(.*?)```", text, re.S)+ if not m:+ return None, None+ return (m.group(1) or "").lower(), m.group(2)+++def run_and_judge(lang, code):+ """Runner: execute the code's own usage example. Judge: the seven checks. Returns (ok, out, pass, total, lines)."""+ d = tempfile.mkdtemp(prefix="crew-run-")+ try:+ if lang not in ("ts", "typescript"):+ return None, f"no runner for language {lang!r}", 0, 8, "judge expects TypeScript"+ path = os.path.join(d, "main.ts")+ open(path, "w", encoding="utf-8").write(code)+ p = subprocess.run(["npx", "--yes", "tsx", path], capture_output=True, text=True, timeout=120, shell=(os.name == "nt"))+ run_out = ((p.stdout + p.stderr).strip() or "(no output)") + f"\n\nexit code {p.returncode}"+ shutil.copy(JUDGE_FILE, os.path.join(d, "judge.ts"))+ j = subprocess.run(["npx", "--yes", "tsx", os.path.join(d, "judge.ts")], capture_output=True, text=True, timeout=120, shell=(os.name == "nt"))+ jout = (j.stdout + j.stderr).strip()+ m = re.search(r"SCORE (\d+)/(\d+)", jout)+ if m:+ passed, total = int(m.group(1)), int(m.group(2))+ else:+ passed, total = 0, 8+ jout = "judge could not run the code:\n" + jout[-1200:]+ lines = "\n".join(l for l in jout.splitlines() if l.startswith(("PASS", "FAIL"))) or jout[-1200:]+ return p.returncode == 0, run_out, passed, total, lines+ except subprocess.TimeoutExpired:+ return False, "timed out after 120 s", 0, 8, "timed out"+ finally:+ shutil.rmtree(d, ignore_errors=True)+++def run_crew():+ state["running"] = True+ state["tok_in"] = state["tok_out"] = 0+ try:+ task = task_text()+ model = model_name()+ emit(kind="model", model=model, where=("local door, port " + str(urlparse(BASE).port)) if LOCAL else ("cloud " + HOST), local=LOCAL, host=HOST, task=task)+ headers = {"Host": "127.0.0.1:8090"} if LOCAL else None+ limit = {"max_completion_tokens": MAX_TOKENS} if CLOUD else {"max_tokens": MAX_TOKENS}+ temp = {} if CLOUD else {"temperature": 0} # newer cloud models reject temperature and the old limit name+ llm = LLM(model=f"openai/{model}", base_url=BASE, api_key=api_key(), stream=True, extra_headers=headers, **limit, **temp)+ ba = Agent(role="Business Analyst", goal="Turn the task into precise, testable requirements.",+ backstory="You write short numbered requirement lists (8 at most) that name the language and the public API exactly. No code, no preamble.",+ llm=llm, verbose=False, allow_delegation=False)+ arch = Agent(role="Software Architect", goal="Decide the design before any code is written.",+ backstory="You read the requirements and write a short design: the data structure, the invariants, the complexity of each operation, and the two or three traps to avoid. Under 200 words, no code.",+ llm=llm, verbose=False, allow_delegation=False)+ dev = Agent(role="Senior Developer", goal="Implement the design exactly.",+ backstory="You answer with one fenced ```typescript code block only: `export class LruCache<K, V>` with the constructor (capacity, ttlMs), then a short runnable usage example at the end that prints its results. No dependencies. No prose outside the block.",+ llm=llm, verbose=False, allow_delegation=False)+ tester = Agent(role="Strict Tester", goal="Find every requirement the code fails.",+ backstory="You read the task, the requirements, the design and the code. You list each failed requirement on its own line with the line of code at fault, most serious first. If nothing fails you reply exactly: ALL REQUIREMENTS MET. You never rewrite the code. Be brief.",+ llm=llm, verbose=False, allow_delegation=False)+ t1 = Task(description=f"Task from the user:\n{task}\n\nWrite the requirements.", expected_output="A numbered list of at most 8 testable requirements.", agent=ba)+ t2 = Task(description="Write the design for the requirements.", expected_output="A short design note: structure, invariants, complexity, traps.", agent=arch, context=[t1])+ t3 = Task(description="Implement the design and the requirements, exactly. Export the class.", expected_output="One fenced typescript block: `export class LruCache<K, V>` and a runnable usage example.", agent=dev, context=[t1, t2])+ t4 = Task(description=f"The original task:\n{task}\n\nCheck the developer's code against the requirements and the design.", expected_output="Either the failed requirements, one per line, or exactly: ALL REQUIREMENTS MET.", agent=tester, context=[t1, t2, t3])+ crew = Crew(agents=[ba, arch, dev, tester], tasks=[t1, t2, t3, t4], process=Process.sequential, verbose=False)+ result = crew.kickoff()+ dev_out = str(t3.output.raw) if t3.output else ""+ verdict = str(t4.output.raw) if t4.output else str(result)+ lang, code = extract_code(dev_out)+ if code:+ emit(kind="run_start", lang=lang)+ ok, out, passed, total, lines = run_and_judge(lang, code)+ emit(kind="run_done", ok=ok, output=out)+ emit(kind="judge", **{"pass": passed, "total": total, "lines": lines})+ else:+ emit(kind="run_done", ok=None, output="no code block found in the developer's answer")+ emit(kind="judge", **{"pass": 0, "total": 8, "lines": "no code to judge"})+ head = re.sub(r"[^A-Z ]", "", verdict.strip().upper()[:40])+ emit(kind="verdict", text=verdict.strip(), met=head.startswith("ALL REQUIREMENTS MET"))+ except Exception as e:+ emit(kind="error", text=f"{type(e).__name__}: {e}")+ finally:+ state["running"] = False+ emit(kind="end")+++class H(BaseHTTPRequestHandler):+ def log_message(self, *a):+ pass++ def send_json(self, obj, code=200):+ body = json.dumps(obj).encode()+ self.send_response(code); self.send_header("Content-Type", "application/json"); self.send_header("Content-Length", str(len(body))); self.end_headers(); self.wfile.write(body)++ def do_GET(self):+ if self.path == "/":+ body = open(os.path.join(HERE, "crew_app.html"), "rb").read()+ self.send_response(200); self.send_header("Content-Type", "text/html; charset=utf-8"); self.send_header("Content-Length", str(len(body))); self.end_headers(); self.wfile.write(body)+ elif self.path == "/task":+ self.send_json({"task": task_text()})+ elif self.path == "/events":+ self.send_response(200); self.send_header("Content-Type", "text/event-stream"); self.send_header("Cache-Control", "no-cache"); self.end_headers()+ try:+ if state["model"]:+ hello = {"kind": "model", "model": state["model"], "where": ("local door, port " + str(urlparse(BASE).port)) if LOCAL else ("cloud " + HOST), "local": LOCAL, "host": HOST}+ self.wfile.write(("data: " + json.dumps(hello) + "\n\n").encode()); self.wfile.flush()+ while True:+ try:+ ev = events.get(timeout=15)+ self.wfile.write(f"data: {json.dumps(ev)}\n\n".encode()); self.wfile.flush()+ except queue.Empty:+ self.wfile.write(b": keepalive\n\n"); self.wfile.flush()+ except (BrokenPipeError, ConnectionResetError, ConnectionAbortedError):+ return+ else:+ self.send_response(404); self.end_headers()++ def do_POST(self):+ if self.path == "/run":+ if state["running"]:+ self.send_response(409); self.end_headers(); return+ threading.Thread(target=run_crew, daemon=True).start()+ self.send_response(202); self.end_headers()+ else:+ self.send_response(404); self.end_headers()+++if __name__ == "__main__":+ Streamer()+ print(f"Coachwhip Crew on http://127.0.0.1:{PORT}/ ({'CLOUD ' + HOST if CLOUD else 'local door ' + BASE})", flush=True)+ ThreadingHTTPServer(("127.0.0.1", PORT), H).serve_forever()diff --git a/docs/crew/judge_lru.ts b/docs/crew/judge_lru.tsnew file mode 100644index 0000000..f65d07b--- /dev/null+++ b/docs/crew/judge_lru.ts@@ -0,0 +1,37 @@+// The judge: eight executed checks against the developer's LruCache. Same file for every run, no AI.+// The developer's code is written to ./main.ts and must export the class LruCache.+import { LruCache } from "./main";++let pass = 0, fail = 0;+function check(name: string, fn: () => boolean) {+ let ok = false;+ try { ok = fn(); } catch (e) { ok = false; }+ console.log((ok ? "PASS " : "FAIL ") + name);+ ok ? pass++ : fail++;+}+const sleep = (ms: number) => { const t = Date.now(); while (Date.now() - t < ms) {} };++check("capacity < 1 throws RangeError", () => { try { new LruCache<string, number>(0, 1000); return false; } catch (e) { return e instanceof RangeError; } });+check("get returns the value and marks it most recently used", () => {+ const c = new LruCache<string, number>(2, 10000); c.set("a", 1); c.set("b", 2); c.get("a"); c.set("c", 3);+ return c.get("a") === 1 && c.get("b") === undefined && c.get("c") === 3;+});+check("peek does not change recency", () => {+ const c = new LruCache<string, number>(2, 10000); c.set("a", 1); c.set("b", 2); c.peek("a"); c.set("c", 3);+ return c.get("a") === undefined && c.get("b") === 2;+});+check("has() is true for a stored undefined", () => { const c = new LruCache<string, number | undefined>(2, 10000); c.set("u", undefined); return c.has("u") === true; });+check("has() is false for a missing key", () => { const c = new LruCache<string, number>(2, 10000); return c.has("nope") === false; });+check("set on an existing key resets expiry and recency", () => {+ const c = new LruCache<string, number>(2, 60); c.set("a", 1); c.set("b", 2); sleep(40); c.set("a", 9); sleep(40);+ return c.get("a") === 9 && c.has("b") === false;+});+check("expired entry is gone, lazily, no timers", () => {+ const c = new LruCache<string, number>(2, 30); c.set("a", 1); sleep(50);+ return c.has("a") === false && c.get("a") === undefined;+});+check("get does NOT extend expiry", () => {+ const c = new LruCache<string, number>(2, 60); c.set("a", 1); sleep(40); c.get("a"); sleep(40);+ return c.has("a") === false;+});+console.log(`SCORE ${pass}/${pass + fail}`);diff --git a/docs/crew/record_app.py b/docs/crew/record_app.pynew file mode 100644index 0000000..7ea8fda--- /dev/null+++ b/docs/crew/record_app.py@@ -0,0 +1,37 @@+# Records the Coachwhip Crew app (crew_app.py on 127.0.0.1:8071) running one task, real time, 1280x720,+# and writes an MP4 next to this file. Run crew_app.py first. No speed-up: one video second is one real second.+import asyncio, os, glob, time, subprocess, sys+sys.stdout.reconfigure(encoding="utf-8", errors="replace")+from playwright.async_api import async_playwright+import imageio_ffmpeg++OUT = os.path.dirname(os.path.abspath(__file__))+URL = os.environ.get("CREW_URL", "http://127.0.0.1:8071/")+NAME = os.environ.get("CREW_VIDEO", "coachwhip-crew-app")++async def main():+ async with async_playwright() as p:+ browser = await p.chromium.launch()+ ctx = await browser.new_context(viewport={"width": 1280, "height": 720}, color_scheme="dark",+ record_video_dir=OUT, record_video_size={"width": 1280, "height": 720})+ page = await ctx.new_page()+ await page.goto(URL)+ await page.wait_for_timeout(1500)+ t0 = time.time()+ await page.click("#go")+ await page.wait_for_function("document.querySelector('#go') && !document.querySelector('#go').disabled", timeout=1200000)+ print(f"run finished after {time.time() - t0:.0f} s")+ await page.wait_for_timeout(4000)+ await page.screenshot(path=os.path.join(OUT, NAME + "-last.png"))+ verdict = await page.evaluate("document.querySelector('#verdict').innerText")+ runner = await page.evaluate("document.querySelector('#st-run').innerText")+ print("verdict:", verdict[:120]); print("runner:", runner)+ await ctx.close(); await browser.close()+ vids = sorted(glob.glob(os.path.join(OUT, "*.webm")), key=os.path.getmtime)+ webm = vids[-1]+ ff = imageio_ffmpeg.get_ffmpeg_exe()+ mp4 = os.path.join(OUT, NAME + ".mp4")+ subprocess.run([ff, "-y", "-loglevel", "error", "-i", webm, "-c:v", "libx264", "-preset", "medium", "-crf", "20", "-pix_fmt", "yuv420p", "-r", "30", mp4], check=True)+ print("mp4:", mp4, os.path.getsize(mp4) // 1024, "KB")++asyncio.run(main())diff --git a/docs/crew/task_lru.txt b/docs/crew/task_lru.txtnew file mode 100644index 0000000..3e9af30--- /dev/null+++ b/docs/crew/task_lru.txt@@ -0,0 +1 @@+Write a TypeScript class LruCache<K, V> with a maximum capacity and a per-entry time-to-live in milliseconds. Requirements, all of them matter: get(key) returns the value and marks the entry most recently used but must NOT extend its expiry; peek(key) returns the value without changing recency; set(key, value, ttlMs?) on an existing key replaces the value, resets its expiry and makes it most recently used, with ttlMs defaulting to the cache-wide default; has(key) must return true for a live entry whose stored value is undefined and false for a missing or expired key; no timers of any kind, expiry is checked lazily on access; when the cache is full and a new key is inserted, evict expired entries first and only if none are expired evict the least recently used; the constructor must throw a RangeError if capacity is less than 1; all operations O(1) on average using Map insertion order for recency. Export the class. Include a short usage example that prints results for get, peek and has.diff --git a/docs/releases/0.5.2.md b/docs/releases/0.5.2.mdnew file mode 100644index 0000000..186164a--- /dev/null+++ b/docs/releases/0.5.2.md@@ -0,0 +1,19 @@+# Coachwhip 0.5.2++Mac mini M4, 16 GB, measured; your Mac and your prompt will move the numbers.++## Faster on every Qwen3-Next and Qwen3.5/3.6 MoE model++- **The attention block of a linear-attention layer is now one kernel per word.** Three layers in four of these models use gated delta-net attention, and it was built from about forty small GPU operations per layer: the convolution taps, the activation, two norms, the widening, the delta rule over the memory, the output norm and the gate. They are now one Metal kernel per word; the two projections stay as their own matmul kernels. The arithmetic is the same: on the exact path the answers are byte-identical to 0.5.0.+- **Measured, fast mode, raw 300 tokens:** Qwen3.6-35B-A3B squeezed (bank 68) 14.0 → 16.4 tok/s; Qwen3-Coder-Next squeezed (bank 109) 11.9 → 14.3 tok/s. In the crew demo (four agents, a cache with eight executed checks) every seat on the 35B wrote at 16.4 to 17.0 tok/s.+- `COACHWHIP_ATTN_KERNEL=0` restores the old operation-by-operation path.++## Where the time went, for the curious++On a 16 GB Mac the SSD stopped being the clock once experts were squeezed and stood in: a 35B word cost about 60 ms, only 10 of them in the expert layers. The rest was the attention side, and the delta step alone was 13 ms of it. The kernel takes most of that back.++## Not tested++- Macs other than an M4 with 16 GB.+- gpt-oss-120b is unaffected (a different attention); its numbers are 0.5.0's.+- Prompts past 16K tokens.