Picks the main conversation's model for each typed prompt, and caps reasoning effort at xhigh.

Picks the main conversation's model for each typed prompt or skill; caps effort at xhigh.
For selection, routing, and fallback rules, see the model state diagrams.
/automodel on, /automodel off or /automodel status, or click the Auto Model: On/Off chip at the right of the prompt footer. The setting is saved across sessions.trivial, moderate, complex or frontier (8 tokens, 4 seconds). Those tiers map to the haiku, sonnet, opus and fable lines that the /config model row offers. A 10-second toast names the new model.$TMPDIR/claude-auto-model/<session-id> (auto before the first prompt is routed), and .claude/scripts/statusline.sh shows Auto until a turn picks a model, then Opus 5.5 medium (complex). The OS clears the temp folder, so files from ended sessions don't pile up.SKILL.md declares, read from the project's .claude/skills/ first, then ~/.claude/skills/: metadata:
model-tier: trivial # trivial | moderate | complex | frontier
| Tier | Model line |
|---|---|
trivial | haiku |
moderate | sonnet |
complex | opus |
frontier | fable |
A skill without a tier, or a plugin's skill, is sorted by its description. Successful classifications are kept until the description changes; failed attempts are retried on the next invocation. For how to pick a tier, see model tier.
/model or /config) also turns it off, and keeps the model you picked./effort max becomes xhigh, and every request, helper agents included, is sent at xhigh at most, even while Auto Model is off.[!NOTE] Switching models writes
modelto~/.claude/settings.json, as/modeldoes. A new session starts on the last model Auto Model picked. The nextmake install-clauderesets it to the template's default.
hooks/register.tsx 342 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { AutoModelLevel } from '../types'
5import {
6 CLASSIFIER_SYSTEM,
7 availableLines,
8 candidatesFor,
9 clampEffort,
10 clampEffortArgs,
11 displayName,
12 isShortReply,
13 isSlashCommand,
14 isWarm,
15 lineOf,
16 parseLevel,
17 rankOf,
18 requestText,
19 skillPaths,
20 tierFromFrontmatter,
21 tierPath,
22} from './logic'
23
24const COMMAND = 'automodel'
25const STORE_ON = 'isOn'
26const STORE_PREVIOUS = 'previousModel'
27const TOAST_MS = 10_000
28const MAX_CLASSIFIER_CHARS = 12_000
29
30const GOLD = '#F2C46D'
31const SLATE = '#262B33'
32const INK = '#0D1117'
33const TEXT = '#E6EDF3'
34const MUTED = '#7D8590'
35
36const isOn = atom({ plugin: 'auto-model', key: 'isOn' } as const, false)
37const pendingModel = atom({ plugin: 'auto-model', key: 'pendingModel' } as const, null)
38// When the last main-loop turn ended; null before the session's first.
39const lastTurnAt = atom({ plugin: 'auto-model', key: 'lastTurnAt' } as const, null)
40const hasRoutedTier = atom({ plugin: 'auto-model', key: 'hasRoutedTier' } as const, false)
41
42type $ = EngineInterface
43
44const refusedLines = new Set<string>()
45
46async function modelRow($: $) {
47 return (await $.config.list()).find(row => row.key === 'model')
48}
49
50/**
51 * The classifier's tier, or no decision when classification fails. Each
52 * outcome goes to the debug log; failure leaves the current model alone.
53 */
54async function classify($: $, text: string, smallest: string): Promise<AutoModelLevel | undefined> {
55 let why: string
56 try {
57 const reply = await $.model.complete({
58 model: smallest,
59 effort: 'low',
60 system: CLASSIFIER_SYSTEM,
61 prompt: text.slice(0, MAX_CLASSIFIER_CHARS),
62 maxTokens: 8,
63 timeoutMs: 4000,
64 })
65 const level = reply.isAnswered ? parseLevel(reply.text) : undefined
66 if (level !== undefined) {
67 $.ui.log(`auto-model: classifier said ${level}`, { to: 'debug' })
68 return level
69 }
70 why = reply.isAnswered ? `unreadable answer ${JSON.stringify(reply.text)}` : reply.reason
71 } catch (err) {
72 why = String(err)
73 }
74 $.ui.log(`auto-model: classifier gave no tier (${why}); keeping current model`, { to: 'debug' })
75 return undefined
76}
77
78/** The `model-tier` the skill's own SKILL.md declares, project copy first. */
79async function declaredTier($: $, name: string): Promise<AutoModelLevel | undefined> {
80 for (const path of skillPaths(name, await $.session.cwd(), await $.env.get('HOME'))) {
81 try {
82 return tierFromFrontmatter(await $.fs.read(path))
83 } catch {
84 // No skill file here; try the next place.
85 }
86 }
87 return undefined
88}
89
90/**
91 * The tier for a slash command: the skill's `metadata.model-tier`, else its
92 * description, classified once and kept until the description changes.
93 * Built-in and MCP commands, and this mod's own, have none.
94 */
95async function commandLevel($: $, command: string, smallest: string): Promise<AutoModelLevel | undefined> {
96 if (command === COMMAND) return undefined
97 const info = (await $.command.list()).find(c => c.name === command)
98 if (info === undefined || (info.source !== 'user' && info.source !== 'plugin')) return undefined
99 const declared = await declaredTier($, info.name)
100 if (declared !== undefined) return declared
101 const key = `skill:${info.name}:${info.description}`
102 const kept = await $.store.get(key)
103 if (typeof kept === 'string' && parseLevel(kept) !== undefined) return parseLevel(kept)
104 const level = await classify($, `/${info.name}: ${info.description}`, smallest)
105 if (level !== undefined) await $.store.set(key, level)
106 return level
107}
108
109/**
110 * Writes the tier of the model in use for the status line; '' clears it. A
111 * failed write only loses the label, so it never stops a switch or turn-off.
112 */
113async function recordTier($: $, tier: AutoModelLevel | 'auto' | '') {
114 await update($, hasRoutedTier, () => tier !== '' && tier !== 'auto')
115 try {
116 const path = tierPath(await $.env.get('TMPDIR'), await $.session.id())
117 if (path !== undefined) await $.fs.write(path, tier)
118 } catch (err) {
119 $.ui.log(`auto-model: could not record the tier: ${String(err)}`, { to: 'debug' })
120 }
121}
122
123/**
124 * Switches to the best line for `level` the plan accepts; quiet when already
125 * there. With `stepUpOnly` it never moves to a smaller line, and the tier on
126 * the status line stays the bigger model's.
127 */
128async function switchTo($: $, level: AutoModelLevel, current: string, lines: readonly string[], stepUpOnly = false) {
129 for (const line of candidatesFor(level, lines)) {
130 if (refusedLines.has(line)) continue
131 if (lineOf(current) === line) return recordTier($, level)
132 if (stepUpOnly && rankOf(line) <= rankOf(current)) return
133 const set = await $.config.set({ key: 'model', value: line })
134 if (set.deny !== undefined) {
135 refusedLines.add(line)
136 continue
137 }
138 const model = await $.session.model()
139 await update($, pendingModel, () => model)
140 await recordTier($, level)
141 $.ui.toast(`Auto Model: ${displayName(model)} (${level})`, { timeoutMs: TOAST_MS })
142 return
143 }
144}
145
146async function turnOn($: $): Promise<string> {
147 if (await read($, isOn)) return 'Auto Model is already on.'
148 const row = await modelRow($)
149 await $.store.set(STORE_PREVIOUS, row?.value ?? null)
150 await $.store.set(STORE_ON, true)
151 await update($, isOn, () => true)
152 await recordTier($, 'auto')
153 return 'Auto Model is on. Each new prompt picks its model.'
154}
155
156/** Turns it off; `restore` puts back the model in use before it was turned on. */
157async function turnOff($: $, restore: boolean): Promise<string> {
158 if (!(await read($, isOn))) return 'Auto Model is already off.'
159 await $.store.set(STORE_ON, false)
160 await update($, isOn, () => false)
161 await update($, pendingModel, () => null)
162 await recordTier($, '')
163 const previous = await $.store.get(STORE_PREVIOUS)
164 await $.store.delete(STORE_PREVIOUS)
165 if (!restore || typeof previous !== 'string') return 'Auto Model is off.'
166 let set = await $.config.set({ key: 'model', value: previous })
167 const line = lineOf(previous)
168 if (set.deny !== undefined && line !== undefined) {
169 set = await $.config.set({ key: 'model', value: line })
170 }
171 return set.deny === undefined
172 ? `Auto Model is off. Model is back to ${displayName(previous)}.`
173 : `Auto Model is off. Could not restore ${previous}: ${set.deny}`
174}
175
176async function status($: $): Promise<string> {
177 const on = await read($, isOn)
178 const model = displayName(await $.session.model())
179 const previous = await $.store.get(STORE_PREVIOUS)
180 const before = on && typeof previous === 'string' ? ` It restores ${displayName(previous)} when turned off.` : ''
181 return `Auto Model is ${on ? 'on' : 'off'}. Current model: ${model}.${before}`
182}
183
184export const register: Register = on => {
185 on('session.start', async ($, e, next) => {
186 try {
187 refusedLines.clear()
188 await update($, isOn, () => false)
189 if ((await $.store.get(STORE_ON)) === true) {
190 await update($, isOn, () => true)
191 if (!(await read($, hasRoutedTier)) && (await read($, lastTurnAt)) === null) await recordTier($, 'auto')
192 }
193 await $.command.register({
194 name: COMMAND,
195 description: 'Auto Model: pick the model for each prompt (on, off, status)',
196 argumentHint: 'on|off|status',
197 immediate: true,
198 })
199 } catch (err) {
200 $.ui.log(`auto-model: could not start: ${String(err)}`, { to: 'debug' })
201 }
202 return next(e)
203 })
204
205 on('session.end', async ($, e, next) => {
206 await update($, hasRoutedTier, () => false)
207 await update($, lastTurnAt, () => null)
208 return next(e)
209 })
210
211 on('command.run', { command: COMMAND }, async ($, e) => {
212 try {
213 const arg = e.args.trim().toLowerCase()
214 if (arg === 'on') return { text: await turnOn($) }
215 if (arg === 'off') return { text: await turnOff($, true) }
216 if (arg === '' || arg === 'status') return { text: await status($) }
217 return { text: 'Use /automodel on, /automodel off or /automodel status.' }
218 } catch (err) {
219 return { text: `Auto Model could not do that: ${String(err)}` }
220 }
221 }).catch(() => ({ text: 'Auto Model could not do that. Try again.' }))
222
223 on('prompt.submit', async ($, e, next) => {
224 try {
225 const lastTurn = await read($, lastTurnAt)
226 const skip =
227 !(await read($, isOn)) ||
228 e.origin.kind !== 'composer' ||
229 e.turnId !== undefined ||
230 isSlashCommand(e.text) ||
231 isShortReply(e.text, lastTurn !== null)
232 if (!skip) {
233 const row = await modelRow($)
234 const lines = availableLines(row?.options)
235 if (lines.length > 0) {
236 const level = await classify($, requestText(e.text), lines[0] ?? 'haiku')
237 if (level !== undefined) {
238 // A prompt while the cache is warm is likely the same task, so only a
239 // bigger tier is worth re-sending the history uncached. A skill (below)
240 // gets the same check.
241 const warm = isWarm(lastTurn, await $.clock.now())
242 await switchTo($, level, await $.session.model(), lines, warm)
243 }
244 }
245 }
246 } catch (err) {
247 $.ui.log(`auto-model: prompt.submit: ${String(err)}`, { to: 'debug' })
248 }
249 return next(e)
250 }).catch(($, e, next) => next(e))
251
252 // A skill (`/commit`) switches by its level; prompts are handled above. While
253 // the cache is warm, a skill only switches up, same as a prompt.
254 on('command.run', async ($, e, next) => {
255 try {
256 if (e.origin.kind === 'composer' && (await read($, isOn))) {
257 const lines = availableLines((await modelRow($))?.options)
258 const level = lines.length > 0 ? await commandLevel($, e.command, lines[0] ?? 'haiku') : undefined
259 const warm = isWarm(await read($, lastTurnAt), await $.clock.now())
260 if (level !== undefined) await switchTo($, level, await $.session.model(), lines, warm)
261 }
262 } catch (err) {
263 $.ui.log(`auto-model: command.run: ${String(err)}`, { to: 'debug' })
264 }
265 return next(e)
266 }).catch(($, e, next) => next(e))
267
268 // Picking a model by hand turns Auto Model off, so the two never fight.
269 on('config.set', { key: 'model' }, async ($, e, next) => {
270 try {
271 if (e.origin.kind !== 'plugin' && (await read($, isOn))) await turnOff($, false)
272 } catch (err) {
273 $.ui.log(`auto-model: config.set: ${String(err)}`, { to: 'debug' })
274 }
275 return next(e)
276 }).catch(($, e, next) => next(e))
277
278 on('command.run', { command: 'model' }, async ($, e, next) => {
279 try {
280 if (e.origin.kind !== 'plugin' && (await read($, isOn))) await turnOff($, false)
281 } catch (err) {
282 $.ui.log(`auto-model: /model: ${String(err)}`, { to: 'debug' })
283 }
284 return next(e)
285 }).catch(($, e, next) => next(e))
286
287 // Effort never goes above xhigh: `/effort max` is rewritten, and every
288 // request (main loop and helper agents) is clamped on its way out.
289 on('command.run', { command: 'effort' }, ($, e, next) =>
290 next({ ...e, args: clampEffortArgs(e.args) }),
291 ).catch(($, e, next) => next(e))
292
293 on('turn.step', async function* ($, e, next) {
294 let model = e.model
295 if (e.agentId === undefined) {
296 const pending = await read($, pendingModel)
297 if (pending !== null) model = pending
298 }
299 return yield* next({ ...e, model, effort: clampEffort(e.effort) })
300 })
301
302 on('turn.complete', async ($, e, next) => {
303 if (e.agentId === undefined) {
304 await update($, pendingModel, () => null)
305 const now = await $.clock.now()
306 await update($, lastTurnAt, () => now)
307 if ((await read($, isOn)) && !(await read($, hasRoutedTier))) await recordTier($, '')
308 }
309 return next(e)
310 })
311
312 on('ui.render', { component: 'SessionMode' }, async ($, e, next) => {
313 const enabled = await read($, isOn)
314 const { Box, Text, Button } = $.ui.resolve(e)
315 const columns = e.viewport?.columns ?? 80
316 const state = enabled ? 'On' : 'Off'
317 const label = columns < 60 ? `Auto: ${state}` : `Auto Model: ${state}`
318 const modes = e.props.modes.join(' & ')
319 return (
320 <Box flexDirection="row">
321 {modes !== '' && (
322 <Text color={MUTED} wrap="truncate">
323 {modes}{' '}
324 </Text>
325 )}
326 <Button
327 key="auto-model-toggle"
328 plain
329 onPress={async () => {
330 if (await read($, isOn)) await turnOff($, true)
331 else await turnOn($)
332 }}
333 >
334 <Text backgroundColor={enabled ? GOLD : SLATE} color={enabled ? INK : TEXT} bold={enabled}>
335 {` ${label} `}
336 </Text>
337 </Button>
338 </Box>
339 )
340 })
341}
342hooks/logic.ts 147 lines1import type { AutoModelLevel } from '../types'
2
3export const LEVELS: readonly AutoModelLevel[] = ['trivial', 'moderate', 'complex', 'frontier']
4
5// The four model lines, smallest first, as the /config model row names them.
6// Aliases, not dated ids, so they follow whatever this install ships.
7export const LINES = ['haiku', 'sonnet', 'opus', 'fable'] as const
8
9export const CLASSIFIER_SYSTEM = [
10 'Sort the request into exactly one tier. Answer with the one word only.',
11 'Classify the immediate action requested in this turn, not broader project goals mentioned as background.',
12 'Words that only name a command, file or tool are not the task: "update the skill\'s review subcommand" is moderate.',
13 'trivial: quick, mechanical jobs and short writing. Commit, branch, summarize, sort, extract, rename, translate, reformat, small wording-only instruction edits, a short factual answer, a repo-state check (is a commit, branch or slice merged, what changed, who touched a file), an email, a post, a PR body, a ticket, a small edit.',
14 'moderate: the default for hands-on work. Building or changing software, debugging, fixing tests, audits of code quality or behaviour, long documents, anything touching several files; also targeted documentation lookups and bounded troubleshooting before codifying a fix as a reusable instruction.',
15 'complex: project planning and big-picture thinking. Specs, plans, slices, task lists, open-ended research, architecture, substantial architectural decisions, code or security review (including updating a spec, plan, slice, or task list to cover how a feature will be implemented or tested).',
16 'frontier: only the very hardest thinking. Redesigning a whole codebase or system, planning a very large migration, deep research that runs for hours.',
17 'Examples: "Pi shows unclickable links; how can we codify a fix?" -> moderate; "design a new terminal rendering architecture" -> complex; "apply this exact wording to AGENTS.md and commit" -> trivial.',
18 'When unsure between moderate and complex, say moderate.',
19].join('\n')
20
21/** Reads the classifier's one-word answer; undefined when it named no tier. */
22export function parseLevel(text: string): AutoModelLevel | undefined {
23 const word = text.toLowerCase().match(/\b(trivial|moderate|complex|frontier)\b/)
24 return word ? (word[1] as AutoModelLevel) : undefined
25}
26
27const ACKS = new Set([
28 'yes', 'y', 'yep', 'yeah', 'ok', 'okay', 'k', 'sure', 'no', 'nope', 'thanks',
29 'thank you', 'go', 'go ahead', 'go on', 'continue', 'keep going', 'do it',
30 'proceed', 'proceed with edits', 'proceed with the edits',
31 'proceed with updates', 'proceed with the updates',
32 'proceed with changes', 'proceed with the changes',
33 'apply', 'implement', 'approve', 'approved',
34 'lgtm', 'sounds good', 'looks good', 'carry on', 'ship it',
35 'yes please', 'please do', 'next',
36 'show a diff', 'show the diff', 'show full diff', 'show the full diff',
37 'show a full diff', 'show proposed diff', 'show the proposed diff',
38 'show a proposed diff',
39])
40
41/** A slash command (`/compact`, `/commit args`), not a leading file path (`/var/folders/...`). */
42export function isSlashCommand(text: string): boolean {
43 return /^\/[a-zA-Z0-9:_-]+(?:\s|$)/.test(text.trimStart())
44}
45
46/** A reply to what Claude just said: a plain go-ahead, or under four words after a turn. */
47export function isShortReply(text: string, hasPriorTurn = true): boolean {
48 const plain = text.toLowerCase().replace(/[^\p{L}\p{N}\s']/gu, ' ').replace(/\s+/g, ' ').trim()
49 if (plain === '') return true
50 if (ACKS.has(plain)) return true
51 if (!hasPriorTurn) return false
52 return plain.split(' ').length < 4
53}
54
55const FENCED = /^(`{3,}|~{3,})[^\n]*\n[\s\S]*?^\1[ \t]*$/gm
56const INLINE_CODE = /`[^`\n]+`/g
57const QUOTED = /^>.*$/gm
58
59/**
60 * What the user wrote, without fenced blocks, inline code or `>` quotes, in one
61 * line: a quoted word (`review`) names a thing, not the task. Pastes arrive
62 * unmarked, so only fenced or quoted ones are left out. All quoted: as given.
63 */
64export function requestText(text: string): string {
65 const own = text.replace(FENCED, ' ').replace(INLINE_CODE, ' ').replace(QUOTED, ' ').replace(/\s+/g, ' ').trim()
66 return own === '' ? text : own
67}
68
69// How long the prompt cache keeps a conversation after its last request. A
70// switch inside it re-sends the whole history uncached, so only a step up is
71// worth that; once it has lapsed, a switch costs nothing extra.
72export const WARM_MS = 60 * 60 * 1000
73
74/** True while the last main-loop turn is recent enough for its cache to be warm. */
75export function isWarm(lastTurnAt: number | null, now: number): boolean {
76 return lastTurnAt !== null && now - lastTurnAt < WARM_MS
77}
78
79/** A line's place, smallest first; -1 for a model outside the four lines. */
80export function rankOf(model: string): number {
81 const line = lineOf(model)
82 return line === undefined ? -1 : LINES.indexOf(line as (typeof LINES)[number])
83}
84
85/** The model lines this install offers, smallest first. */
86export function availableLines(options: readonly string[] | undefined): string[] {
87 return LINES.filter(line => options?.includes(line) ?? false)
88}
89
90/**
91 * The lines to try for a level, best fit first, then each smaller one: the
92 * step-down order when the plan refuses a model. A level whose own line is
93 * missing starts at the nearest smaller line.
94 */
95export function candidatesFor(level: AutoModelLevel, lines: readonly string[]): string[] {
96 const order = LINES.slice(0, LEVELS.indexOf(level) + 1).reverse()
97 const found = order.filter(line => lines.includes(line))
98 return found.length > 0 ? found : [...lines]
99}
100
101/** The line a model id or alias belongs to (`claude-opus-5-5` is `opus`). */
102export function lineOf(model: string): string | undefined {
103 const lower = model.toLowerCase()
104 return LINES.find(line => lower === line || lower.includes(`-${line}`) || lower.startsWith(`${line}`))
105}
106
107/** `claude-opus-5-5` reads `Opus 5.5`; anything else is shown as given. */
108export function displayName(model: string): string {
109 const [, line, version] = model.match(/^claude-([a-z]+)-(\d+(?:-\d+)*)/i) ?? []
110 if (line === undefined || version === undefined) return model
111 return `${line.charAt(0).toUpperCase()}${line.slice(1)} ${version.replace(/-/g, '.')}`
112}
113
114/** Never send `max`: it becomes `xhigh`. Other values pass unchanged. */
115export function clampEffort<T>(effort: T): T | 'xhigh' {
116 return effort === 'max' ? 'xhigh' : effort
117}
118
119/** `/effort max` (in any case) is rewritten to `/effort xhigh`. */
120export function clampEffortArgs(args: string): string {
121 return args.replace(/\bmax\b/gi, 'xhigh')
122}
123
124/** The `metadata.model-tier` a SKILL.md declares; undefined when absent or unknown. */
125export function tierFromFrontmatter(text: string): AutoModelLevel | undefined {
126 const frontmatter = text.match(/^---\r?\n([\s\S]*?)\r?\n---/)?.[1]
127 const metadata = frontmatter?.match(/^metadata:[ \t]*\r?\n((?:[ \t]+.*(?:\r?\n|$))*)/m)?.[1]
128 const value = metadata?.match(/^[ \t]+model-tier:[ \t]*["']?([A-Za-z]+)["']?[ \t]*$/m)?.[1]?.toLowerCase()
129 return LEVELS.find(level => level === value)
130}
131
132/** Where a skill named `name` may live, project first; none for a non-plain name. */
133export function skillPaths(name: string, cwd: string, home: string | undefined): string[] {
134 if (!/^[A-Za-z0-9_-]+$/.test(name)) return []
135 const file = `.claude/skills/${name}/SKILL.md`
136 return home === undefined ? [`${cwd}/${file}`] : [`${cwd}/${file}`, `${home}/${file}`]
137}
138
139/**
140 * Where the status line reads this session's tier. The temp folder, so the OS
141 * clears files from ended sessions; none for a non-plain session id.
142 */
143export function tierPath(tmpdir: string | undefined, sessionId: string): string | undefined {
144 if (tmpdir === undefined || !/^[A-Za-z0-9_-]+$/.test(sessionId)) return undefined
145 return `${tmpdir.replace(/\/+$/, '')}/claude-auto-model/${sessionId}`
146}
147types/index.d.ts 13 lines1export type AutoModelLevel = 'trivial' | 'moderate' | 'complex' | 'frontier'
2
3declare module 'claude-code' {
4 interface PluginState {
5 'auto-model': {
6 isOn: boolean
7 pendingModel: string | null
8 lastTurnAt: number | null
9 hasRoutedTier: boolean
10 }
11 }
12}
13