SLOPSHOPPER

model-router-slim

Picks the model and the reasoning effort for each task with TypeSafe's Jev, a System One decision model reached either through TypeSafe's own API or the Vercel…

commandtoastpromptmodelnetworkagents
v0.4.3MITupdated 2026-10-24GambetaClub/model-router
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · model-router-slim
› fix the failing auth test and add an audit log call ● model-router-slim: [Jev Model Router] ready on the built-in classifier, no key set; routing subagent model, main effort, main model ● model-router-slim: [Jev Model Router] jev: tier [object Object] (n/d) · 20ms ⏺ 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 › /router ⎿ model-router-slim: Jev model router is on. ● model-router-slim: [Jev Model Router] outcome: claude-opus-5-5 · effort n/d · 42s · 1480 out · 4300 written ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts
README

Model Router

A Claude Code mod that picks the model and reasoning effort for every prompt. It asks Jev, TypeSafe's small decision model, how hard the task is, then sends the turn to the model that fits.

Forked from jev-model-router in claude-code-templates.

What it does

TierModelFor
fastHaiku 5.5Small, mechanical work: read a file, rename a symbol
balancedSonnet 5.5Everyday changes across a few files
deepOpus 5.5Design, unknown bugs, security, migrations
superDeepFable 5.1Big refactors and features that span many files
  • It sets the effort for each prompt: low, medium, high or xhigh.
  • It picks the main model on the first turn and keeps it until /clear or a compaction. Switching models mid-chat would throw away the prompt cache.
  • Each subagent gets its own model. Subagents start fresh, so a different model costs nothing there.
  • When a prompt has nothing to do with the current chat, the mod holds it back and suggests a new session, with a ready-to-paste claude --model … '<prompt>' command. Send the prompt again to run it in the current chat.
  • A task that would change production, move money or destroy data gets at least deep and high effort.

Install

git clone https://github.com/GambetaClub/model-router .claude/skills/model-router

You need Claude Code 2.1.287 or newer. On an older version, start it with CLAUDE_CODE_ENABLE_FUNCTION_HOOKS=1 claude. Accept the trust prompt the first time you open the project.

Setup

Add this to ~/.claude/settings.json (user settings, not project settings):

{
  "pluginConfigs": {
    "model-router-slim@skills-dir": {
      "options": { "typesafeApiKey": "…", "timeoutMs": 2000 }
    }
  }
}

With no key, the mod falls back to Claude Code's built-in classifier (Haiku). It works, but the classifier only sees the tier names, gives no confidence score, never moves you to a smaller model, and can't do the new-task check.

What you'll see

[Jev Model Router] jev: tier fast (0.99) · effort 0.0 → low (1.00) · risky 0.07 · 396ms
[Jev Model Router] main loop → claude-haiku-5-5, effort low: fast (confidence 0.99)

The mod adds no row under the prompt. It publishes whether it is on or off as $.state model-router-slim.off, and the model and effort it last sent as model-router-slim.sent, so another mod can show them.

/model and the model's own answer will keep naming your session model. The mod changes each request, not the setting. To see which model really answered, check the session log:

jq -r 'select(.type=="assistant") | .message.model' ~/.claude/projects/<project>/<session>.jsonl | uniq -c

Options

OptionDefaultWhat it does
typesafeApiKey / gatewayApiKeynoneJev through TypeSafe (preferred, gives confidence) or the Vercel AI Gateway
fastModel, balancedModel, deepModel, superDeepModelhaiku, sonnet, opus, fableAlias or full model id per tier
routeMainModeltruePick the main chat's model from its first prompt
routeMainEfforttruePick the main chat's effort
routeSubagentModeltruePick each subagent's model
minUpgradeConfidence / minDowngradeConfidence0.3 / 0.6How sure Jev must be to move up or down
timeoutMs800Wait limit per classification; 2000 avoids timeouts on the first call
logDecisionstrueShow the log lines above

Privacy

With a key set, your prompt goes to TypeSafe or Vercel, along with up to five earlier prompts (500 characters each) for the new-task check. For subagents it sends their prompt, description and type. With no key, nothing goes anywhere except Anthropic.

Tests

claude plugin test .
node eval/eval.ts

eval/eval.ts checks the first-prompt pick and the no-switch rule: real Jev calls through the hook, plus an audit of your past sessions. It needs Node 22.6 or newer.

MIT licensed.

