Suggests haiku, sonnet or opus for the task you are typing, live, in a band above the prompt. Instant word rules, then a small model reads the draft when you…

A Claude Code mod that reads the prompt as you type and suggests the model tier the task wants, in a band above the prompt. Two passes: word rules answer on every keystroke for free, then, once you pause for 300 ms, a small model (haiku by default) reads the draft and its verdict replaces the rules'. One short completion per pause, nothing while you are typing.

Recorded live with VHS; the GIF and the script that records it are on the assets branch.
While you type it says reading the draft...; the verdict lands 1.2 to 1.9 s after you stop typing (a 300 ms pause, then a haiku call that measured 0.9 to 1.6 s). A draft judged once in the session answers instantly from a cache. The Switch button appears only when the session's model does not cover the verdict; a covered one reads opus hard concurrency bug · covered by fable. The band clears when you submit.
With the default engine: model, your unsent draft leaves your machine. About 300 ms after you stop typing, the first 4,000 characters go to the judge model through Claude Code's own connection: your login, your configured provider (Anthropic, Bedrock, Vertex or a gateway), billed like any request and counted against your plan. Another installed plugin that hooks model.complete can see those calls too.
What is never sent:
not sent, looks like a secret! shell escapes, # memory notes, and drafts under 15 characters/model-hint turns it off for the sessionSet engine to rules and nothing leaves your machine: the hint comes from local word rules only.
The plugin itself makes no network, file or shell calls, and it reads no credentials or environment variables. The judge call goes through Claude Code's own $.model.complete, which uses the session's existing login; the plugin never sees it.
It changes one setting, model, and only when you press Switch (or its s hotkey). It writes through the /config Model row ($.config.set({ key: 'model' })), the same row /model uses, so the new model is saved to your user settings (~/.claude/settings.json) and becomes the default for later sessions. The toast names the model it replaced. Nothing else is written.
It hooks these events, all read-only except where noted:
| Hook | What it does | | :- | :- | | prompt.edit | Reads the draft after each edit to classify it. Passes the edit through unchanged. | | prompt.fill | Reads the draft after another plugin fills the box. Passes the fill through unchanged. | | prompt.submit | Clears the hint. Passes the prompt through unchanged and never blocks it. | | session.attach, session.detach | Start and stop the 300 ms draft reading on surfaces that send no edits (the VS Code panel). | | ui.render (AbovePrompt) | Draws the band, or leaves the engine's own drawing in place. | | command.run (/model-hint) | Turns the plugin off and on for the session. |
| Where | Works | Notes | | :- | :- | :- | | Claude Code in a terminal | Yes | Seen working on 2.1.296 and 2.1.299 | | VS Code, terminal mode | Yes | Same engine as above; setup below | | VS Code, graphical chat panel | Yes, from extension 2.1.301 | Seen working on 18 Oct 2026. The panel draws the band but sends no keystroke events, so model-hint reads the draft every 300 ms while the panel is attached. Earlier extensions draw nothing (#99045) | | JetBrains terminal, Claude Code Desktop | Expected | Not yet seen working | | Windows | Untested | |
VS Code setup. On extension 2.1.301 or later the chat panel works once the plugin is installed; nothing else to set up. On older extensions, use terminal mode. It runs whatever claude is first on your PATH, and the extension does not install one.
npm i -g @anthropic-ai/claude-code), and check claude --version in a new terminal.claudeCode.useTerminal.Terminal mode keeps inline diffs but gives up the panel's plan review, @-mention chips and click-to-rewind.
Some tools pick a model for you without saying so. model-hint does the opposite: it tells you which tier it thinks the task needs and why, before you send, and leaves the choice with you. Nothing changes unless you press Switch. When it is wrong, you can see its reason and ignore it.
/plugin install model-hint --marketplace hashswingingslasher/model-hint
Answer y to add the marketplace, then pick the user scope so it loads in every session. Needs a Claude Code build with function hooks (mods), 2.1.296 or later.
To run it from a checkout instead:
claude --plugin-dir /path/to/model-hint
| Draft | Hint | Why | | :- | :- | :- | | fix the typo in the README | haiku | mechanical edit, short ask | | add a --verbose flag to the CLI and log the resolved config | sonnet | ordinary coding task | | there is a race condition in the job queue, find the root cause | opus | hard bug class | | i need to build a AAA video game similar to GTA 5 | opus | open-ended, huge scope (from the model) | | /model opus, !git status, an empty box | nothing | the model never sees it |
Rules pass. Each signal in hooks/classify.ts has a weight. The weights sum to a score; below one threshold the hint is haiku, above the other it is opus, between them sonnet. With the model pass on, the rules' guess is never shown as a tier; it stands in only when the model pass fails, labelled (judge API error, rules' guess). With engine set to rules it is the verdict, with the two strongest signals as the reason.
Model pass. After a pause, the draft goes to the judge model with a fixed system prompt (hooks/judge.ts) that describes the three tiers and asks for {"tier","reason"} in at most sixty output tokens at low effort. The verdict lands only if you have not typed since, and it stays on screen while you keep typing, until the next pause re-judges. Drafts under 15 characters, commands and shell escapes are never sent. A failed or malformed reply leaves the rules' hint in place.
A session on Fable counts as covering an opus hint, so the band does not ask you to step down.
Switch to <tier> changes the model through the /config Model row. Like /model, this also saves it as your default for later sessions, and a toast says what it was before. It is hidden while Claude is working. Where that row is not available or is locked by policy, the button shows a toast with the /model command to type instead. Hide closes the band for the prompt you are writing; it comes back when you send it or clear the box. Off turns model-hint off for the rest of the session: no band and no model calls. s, h and o press them while the band has focus (ctrl+x tab).
/model-hint turns it off and on for the session, the same as the Off button. Off stops the model calls too, not only the band.
Set in /config under the plugin's rows, or at install.
| Option | Values | Default | Effect | | :- | :- | :- | :- | | engine | model, rules | model | rules turns the model pass off: words only, no completions | | judge | a model alias or id | haiku | Which model reads the draft | | show | always, when-different | always | when-different hides the band entirely when the session's model covers the verdict | | bias | balanced, cost, quality | balanced | Moves the two thresholds. cost needs more evidence before suggesting opus; quality needs less |
Three hooks and one render site, all in hooks/register.tsx:
prompt.edit fires on each edit the composer makes. The hook lets the edit through, runs the rules on the draft that results, writes the hint to $.state only when it changed, and arms a $.clock.after timer for the model pass. Each edit cancels the previous timer and aborts any completion in flight, so at most one model call is ever pending.prompt.fill covers a draft another plugin wrote into the box, which raises no edit.prompt.submit clears the hint.ui.render on AbovePrompt reads the hint, the session's model and the Hide state and draws the band, or yields to the engine. A failed model pass is logged to the debug log (claude --debug) and named in the band.session.attach starts a 300 ms timer that reads the draft with $.prompt.read() when a surface attaches that draws the band but raises no prompt.edit (the VS Code panel). The first prompt.edit switches the timer off for the session, so the terminal never polls.$.ui.status mirrors the hint under the prompt until a band has drawn once. It is kept for surfaces not yet checked, such as mobile; it does not help in the VS Code panel, where none of the hooks above fire.hooks/classify.ts and hooks/judge.ts are pure and have no engine dependency; hooks/model.ts maps a model id to a tier. The $.state contract is in types/index.d.ts.
claude plugin validate . # manifest, hooks module, state contract
claude plugin test . # tests/*.test.ts against the engine's own runtime
npm install && npm run typecheck
tsc needs the API declarations the engine lays in .claude-plugin/types/ the first time it loads the mod from this folder (claude --plugin-dir .). They are gitignored. tsconfig.core.json checks the engine-free core (classify.ts, model.ts) without them.
CI runs that core typecheck, then plugin validate --strict and plugin test on Claude Code 2.1.296 (the minimum, required) and on the latest release (allowed to fail, so API drift shows without blocking a merge).
Live check (haiku judge, 10 prompts labelled before the run: 3 haiku, 4 sonnet, 3 opus). 10 of 10 matched (14 Oct 2026). In live terminal sessions on 15 Oct the verdict landed 1.2 to 1.9 s after the last keystroke, median about 1.5 s. Run with claude --debug to see the same timing for your own prompts: each verdict logs its time after the last edit, split into the pause and the judge call.
Tests cover the rules on their own, the judge's prompt and reply parsing, the model-id mapping, and the band on both the terminal and desktop surfaces: it draws when the tier differs, stays quiet when covered, hides and comes back, clears on submit, takes the model's verdict after the pause, cancels the pass when typing resumes, and drops a verdict for a draft that moved on. The judge model and the clock are mocked.
haiku stays the default.engine to rules to avoid that.haiku, sonnet, opus or fable; anything else is treated as unknown and the band always shows./config Model row, which policy can lock.MIT
hooks/register.tsx 417 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, Timer } from 'claude-code'
3
4import type { Suggestion } from '../types'
5import { classify, isSkippable, type Bias } from './classify'
6import * as judge from './judge'
7import { satisfies, tierOf } from './model'
8
9const COMMAND = 'model-hint'
10
11const suggestion = atom({ plugin: 'model-hint', key: 'suggestion' } as const, null)
12const isEnabled = atom({ plugin: 'model-hint', key: 'isEnabled' } as const, true)
13const isDismissed = atom({ plugin: 'model-hint', key: 'isDismissed' } as const, false)
14const judgeNote = atom({ plugin: 'model-hint', key: 'judgeNote' } as const, null)
15
16const BIASES: readonly Bias[] = ['balanced', 'cost', 'quality']
17const SHOWS = ['always', 'when-different'] as const
18const ENGINES = ['model', 'rules'] as const
19type Show = (typeof SHOWS)[number]
20type Engine = (typeof ENGINES)[number]
21
22/**
23 * How long the person must pause before the model reads the draft. A judge call
24 * measured 0.8 to 1.4 s (median about 0.95 s), so 300 ms keeps the verdict near
25 * 1.25 s after typing stops; a stray keystroke only aborts the call in flight.
26 */
27export const PAUSE_MS = 300
28
29/** Verdicts kept per session, so a draft judged once answers instantly. */
30const CACHE_SIZE = 64
31
32/**
33 * How often the draft is read on a surface that draws the band but raises no
34 * prompt.edit (the VS Code chat panel as of 2.1.301).
35 */
36export const POLL_MS = 300
37
38type Settings = { bias: Bias; show: Show; engine: Engine; judgeModel: string }
39
40function pick<T extends string>(value: unknown, allowed: readonly T[], fallback: T): T {
41 return typeof value === 'string' && (allowed as readonly string[]).includes(value) ? (value as T) : fallback
42}
43
44function sameSuggestion(a: Suggestion | null, b: Suggestion | null): boolean {
45 if (a === null || b === null) return a === b
46 return a.tier === b.tier && a.reasons.join('|') === b.reasons.join('|')
47}
48
49/**
50 * Writes the hint only when it changed, so a stable classification never redraws.
51 * A Hide lasts for the prompt being written: a new verdict does not undo it, only
52 * sending the prompt or clearing the box (`newPrompt`) does.
53 */
54async function publish($: EngineInterface, next: Suggestion | null, newPrompt: boolean): Promise<void> {
55 await update($, suggestion, prev => (sameSuggestion(prev, next) ? prev : next))
56 if (newPrompt) await update($, isDismissed, () => false)
57}
58
59/** Turns the plugin on or off for the session. Off stops the model calls as well as the band. */
60async function setEnabled($: EngineInterface, settings: Settings, on: boolean): Promise<void> {
61 await update($, isEnabled, () => on)
62 if (!on) {
63 cancelPending()
64 await update($, suggestion, () => null)
65 await update($, judgeNote, () => null)
66 }
67 await update($, isDismissed, () => false)
68 await mirror($, settings)
69}
70
71// One pending model pass at a time, for the draft as it stood when the person
72// paused. Module state: a hot reload drops it, which is the right outcome.
73let pending: Timer | undefined
74let inflight: AbortController | undefined
75let generation = 0
76
77// Verdicts by judge model and trimmed draft, oldest first. Backspacing to a
78// draft already judged, or pausing twice on the same text, costs no call.
79const verdicts = new Map<string, Suggestion>()
80
81// Wall-clock time of the last edit, for the debug log's latency line only.
82let editedAt = 0
83
84// The VS Code chat panel (2.1.301) attaches as a surface and draws the band, but
85// never forwards typing as prompt.edit; it does answer $.prompt.read. While such a
86// surface is attached the draft is read on a timer instead. The first prompt.edit
87// proves the host forwards edits and switches the timer off for the session.
88let poller: Timer | undefined
89let hearsEdits = false
90let lastPolled = ''
91
92function stopPolling(): void {
93 poller?.cancel()
94 poller = undefined
95}
96
97async function poll($: EngineInterface, settings: Settings): Promise<void> {
98 if (hearsEdits) {
99 stopPolling()
100 return
101 }
102 try {
103 const box = await $.prompt.read()
104 if (box.text === lastPolled) return
105 lastPolled = box.text
106 await onDraft($, box.text, settings)
107 } catch (err) {
108 $.ui.log(`model-hint: reading the draft failed: ${String(err)}`, { to: 'debug' })
109 }
110}
111
112/** FNV-1a over the text, so the cache holds a short key rather than the draft itself. */
113function fingerprint(text: string): string {
114 let hash = 0x811c9dc5
115 for (let i = 0; i < text.length; i += 1) {
116 hash ^= text.charCodeAt(i)
117 hash = Math.imul(hash, 0x01000193)
118 }
119 return `${(hash >>> 0).toString(36)}:${text.length}`
120}
121
122function cacheKey(settings: Settings, draft: string): string {
123 return `${settings.judgeModel}:${fingerprint(draft.trim().slice(0, judge.SEND_LIMIT))}`
124}
125
126function remember(key: string, verdict: Suggestion): void {
127 verdicts.delete(key)
128 verdicts.set(key, verdict)
129 if (verdicts.size > CACHE_SIZE) {
130 const oldest = verdicts.keys().next().value
131 if (oldest !== undefined) verdicts.delete(oldest)
132 }
133}
134
135// Whether this session draws the band. Learned at the first AbovePrompt render,
136// not from the surface's name: until then the status line under the prompt
137// carries the hint. That covers surfaces with a status line but no band; it does
138// nothing in the VS Code panel, where prompt.edit never fires.
139let hasBand = false
140
141async function mirror($: EngineInterface, settings: Settings): Promise<void> {
142 if (hasBand) return
143 const [hint, enabled, note] = await Promise.all([read($, suggestion), read($, isEnabled), read($, judgeNote)])
144 if (hint === null || !enabled) {
145 $.ui.status(undefined)
146 return
147 }
148 if (hint.source === 'rules' && settings.engine === 'model' && note === null) {
149 $.ui.status('model-hint: reading the draft...')
150 return
151 }
152 const current = tierOf(await $.session.model())
153 const covered = satisfies(current, hint.tier)
154 if (covered && settings.show === 'when-different') {
155 $.ui.status(undefined)
156 return
157 }
158 const tail = covered && current ? `covered by ${current}` : `/model ${hint.tier} to switch`
159 $.ui.status(`model-hint: ${hint.tier} · ${hint.reasons.join(', ')}${note ? ` (${note}, rules' guess)` : ''} · ${tail}`)
160}
161
162function cancelPending(): number {
163 pending?.cancel()
164 inflight?.abort()
165 generation += 1
166 return generation
167}
168
169/**
170 * The instant pass. The rules answer at once; a model verdict already on
171 * screen is kept while the person keeps typing, so the band does not flip
172 * between the two sources on every keystroke. Then the model pass is armed.
173 */
174async function onDraft($: EngineInterface, draft: string, settings: Settings): Promise<void> {
175 const mine = cancelPending()
176 editedAt = Date.now()
177 // Off means off: nothing is classified, and nothing is sent.
178 if (!(await read($, isEnabled))) return
179
180 const rules = classify(draft, settings.bias)
181 await update($, judgeNote, () => null)
182
183 const known = settings.engine === 'model' && rules !== null ? verdicts.get(cacheKey(settings, draft)) : undefined
184 if (known) {
185 await publish($, known, false)
186 await mirror($, settings)
187 return
188 }
189
190 const held = await read($, suggestion)
191 const keepModelVerdict = held?.source === 'model' && rules !== null
192 if (!keepModelVerdict) await publish($, rules, draft.trim().length === 0)
193 await mirror($, settings)
194
195 if (settings.engine !== 'model' || rules === null || draft.trim().length < judge.MIN_LENGTH) return
196 if (judge.looksSecret(draft.slice(0, judge.SEND_LIMIT))) {
197 await update($, judgeNote, () => 'not sent, looks like a secret')
198 await mirror($, settings)
199 return
200 }
201 pending = $.clock.after(PAUSE_MS, () => {
202 void ask($, draft, mine, settings)
203 })
204}
205
206/** The model pass, guarded: a failure anywhere in it is logged, never thrown into a timer. */
207async function ask($: EngineInterface, draft: string, mine: number, settings: Settings): Promise<void> {
208 try {
209 await judgeDraft($, draft, mine, settings)
210 } catch (err) {
211 $.ui.log(`model-hint: model pass failed: ${String(err)}`, { to: 'debug' })
212 }
213}
214
215/** A verdict lands only while it is still the latest and the draft has not moved on. */
216async function judgeDraft($: EngineInterface, draft: string, mine: number, settings: Settings): Promise<void> {
217 const stop = new AbortController()
218 inflight = stop
219 const firedAt = Date.now()
220 // A failure is shown in the band and logged; it never sits silently on "reading".
221 const fail = async (note: string, detail: string) => {
222 $.ui.log(`model-hint: ${note}: ${detail}`, { to: 'debug' })
223 if (mine !== generation) return
224 await update($, judgeNote, () => note)
225 await mirror($, settings)
226 }
227 let reply
228 try {
229 reply = await $.model.complete(judge.request(draft, settings.judgeModel), { signal: stop.signal })
230 } catch (err) {
231 await fail('judge call failed', String(err))
232 return
233 }
234 if (mine !== generation) return
235 if (!reply.isAnswered) {
236 if (reply.reason === 'aborted') return
237 const detail = reply.reason === 'api-error' ? `${reply.status ?? ''} ${reply.error}` : reply.reason
238 await fail(reply.reason === 'api-error' ? 'judge API error' : 'judge gave no answer', detail)
239 return
240 }
241
242 const verdict = judge.parse(reply.text)
243 if (verdict === null) {
244 await fail('judge reply unreadable', reply.text.slice(0, 200))
245 return
246 }
247 const box = await $.prompt.read()
248 if (box.text !== draft) {
249 $.ui.log(`model-hint: draft moved on before the verdict landed (${box.text.length} vs ${draft.length} chars)`, { to: 'debug' })
250 return
251 }
252 remember(cacheKey(settings, draft), verdict)
253 const now = Date.now()
254 $.ui.log(
255 `model-hint: verdict ${verdict.tier} (${verdict.reasons[0]}) ${now - editedAt} ms after the last edit ` +
256 `(timer ${firedAt - editedAt} ms, judge call ${now - firedAt} ms)`,
257 { to: 'debug' },
258 )
259 await publish($, verdict, false)
260 await mirror($, settings)
261}
262
263export const register: Register = (on, options) => {
264 const settings: Settings = {
265 bias: pick(options.bias, BIASES, 'balanced'),
266 show: pick<Show>(options.show, SHOWS, 'always'),
267 engine: pick<Engine>(options.engine, ENGINES, 'model'),
268 judgeModel: typeof options.judge === 'string' && options.judge.trim() ? options.judge.trim() : 'haiku',
269 }
270
271 on('session.start', async ($, e, next) => {
272 await $.command.register({
273 name: COMMAND,
274 description: 'Toggle the model hint band above the prompt',
275 })
276 return next(e)
277 })
278
279 on('command.run', { command: COMMAND }, async $ => {
280 const enabled = !(await read($, isEnabled))
281 await setEnabled($, settings, enabled)
282 return { text: enabled ? 'Model hint on.' : 'Model hint off for this session. /model-hint turns it back on.' }
283 }).catch(() => ({ text: 'Model hint: could not toggle, see the debug log.' }))
284
285 on('session.attach', async ($, e, next) => {
286 const attached = await next(e)
287 if (e.surface !== 'terminal' && !hearsEdits && poller === undefined) {
288 poller = $.clock.every(POLL_MS, () => {
289 void poll($, settings)
290 })
291 }
292 return attached
293 })
294
295 on('session.detach', async ($, e, next) => {
296 const detached = await next(e)
297 const remote = (await $.session.surfaces()).filter(surface => surface !== 'terminal')
298 if (remote.length === 0) stopPolling()
299 return detached
300 })
301
302 // Fires on each edit the composer makes; `next(e)` resolves the box after it.
303 on('prompt.edit', async ($, e, next) => {
304 if (!hearsEdits) {
305 hearsEdits = true
306 stopPolling()
307 }
308 const box = await next(e)
309 await onDraft($, box.text, settings)
310 return box
311 }).catch((_$, e, next) => next(e))
312
313 // A plugin's fill replaces the draft without a prompt.edit, so re-read it.
314 on('prompt.fill', async ($, e, next) => {
315 const filled = await next(e)
316 if (filled.isFilled) {
317 const box = await $.prompt.read()
318 await onDraft($, box.text, settings)
319 }
320 return filled
321 }).catch((_$, e, next) => next(e))
322
323 // A failure here must never hold a prompt back: let it through untouched.
324 on('prompt.submit', async ($, e, next) => {
325 cancelPending()
326 lastPolled = ''
327 await update($, suggestion, () => null)
328 await update($, isDismissed, () => false)
329 await update($, judgeNote, () => null)
330 $.ui.status(undefined)
331 return next(e)
332 }).catch((_$, e, next) => next(e))
333
334 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
335 if (!hasBand) {
336 hasBand = true
337 $.ui.status(undefined)
338 }
339 if (e.props.hasSurvey) return next(e)
340
341 const [hint, enabled, dismissed, note] = await Promise.all([
342 read($, suggestion),
343 read($, isEnabled),
344 read($, isDismissed),
345 read($, judgeNote),
346 ])
347 if (hint === null || !enabled || dismissed) return next(e)
348
349 const current = tierOf(await $.session.model())
350 const covered = satisfies(current, hint.tier)
351 if (covered && settings.show === 'when-different') return next(e)
352
353 const { Box, Button, Text } = $.ui.resolve(e)
354 const tier = hint.tier
355 const turnOff = async () => {
356 await setEnabled($, settings, false)
357 $.ui.toast('model-hint is off for this session. /model-hint turns it back on.')
358 }
359 // Hide: gone until this prompt is sent or cleared. Off: gone, and no model calls, for the session.
360 const hide = (
361 <>
362 <Button key="hide" label="Hide" hotkey="h" onPress={() => update($, isDismissed, () => true)} />
363 <Button key="off" label="Off" hotkey="o" onPress={turnOff} />
364 </>
365 )
366
367 // The rules' guess is never shown as a tier while the model is still reading.
368 if (hint.source === 'rules' && settings.engine === 'model' && note === null) {
369 return (
370 <Box gap={1}>
371 <Text dimColor>reading the draft...</Text>
372 {hide}
373 </Box>
374 )
375 }
376
377 const switchTo = async () => {
378 const rows = await $.config.list()
379 const row = rows.find(r => r.key === 'model')
380 if (!row || row.isLocked) {
381 $.ui.toast(`Type /model ${tier} to switch`)
382 return
383 }
384 const before = await $.session.model()
385 const set = await $.config.set({ key: 'model', value: tier })
386 if (set.deny) {
387 $.ui.toast(`Could not switch: ${set.deny}. Type /model ${tier}`)
388 return
389 }
390 // Like /model, the Model row saves the default for later sessions too; say so.
391 $.ui.toast(`Default model is now ${tier} (was ${before}), same as /model`)
392 await update($, isDismissed, () => true)
393 }
394
395 const detail = [
396 hint.reasons.join(', '),
397 note ? `(${note}, rules' guess)` : '',
398 covered && current ? `· covered by ${current}` : '',
399 ]
400 .filter(Boolean)
401 .join(' ')
402
403 return (
404 <Box gap={1}>
405 <Text color={covered ? 'success' : 'suggestion'} bold>
406 {tier}
407 </Text>
408 <Text dimColor wrap="truncate-end">
409 {detail}
410 </Text>
411 {!covered && !e.props.isWorking && <Button key="switch" label={`Switch to ${tier}`} hotkey="s" onPress={switchTo} />}
412 {hide}
413 </Box>
414 )
415 }).catch((_$, e, next) => next(e))
416}
417hooks/classify.ts 122 lines1import type { Suggestion, Tier } from '../types'
2
3/**
4 * Scores a draft prompt and picks a tier. Pure: no engine, no model call, so it
5 * runs on every keystroke without cost and is unit-tested in isolation.
6 *
7 * The score is a sum of signals. Negative leans haiku, positive leans opus,
8 * the middle is sonnet. `bias` shifts the two thresholds so a cost-conscious
9 * person needs more evidence before being pushed up a tier, and vice versa.
10 */
11
12export type Bias = 'balanced' | 'cost' | 'quality'
13
14type Signal = {
15 /** Shown to the person as the reason for the pick; keep it short. */
16 label: string
17 weight: number
18 test: (draft: string, lower: string) => boolean
19}
20
21const words = (list: string[]) => new RegExp(`\\b(?:${list.join('|')})\\b`, 'i')
22
23const HEAVY_VERBS = words([
24 'architect', 'design', 'redesign', 'rearchitect', 'restructure', 'migrate', 'migration',
25 'refactor', 'rewrite', 'port', 'overhaul', 'modernize', 'modernise', 'decompose',
26 'modulari[sz]e', 'made modular', 'make .{1,30} modular', 'decouple', 'untangle', 'separat(?:e|ed|ing)',
27 'split (?:up|out|into|apart)', 'break (?:up|apart|out)', 'extract (?:into|out|a|the)', 'consolidate',
28])
29const HARD_PROBLEMS = words([
30 'race condition', 'deadlock', 'memory leak', 'flaky', 'intermittent', 'heisenbug',
31 'root cause', 'regression', 'data loss', 'corrupt(?:ed|ion)?', 'nondeterministic',
32 'performance', 'latency', 'throughput', 'scal(?:e|ing|ability)', 'concurren(?:cy|t)',
33])
34const JUDGMENT = words([
35 'trade-?offs?', 'strategy', 'approach', 'options?', 'compare', 'evaluate', 'assess',
36 'recommend', 'should (?:we|i)', 'pros and cons', 'which is better', 'critique', 'review',
37 'audit', 'security', 'threat model', 'plan', 'roadmap', 'spec', 'rfc', 'proposal',
38])
39const WIDE_SCOPE = words([
40 'across', 'entire', 'whole', 'all (?:the )?(?:files|modules|packages|services|tests)',
41 'codebase', 'monorepo', 'end[- ]to[- ]end', 'every', 'throughout', 'system[- ]wide',
42 '(?:multiple|several|many) (?:features|modules|files|services|components|packages|places)',
43])
44const DEBUG = words(['debug(?:ging|ged)?', 'investigate', 'troubleshoot(?:ing)?', 'diagnose', 'figure out', 'why (?:does|is|do|did|are|was|were)', "doesn't work", 'not working', 'broken', 'crash(?:es|ing)?'])
45
46const TRIVIAL = words([
47 'typo', 'rename', 'spelling', 'capitali[sz]e', 'lowercase', 'uppercase', 'indent',
48 'reformat', 'prettier', 'lint', 'alphabeti[sz]e', 'reorder',
49 'add a comment', 'remove (?:the )?comment', 'bump (?:the )?version', 'changelog',
50 'git (?:status|log|diff|add|commit|push|pull|stash|branch)', 'commit this', 'commit message',
51 'run (?:the )?tests?', 'run (?:the )?build', 'run (?:the )?linter', 'npm (?:run|test|install)',
52 'what does .{1,40} (?:do|mean|return)', 'what is .{1,40}\\?', 'where is', 'where are', 'which file',
53 'list (?:the|all)', 'show me', 'how many',
54 'translate', 'convert .{1,30} to (?:json|yaml|csv|markdown|md)', 'one[- ]liner', 'quick question',
55])
56const SMALL_SCOPE = words(['this line', 'this function', 'this file', 'one line', 'single line', 'tiny', 'minor', 'quick'])
57
58/** Past this length a draft is a brief, not a mechanical edit, whatever words it uses. */
59const MECHANICAL_MAX = 140
60
61const SIGNALS: Signal[] = [
62 { label: 'architecture or large refactor', weight: 3, test: (_, l) => HEAVY_VERBS.test(l) },
63 { label: 'hard bug class', weight: 3, test: (_, l) => HARD_PROBLEMS.test(l) },
64 { label: 'needs judgment', weight: 3, test: (_, l) => JUDGMENT.test(l) },
65 { label: 'wide scope', weight: 2, test: (_, l) => WIDE_SCOPE.test(l) },
66 { label: 'debugging', weight: 2, test: (_, l) => DEBUG.test(l) },
67 { label: 'multi-step', weight: 3, test: d => countSteps(d) >= 3 },
68 { label: 'long brief', weight: 2, test: d => d.length >= 600 },
69 { label: 'detailed brief', weight: 1, test: d => d.length >= 250 && d.length < 600 },
70 { label: 'mechanical edit', weight: -3, test: (d, l) => d.length < MECHANICAL_MAX && TRIVIAL.test(l) },
71 { label: 'small scope', weight: -1, test: (_, l) => SMALL_SCOPE.test(l) },
72 { label: 'short ask', weight: -1, test: d => d.trim().length < 40 },
73]
74
75/**
76 * The rules read at most this much of a draft. Past it the shape of a request
77 * is clear, and every keystroke stays cheap however much is pasted.
78 */
79export const READ_LIMIT = 8000
80
81/** Numbered items, bullets, or "then"/"after that" chains count as steps. */
82export function countSteps(draft: string): number {
83 // [ \t] rather than \s: a \s* that can cross newlines goes quadratic on blank lines.
84 const listed = (draft.match(/^[ \t]*(?:\d+[.)]|[-*•])[ \t]+\S/gm) ?? []).length
85 const chained = (draft.match(/\b(?:then|after that|next|finally|afterwards|once that)\b/gi) ?? []).length
86 return Math.max(listed, chained + 1)
87}
88
89/** Drafts the model never sees: slash commands, shell escapes, memory notes, nothing typed. */
90export function isSkippable(draft: string): boolean {
91 const t = draft.trimStart()
92 return t.length === 0 || t.startsWith('/') || t.startsWith('!') || t.startsWith('#')
93}
94
95const THRESHOLDS: Record<Bias, { up: number; down: number }> = {
96 balanced: { up: 3, down: -2 },
97 cost: { up: 5, down: -1 },
98 quality: { up: 2, down: -3 },
99}
100
101export function classify(whole: string, bias: Bias = 'balanced'): Suggestion | null {
102 if (isSkippable(whole)) return null
103 // Length still counts as a signal past the limit, so the brief keeps its weight.
104 const draft = whole.length > READ_LIMIT ? whole.slice(0, READ_LIMIT) : whole
105
106 const lower = draft.toLowerCase()
107 const hits = SIGNALS.filter(s => s.test(draft, lower))
108 const score = hits.reduce((sum, s) => sum + s.weight, 0)
109 const { up, down } = THRESHOLDS[bias]
110
111 const tier: Tier = score >= up ? 'opus' : score <= down ? 'haiku' : 'sonnet'
112
113 // Explain the pick with the signals that pulled in its direction, strongest first.
114 const towards = hits
115 .filter(s => (tier === 'opus' ? s.weight > 0 : tier === 'haiku' ? s.weight < 0 : true))
116 .sort((a, b) => Math.abs(b.weight) - Math.abs(a.weight))
117 .map(s => s.label)
118 const reasons = towards.length > 0 ? towards.slice(0, 2) : ['ordinary coding task']
119
120 return { tier, reasons, score, source: 'rules' }
121}
122hooks/judge.ts 87 lines1import type { ModelCompleteRequest } from 'claude-code'
2
3import type { Suggestion, Tier } from '../types'
4
5/**
6 * The model pass. The rules in classify.ts answer instantly from words; this
7 * reads the task. It runs once the person pauses, on a small model, with a
8 * fixed system prompt and the draft as the only user message.
9 */
10
11const TIERS: readonly Tier[] = ['haiku', 'sonnet', 'opus']
12
13export const SYSTEM = [
14 'You route a coding-assistant request to one of three model tiers.',
15 'Reply with JSON only, nothing else: {"tier":"haiku"|"sonnet"|"opus","reason":"<at most six words>"}',
16 '',
17 'haiku: mechanical or lookup work. One obvious change, a rename, a typo, running a command, a factual question about the code.',
18 'sonnet: a well-specified feature, fix or test in a known area. The default for ordinary coding.',
19 'opus: architecture or design, open-ended or ambiguous goals, large or multi-system scope, hard debugging, trade-off judgement, plans and reviews, anything a senior engineer would need days for.',
20 '',
21 'Judge the task itself, not the wording or length. The text is a draft the person is still typing; judge what they are asking for so far.',
22].join('\n')
23
24/** Drafts shorter than this are judged by the rules alone; the model would see too little. */
25export const MIN_LENGTH = 15
26
27/**
28 * At most this much of a draft is sent. The request is clear from its start, and
29 * a pasted log should not be re-sent in full at every pause.
30 */
31export const SEND_LIMIT = 4000
32
33/** A reply longer than this is not a 60-token verdict; it is not parsed. */
34const REPLY_LIMIT = 2000
35
36/**
37 * Text that looks like a credential. A draft containing one is never sent; the
38 * rules' guess stands in and the band says why.
39 */
40const SECRET = new RegExp(
41 [
42 'sk-ant-[A-Za-z0-9_-]{16,}',
43 'sk-[A-Za-z0-9]{32,}',
44 'gh[pousr]_[A-Za-z0-9]{30,}',
45 'github_pat_[A-Za-z0-9_]{40,}',
46 'xox[abposr]-[A-Za-z0-9-]{10,}',
47 'AKIA[0-9A-Z]{16}',
48 'AIza[0-9A-Za-z_-]{35}',
49 '-----BEGIN [A-Z ]*PRIVATE KEY-----',
50 'eyJ[A-Za-z0-9_-]{10,}\\.eyJ[A-Za-z0-9_-]{10,}\\.[A-Za-z0-9_-]{10,}',
51 ].join('|'),
52)
53
54export function looksSecret(draft: string): boolean {
55 return SECRET.test(draft)
56}
57
58export function request(draft: string, model: string): ModelCompleteRequest {
59 const prompt = draft.length > SEND_LIMIT ? draft.slice(0, SEND_LIMIT) : draft
60 return { model, system: SYSTEM, prompt, maxTokens: 60, effort: 'low', timeoutMs: 8000 }
61}
62
63// C0 and C1 controls, zero-width and bidirectional marks: nothing a reason needs,
64// and a terminal may act on them.
65const UNPRINTABLE = /[\u0000-\u001f\u007f-\u009f\u200b-\u200f\u202a-\u202e\u2066-\u2069]/g
66
67/** Reads the verdict out of the reply; null when it names no tier. */
68export function parse(reply: string): Suggestion | null {
69 if (reply.length > REPLY_LIMIT) return null
70 const open = reply.indexOf('{')
71 const close = reply.lastIndexOf('}')
72 if (open === -1 || close < open) return null
73 const json = reply.slice(open, close + 1)
74 let parsed: unknown
75 try {
76 parsed = JSON.parse(json)
77 } catch {
78 return null
79 }
80 if (typeof parsed !== 'object' || parsed === null) return null
81 const { tier, reason } = parsed as { tier?: unknown; reason?: unknown }
82 if (typeof tier !== 'string' || !(TIERS as readonly string[]).includes(tier)) return null
83 const clean = typeof reason === 'string' ? reason.replace(UNPRINTABLE, '').trim() : ''
84 const why = clean ? clean.slice(0, 60) : 'judged by the model'
85 return { tier: tier as Tier, reasons: [why], score: 0, source: 'model' }
86}
87hooks/model.ts 25 lines1import type { Tier } from '../types'
2
3/**
4 * Maps what `/model` shows (an alias, a full id, a Bedrock or Vertex id) to the
5 * tier the hint reasons about. Fable sits above opus and satisfies an opus
6 * hint; anything unrecognised is null and the hint always shows.
7 */
8export type Current = Tier | 'fable' | null
9
10export function tierOf(model: string): Current {
11 const m = model.toLowerCase()
12 if (m.includes('fable')) return 'fable'
13 if (m.includes('opus')) return 'opus'
14 if (m.includes('sonnet')) return 'sonnet'
15 if (m.includes('haiku')) return 'haiku'
16 return null
17}
18
19/** Whether the session's model already covers the suggested tier. */
20export function satisfies(current: Current, suggested: Tier): boolean {
21 if (current === null) return false
22 if (current === suggested) return true
23 return current === 'fable' && suggested === 'opus'
24}
25types/index.d.ts 31 lines1/** The three tiers the hint picks between. */
2export type Tier = 'haiku' | 'sonnet' | 'opus'
3
4/** What produced a suggestion: the instant word rules, or the small model that reads the draft after a pause. */
5export type Source = 'rules' | 'model'
6
7/** What the classifier concluded about the current draft. */
8export type Suggestion = {
9 tier: Tier
10 /** Short, human-readable grounds for the pick, e.g. "typo fix, one line". */
11 reasons: string[]
12 /** The rules' net score: negative leans haiku, positive leans opus. 0 for a model verdict. */
13 score: number
14 source: Source
15}
16
17declare module 'claude-code' {
18 interface PluginState {
19 'model-hint': {
20 /** The hint for the draft as it stands; null while the box is empty or the draft is a command. */
21 suggestion: Suggestion | null
22 /** Session toggle, flipped by /model-hint. */
23 isEnabled: boolean
24 /** True once the person hides the band for the current draft; reset when the draft is submitted or emptied. */
25 isDismissed: boolean
26 /** Why the last model pass gave no verdict, shown in the band in place of "(reading...)"; null while none failed. */
27 judgeNote: string | null
28 }
29 }
30}
31