diff --git a/bin/free-agent b/bin/free-agent new file mode 100755 index 0000000..59a5ae5 --- /dev/null +++ b/bin/free-agent @@ -0,0 +1,219 @@ +#!/usr/bin/env bun +// free-agent — run one task brief through a pool of free models, with local +// rate-limit accounting and automatic failover. +// +// free-agent --brief BRIEF.md --dir ~/Projects/thing --role code [--id slug] +// free-agent --list # pool + today's budget +// free-agent --dry-run ... # show the model it would pick +// +// Exit: 0 done, 1 all attempts failed, 2 usage, 3 no model has budget today. + +import { existsSync, mkdirSync, readFileSync, writeFileSync, appendFileSync, copyFileSync } from "node:fs"; +import { dirname, join, resolve, basename } from "node:path"; +import { homedir } from "node:os"; + +const HOME = homedir(); +const DOTFILES = process.env.DOTFILES_DIR || join(HOME, ".dotfiles"); +const POOL = process.env.FREE_AGENT_POOL || join(DOTFILES, "config/free-agent/pool.json"); +const WORKER = join(DOTFILES, "config/free-agent/WORKER.md"); +const STATE = join(process.env.XDG_STATE_HOME || join(HOME, ".local/state"), "free-agent"); +const BUDGET = join(STATE, "budget.json"); +const RUNS = join(STATE, "runs"); + +// ---------- args ---------- +const opts = { brief: "", dir: "", role: "code", id: "", model: "", timeout: 1800, attempts: 3, dryRun: false, list: false, quiet: false }; +const argv = process.argv.slice(2); +for (let i = 0; i < argv.length; i++) { + const a = argv[i]; + if (a === "--list") opts.list = true; + else if (a === "--dry-run") opts.dryRun = true; + else if (a === "--quiet") opts.quiet = true; + else if (a === "-h" || a === "--help") { + console.log(`free-agent — hand a brief to a free model + + --brief task brief (required unless --list) + --dir working directory for the worker (default: brief's folder) + --role code | review | infra (default code) + --id run id (default: derived from the brief file name + time) + --model

