SLOPSHOPPER

effort-router

Routes each turn's effort from your prompt: git housekeeping replies ("merged", "commit and push", "push it") run at low effort, deep asks (review, audit…

commandtoaststatusprompt
★ 1v0.2.0no licenseupdated 2026-10-16joeldg/claude-mods/effort-router
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · effort-router
› fix the failing auth test and add an audit log call ⏺ Read(src/auth.ts) ⎿ Read 6 lines ⏺ Update(src/auth.ts) ⎿ Added 2 lines, removed 1 line ⏺ Bash(bun test) ⎿ 3 pass, 1 fail ● Done. refresh now rejects expired claims and logs an audit event. ✻ Worked for 42s · done 4:20 PM › /route ⎿ effort-router: effort-router: on ⎿ effort-router: Last turn: deep "fix the failing auth test and add an audit log call", mentions "audit" → effort not chosen ye ⎿ effort-router: This session: 0 routine, 0 deep, 0 neutral turns · 0 effort switches · 0 held for the prompt cache ⎿ effort-router: Routine → low, deep → max, neutral → the session's own effort. ⎿ effort-router: Cache guard: a switch is made at once under 30k context tokens, after 60 min idle, or toward more effort; less ⎿ effort-router: Model guard: off ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts
README

claude-mods

Claude Code mods (function-hook plugins) I find helpful. Each folder is one plugin.

Requires a Claude Code build with function-hook plugins (2.1.289 or newer). machine-guard reads macOS tools (sysctl, vm_stat, ioreg, ps).

git clone https://github.com/joeldg/claude-mods ~/Projects/claude-mods

dev-servers

A pane of your project's running dev servers, so you don't have to ask Claude to restart them — and a tool so Claude doesn't have to run lsof to find out what's listening.

  • /servers opens the Servers pane:
  • running servers whose working folder is in this repo: name, port, pid and uptime, with Restart, Stop and Log
  • known start commands that aren't running, with Start: package.json dev/start/serve/preview scripts (run with your lockfile's package manager), .claude/launch.json and Procfile
  • a count of other listeners on the machine. Claude Code's own sessions (the desktop app's engine and the claude CLI, which also listen on localhost from the project's folder) are never listed as servers nor counted as other listeners.
  • Only button presses start or stop anything:
  • Start runs the command detached, logging to ~/.claude/dev-servers/<project>/.
  • Stop sends SIGTERM. If the server ignores it, pressing again within 10s force-stops it.
  • Restart stops the server, waits for the port to free up, then starts it.
  • Before any signal, it checks the pid still runs the same command.
  • Claude gets a read-only dev_servers tool: this project's running servers (name, port, pid, uptime, and the log when it was started from the pane), the start commands that aren't running, and with all: true every other listener on the machine (port, process), ending with how many Claude Code sessions it left out, e.g. (7 Claude Code sessions not listed), so nothing is hidden silently. Its description tells Claude to use it instead of lsof/netstat/ps. It never starts or stops anything.
  • When a command fails with "address already in use", Claude gets a note (and you a toast) naming the holder, e.g. Port 4000 is held by node (pid 123, up 2h, in /Users/me/other).
  • Status line: servers: :4000 :5173.
  • Makes no model calls. The port scan is netstat -anv -p tcp (macOS) or ss -ltnp (Linux), never a bare lsof; ps and lsof -d cwd run once per new pid, one pid at a time. One open session scans per interval (15s by default) and writes ~/.claude/dev-servers/scan-cache.json for the others; a slow scan doubles the interval, up to 5 minutes.

downloads-drop

Puts files you just downloaded into your prompt with one click.

  • Watches ~/Downloads (top level). When a new file arrives (PDF, Markdown, images, 3MF/STL/OBJ, zip, video…), a band appears above the prompt: New in Downloads: paper.pdf, model-b.3mf · 2m ago [Attach] [Dismiss].
  • Attach puts @"/Users/you/Downloads/paper.pdf" mentions in your prompt. Dismiss hides those files.
  • Waits until a file has finished downloading (skips partial downloads and files still growing), and ignores hidden and zero-byte files.
  • /downloads lists the 10 newest files, numbered. /downloads attach 1 3 (or 2-4) adds those, and /downloads clear dismisses everything new.
  • Stacks with other mods' bands (repo-brief, standing-orders, secret-guard) instead of hiding them.
  • Makes no model calls.

Settings: folder (~/Downloads), extensions, pollSeconds (5), maxAgeMinutes (120).

effort-router

Sets effort per message, so you don't have to switch it by hand.

  • Git chores ("merged", "#219 merged", "commit and push", "push it", "open a PR", "close the issue") run at low effort and come back faster.
  • Deep asks (audit, review, plan, design, investigate, root cause, "why does…", "figure out") run at max.
  • Everything else, including approvals like "yes", "go ahead" and "continue" and anything that starts new work ("merged 219, go ahead with #214"), keeps your session's own effort.
  • Prompt cache: changing effort makes the whole conversation get cached again. So it never switches mid-turn, raises effort at once, and over a large, warm cache lowers it only after 2 routine turns in a row. In small contexts, or once the cache has lapsed, it switches right away.
  • Budget cap: reads usage-meter's machine-wide summary of the last 5 hours (~/.claude/usage-meter/summary.json, at most every 30 s) and, once pct reaches budgetCapAt (80%), caps every turn at budgetCapEffort (high), deep asks included, so you stop hitting the 5-hour wall. A turn already at or below the cap is left alone; lowering over a warm cache waits like any other lowering and never happens mid-turn. A missing or stale summary (over 10 minutes old), or one with no percentage yet (no fresh API reading and no limit learned), is no budget information. The debug log gets one line when the cap engages and one when it releases. budgetCapAt: 0 turns it off.
  • Subagents: set subagentEffort (empty by default) to run every subagent request at that effort; the budget cap applies to them too (the lower of the two). Each subagent turn's effort is decided at its first request and kept for the turn.
  • Model guard: set avoidModel (a regex such as fable) to send those requests to fallbackModel instead, subagents included.
  • /route shows the last decision, the session's counts, the budget state (percent used, the cap, whether it is engaged) and the subagent effort. /route off and /route on toggle it all; /route deep and /route routine force the next turn.
  • Status line while a turn is routed: effort: low (routine); while the budget cap lowers it: effort: high (budget 84%).
  • Makes no model calls.

