SLOPSHOPPER

jev-router

Routes each Claude Code turn to Haiku, Opus or Fable using TypeSafe's Jev, asks you when Jev is unsure, sends all image work to OpenAI GPT-Image-2.5, and…

guardcommandstatusprompttoolmodel
v0.1.0no licenseupdated 2026-10-20davidmclaughlinemail/jev-router
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · jev-router
› fix the failing auth test and add an audit log call ⏺ Read(src/auth.ts) ⎿ Read 6 lines ⏺ Update(src/auth.ts) ⎿ Added 2 lines, removed 1 line ⏺ Bash(bun test) ⎿ 3 pass, 1 fail ● Done. refresh now rejects expired claims and logs an audit event. ✻ Worked for 42s · done 4:20 PM › /route ⎿ jev-router: Last turn: Opus 5.5 on claude-opus-5-5. ⎿ jev-router: Why: Jev unavailable (TYPESAFE_API_KEY is not set); default route. ⎿ jev-router: Classifier: default, 0 ms. ⎿ jev-router: Opus 5.5 #################### 100% ⎿ jev-router: Haiku 5.5 0% ⎿ jev-router: Fable 5.1 0% ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts ⚠ jev-router: Opus 5.5 (default)
README

jev-router

A Claude Code mod that routes every turn to the right model.

  • Jev decides. Each prompt goes to TypeSafe's Jev, which returns a calibrated choice between Haiku, Opus, Fable and image work, plus two side checks (is this security work, is this a premium image).
  • You stay in control. When Jev's confidence is under your threshold, a question pops up showing its ranking and you pick. Fable always asks first (configurable). /route overrides, locks, and explains.
  • Routing is enforced, not suggested. A turn.step hook sends every model request of the turn to the chosen model, and subagents that don't name a model follow the same route.
  • All graphics go to OpenAI. The mod gives Claude two tools, generate_image and edit_image. By default they run through the Codex CLI on your ChatGPT plan, so no API key is needed; set imageBackend to api to use the Images API instead. Image turns run on Haiku, which just drives those tools. Flare is the default tier; Sunburst is used when Jev flags a premium asset or Claude asks for it.

Routing policy

RouteModel (default id)Used for
haikuclaude-haiku-5-5Lookups, small edits, summaries, commit messages, chat
opusclaude-opus-5-5Ordinary engineering, and the fallback for everything
fableclaude-fable-5-1Architecture, long agentic work, deep ambiguous problems
imageHaiku + Codex image generation (or gpt-image-2.5-flare / -sunburst on the API)Creating or editing any image
securityOpus + OpenAI Daybreak Blue through Codex (--cyber-access-program daybreak_blue), read-onlyVulnerability review, threat modeling, secure code review, after you say yes

