SLOPSHOPPER

jev-model-router

Sets the model of every subagent spawn (agent.spawn). The agent type sets the baseline: agents whose definition pins a model keep it, general-purpose, claude…

networkagents
A shopper browsing a rack in a slop shop
README

dotfiles

Configs for my machine.

AI tooling

All agent-related configuration lives under ai/: shared agent rules, Claude defaults, MCP definitions, and reusable skills. Run ./setup to install the shared rules, MCP configuration, and skills. Run ./ai/skills/install when you only need to refresh the skills.

Tests

./test runs every check: shellcheck, config parsing, the herdr keymap check, the herdr-task / herdr-status tests (fake herdr, no server), the vim-mode fzf defaults, and the aws and mcps tests. ./test herdr fzf runs some. Checks whose tool is missing are skipped locally; CI (.github/workflows/test.yml) installs everything and runs with TEST_STRICT=1, so nothing is skipped there.

Inspiration

Source 2 files
hooks/jev-model-router.ts 98 lines
1/**
2 * jev-model-router: sets the model of every subagent spawn, so routing
3 * doesn't depend on the main session remembering /delegate's table.
4 *
5 * Only `agent.spawn` is hooked. The baseline is the agent type (policy.ts):
6 * types whose definition pins a model keep it, judged types (general-purpose,
7 * claude, Plan) get sonnet, and TypeSafe's Jev may move a judged spawn down to
8 * haiku, or up to opus when it reads the task as risky. Sonnet is the ceiling
9 * otherwise; a description starting with `[opus]` is the explicit way up.
10 *
11 * Fail-safe, not fail-open: no key, an error, or a verdict later than the
12 * latency budget leaves the baseline, not the parent's model (Opus).
13 *
14 * Mods are on by default from Claude Code v2.1.287 (CLAUDE_CODE_ENABLE_FUNCTION_HOOKS
15 * for older builds). Typed against https://github.com/anthropics/claude-code/tree/main/mods
16 */
17import type { Register } from 'claude-code'
18import {
19  DEFAULT_BASE_URL,
20  DEFAULT_MODEL,
21  DEFAULT_POLICY,
22  endpoint,
23  needsJudgment,
24  readDecision,
25  requestBody,
26  requestHeaders,
27  route,
28} from './policy.ts'
29import type { Decision, PolicyConfig, Spawn } from './policy.ts'
30
31export const register: Register = (on, options) => {
32  const text = (key: string, fallback: string) =>
33    typeof options[key] === 'string' && options[key] ? (options[key] as string) : fallback
34  const number = (key: string, fallback: number) =>
35    typeof options[key] === 'number' ? (options[key] as number) : fallback
36  const flag = (key: string, fallback: boolean) =>
37    typeof options[key] === 'boolean' ? (options[key] as boolean) : fallback
38
39  const timeoutMs = number('timeoutMs', 800)
40  const maxBriefChars = number('maxBriefChars', 4000)
41  const logDecisions = flag('logDecisions', true)
42  const policy: PolicyConfig = {
43    minHaikuConfidence: number('minHaikuConfidence', DEFAULT_POLICY.minHaikuConfidence),
44    minRiskyForOpus: number('minRiskyForOpus', DEFAULT_POLICY.minRiskyForOpus),
45  }
46  const baseUrl = text('typesafeBaseUrl', DEFAULT_BASE_URL)
47  const modelId = text('typesafeModel', DEFAULT_MODEL)
48  const url = endpoint(baseUrl)
49
50  let apiKey: string | null = null
51
52  on('agent.spawn', async ($, e, next) => {
53    const spawn: Spawn = {
54      subagentType: e.subagentType,
55      description: e.description,
56      model: e.model,
57      fork: e.fork,
58    }
59
60    let decision: Decision | null = null
61    let waited = ''
62    if (needsJudgment(spawn)) {
63      // Resolve the key lazily and once: the plugin's own userConfig field
64      // first, then the environment variable the shell already exports.
65      if (apiKey === null) {
66        apiKey = text('typesafeApiKey', '') || (await $.env.get('TYPESAFE_API_KEY')) || ''
67        if (logDecisions && !apiKey) {
68          $.ui.log('[jev-model-router] no TypeSafe key (userConfig.typesafeApiKey or $TYPESAFE_API_KEY): routing by agent type only')
69        }
70      }
71      if (apiKey) {
72        const startedAt = await $.clock.now()
73        try {
74          const response = await Promise.race([
75            $.http.fetch(url, {
76              method: 'POST',
77              headers: requestHeaders(apiKey),
78              body: requestBody({ ...spawn, prompt: e.prompt }, modelId, maxBriefChars),
79            }),
80            $.clock.sleep(timeoutMs),
81          ])
82          if (response && response.ok) decision = readDecision(response.text)
83          else if (response) waited = `, typesafe ${response.status}`
84          else waited = `, no verdict in ${timeoutMs}ms`
85        } catch (error) {
86          waited = `, typesafe failed: ${String(error)}`
87        }
88        waited = `, ${(await $.clock.now()) - startedAt}ms${waited}`
89      }
90    }
91
92    const { model, reason } = route(spawn, decision, policy)
93    if (logDecisions) $.ui.log(`[jev-model-router] ${e.subagentType}: ${reason}${waited}`)
94
95    return model ? next({ ...e, model }) : next(e)
96  })
97}
98
hooks/policy.ts 207 lines
1/**
2 * jev-model-router: pure decision logic. No `$`, no I/O: builds the TypeSafe
3 * request, reads its answer, and turns a spawn plus that answer into a model.
4 *
5 * The baseline is the agent type, never the parent's model. The parent is
6 * Opus, and starting every spawn from Opus (then asking Jev for a confident
7 * downgrade) is what kept subagents on Opus. Types whose definition pins a
8 * model keep it; Jev only judges the types whose tier depends on the task,
9 * choosing haiku or sonnet. Sonnet is the ceiling: Opus only for a brief the
10 * caller tags `[opus]`, or one Jev reads as risky.
11 */
12
13export type Model = 'haiku' | 'sonnet' | 'opus'
14export type Tier = 'mechanical' | 'ordinary' | 'deep'
15
16/**
17 * Agent types whose definition fixes the model: ai/claude/agents/*.md plus the
18 * built-ins that carry their own. Kept in step with the agent files by
19 * ai/claude/tests/jev-policy.test.ts.
20 */
21export const PINNED: Readonly<Record<string, Model>> = {
22  Explore: 'haiku',
23  fetcher: 'haiku',
24  'mechanical-editor': 'haiku',
25  'claude-code-guide': 'haiku',
26  'feature-implementer': 'sonnet',
27  researcher: 'sonnet',
28  browser: 'sonnet',
29  'statusline-setup': 'sonnet',
30}
31
32/** Agent types with no fixed tier: Jev picks haiku or sonnet, sonnet without a verdict. */
33export const JUDGED: ReadonlySet<string> = new Set(['general-purpose', 'claude', 'Plan'])
34
35/** A brief whose description starts with this runs on Opus, no questions asked. */
36export const OPUS_TAG = /^\s*\[opus\]/i
37
38const TIER_MODEL: Record<Tier, Model> = { mechanical: 'haiku', ordinary: 'sonnet', deep: 'sonnet' }
39
40const TIER_CRITERIA: Record<Tier, string> = {
41  mechanical:
42    'Lookups, searches, fetching and summarising output, well-specified edits, renames, boilerplate, or an already-diagnosed fix. The answer or exact change is known or directly findable; no design left to do.',
43  ordinary:
44    'A feature, bug fix, refactor, review or research question whose approach is decided but still takes judgment across several files or sources.',
45  deep: 'Open-ended: the cause is unknown, the approach is undecided, or it is architecture, security, a data migration, or something whose shape has to be discovered while doing it.',
46}
47
48export interface Decision {
49  tier: Tier
50  /** Confidence in the tier, or null when the backend reported none. */
51  confidence: number | null
52  /** P(true) that carrying the task out wrong would be costly or hard to reverse. */
53  risky: number | null
54}
55
56/** What the router knows about a spawn: the parts of `agent.spawn`'s input it reads. */
57export interface Spawn {
58  subagentType: string
59  description: string
60  /** The Agent tool's `model` parameter as given; undefined lets the definition decide. */
61  model?: string
62  fork: boolean
63}
64
65export interface PolicyConfig {
66  /** Jev's confidence in "mechanical" needed to pick haiku over sonnet. */
67  minHaikuConfidence: number
68  /** Jev's risky probability that lifts a judged spawn to Opus. */
69  minRiskyForOpus: number
70}
71
72export const DEFAULT_POLICY: PolicyConfig = { minHaikuConfidence: 0.6, minRiskyForOpus: 0.8 }
73
74export interface Routing {
75  /** The model to set on the spawn, or null to leave it as the caller built it. */
76  model: Model | null
77  reason: string
78}
79
80export const DEFAULT_BASE_URL = 'https://api.typesafe.ai'
81export const DEFAULT_MODEL = 'jev-latest'
82
83/** The model family an alias or full id names, or null when it names none. */
84export function familyOf(model: string | undefined): Model | 'fable' | null {
85  if (!model) return null
86  const lowered = model.toLowerCase()
87  for (const family of ['haiku', 'sonnet', 'opus', 'fable'] as const) {
88    if (lowered.includes(family)) return family
89  }
90  return null
91}
92
93function isCheap(family: ReturnType<typeof familyOf>): boolean {
94  return family === 'haiku' || family === 'sonnet'
95}
96
97function isExpensive(family: ReturnType<typeof familyOf>): boolean {
98  return family === 'opus' || family === 'fable'
99}
100
101/**
102 * Whether Jev's verdict can change this spawn's model, so the call (latency,
103 * the brief leaving the machine) is worth making. Only judged types the caller
104 * left unpriced or priced at Opus qualify.
105 */
106export function needsJudgment(spawn: Spawn): boolean {
107  if (spawn.fork || OPUS_TAG.test(spawn.description)) return false
108  if (!JUDGED.has(spawn.subagentType)) return false
109  return !isCheap(familyOf(spawn.model))
110}
111
112function said(decision: Decision): string {
113  const confidence = decision.confidence === null ? 'n/d' : decision.confidence.toFixed(2)
114  return `jev ${decision.tier} ${confidence}`
115}
116
117/** Turns a spawn and Jev's verdict (or none) into a model. */
118export function route(spawn: Spawn, decision: Decision | null, config: PolicyConfig = DEFAULT_POLICY): Routing {
119  if (spawn.fork) return { model: null, reason: 'kept, a fork inherits its parent' }
120  if (OPUS_TAG.test(spawn.description)) return { model: 'opus', reason: '→opus (tagged [opus])' }
121
122  const asked = familyOf(spawn.model)
123  const pinned = PINNED[spawn.subagentType]
124
125  if (pinned) {
126    if (isExpensive(asked)) return { model: pinned, reason: `→${pinned} (asked ${asked}, capped to its definition)` }
127    return { model: null, reason: `kept ${asked ?? pinned} (${asked ? 'asked' : 'definition'})` }
128  }
129
130  if (!JUDGED.has(spawn.subagentType)) {
131    if (isExpensive(asked)) return { model: 'sonnet', reason: `→sonnet (asked ${asked}, capped)` }
132    return { model: null, reason: `kept ${asked ?? 'its definition'} (unknown type)` }
133  }
134
135  if (isCheap(asked)) return { model: null, reason: `kept ${asked} (asked)` }
136
137  if (!decision) return { model: 'sonnet', reason: '→sonnet (no verdict)' }
138
139  if (decision.risky !== null && decision.risky >= config.minRiskyForOpus) {
140    return { model: 'opus', reason: `→opus (jev risky ${decision.risky.toFixed(2)})` }
141  }
142
143  const confident = decision.confidence !== null && decision.confidence >= config.minHaikuConfidence
144  const model = decision.tier === 'mechanical' && !confident ? 'sonnet' : TIER_MODEL[decision.tier]
145  const note = decision.tier === 'deep' ? ', capped' : decision.tier === 'mechanical' && !confident ? ', below threshold' : ''
146  return { model, reason: `→${model} (${said(decision)}${note})` }
147}
148
149export function endpoint(baseUrl: string): string {
150  return `${baseUrl.replace(/\/+$/, '')}/v1/systemone`
151}
152
153/** The brief as Jev sees it: the prompt cut to `maxChars`, which bounds latency and what leaves the machine. */
154export function requestBody(spawn: Spawn & { prompt: string }, model: string, maxChars: number): string {
155  const prompt = spawn.prompt.length > maxChars ? `${spawn.prompt.slice(0, maxChars)}\n[truncated]` : spawn.prompt
156  return JSON.stringify({
157    model,
158    state: { prompt, description: spawn.description, subagentType: spawn.subagentType },
159    questions: {
160      tier: {
161        type: 'choice',
162        instructions: 'Which is the cheapest tier of engineer that can complete this task well, unsupervised?',
163        criteria: TIER_CRITERIA,
164      },
165      risky: {
166        type: 'noul',
167        instructions:
168          'Carrying out this task wrong would itself be costly or hard to reverse (touches production, money, credentials, or data that cannot be restored). Writing or testing code that deals with such things, without running it against the real system, does not count.',
169      },
170    },
171  })
172}
173
174export function requestHeaders(apiKey: string): Record<string, string> {
175  return { 'content-type': 'application/json', authorization: `Bearer ${apiKey}` }
176}
177
178function isTier(value: unknown): value is Tier {
179  return value === 'mechanical' || value === 'ordinary' || value === 'deep'
180}
181
182function confidenceOf(answer: Record<string, unknown>): number | null {
183  if (typeof answer.confidence === 'number') return answer.confidence
184  const probabilities = answer.probabilities as Record<string, number> | undefined
185  const values = probabilities ? Object.values(probabilities) : []
186  return values.length > 0 ? Math.max(...values) : null
187}
188
189export function readDecision(responseText: string): Decision | null {
190  let parsed: unknown
191  try {
192    parsed = JSON.parse(responseText)
193  } catch {
194    return null
195  }
196  const answers = (parsed as { answers?: Record<string, Record<string, unknown>> } | null)?.answers
197  if (!answers) return null
198
199  const tierAnswer = answers.tier
200  if (!tierAnswer || !isTier(tierAnswer.choice)) return null
201
202  const riskyAnswer = answers.risky
203  const risky = typeof riskyAnswer?.noul === 'number' ? riskyAnswer.noul : null
204
205  return { tier: tierAnswer.choice, confidence: confidenceOf(tierAnswer), risky }
206}
207