Settings: routineEffort (low), deepEffort (max), routinePattern, deepPattern, avoidModel, fallbackModel (opus), stickyTurns (2), freeSwitchTokens (30000), cacheTtlMinutes (60), budgetCapAt (80; 0 = off), budgetCapEffort (high), subagentEffort (empty = the session's own).

job-watch

A Jobs pane for long-running work: training runs, downloads, extractions — and three tools so Claude follows them instead of polling.

  • Picks up background Bash tasks and detached nohup … > log & launches by itself.
  • /watch <log> [label] adds any other log file.
  • Shows progress, ETA and the last log line, and flags a job as stalled when its log goes quiet; a background task's exit code is read from the end of its output.
  • Shows free space on / and /Volumes/* (the NAS).
  • Toasts when a job finishes or stalls. The status line shows jobs: 2 running · 1 stalled. A timer Claude sets for itself — sleep 600 && echo done, a loop of sleeps, or a task described as a wait, timer, pause or delay that only polls and reports with read-only programs (rg, tail, pgrep…) — is still listed by jobs_list and shown as a dim timer row, but never toasts, never counts in the status line, does not open the pane, is judged by its exit marker alone (no ps), and leaves a minute after it ends. Anything that runs a real program is a job, however it is described.
  • /jobs opens the pane, /unwatch <label|id|done|all> removes jobs.
  • Tools for Claude: jobs_list (every watched job's state, pid, progress, ETA, last-output age, exit code and log path), jobs_watch ({ pid?, log?, name?, quietMinutes? }: follow a process or log started elsewhere; it never starts commands) and jobs_unwatch ({ name }). The first message of each conversation says jobs are watched and names them, so Claude stops writing until … sleep loops and running ps. They need no permission prompt: they only read the mod's own list.
  • Makes no model calls: it reads logs with tail, checks processes with ps (one listing, or a per-pid lookup when only pids are watched), and runs df. A probe that times out or takes over 2 s is retried at a doubling interval, up to 5 minutes, until it is fast again. The debug log names a probe's pace only once it has held for two probes in a row, and at most once per five minutes per probe, so a pace that flips with the Mac's load leaves no trail.

Settings (in /config): stall minutes (10), refresh seconds (10), how long finished jobs stay (120 min; a timer leaves after a minute), auto-open (on), which disks to show.

machine-guard

Memory, swap and GPU on the status line, a machine_status tool for Claude, and a guard that refuses heavy local jobs when the Mac can't take them.

  • Status line: RAM tight 12% free · swap 7.9/8G · top python 31G · GPU 87%, and CPU 4/16 cores whenever macOS has parked the performance cores. "Free" is unused memory (vm_stat's free + inactive + speculative pages): what a new job can take without pushing anyone out. macOS's own "memory free percentage" counts active pages too, which is how a Mac can be "55% free" with the swap nearly full.
  • It reads the kernel's counters only (two sysctl calls and vm_stat), every 15 s by default; the GPU (ioreg) on every third sample, never right after a slow one. One session samples and writes ~/.claude/machine-guard/sample.json (with a lock.json while it probes); every other session shows the same numbers instead of probing too. When probes are slow or time out (10–40 s while the Mac swaps) on two samples in a row, the interval doubles, and doubles again with each further slow sample, up to 2 min; a single slow sample is a blip and changes nothing. The configured pace returns once two samples in a row are fast again. The other sessions follow the sampler's pace, so a blip stays quiet in every session.
  • Parked cores: every sample also reads kern.sched_recommended_cores, the bitmask of CPUs the scheduler may use. When macOS's performance controller parks the performance cores (after a thermal event, or stuck until a sleep/wake or reboot), the status line shows CPU 4/16 cores, machine_status and /guard report it with the parked count, you get one toast once at least half the cores have been parked for a minute, or any parking has lasted five minutes (masks blip for seconds under GPU load), and one when they come back, and Claude gets a note when it starts heavy work so it keeps worker counts small. The guard never blocks on it.
  • The process table (ps, the slowest probe) is taken only on demand (/guard, machine_status) or when a sample shows pressure, at most once a minute; "biggest" means the apps from a table taken in the last 5 minutes.
  • It refuses heavy jobs (training, inference, rendering, extraction, Blender, Docker, ffmpeg) when:
  • macOS reports critical memory pressure (kernel level 4, or under 10% free with the swap 95% full), or
  • the Mac is reserved with /busy.

When memory is only tight (under 20% free, or kernel level 2), the job runs and Claude gets a note to start one heavy job at a time.

  • machine_status is a tool Claude can call (no input, allowed without asking): the sample's age, RAM free, swap, GPU, the pressure level, the biggest apps (or how to get a table), the guard's verdict and its rules. Claude is told to use it instead of ps, top, vm_stat, memory_pressure or project scripts before launching heavy work.
  • /busy 3h training a vision model reserves the Mac in every Claude session. /busy off lifts it. The reservation lives in ~/.claude/machine-guard.json, so a training script can write it too: ``bash echo '{"reason":"overnight training","until":'$(( ($(date +%s) + 8*3600) * 1000 ))'}' > ~/.claude/machine-guard.json ``
  • /guard shows what it sees (and takes a process table when one is due). /guard pause 15m lets heavy jobs through in this session; /guard on resumes the guard.
  • Remote runs (modal run, ssh), tests (pytest) and installs are never treated as heavy.
  • Add your own heavy commands with the "Also heavy" setting (a regex), e.g. overnight_|nightly_run\.sh.

mod-monitor

Watches how the other mods behave in real use, without changing them. It is listed first in CLAUDE_CODE_PLUGIN_DIRS, so the other mods' hooks run beneath it.

  • Failures: any mod hook that throws, times out or rejects, read from the hook chain's results (next.trace), with the mod's name, the event and how long it ran. Slow hooks (over 1.5 s) are recorded too. The first failure of each mod in a session raises a toast.
  • What each mod did: its toasts ("#219 merged → …", "Blocked: …"), status-line changes, the mod commands you used (never their arguments), and failed subprocesses (a burst of 5 in 10 minutes raises a toast). Git checks run outside a repository, and rg, grep, pgrep or pkill exiting 1 with nothing on stderr (no match, no such process), are logged as expected (proc-expected, with why), not as failures; an exit of 2 or more, or anything on stderr, still counts. It also records model calls (the only usage the mods cost: /second-opinion, /recall ask) and file writes (folders only, never contents).
  • /mods: a pane with one row per mod: ✓ active, ⚠ failing, ✗ not seen this session, · seen but idle. Each row shows today's counts and last activity, with Details for its recent events. It also says which mods it can't see, if any of them run above it.
  • /mods report [24h|7d|30d]: a per-mod report across all sessions, also written to ~/.claude/mods/monitor/report-latest.md for a scheduled review or Claude to read.
  • /mods failures [7d]: failures and failed subprocesses only.
  • Logs: ~/.claude/mods/monitor/<date>/<session>.jsonl, flushed every minute and at session end, with secrets masked and old days removed after 30 days.
  • Makes no model calls and adds no measurable latency.
  • Error lines mods log themselves ($.ui.log with wording like "failed" or "could not"): shown in Details and in /mods failures. Three in an hour mark the mod ⚠ and raise one toast. That is how effort-router's per-request hook, which runs inside the response stream where no monitor should sit, reports a failure. It also always sends the request on unchanged.
  • Transcript-row hooks (secret-guard masks /secrets records there) are watched for failures and slow runs, but not counted per run.

Settings: alerts (on), slowMs (1500), watchRender (on), watchCommands (on; off stops "mod-monitor" appearing beside other mods' command output), watchAppend (on), retentionDays (30), flushSeconds (60).

modal-meter

Keeps an eye on Modal so idle GPU containers don't burn credits — in the projects that use Modal, with one CLI run per minute for the whole machine.

  • Watches a project only when it uses Modal: a .py file with import modal / from modal import … (one rg run, 5 s at most), or modal named in pyproject.toml, requirements*.txt, uv.lock or poetry.lock. The answer is remembered per project for a day. Running /modal, or any modal … command in Bash, switches it on for the session; alwaysPoll (off) watches every project.
  • One session polls for all of them: whoever holds ~/.claude/modal-meter/lock.json runs modal app list --json every pollSeconds (60) and writes cache.json; the other open sessions read the cache and refresh their own status line and pane from it. Once one session learns the CLI has no billing report, none tries it again for a day.
  • Backs off while Modal is slow: an app list over 2 s or a timeout doubles the interval (up to 10 minutes); a fast answer brings it back.
  • Status line while containers run: Modal: 1 running (2 containers). Deployed apps with no containers cost nothing, so they stay off it.
  • A toast when an app has had containers up longer than alertMinutes (30), repeated at most every 30 minutes.
  • /modal opens a pane of apps with state, containers and uptime. Stop asks for Confirm, then runs modal app stop. Nothing is stopped any other way.
  • Shows today's spend and alerts on a budgetToday where the Modal CLI supports billing report (1.3.3+, Team/Enterprise workspaces). Otherwise /modal says why spend isn't shown.
  • Finds the CLI as modal or python3 -m modal. It checks PATH first rather than running a command that can only fail, never retries one that isn't there, and stays silent when Modal isn't set up.
  • Makes no model calls: only the Modal CLI, never at session start — the first read runs in the background.

pr-autopilot

Does the "merged #219, clean up branches and start #214" round trip for you, and surfaces CI failures with their logs.

  • Watches your open PRs in the session's repo: it adopts them at session start, and picks up every gh pr create Claude runs. It polls gh pr view every 60s.
  • Status line: PRs: #219 ✓ · #220 CI… · #221 ✗, for every watched PR.
  • CI toasts only where they're wanted. A CI pass or failure (with the failing check names) toasts for the PRs this session opened (gh pr create) or you added with /prs watch, and for any PR whose branch this worktree has checked out. PRs adopted from the repository at start stay on the status line, in /prs and in prs_status, and still get the merge ritual, but their CI results don't toast — so with seven worktree sessions of one repo a result toasts once, where it matters, not seven times. toastAdoptedCi (off) brings back toasts for every watched PR.
  • When a PR merges, it cleans up with plain local git, then toasts the outcome and suggests carrying on (Tab to accept):
  • git fetch --prune, switch to the default branch (only from the PR's own branch) and git pull --ff-only.
  • Never with uncommitted changes, never --force, never other branches.
  • Deletes the local branch only if it points at exactly the commit GitHub merged, so nothing local is lost. It also leaves a branch checked out in any worktree alone.
  • In a linked worktree (git worktree add, such as Claude Code's .claude/worktrees/<name> sessions) it only fetches: it never switches or pulls there, because the default branch is checked out in the primary worktree and the switch could only fail ('main' is already used by worktree …). When the merged branch is the one the worktree has checked out, the toast says #N merged → this worktree's branch; remove the worktree when you're done (git worktree remove <path>) and the Tab suggestion tells Claude the branch and worktree stay until you remove them. In the primary worktree the ritual is unchanged.
  • A merge seen mid-turn is cleaned up when the turn ends, so git never races Claude.
  • When you mention failing CI ("#258 is failing", "CI failed, fix it"), your message goes to Claude with gh pr checks and the tail of the failed log attached, so you don't paste it.
  • Claude reads the watched PRs with a tool, prs_status (number, title, state, branch, CI, URL, and how old the data is), instead of running gh pr view or gh pr checks itself: no API call, and it refreshes first when the data is older than a poll.
  • When gh can't read the checks (a fine-grained token without "Checks: read" — the cause of Resource not accessible by personal access token), it tells you once with the fix (gh auth login --web, or grant the token "Checks: read"), keeps polling the PRs without their checks so merges are still handled, shows them as #219 CI?, and tries the checks again after 30 minutes or when you run /prs. If gh can't read PRs at all (not logged in), the status line says PRs: gh can't read them and nothing is polled until then. A GitHub rate limit pauses polling for 5 minutes; any other failure doubles the wait up to 10 minutes, back to normal on the next success. Nothing retries every minute forever; the debug log gets one line per change.
  • /prs lists watched PRs and asks gh again at once. /prs watch <n|url> and /prs forget <n|all> add and remove them.
  • Makes no model calls: only gh and git, at about one GitHub API call per open PR per minute.

Settings:

  • pollSeconds (60)
  • authRetryMinutes (30): how long before the checks are tried again after gh refused them over auth.
  • attachCiLogs (on)
  • logLines (120)
  • deleteRemoteBranch (off): deletes the branch on GitHub too, only while it still points at the merged commit. GitHub's own "Automatically delete head branches" setting does the same job.
  • toastAdoptedCi (off): toast the CI results of PRs adopted from the repository too, as every PR's used to; with several worktree sessions of one repo, each would toast.

It never closes issues; put "Closes #N" in PR bodies for that.

recall

Search everything you've done with coding agents, from Claude or from /recall. It replaces the broken agent-memory plugin.

  • What it searches: Claude Code sessions, Codex sessions, subagent and workflow runs, Claude's memory files, standing orders, second-opinion reviews, and your /remember notes. Routine (scheduled) runs are left out unless you add routines:include to a query.
  • What it keeps: prompts, answers, compaction summaries, session titles, commands, files touched, commits, PRs, issues, URLs, tasks and decisions (what you approved or ruled out). Read-only look-ups like grep and cat are kept but ranked low.
  • History survives cleanup: extracts stay searchable after Claude Code deletes old transcripts.
  • Claude searches it itself with four read-only tools, search, expand, recap and list, which run without permission prompts. It checks them when you say "like last time" or "what did we decide", and before asking you something you already settled.
  • The ledger survives compaction: as a session goes, recall keeps what it has settled — your /goal (or the Stop hook's condition), open tasks with a count of the done ones, the questions you asked with the first line of each answer, the files touched, the commits made and PRs opened. After a compaction it goes back into Claude's context as Ledger (this session, before compaction) (about 40 lines at most), so you don't have to say "don't lose track of where we were". /recall ledger prints it any time; /clear starts a fresh one. It is written to ~/.claude/recall/ledger/<session>.json (readable only by you, secrets masked) so a reload keeps it.
  • Commands:
  • /recall <query> opens a pane of hits grouped by session. Open shows the conversation around a hit, Attach sends it with your next message, and Copy resume command copies claude --resume <id>.
  • /recall last [n] recaps your last session in this repo: last asks, last answer, PRs, commits, open tasks and decisions. Send to Claude attaches it.
  • /recall ledger prints this session's ledger (above).
  • /recall timeline [7d|30d|90d] [all]
  • /recall decisions|commands|files|prs|commits|issues|urls|tasks|notes [query]
  • /recall ask <question> answers from your history with Haiku 4.5, citing sessions. It costs a little usage and sends the matching excerpts to the model.
  • /recall stats, /recall reindex, /recall forget session <id>|project <name>|before <date> (asks you to confirm), /recall help.
  • /remember <fact>, /remember list, /remember forget <ref>.
  • Bands:
  • Once per session: Last session here (2d ago): "…" · PR #99 · 3 open tasks [Recap].
  • When a prompt mentions #214, ABC-12, a file name or a quoted phrase seen in past sessions, a band offers what happened then. Nothing is sent unless you click.
  • Query syntax: words must all match. OR gives alternatives, "quotes" an exact phrase, and -word excludes. Filters: project:name, kind:decision, since:7d, until:2026-09-30, source:codex, routines:include.
  • Privacy:
  • The index lives at ~/.claude/recall/index.db, readable only by you, and never goes in a repo. The ledgers beside it are kept the same way.
  • Secrets are masked before anything is stored: known token shapes, labelled values ("password: …"), the values of secret-named exports in ~/.zshrc, ~/.zprofile, ~/.bashrc and `~/.bash_profile
Source 3 files
hooks/register.ts 413 lines
1/**
2 * effort-router: sends git housekeeping replies ("merged", "#219 merged", "commit and push", "push it")
3 * at low effort and deep asks ("review", "audit", "why does ...") at max, by rewriting the effort of
4 * each model request (`turn.step`). Approvals and replies that start new work ("yes", "continue",
5 * "merged, go ahead with #214") keep the session's own effort. The prompt itself passes through
6 * unchanged; no model call is made.
7 *
8 * The prompt cache. Claude Code sends effort as the request's top-level `output_config.effort`
9 * (this build has no per-message effort beta), and the API renders effort into the prompt: changing
10 * it between requests invalidates the cached messages (on some models the system prompt and tools
11 * too), so the next request writes the whole conversation to the cache again at the write price
12 * instead of reading it at a tenth of the input price. On a large conversation one switch can cost
13 * more than low effort saves on a short reply, and switching down and back up costs it twice. So:
14 *
15 * - The effort is chosen once per turn, at its first request, and every later request of the turn
16 *   (each tool round) carries the same effort: never a switch mid-turn.
17 * - A switch is made at once when it is cheap or asked for: the context is small (`freeSwitchTokens`),
18 *   the cache has lapsed (idle past `cacheTtlMinutes`; Claude Code caches the main thread for an hour
19 *   on a subscription, five minutes with an API key), the model or the session's own /effort changed,
20 *   compaction or /clear rewrote the history, `/route deep|routine` forced it, or the turn wants MORE
21 *   effort (quality never waits for the cache).
22 * - Less effort over a warm, large cache waits until `stickyTurns` turns in a row have wanted it
23 *   (hysteresis): one "push it" between two real tasks is not worth two cache rewrites.
24 *
25 * The model guard (`avoidModel` → `fallbackModel`) rewrites every request the same way, main loop and
26 * subagents alike, so the cache is rebuilt once for the new model and then reused.
27 *
28 * The budget cap (`budgetCapAt` → `budgetCapEffort`). usage-meter writes a machine-wide summary of the
29 * last 5 hours to ~/.claude/usage-meter/summary.json; once its `pct` (of the last learned limit)
30 * reaches `budgetCapAt`, every turn's effort is capped at `budgetCapEffort`, deep asks included: the
31 * point is not to hit the wall. The summary is read at a turn's first request, one reading serving
32 * 30 s; a missing or stale file (over 10 minutes old) or a null `pct` is no budget information. The
33 * cap only lowers what a turn wants, so it goes through the same cache discipline: over a warm, large
34 * cache it waits for `stickyTurns` turns like any lowering, and a turn's effort never changes midway.
35 *
36 * Subagents (`subagentEffort`) run at that effort when it is set, the budget cap applying to them too
37 * (the lower of the two); each subagent turn's effort is decided at its first request and kept.
38 */
39import { atom, read, update } from 'claude-code'
40import type { EngineInterface, PromptOrigin, Register, TurnStepInput, TurnStepResult } from 'claude-code'
41
42import type { RouteBudget, RouteState } from '../types'
43import {
44  BUDGET_MEMO_MS,
45  EMPTY_STATE,
46  SUMMARY_PATH,
47  agentDone,
48  cleared,
49  compilePatterns,
50  describeBudgetChange,
51  describeRoute,
52  guardModel,
53  isLevel,
54  noteBudget,
55  parseSummary,
56  planAgentStep,
57  planStep,
58  resolveModel,
59  responded,
60  started,
61  submitted,
62} from './route'
63import type { BudgetChange, Level, Patterns, Planned, Settings } from './route'
64
65type Engine = EngineInterface
66
67const router = atom({ plugin: 'effort-router', key: 'router' } as const, EMPTY_STATE)
68
69/** Prompts the person wrote: typed, through Remote Control, a host's own turn, a scheduled routine, a Slack ping. */
70const PERSONAL = new Set<string>(['composer', 'bridge', 'sdk', 'scheduled-trigger', 'slack-ping'])
71
72const isPersonal = (origin: PromptOrigin): boolean =>
73  PERSONAL.has(origin.kind) || (origin.kind === 'plugin' && origin.asUser === true)
74
75const USAGE = 'Usage: /route (status) | /route on | /route off | /route deep | /route routine (forces the next prompt)'
76
77type Config = {
78  enabled: boolean
79  settings: Settings
80  patterns: Patterns
81  errors: string[]
82  avoid: RegExp | null
83  fallbackModel: string
84}
85
86const DEFAULT_SETTINGS: Settings = {
87  routineEffort: 'low',
88  deepEffort: 'max',
89  guard: { stickyTurns: 2, freeSwitchTokens: 30_000, cacheTtlMs: 60 * 60_000 },
90  budgetCapAt: 80,
91  budgetCapEffort: 'high',
92  subagentEffort: null,
93}
94
95let config: Config = {
96  enabled: true,
97  settings: DEFAULT_SETTINGS,
98  patterns: compilePatterns('', '').patterns,
99  errors: [],
100  avoid: null,
101  fallbackModel: 'opus',
102}
103
104const numberIn = (value: unknown, fallback: number, min: number, max: number): number => {
105  const n = typeof value === 'number' ? value : Number(value)
106  return Number.isFinite(n) ? Math.min(max, Math.max(min, n)) : fallback
107}
108
109const textOf = (value: unknown): string => (typeof value === 'string' ? value : '')
110
111const modelGuardLine = (): string | null =>
112  config.avoid === null ? null : `models matching /${config.avoid.source}/i run on ${resolveModel(config.fallbackModel, '')}`
113
114/** The model a request goes to; the first rewrite of each kind is announced once. */
115async function guardedModel($: Engine, model: string): Promise<string> {
116  if (config.avoid === null || !config.avoid.test(model)) {
117    return model
118  }
119  const target = guardModel(model, config.avoid, config.fallbackModel)
120  const key = `${model}→${target}`
121  let isFirst = false
122  await update($, router, state => {
123    isFirst = !state.rewrites.includes(key)
124    return isFirst ? { ...state, rewrites: [...state.rewrites, key] } : state
125  })
126  if (isFirst) {
127    $.ui.toast(
128      target === model
129        ? `effort-router: ${model} matches avoidModel, but so does the fallback "${config.fallbackModel}"; requests stay on ${model}.`
130        : `effort-router: requests for ${model} go to ${target} (avoidModel).`,
131    )
132  }
133  return target
134}
135
136/** The context's size when the mod first sees a request (it may have loaded mid-session); 0 if unknown. */
137async function contextNow($: Engine): Promise<number> {
138  try {
139    const usage = await $.session.usage()
140    return usage.context.tokens ?? 0
141  } catch {
142    return 0
143  }
144}
145
146/** usage-meter's summary of the last 5 hours, machine-wide; null when there is none to read. */
147async function readSummary($: Engine): Promise<string | null> {
148  try {
149    const home = await $.env.get('HOME')
150    return home ? await $.fs.read(`${home}/${SUMMARY_PATH}`) : null
151  } catch {
152    return null
153  }
154}
155
156/**
157 * Brings the budget reading up to date once the memo has run out, and logs the cap engaging or
158 * releasing. Never throws: without a fresh reading the turn runs on the last one.
159 */
160async function refreshBudget($: Engine, now: number, known: RouteState): Promise<void> {
161  if (config.settings.budgetCapAt <= 0) {
162    return
163  }
164  const memo = known.budget ?? null
165  if (memo !== null && now - memo.checkedAt < BUDGET_MEMO_MS) {
166    return
167  }
168  try {
169    const reading = parseSummary(await readSummary($), now)
170    const noted: { change: BudgetChange; budget: RouteBudget | null } = { change: null, budget: null }
171    await update($, router, state => {
172      const next = noteBudget(state, reading, now, config.settings.budgetCapAt)
173      noted.change = next.change
174      noted.budget = next.state.budget
175      return next.state
176    })
177    if (noted.change !== null && noted.budget !== null) {
178      $.ui.log(describeBudgetChange(noted.change, noted.budget, config.settings), { to: 'debug' })
179    }
180  } catch (error) {
181    reportFailure($, 'reading the budget', error, 'so the turn runs on the last reading')
182  }
183}
184
185/** The effort this main-loop request is sent at: decided at the turn's first request, then kept. */
186async function chooseEffort($: Engine, e: TurnStepInput, model: string, base: Level): Promise<Level> {
187  const before = await read($, router)
188  if (before.turn !== null && before.turn.id === e.turnId && before.turn.effort !== null) {
189    return before.turn.effort
190  }
191  const now = await $.clock.now()
192  if (before.isOn || (before.turn !== null && before.turn.id === e.turnId && before.turn.isForced)) {
193    await refreshBudget($, now, before)
194  }
195  const contextTokens = before.cache === null ? await contextNow($) : 0
196  const plan: { planned: Planned | null } = { planned: null }
197  await update($, router, state => {
198    plan.planned = planStep(state, { turnId: e.turnId, model, base, messageCount: e.messageCount, now, contextTokens }, config.settings)
199    return plan.planned.state
200  })
201  if (plan.planned === null) {
202    return base
203  }
204  if (plan.planned.isNew) {
205    $.ui.status(plan.planned.status)
206  }
207  return plan.planned.effort
208}
209
210/** The effort a subagent's request is sent at: decided at its turn's first request, then kept. */
211async function chooseAgentEffort($: Engine, agentId: string, turnId: string, base: Level): Promise<Level> {
212  const before = await read($, router)
213  const pinned = (before.agents ?? {})[agentId]
214  if (pinned !== undefined && pinned.turnId === turnId) {
215    return pinned.effort
216  }
217  if (before.isOn) {
218    await refreshBudget($, await $.clock.now(), before)
219  }
220  const plan = { effort: base }
221  await update($, router, state => {
222    const planned = planAgentStep(state, { agentId, turnId, effort: base }, config.settings)
223    plan.effort = planned.effort
224    return planned.state
225  })
226  return plan.effort
227}
228
229/** Remembers how large the cached conversation is now, and when it was last written. */
230async function noteResponse($: Engine, messageCount: number, model: string, result: TurnStepResult) {
231  try {
232    const now = await $.clock.now()
233    await update($, router, state => responded(state, { model, messageCount, now, usage: result.usage }))
234  } catch {
235    // The next turn decides from what was known before; nothing to undo.
236  }
237}
238
239/** A failure in effort-router's own code, logged (to the debug log) for mod-monitor to count. */
240function reportFailure($: Engine, what: string, error: unknown, consequence = 'so the request went out unchanged') {
241  const message = error instanceof Error ? error.message : String(error)
242  $.ui.log(`effort-router: ${what} failed, ${consequence}: ${message.slice(0, 200)}`, { to: 'debug' })
243}
244
245/**
246 * The request as it goes out: the model after the guard, and the effort chosen for the main loop's
247 * turn or the subagent's. Routing must never cost a request: if choosing fails, the request goes out
248 * exactly as it came, and the failure is logged where mod-monitor reads it (the response stream is not
249 * a hook it can watch). `isRouted` says the main loop's response should be noted for the cache.
250 */
251async function routeRequest($: Engine, e: TurnStepInput): Promise<{ routed: TurnStepInput; model: string; isRouted: boolean }> {
252  try {
253    const model = await guardedModel($, e.model)
254    if (!isLevel(e.effort)) {
255      // A model without effort levels has none to route.
256      return { routed: model === e.model ? e : { ...e, model }, model, isRouted: false }
257    }
258    if (e.agentId !== undefined) {
259      const effort = await chooseAgentEffort($, e.agentId, e.turnId, e.effort)
260      return { routed: effort === e.effort && model === e.model ? e : { ...e, model, effort }, model, isRouted: false }
261    }
262    const effort = await chooseEffort($, e, model, e.effort)
263    return { routed: effort === e.effort && model === e.model ? e : { ...e, model, effort }, model, isRouted: true }
264  } catch (error) {
265    reportFailure($, 'choosing the effort', error)
266    return { routed: e, model: e.model, isRouted: false }
267  }
268}
269
270/** A subagent's turn ended: the effort pinned for it is dropped. */
271async function forgetAgent($: Engine, agentId: string): Promise<void> {
272  try {
273    await update($, router, state => agentDone(state, agentId))
274  } catch (error) {
275    reportFailure($, 'forgetting a subagent turn', error, 'so its effort stays pinned until its next turn')
276  }
277}
278
279/** /route: the status, on or off for the session, or forcing the next prompt deep or routine. */
280async function runRoute($: Engine, args: string): Promise<{ text: string }> {
281  if (!config.enabled) {
282    return { text: 'effort-router is turned off in its settings (enabled: false); requests are left as they are.' }
283  }
284  const verb = args.trim().toLowerCase()
285  if (verb === 'off') {
286    await update($, router, state => ({ ...state, isOn: false }))
287    return { text: "Effort routing is off for this session: turns run at the session's own effort. /route on turns it back on." }
288  }
289  if (verb === 'on') {
290    await update($, router, state => ({ ...state, isOn: true }))
291    return { text: 'Effort routing is on.' }
292  }
293  if (verb === 'deep' || verb === 'routine') {
294    const forced: 'deep' | 'routine' = verb
295    await update($, router, state => ({ ...state, forced }))
296    const effort = forced === 'deep' ? config.settings.deepEffort : config.settings.routineEffort
297    return { text: `Your next prompt runs at ${effort} (${forced}), whatever it says.` }
298  }
299  if (verb !== '' && verb !== 'status') {
300    return { text: USAGE }
301  }
302  let state = await read($, router)
303  if (state.isOn && config.settings.budgetCapAt > 0) {
304    // Shows the budget as it stands now, not as the last turn saw it.
305    try {
306      await refreshBudget($, await $.clock.now(), state)
307      state = await read($, router)
308    } catch (error) {
309      reportFailure($, 'reading the budget', error, 'so /route shows the last reading')
310    }
311  }
312  return { text: describeRoute(state, { settings: config.settings, modelGuard: modelGuardLine(), errors: config.errors }) }
313}
314
315export const register: Register = (on, options) => {
316  const compiled = compilePatterns(textOf(options.routinePattern), textOf(options.deepPattern))
317  const errors = [...compiled.errors]
318  let avoid: RegExp | null = null
319  const avoidSource = textOf(options.avoidModel).trim()
320  if (avoidSource !== '') {
321    try {
322      avoid = new RegExp(avoidSource, 'i')
323    } catch (error) {
324      errors.push(`avoidModel is not a valid regular expression (${error instanceof Error ? error.message : String(error)}); the model guard is off.`)
325    }
326  }
327  config = {
328    enabled: options.enabled !== false,
329    settings: {
330      routineEffort: isLevel(options.routineEffort) ? options.routineEffort : 'low',
331      deepEffort: isLevel(options.deepEffort) ? options.deepEffort : 'max',
332      guard: {
333        stickyTurns: Math.round(numberIn(options.stickyTurns, 2, 1, 20)),
334        freeSwitchTokens: numberIn(options.freeSwitchTokens, 30_000, 0, 10_000_000),
335        cacheTtlMs: numberIn(options.cacheTtlMinutes, 60, 0, 24 * 60) * 60_000,
336      },
337      budgetCapAt: numberIn(options.budgetCapAt, 80, 0, 100),
338      budgetCapEffort: isLevel(options.budgetCapEffort) ? options.budgetCapEffort : 'high',
339      subagentEffort: isLevel(options.subagentEffort) ? options.subagentEffort : null,
340    },
341    patterns: compiled.patterns,
342    errors,
343    avoid,
344    fallbackModel: textOf(options.fallbackModel).trim() || 'opus',
345  }
346
347  on('session.start', async ($, e, next) => {
348    await $.command.register({
349      name: 'route',
350      description: 'Effort routing: status, on/off for this session, or force the next prompt deep or routine',
351      argumentHint: '[on | off | deep | routine]',
352      immediate: true,
353    })
354    return next(e)
355  })
356
357  on('command.run', { command: 'route' }, ($, e) => runRoute($, e.args))
358
359  if (!config.enabled) {
360    return
361  }
362
363  // Classifies the prompt for the turn it starts; the prompt itself goes on unchanged.
364  on('prompt.submit', async ($, e, next) => {
365    try {
366      const isMine = isPersonal(e.origin)
367      await update($, router, state => submitted(state, e.text, isMine, config.patterns))
368    } catch {
369      // Unclassified: the turn runs at the session's own effort.
370    }
371    return next(e)
372  })
373
374  on('turn.start', async ($, e, next) => {
375    if (e.agentId !== undefined) {
376      // A subagent's turn: its prompt is not the person's, and the main turn keeps its own record.
377      return next(e)
378    }
379    await update($, router, state => started(state, e.turnId, e.text, config.patterns))
380    return next(e)
381  })
382
383  on('turn.step', async function* ($, e, next) {
384    const { routed, model, isRouted } = await routeRequest($, e)
385    const result = yield* next(routed)
386    if (isRouted) {
387      try {
388        await noteResponse($, e.messageCount, model, result)
389      } catch (error) {
390        reportFailure($, 'noting the response', error)
391      }
392    }
393    return result
394  })
395
396  on('turn.complete', async ($, e, next) => {
397    const done = await next(e)
398    if (e.agentId === undefined) {
399      $.ui.status(undefined)
400    } else {
401      await forgetAgent($, e.agentId)
402    }
403    return done
404  })
405
406  on('session.end', async ($, e, next) => {
407    if (e.reason === 'clear') {
408      await update($, router, cleared)
409    }
410    return next(e)
411  })
412}
413
hooks/route.ts 581 lines
1import type { ModelEffort, ModelUsage } from 'claude-code'
2
3import type { RouteAgentTurn, RouteBudget, RouteCache, RouteClass, RouteCounts, RoutePending, RouteState, RouteTurn } from '../types'
4
5export type Level = ModelEffort
6
7export const LEVELS: readonly Level[] = ['low', 'medium', 'high', 'xhigh', 'max']
8
9export const isLevel = (value: unknown): value is Level =>
10  typeof value === 'string' && (LEVELS as readonly string[]).includes(value)
11
12export const rank = (level: Level): number => LEVELS.indexOf(level)
13
14/** A prompt longer than this is never routine, whatever it starts with. */
15export const ROUTINE_MAX_CHARS = 120
16/** How many words may follow the routine phrases ("both are merged now" leaves one), none of them new work. */
17export const ROUTINE_MAX_EXTRA_WORDS = 6
18
19/**
20 * Routine replies are git housekeeping, matched at the start of the prompt: "merged", "#123 merged",
21 * "both are merged", "commit and push", "commit it", "push it", "open a PR", "close it". Approvals and
22 * resumptions ("yes", "go ahead", "continue", "keep going") are not: they start real work.
23 */
24export const DEFAULT_ROUTINE = String.raw`merged|(?:pr\s*)?#\d+\s+(?:is\s+|was\s+|got\s+)?merged|(?:all\s+|both\s+|everything\s+)?(?:is\s+|are\s+)?merged|commit(?:\s+and)?\s+push|commit(?:\s+it)?|push(?:\s+it)?|open\s+(?:a\s+)?pr|close\s+(?:it|the\s+issue)`
25
26/** Words that ask for deep thought, anywhere in the prompt (word starts: "audit" covers "auditing"). */
27export const DEFAULT_DEEP = String.raw`\b(?:audit|review|plan(?:s|ned|ning)?\b|architect|design|deep[\s-]*dive|assess|investigat|root[\s-]*cause|research|why\s+(?:is|does|did)\b|figure\s+out|what(?:['’]s|\s+is)\s+wrong)`
28
29export type Patterns = {
30  /** Anchored at the start; one routine phrase. */
31  routine: RegExp
32  /** Unanchored; any deep wording. */
33  deep: RegExp
34}
35
36export type PatternSet = { patterns: Patterns; errors: string[] }
37
38const leading = (source: string): RegExp => new RegExp(String.raw`^(?:${source})(?![A-Za-z0-9_])`, 'i')
39const anywhere = (source: string): RegExp => new RegExp(source, 'i')
40
41const compileOne = (
42  source: string,
43  fallback: string,
44  make: (source: string) => RegExp,
45  name: string,
46  errors: string[],
47): RegExp => {
48  const trimmed = source.trim()
49  if (trimmed !== '') {
50    try {
51      return make(trimmed)
52    } catch (error) {
53      errors.push(`${name} is not a valid regular expression (${error instanceof Error ? error.message : String(error)}); the built-in one is used.`)
54    }
55  }
56  return make(fallback)
57}
58
59/** The routine and deep patterns from settings; an empty or broken one falls back to the built-in. */
60export function compilePatterns(routineSource: string, deepSource: string): PatternSet {
61  const errors: string[] = []
62  return {
63    patterns: {
64      routine: compileOne(routineSource, DEFAULT_ROUTINE, leading, 'routinePattern', errors),
65      deep: compileOne(deepSource, DEFAULT_DEEP, anywhere, 'deepPattern', errors),
66    },
67    errors,
68  }
69}
70
71/** Punctuation and quoting between and around routine phrases. */
72const FILLER = /^[\s,.;:!?…—–\-"'`*_()[\]>]+/
73
74const wordCount = (text: string): number => text.split(/\s+/).filter(word => /[A-Za-z0-9]/.test(word)).length
75
76/** The routine phrases a prompt opens with ("merged, commit and push") and what follows them. */
77export function leadingRoutine(text: string, routine: RegExp): { phrases: string[]; rest: string } | null {
78  let rest = text.replace(FILLER, '')
79  const phrases: string[] = []
80  for (let i = 0; i < 8; i++) {
81    const found = routine.exec(rest)
82    if (!found || found[0] === '') {
83      break
84    }
85    phrases.push(found[0])
86    rest = rest.slice(found[0].length).replace(FILLER, '')
87  }
88  return phrases.length > 0 ? { phrases, rest } : null
89}
90
91/**
92 * Words after the routine phrases that start new work ("merged, go ahead with #214", "push it and fix
93 * the lint"): such a prompt is not routine, whatever it opens with.
94 */
95export const NEW_WORK =
96  /\b(?:start|begin|work\s+on|take|tackle|fix|implement|build|add|write|create|make|proceed|move\s+on|run|deploy|refactor|update|change|rename|remove|delete|investigate|look|check|debug|test|handle|address|file|install|download|train|generate|render|print|go\s+(?:ahead\s+)?(?:with|on)|continue|keep\s+going|do\b|try)\b|\b(?:with|on|to)\s+#?[A-Za-z]*-?\d/i
97
98export type Classified = { cls: RouteClass; why: string }
99
100/**
101 * Routine: at most 120 characters, opening with routine phrases and little else. Deep: deep wording
102 * anywhere. Both at once ("commit and push, then review the diff") is no opinion: the session's own effort.
103 */
104export function classify(text: string, patterns: Patterns): Classified {
105  const trimmed = text.trim()
106  const lead = leadingRoutine(trimmed, patterns.routine)
107  const isRoutine =
108    lead !== null &&
109    trimmed.length <= ROUTINE_MAX_CHARS &&
110    wordCount(lead.rest) <= ROUTINE_MAX_EXTRA_WORDS &&
111    !NEW_WORK.test(lead.rest)
112  const deep = patterns.deep.exec(trimmed)
113  if (isRoutine && deep) {
114    return { cls: 'neutral', why: `both routine ("${lead.phrases.join(', ')}") and deep ("${deep[0]}")` }
115  }
116  if (isRoutine) {
117    return { cls: 'routine', why: `starts with "${lead.phrases.join(', ')}"` }
118  }
119  if (deep) {
120    return { cls: 'deep', why: `mentions "${deep[0]}"` }
121  }
122  if (lead !== null) {
123    return { cls: 'neutral', why: trimmed.length > ROUTINE_MAX_CHARS ? 'too long to be routine' : 'more than a routine reply' }
124  }
125  return { cls: 'neutral', why: 'no routine or deep wording' }
126}
127
128export type Guard = {
129  /** Turns in a row a lower effort must be wanted before it is sent over a warm, large cache. */
130  stickyTurns: number
131  /** Below this many context tokens a switch costs little: it is made at once. */
132  freeSwitchTokens: number
133  /** Idle longer than this and the cache has lapsed: a switch costs nothing extra. */
134  cacheTtlMs: number
135}
136
137export type Why = 'same' | 'forced' | 'off' | 'model' | 'base' | 'history' | 'cold' | 'small' | 'up' | 'streak' | 'hold'
138
139export type Ask = {
140  want: Level
141  /** The model this request names (after the model guard). */
142  model: string
143  /** The session's own effort, as the engine offers it on this request. */
144  base: Level
145  messageCount: number
146  now: number
147  isForced: boolean
148}
149
150export type Decision = { effort: Level; why: Why; lowerStreak: number }
151
152/**
153 * The effort a new turn is sent at, given what the prompt cache was written with.
154 *
155 * Claude Code sends effort as the request's top-level `output_config.effort`, and the API renders it
156 * into the prompt: a change invalidates the cached messages (on some models the system prompt and
157 * tools too), so the next request re-writes the whole conversation at the cache-write price. So a
158 * switch is made at once only when it is cheap or asked for: the person forced it, the model or the
159 * session's own effort changed (the cache is cold for it anyway), the history shrank (compaction,
160 * /clear), the cache has lapsed (idle past its TTL), the context is small, or the turn wants MORE
161 * effort (quality never waits). A turn wanting LESS effort over a warm, large cache is held at the
162 * current effort until `stickyTurns` turns in a row have wanted less.
163 */
164export function decide(cache: RouteCache, ask: Ask, guard: Guard): Decision {
165  const switchTo = (why: Why): Decision => ({ effort: ask.want, why, lowerStreak: 0 })
166  if (ask.want === cache.applied) {
167    return switchTo('same')
168  }
169  if (ask.isForced) {
170    return switchTo('forced')
171  }
172  if (ask.model !== cache.model) {
173    return switchTo('model')
174  }
175  if (ask.base !== cache.base) {
176    return switchTo('base')
177  }
178  if (ask.messageCount < cache.messageCount) {
179    return switchTo('history')
180  }
181  if (cache.lastAt !== null && ask.now - cache.lastAt > guard.cacheTtlMs) {
182    return switchTo('cold')
183  }
184  if (cache.contextTokens < guard.freeSwitchTokens) {
185    return switchTo('small')
186  }
187  if (rank(ask.want) > rank(cache.applied)) {
188    return switchTo('up')
189  }
190  const lowerStreak = cache.lowerStreak + 1
191  if (lowerStreak >= Math.max(1, guard.stickyTurns)) {
192    return switchTo('streak')
193  }
194  return { effort: cache.applied, why: 'hold', lowerStreak }
195}
196
197export const EMPTY_COUNTS: RouteCounts = { routine: 0, deep: 0, neutral: 0, switches: 0, holds: 0 }
198
199export const EMPTY_STATE: RouteState = {
200  isOn: true,
201  forced: null,
202  pending: null,
203  turn: null,
204  cache: null,
205  counts: EMPTY_COUNTS,
206  rewrites: [],
207  budget: null,
208  agents: {},
209}
210
211/** A prompt was submitted: classify it (or take the class /route forced) for the turn it starts. */
212export function submitted(state: RouteState, text: string, isPersonal: boolean, patterns: Patterns): RouteState {
213  if (!isPersonal) {
214    return { ...state, pending: { cls: 'neutral', why: 'not typed by you', isForced: false, text } }
215  }
216  if (state.forced !== null) {
217    return { ...state, forced: null, pending: { cls: state.forced, why: 'forced with /route', isForced: true, text } }
218  }
219  return { ...state, pending: { ...classify(text, patterns), isForced: false, text } }
220}
221
222/** A main-loop turn started: it takes the pending prompt's class. */
223export function started(state: RouteState, turnId: string, text: string, patterns: Patterns): RouteState {
224  const pending: RoutePending =
225    state.pending ??
226    (text.trim() === ''
227      ? { cls: 'neutral', why: 'no prompt', isForced: false, text: '' }
228      : { ...classify(text, patterns), isForced: false, text })
229  const turn: RouteTurn = { ...pending, id: turnId, effort: null, want: null, decision: null, streak: 0, cappedAt: null }
230  return { ...state, pending: null, turn }
231}
232
233export type Settings = {
234  routineEffort: Level
235  deepEffort: Level
236  guard: Guard
237  /** Percent of the 5-hour limit used at which every effort is capped; 0 turns the cap off. */
238  budgetCapAt: number
239  /** The most effort any request gets while the cap is in force. */
240  budgetCapEffort: Level
241  /** The effort subagent requests run at; null leaves them at the session's own. */
242  subagentEffort: Level | null
243}
244
245/** Where usage-meter writes its machine-wide summary of the last 5 hours, under the home folder. */
246export const SUMMARY_PATH = '.claude/usage-meter/summary.json'
247/** How long one reading of the summary serves. */
248export const BUDGET_MEMO_MS = 30_000
249/** A summary older than this says nothing about now. */
250export const BUDGET_STALE_MS = 10 * 60_000
251
252/** What usage-meter's summary says: the percent of the 5-hour limit used, or why there is no information. */
253export type BudgetReading = { pct: number | null; note: string }
254
255const NO_SUMMARY: BudgetReading = { pct: null, note: 'no usage-meter summary' }
256
257/**
258 * usage-meter's summary (`{ ts, pct, ... }`) read as budget information: its `pct` when the file parses
259 * and its `ts` is at most 10 minutes old; none when the file is missing, unreadable or stale, or `pct`
260 * is null (no limit has been hit yet, so none is learned).
261 */
262export function parseSummary(text: string | null, now: number): BudgetReading {
263  if (text === null) {
264    return NO_SUMMARY
265  }
266  let parsed: unknown
267  try {
268    parsed = JSON.parse(text)
269  } catch {
270    return NO_SUMMARY
271  }
272  if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
273    return NO_SUMMARY
274  }
275  const { ts, pct } = parsed as { ts?: unknown; pct?: unknown }
276  if (typeof ts !== 'number' || !Number.isFinite(ts)) {
277    return NO_SUMMARY
278  }
279  if (now - ts > BUDGET_STALE_MS) {
280    return { pct: null, note: `summary is ${Math.round((now - ts) / 60_000)} min old` }
281  }
282  if (pct === null) {
283    return { pct: null, note: 'no limit learned yet' }
284  }
285  if (typeof pct !== 'number' || !Number.isFinite(pct)) {
286    return NO_SUMMARY
287  }
288  return { pct, note: '' }
289}
290
291export type BudgetChange = 'engaged' | 'released' | null
292
293/** A fresh reading of the summary: kept for the memo, the cap engaging or releasing as it crosses `capAt`. */
294export function noteBudget(state: RouteState, reading: BudgetReading, now: number, capAt: number): { state: RouteState; change: BudgetChange } {
295  const was = state.budget?.isCapping ?? false
296  const isCapping = capAt > 0 && reading.pct !== null && reading.pct >= capAt
297  const budget: RouteBudget = { checkedAt: now, pct: reading.pct, note: reading.note, isCapping }
298  return { state: { ...state, budget }, change: isCapping === was ? null : isCapping ? 'engaged' : 'released' }
299}
300
301/** The percent used while the cap is in force; null when it is not (cap off, no information, under the threshold). */
302export function cappingPct(state: RouteState, settings: Settings): number | null {
303  const budget = state.budget ?? null
304  return settings.budgetCapAt > 0 && budget !== null && budget.isCapping ? budget.pct : null
305}
306
307/** The effort a turn or subagent wants, lowered to the cap while the budget is in force; a want at or below it is left alone. */
308function capped(want: Level, state: RouteState, settings: Settings): { want: Level; cappedAt: number | null } {
309  const pct = cappingPct(state, settings)
310  return pct !== null && rank(want) > rank(settings.budgetCapEffort) ? { want: settings.budgetCapEffort, cappedAt: pct } : { want, cappedAt: null }
311}
312
313/** The debug-log line when the budget cap engages or releases. */
314export function describeBudgetChange(change: 'engaged' | 'released', budget: RouteBudget, settings: Settings): string {
315  const used =
316    budget.pct === null ? `no budget information (${budget.note})` : `${Math.round(budget.pct)}% of the 5-hour limit used (cap at ${settings.budgetCapAt}%)`
317  return change === 'engaged'
318    ? `effort-router: budget cap engaged: ${used}; turns run at ${settings.budgetCapEffort} or less`
319    : `effort-router: budget cap released: ${used}`
320}
321
322/** What a subagent's request carries. */
323export type AgentFacts = { agentId: string; turnId: string; effort: Level }
324
325/**
326 * The effort a subagent's request is sent at: `subagentEffort` when set, else its own, lowered to the
327 * budget cap while it is in force. Decided at the first request of the agent's turn and kept for the
328 * turn (routing off included), so a subagent never switches midway either.
329 */
330export function planAgentStep(state: RouteState, facts: AgentFacts, settings: Settings): { state: RouteState; effort: Level } {
331  const agents = state.agents ?? {}
332  const pinned = agents[facts.agentId]
333  if (pinned !== undefined && pinned.turnId === facts.turnId) {
334    return { state, effort: pinned.effort }
335  }
336  const want = state.isOn ? capped(settings.subagentEffort ?? facts.effort, state, settings).want : facts.effort
337  const pin: RouteAgentTurn = { turnId: facts.turnId, effort: want }
338  return { state: { ...state, agents: { ...agents, [facts.agentId]: pin } }, effort: want }
339}
340
341/** A subagent's turn ended: the effort pinned for it is dropped. */
342export function agentDone(state: RouteState, agentId: string): RouteState {
343  const agents = state.agents ?? {}
344  if (!(agentId in agents)) {
345    return state
346  }
347  const rest = { ...agents }
348  delete rest[agentId]
349  return { ...state, agents: rest }
350}
351
352/** What a main-loop request carries, as the engine is about to send it. */
353export type StepFacts = {
354  turnId: string
355  /** The model it names, after the model guard. */
356  model: string
357  /** The session's own effort. */
358  base: Level
359  messageCount: number
360  now: number
361  /** The context's size, used only when nothing was seen before (the mod loaded mid-session). */
362  contextTokens: number
363}
364
365export type Planned = { state: RouteState; effort: Level; isNew: boolean; status: string | undefined }
366
367/**
368 * What the status line says while a turn runs; undefined when the turn runs as the session would.
369 * `cappedAt` is the budget percent that lowered the turn's want, when the cap did.
370 */
371export function statusText(cls: RouteClass, decision: Decision, isForced: boolean, stickyTurns: number, cappedAt: number | null = null): string | undefined {
372  const budget = cappedAt === null ? null : `budget ${Math.round(cappedAt)}%`
373  if (decision.why === 'hold') {
374    const lead = budget !== null ? `${budget}, ` : cls === 'neutral' ? '' : `${cls}, `
375    return `effort: ${decision.effort} (${lead}held for the prompt cache ${decision.lowerStreak}/${stickyTurns})`
376  }
377  if (budget !== null) {
378    return `effort: ${decision.effort} (${budget})`
379  }
380  if (cls === 'neutral' || decision.why === 'off') {
381    return undefined
382  }
383  return `effort: ${decision.effort} (${cls}${isForced ? ', forced' : ''})`
384}
385
386/**
387 * The effort a main-loop request is sent at. The turn's first request decides; every later
388 * request of the same turn carries the same effort, so a turn never switches midway.
389 */
390export function planStep(state: RouteState, facts: StepFacts, settings: Settings): Planned {
391  const current = state.turn
392  if (current !== null && current.id === facts.turnId && current.effort !== null) {
393    return { state, effort: current.effort, isNew: false, status: undefined }
394  }
395  const turn: RouteTurn =
396    current !== null && current.id === facts.turnId
397      ? current
398      : { id: facts.turnId, cls: 'neutral', why: 'its prompt was not seen', isForced: false, text: '', effort: null, want: null, decision: null, streak: 0, cappedAt: null }
399  const cache: RouteCache = state.cache ?? {
400    applied: facts.base,
401    model: facts.model,
402    base: facts.base,
403    messageCount: facts.messageCount,
404    contextTokens: facts.contextTokens,
405    lastAt: null,
406    lowerStreak: 0,
407  }
408  const isRouted = state.isOn || turn.isForced
409  const asked: Level = !isRouted || turn.cls === 'neutral' ? facts.base : turn.cls === 'routine' ? settings.routineEffort : settings.deepEffort
410  // The budget cap lowers what any routed turn wants, deep asks included; the cache guard below treats it as any lowering.
411  const { want, cappedAt } = isRouted ? capped(asked, state, settings) : { want: asked, cappedAt: null }
412  const decision: Decision = isRouted
413    ? decide(cache, { want, model: facts.model, base: facts.base, messageCount: facts.messageCount, now: facts.now, isForced: turn.isForced }, settings.guard)
414    : { effort: want, why: 'off', lowerStreak: 0 }
415  const counts: RouteCounts = {
416    ...state.counts,
417    [turn.cls]: state.counts[turn.cls] + 1,
418    switches: state.counts.switches + (decision.effort === cache.applied ? 0 : 1),
419    holds: state.counts.holds + (decision.why === 'hold' ? 1 : 0),
420  }
421  return {
422    state: {
423      ...state,
424      turn: { ...turn, effort: decision.effort, want, decision: decision.why, streak: decision.lowerStreak, cappedAt },
425      cache: {
426        ...cache,
427        applied: decision.effort,
428        model: facts.model,
429        base: facts.base,
430        messageCount: facts.messageCount,
431        lowerStreak: decision.lowerStreak,
432      },
433      counts,
434    },
435    effort: decision.effort,
436    isNew: true,
437    status: statusText(turn.cls, decision, turn.isForced, Math.max(1, settings.guard.stickyTurns), cappedAt),
438  }
439}
440
441/** Prompt tokens a response was answered over plus its output: what the next request re-sends. */
442export const contextOf = (usage: ModelUsage): number =>
443  usage.input_tokens + usage.cache_read_input_tokens + usage.cache_creation_input_tokens + usage.output_tokens
444
445/** A main-loop response arrived: remember how big the cached prefix now is, and when it was written. */
446export function responded(
447  state: RouteState,
448  facts: { model: string; messageCount: number; now: number; usage: ModelUsage | null },
449): RouteState {
450  if (state.cache === null) {
451    return state
452  }
453  const cache: RouteCache =
454    facts.usage === null
455      ? { ...state.cache, model: facts.model, messageCount: facts.messageCount }
456      : { ...state.cache, model: facts.model, messageCount: facts.messageCount, contextTokens: contextOf(facts.usage), lastAt: facts.now }
457  return { ...state, cache }
458}
459
460/** /clear: a new conversation whose first request writes a fresh cache, so the next switch is free. */
461export function cleared(state: RouteState): RouteState {
462  return {
463    ...state,
464    pending: null,
465    turn: null,
466    counts: EMPTY_COUNTS,
467    cache: state.cache === null ? null : { ...state.cache, messageCount: 0, contextTokens: 0, lastAt: null, lowerStreak: 0 },
468    agents: {},
469  }
470}
471
472/** Current model ids for the family aliases, so a rewrite never depends on the engine resolving an alias. */
473export const MODEL_IDS: Readonly<Record<string, string>> = {
474  opus: 'claude-opus-5-5',
475  sonnet: 'claude-sonnet-5-5',
476  haiku: 'claude-haiku-5-5',
477  fable: 'claude-fable-5-1',
478}
479
480/**
481 * The model id a fallback names: a family alias becomes its current id, spelled with the provider
482 * prefix the engine's own id carries (`us.anthropic.`); anything else is taken as written.
483 */
484export function resolveModel(fallback: string, current: string): string {
485  const name = fallback.trim()
486  const id = MODEL_IDS[name.toLowerCase()]
487  if (id === undefined) {
488    return name
489  }
490  const at = current.indexOf('claude-')
491  return (at > 0 ? current.slice(0, at) : '') + id
492}
493
494/** The model a request goes to: the fallback when the engine's matches `avoid` (and the fallback does not). */
495export function guardModel(model: string, avoid: RegExp | null, fallback: string): string {
496  if (avoid === null || !avoid.test(model)) {
497    return model
498  }
499  const target = resolveModel(fallback, model)
500  return target === '' || avoid.test(target) ? model : target
501}
502
503const clip = (text: string, max: number): string => {
504  const line = text.replace(/\s+/g, ' ').trim()
505  return line.length > max ? `${line.slice(0, max - 1)}…` : line
506}
507
508const WHY_WORDS: Readonly<Record<string, string>> = {
509  same: 'no change',
510  forced: 'forced',
511  off: 'routing off',
512  model: 'switched with the model',
513  base: 'your own /effort changed',
514  history: 'after compaction',
515  cold: 'cache had lapsed',
516  small: 'small context',
517  up: 'more effort never waits',
518  streak: 'lower effort wanted turns in a row',
519  hold: 'held for the prompt cache',
520}
521
522export type Describe = {
523  settings: Settings
524  /** e.g. `models matching /fable/i run on claude-opus-5-5`, or null when off. */
525  modelGuard: string | null
526  errors: readonly string[]
527}
528
529const formatTokens = (n: number): string => (n >= 1000 ? `${Math.round(n / 1000)}k` : String(n))
530
531/** The /route line about the last turn: its class, prompt and why, and the effort it got or is held at. */
532function lastTurnLine(turn: RouteTurn): string {
533  const quoted = turn.text === '' ? '' : ` "${clip(turn.text, 60)}"`
534  const cappedAt = turn.cappedAt ?? null
535  const budget = cappedAt === null ? null : `budget ${Math.round(cappedAt)}%`
536  const effort =
537    turn.effort === null
538      ? 'effort not chosen yet'
539      : turn.decision === 'hold'
540        ? `${turn.effort}, held for the prompt cache (wanted ${turn.want ?? '?'}${budget === null ? '' : `: ${budget}`})`
541        : budget !== null
542          ? `${turn.effort} (${budget})`
543          : `${turn.effort} (${WHY_WORDS[turn.decision ?? 'same'] ?? turn.decision})`
544  return `Last turn: ${turn.cls}${quoted}, ${turn.why} → ${effort}`
545}
546
547/** The /route lines about the budget cap (the last reading, the threshold and effort, whether it is in force) and subagents. */
548function budgetLines(state: RouteState, settings: Settings): string[] {
549  const subagents = settings.subagentEffort === null ? "Subagents: the session's own effort" : `Subagents: run at ${settings.subagentEffort}`
550  if (settings.budgetCapAt <= 0) {
551    return ['Budget cap: off', subagents]
552  }
553  const budget = state.budget ?? null
554  const used = budget === null ? 'not read yet' : budget.pct === null ? `unknown (${budget.note})` : `${Math.round(budget.pct)}% of the 5-hour limit used`
555  const standing = budget === null || !budget.isCapping ? 'not engaged' : state.isOn ? 'engaged' : 'not applied while routing is off'
556  return [`Budget: ${used} · cap at ${settings.budgetCapAt}% → ${settings.budgetCapEffort}: ${standing}`, subagents]
557}
558
559/** What /route prints. */
560export function describeRoute(state: RouteState, info: Describe): string {
561  const { settings } = info
562  const effortFor = (cls: 'routine' | 'deep'): Level => (cls === 'routine' ? settings.routineEffort : settings.deepEffort)
563  const lines = [state.isOn ? 'effort-router: on' : 'effort-router: off for this session (/route on resumes; /route deep or routine still apply)']
564  if (state.forced !== null) {
565    lines.push(`Next prompt: forced ${state.forced} (${effortFor(state.forced)})`)
566  }
567  lines.push(state.turn === null ? 'No turn routed yet.' : lastTurnLine(state.turn))
568  const c = state.counts
569  lines.push(
570    `This session: ${c.routine} routine, ${c.deep} deep, ${c.neutral} neutral turns · ${c.switches} effort ${c.switches === 1 ? 'switch' : 'switches'} · ${c.holds} held for the prompt cache`,
571    `Routine → ${settings.routineEffort}, deep → ${settings.deepEffort}, neutral → the session's own effort.`,
572    `Cache guard: a switch is made at once under ${formatTokens(settings.guard.freeSwitchTokens)} context tokens, after ${Math.round(settings.guard.cacheTtlMs / 60_000)} min idle, or toward more effort; less effort waits for ${Math.max(1, settings.guard.stickyTurns)} turns in a row.`,
573  )
574  if (state.cache !== null) {
575    lines.push(`Prompt cache: written at ${state.cache.applied} over about ${formatTokens(state.cache.contextTokens)} tokens.`)
576  }
577  lines.push(info.modelGuard === null ? 'Model guard: off' : `Model guard: ${info.modelGuard}`)
578  lines.push(...budgetLines(state, settings), ...info.errors)
579  return lines.join('\n')
580}
581
types/index.d.ts 100 lines
1/** The effort levels a `turn.step` request can name, lowest first. */
2export type RouteLevel = 'low' | 'medium' | 'high' | 'xhigh' | 'max'
3
4/** What a prompt asks for: little thought, deep thought, or no opinion. */
5export type RouteClass = 'routine' | 'deep' | 'neutral'
6
7/** A prompt's class, waiting for the turn it starts. */
8export type RoutePending = {
9  cls: RouteClass
10  /** Why it got that class, for /route ("starts with \"merged\""). */
11  why: string
12  /** True when /route deep or /route routine chose the class. */
13  isForced: boolean
14  text: string
15}
16
17/** The main loop's current (or last) turn and the effort chosen for it. */
18export type RouteTurn = RoutePending & {
19  id: string
20  /** The effort every request of the turn carries; null until its first request. */
21  effort: RouteLevel | null
22  /** The effort the class asked for; differs from `effort` while the cache guard holds. */
23  want: RouteLevel | null
24  /** Why `effort` was chosen (`same`, `small`, `up`, `hold`, ...). */
25  decision: string | null
26  /** Turns in a row that wanted less effort than was being sent, this one included. */
27  streak: number
28  /** The percent of the 5-hour budget used when its cap lowered this turn's wanted effort; null when the cap did not. */
29  cappedAt: number | null
30}
31
32/** What the prompt cache was last written with on the main loop, so a switch is only made when it pays. */
33export type RouteCache = {
34  /** The effort the main loop's last request carried. */
35  applied: RouteLevel
36  /** The model the main loop's last request named. */
37  model: string
38  /** The session's own effort, as the engine last offered it. */
39  base: RouteLevel
40  /** How many messages the main loop's last request carried. */
41  messageCount: number
42  /** Prompt tokens the last response was answered over, plus its output: what the next request re-sends. */
43  contextTokens: number
44  /** When the last main-loop response arrived; null before one has. */
45  lastAt: number | null
46  /** Turns in a row that wanted less effort than `applied`. */
47  lowerStreak: number
48}
49
50export type RouteCounts = {
51  routine: number
52  deep: number
53  neutral: number
54  /** Turns whose effort differed from the turn before (each one rewrites the prompt cache). */
55  switches: number
56  /** Turns kept at the previous effort to spare the prompt cache. */
57  holds: number
58}
59
60/** usage-meter's reading of the machine-wide 5-hour budget, as last read (one reading serves 30 s). */
61export type RouteBudget = {
62  /** When the summary was last read, for the memo. */
63  checkedAt: number
64  /** Percent of the last learned 5-hour limit already used; null without budget information. */
65  pct: number | null
66  /** Why there is no information ("no usage-meter summary", "summary is 12 min old", "no limit learned yet"); "" when pct is known. */
67  note: string
68  /** True while pct is at or over budgetCapAt: every turn and subagent is capped at budgetCapEffort. */
69  isCapping: boolean
70}
71
72/** A subagent's running turn and the effort chosen at its first request, kept for the turn. */
73export type RouteAgentTurn = {
74  turnId: string
75  effort: RouteLevel
76}
77
78export type RouteState = {
79  /** /route off turns automatic routing off for the session; /route deep and /route routine still apply. */
80  isOn: boolean
81  /** A class /route forced on the next prompt. */
82  forced: 'routine' | 'deep' | null
83  pending: RoutePending | null
84  turn: RouteTurn | null
85  cache: RouteCache | null
86  counts: RouteCounts
87  /** Model rewrites already announced with a toast (`from→to`). */
88  rewrites: string[]
89  /** The last budget reading; null before one, or while the cap is off. */
90  budget: RouteBudget | null
91  /** Subagents with a turn running, by agent id, each with the effort its turn keeps. */
92  agents: Record<string, RouteAgentTurn>
93}
94
95declare module 'claude-code' {
96  interface PluginState {
97    'effort-router': { router: RouteState }
98  }
99}
100