Rules on top of Jev:

  • Security work (the classifier picks security, or Jev's security check is over 50%) asks first: "Send it to OpenAI Daybreak?" Yes runs the turn on Opus, which hands the analysis to the daybreak tool. That tool runs Codex read-only on your project and returns the findings, and Claude applies fixes only if you ask. No, or nobody answering, means Opus. Security work never goes to Fable, which carries extra safeguards for cybersecurity.
  • The daybreak tool refuses on any turn you didn't approve (a yes, or /route security), so your code never goes to OpenAI unasked.
  • Jev confidence below confidenceThreshold (default 0.7): you are asked.
  • Jev picks Fable confidently and confirmFable is on: you are asked.
  • Jev unreachable or no key: Haiku classifies with a one-word answer; if that fails too, Opus.
  • Prompts typed while a turn is running keep the running turn's model.

The route descriptions Jev scores against live in hooks/jev.ts (ROUTE_CRITERIA). Editing them is how you tune the policy.

Requirements

  • Claude Code v2.1.287 or later, in the terminal or the Code tab of the Desktop app (mods run there)
  • TYPESAFE_API_KEY: a Jev key from console.typesafe.ai (early access). Without it the router still works on the Haiku fallback.
  • For images, either backend:
  • codex (default): the Codex CLI, recent enough for OpenAI's current models (0.162 or later; older versions are refused), signed in with codex login using your ChatGPT account. On Windows the mod runs node.exe from Program Files\nodejs on Codex's npm install by absolute path; if yours lives elsewhere, set codexPath.
  • api: OPENAI_API_KEY with access to gpt-image-2.5-flare and gpt-image-2.5-sunburst. On macOS or Linux, curl and openssl on the PATH; on Windows nothing extra (System32 curl.exe and powershell.exe by absolute path).
  • For Daybreak: the same Codex CLI. The mod asks for daybreakProgram (default daybreak_blue), but your OpenAI account decides what you actually get. Codex doesn't say whether the program was granted or the server fell back to standard access, and no setting here relaxes guardrails your account doesn't have.

Put the keys in your shell profile or in ~/.claude/settings.json under env. There is no .env file: the mod reads Claude Code's own environment.

To test in one folder without touching your global settings, copy examples/settings.local.json to <test folder>/.claude/settings.local.json, fill in the keys, and start claude --plugin-dir <path to jev-router> from that folder. The keys apply to that folder only. The mod itself still needs --plugin-dir, because CLAUDE_CODE_PLUGIN_DIRS in a folder's settings does not load it.

Install

Try it for one session:

claude --plugin-dir /path/to/jev-router

Load it in every session by adding the folder to ~/.claude/settings.json:

{
  "env": {
    "CLAUDE_CODE_PLUGIN_DIRS": "/path/to/jev-router",
    "TYPESAFE_API_KEY": "...",
    "OPENAI_API_KEY": "..."
  }
}

Check it loaded: run /plugin and look for 1 mod active · jev-router. Before installing, claude plugin validate ./jev-router lists every event it hooks and every call it makes.

Use

CommandEffect
/route or /route whyThe last decision: route, model, reason, and Jev's full probability breakdown
/route opus (or haiku, fable, image, security)Next turn only, then Jev decides again. /route security counts as approving Daybreak
/route lock fableEvery turn on that route until /route auto
/route autoHand control back to Jev
/route logThe last 10 decisions

/route runs immediately, even while Claude is working. The line under the prompt always shows the current route, who decided, and the confidence, for example Opus 5.5 (Jev 91%).

Settings

Change these in /config (each is a row there) or under pluginConfigs in settings, keyed jev-router@inline for a --plugin-dir install:

SettingDefault
haikuModel, opusModel, fableModelclaude-haiku-5-5, claude-opus-5-5, claude-fable-5-1Model ids per route
confidenceThreshold0.7Ask below this
cacheHoldtrueStay on Opus when Jev's move down to Haiku would cost more, cache rebuild included
cacheTtlMinutes60How long a model's cache is assumed to last since its last request; 60 or more prices cache writes at the 1-hour rate
pricesemptyJSON per-million prices keyed by model id, merged over the built-in table (input, output, read, optional longAbove and long)
confirmFabletrueAsk before any Fable turn
routeSubagentstrueSubagents without a model follow the route
imageDirassets/generatedWhere images are saved
imageBackendcodexcodex (ChatGPT plan, through the Codex CLI) or api (Images API, OPENAI_API_KEY). No automatic fallback between them
codexPathemptyWhere Codex is, if not found automatically: codex.js on Windows, the codex executable elsewhere
daybreakProgramdaybreak_blueCyber access program requested for approved security work: daybreak_blue, daybreak_red (approved partners only) or standard
daybreakModelemptyEmpty uses Codex's default model; otherwise the model id passed with -m
logPath.jev-router/decisions.jsonlDecision log (add it to .gitignore)

The decision log

Every decision, override, image call and finished turn (with its token usage) is one JSON line in logPath. Turns where you overrode Jev, or picked differently when asked, are your labeled data for tuning ROUTE_CRITERIA and the threshold. The log keeps the last 5,000 lines.

Things to know

  • Model switches cost cache. Prompt caching is per model, so the first request on a different model writes whatever that model doesn't have cached yet: the whole conversation if it never ran or its cache lapsed, otherwise only what was added since it last ran. The route holds for a whole turn, and the router reads each request's usage to know what each model has cached. When Jev moves an Opus session down to Haiku, it estimates the turn's dollars on both: the first request's cache read and write, later requests' reads, and output, with the turn's requests and output taken from the median of recent Haiku-picked turns (3 requests and 1,500 tokens until there are three). If Opus is cheaper, the turn stays there; the status line says (cache) and /route why shows both estimates. Haiku is cheaper below its 100k long-context price tier even with a cold cache, so in practice this holds only for short turns over 100k tokens. Moves up, Fable, image and security work, your picks and /route always switch. The built-in prices date from 2026-10-06; Haiku 5.5's cache-read rate isn't published and is assumed to be 0.1x input. Update prices when they change.
  • Jev sees the prompt plus the tail of Claude's last reply, so a short follow-up like "yes, do that" routes with its context.
  • Codex images take about a minute. Each one is a full Codex agent run (generation plus saving), sandboxed to imageDir, and it counts against your ChatGPT plan's Codex limits. The mod checks that the file exists afterwards rather than trusting Codex's reply.
  • Daybreak needs a working Codex sandbox. Codex reads your code by running shell commands inside its sandbox. On Windows, a broken elevated sandbox setup ("setup refresh had errors") makes every read fail, and the report then says it couldn't read the files. Check with codex exec -s read-only "print the first line of README.md" in any project. The mod leaves the sandbox mode to your Codex config.
  • Image size (api backend). Image files are decoded from the API's base64 output; very large outputs (over about 4 MB of base64) can exceed the mod API's read limit on edits.
  • Trust. A mod runs with your permissions and reads the two API keys from your environment. Keep it in a folder or marketplace you control.

Tests

claude plugin validate ./jev-router
claude plugin test ./jev-router

The suite (36 tests) covers confident routing, low-confidence asks, Fable confirmation, the Daybreak ask and the daybreak tool's approval gate, image routing, both fallbacks, subagent routing, every /route form, settings, and both image backends, with Jev, OpenAI, Codex, files and dialogs answered in memory.

Source 5 files
hooks/register.ts 713 lines
1import type { EngineInterface, ModelUsage, PluginOptions, Register } from 'claude-code'
2import { type Classification, type Route, ROUTES, classifyWithHaiku, classifyWithJev, isRoute, ranked } from './jev'
3import { type ImageTier, editImage, generateImage } from './images'
4import { codexImage } from './codex'
5import { type DaybreakProgram, daybreakName, daybreakReview } from './daybreak'
6
7/** One routing decision: what Jev said, what was chosen, and why. */
8type Decision = {
9  at: string
10  prompt: string
11  route: Route
12  model: string
13  imageTier?: ImageTier
14  decidedBy: 'jev' | 'you' | 'override' | 'lock' | 'rule' | 'cache'
15  reason: string
16  classification?: Classification
17  /** The turn's estimated cost in dollars on the held model and on Jev's pick, when the router held. */
18  costs?: { stay: number; pick: number }
19}
20
21type Override = { route: Route; sticky: boolean }
22
23/** What one model last had cached: the conversation size at its latest request, and when that was. */
24type Cached = { tokens: number; at: number }
25
26/** Dollars per million tokens. `long` replaces the rates for a prompt over `longAbove` tokens. */
27type Rates = { input: number; output: number; read: number }
28type Price = Rates & { longAbove?: number; long?: Rates }
29
30/** How one finished main turn went: its requests and output tokens. */
31type Shape = { steps: number; output: number }
32
33// Published per-million rates (2026-10-06). Haiku 5.5's cache-read rate isn't published:
34// these assume the usual 0.1x of input. Cache writes are input x 1.25 (5 min) or x 2 (1 h).
35const PRICES: Record<string, Price> = {
36  'claude-opus-5-5': { input: 4, output: 20, read: 0.2 },
37  'claude-haiku-5-5': {
38    input: 0.1,
39    output: 0.5,
40    read: 0.01,
41    longAbove: 100_000,
42    long: { input: 0.5, output: 2.5, read: 0.05 },
43  },
44}
45
46// Until a route has this many finished turns, its turn shape is assumed to be DEFAULT_SHAPE.
47const MIN_SHAPES = 3
48const MAX_SHAPES = 20
49const DEFAULT_SHAPE: Shape = { steps: 3, output: 1500 }
50
51type Opts = {
52  haikuModel: string
53  opusModel: string
54  fableModel: string
55  threshold: number
56  confirmFable: boolean
57  routeSubagents: boolean
58  imageDir: string
59  imageBackend: 'codex' | 'api'
60  codexPath: string
61  daybreakProgram: DaybreakProgram
62  daybreakModel: string
63  logPath: string
64  cacheHold: boolean
65  cacheTtlMs: number
66  prices: Record<string, Price>
67}
68
69const LABEL: Record<Route, string> = {
70  haiku: 'Haiku 5.5',
71  opus: 'Opus 5.5',
72  fable: 'Fable 5.1',
73  image: 'Images 2.5',
74  security: 'Daybreak',
75}
76
77const MAX_LOG_LINES = 5000
78
79// Codex writes Daybreak's report here; the folder is the decision log's, which stays out of git.
80const DAYBREAK_REPLY = '.jev-router/daybreak-last-report.md'
81
82// Module state. A reload starts it over, which is fine: the next prompt decides again.
83// `cache`, `last`, `turn` and `shapes` come from main-loop requests only; after a reload they are
84// empty, so the router knows nothing about the cache and never holds a model for it.
85const S: {
86  opt: Opts
87  active?: Decision
88  override?: Override
89  cache: Record<string, Cached>
90  last?: { model: string; tokens: number }
91  turn: Shape
92  shapes: Partial<Record<Route, Shape[]>>
93} = { opt: readOptions({}), cache: {}, turn: { steps: 0, output: 0 }, shapes: {} }
94
95export const register: Register = (on, options) => {
96  S.opt = readOptions(options)
97  S.active = undefined
98  S.override = undefined
99  S.cache = {}
100  S.last = undefined
101  S.turn = { steps: 0, output: 0 }
102  S.shapes = {}
103
104  on('session.start', async ($, e, next) => {
105    await registerTools($)
106    try {
107      await $.command.register({
108        name: 'route',
109        description: 'Jev router: why | haiku | opus | fable | image | security | lock <route> | auto | log',
110        argumentHint: '[why|haiku|opus|fable|image|security|lock <route>|auto|log]',
111        immediate: true,
112      })
113    } catch (err) {
114      $.ui.log(`/route was not registered: ${String(err)}`)
115    }
116    return next(e)
117  })
118
119  on('command.run', { command: 'route' }, async ($, e) => ({ text: await runRouteCommand($, e.args) }))
120
121  // Decide: classify each prompt typed while the session is idle.
122  on('prompt.submit', async ($, e, next) => {
123    if (e.command || e.isMeta || e.turnId) return next(e)
124
125    const decision = await decide($, e.text)
126    S.active = decision
127    S.turn = { steps: 0, output: 0 }
128    showStatus($, decision)
129    await writeLog($, { type: 'decision', ...decision })
130
131    const tool = `mcp__${$.plugin.name}__`
132    const note =
133      decision.route === 'image'
134        ? `jev-router: this request is image work. Create images with ${tool}generate_image and change existing ones with ${tool}edit_image, using tier "${decision.imageTier}". Do not draw images by hand in SVG, HTML or code. Report the saved file path when done.`
135        : decision.route === 'security'
136          ? `jev-router: the user approved sending this security work to OpenAI ${daybreakLabel()}. Call ${tool}daybreak with the full task and the most relevant file paths; it reads the project read-only and returns findings. Report those findings to the user, and change code only if they ask.`
137          : undefined
138    if (!note) return next(e)
139    return next({ ...e, context: [...(e.context ?? []), note] })
140  }).catch(($, e, next) => {
141    // Never lose a prompt to a routing failure: send it on unrouted (the session's own model).
142    $.ui.status('Jev router failed: this turn uses the session model')
143    return next.called ? { text: e.text } : next(e)
144  })
145
146  // Enforce: every model request of the main loop goes to the routed model. Each response's usage
147  // also records what that model now has cached, for the next decision.
148  on('turn.step', async function* ($, e, next) {
149    const d = S.active
150    // Subagent loops are routed when they spawn (agent.spawn); leave their steps alone.
151    if (e.agentId) return yield* next(e)
152    const step = d && e.model !== d.model ? { ...e, model: d.model } : e
153    const r = yield* next(step)
154    if (r.usage) {
155      noteCache(step.model, r.usage, await $.clock.now())
156      S.turn = { steps: S.turn.steps + 1, output: S.turn.output + r.usage.output_tokens }
157    }
158    return r
159  })
160
161  // Subagents that name no model run on the turn's routed model.
162  on('agent.spawn', async ($, e, next) => {
163    const d = S.active
164    if (!S.opt.routeSubagents || !d || e.model) return next(e)
165    return next({ ...e, model: d.model })
166  }).catch(($, e, next) => next(e))
167
168  // Record what each main turn cost, for tuning later.
169  on('turn.complete', async ($, e, next) => {
170    const d = S.active
171    if (!e.agentId && d) {
172      await writeLog($, {
173        type: 'turn',
174        at: new Date().toISOString(),
175        turnId: e.turnId,
176        route: d.route,
177        model: e.usage?.model ?? d.model,
178        durationMs: e.durationMs,
179        isAborted: e.isAborted,
180        usage: e.usage,
181      })
182      if (!e.isAborted) noteShape(d)
183    }
184    return next(e)
185  })
186
187  on('tool.call', { tool: 'mcp__jev-router__generate_image' }, async ($, e) => ({
188    result: await runGenerate($, e as unknown as Record<string, unknown>),
189  })).catch(($, e, next) => ({ result: `generate_image failed inside jev-router: ${next.error?.message ?? 'unknown error'}` }))
190
191  on('tool.call', { tool: 'mcp__jev-router__edit_image' }, async ($, e) => ({
192    result: await runEdit($, e as unknown as Record<string, unknown>),
193  })).catch(($, e, next) => ({ result: `edit_image failed inside jev-router: ${next.error?.message ?? 'unknown error'}` }))
194
195  on('tool.call', { tool: 'mcp__jev-router__daybreak' }, async ($, e) => ({
196    result: await runDaybreak($, e as unknown as Record<string, unknown>),
197  })).catch(($, e, next) => ({ result: `daybreak failed inside jev-router: ${next.error?.message ?? 'unknown error'}` }))
198}
199
200// ---------- options ----------
201
202function readOptions(options: PluginOptions): Opts {
203  return {
204    haikuModel: String(options.haikuModel ?? 'claude-haiku-5-5'),
205    opusModel: String(options.opusModel ?? 'claude-opus-5-5'),
206    fableModel: String(options.fableModel ?? 'claude-fable-5-1'),
207    threshold: Number(options.confidenceThreshold ?? 0.7),
208    confirmFable: options.confirmFable !== false,
209    routeSubagents: options.routeSubagents !== false,
210    imageDir: String(options.imageDir ?? 'assets/generated'),
211    imageBackend: options.imageBackend === 'api' ? 'api' : 'codex',
212    codexPath: String(options.codexPath ?? ''),
213    daybreakProgram: options.daybreakProgram === 'daybreak_red' || options.daybreakProgram === 'standard' ? options.daybreakProgram : 'daybreak_blue',
214    daybreakModel: String(options.daybreakModel ?? ''),
215    logPath: String(options.logPath ?? '.jev-router/decisions.jsonl'),
216    cacheHold: options.cacheHold !== false,
217    cacheTtlMs: Number(options.cacheTtlMinutes ?? 60) * 60_000,
218    prices: readPrices(options.prices),
219  }
220}
221
222// The `prices` setting is JSON keyed by model id, merged over the built-in table. A setting that
223// doesn't parse is ignored rather than failing the router.
224function readPrices(x: unknown): Record<string, Price> {
225  if (typeof x !== 'string' || x.trim() === '') return PRICES
226  try {
227    const parsed: unknown = JSON.parse(x)
228    return parsed && typeof parsed === 'object' ? { ...PRICES, ...(parsed as Record<string, Price>) } : PRICES
229  } catch {
230    return PRICES
231  }
232}
233
234// The image route runs on Haiku: it only has to drive the image tools. The security route runs on
235// Opus, which hands the analysis to Daybreak and then explains and applies its findings.
236function modelFor(r: Route): string {
237  return r === 'fable' ? S.opt.fableModel : r === 'opus' || r === 'security' ? S.opt.opusModel : S.opt.haikuModel
238}
239
240// ---------- deciding ----------
241
242async function decide($: EngineInterface, text: string): Promise<Decision> {
243  const base = { at: new Date().toISOString(), prompt: text.slice(0, 500) }
244
245  const o = S.override
246  if (o) {
247    if (!o.sticky) S.override = undefined
248    return {
249      ...base,
250      route: o.route,
251      model: modelFor(o.route),
252      imageTier: o.route === 'image' ? 'flare' : undefined,
253      decidedBy: o.sticky ? 'lock' : 'override',
254      reason: o.sticky ? 'locked with /route lock' : 'set with /route',
255    }
256  }
257
258  const c = await classify($, text)
259  let route = c.route
260  let decidedBy: Decision['decidedBy'] = 'jev'
261  let reason =
262    c.source === 'jev'
263      ? `Jev picked ${route} at ${pct(c.confidence)}`
264      : c.source === 'fallback-haiku'
265        ? `Jev unavailable (${c.error}); Haiku picked ${route}`
266        : `Jev unavailable (${c.error}); default route`
267
268  // Security work goes to OpenAI Daybreak, but only on a yes. Otherwise Opus, never Fable,
269  // which carries extra safeguards for cybersecurity.
270  if (route === 'security' || (route !== 'image' && c.securitySensitive > 0.5)) {
271    const why =
272      route === 'security' ? `${classifierName(c)} flagged security work` : `security-sensitive (${pct(c.securitySensitive)})`
273    const answer = await askSafely(
274      $,
275      `${why}. Send it to OpenAI ${daybreakLabel()}, read-only through Codex?`,
276      ['OpenAI Daybreak', 'Opus 5.5'],
277    )
278    route = answer === 'OpenAI Daybreak' ? 'security' : 'opus'
279    decidedBy = answer === undefined ? 'rule' : 'you'
280    reason =
281      answer === 'OpenAI Daybreak'
282        ? `${why}; you approved Daybreak`
283        : answer === undefined
284          ? `${why}; nobody approved Daybreak, so Opus`
285          : `${why}; you chose Opus over Daybreak`
286  }
287
288  if (decidedBy === 'jev' && c.source === 'jev' && c.confidence < S.opt.threshold) {
289    // Jev is unsure: ask, showing its ranking.
290    const picked = await askForRoute($, c)
291    if (picked) {
292      route = picked
293      decidedBy = 'you'
294      reason = `Jev unsure (${pct(c.confidence)}); you picked ${route}`
295    } else if (route === 'fable' && S.opt.confirmFable) {
296      // Nobody picked, and Fable needs a yes: don't spend it unasked.
297      route = 'opus'
298      decidedBy = 'rule'
299      reason = `Jev unsure (${pct(c.confidence)}) and nobody picked; Fable needs a yes, so Opus`
300    }
301  } else if (route === 'fable' && S.opt.confirmFable && decidedBy === 'jev') {
302    const answer = await askSafely(
303      $,
304      `${classifierName(c)} wants Fable 5.1 for this turn (${pct(c.confidence)}). Use it?`,
305      ['Fable 5.1', 'Opus 5.5'],
306    )
307    if (answer === 'Opus 5.5') {
308      route = 'opus'
309      decidedBy = 'you'
310      reason = 'you chose Opus over Fable'
311    } else if (answer !== 'Fable 5.1') {
312      // Dismissed, or a -p run with nobody to ask: Fable runs only on a yes.
313      route = 'opus'
314      decidedBy = 'rule'
315      reason = 'nobody confirmed Fable, so Opus'
316    }
317  }
318
319  // A switch writes the conversation into the new model's cache. When Jev moves an Opus session
320  // down to Haiku and the turn would cost less on Opus, cache rebuild included, it stays on Opus.
321  // Moves up, Fable, image and security work, your picks and /route always go through.
322  let costs: Decision['costs']
323  if (decidedBy === 'jev' && route === 'haiku' && S.last?.model === S.opt.opusModel && S.opt.cacheHold) {
324    const now = await $.clock.now()
325    const shape = expectedShape('haiku')
326    const stay = turnCost(S.opt.opusModel, shape, now)
327    const pick = turnCost(modelFor('haiku'), shape, now)
328    if (stay !== undefined && pick !== undefined && stay < pick) {
329      reason = `${reason}; stayed on ${LABEL.opus}, cheaper with its cache (~${usd(stay)} vs ~${usd(pick)} on ${LABEL.haiku})`
330      route = 'opus'
331      decidedBy = 'cache'
332      costs = { stay, pick }
333    }
334  }
335
336  return {
337    ...base,
338    route,
339    model: modelFor(route),
340    imageTier: route === 'image' ? (c.premiumImage > 0.5 ? 'sunburst' : 'flare') : undefined,
341    decidedBy,
342    reason,
343    classification: c,
344    ...(costs === undefined ? {} : { costs }),
345  }
346}
347
348// ---------- prompt cache ----------
349
350// The size of the request's prompt is what the model now has cached: the part read from the
351// cache, the part written to it, and the uncached rest.
352function noteCache(model: string, u: ModelUsage, now: number) {
353  const tokens = u.input_tokens + u.cache_read_input_tokens + u.cache_creation_input_tokens
354  S.cache[model] = { tokens, at: now }
355  S.last = { model, tokens }
356}
357
358// Roughly what the next request would write to `model`'s cache: the whole conversation when it
359// has nothing cached or its entry has lapsed, otherwise what was added since it last ran. A
360// conversation smaller than what the model cached was compacted since, so its cached prefix no
361// longer matches and the whole conversation is written again.
362function cacheWriteFor(model: string, now: number): number {
363  const total = S.last?.tokens ?? 0
364  const c = S.cache[model]
365  if (!c || now - c.at > S.opt.cacheTtlMs || total < c.tokens) return total
366  return total - c.tokens
367}
368
369// A turn's dollars on `model` over the current conversation: the first request reads what the
370// model has cached and writes the rest, each later request reads the whole conversation, and the
371// output is billed once. Undefined when the model has no price, so the router never holds blind.
372function turnCost(model: string, shape: Shape, now: number): number | undefined {
373  const total = S.last?.tokens ?? 0
374  const p = priceFor(model)
375  if (!p) return undefined
376  const r = p.long && p.longAbove !== undefined && total > p.longAbove ? p.long : p
377  const write = r.input * (S.opt.cacheTtlMs >= 60 * 60_000 ? 2 : 1.25)
378  const uncached = cacheWriteFor(model, now)
379  const first = (total - uncached) * r.read + uncached * write
380  const later = (shape.steps - 1) * total * r.read
381  return (first + later + shape.output * r.output) / 1e6
382}
383
384// Exact id first; then a dated id like claude-opus-5-5-20261001 takes its base model's price.
385function priceFor(model: string): Price | undefined {
386  const exact = S.opt.prices[model]
387  if (exact) return exact
388  const base = Object.keys(S.opt.prices).find(id => model.startsWith(`${id}-`))
389  return base ? S.opt.prices[base] : undefined
390}
391
392// Turns are filed under the route Jev picked, so a held turn still teaches what Haiku-picked
393// prompts look like.
394function noteShape(d: Decision) {
395  if (S.turn.steps === 0) return
396  const key = d.classification?.route ?? d.route
397  const list = [...(S.shapes[key] ?? []), S.turn].slice(-MAX_SHAPES)
398  S.shapes[key] = list
399}
400
401function expectedShape(r: Route): Shape {
402  const list = S.shapes[r] ?? []
403  if (list.length < MIN_SHAPES) return DEFAULT_SHAPE
404  return { steps: median(list.map(s => s.steps)), output: median(list.map(s => s.output)) }
405}
406
407function median(xs: number[]): number {
408  const s = [...xs].sort((a, b) => a - b)
409  const mid = Math.floor(s.length / 2)
410  return s.length % 2 ? (s[mid] ?? 0) : ((s[mid - 1] ?? 0) + (s[mid] ?? 0)) / 2
411}
412
413async function classify($: EngineInterface, text: string): Promise<Classification> {
414  const state = await buildState($, text)
415  const key = await $.env.get('TYPESAFE_API_KEY')
416  if (!key) return classifyWithHaiku($, state, 'TYPESAFE_API_KEY is not set')
417  try {
418    return await classifyWithJev($, key, state)
419  } catch (err) {
420    return classifyWithHaiku($, state, err instanceof Error ? err.message : String(err))
421  }
422}
423
424// Jev reads the new prompt plus the tail of the last reply, so "yes, do that" routes like what it answers.
425async function buildState($: EngineInterface, text: string): Promise<string> {
426  let lastReply = ''
427  try {
428    const messages = await $.session.messages()
429    const last = [...messages].reverse().find(m => m.role === 'assistant' && m.text.trim().length > 0)
430    lastReply = last ? last.text.slice(-1500) : ''
431  } catch {
432    // no transcript to read
433  }
434  return lastReply ? `Previous assistant reply (tail):\n${lastReply}\n\nNew request:\n${text}` : `New request:\n${text}`
435}
436
437async function askForRoute($: EngineInterface, c: Classification): Promise<Route | undefined> {
438  const top = ranked(c).slice(0, 3)
439  const labels = top.map(r => `${LABEL[r]} (${pct(c.probabilities[r] ?? 0)})`)
440  const answer = await askSafely($, `Jev is unsure (${pct(c.confidence)}). Which model should take this turn?`, labels)
441  if (answer === undefined) return undefined
442  const i = labels.indexOf(answer)
443  if (i >= 0) return top[i]
444  return ROUTES.find(r => answer.toLowerCase().includes(r))
445}
446
447async function askSafely($: EngineInterface, question: string, labels: string[]): Promise<string | undefined> {
448  try {
449    return await $.ui.ask(question, labels)
450  } catch {
451    return undefined // dismissed, or a -p run with nobody to ask: keep Jev's pick
452  }
453}
454
455// ---------- /route ----------
456
457async function runRouteCommand($: EngineInterface, args: string): Promise<string> {
458  const [first, second] = args.trim().toLowerCase().split(/\s+/).filter(Boolean)
459
460  if (!first || first === 'why') {
461    // A reload clears S.active; explain the last logged decision instead. Only for display:
462    // S.active stays empty, so a stale decision never routes a turn or approves Daybreak.
463    if (S.active) return explain(S.active, S.override)
464    return explain(await lastLoggedDecision($), S.override, true)
465  }
466
467  if (first === 'auto') {
468    S.override = undefined
469    $.ui.status(S.active ? `${LABEL[S.active.route]} (Jev, auto)` : 'Jev: auto')
470    return 'Jev is routing again.'
471  }
472
473  if (first === 'log') return recentDecisions($)
474
475  const lock = first === 'lock'
476  const target = lock ? second : first
477  if (!isRoute(target)) return 'Usage: /route [why | haiku | opus | fable | image | security | lock <route> | auto | log]'
478
479  S.override = { route: target, sticky: lock }
480  $.ui.status(`${LABEL[target]} (${lock ? 'locked' : 'next turn'})`)
481  await writeLog($, { type: 'override', at: new Date().toISOString(), route: target, sticky: lock })
482  return lock
483    ? `Locked to ${LABEL[target]} until /route auto.`
484    : `Next turn runs on ${LABEL[target]}, then Jev takes over again.`
485}
486
487async function recentDecisions($: EngineInterface): Promise<string> {
488  const path = S.opt.logPath
489  const prior = (await $.fs.exists(path)) ? await $.fs.read(path) : ''
490  const rows = prior
491    .split('\n')
492    .filter(l => l.includes('"type":"decision"'))
493    .slice(-10)
494    .map(l => {
495      const d = JSON.parse(l) as Decision
496      return `${d.at.slice(11, 19)}  ${LABEL[d.route].padEnd(10)} ${d.decidedBy.padEnd(8)} ${d.prompt.slice(0, 60)}`
497    })
498  return rows.length ? rows.join('\n') : `No decisions logged yet in ${path}.`
499}
500
501async function lastLoggedDecision($: EngineInterface): Promise<Decision | undefined> {
502  const path = S.opt.logPath
503  try {
504    const prior = (await $.fs.exists(path)) ? await $.fs.read(path) : ''
505    const last = prior
506      .split('\n')
507      .filter(l => l.includes('"type":"decision"'))
508      .pop()
509    return last ? (JSON.parse(last) as Decision) : undefined
510  } catch {
511    return undefined
512  }
513}
514
515function explain(d: Decision | undefined, o: Override | undefined, fromLog = false): string {
516  const lines: string[] = []
517  if (o) lines.push(o.sticky ? `Locked to ${LABEL[o.route]} (/route auto to unlock).` : `Next turn: ${LABEL[o.route]} (one time).`)
518  if (!d) {
519    lines.push('No turn routed yet in this session.')
520    return lines.join('\n')
521  }
522  if (fromLog) lines.push(`From the log (the router reloaded since), routed at ${d.at.slice(11, 19)}:`)
523  lines.push(`Last turn: ${LABEL[d.route]} on ${d.model}${d.imageTier ? `, image tier ${d.imageTier}` : ''}.`)
524  lines.push(`Why: ${d.reason}.`)
525  const c = d.classification
526  if (c) {
527    lines.push(`Classifier: ${c.source}${c.jevModel ? ` (${c.jevModel})` : ''}, ${c.latencyMs} ms.`)
528    for (const r of ranked(c)) {
529      const p = c.probabilities[r] ?? 0
530      lines.push(`  ${LABEL[r].padEnd(11)} ${'#'.repeat(Math.round(p * 20)).padEnd(20)} ${pct(p)}`)
531    }
532    lines.push(`  security ${pct(c.securitySensitive)}, premium image ${pct(c.premiumImage)}`)
533  }
534  return lines.join('\n')
535}
536
537// ---------- status and log ----------
538
539function showStatus($: EngineInterface, d: Decision) {
540  const c = d.classification
541  // decidedBy 'jev' means "the classifier's pick", which is Haiku or the default when Jev is unavailable.
542  const who = d.decidedBy === 'jev' && c ? classifierName(c) : d.decidedBy
543  // A cache hold overruled the pick, so its confidence would describe the other model.
544  const conf = c && c.source !== 'default' && d.decidedBy !== 'cache' ? ` ${pct(c.confidence)}` : ''
545  const tier = d.route === 'image' ? ` ${d.imageTier}` : ''
546  const lock = S.override?.sticky ? ' [locked]' : ''
547  $.ui.status(`${LABEL[d.route]}${tier} (${who}${conf})${lock}`)
548}
549
550async function writeLog($: EngineInterface, entry: Record<string, unknown>) {
551  const path = S.opt.logPath
552  try {
553    const prior = (await $.fs.exists(path)) ? await $.fs.read(path) : ''
554    const lines = prior.split('\n').filter(l => l.length > 0)
555    lines.push(JSON.stringify(entry))
556    await $.fs.write(path, lines.slice(-MAX_LOG_LINES).join('\n') + '\n')
557  } catch (err) {
558    $.ui.log(`could not write the decision log: ${String(err)}`, { to: 'debug' })
559  }
560}
561
562// ---------- image tools ----------
563
564async function registerTools($: EngineInterface) {
565  const common = {
566    tier: {
567      type: 'string',
568      enum: ['flare', 'sunburst'],
569      description: 'flare: fast, the default. sunburst: premium, for polished final assets.',
570    },
571    size: { type: 'string', description: 'For example 1024x1024, 1536x1024, 1024x1536, or auto.' },
572    quality: { type: 'string', enum: ['low', 'medium', 'high', 'auto'] },
573    background: { type: 'string', enum: ['transparent', 'opaque', 'auto'] },
574    output_format: { type: 'string', enum: ['png', 'jpeg', 'webp'] },
575    filename: { type: 'string', description: 'Optional file name, without extension.' },
576  }
577  await $.tool.register({
578    name: 'generate_image',
579    description:
580      'Generate an image with OpenAI image generation and save it into the project. Takes up to a few minutes. Use this for ALL image creation: illustrations, logos, icons, photos, mockup images, pictures of diagrams. Never draw images by hand in code when this tool fits. Returns the saved file path.',
581    inputSchema: {
582      type: 'object',
583      properties: { prompt: { type: 'string', description: 'A full description of the image.' }, ...common },
584      required: ['prompt'],
585    },
586    isDeferred: false,
587  })
588  await $.tool.register({
589    name: 'edit_image',
590    description:
591      'Edit or restyle existing images with OpenAI image generation (takes up to a few minutes): change one element, swap a background, combine references. Use this for ALL image edits. Returns the saved file path.',
592    inputSchema: {
593      type: 'object',
594      properties: {
595        image_paths: { type: 'array', items: { type: 'string' }, description: 'Source image files in the project.' },
596        prompt: { type: 'string', description: 'What to change, and what to keep the same.' },
597        mask_path: { type: 'string', description: 'Optional PNG mask; transparent areas are edited.' },
598        ...common,
599      },
600      required: ['image_paths', 'prompt'],
601    },
602    isDeferred: false,
603  })
604  await $.tool.register({
605    name: 'daybreak',
606    description:
607      'Hand security work to OpenAI Daybreak through Codex: vulnerability review, secure code review, threat modeling, dependency risk, validating a security fix. It reads the project read-only, can take several minutes, and returns its findings. Works only on turns the user approved for Daybreak.',
608    inputSchema: {
609      type: 'object',
610      properties: {
611        task: { type: 'string', description: 'The full security task, with the context Daybreak needs.' },
612        paths: { type: 'array', items: { type: 'string' }, description: 'Files to start with, relative to the project.' },
613      },
614      required: ['task'],
615    },
616    isDeferred: false,
617  })
618}
619
620// Daybreak sends project code to OpenAI, so it runs only on a turn the user approved:
621// a yes to the dialog, or /route security.
622async function runDaybreak($: EngineInterface, a: Record<string, unknown>): Promise<string> {
623  if (S.active?.route !== 'security') {
624    return 'The user has not approved Daybreak for this turn, so nothing was sent to OpenAI. They can approve it with /route security.'
625  }
626  const task = String(a.task ?? '').trim()
627  if (!task) return 'daybreak needs a task.'
628  const paths = Array.isArray(a.paths) ? a.paths.map(String) : []
629  const out = await daybreakReview($, S.opt.codexPath, S.opt.daybreakProgram, S.opt.daybreakModel, DAYBREAK_REPLY, task, paths)
630  await writeLog($, {
631    type: 'daybreak',
632    at: new Date().toISOString(),
633    program: S.opt.daybreakProgram,
634    model: S.opt.daybreakModel || 'codex default',
635    ok: out.ok,
636    ...(out.ok ? {} : { error: out.error }),
637  })
638  return out.ok ? `OpenAI ${daybreakLabel()} reported:\n\n${out.report}` : `Daybreak failed: ${out.error}`
639}
640
641// The image tools run through Codex on the user's ChatGPT plan by default, or the Images API
642// when imageBackend is "api". There is no automatic fallback between them: the setting decides.
643async function runGenerate($: EngineInterface, a: Record<string, unknown>): Promise<string> {
644  const args = imageArgs(a)
645  let out
646  if (S.opt.imageBackend === 'codex') {
647    out = await codexImage($, S.opt.codexPath, S.opt.imageDir, args)
648  } else {
649    const key = await $.env.get('OPENAI_API_KEY')
650    if (!key) return 'OPENAI_API_KEY is not set, so no image was generated. Ask the user to set it, or to switch imageBackend to codex in /config.'
651    out = await generateImage($, key, S.opt.imageDir, args)
652  }
653  await writeLog($, { type: 'image', at: new Date().toISOString(), op: 'generate', backend: S.opt.imageBackend, ...out })
654  return out.ok ? `Saved ${out.path} (${out.model}).` : `Image generation failed: ${out.error}`
655}
656
657async function runEdit($: EngineInterface, a: Record<string, unknown>): Promise<string> {
658  const paths = Array.isArray(a.image_paths) ? a.image_paths.map(String) : []
659  if (paths.length === 0) return 'edit_image needs at least one path in image_paths.'
660  const args = { ...imageArgs(a), imagePaths: paths, maskPath: str(a.mask_path) }
661  let out
662  if (S.opt.imageBackend === 'codex') {
663    out = await codexImage($, S.opt.codexPath, S.opt.imageDir, args)
664  } else {
665    const key = await $.env.get('OPENAI_API_KEY')
666    if (!key) return 'OPENAI_API_KEY is not set, so no image was edited. Ask the user to set it, or to switch imageBackend to codex in /config.'
667    out = await editImage($, key, S.opt.imageDir, args)
668  }
669  await writeLog($, { type: 'image', at: new Date().toISOString(), op: 'edit', backend: S.opt.imageBackend, ...out })
670  return out.ok ? `Saved ${out.path} (${out.model}).` : `Image edit failed: ${out.error}`
671}
672
673function imageArgs(a: Record<string, unknown>) {
674  return {
675    prompt: String(a.prompt ?? ''),
676    tier: pickTier(a.tier),
677    size: str(a.size),
678    quality: str(a.quality),
679    background: str(a.background),
680    outputFormat: str(a.output_format),
681    filename: str(a.filename),
682  }
683}
684
685function pickTier(x: unknown): ImageTier {
686  if (x === 'flare' || x === 'sunburst') return x
687  return S.active?.imageTier ?? 'flare'
688}
689
690// ---------- helpers ----------
691
692// "Daybreak Blue", or "Daybreak Blue (gpt-6-sol)" when a model is pinned.
693function daybreakLabel(): string {
694  const name = daybreakName(S.opt.daybreakProgram)
695  return S.opt.daybreakModel ? `${name} (${S.opt.daybreakModel})` : name
696}
697
698function classifierName(c: Classification): string {
699  return c.source === 'jev' ? 'Jev' : c.source === 'fallback-haiku' ? 'Haiku' : 'default'
700}
701
702function pct(x: number): string {
703  return `${Math.round(x * 100)}%`
704}
705
706function usd(x: number): string {
707  return `$${x.toFixed(3)}`
708}
709
710function str(x: unknown): string | undefined {
711  return typeof x === 'string' && x.length > 0 ? x : undefined
712}
713
hooks/jev.ts 143 lines
1import type { EngineInterface } from 'claude-code'
2
3export type Route = 'haiku' | 'opus' | 'fable' | 'image' | 'security'
4export const ROUTES: readonly Route[] = ['haiku', 'opus', 'fable', 'image', 'security']
5
6export type Classification = {
7  source: 'jev' | 'fallback-haiku' | 'default'
8  route: Route
9  confidence: number
10  probabilities: Partial<Record<Route, number>>
11  securitySensitive: number
12  premiumImage: number
13  jevModel?: string
14  latencyMs: number
15  error?: string
16}
17
18const JEV_URL = 'https://api.typesafe.ai/v1/systemone'
19
20// What each route is for. Jev reads these as the Choice criteria, so they are the routing policy.
21export const ROUTE_CRITERIA: Record<Route, string> = {
22  haiku:
23    'Quick, low-stakes work: a lookup, a question about the code answered by reading one or two files, a summary, a commit message, formatting, renaming, a one-line fix, or a conversational reply.',
24  opus:
25    'Ordinary engineering work: writing or changing code across a few files, debugging with a clear trail, writing tests, reviewing a change, or a design question with a known shape.',
26  fable:
27    'The hardest work: architecture across a whole codebase, long multi-step agentic tasks, deep debugging with no clear lead, ambiguous problems needing extended reasoning, or high-stakes design decisions.',
28  image:
29    'The request is mainly to create, generate, draw, edit, restyle or retouch an image, picture, illustration, logo, icon, mockup image, photo or other graphic.',
30  security:
31    'Security work: finding or fixing vulnerabilities, secure code review, threat modeling, dependency risk, validating a security patch, exploits, malware, penetration testing or security tooling.',
32}
33
34/** Ask Jev which route fits. Throws on any transport or schema problem so the caller can fall back. */
35export async function classifyWithJev($: EngineInterface, apiKey: string, state: string): Promise<Classification> {
36  const started = await $.clock.now()
37  const res = await $.http.fetch(JEV_URL, {
38    method: 'POST',
39    headers: { Authorization: `Bearer ${apiKey}`, 'Content-Type': 'application/json' },
40    body: JSON.stringify({
41      model: 'jev-latest',
42      state,
43      questions: {
44        route: {
45          type: 'choice',
46          instructions: 'Which model tier should handle this request to a coding agent',
47          criteria: ROUTE_CRITERIA,
48        },
49        security: {
50          type: 'noul',
51          instructions:
52            'The request involves security work: exploits, vulnerabilities, malware, penetration testing, attack techniques or security tooling',
53        },
54        premium_image: {
55          type: 'noul',
56          instructions:
57            'The request asks for a polished, final, production-ready or campaign-quality image rather than a quick draft',
58        },
59      },
60    }),
61  })
62  if (!res.ok) throw new Error(`Jev HTTP ${res.status}: ${res.text.slice(0, 200)}`)
63
64  const body = JSON.parse(res.text) as {
65    model?: string
66    answers?: Record<string, { choice?: string; confidence?: number; probabilities?: Record<string, number>; noul?: number }>
67  }
68  const route = body.answers?.route
69  const choice = route?.choice
70  if (!route || !isRoute(choice)) throw new Error('Jev answered without a usable route')
71
72  const probabilities: Partial<Record<Route, number>> = {}
73  for (const r of ROUTES) {
74    const p = route.probabilities?.[r]
75    if (typeof p === 'number') probabilities[r] = p
76  }
77  return {
78    source: 'jev',
79    route: choice,
80    confidence: typeof route.confidence === 'number' ? route.confidence : (probabilities[choice] ?? 0),
81    probabilities,
82    securitySensitive: body.answers?.security?.noul ?? 0,
83    premiumImage: body.answers?.premium_image?.noul ?? 0,
84    jevModel: body.model,
85    latencyMs: (await $.clock.now()) - started,
86  }
87}
88
89/** Fallback when Jev is unavailable: one-word Haiku classification. Never throws. */
90export async function classifyWithHaiku($: EngineInterface, state: string, jevError: string): Promise<Classification> {
91  const started = await $.clock.now()
92  try {
93    const r = await $.model.complete({
94      model: 'haiku',
95      system:
96        'You route requests for a coding agent. Reply with exactly one word: haiku, opus, fable, image or security.\n' +
97        ROUTES.map(k => `${k}: ${ROUTE_CRITERIA[k]}`).join('\n'),
98      prompt: state,
99      maxTokens: 5,
100      timeoutMs: 8000,
101    })
102    const word = r.isAnswered ? r.text.trim().toLowerCase().replace(/[^a-z]/g, '') : ''
103    if (isRoute(word)) {
104      return {
105        source: 'fallback-haiku',
106        route: word,
107        // A one-word answer carries no calibrated confidence: treat it as unsure enough to show, sure enough not to ask.
108        confidence: 0.75,
109        probabilities: { [word]: 0.75 },
110        securitySensitive: 0,
111        premiumImage: 0,
112        latencyMs: (await $.clock.now()) - started,
113        error: jevError,
114      }
115    }
116  } catch {
117    // fall through to the default
118  }
119  return defaultClassification(jevError)
120}
121
122export function defaultClassification(error: string): Classification {
123  return {
124    source: 'default',
125    route: 'opus',
126    confidence: 1,
127    probabilities: { opus: 1 },
128    securitySensitive: 0,
129    premiumImage: 0,
130    latencyMs: 0,
131    error,
132  }
133}
134
135export function isRoute(x: unknown): x is Route {
136  return typeof x === 'string' && (ROUTES as readonly string[]).includes(x)
137}
138
139/** The routes ranked by Jev's probability, highest first. */
140export function ranked(c: Classification): Route[] {
141  return [...ROUTES].sort((a, b) => (c.probabilities[b] ?? 0) - (c.probabilities[a] ?? 0))
142}
143
hooks/images.ts 157 lines
1import type { EngineInterface } from 'claude-code'
2
3export type ImageTier = 'flare' | 'sunburst'
4
5export const IMAGE_MODELS: Record<ImageTier, string> = {
6  flare: 'gpt-image-2.5-flare',
7  sunburst: 'gpt-image-2.5-sunburst',
8}
9
10const OPENAI = 'https://api.openai.com/v1/images'
11
12export type ImageArgs = {
13  prompt: string
14  tier: ImageTier
15  size?: string
16  quality?: string
17  background?: string
18  outputFormat?: string
19  filename?: string
20}
21
22export type EditArgs = ImageArgs & { imagePaths: readonly string[]; maskPath?: string }
23
24export type ImageOutcome = { ok: true; path: string; model: string } | { ok: false; error: string }
25
26/** Text-to-image through the Images API, saved as a file under `dir`. */
27export async function generateImage($: EngineInterface, apiKey: string, dir: string, a: ImageArgs): Promise<ImageOutcome> {
28  const model = IMAGE_MODELS[a.tier]
29  const body: Record<string, unknown> = { model, prompt: a.prompt, n: 1 }
30  if (a.size) body.size = a.size
31  if (a.quality) body.quality = a.quality
32  if (a.background) body.background = a.background
33  if (a.outputFormat) body.output_format = a.outputFormat
34
35  const res = await $.http.fetch(`${OPENAI}/generations`, {
36    method: 'POST',
37    headers: { Authorization: `Bearer ${apiKey}`, 'Content-Type': 'application/json' },
38    body: JSON.stringify(body),
39  })
40  if (!res.ok) return { ok: false, error: `OpenAI HTTP ${res.status}: ${openAiMessage(res.text)}` }
41  return saveFirstImage($, res.text, dir, a, model)
42}
43
44/**
45 * Image edit. The Images edit endpoint takes multipart form data with the image files,
46 * which $.http.fetch (text bodies only) cannot send, so curl does the upload.
47 * The key goes to curl on stdin (`-H @-`), never on its command line.
48 */
49export async function editImage($: EngineInterface, apiKey: string, dir: string, a: EditArgs): Promise<ImageOutcome> {
50  const model = IMAGE_MODELS[a.tier]
51  for (const p of [...a.imagePaths, ...(a.maskPath ? [a.maskPath] : [])]) {
52    if (!(await $.fs.exists(p))) return { ok: false, error: `No such file: ${p}` }
53  }
54  const responseFile = `${dir}/.last-edit-response.json`
55  const sys = await windowsSystem32($)
56
57  const argv = [
58    sys ? `${sys}\\curl.exe` : 'curl', '-sS', '-X', 'POST', `${OPENAI}/edits`,
59    '-H', '@-',
60    '--create-dirs',
61    '-F', `model=${model}`,
62    '-F', `prompt=${a.prompt}`,
63    '-o', responseFile,
64    '-w', '%{http_code}',
65  ]
66  for (const p of a.imagePaths) argv.push('-F', `image[]=@${p}`)
67  if (a.maskPath) argv.push('-F', `mask=@${a.maskPath}`)
68  if (a.size) argv.push('-F', `size=${a.size}`)
69  if (a.quality) argv.push('-F', `quality=${a.quality}`)
70  if (a.background) argv.push('-F', `background=${a.background}`)
71  if (a.outputFormat) argv.push('-F', `output_format=${a.outputFormat}`)
72
73  const run = await $.process.run(argv, { stdin: `Authorization: Bearer ${apiKey}\n`, timeoutMs: 300_000 })
74  if (run.exitCode !== 0) return { ok: false, error: `curl failed: ${run.stderr.slice(0, 300)}` }
75  const text = await $.fs.read(responseFile)
76  const status = Number(run.stdout.trim())
77  if (status < 200 || status >= 300) return { ok: false, error: `OpenAI HTTP ${status}: ${openAiMessage(text)}` }
78  return saveFirstImage($, text, dir, a, model)
79}
80
81async function saveFirstImage($: EngineInterface, json: string, dir: string, a: ImageArgs, model: string): Promise<ImageOutcome> {
82  let b64: string | undefined
83  try {
84    b64 = (JSON.parse(json) as { data?: { b64_json?: string }[] }).data?.[0]?.b64_json
85  } catch {
86    return { ok: false, error: 'OpenAI answered with something that is not JSON' }
87  }
88  if (!b64) return { ok: false, error: 'OpenAI answered without image data' }
89
90  const path = await outputPath($, dir, a)
91
92  // $.fs.write writes text only, so a host tool decodes the base64 into the binary file.
93  const sys = await windowsSystem32($)
94  let run
95  if (sys) {
96    // The output path goes in through the environment, never spliced into the script.
97    run = await $.process.run(
98      [`${sys}\\WindowsPowerShell\\v1.0\\powershell.exe`, '-NoProfile', '-NonInteractive', '-Command', DECODE_PS],
99      { stdin: b64, env: { JEV_IMAGE_OUT: path } },
100    )
101  } else {
102    await $.process.run(['mkdir', '-p', dir])
103    run = await $.process.run(['openssl', 'base64', '-d', '-A', '-out', path], { stdin: b64 })
104  }
105  if (run.exitCode !== 0) return { ok: false, error: `Could not write ${path}: ${run.stderr.slice(0, 200)}` }
106  return { ok: true, path, model }
107}
108
109// Reads base64 on stdin and writes the bytes to $env:JEV_IMAGE_OUT, creating its folder.
110const DECODE_PS =
111  "$ErrorActionPreference = 'Stop'; try { " +
112  '$p = [IO.Path]::GetFullPath($env:JEV_IMAGE_OUT); ' +
113  '[void][IO.Directory]::CreateDirectory([IO.Path]::GetDirectoryName($p)); ' +
114  '[IO.File]::WriteAllBytes($p, [Convert]::FromBase64String([Console]::In.ReadToEnd())) ' +
115  '} catch { [Console]::Error.WriteLine($_.Exception.Message); exit 1 }'
116
117/**
118 * Windows has no mkdir or openssl executables, and what is on PATH depends on how
119 * Claude Code was launched, so on Windows the System32 tools are run by absolute path.
120 * Resolves undefined everywhere else.
121 */
122export async function windowsSystem32($: EngineInterface): Promise<string | undefined> {
123  if ((await $.env.get('OS')) !== 'Windows_NT') return undefined
124  return `${(await $.env.get('SystemRoot')) ?? 'C:\\Windows'}\\System32`
125}
126
127function openAiMessage(text: string): string {
128  try {
129    return (JSON.parse(text) as { error?: { message?: string } }).error?.message ?? text.slice(0, 300)
130  } catch {
131    return text.slice(0, 300)
132  }
133}
134
135export function slug(s: string): string {
136  return (
137    s
138      .toLowerCase()
139      .replace(/[^a-z0-9]+/g, '-')
140      .replace(/^-+|-+$/g, '')
141      .slice(0, 40) || 'image'
142  )
143}
144
145/** Where an image is saved: `<dir>/<filename or prompt slug>.<format>`, the same for every backend. */
146export async function outputPath($: EngineInterface, dir: string, a: ImageArgs): Promise<string> {
147  const ext = a.outputFormat === 'jpeg' ? 'jpg' : (a.outputFormat ?? 'png')
148  const name = sanitize(a.filename) ?? `${slug(a.prompt)}-${await $.clock.now()}`
149  return `${dir}/${name}.${ext}`
150}
151
152function sanitize(name: string | undefined): string | undefined {
153  if (!name) return undefined
154  const base = name.replace(/\.(png|jpe?g|webp)$/i, '').replace(/[^A-Za-z0-9._-]+/g, '-')
155  return base.length > 0 ? base : undefined
156}
157
hooks/codex.ts 107 lines
1import type { EngineInterface } from 'claude-code'
2import { type EditArgs, type ImageArgs, type ImageOutcome, outputPath, windowsSystem32 } from './images'
3
4/**
5 * Image work through the Codex CLI, billed to the user's ChatGPT plan instead of the API.
6 *
7 * `codex exec` is a whole agent run: it gets the request on stdin, generates with its
8 * image tool, and must save exactly one file at the path we name. We confirm that file
9 * exists afterwards rather than trusting its reply.
10 */
11
12const TIER_HINT = {
13  flare: 'a good-quality draft; favor speed',
14  sunburst: 'a polished, production-ready final asset; take care over detail',
15} as const
16
17// A Codex agent run, image generation included, takes about a minute; allow the API's maximum.
18const TIMEOUT_MS = 600_000
19
20export type CodexImageArgs = ImageArgs & Partial<Pick<EditArgs, 'imagePaths' | 'maskPath'>>
21
22export async function codexImage($: EngineInterface, codexPath: string, dir: string, a: CodexImageArgs): Promise<ImageOutcome> {
23  const launch = await codexLaunch($, codexPath)
24  if ('error' in launch) return { ok: false, error: launch.error }
25
26  const sources = [...(a.imagePaths ?? []), ...(a.maskPath ? [a.maskPath] : [])]
27  for (const p of sources) {
28    if (!(await $.fs.exists(p))) return { ok: false, error: `No such file: ${p}` }
29  }
30
31  // Writing Codex's reply file first creates the folder, which Codex needs as its working root.
32  const lastMessage = `${dir}/.codex-last-message.txt`
33  await $.fs.write(lastMessage, '')
34  const absDir = await absolute($, dir)
35  const path = await outputPath($, dir, a)
36  const absPath = `${absDir}/${path.slice(path.lastIndexOf('/') + 1)}`
37
38  // Sandboxed to the image folder: Codex can read the attached sources but write nowhere else.
39  const argv = [
40    ...launch.argv, 'exec',
41    '--skip-git-repo-check', '--ephemeral', '--color', 'never',
42    '-s', 'workspace-write',
43    '-C', absDir,
44    '-o', `${absDir}/.codex-last-message.txt`,
45  ]
46  for (const p of sources) argv.push('-i', await absolute($, p))
47  argv.push('-') // the request comes on stdin
48
49  const run = await $.process.run(argv, { stdin: instructions(a, absPath), timeoutMs: TIMEOUT_MS })
50  if (run.exitCode !== 0) return { ok: false, error: `codex exited ${run.exitCode}: ${tail(run.stderr)}` }
51  if (!(await $.fs.exists(path))) {
52    const said = await $.fs.read(lastMessage).catch(() => '')
53    return { ok: false, error: `Codex finished without saving ${path}. It said: ${said.slice(0, 300) || '(nothing)'}` }
54  }
55  return { ok: true, path, model: 'codex (ChatGPT plan)' }
56}
57
58function instructions(a: CodexImageArgs, absPath: string): string {
59  const editing = (a.imagePaths?.length ?? 0) > 0
60  const lines = [
61    editing
62      ? 'Use your image generation tool to edit the attached image(s) as described below.'
63      : 'Use your image generation tool to create the image described below.',
64    '',
65    `Request: ${a.prompt}`,
66    `Quality: ${TIER_HINT[a.tier]}.`,
67  ]
68  if (a.maskPath) lines.push('The last attached image is a mask: change only its transparent areas.')
69  if (a.size) lines.push(`Size: ${a.size}.`)
70  if (a.quality) lines.push(`Rendering quality: ${a.quality}.`)
71  if (a.background) lines.push(`Background: ${a.background}.`)
72  lines.push(
73    '',
74    `Save exactly one image file at this absolute path: ${absPath}`,
75    'Do not create, change or delete any other file.',
76    "Reply with only the saved file's absolute path.",
77  )
78  return lines.join('\n')
79}
80
81/**
82 * How to start Codex without a shell. On Windows the npm install is a .cmd/.ps1 shim,
83 * which can't be run by argv, so node.exe runs Codex's own codex.js by absolute path.
84 * `codexPath` overrides where codex.js (or, elsewhere, the codex executable) lives.
85 */
86export async function codexLaunch($: EngineInterface, codexPath: string): Promise<{ argv: string[] } | { error: string }> {
87  if (!(await windowsSystem32($))) {
88    if (!codexPath) return { argv: ['codex'] }
89    return { argv: codexPath.endsWith('.js') ? ['node', codexPath] : [codexPath] }
90  }
91  const node = `${(await $.env.get('ProgramFiles')) ?? 'C:\\Program Files'}\\nodejs\\node.exe`
92  const script = codexPath || `${(await $.env.get('APPDATA')) ?? ''}\\npm\\node_modules\\@openai\\codex\\bin\\codex.js`
93  if (!(await $.fs.exists(node))) return { error: `Node.js not found at ${node}, which Codex needs.` }
94  if (!(await $.fs.exists(script))) {
95    return { error: `Codex not found at ${script}. Install it (npm install -g @openai/codex) or set codexPath in /config.` }
96  }
97  return { argv: [node, script] }
98}
99
100export async function absolute($: EngineInterface, path: string): Promise<string> {
101  return (await $.fs.stat(path, { resolve: true })).realPath ?? path
102}
103
104export function tail(s: string): string {
105  return s.trim().split('\n').slice(-3).join(' | ').slice(0, 400)
106}
107
hooks/daybreak.ts 77 lines
1import type { EngineInterface } from 'claude-code'
2import { absolute, codexLaunch, tail } from './codex'
3
4/**
5 * Security work handed to OpenAI Daybreak through the Codex CLI, on the user's ChatGPT plan.
6 *
7 * `--cyber-access-program` asks the server for the Daybreak tier. Whether it is granted
8 * depends on the user's OpenAI account, not on anything sent from here.
9 *
10 * Codex runs read-only at the project root: it can read the code but change nothing, and
11 * Claude applies any fixes in the session under the user's normal permissions. The report
12 * is Codex's final message, which `-o` writes to `replyPath`.
13 */
14
15// A review can read a lot of code; allow the API's maximum.
16const TIMEOUT_MS = 600_000
17
18export type DaybreakProgram = 'standard' | 'daybreak_blue' | 'daybreak_red'
19
20export function daybreakName(p: DaybreakProgram): string {
21  return p === 'daybreak_red' ? 'Daybreak Red' : p === 'daybreak_blue' ? 'Daybreak Blue' : 'Daybreak (standard access)'
22}
23
24export type DaybreakOutcome = { ok: true; report: string } | { ok: false; error: string }
25
26export async function daybreakReview(
27  $: EngineInterface,
28  codexPath: string,
29  program: DaybreakProgram,
30  model: string,
31  replyPath: string,
32  task: string,
33  paths: string[],
34): Promise<DaybreakOutcome> {
35  const launch = await codexLaunch($, codexPath)
36  if ('error' in launch) return { ok: false, error: launch.error }
37
38  for (const p of paths) {
39    if (!(await $.fs.exists(p))) return { ok: false, error: `No such file: ${p}` }
40  }
41
42  // Clearing the reply file first creates its folder and drops any earlier report.
43  await $.fs.write(replyPath, '')
44  const argv = [
45    ...launch.argv, 'exec',
46    '--skip-git-repo-check', '--ephemeral', '--color', 'never',
47    '--cyber-access-program', program,
48    ...(model ? ['-m', model] : []), // empty: Codex's own default model
49    '-s', 'read-only',
50    '-C', await absolute($, '.'),
51    '-o', await absolute($, replyPath),
52    '-', // the task comes on stdin
53  ]
54
55  const run = await $.process.run(argv, { stdin: instructions(task, paths), timeoutMs: TIMEOUT_MS })
56  if (run.exitCode !== 0) return { ok: false, error: `codex exited ${run.exitCode}: ${tail(run.stderr)}` }
57  const report = (await $.fs.read(replyPath).catch(() => '')).trim()
58  if (!report) return { ok: false, error: 'Daybreak finished without a report.' }
59  return { ok: true, report }
60}
61
62function instructions(task: string, paths: string[]): string {
63  const lines = [
64    "Defensive security work on this repository, handed over from Claude Code by the repository's owner.",
65    '',
66    `Task: ${task}`,
67  ]
68  if (paths.length) lines.push('', 'Start with these files:', ...paths.map(p => `- ${p}`))
69  lines.push(
70    '',
71    'You are read-only: do not try to change any file.',
72    'Report each finding with its file and line, severity, why it matters, and a concrete fix (a diff where it helps).',
73    'If you find nothing, say so plainly.',
74  )
75  return lines.join('\n')
76}
77