force one model instead of the pool + --timeout per attempt (default 1800) + --attempts how many pool models to try (default 3) + --dry-run print the chosen model and exit + --list print pool and today's usage`); + process.exit(0); + } else if (a.startsWith("--")) { + const v = argv[++i]; + if (a === "--brief") opts.brief = v; + else if (a === "--dir") opts.dir = v; + else if (a === "--role") opts.role = v; + else if (a === "--id") opts.id = v; + else if (a === "--model") opts.model = v; + else if (a === "--timeout") opts.timeout = Number(v); + else if (a === "--attempts") opts.attempts = Number(v); + else { console.error(`free-agent: unknown option ${a}`); process.exit(2); } + } +} + +// ---------- budget ---------- +const today = new Date().toISOString().slice(0, 10); +function loadBudget() { + let b = { date: today, models: {} }; + if (existsSync(BUDGET)) { + try { b = JSON.parse(readFileSync(BUDGET, "utf8")); } catch {} + } + if (b.date !== today) b = { date: today, models: {} }; + return b; +} +function saveBudget(b) { + mkdirSync(dirname(BUDGET), { recursive: true }); + writeFileSync(BUDGET, JSON.stringify(b, null, 1)); +} +function usageOf(b, id) { + const e = b.models[id] || { day: 0, minute: [] }; + const now = Date.now(); + const minute = (e.minute || []).filter((ts) => now - ts < 60_000); + return { day: e.day || 0, minute, exhausted: !!e.exhausted }; +} +function record(b, id) { + const u = usageOf(b, id); + u.minute.push(Date.now()); + b.models[id] = { day: u.day + 1, minute: u.minute.slice(-60), exhausted: b.models[id]?.exhausted || false }; +} +function markExhausted(b, id) { + const u = usageOf(b, id); + b.models[id] = { day: u.day, minute: u.minute, exhausted: true }; +} + +const pool = JSON.parse(readFileSync(POOL, "utf8")).models; + +function pick(role, skip) { + const b = loadBudget(); + for (const m of pool) { + if (skip.has(m.id)) continue; + if (!(m.roles || []).includes(role)) continue; + const u = usageOf(b, m.id); + if (u.exhausted) continue; + if (u.day >= m.rpd) continue; + if (u.minute.length >= m.rpm) continue; + return m; + } + return null; +} + +if (opts.list) { + const b = loadBudget(); + const c = loadBudget(); + for (const m of pool) { + const u = loadBudget() && usageOf(b, m.id); + console.log( + `${m.id.padEnd(48)} ${String(u.day).padStart(4)}/${String(m.rpd).padEnd(5)} ${u.exhausted ? "EXHAUSTED" : ""} ${m.roles.join(",")}` + ); + } + console.log(`\nbudget file: ${BUDGET} (${c.date})`); + process.exit(0); +} + +if (!opts.brief) { console.error("free-agent: --brief is required (or --list)"); process.exit(2); } +const briefPath = resolve(opts.brief); +if (!existsSync(briefPath)) { console.error(`free-agent: no such brief ${briefPath}`); process.exit(2); } +const workDir = resolve(opts.dir || dirname(briefPath)); +if (!existsSync(workDir)) { console.error(`free-agent: no such dir ${workDir}`); process.exit(2); } + +// ---------- run dir ---------- +const slug = (s) => s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 40); +const runId = opts.id || `${slug(basename(briefPath, ".md"))}-${new Date().toISOString().replace(/[-:T]/g, "").slice(4, 14)}`; +const runDir = join(RUNS, runId); +mkdirSync(runDir, { recursive: true }); +copyFileSync(briefPath, join(runDir, "BRIEF.md")); +const logPath = join(runDir, "run.log"); +const statusPath = join(runDir, "status.json"); + +const writeStatus = (o) => writeFileSync(statusPath, JSON.stringify({ id: runId, dir: workDir, role: opts.role, ...o }, null, 1)); + +// ---------- attempts ---------- +const skip = new Set(); +if (opts.model) skip.clear(); +const workerProtocol = readFileSync(WORKER, "utf8"); +const prompt = [ + `Read the brief at ${join(runDir, "BRIEF.md")} and complete it.`, + `Work inside ${workDir}.`, + `Write your report to ${join(runDir, "HANDOFF-REPORT.md")}.`, +].join("\n"); + +writeStatus({ state: "running", startedAt: new Date().toISOString(), attempts: [] }); +const attempts = []; + +for (let n = 0; n < Math.max(1, opts.attempts); n++) { + let model; + if (opts.model) { + model = pool.find((m) => m.id === opts.model) || { id: opts.model, roles: [opts.role], rpd: 1e9, rpm: 1e9 }; + } else { + model = pick(opts.role, skip); + if (!model) break; + } + skip.add(model.id); + + const b = loadBudget(); + record(b, model.id); + 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 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); + } + }; + 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|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 }); + + if (rateLimited) { + const bb = loadBudget(); + markExhausted(bb, model.id); + saveBudget(bb); + if (!opts.quiet) console.log(`\n[free-agent] ${model.id}: rate limited — parked for today, trying next`); + continue; + } + if (ok) { + writeStatus({ state: "done", endedAt: new Date().toISOString(), model: model.id, secs: Number(secs), attempts, report: join(runDir, "HANDOFF-REPORT.md") }); + if (!opts.quiet) console.log(`\n[free-agent] ${runId}: done with ${model.id} in ${secs}s`); + console.log(runDir); + process.exit(0); + } + if (!opts.quiet) console.log(`\n[free-agent] ${model.id}: exit ${code}, no HANDOFF-DONE — next model`); +} + +const state = attempts.length === 0 ? "no-capacity" : "failed"; +writeStatus({ state, endedAt: new Date().toISOString(), attempts }); +if (!opts.quiet) console.error(`[free-agent] ${runId}: ${state}`); +process.exit(attempts.length === 0 ? 3 : 1); diff --git a/bin/handoff b/bin/handoff new file mode 100755 index 0000000..495c6fe --- /dev/null +++ b/bin/handoff @@ -0,0 +1,198 @@ +#!/usr/bin/env bash +# handoff — queue task briefs for free-model workers, run them in tmux, and +# hand the result back for review by the primary agent. +# +# handoff submit BRIEF.md --dir ~/Projects/thing --role code +# echo "..." | handoff submit - --dir . --id fix-tests +# handoff list | status ID | log ID | review ID | kill ID | attach | clean +# handoff daemon # queue watcher (systemd user service runs this) +# +# State: ~/.local/share/handoff/{queue,running,done,failed}/ID.json +# Worker logs: ~/.local/state/free-agent/runs/ID/{run.log,HANDOFF-REPORT.md,status.json} + +set -uo pipefail + +HOME_DIR="${HOME}" +DATA="${XDG_DATA_HOME:-$HOME_DIR/.local/share}/handoff" +STATE="${XDG_STATE_HOME:-$HOME_DIR/.local/state}/free-agent/runs" +QUEUE="$DATA/queue"; RUNNING="$DATA/running"; DONE="$DATA/done"; FAILED="$DATA/failed" +TMUX_SESSION="${HANDOFF_TMUX:-handoff}" +MAX_PARALLEL="${HANDOFF_MAX_PARALLEL:-2}" +mkdir -p "$QUEUE" "$RUNNING" "$DONE" "$FAILED" + +die() { printf 'handoff: %s\n' "$*" >&2; exit 1; } +now() { date -u +%Y-%m-%dT%H:%M:%SZ; } + +slugify() { printf '%s' "$1" | tr '[:upper:]' '[:lower:]' | sed -E 's/[^a-z0-9]+/-/g; s/^-+|-+$//g' | cut -c1-40; } + +usage() { + sed -n '2,14p' "$0" | sed 's/^# \{0,1\}//' + cat <<'EOF' + +Roles: code (implement), review (critique a diff/design), infra (config/runbooks). +Brief format: what to change, which files, acceptance command, what not to touch. +EOF +} + +need_id() { [ -n "${1:-}" ] || die "missing run id"; } +task_file() { local id="$1" d; for d in "$RUNNING" "$QUEUE" "$DONE" "$FAILED"; do [ -f "$d/$id.json" ] && { printf '%s' "$d/$id.json"; return 0; }; done; return 1; } + +cmd_submit() { + local brief="" dir="" role="code" id="" + while [ $# -gt 0 ]; do + case "$1" in + --dir) dir="${2:-}"; shift 2 ;; + --role) role="${2:-code}"; shift 2 ;; + --id) id="${2:-}"; shift 2 ;; + -h|--help) usage; exit 0 ;; + -) brief="STDIN"; shift ;; + *) brief="$1"; shift ;; + esac + done + [ -n "$brief" ] || die "give a brief file, or - to read stdin" + [ -n "$dir" ] || dir="$(pwd)" + [ -d "$dir" ] || die "no such dir: $dir" + dir="$(cd "$dir" && pwd)" + + local body + if [ "$brief" = "STDIN" ]; then body="$(cat)"; else [ -f "$brief" ] || die "no such brief: $brief"; body="$(cat "$brief")"; fi + [ -n "$body" ] || die "brief is empty" + + [ -n "$id" ] || id="$(slugify "$(head -c 60 <<<"$body" | tr '\n' ' ')")-$(date +%H%M%S)" + local bpath="$DATA/$id.brief.md" + printf '%s\n' "$body" > "$bpath" + + python3 - "$QUEUE/$id.json" "$id" "$dir" "$role" "$bpath" <<'PY' +import json, sys, datetime +path, rid, d, role, brief = sys.argv[1:6] +json.dump({"id": rid, "dir": d, "role": role, "brief": brief, "queuedAt": datetime.datetime.utcnow().isoformat()+"Z"}, open(path, "w"), indent=1) +PY + printf 'queued %s\n dir: %s\n role: %s\n log: %s/%s/run.log\n' "$id" "$dir" "$role" "$STATE" "$id" + echo " start the daemon if it is not running: handoff daemon &" +} + +ensure_session() { + tmux has-session -t "$TMUX_SESSION" 2>/dev/null && return 0 + tmux new-session -d -s "$TMUX_SESSION" -n workers -c "$HOME_DIR" + tmux set-option -t "$TMUX_SESSION" history-limit 20000 >/dev/null 2>&1 +} + +running_count() { find "$RUNNING" -maxdepth 1 -name '*.json' | wc -l | tr -d ' '; } + +start_task() { + local f="$1" id dir role brief + id="$(python3 -c 'import json,sys;print(json.load(open(sys.argv[1]))["id"])' "$f")" + dir="$(python3 -c 'import json,sys;print(json.load(open(sys.argv[1]))["dir"])' "$f")" + role="$(python3 -c 'import json,sys;d=json.load(open(sys.argv[1]));print(d.get("role","code"))' "$f")" + brief="$(python3 -c 'import json,sys;print(json.load(open(sys.argv[1]))["brief"])' "$f")" + + mv "$f" "$RUNNING/$id.json" 2>/dev/null || return 0 + ensure_session + tmux new-window -d -t "$TMUX_SESSION" -n "$id" -c "$dir" \ + "free-agent --brief $(printf '%q' "$brief") --dir $(printf '%q' "$dir") --role $(printf '%q' "$role") --id $(printf '%q' "$id"); printf '\nhandoff window finished: %s\n' \$?; sleep 2" \ + >/dev/null 2>&1 || { echo "handoff: tmux failed for $id" >&2; mv "$RUNNING/$id.json" "$FAILED/$id.json"; return 1; } + echo "[$(now)] started $id ($role) in $dir" +} + +collect_finished() { + local f id st + for f in "$RUNNING"/*.json; do + [ -e "$f" ] || continue + id="$(basename "$f" .json)" + st="$STATE/$id/status.json" + [ -f "$st" ] || continue + local state + state="$(python3 -c 'import json,sys;print(json.load(open(sys.argv[1])).get("state","?"))' "$st" 2>/dev/null)" + case "$state" in + done) mv "$f" "$DONE/$id.json"; echo "[$(now)] done $id -> $(dirname "$st")/HANDOFF-REPORT.md" ;; + failed|no-capacity) mv "$f" "$FAILED/$id.json"; echo "[$(now)] $state $id" ;; + esac + if [ -n "${state:-}" ] && [ "$state" != "running" ]; then + tmux list-windows -t "$TMUX_SESSION" -F '#{window_name}' 2>/dev/null | grep -qx "$id" && tmux kill-window -t "$TMUX_SESSION:$id" 2>/dev/null + fi + done +} + +cmd_daemon() { + ensure_session + echo "[$(now)] handoff daemon: queue=$QUEUE parallel=$MAX_PARALLEL session=$TMUX_SESSION" + local unpaused="$DATA/pause" + trap 'echo "[$(now)] handoff daemon: stopping"; exit 0' INT TERM + while :; do + if [ ! -f "$unpaused" ]; then + collect_finished + for f in "$QUEUE"/*.json; do + [ -e "$f" ] || continue + [ "$(running_count)" -lt "$MAX_PARALLEL" ] || break + start_task "$f" + done + fi + sleep 5 + done +} + +cmd_list() { + local d id st + for d in queue running done failed; do + for f in "$DATA/$d"/*.json; do + [ -e "$f" ] || continue + id="$(basename "$f" .json)" + st="$STATE/$id/status.json" + local model="-" + [ -f "$st" ] && model="$(python3 -c 'import json,sys;d=json.load(open(sys.argv[1]));print(d.get("model") or d.get("state","-"))' "$st" 2>/dev/null)" + printf '%-8s %-28s %-34s %s\n' "$d" "$id" "$model" "$(dirname "$st")" + done + done +} + +cmd_status() { need_id "${1:-}"; local id="$1" f; f="$(task_file "$id")" || die "unknown id $id"; echo "task: $f"; cat "$f"; echo; [ -f "$STATE/$id/status.json" ] && cat "$STATE/$id/status.json"; } + +cmd_log() { need_id "${1:-}"; local id="$1" n="${2:-120}"; tail -n "$n" "$STATE/$id/run.log" 2>/dev/null || die "no log for $id"; } + +cmd_review() { + need_id "${1:-}"; local id="$1" + local dir=""; [ -f "$DATA/done/$id.json" ] && dir="$(python3 -c 'import json,sys;print(json.load(open(sys.argv[1]))["dir"])' "$DATA/done/$id.json")" + [ -n "$dir" ] || [ -f "$DATA/running/$id.json" ] && dir="$(python3 -c 'import json,sys;print(json.load(open(sys.argv[1]))["dir"])' "$DATA/running/$id.json" 2>/dev/null)" + echo "== status =="; cat "$STATE/$id/status.json" 2>/dev/null || echo "(no status yet)" + echo; echo "== report =="; cat "$STATE/$id/HANDOFF-REPORT.md" 2>/dev/null || echo "(no report written)" + if [ -n "$dir" ] && [ -d "$dir/.git" ]; then + echo; echo "== working tree =="; git -C "$dir" status --short | head -40 + echo; echo "== diffstat =="; git -C "$dir" diff --stat | tail -20 + echo; echo "review with: git -C $dir diff (or 'git add -p' to stage selectively)" + fi +} + +cmd_kill() { + need_id "${1:-}"; local id="$1" + tmux kill-window -t "$TMUX_SESSION:$id" 2>/dev/null && echo "killed window $id" || echo "no tmux window $id" + pkill -f "free-agent --brief .*--id $id" 2>/dev/null && echo "stopped worker" || true + for d in queue running; do [ -f "$DATA/$d/$id.json" ] && mv "$DATA/$d/$id.json" "$FAILED/$id.json" && echo "moved task to failed/"; done +} + +cmd_pause() { touch "$DATA/pause"; echo "daemon paused (existing runs continue)"; } +cmd_resume() { rm -f "$DATA/pause"; echo "daemon resumed"; } + +cmd_clean() { + local days="${1:-7}" + find "$DATA/done" "$DATA/failed" -name '*.json' -mtime +"$days" -delete 2>/dev/null + find "$STATE" -maxdepth 1 -type d -mtime +"$days" -name '*-*' -exec rm -rf {} + 2>/dev/null + echo "removed runs older than $days days" +} + +cmd_attach() { ensure_session; exec tmux attach -t "$TMUX_SESSION"; } + +case "${1:-}" in + submit) shift; cmd_submit "$@" ;; + daemon) cmd_daemon ;; + list|ls) cmd_list ;; + status) shift; cmd_status "$@" ;; + log|tail) shift; cmd_log "$@" ;; + review) shift; cmd_review "$@" ;; + kill) shift; cmd_kill "$@" ;; + attach) cmd_attach ;; + pause) cmd_pause ;; + resume) cmd_resume ;; + clean) shift; cmd_clean "$@" ;; + -h|--help|help|"") usage ;; + *) usage; exit 2 ;; +esac diff --git a/config/free-agent/WORKER.md b/config/free-agent/WORKER.md new file mode 100644 index 0000000..7dd7d95 --- /dev/null +++ b/config/free-agent/WORKER.md @@ -0,0 +1,40 @@ +# Worker protocol + +You are a **worker agent** in a handoff pipeline. A stronger model wrote the brief +you were given; it will review your work afterwards. Optimise for a clean, reviewable +diff — not for finishing fast. + +## Rules + +1. Read the brief first (`BRIEF.md` in the run directory). If it names files, read them + before editing. If it names an acceptance command, run it. +2. Stay inside the repository named in the brief. Never touch anything outside it, + never change credentials, never push, never install system packages. +3. Make the smallest change that satisfies the brief. No drive-by refactors, no + reformatting untouched code, no new dependencies unless the brief allows them. +4. Verify what you can: run the project's formatter, linter or test command when one + exists (see the brief). If it fails, fix it or record the failure honestly. +5. Never ask a question and stop. If something is ambiguous, pick the conservative + reading, do it, and note the ambiguity in the report. +6. If you cannot do the task at all, say why in one paragraph and change nothing. + +## Report + +Before you finish, write `HANDOFF-REPORT.md` in the run directory with exactly these +sections, under 40 lines total: + +``` +## Summary +One paragraph: what you changed and why. + +## Files +- path — what changed (one line each) + +## Verified +- command — result (or "not run: reason") + +## Risks / open questions +- anything the reviewer must check, or "none" +``` + +Then print `HANDOFF-DONE` as the last line of your reply. diff --git a/config/free-agent/pool.json b/config/free-agent/pool.json new file mode 100644 index 0000000..b15ffa6 --- /dev/null +++ b/config/free-agent/pool.json @@ -0,0 +1,68 @@ +{ + "$comment": "Free-model worker pool for `free-agent` / `handoff`. Limits are conservative published free-tier numbers (Nov 2026); free-agent enforces rpm/rpd locally so a burst never trips a provider's 429. Order = preference: first model that has budget and a matching role wins.", + "models": [ + { + "id": "google/gemini-3.5-flash", + "roles": ["code", "review", "infra"], + "rpm": 8, + "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"], + "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"], + "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"], + "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, + "rpd": 800, + "note": "Cheap second Gemini lane for small edits and reviews." + }, + { + "id": "openrouter/nvidia/nemotron-3-super-120b-a12b:free", + "roles": ["code", "review"], + "rpm": 18, + "rpd": 45, + "note": "OpenRouter :free alternative when minimax is busy." + }, + { + "id": "openrouter/cohere/north-mini-code:free", + "roles": ["code"], + "rpm": 18, + "rpd": 45, + "note": "Code-tuned free lane through OpenRouter." + }, + { + "id": "groq/qwen/qwen3.8-27b", + "roles": ["code"], + "rpm": 28, + "rpd": 900, + "note": "Groq fallback, small max output (16K)." + }, + { + "id": "cohere/north-mini-code-1.0", + "roles": ["code", "review"], + "rpm": 18, + "rpd": 30, + "note": "Existing Cohere trial key: 1000 calls/month, so ~30/day." + } + ] +} diff --git a/home/agents.nix b/home/agents.nix index ce97348..175a32f 100644 --- a/home/agents.nix +++ b/home/agents.nix @@ -39,6 +39,9 @@ in ".free-pi/agent/mcp.json".source = link "config/free-pi/mcp.json"; ".free-pi/agent/AGENTS.md".source = link "config/free-pi/AGENTS.md"; + # Free-model worker pool for the handoff pipeline (bin/free-agent, bin/handoff). + ".config/free-agent/pool.json".source = link "config/free-agent/pool.json"; + # Progressive context disclosure: a thin always-on AGENTS.md, the detail in # skills, and an extension that refuses unbounded reads of large files. "AGENTS.md".source = link "config/pi/AGENTS.md"; @@ -61,6 +64,24 @@ in // skillSet ".codex/skills" allSkills // skillSet ".agents/skills" (builtins.filter (n: !(builtins.elem n cliSkills)) sharedSkills) // cliSet ".agents/skills"; + # Free-model handoff pipeline. The daemon owns the tmux session "handoff" and + # starts one window per queued brief, so workers survive a terminal closing and + # are all back after a reboot. Rate limits are enforced by free-agent itself. + systemd.user.services.handoff = { + Unit = { + Description = "Free-model handoff queue (tmux workers)"; + After = [ "default.target" ]; + }; + Service = { + ExecStart = "${config.home.homeDirectory}/.dotfiles/bin/handoff daemon"; + Restart = "always"; + RestartSec = 10; + # dotfiles/bin holds handoff + free-agent, .nix-profile and mise supply pi/node. + Environment = "PATH=${config.home.homeDirectory}/.dotfiles/bin:${config.home.homeDirectory}/.nix-profile/bin:${config.home.homeDirectory}/.local/bin:${config.home.homeDirectory}/.local/share/mise/shims:/run/current-system/sw/bin:/usr/bin:/bin"; + }; + Install.WantedBy = [ "default.target" ]; + }; + # MCP servers carry tokens, so they are rendered from config/*/mcp*.json templates # plus ~/.config/dotfiles/secrets.env by `dot secrets render` (never committed). }