Source 3 files
hooks/model-router.ts 468 lines
1/**
2 * model-router — Claude Mod
3 *
4 * Picks the model each task runs on with TypeSafe's Jev, a System One
5 * decision model: unstructured state in, a typed choice with a probability
6 * distribution out.
7 *
8 * Jev is reached one of two ways, whichever key is configured: TypeSafe's
9 * own API (`typesafeApiKey`), which reports a calibrated confidence per
10 * answer, or the Vercel AI Gateway (`gatewayApiKey`), which does not. With
11 * neither, the engine's own `$.model.classify` stands in, so the mod is
12 * useful without any account.
13 *
14 * Three things it can set, each on its own switch:
15 *   agent.spawn  — the model of each subagent (on by default)
16 *   turn.step    — the reasoning effort of the main loop (on by default)
17 *   turn.step    — the model of the main loop (off by default: switching
18 *                  models mid-session invalidates the prompt cache, which can
19 *                  cost more than the cheaper tier saves)
20 *
21 * Every one of them moves in both directions: a task the decision model reads
22 * as mechanical is routed down, one it reads as hard is routed up. The two
23 * mistakes do not cost the same, so they do not clear the same confidence bar
24 * (see `minUpgradeConfidence` / `minDowngradeConfidence` in policy.ts).
25 *
26 * The Agent tool has no effort parameter, so a subagent's effort is not ours
27 * to set; only its model is.
28 *
29 * The prompt is classified at `prompt.submit`, which runs before the turn
30 * starts, and the decision is applied at the turn's first request.
31 *
32 * Every failure path is fail-open: a classification that errors or runs past
33 * the latency budget leaves the request exactly as the engine built it.
34 *
35 * The API key comes from the plugin's options (userConfig "typesafeApiKey"
36 * or "gatewayApiKey"). Never hardcode it in this file.
37 *
38 * Needs Claude Code >= 2.1.287. Typed
39 * against Anthropic's declarations: https://github.com/anthropics/claude-code/tree/main/mods
40 *
41 * Privacy: with a key set, the prompt text is sent to whichever backend the
42 * key belongs to.
43 */
44import type { Register } from 'claude-code'
45import {
46  DEFAULT_BASE_URL,
47  DEFAULT_MODEL,
48  describeDecision,
49  describeSetup,
50  describeStatus,
51  endpoint,
52  pendingDecisions,
53  readDecision,
54  selectProvider,
55  requestBody,
56  requestHeaders,
57  requestModelId,
58  route,
59  TIER_ORDER,
60  bareCommand,
61  NEW_TASK_THRESHOLD,
62  newSessionAdvice,
63} from './policy.ts'
64import type { Decision, Effort, PolicyConfig, Provider, Tier } from './policy.ts'
65
66export const register: Register = (on, options) => {
67  const text = (key: string, fallback: string) =>
68    typeof options[key] === 'string' && options[key] ? (options[key] as string) : fallback
69  const number = (key: string, fallback: number) =>
70    typeof options[key] === 'number' ? (options[key] as number) : fallback
71  const flag = (key: string, fallback: boolean) =>
72    typeof options[key] === 'boolean' ? (options[key] as boolean) : fallback
73
74  // TypeSafe's own API is preferred when both keys are set: it is the only
75  // one that reports a calibrated confidence, which the policy's threshold
76  // reads. `provider` forces one, including "builtin" to use neither.
77  const typesafeKey = text('typesafeApiKey', '')
78  const gatewayKey = text('gatewayApiKey', '')
79  const forced = text('provider', 'auto')
80  const active: Provider | null = selectProvider(forced, typesafeKey, gatewayKey)
81
82  // Each backend keeps its own URL and model, so an override written for one
83  // can never be sent to the other when `auto` picks differently than expected.
84  const apiKey = active === 'typesafe' ? typesafeKey : active === 'gateway' ? gatewayKey : ''
85  const modelId = !active
86    ? ''
87    : active === 'typesafe'
88      ? text('typesafeModel', DEFAULT_MODEL.typesafe)
89      : text('gatewayModel', DEFAULT_MODEL.gateway)
90  const url = !active
91    ? ''
92    : active === 'typesafe'
93      ? endpoint('typesafe', text('typesafeBaseUrl', DEFAULT_BASE_URL.typesafe))
94      : endpoint('gateway', text('gatewayBaseUrl', DEFAULT_BASE_URL.gateway))
95
96  // A backend named in the options but missing its key degrades to the
97  // built-in classifier, which is silent; say so once, when a hook first runs.
98  let unusableReported = forced === 'auto' || forced === 'builtin' || active !== null
99
100  const timeoutMs = number('timeoutMs', 800)
101  const routeSubagentModel = flag('routeSubagentModel', true)
102  const routeMainEffort = flag('routeMainEffort', true)
103  const routeMainModel = flag('routeMainModel', true)
104  const routeMainLoop = routeMainEffort || routeMainModel
105  const logDecisions = flag('logDecisions', true)
106
107  const policy: PolicyConfig = {
108    tiers: {
109      fast: text('fastModel', 'haiku'),
110      balanced: text('balancedModel', 'sonnet'),
111      deep: text('deepModel', 'opus'),
112      superDeep: text('superDeepModel', 'fable'),
113    },
114    minUpgradeConfidence: number('minUpgradeConfidence', 0.3),
115    minDowngradeConfidence: number('minDowngradeConfidence', 0.6),
116  }
117
118  // The classification waiting for the turn that reads its prompt, and what
119  // the current turn settled on. Both are single slots: main-loop turns run
120  // one at a time, so nothing accumulates over a long session. `pending`
121  // reports no decision when two prompts are waiting at once, rather than
122  // routing a turn on a decision made for a different prompt.
123  const pending = pendingDecisions()
124  // Said once, the first time a hook runs. A router that loaded and one that
125  // never loaded are otherwise told apart only by the absence of later lines,
126  // and absence is not evidence: the policy leaves most turns alone anyway.
127  let announced = false
128  let appliedTurnId: string | undefined
129  let applied: { model?: string; effort?: Effort } | null = null
130  // The main model is picked on a conversation's first turn and kept: a switch later re-reads it all uncached.
131  let modelSettled = false
132  let sessionModel: string | undefined
133  // This session's prompts, so Jev can tell a new task from the current one.
134  let earlier: string[] = []
135  let held: string | undefined
136  let stopNextTurn: string[] | undefined
137  let off = false
138  const SHORT_FOLLOW_UP = 30
139  // Held by the host so a hot reload mid-chat does not read as a fresh chat and switch the model.
140  const settledRef = { plugin: 'model-router-slim', key: 'settled' } as const
141  const offRef = { plugin: 'model-router-slim', key: 'off' } as const
142  const sentRef = { plugin: 'model-router-slim', key: 'sent' } as const
143
144  on('session.start', async ($, e, next) => {
145    const started = await next(e)
146    const { value } = await $.state.get(settledRef)
147    if (value) {
148      modelSettled = value.modelSettled
149      sessionModel = value.sessionModel ?? undefined
150    }
151    off = (await $.store.get('off')) === true
152    await $.state.set(offRef, off)
153    await $.command.register({ name: 'router', description: 'Turn the Jev model router on or off: /router on|off', argumentHint: '[on | off]', immediate: true })
154    return started
155  })
156  on('command.run', { command: 'router' }, async ($, e) => {
157    const arg = e.args.trim().toLowerCase()
158    if (arg === 'on' || arg === 'off') {
159      off = arg === 'off'
160      await $.store.set('off', off)
161      await $.state.set(offRef, off)
162    }
163    return { text: `Jev model router is ${off ? 'off' : 'on'}.` }
164  })
165
166  on('session.end', async ($, e, next) => {
167    modelSettled = false
168    sessionModel = undefined
169    await $.state.set(settledRef, { modelSettled, sessionModel: sessionModel ?? null })
170    earlier = []
171    held = undefined
172    stopNextTurn = undefined
173    return next(e)
174  })
175  on('session.compact', async ($, e, next) => {
176    modelSettled = false
177    sessionModel = undefined
178    await $.state.set(settledRef, { modelSettled, sessionModel: sessionModel ?? null })
179    return next(e)
180  })
181
182  on('prompt.submit', async ($, e, next) => {
183    if (off) return next(e)
184    // Before the routing guards: a module whose switches are all off has still
185    // loaded, and that is exactly when its silence is most misleading.
186    if (!announced) {
187      announced = true
188      if (logDecisions) {
189        $.ui.log(
190          `[Jev Model Router] ${describeSetup(
191            active,
192            url,
193            {
194              subagentModel: routeSubagentModel,
195              mainEffort: routeMainEffort,
196              mainModel: routeMainModel,
197            },
198            forced === 'builtin',
199          )}`,
200        )
201      }
202    }
203    if (!routeMainLoop) return next(e)
204
205    if (!unusableReported) {
206      unusableReported = true
207      $.ui.log(`[Jev Model Router] provider "${forced}" has no key set; using the built-in classifier`)
208    }
209
210    // A slash command alone gives the decision model only the command's name.
211    // Its turn keeps the session's model and effort; the null put keeps a
212    // previous prompt's decision from reaching it.
213    if (bareCommand(e.text)) {
214      if (logDecisions) $.ui.log('[Jev Model Router] a command with nothing after it; leaving the turn alone')
215      pending.put(null)
216      return next(e)
217    }
218
219    if (earlier.length > 0 && e.text.trim().length < SHORT_FOLLOW_UP) {
220      if (logDecisions) $.ui.log('[Jev Model Router] short follow-up; keeping the session model and effort')
221      pending.put(null)
222      return next(e)
223    }
224
225    const startedAt = await $.clock.now()
226    let decision: Decision | null = null
227    if (active) {
228      try {
229        const response = await Promise.race([
230          $.http.fetch(url, {
231            method: 'POST',
232            headers: requestHeaders(active, apiKey, modelId),
233            body: requestBody(
234              active,
235              earlier.length > 0
236                ? { prompt: e.text, earlierPrompts: earlier.slice(-5).map(text => text.slice(0, 500)) }
237                : { prompt: e.text },
238              modelId,
239            ),
240          }),
241          $.clock.sleep(timeoutMs),
242        ])
243        if (response && response.ok) decision = readDecision(response.text)
244        else if (response) $.ui.log(`[Jev Model Router] ${active} responded ${response.status}`)
245        else $.ui.log(`[Jev Model Router] classification passed ${timeoutMs}ms; leaving the turn alone`)
246      } catch (error) {
247        $.ui.log(`[Jev Model Router] classification failed: ${String(error)}`)
248      }
249    } else {
250      // No backend: the engine's own small-model classifier answers the same
251      // question, without the confidence the policy's threshold reads.
252      try {
253        const label = await $.model.classify(e.text, TIER_ORDER)
254        if (label) {
255          decision = {
256            tier: label as Tier,
257            confidence: null,
258            risky: null,
259            effort: null,
260            effortConfidence: null,
261          }
262        }
263      } catch (error) {
264        $.ui.log(`[Jev Model Router] built-in classifier failed: ${String(error)}`)
265      }
266    }
267
268    // What the decision model actually answered, whatever the policy then
269    // does with it. This is the line that proves the classification ran.
270    if (logDecisions) {
271      const ms = (await $.clock.now()) - startedAt
272      $.ui.log(`[Jev Model Router] jev: ${describeDecision(decision, ms)}`)
273    }
274
275    const resent = held === e.text
276    held = undefined
277    if (
278      !resent &&
279      e.origin.kind === 'composer' &&
280      decision?.newTask != null &&
281      decision.newTask >= NEW_TASK_THRESHOLD
282    ) {
283      held = e.text
284      // Keep the prompt in the chat; turn.start shows this under it and cancels the turn.
285      stopNextTurn = newSessionAdvice(e.text, decision.tier, policy.tiers[decision.tier])
286      return next(e)
287    }
288
289    earlier.push(e.text)
290    pending.put(decision)
291    return next(e)
292  })
293
294  on('turn.start', async ($, e, next) => {
295    const result = await next(e)
296    if (stopNextTurn) {
297      const advice = stopNextTurn
298      stopNextTurn = undefined
299      for (const line of advice) $.ui.log(`[Jev Model Router] ${line}`)
300      $.ui.toast('Jev: new task. /clear and resend it, or send it again to run it here.', { timeoutMs: 15000 })
301      await $.turn.abort({ turnId: e.turnId })
302    }
303    return result
304  })
305
306  on('turn.step', async function* ($, e, next) {
307    if (e.agentId) return yield* next(e)
308    const send = async function* (step: typeof e) {
309      await $.state.set(sentRef, { model: step.model, effort: step.effort === undefined ? null : String(step.effort) })
310      return yield* next(step)
311    }
312    // A turn that ran with the router off still started the chat, so `/router on` later must not switch.
313    if (off || !routeMainLoop) {
314      if (!modelSettled) {
315        modelSettled = true
316        await $.state.set(settledRef, { modelSettled, sessionModel: sessionModel ?? null })
317      }
318      return yield* send(e)
319    }
320
321    // Every request after the first reuses what the turn settled on, so
322    // neither the model nor the effort changes under its own tool loop.
323    if (e.index > 0 && e.turnId === appliedTurnId) {
324      return yield* send(applied ? { ...e, ...applied } : e)
325    }
326
327    const decision = pending.take()
328    const routing = route(decision, { model: e.model, effort: e.effort }, policy)
329    const change: { model?: string; effort?: Effort } = {}
330    // The main loop's `model` is sent to the API as written, so an alias
331    // becomes its id here; a subagent's (agent.spawn) may stay an alias.
332    if (routeMainModel && routing.model && !modelSettled) sessionModel = requestModelId(routing.model)
333    if (routeMainModel && sessionModel && sessionModel !== e.model) change.model = sessionModel
334    const keptMidway = routeMainModel && routing.model && modelSettled
335    if (!modelSettled) {
336      modelSettled = true
337      await $.state.set(settledRef, { modelSettled, sessionModel: sessionModel ?? null })
338    }
339    if (routeMainEffort && routing.effort) change.effort = routing.effort
340
341    const effectiveEffort = change.effort ?? e.effort
342    if ((change.model ?? e.model) === 'claude-opus-5-5' && (effectiveEffort === 'xhigh' || effectiveEffort === 'max')) {
343      change.effort = 'high'
344    }
345
346    appliedTurnId = e.turnId
347    applied = Object.keys(change).length > 0 ? change : null
348    // A row in the transcript scrolls away; this line stays on screen.
349
350    if (!applied) {
351      // A turn left alone is the common case, and it used to be silent, which
352      // made a working mod look like one that never loaded. Say what happened.
353      if (logDecisions) {
354        const suppressed =
355          routing.model && !routeMainModel
356            ? ' (main-loop model routing off)'
357            : keptMidway
358              ? ' (model kept mid-conversation)'
359              : ''
360        $.ui.log(`[Jev Model Router] main loop: ${routing.reason}${suppressed}`)
361      }
362      return yield* send(e)
363    }
364    if (logDecisions) {
365      const what = [change.model, change.effort && `effort ${change.effort}`]
366        .filter(Boolean)
367        .join(', ')
368      $.ui.log(`[Jev Model Router] main loop → ${what}: ${routing.reason}${keptMidway ? ' (model kept mid-conversation)' : ''}`)
369    }
370    return yield* send({ ...e, ...change })
371  })
372
373  on('turn.complete', async ($, e, next) => {
374    const result = await next(e)
375    if (!off && logDecisions && !e.agentId && e.usage) {
376      const sent = (await $.state.get(sentRef)).value
377      $.ui.log(`[Jev Model Router] outcome: ${sent?.model ?? e.usage.model} · effort ${sent?.effort ?? 'n/d'} · ${Math.round(e.durationMs / 1000)}s · ${e.usage.output_tokens} out · ${e.usage.cache_creation_input_tokens} written`)
378    }
379    return result
380  })
381
382  on('agent.spawn', async ($, e, next) => {
383    if (off) return next(e)
384    // Before the routing guards: a module whose switches are all off has still
385    // loaded, and that is exactly when its silence is most misleading.
386    if (!announced) {
387      announced = true
388      if (logDecisions) {
389        $.ui.log(
390          `[Jev Model Router] ${describeSetup(
391            active,
392            url,
393            {
394              subagentModel: routeSubagentModel,
395              mainEffort: routeMainEffort,
396              mainModel: routeMainModel,
397            },
398            forced === 'builtin',
399          )}`,
400        )
401      }
402    }
403
404    // A fork inherits its parent's model; `model` is ignored for it.
405    if (!routeSubagentModel || e.fork || e.model) return next(e)
406
407    if (!unusableReported) {
408      unusableReported = true
409      $.ui.log(`[Jev Model Router] provider "${forced}" has no key set; using the built-in classifier`)
410    }
411
412    const startedAt = await $.clock.now()
413    let decision: Decision | null = null
414    if (active) {
415      try {
416        const response = await Promise.race([
417          $.http.fetch(url, {
418            method: 'POST',
419            headers: requestHeaders(active, apiKey, modelId),
420            body: requestBody(
421              active,
422              { prompt: e.prompt, description: e.description, agentType: e.subagentType },
423              modelId,
424            ),
425          }),
426          $.clock.sleep(timeoutMs),
427        ])
428        if (response && response.ok) decision = readDecision(response.text)
429        else if (response) $.ui.log(`[Jev Model Router] ${active} responded ${response.status}`)
430        else $.ui.log(`[Jev Model Router] classification passed ${timeoutMs}ms; leaving the subagent alone`)
431      } catch (error) {
432        $.ui.log(`[Jev Model Router] classification failed: ${String(error)}`)
433      }
434    } else {
435      try {
436        const label = await $.model.classify(e.prompt, TIER_ORDER)
437        if (label) {
438          decision = {
439            tier: label as Tier,
440            confidence: null,
441            risky: null,
442            effort: null,
443            effortConfidence: null,
444          }
445        }
446      } catch (error) {
447        $.ui.log(`[Jev Model Router] built-in classifier failed: ${String(error)}`)
448      }
449    }
450
451    if (logDecisions) {
452      const ms = (await $.clock.now()) - startedAt
453      $.ui.log(`[Jev Model Router] jev (${e.subagentType}): ${describeDecision(decision, ms)}`)
454    }
455
456    // The subagent inherits the parent's model, so that is what a change is measured from.
457    // The Agent tool takes no effort, so only the model is ours to set here.
458    const current = e.parentModel
459    const { model, reason } = route(decision, { model: current }, policy)
460    if (!model) {
461      if (logDecisions) $.ui.log(`[Jev Model Router] ${e.subagentType}: ${reason}`)
462      return next(e)
463    }
464    if (logDecisions) $.ui.log(`[Jev Model Router] ${e.subagentType} → ${model}: ${reason}`)
465    return next({ ...e, model })
466  })
467}
468
hooks/policy.ts 577 lines
1/**
2 * model-router — pure decision logic.
3 *
4 * No `$` and no I/O here: this module only builds the request the decision
5 * API takes, reads its answer, and turns that answer into a model id. The
6 * hooks module does every call on `$` at its own call site.
7 *
8 * Two backends speak to the same model with different wire shapes:
9 *
10 *   typesafe  POST https://api.typesafe.ai/v1/systemone
11 *             `{ model, state, questions }`; a yes/no question is a `noul`
12 *             and every answer carries its own `confidence`.
13 *   gateway   POST https://ai-gateway.vercel.sh/v4/ai/evaluation-model
14 *             `{ state, questions }` with the model in a header; a yes/no
15 *             question is a `boolean`, and there is no `confidence` field —
16 *             it has to be derived from an optional distribution.
17 *
18 * The Gateway shape is not documented publicly; it was read from
19 * @ai-sdk/gateway and @ai-sdk/provider.
20 */
21
22export type Provider = 'typesafe' | 'gateway'
23
24export type Tier = 'fast' | 'balanced' | 'deep' | 'superDeep'
25
26export interface Tiers {
27  fast: string
28  balanced: string
29  deep: string
30  superDeep: string
31}
32
33export interface Decision {
34  tier: Tier
35  /** Confidence in the tier, or null when the backend reported none. */
36  confidence: number | null
37  /** P(true) that carrying the task out would itself be costly or final. */
38  risky: number | null
39  /** 0..3 along the effort rubric, or null when absent. */
40  effort: number | null
41  /** Confidence in the effort, or null when the backend reported none. */
42  effortConfidence: number | null
43  /** P(true) that the prompt starts a task unrelated to the session's earlier prompts. */
44  newTask?: number | null
45}
46
47/** The reasoning levels a turn can ask for, cheapest first. */
48export const EFFORT_ORDER = ['low', 'medium', 'high', 'xhigh'] as const
49
50export type Effort = (typeof EFFORT_ORDER)[number]
51
52export const TIER_ORDER: readonly Tier[] = ['fast', 'balanced', 'deep', 'superDeep']
53
54/**
55 * How each tier is described to the decision model. Deliberately about the
56 * shape of the work, not about model names: the model never sees an id.
57 */
58const TIER_CRITERIA: Record<Tier, string> = {
59  fast: 'Trivially dumb: no thinking needed at all. Run one command, print or read one file, answer a one-line factual question already in context. If in doubt, it is not this tier.',
60  balanced:
61    'Ordinary engineering: implement a well-specified change across a few files, write tests, fix a clearly described bug, review a small diff.',
62  deep: 'Hard or high-stakes: architecture and design, debugging a failure whose cause is unknown, security, data migrations, concurrency, anything touching production or money.',
63  superDeep:
64    'Large work to orchestrate: a big refactor or a feature spanning many files or modules, planned and split across several steps or subagents.',
65}
66
67const EFFORT_RUBRIC = ['almost none', 'some', 'a lot', 'as much as possible'] as const
68
69export const DEFAULT_BASE_URL: Record<Provider, string> = {
70  typesafe: 'https://api.typesafe.ai',
71  gateway: 'https://ai-gateway.vercel.sh/v4/ai',
72}
73
74/**
75 * The Gateway's own protocol version, sent as `ai-gateway-protocol-version`.
76 * Tracks the `AI_GATEWAY_PROTOCOL_VERSION` of `@ai-sdk/gateway` (4.0.87).
77 */
78const AI_GATEWAY_PROTOCOL_VERSION = '0.0.1'
79
80export const DEFAULT_MODEL: Record<Provider, string> = {
81  typesafe: 'jev-latest',
82  gateway: 'typesafe-ai/jev',
83}
84
85/**
86 * Which backend a configuration asks for, or null for the built-in
87 * classifier. `auto` prefers TypeSafe, since it is the only one that reports
88 * a calibrated confidence; a forced backend whose key is missing resolves to
89 * null rather than falling through to the other one's key.
90 */
91export function selectProvider(
92  forced: string,
93  typesafeKey: string,
94  gatewayKey: string,
95): Provider | null {
96  if (forced === 'builtin') return null
97  if (forced === 'typesafe') return typesafeKey ? 'typesafe' : null
98  if (forced === 'gateway') return gatewayKey ? 'gateway' : null
99  if (typesafeKey) return 'typesafe'
100  if (gatewayKey) return 'gateway'
101  return null
102}
103
104/** The full endpoint a backend posts to. */
105export function endpoint(provider: Provider, baseUrl: string): string {
106  const root = baseUrl.replace(/\/+$/, '')
107  return provider === 'typesafe' ? `${root}/v1/systemone` : `${root}/evaluation-model`
108}
109
110/** The `questions` map, in the shape the backend's schema names. */
111export function questions(provider: Provider, withNewTask = false): Record<string, unknown> {
112  const yesNo = provider === 'typesafe' ? 'noul' : 'boolean'
113  return {
114    ...(withNewTask && {
115      newTask: {
116        type: yesNo,
117        instructions:
118          'The prompt starts a new task unrelated to the earlier prompts of this session, so nothing said in that conversation would help with it.',
119      },
120    }),
121    tier: {
122      type: 'choice',
123      instructions: 'Which is the cheapest tier that can complete this coding task well?',
124      criteria: TIER_CRITERIA,
125    },
126    effort: {
127      type: 'score',
128      instructions: 'How much step-by-step reasoning does this task need?',
129      criteria: EFFORT_RUBRIC,
130    },
131    risky: {
132      // The same question under two names: `noul` on TypeSafe's own API,
133      // `boolean` in the AI SDK's evaluation schema.
134      type: provider === 'typesafe' ? 'noul' : 'boolean',
135      // Asked about the act, not the subject. The first wording ("the task
136      // touches production, money, credentials") scored 0.96 on "add a
137      // refund endpoint that calls Stripe" — ordinary code that happens to be
138      // about money — and would have escalated it past a 0.98-confidence
139      // answer of the balanced tier.
140      instructions:
141        'Carrying out this task would itself change production, move real money, or alter data that cannot be restored. Writing or testing code that deals with such things, without running it against the real system, does not count.',
142    },
143  }
144}
145
146/** The request body. The Gateway carries the model in a header instead. */
147export function requestBody(
148  provider: Provider,
149  state: Record<string, unknown>,
150  model: string,
151): string {
152  const body =
153    provider === 'typesafe'
154      ? { model, state, questions: questions(provider, 'earlierPrompts' in state) }
155      : { state, questions: questions(provider, 'earlierPrompts' in state) }
156  return JSON.stringify(body)
157}
158
159/** The request headers. */
160export function requestHeaders(
161  provider: Provider,
162  apiKey: string,
163  model: string,
164): Record<string, string> {
165  const common = { 'content-type': 'application/json', authorization: `Bearer ${apiKey}` }
166  if (provider === 'typesafe') return common
167  return {
168    ...common,
169    'ai-gateway-auth-method': 'api-key',
170    'ai-model-id': model,
171    // The Gateway rejects any request that does not name the protocol it
172    // speaks: 400 "Unsupported gateway protocol version". Every other header
173    // here is accepted without it, so the omission fails the whole backend.
174    'ai-gateway-protocol-version': AI_GATEWAY_PROTOCOL_VERSION,
175    'ai-evaluation-model-specification-version': '4',
176  }
177}
178
179function isTier(value: unknown): value is Tier {
180  return TIER_ORDER.includes(value as Tier)
181}
182
183/**
184 * Reads a response from either backend.
185 *
186 * TypeSafe's own API reports a `confidence` per answer and a `noul` number
187 * for a yes/no question. The Gateway reports neither: confidence has to come
188 * from the highest probability of a distribution that is itself optional, and
189 * a yes/no answer arrives as `probability`. Both are handled, and a missing
190 * confidence reads as null rather than as a number the policy would trust.
191 */
192export function readDecision(responseText: string): Decision | null {
193  let parsed: unknown
194  try {
195    parsed = JSON.parse(responseText)
196  } catch {
197    return null
198  }
199  const answers = (parsed as { answers?: Record<string, Record<string, unknown>> }).answers
200  if (!answers) return null
201
202  const tierAnswer = answers.tier
203  if (!tierAnswer || !isTier(tierAnswer.choice)) return null
204
205  const effortAnswer = answers.effort
206  const yesOf = (answer: Record<string, unknown> | undefined) =>
207    typeof answer?.noul === 'number'
208      ? answer.noul
209      : typeof answer?.probability === 'number'
210        ? answer.probability
211        : null
212  const risky = yesOf(answers.risky)
213
214  return {
215    tier: tierAnswer.choice,
216    confidence: confidenceOf(tierAnswer),
217    effort: typeof effortAnswer?.score === 'number' ? effortAnswer.score : null,
218    effortConfidence: effortAnswer ? confidenceOf(effortAnswer) : null,
219    risky,
220    newTask: yesOf(answers.newTask),
221  }
222}
223
224/** How sure Jev must be that a prompt is a new task before it is held back. */
225export const NEW_TASK_THRESHOLD = 0.8
226
227/** What to show instead of running a prompt that belongs in a new session. */
228export function newSessionAdvice(text: string, tier: Tier, model: string): string[] {
229  const quoted = `'${text.replace(/'/g, `'\\''`)}'`
230  return [
231    `New task, unrelated to this chat. Jev picks ${tier} (${model}).`,
232    'Start fresh: /clear, then send it again.',
233    `Or keep this chat and open a new tab: claude --model ${requestModelId(model)} ${quoted}`,
234    'Jev wrong? Send the same prompt again to run it here.',
235  ]
236}
237
238/**
239 * How sure an answer is. TypeSafe reports it; the Gateway does not, so there
240 * it is the highest probability of a distribution that is itself optional.
241 */
242function confidenceOf(answer: Record<string, unknown>): number | null {
243  if (typeof answer.confidence === 'number') return answer.confidence
244  const probabilities = answer.probabilities as Record<string, number> | undefined
245  const values = probabilities ? Object.values(probabilities) : []
246  return values.length > 0 ? Math.max(...values) : null
247}
248
249/** The rubric score (0..3) as a level: medium by default, high from 2, xhigh from 2.75. */
250export function effortLevel(score: number): Effort {
251  if (score < 0.3) return 'low'
252  if (score < 2) return 'medium'
253  return score < 2.75 ? 'high' : 'xhigh'
254}
255
256/**
257 * Where a reasoning level sits on the ladder, or null when its place cannot
258 * be known. `max` is above every rung the rubric can produce, so it ranks
259 * above them without joining EFFORT_ORDER, which is also the set of values
260 * this router is allowed to ask for.
261 */
262export function effortRank(effort: string | number | undefined): number | null {
263  if (typeof effort !== 'string') return null
264  if (effort === 'max') return EFFORT_ORDER.length
265  const index = EFFORT_ORDER.indexOf(effort as Effort)
266  return index === -1 ? null : index
267}
268
269/**
270 * Where a model id sits on the tier ladder, by matching it against the
271 * configured tier names first and then the family words. Null when it matches
272 * none, in which case the change is treated as an upgrade rather than guessed
273 * at: an unrecognised id gets the gentler threshold, never the strict one.
274 */
275export function rankOf(model: string, tiers: Tiers): number | null {
276  const lowered = model.toLowerCase()
277  for (let index = 0; index < TIER_ORDER.length; index++) {
278    const tier = TIER_ORDER[index] as Tier
279    const configured = tiers[tier].toLowerCase()
280    if (configured && lowered.includes(configured)) return index
281  }
282  if (lowered.includes('haiku')) return 0
283  if (lowered.includes('sonnet')) return 1
284  if (lowered.includes('opus')) return 2
285  if (lowered.includes('fable')) return 3
286  return null
287}
288
289/**
290 * The full id a family alias names on the main loop.
291 *
292 * `agent.spawn` takes an alias (`haiku`) the way the Agent tool does, but
293 * `turn.step`'s `model` is the id the engine already resolved for the request
294 * and goes to the API as written: an alias there is refused ("There's an
295 * issue with the selected model (haiku)"). So the tiers stay aliases in the
296 * options, and only a main-loop rewrite resolves them, here.
297 */
298const ALIAS_IDS: Record<string, string> = {
299  haiku: 'claude-haiku-5-5',
300  sonnet: 'claude-sonnet-5-5',
301  opus: 'claude-opus-5-5',
302  fable: 'claude-fable-5-1',
303}
304
305/**
306 * What to write into `turn.step`'s `model`: a full id as given, or the id
307 * behind a family alias. Anything else is returned unchanged for the engine
308 * to judge.
309 */
310export function requestModelId(model: string): string {
311  return ALIAS_IDS[model.trim().toLowerCase()] ?? model
312}
313
314export interface PolicyConfig {
315  tiers: Tiers
316  /**
317   * How sure the decision must be to spend more (a bigger model, more
318   * reasoning). Being wrong here costs money, so the bar is low.
319   */
320  minUpgradeConfidence: number
321  /**
322   * How sure it must be to spend less. Being wrong here means a task handled
323   * by too small a model or too little thought, so the bar is high.
324   */
325  minDowngradeConfidence: number
326}
327
328export interface Routing {
329  /** The model to run on, or null to leave the request as it is. */
330  model: string | null
331  /** The reasoning level to ask for, or null to leave it as it is. */
332  effort: Effort | null
333  /** Why, for the log line. */
334  reason: string
335}
336
337const NOTHING: Routing = { model: null, effort: null, reason: 'no decision' }
338
339/**
340 * Whether a change of rank passes its threshold. Both directions are allowed;
341 * they just do not have to clear the same bar, because the two mistakes do not
342 * cost the same. A move whose direction cannot be told (an unrecognised
343 * current value) is treated as an upgrade.
344 */
345function allowed(
346  wanted: number,
347  current: number | null,
348  confidence: number | null,
349  config: PolicyConfig,
350): boolean {
351  if (current !== null && wanted === current) return false
352  const isDowngrade = current !== null && wanted < current
353  const bar = isDowngrade ? config.minDowngradeConfidence : config.minUpgradeConfidence
354  // A backend that reports no confidence (the Gateway without a distribution,
355  // or the built-in classifier) clears the upgrade bar but never the
356  // downgrade one: spending less on an unmeasured hunch is the bad trade.
357  if (confidence === null) return !isDowngrade
358  return confidence >= bar
359}
360
361/**
362 * Turns a decision into a model and a reasoning level, either of which may be
363 * null to leave the request as it is. Both can move in either direction.
364 */
365export function route(
366  decision: Decision | null,
367  current: { model: string; effort?: string | number },
368  config: PolicyConfig,
369): Routing {
370  if (!decision) return NOTHING
371
372  let tier = decision.tier
373  let effortScore = decision.effort
374  let forced = false
375
376  // Carrying out something final is never worth the saving: take the deep
377  // tier and real reasoning, whatever the cheaper answer said, and skip the
378  // thresholds — this is the one case that is not a confidence question.
379  if (decision.risky !== null && decision.risky > 0.7) {
380    if (TIER_ORDER.indexOf(tier) < TIER_ORDER.indexOf('deep')) tier = 'deep'
381    effortScore = Math.max(effortScore ?? 0, 2)
382    forced = true
383  }
384
385  const wantedTier = TIER_ORDER.indexOf(tier)
386  const currentTier = rankOf(current.model, config.tiers)
387  const wantedModel = config.tiers[tier]
388
389  const model =
390    wantedModel &&
391    wantedModel !== current.model &&
392    // Risk raises the model floor too; forcing never pulls superDeep down to deep.
393    (forced
394      ? currentTier === null || wantedTier > currentTier
395      : allowed(wantedTier, currentTier, decision.confidence, config))
396      ? wantedModel
397      : null
398
399  let effort: Effort | null = null
400  if (effortScore !== null) {
401    const currentRank = effortRank(current.effort)
402    let wantedRank = EFFORT_ORDER.indexOf(effortLevel(effortScore))
403
404    // High effort is for planning-heavy (deep tier or above) or sensitive (risky) work; everything else stops at medium.
405    const needsHigh = wantedTier >= TIER_ORDER.indexOf('deep') || (decision.risky ?? 0) > 0.5
406    if (!needsHigh) wantedRank = Math.min(wantedRank, EFFORT_ORDER.indexOf('medium'))
407
408    // Risk raises the floor; it must never lower one. Forcing only skips the
409    // thresholds, so without this clamp a task already at `xhigh` or `max`
410    // and rated mechanically simple would be pulled down to `high` with no
411    // confidence check at all — the opposite of what the rule is for.
412    if (forced && currentRank !== null) wantedRank = Math.max(wantedRank, currentRank)
413
414    // A numeric effort is the caller's own scale, not this ladder; leave it.
415    const comparable = typeof current.effort !== 'number'
416    const wanted = EFFORT_ORDER[Math.min(EFFORT_ORDER.length - 1, wantedRank)] as Effort
417    if (
418      comparable &&
419      wantedRank !== currentRank &&
420      (forced || allowed(wantedRank, currentRank, decision.effortConfidence, config))
421    ) {
422      effort = wanted
423    }
424  }
425
426  const said = decision.confidence === null ? 'confidence n/d' : `confidence ${decision.confidence.toFixed(2)}`
427
428  if (!model && !effort) {
429    // Naming what it wanted and what it kept is the whole point of this line.
430    // Without it, a mod that classified and decided to leave the request alone
431    // is indistinguishable from one that never loaded.
432    const wantedEffort = effortScore === null ? null : effortLevel(effortScore)
433    const kept = `${current.model}${current.effort === undefined ? '' : `/${current.effort}`}`
434    const modelDiffers = Boolean(wantedModel) && wantedModel !== current.model
435    const effortDiffers = wantedEffort !== null && wantedEffort !== current.effort
436    if (!modelDiffers && !effortDiffers) {
437      return { model: null, effort: null, reason: `stayed on ${kept}: already the right fit` }
438    }
439    const target = modelDiffers ? wantedModel : `effort ${wantedEffort}`
440    const sure = modelDiffers ? decision.confidence : decision.effortConfidence
441    const why =
442      sure === null
443        ? `no confidence score, so no switch to ${target}`
444        : `too unsure to switch to ${target} (${Math.round(sure * 100)}% sure)`
445    return { model: null, effort: null, reason: `stayed on ${kept}: ${why}` }
446  }
447
448  return { model, effort, reason: forced ? `${tier}, forced by risk` : `${tier} (${said})` }
449}
450
451/**
452 * Whether a prompt is a slash command and nothing else (`/simplify`). The
453 * decision model sees only the name, never the skill or command it runs:
454 * measured on TypeSafe (three calls each), `/simplify`, `/run` and `/github`
455 * came back fast with effort 0.1 to 0.5, low effort for a multi-step skill,
456 * while `/code-review` and `/security-review` came back balanced and deep.
457 * With text after the name there is a task to read, and it is classified.
458 * A one-segment path alone (`/etc`) matches too; nobody sends one as a task.
459 */
460export function bareCommand(text: string): boolean {
461  return /^\/[^\s/]+$/.test(text.trim())
462}
463
464/**
465 * Holds a prompt's classification until the turn that reads that prompt
466 * starts.
467 *
468 * Nothing ties a decision to the turn it belongs to. Prompts can be queued
469 * while the model is busy, a peer session's message can be delivered inside a
470 * running turn, and `prompt.submit` carries no turn id at all while the
471 * session is idle. So when more than one prompt is waiting, `take` reports
472 * none: running a turn on another prompt's decision is a worse outcome than
473 * not routing it, and not routing is what every other failure path here does.
474 */
475export function pendingDecisions(): {
476  put(decision: Decision | null): void
477  take(): Decision | null
478} {
479  let held: Decision | null = null
480  let waiting = 0
481
482  return {
483    put(decision) {
484      waiting += 1
485      // Past the first, which prompt a turn will read is unknowable, so the
486      // slot is emptied instead of holding a decision that may not fit.
487      held = waiting === 1 ? decision : null
488    },
489    take() {
490      const decision = waiting === 1 ? held : null
491      held = null
492      waiting = 0
493      return decision
494    },
495  }
496}
497
498/** A number for the log, or `n/d` when the backend reported none. */
499function reported(value: number | null): string {
500  return value === null ? 'n/d' : value.toFixed(2)
501}
502
503/**
504 * The one-time line that says the router is alive, which backend answers it,
505 * and which of the three switches are on.
506 *
507 * Without this, a router that loaded and a router that never loaded are told
508 * apart only by the absence of later lines, which is not evidence of anything.
509 */
510export function describeSetup(
511  provider: Provider | null,
512  url: string,
513  switches: { subagentModel: boolean; mainEffort: boolean; mainModel: boolean },
514  // `provider: "builtin"` is a choice, not a missing key. Reporting it as a
515  // credential problem sends someone hunting for a key they meant to omit.
516  builtinByChoice = false,
517): string {
518  const backend = provider
519    ? `${provider} (${url})`
520    : builtinByChoice
521      ? 'the built-in classifier, by choice'
522      : 'the built-in classifier, no key set'
523  const on = [
524    switches.subagentModel && 'subagent model',
525    switches.mainEffort && 'main effort',
526    switches.mainModel && 'main model',
527  ].filter(Boolean)
528  return `ready on ${backend}; routing ${on.length > 0 ? on.join(', ') : 'nothing, every switch is off'}`
529}
530
531/**
532 * What the decision model answered, before any policy touches it: the raw
533 * tier, effort and risk with their confidences, and how long it took.
534 *
535 * This is the line that shows the classification happened at all, separately
536 * from whether the policy then decided to act on it.
537 */
538export function describeDecision(decision: Decision | null, ms: number | null): string {
539  const took = ms === null ? '' : ` · ${Math.round(ms)}ms`
540  if (!decision) return `no answer${took}`
541
542  const parts = [`tier ${decision.tier} (${reported(decision.confidence)})`]
543  if (decision.effort !== null) {
544    parts.push(
545      `effort ${decision.effort.toFixed(1)} → ${effortLevel(decision.effort)} (${reported(decision.effortConfidence)})`,
546    )
547  }
548  if (decision.risky !== null) parts.push(`risky ${reported(decision.risky)}`)
549  if (decision.newTask != null) parts.push(`new task ${reported(decision.newTask)}`)
550  return parts.join(' · ') + took
551}
552
553/**
554 * The persistent status line: the last thing the router did, short enough to
555 * sit on screen beside the engine's own notices.
556 */
557export function describeStatus(
558  decision: Decision | null,
559  change: { model?: string; effort?: Effort } | null,
560  current: { model: string; effort?: string | number },
561): string {
562  const model = modelName(change?.model ?? current.model)
563  const effort = change?.effort ?? current.effort
564  const running = effort === undefined ? model : `${model} · ${effort} effort`
565  if (!decision) return `${running} · no answer`
566  const confidence = decision.confidence === null ? '' : ` ${Math.round(decision.confidence * 100)}%`
567  return `${running} · ${decision.tier}${confidence}`
568}
569
570/** `claude-haiku-5-5` as "Haiku 5.5"; an alias or unknown id is only capitalised. */
571export function modelName(id: string): string {
572  const match = /^claude-([a-z]+)-(\d+)(?:-(\d{1,2})(?!\d))?/.exec(id)
573  const capital = (word: string) => word.charAt(0).toUpperCase() + word.slice(1)
574  if (!match) return capital(id)
575  return `${capital(match[1] as string)} ${match[2]}${match[3] ? `.${match[3]}` : ''}`
576}
577
types/index.d.ts 9 lines
1export type Settled = { modelSettled: boolean; sessionModel: string | null }
2export type Sent = { model: string; effort: string | null }
3
4declare module 'claude-code' {
5  interface PluginState {
6    'model-router-slim': { settled: Settled; off: boolean; sent: Sent }
7  }
8}
9