diff --git a/bin/free-agent b/bin/free-agent index 59a5ae5..1d930aa 100755 --- a/bin/free-agent +++ b/bin/free-agent @@ -158,44 +158,69 @@ for (let n = 0; n < Math.max(1, opts.attempts); n++) { saveBudget(b); const started = Date.now(); - if (!opts.quiet) console.log(`[free-agent] ${runId}: trying ${model.id} (attempt ${n + 1})`); - appendFileSync(logPath, `\n=== ${new Date().toISOString()} ${model.id} ===\n`); + const modelAttempts = []; + for (let r = 1; r <= 3; r++) { + if (!opts.quiet) console.log(`[free-agent] ${runId}: trying ${model.id} (attempt ${n + 1}.${r})`); + appendFileSync(logPath, `\n=== ${new Date().toISOString()} ${model.id} ===\n`); - const proc = Bun.spawn({ - cmd: [ - "pi", "-p", - "--model", model.id, - "--no-session", - "--append-system-prompt", workerProtocol, - prompt, - ], - cwd: workDir, - stdout: "pipe", - stderr: "pipe", - env: { ...process.env }, - }); + const proc = Bun.spawn({ + cmd: [ + "pi", "-p", + "--model", model.id, + "--no-session", + "--append-system-prompt", workerProtocol, + prompt, + ], + cwd: workDir, + stdout: "pipe", + stderr: "pipe", + env: { ...process.env }, + }); - let out = ""; - const timer = setTimeout(() => { try { proc.kill(); } catch {} }, opts.timeout * 1000); - const pump = async (stream) => { - const dec = new TextDecoder(); - for await (const chunk of stream) { - const s = dec.decode(chunk); - out += s; - appendFileSync(logPath, s); - if (!opts.quiet) process.stdout.write(s); + let out = ""; + const timer = setTimeout(() => { try { proc.kill(); } catch {} }, opts.timeout * 1000); + const pump = async (stream) => { + const dec = new TextDecoder(); + for await (const chunk of stream) { + const s = dec.decode(chunk); + out += s; + appendFileSync(logPath, s); + if (!opts.quiet) process.stdout.write(s); + } + }; + await Promise.all([pump(proc.stdout), pump(proc.stderr)]); + const code = await proc.exited; + clearTimeout(timer); + const secs = ((Date.now() - started) / 1000).toFixed(0); + + const rateLimited = /429|rate.?limit|quota|RESOURCE_EXHAUSTED|insufficient|overloaded|no capacity|too many requests/i.test(out); + const finished = /HANDOFF-DONE/.test(out); + const ok = code === 0 && finished; + modelAttempts.push({ exit: code, secs: Number(secs), rateLimited, ok }); + + // A free tier that says "retry in 41s" is a wait, not a dead model: sleep the + // delay it asks for and try the same model again before spending another lane. + if (rateLimited && !ok && r < 3) { + const m = + out.match(/retry in ([\d.]+)\s*s/i) || + out.match(/"retryDelay":\s*"(\d+)s"/) || + out.match(/try again in ([\d.]+)\s*s/i) || + out.match(/retry after:?\s*(\d+)/i); + const wait = Math.min(120, Math.ceil(Number(m ? m[1] : 45)) + 2); + if (!opts.quiet) console.log(`\n[free-agent] ${model.id}: rate limited, waiting ${wait}s (retry ${r}/3)`); + await Bun.sleep(wait * 1000); + continue; } - }; - await Promise.all([pump(proc.stdout), pump(proc.stderr)]); - const code = await proc.exited; - clearTimeout(timer); + if (ok) break; + if (!rateLimited) break; + } + const secs = ((Date.now() - started) / 1000).toFixed(0); + const last = modelAttempts[modelAttempts.length - 1] || {}; + const rateLimited = !!last.rateLimited; + const ok = !!last.ok; - const rateLimited = /429|rate.?limit|quota|insufficient|overloaded|no capacity|too many requests/i.test(out); - const finished = /HANDOFF-DONE/.test(out); - const ok = code === 0 && finished; - - attempts.push({ model: model.id, exit: code, secs: Number(secs), rateLimited, ok }); + attempts.push({ model: model.id, exit: last.exit, secs: Number(secs), rateLimited, ok, tries: modelAttempts.length }); if (rateLimited) { const bb = loadBudget(); diff --git a/config/free-agent/pool.json b/config/free-agent/pool.json index b15ffa6..252fce8 100644 --- a/config/free-agent/pool.json +++ b/config/free-agent/pool.json @@ -3,63 +3,91 @@ "models": [ { "id": "google/gemini-3.5-flash", - "roles": ["code", "review", "infra"], - "rpm": 8, + "roles": [ + "code", + "review", + "infra" + ], + "rpm": 4, "rpd": 200, "note": "Free tier workhorse: 1M context, strong tool use, per-project limits shown in AI Studio." }, { "id": "zai/glm-4.5-flash", - "roles": ["code", "infra"], + "roles": [ + "code", + "infra" + ], "rpm": 10, "rpd": 200, "note": "Permanent $0 Flash model on Z.ai; fastest of the four in practice." }, { "id": "groq/openai/gpt-oss-120b", - "roles": ["code", "review", "infra"], + "roles": [ + "code", + "review", + "infra" + ], "rpm": 28, "rpd": 900, "note": "Groq LPU, very fast, 131K context. Free tier is token-per-minute tight (~6-8K TPM), so keep briefs short." }, { "id": "openrouter/minimax/minimax-m3.1-flash:free", - "roles": ["code", "review", "infra"], + "roles": [ + "code", + "review", + "infra" + ], "rpm": 18, "rpd": 45, "note": "OpenRouter :free, 1M context, vision. 50 req/day cap (45 here for headroom)." }, { "id": "google/gemini-3.1-flash-lite", - "roles": ["code", "review"], - "rpm": 12, + "roles": [ + "code", + "review" + ], + "rpm": 4, "rpd": 800, "note": "Cheap second Gemini lane for small edits and reviews." }, { "id": "openrouter/nvidia/nemotron-3-super-120b-a12b:free", - "roles": ["code", "review"], + "roles": [ + "code", + "review" + ], "rpm": 18, "rpd": 45, "note": "OpenRouter :free alternative when minimax is busy." }, { "id": "openrouter/cohere/north-mini-code:free", - "roles": ["code"], + "roles": [ + "code" + ], "rpm": 18, "rpd": 45, "note": "Code-tuned free lane through OpenRouter." }, { "id": "groq/qwen/qwen3.8-27b", - "roles": ["code"], + "roles": [ + "code" + ], "rpm": 28, "rpd": 900, "note": "Groq fallback, small max output (16K)." }, { "id": "cohere/north-mini-code-1.0", - "roles": ["code", "review"], + "roles": [ + "code", + "review" + ], "rpm": 18, "rpd": 30, "note": "Existing Cohere trial key: 1000 calls/month, so ~30/day." diff --git a/config/free-pi/models.json b/config/free-pi/models.json index 42e868a..3010219 100644 --- a/config/free-pi/models.json +++ b/config/free-pi/models.json @@ -141,7 +141,49 @@ "apiKey": "!secretctl get OPENROUTER_API_KEY -- sh -c 'printf %s \"$OPENROUTER_API_KEY\"'" }, "zai": { - "apiKey": "!secretctl get ZAI_API_KEY -- sh -c 'printf %s \"$ZAI_API_KEY\"'" + "apiKey": "!secretctl get ZAI_API_KEY -- sh -c 'printf %s \"$ZAI_API_KEY\"'", + "models": [ + { + "id": "glm-4.5-flash", + "name": "GLM-4.5 Flash (free)", + "contextWindow": 128000, + "maxTokens": 32768, + "reasoning": false, + "input": [ + "text" + ], + "samplingParams": { + "temperature": 0.3 + } + }, + { + "id": "glm-4.7-flash", + "name": "GLM-4.7 Flash (free)", + "contextWindow": 128000, + "maxTokens": 32768, + "reasoning": false, + "input": [ + "text" + ], + "samplingParams": { + "temperature": 0.3 + } + }, + { + "id": "glm-4.6v-flash", + "name": "GLM-4.6V Flash (free, vision)", + "contextWindow": 128000, + "maxTokens": 32768, + "reasoning": false, + "input": [ + "text", + "image" + ], + "samplingParams": { + "temperature": 0.3 + } + } + ] } } } diff --git a/config/pi/models.json b/config/pi/models.json index 00ef18b..b392df3 100644 --- a/config/pi/models.json +++ b/config/pi/models.json @@ -167,7 +167,49 @@ "apiKey": "!secretctl get OPENROUTER_API_KEY -- sh -c 'printf %s \"$OPENROUTER_API_KEY\"'" }, "zai": { - "apiKey": "!secretctl get ZAI_API_KEY -- sh -c 'printf %s \"$ZAI_API_KEY\"'" + "apiKey": "!secretctl get ZAI_API_KEY -- sh -c 'printf %s \"$ZAI_API_KEY\"'", + "models": [ + { + "id": "glm-4.5-flash", + "name": "GLM-4.5 Flash (free)", + "contextWindow": 128000, + "maxTokens": 32768, + "reasoning": false, + "input": [ + "text" + ], + "samplingParams": { + "temperature": 0.3 + } + }, + { + "id": "glm-4.7-flash", + "name": "GLM-4.7 Flash (free)", + "contextWindow": 128000, + "maxTokens": 32768, + "reasoning": false, + "input": [ + "text" + ], + "samplingParams": { + "temperature": 0.3 + } + }, + { + "id": "glm-4.6v-flash", + "name": "GLM-4.6V Flash (free, vision)", + "contextWindow": 128000, + "maxTokens": 32768, + "reasoning": false, + "input": [ + "text", + "image" + ], + "samplingParams": { + "temperature": 0.3 + } + } + ] } } } diff --git a/config/skills/cli/handoff/SKILL.md b/config/skills/cli/handoff/SKILL.md new file mode 100644 index 0000000..9143504 --- /dev/null +++ b/config/skills/cli/handoff/SKILL.md @@ -0,0 +1,81 @@ +--- +name: handoff +description: Delegate a chunk of work to free models (Gemini Flash, GLM Flash, Groq, OpenRouter :free, Cohere) through a tmux worker queue, then review and correct what they produce. Use when a task is well-specified enough for a cheaper model to attempt it and you want to keep the expensive model for review. +--- + +# Handoff to free-model workers + +A worker is a `pi` session on a free model, given a brief, in its own tmux window. +It writes `HANDOFF-REPORT.md` and stops. You review the diff and fix what it missed. + +Pool, limits and budgets: `~/.config/free-agent/pool.json` (linked from +`dotfiles/config/free-agent/pool.json`). Today's usage: `free-agent --list`. + +## Write a brief that a weaker model can actually follow + +``` +# + +Repository: + +1. +2. + +Files: +Do not touch: + +Acceptance: +``` + +Rules that make the difference: absolute paths, numbered concrete changes, one +acceptance command, an explicit "do not touch" list, and no open questions. + +## Delegate + +```sh +handoff submit BRIEF.md --dir ~/Projects/thing --role code --id fix-tests +``` + +`--role code` implements, `review` critiques a diff or design, `infra` writes +config/runbooks. The daemon (systemd user unit `handoff.service`, tmux session +`handoff`) picks it up within 5 s and runs it in a new window. + +```sh +handoff list # queue / running / done / failed +handoff log fix-tests 60 # last 60 lines of the worker's transcript +handoff attach # watch the tmux session live +handoff pause | resume # stop taking new work +handoff kill fix-tests +``` + +Run one directly, without the queue (useful while iterating on a brief): + +```sh +free-agent --brief BRIEF.md --dir ~/Projects/thing --role code --dry-run # which model +free-agent --brief BRIEF.md --dir ~/Projects/thing --role code # run it +free-agent --list # budgets +``` + +## Review — always + +```sh +handoff review fix-tests +``` + +That prints the status, the report, `git status --short` and `git diff --stat`. +Then, yourself: + +1. `git -C diff` — read every hunk. Workers hallucinate plausible edits. +2. Run the acceptance command, plus the project's own tests. +3. Fix, or submit a follow-up brief naming exactly what was wrong. +4. Commit yourself. Workers never commit. + +## Budgets and rate limits + +`free-agent` records one request per attempt in +`~/.local/state/free-agent/budget.json`, enforces each model's rpm/rpd from the +pool, marks a model dead for the day on a hard quota error, and on a "retry in +Ns" reply it sleeps the delay and retries the same model before spending another +lane. Free tiers are small: Gemini Flash is ~5 requests/minute, which a tool +loop can burn in one turn — expect waits, keep briefs short, and prefer +`--role code` tasks with few steps. diff --git a/home/agents.nix b/home/agents.nix index 175a32f..d5140fb 100644 --- a/home/agents.nix +++ b/home/agents.nix @@ -10,7 +10,7 @@ let "git" "gt" "mise-cli" "secrets_man" "searxng" "playwright-cli" "context-discipline" "homelab-policies" "memory-layer" ]; - cliSkills = [ "infra-change" "wiki-update" "wiki-view" "lapis-memory" ]; + cliSkills = [ "infra-change" "wiki-update" "wiki-view" "lapis-memory" "handoff" ]; allSkills = sharedSkills ++ cliSkills; skillSet = dir: names: lib.listToAttrs (map (n: lib.nameValuePair "${dir}/${n}" { source = link "config/skills/${n}";