SLOPSHOPPER

optimaizr

optimAIzr inside Claude Code: what the turn has cost and your 5-hour window while Claude works, what each model switch saved, the model and effort switches you…

panebandspinnerguardcommandtoast
★ 163v0.12.1MITupdated 2026-10-25blendbunjaku/optimaizr/mods/optimaizr
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · optimaizr
│ ┃ optimaizr ✕ › fix the failing auth test and add an audit log call │ ┃ optimAIzr ● watching │ ┃ ⏺ Read(src/auth.ts) │ ┃ no switch yet · press Y in optimaizr live ⎿ Read 6 lines │ ┃ spent $0.42 · 0 requests ⏺ Update(src/auth.ts) │ ┃ ⎿ Added 2 lines, removed 1 line │ ┃ 5h ███████░░░░░░░░░░░░░░░░░ 31% ⏺ Bash(bun test) │ ┃ resets 09:53 ⎿ 3 pass, 1 fail │ ┃ │ ┃ Esc closes ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ › /optimaizr │ ⎿ optimaizr: Spend $0.42 at API rates over 0 requests since 0 │ ⎿ optimaizr: 5h window 31% · resets 09:53 │ ⎿ optimaizr: Switch none: accept one with Y in optimaizr live │ │ ✻ Thinking · 31% of 5h… optimAIzr █████░░░░░░░░░░░ 31% of 5h · resets 09:53 ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
optimAIzr █████░░░░░░░░░░░ 31% of 5h · resets 09:53
Pane · optimaizr
optimAIzr ● watching no switch yet · press Y in optimaizr live spent $0.42 · 0 requests 5h ███████░░░░░░░░░░░░░░░░░ 31% resets 09:53 Esc closes
README

optimAIzr for Claude Code

A Claude Code mod from optimAIzr. It puts what your session costs where you work, lets optimaizr live switch the model or effort of the session you are in, and shows what each switch saved.

/plugin marketplace add blendbunjaku/optimaizr
/plugin install optimaizr@optimaizr

Needs Claude Code 2.1.287 or later.

What it adds

  • The spinner shows what the turn has cost so far and how full your 5-hour window is: Thinking · $0.18 · 61% of 5h…
  • The band above the prompt shows the window, how long it lasts at this pace and when it resets: 61% of 5h · ~2h 25m left at this pace · resets 01:00
  • Each answer gets one line: optimaizr: this turn $0.18 · 2m 10s · 4 requests · ~0.4% of 5h. The share is the turn's own, from its dollars, not the meter before and after: other sessions move the meter too. It shows once optimaizr sessions or optimaizr live has worked out what 1% of your window costs.
  • What a switch saved: a switched turn's line leads with it, e.g. ~$0.10 less than the same tokens on Opus 5.5 · this turn $0.10 on Sonnet 5.5 · …, and the band keeps a running total. It prices the tokens the new model used on both models; it can't know what the original model would have used.
  • /optimaizr prints the session's spend, what it saved, both plan windows and any switch. /optimaizr hud shows it as gauges and a sparkline.
  • Switches that pay: subagents switch at once; a long conversation waits until reloading it into the new model pays back, and the band says so.
  • Before the cache expires: Claude Code caches the conversation for an hour. Once it carries 50K tokens or more, the band counts down the last 15 minutes, cache warm 10m more, then 300K is written again ($2.40), and one toast comes 5 minutes before. After it expires, the band says what the next message will cost. Past 200K, it says what each request re-reads.
  • /optimaizr handoff: Claude writes a four-line note (done, what was tried and dropped, next, the file to start from) while the cache is still warm, so it costs cents. /clear, and the next conversation in that project starts from the note instead of re-reading the old one. A note is used once and expires after 12 hours. Once the cache has expired, the note costs what your next message would, so it says how much and goes ahead only when you run it again. It is not /compact: /compact shrinks the conversation you are in and carries on, a handoff starts a new one.
  • A heavy start: when a new conversation's first request carries 60K or more before any work (a usual start is about 30K), one toast says so and points to /context, which shows what fills it: MCP tools, agents, skills, memory files. Once a session, never after /resume or compaction.
  • A guard against retry loops: when the same command fails twice in a row with nothing changed, the next identical attempt is held once and Claude is asked to change something first.
  • Switches. Press Y on a model swap in optimaizr live and running sessions in that project use the new model from their next request. A reasoning-effort finding lowers effort the same way. The first switched request leaves a note, and the band names the model. Harder task? /optimaizr off goes back for this session, /optimaizr on resumes, and optimaizr undo <rule> takes it back everywhere.

Options

OptionDefaultWhat it does
turnLinetrueThe line under each answer with what it cost.
retryGuardtrueHold a command that failed twice unchanged.

Privacy

It reads the usage figures Claude Code already shows you (cost, token counts, context fill, plan windows) and the commands Claude runs, kept in memory for the retry guard. It never reads your prompts or file contents and makes no network calls of its own. It reads ~/.optimaizr/overrides.json and ~/.optimaizr/window-rate.json, and writes one small file per session to ~/.optimaizr/mod/sessions, which is how optimaizr live knows it is running. That file also carries Claude Code's own 5-hour and weekly meters, so optimaizr profile and optimaizr live can show your real windows. /optimaizr handoff is the one exception to "no text": only when you run it, it asks Claude for a note through your own session and saves the reply to ~/.optimaizr/mod/handoffs, one file per project, which the next conversation there reads once. Nothing leaves your machine besides that one request to Claude. claude plugin validate on this folder lists every call it makes.

Develop

claude --plugin-dir mods/optimaizr     # reloads on save
claude plugin validate mods/optimaizr
claude plugin test mods/optimaizr

The tests were last run on Claude Code 2.1.296.

Source 3 files
hooks/register.tsx 1049 lines
1import type {
2  EngineInterface,
3  Register,
4  SessionUsage,
5  TurnStepInput,
6  TurnStepResult,
7} from "claude-code";
8import {
9  bar,
10  cacheNote,
11  carryCost,
12  coldHandoff,
13  costAt,
14  crossed,
15  describeSwitch,
16  duration,
17  effortFor,
18  EXPIRY_TOAST_MS,
19  EXPIRY_TOAST_USD,
20  fiveHour,
21  type Handoff,
22  HANDOFF_CONFIRM_MS,
23  handoffBlock,
24  handoffFile,
25  handoffFor,
26  HANDOFF_PROMPT,
27  inProject,
28  isWindow,
29  kTokens,
30  LONG_CONTEXT,
31  meterColor,
32  meterText,
33  modelLabel,
34  OPENING_MESSAGES,
35  type Override,
36  parseOverrides,
37  parseWindowRate,
38  PAYBACK_REQUESTS,
39  paybackRequests,
40  percent,
41  projectName,
42  record,
43  reloadCost,
44  SAVED_MILESTONES,
45  savedBy,
46  sevenDay,
47  share,
48  sparkline,
49  startNote,
50  summary,
51  switchFor,
52  turnLine,
53  usd,
54  type Tokens,
55  type Window,
56  WINDOW_ALERTS,
57  windowNote,
58  windowShare,
59  windowsOf,
60} from "./meter.ts";
61
62// The optimAIzr mod: this turn's cost and the 5-hour window while Claude works,
63// one line under each answer, the model and effort switches `optimaizr live`
64// accepts, a guard against retry loops, and a countdown before the cache expires.
65// It reads usage figures and the commands Claude runs, never prompt text or file
66// contents. The one text it keeps is the note /optimaizr handoff asks Claude for.
67
68const VERSION = "0.12.1";
69// The HUD /optimaizr hud opens beside the conversation.
70const PANE = "optimaizr";
71// overrides.json is read again at most this often, so `optimaizr undo` lands fast.
72const REREAD_MS = 3_000;
73// `optimaizr live` counts a session as gone after three missed beats.
74const BEAT_MS = 60_000;
75// Claude Code caches the main conversation for an hour; after that a reload is paid either way.
76const CACHE_TTL_MS = 55 * 60_000;
77// A command that failed this many times in a row, unchanged, is held once.
78const RETRY_LIMIT = 2;
79
80// Tools whose success can change what a retried command sees.
81const MUTATING = new Set(["Edit", "Write", "MultiEdit", "NotebookEdit", "Bash"]);
82
83type Api = EngineInterface;
84
85type Turn = {
86  startUsd: number;
87  calls: number;
88  switched?: Override;
89  saved?: number;
90  effort?: string;
91  held: number;
92};
93
94// One session's figures, shared by the hooks below.
95const state = {
96  dir: "",
97  file: "",
98  id: "",
99  // The project root: where the session started. A shell `cd` doesn't move it.
100  root: "",
101  startedAt: 0,
102  requests: 0,
103  usage: null as SessionUsage | null,
104  window: undefined as Window | undefined,
105  turn: null as Turn | null,
106  overrides: [] as Override[],
107  readAt: -Infinity,
108  // Switches that moved at least one request in this session, by slot.
109  applied: new Map<string, Override>(),
110  // Targets the API refused here; the session keeps its own setting for them.
111  refused: new Set<string>(),
112  // `/optimaizr off`: this session goes back to its own model until `/optimaizr on`.
113  paused: false,
114  // Switches the person has been told about, so the note shows once.
115  told: new Set<string>(),
116  // Net saving of the switched requests, once one has been priced.
117  saved: undefined as number | undefined,
118  held: 0,
119  // The session's average unswitched main request, which a switch is weighed against.
120  avg: { n: 0, input: 0, output: 0, read: 0, write: 0 },
121  // When the main conversation last made a request; past the cache's lifetime, it reloads anyway.
122  lastMainAt: null as number | null,
123  // The model that request went to, whose cache holds the conversation.
124  model: "",
125  // Counts /clear and /resume, so a handoff note is never read back where it was written.
126  conversation: 0,
127  // The idle stretch, by its last request, already warned about the cache expiring.
128  expiryTold: null as number | null,
129  // When a handoff on an expired cache said what it costs; running it again goes ahead.
130  handoffAsked: null as number | null,
131  // A main-conversation switch held back because its reload wouldn't pay back yet.
132  waiting: null as { o: Override; reload: number; payback: number } | null,
133  // Token totals since the mod loaded, for the cache-hit share.
134  tokens: { input: 0, read: 0, write: 0 },
135  // What switched requests cost, and what they would have cost unswitched.
136  switchedWas: 0,
137  switchedIs: 0,
138  // Session cost and 5-hour reading when the mod loaded, for the burn rate and window share.
139  startUsd: null as number | null,
140  startPct: null as number | null,
141  // What each finished turn cost, newest last, for the pane's sparkline.
142  turnCosts: [] as number[],
143  // Window levels already toasted, by reset time.
144  warned: new Set<string>(),
145  // Told once this session that a conversation started heavy.
146  startTold: false,
147  // What this conversation has seen; compaction and /clear forget it.
148  convo: {
149    // Its first main request has been made, so a later one is no start to judge.
150    started: false,
151    // Models that already wrote this conversation to their cache.
152    loaded: new Set<string>(),
153    fails: new Map<string, number>(),
154    // Held once already: the next identical command goes through.
155    waived: new Set<string>(),
156    // The handoff block this conversation started from, kept so a re-read gets the same one.
157    handoff: null as string | null,
158    // Told once that the conversation passed LONG_CONTEXT.
159    long: false,
160  },
161};
162
163function forget(): void {
164  state.convo = {
165    started: false,
166    loaded: new Set(),
167    fails: new Map(),
168    waived: new Set(),
169    handoff: null,
170    long: false,
171  };
172}
173
174async function optimaizrDir($: Api): Promise<string> {
175  const set = await $.env.get("OPTIMAIZR_DIR");
176  if (set) return set;
177  const home = (await $.env.get("HOME")) ?? (await $.env.get("USERPROFILE")) ?? ".";
178  return `${home}/.optimaizr`;
179}
180
181/** Keep the latest usage, add a 5-hour reading to the shared history, redraw. */
182async function take($: Api, u: SessionUsage): Promise<void> {
183  const was = fiveHour(state.usage?.rateLimits)?.percentUsed;
184  state.usage = u;
185  const five = fiveHour(u.rateLimits);
186  if (five && was !== undefined) {
187    const level = crossed(WINDOW_ALERTS, was, five.percentUsed);
188    const key = `${five.resetsAt ?? ""}:${level}`;
189    if (level !== null && !state.warned.has(key)) {
190      state.warned.add(key);
191      void $.ui.toast(
192        `optimAIzr: 5h window at ${percent(five.percentUsed)}${windowNote(five, state.window, await $.clock.now())}`,
193        { timeoutMs: 8_000 },
194      );
195    }
196  }
197  // The CLI reads the meters from the session file, so a move is written at once.
198  if (five && five.percentUsed !== was) await beat($).catch(() => undefined);
199  if (five) {
200    const stored = await $.store.get("window");
201    const prev = isWindow(stored) ? stored : state.window;
202    const next = record(prev, five, await $.clock.now());
203    state.window = next;
204    if (next !== prev) await $.store.set("window", next);
205  }
206  void $.ui.invalidate("ui.render");
207}
208
209async function measure($: Api): Promise<void> {
210  await take($, await $.session.usage());
211}
212
213/** The session file `optimaizr live` and `optimaizr mod` read. */
214async function beat($: Api, ended = false): Promise<void> {
215  if (!state.file) return;
216  const at = await $.clock.now();
217  const now = new Date(at).toISOString();
218  const windows = windowsOf(state.usage?.rateLimits, at);
219  const body = {
220    id: state.id,
221    version: VERSION,
222    cwd: state.root,
223    startedAt: new Date(state.startedAt).toISOString(),
224    seenAt: now,
225    ...(ended ? { endedAt: now } : {}),
226    ...(windows ? { windows } : {}),
227  };
228  await $.fs.write(state.file, `${JSON.stringify(body)}\n`);
229}
230
231/** Once a minute: tell the CLI the session is alive, and notice an undo while idle. */
232async function refresh($: Api): Promise<void> {
233  await beat($).catch(() => undefined);
234  await switches($).catch(() => undefined);
235  await expiring($).catch(() => undefined);
236  void $.ui.invalidate("ui.render");
237}
238
239/** What to say about the main conversation's cache while the prompt waits. */
240async function cacheNow($: Api): Promise<{ label: string; text: string } | null> {
241  if (state.turn || state.lastMainAt === null || !state.model) return null;
242  return cacheNote({
243    model: state.model,
244    context: state.usage?.context.tokens ?? 0,
245    idleMs: (await $.clock.now()) - state.lastMainAt,
246    ttlMs: CACHE_TTL_MS,
247  });
248}
249
250/** One toast shortly before an idle conversation's cache expires, when coming back would cost. */
251async function expiring($: Api): Promise<void> {
252  const at = state.lastMainAt;
253  if (at === null || state.turn || state.expiryTold === at) return;
254  const left = at + CACHE_TTL_MS - (await $.clock.now());
255  const context = state.usage?.context.tokens ?? 0;
256  const cost = carryCost(state.model, context);
257  if (left <= 0 || left > EXPIRY_TOAST_MS || !cost || cost.rewrite < EXPIRY_TOAST_USD) return;
258  state.expiryTold = at;
259  void $.ui.toast(
260    `optimAIzr: the cache expires in ${duration(left)}. Coming back after that writes ${kTokens(context)} again (${usd(cost.rewrite)}). Leaving? /optimaizr handoff saves a note now, while it costs cents, and after /clear the next conversation starts from it.`,
261    { timeoutMs: 10_000 },
262  );
263}
264
265/** /optimaizr handoff: Claude writes a note from the warm cache, kept for the next conversation here. */
266async function handoff($: Api): Promise<string> {
267  if (state.turn) return "Claude is still working. Run /optimaizr handoff once the turn ends.";
268  // On an expired cache the note writes the whole conversation again, so it says so first.
269  const at = await $.clock.now();
270  const idle = state.lastMainAt === null ? 0 : at - state.lastMainAt;
271  const context = state.usage?.context.tokens ?? 0;
272  const cold = coldHandoff({ model: state.model, context, idleMs: idle, ttlMs: CACHE_TTL_MS });
273  const asked = state.handoffAsked !== null && at - state.handoffAsked <= HANDOFF_CONFIRM_MS;
274  if (cold !== null && !asked) {
275    state.handoffAsked = at;
276    return (
277      `The cache expired while you were away (${duration(idle)}), so the note writes all ${kTokens(context)} again (${usd(cold)}), as your next message would. ` +
278      `Run /optimaizr handoff again within 2 minutes to go ahead, or skip the note: /clear, and tell the new conversation in a line or two what you were doing.`
279    );
280  }
281  state.handoffAsked = null;
282  const r = await $.model.fork({ prompt: HANDOFF_PROMPT });
283  if (!r.isAnswered) {
284    if (r.reason === "nothing-to-fork") {
285      return "Nothing to hand off yet: Claude hasn't answered in this conversation.";
286    }
287    if (r.reason === "api-error") {
288      return `Couldn't write the note: the API answered ${r.status ?? "nothing"} (${r.error}). Try again in a moment.`;
289    }
290    return r.reason === "aborted"
291      ? "The note was cancelled."
292      : "Claude answered without a note. Try again.";
293  }
294  const now = await $.clock.now();
295  const note: Handoff = {
296    version: 1,
297    root: state.root,
298    session: state.id,
299    conversation: state.conversation,
300    at: new Date(now).toISOString(),
301    text: r.text.trim(),
302  };
303  await $.fs.write(handoffFile(state.dir, state.root), `${JSON.stringify(note, null, 2)}\n`);
304
305  // Mostly read from cache, it cost little; otherwise the cache had expired.
306  const u = r.usage;
307  const cost = costAt(state.model, u, { hour: true });
308  const warm = u.cache_read_input_tokens >= u.input_tokens + u.cache_creation_input_tokens;
309  const how =
310    cost === null
311      ? ""
312      : warm
313        ? `, written from the warm cache for ${usd(cost)}`
314        : `, for ${usd(cost)}: the cache had expired, so Claude read the conversation again`;
315  return (
316    `Handoff saved for ${projectName(state.root)}${how}.\n\n${note.text}\n\n` +
317    `/clear now and the next conversation in this project starts from this note. ` +
318    `It is used once, within 12 hours.`
319  );
320}
321
322/** The handoff note a new conversation here starts from, claimed once. */
323async function startFrom($: Api): Promise<string | null> {
324  if (state.convo.handoff !== null) return state.convo.handoff;
325  const dir = state.dir || (await optimaizrDir($));
326  const root = state.root || (await $.session.root());
327  const file = handoffFile(dir, root);
328  const text = await $.fs.read(file).catch(() => "");
329  let stored: unknown = null;
330  try {
331    stored = JSON.parse(typeof text === "string" ? text : "");
332  } catch {
333    return null;
334  }
335  const now = await $.clock.now();
336  const h = handoffFor(stored, {
337    root,
338    session: state.id,
339    conversation: state.conversation,
340    now,
341  });
342  if (!h) return null;
343  await $.fs.write(
344    file,
345    `${JSON.stringify({ ...h, usedAt: new Date(now).toISOString() }, null, 2)}\n`,
346  );
347  state.convo.handoff = handoffBlock(h);
348  void $.ui.toast("optimAIzr: this conversation starts from your handoff note", {
349    timeoutMs: 6_000,
350  });
351  return state.convo.handoff;
352}
353
354// Written by `optimaizr live` and `optimaizr sessions`; read once per answer.
355async function windowRate($: Api): Promise<number | null> {
356  const text = await $.fs.read(`${state.dir}/window-rate.json`).catch(() => "");
357  return parseWindowRate(typeof text === "string" ? text : "");
358}
359
360async function switches($: Api): Promise<Override[]> {
361  const now = await $.clock.now();
362  if (now - state.readAt < REREAD_MS) return state.overrides;
363  state.readAt = now;
364  const text = await $.fs.read(`${state.dir}/overrides.json`).catch(() => "");
365  state.overrides = parseOverrides(typeof text === "string" ? text : "");
366  return state.overrides;
367}
368
369/** Fold an unswitched main request into the session's average. */
370function learn(u: Tokens): void {
371  const a = state.avg;
372  a.n += 1;
373  a.input += (u.input_tokens - a.input) / a.n;
374  a.output += (u.output_tokens - a.output) / a.n;
375  a.read += (u.cache_read_input_tokens - a.read) / a.n;
376  a.write += (u.cache_creation_input_tokens - a.write) / a.n;
377}
378
379/** The average request, or a modest one before there is any to go on. */
380function average(contextTokens: number): Tokens {
381  const a = state.avg;
382  return a.n > 0
383    ? {
384        input_tokens: a.input,
385        output_tokens: a.output,
386        cache_read_input_tokens: a.read,
387        cache_creation_input_tokens: a.write,
388      }
389    : {
390        input_tokens: 0,
391        output_tokens: 500,
392        cache_read_input_tokens: contextTokens,
393        cache_creation_input_tokens: 1_000,
394      };
395}
396
397/** Count a finished request and refresh the figures the spinner shows. */
398async function counted($: Api, u?: Tokens | null): Promise<void> {
399  if (u) {
400    state.tokens.input += u.input_tokens;
401    state.tokens.read += u.cache_read_input_tokens;
402    state.tokens.write += u.cache_creation_input_tokens;
403  }
404  state.requests += 1;
405  if (state.turn) state.turn.calls += 1;
406  await measure($).catch(() => undefined);
407}
408
409const slotOf = (o: Override) =>
410  `${o.project}\u0000${o.subagent ?? ""}\u0000${o.from}\u0000${o.effort ?? ""}`;
411
412// No response and no usage, and not because the person interrupted: the request failed.
413const failed = (r: TurnStepResult, aborted: boolean) =>
414  !aborted && r.stopReason === null && r.usage === null;
415
416const clip = (s: string, n = 60) => (s.length > n ? `${s.slice(0, n - 3)}...` : s);
417
418const commandKey = (agent: string, command: string) =>
419  `${agent}\u0000${command.trim().replace(/\s+/g, " ")}`;
420
421export const register: Register = (on, options) => {
422  const showTurnLine = options.turnLine !== false;
423  const retryGuard = options.retryGuard !== false;
424
425  on("session.start", async ($, e, next) => {
426    state.dir = await optimaizrDir($);
427    state.id = await $.session.id();
428    state.root = await $.session.root();
429    state.startedAt = await $.clock.now();
430    state.file = `${state.dir}/mod/sessions/${state.id}.json`;
431    await $.command.register({
432      name: "optimaizr",
433      description:
434        "This session's spend, savings and plan windows; hud opens the HUD, handoff saves a note to start fresh from, off or on pauses a switch",
435      argumentHint: "[hud|handoff|off|on]",
436      immediate: true,
437    });
438    await beat($).catch(() => undefined);
439    $.clock.every(BEAT_MS, () => void refresh($));
440    await measure($).catch(() => undefined);
441    state.startUsd = state.usage?.cost?.usd ?? null;
442    state.startPct = fiveHour(state.usage?.rateLimits)?.percentUsed ?? null;
443    return next(e);
444  });
445
446  // /clear and /resume end a conversation, not the session the mod runs in.
447  on("session.end", async ($, e, next) => {
448    forget();
449    if (e.reason === "clear" || e.reason === "resume") {
450      state.conversation += 1;
451      state.lastMainAt = null;
452    } else {
453      await beat($, true).catch(() => undefined);
454    }
455    return next(e);
456  });
457
458  // A new conversation in a project with a waiting handoff note starts from it, once.
459  on("prompt.context", async ($, e, next) => {
460    const r = await next(e);
461    const text = await startFrom($).catch(() => null);
462    return text ? { ...r, blocks: [...r.blocks, { name: "optimaizrHandoff", text }] } : r;
463  });
464
465  // After compaction the conversation is new to every model's cache.
466  on("session.compact", async ($, e, next) => {
467    forget();
468    // It goes on from a summary, so its next request is no start to judge.
469    state.convo.started = true;
470    return next(e);
471  });
472
473  on("session.measure", async ($, e, next) => {
474    await take($, { context: e.context, rateLimits: e.rateLimits, cost: e.cost }).catch(
475      () => undefined,
476    );
477    return next(e);
478  });
479
480  on("turn.start", async ($, e, next) => {
481    await measure($).catch(() => undefined);
482    state.turn = {
483      startUsd: state.usage?.cost?.usd ?? 0,
484      calls: 0,
485      held: 0,
486    };
487    return next(e);
488  });
489
490  on("turn.step", async function* ($, e, next) {
491    const req = {
492      cwd: state.root,
493      model: e.model,
494      subagent: e.agentId !== undefined,
495      ...(e.effort !== undefined ? { effort: e.effort } : {}),
496    };
497    const list = state.paused ? [] : await switches($).catch(() => []);
498    const sw = switchFor(list, req);
499    let model = sw && !state.refused.has(sw.to) ? sw : undefined;
500
501    // A conversation under way switches only once reloading it pays back soon.
502    // Subagents start with an empty cache, so they always switch.
503    const now = await $.clock.now();
504    const cold = state.lastMainAt !== null && now - state.lastMainAt > CACHE_TTL_MS;
505    if (model && e.agentId === undefined && !state.convo.loaded.has(model.to) && !cold) {
506      const context = state.usage?.context.tokens ?? 0;
507      const payback = paybackRequests(model, context, average(context));
508      if (payback > PAYBACK_REQUESTS) {
509        state.waiting = { o: model, reload: reloadCost(model, context) ?? 0, payback };
510        model = undefined;
511      } else {
512        state.waiting = null;
513      }
514    }
515    // A new conversation's first request shows what loads before any work.
516    const opening =
517      e.agentId === undefined && !state.convo.started && e.messageCount <= OPENING_MESSAGES;
518    if (e.agentId === undefined) {
519      state.lastMainAt = now;
520      state.model = model?.to ?? e.model;
521      state.convo.started = true;
522    }
523    const ef = model ? undefined : effortFor(list, req);
524    const effort = ef && !state.refused.has(`effort:${ef.effort}`) ? ef : undefined;
525    const o = model ?? effort;
526    if (!o) {
527      const r = yield* next(e);
528      // A request that rewrote an expired cache would make every request look costly.
529      if (e.agentId === undefined && r.usage && !cold) learn(r.usage);
530      if (opening) heavyStart($, r.usage);
531      await counted($, r.usage);
532      return r;
533    }
534
535    // Stream the switched request through by hand, to know whether any of it
536    // arrived before deciding it failed.
537    const stream = next(
538      model ? { ...e, model: model.to } : { ...e, effort: o.effort as TurnStepInput["effort"] },
539    );
540    let arrived = false;
541    let result: TurnStepResult | undefined;
542    try {
543      for (;;) {
544        const step = await stream.next();
545        if (step.done) {
546          result = step.value;
547          break;
548        }
549        arrived = true;
550        yield step.value;
551      }
552    } catch (err) {
553      if (arrived || next.signal.aborted) throw err;
554    }
555    if (result && (arrived || !failed(result, next.signal.aborted))) {
556      state.applied.set(slotOf(o), o);
557      if (model && result.usage) {
558        // Only a warm main conversation has a cache to reload; a subagent, or a
559        // conversation idle past the cache's lifetime, writes it on either model.
560        const main = e.agentId === undefined;
561        const first = main && !cold && !state.convo.loaded.has(model.to);
562        if (main) state.convo.loaded.add(model.to);
563        const saved = savedBy(model, result.usage, first, e.agentId === undefined);
564        const was = costAt(model.from, result.usage, { warm: first, hour: main });
565        const is = costAt(model.to, result.usage, { hour: main });
566        if (was !== null && is !== null) {
567          state.switchedWas += was;
568          state.switchedIs += is;
569        }
570        const before = state.saved ?? 0;
571        if (saved !== null) state.saved = before + saved;
572        const milestone = crossed(SAVED_MILESTONES, before, state.saved ?? 0);
573        if (milestone !== null) {
574          void $.ui.toast(
575            `optimAIzr: switching saved ~${usd(state.saved ?? 0)} this session, against the same tokens on the original model`,
576            { timeoutMs: 6_000 },
577          );
578        }
579        if (state.turn && saved !== null) state.turn.saved = (state.turn.saved ?? 0) + saved;
580      }
581      if (state.turn && model) state.turn.switched = model;
582      if (state.turn && !model) state.turn.effort = o.effort;
583      // Subagents and the main conversation are told apart: either can switch first.
584      const sub = e.agentId !== undefined;
585      const told = `${slotOf(o)}\u0000${sub ? "sub" : "main"}`;
586      if (!state.told.has(told)) {
587        state.told.add(told);
588        $.ui.log(switchNote(o, sub));
589        if (o.auto) {
590          void $.ui.toast(
591            `optimAIzr: ${o.effort ? `lowered effort to ${o.effort}` : `switched to ${modelLabel(o.to)}`} automatically · p or /optimaizr off undoes`,
592            { timeoutMs: 8_000 },
593          );
594        }
595      }
596      if (opening) heavyStart($, result.usage);
597      await counted($, result.usage);
598      return result;
599    }
600
601    // Refused before a word came back: send the request as it was, and leave
602    // this target alone for the rest of the session.
603    state.refused.add(model ? model.to : `effort:${o.effort}`);
604    void $.ui.toast(
605      model
606        ? `optimAIzr: ${modelLabel(model.to)} was refused, staying on ${modelLabel(e.model)}`
607        : `optimAIzr: ${o.effort} effort was refused, staying at ${String(e.effort)}`,
608    );
609    const r = yield* next(e);
610    if (opening) heavyStart($, r.usage);
611    await counted($);
612    return r;
613  });
614
615  on("tool.call", async ($, e, next) => {
616    const agent = e.agentId ?? "main";
617    const c = state.convo;
618
619    if (retryGuard && e.tool === "Bash") {
620      const key = commandKey(agent, e.command);
621      if ((c.fails.get(key) ?? 0) >= RETRY_LIMIT && !c.waived.has(key)) {
622        c.waived.add(key);
623        state.held += 1;
624        if (state.turn) state.turn.held += 1;
625        $.ui.log(
626          `Held a retry of \`${clip(e.command.trim())}\`: it failed twice in a row with nothing changed in between.`,
627        );
628        return {
629          deny:
630            "optimAIzr held this retry: the same command failed twice in a row and nothing has changed since. " +
631            "Change something first (the command, the code or the setup), or tell the user what is blocking you. " +
632            "If it must run unchanged, run it again and it will go through.",
633        };
634      }
635    }
636
637    const ran = await next(e);
638    const ok = ran.deny === undefined && ran.isError !== true;
639    if (e.tool === "Bash" && ran.isError === true) {
640      const key = commandKey(agent, e.command);
641      c.fails.set(key, (c.fails.get(key) ?? 0) + 1);
642    }
643    if (ok && MUTATING.has(e.tool)) {
644      c.fails.clear();
645      c.waived.clear();
646    }
647    return ran;
648  });
649
650  on("turn.complete", async ($, e, next) => {
651    const r = await next(e);
652    if (e.agentId !== undefined) return r;
653    const t = state.turn;
654    state.turn = null;
655    void $.ui.invalidate("ui.render");
656    if (!t || e.reason !== "answer") return r;
657
658    await measure($).catch(() => undefined);
659    longNote($);
660    const spent = (state.usage?.cost?.usd ?? 0) - t.startUsd;
661    state.turnCosts = [...state.turnCosts, Math.max(0, spent)].slice(-24);
662    if (!showTurnLine || spent < 0.005) return r;
663    const rate = await windowRate($).catch(() => null);
664    const line = turnLine({
665      usd: spent,
666      calls: t.calls,
667      ...(t.switched
668        ? {
669            switched: {
670              from: modelLabel(t.switched.from),
671              to: modelLabel(t.switched.to),
672              saved: t.saved ?? null,
673            },
674          }
675        : {}),
676      ...(t.effort ? { effort: t.effort } : {}),
677      held: t.held,
678      ...(typeof e.durationMs === "number" ? { ms: e.durationMs } : {}),
679      ...(rate ? { of5h: spent / rate } : {}),
680    });
681    return { ...r, text: line };
682  });
683
684  on("ui.render", { component: "Spinner" }, async ($, e, next) => {
685    const t = state.turn;
686    const extra = meterText({
687      usd: t ? (state.usage?.cost?.usd ?? 0) - t.startUsd : null,
688      five: fiveHour(state.usage?.rateLimits),
689      ...(t?.switched ? { model: modelLabel(t.switched.to) } : {}),
690      ...(t?.saved !== undefined ? { saved: t.saved } : {}),
691    });
692    if (!extra) return next(e);
693    return next({ ...e, props: { ...e.props, suffix: `${extra}${e.props.suffix}` } });
694  });
695
696  on("ui.render", { component: "AbovePrompt" }, async ($, e, next) => {
697    const u = state.usage;
698    if (e.props.hasSurvey || !u) return next(e);
699    const { Box, Text } = $.ui.resolve(e);
700    const five = fiveHour(u.rateLimits);
701    const waiting = waitingNote();
702    const cache = e.props.isWorking ? null : await cacheNow($);
703    const lines = [
704      ...switchLines(activeSwitches()),
705      ...(waiting ? [waiting] : []),
706      ...(cache ? [`${cache.label.padEnd(10)}${cache.text}`] : []),
707    ];
708    const wide = e.props.bodyColumns >= 72;
709
710    // Off a plan there is no window: the session's spend is the real bill.
711    if (!five) {
712      const spent = u.cost?.usd ?? 0;
713      if (spent < 0.01 && lines.length === 0) return next(e);
714      return (
715        <Box flexDirection="column">
716          <Box>
717            <Text color="blue" bold>
718              optimAIzr
719            </Text>
720            <Text dimColor>{`  ${usd(spent)} this session`}</Text>
721          </Box>
722          {lines[0] !== undefined && <Text dimColor>{lines[0]}</Text>}
723          {lines[1] !== undefined && <Text dimColor>{lines[1]}</Text>}
724          {lines[2] !== undefined && <Text dimColor>{lines[2]}</Text>}
725        </Box>
726      );
727    }
728
729    const [filled, empty] = bar(five.percentUsed, 16);
730    const week = sevenDay(u.rateLimits);
731    const note = wide ? windowNote(five, state.window, await $.clock.now()) : "";
732    const weekNote = week && week.percentUsed >= 75 ? ` · 7d ${percent(week.percentUsed)}` : "";
733    return (
734      <Box flexDirection="column">
735        <Box>
736          <Text color="blue" bold>
737            optimAIzr
738          </Text>
739          <Text>{"  "}</Text>
740          {wide && <Text color={meterColor(five.percentUsed)}>{filled}</Text>}
741          {wide && <Text dimColor>{`${empty}  `}</Text>}
742          <Text color={meterColor(five.percentUsed)} bold>
743            {percent(five.percentUsed)}
744          </Text>
745          <Text>{" of 5h"}</Text>
746          <Text dimColor>{`${note}${weekNote}`}</Text>
747        </Box>
748        {lines[0] !== undefined && <Text dimColor>{lines[0]}</Text>}
749        {lines[1] !== undefined && <Text dimColor>{lines[1]}</Text>}
750        {lines[2] !== undefined && <Text dimColor>{lines[2]}</Text>}
751      </Box>
752    );
753  });
754
755  on("command.run", { command: "optimaizr" }, async ($, e) => {
756    const list = await switches($).catch(() => []);
757    const here = list.filter((o) => inProject(state.root, o.project));
758    const arg = e.args.trim().toLowerCase();
759    if (arg === "off" || arg === "on") {
760      state.paused = arg === "off";
761      void $.ui.invalidate("ui.render");
762      return { text: pauseText(here, state.paused) };
763    }
764    // "pane" was its first name; it still works.
765    if (arg === "hud" || arg === "pane") {
766      await $.ui.open({ id: PANE, title: "optimAIzr HUD", focus: true });
767      return { text: "Opened the optimAIzr HUD. Esc closes it." };
768    }
769    if (arg === "handoff") return { text: await handoff($) };
770    if (arg) {
771      return {
772        text: "Use /optimaizr, /optimaizr hud, /optimaizr handoff, /optimaizr off or /optimaizr on.",
773      };
774    }
775
776    await measure($).catch(() => undefined);
777    const u = state.usage;
778    const waiting = waitingNote();
779    const cache = await cacheNow($);
780    return {
781      text: summary({
782        ...(u?.cost ? { usd: u.cost.usd } : {}),
783        requests: state.requests,
784        startedAt: state.startedAt,
785        limits: u?.rateLimits ?? [],
786        ...(state.window ? { window: state.window } : {}),
787        now: await $.clock.now(),
788        switches: here,
789        paused: state.paused,
790        ...(state.saved !== undefined ? { saved: state.saved } : {}),
791        held: state.held,
792        turns: state.turnCosts,
793        ...(waiting ? { note: waiting } : {}),
794        ...(cache ? { cache } : {}),
795      }),
796    };
797  });
798
799  // The session at a glance: /optimaizr hud.
800  on("ui.render", { component: "Pane", requestId: PANE }, async ($, e) => {
801    const { Box, Text, Button } = $.ui.resolve(e);
802    const u = state.usage;
803    const five = fiveHour(u?.rateLimits);
804    const week = sevenDay(u?.rateLimits);
805    const now = await $.clock.now();
806    const cols = e.props.bodyColumns;
807    const width = Math.max(8, Math.min(24, cols - 22));
808
809    const status = hudStatus();
810    const saved = state.saved !== undefined && state.saved > 0 ? state.saved : 0;
811    const cheaper =
812      state.switchedWas > 0 ? Math.round((1 - state.switchedIs / state.switchedWas) * 100) : null;
813    const spent = u?.cost ? u.cost.usd : null;
814    // The rate covers what this mod has watched, from when it loaded.
815    const hours = (now - state.startedAt) / 3_600_000;
816    const rate =
817      spent !== null && state.startUsd !== null && hours >= 1 / 30
818        ? (spent - state.startUsd) / hours
819        : null;
820    const t = state.tokens;
821    const ofWindow =
822      five && spent !== null && state.startUsd !== null && state.startPct !== null
823        ? windowShare(saved, {
824            usd: spent - state.startUsd,
825            pct: five.percentUsed - state.startPct,
826          })
827        : null;
828    const cacheHits = t.input + t.read + t.write > 0 ? t.read / (t.input + t.read + t.write) : null;
829
830    const gauge = (label: string, pct: number, note: string) => (
831      <Box flexDirection="column">
832        <Box>
833          <Text dimColor>{`${label}  `}</Text>
834          <Text color={meterColor(pct)}>{bar(pct, width)[0]}</Text>
835          <Text dimColor>{bar(pct, width)[1]}</Text>
836          <Text color={meterColor(pct)} bold>{`  ${percent(pct)}`}</Text>
837        </Box>
838        {note && <Text dimColor>{`    ${note}`}</Text>}
839      </Box>
840    );
841    const turns = state.turnCosts;
842    const top = Math.max(...turns, 0);
843    const priciest = turns.indexOf(top) + 1;
844    const lines = switchLines(activeSwitches());
845    const waiting = waitingNote();
846    const switchable = activeSwitches().length > 0 || waiting !== null;
847    const cache = await cacheNow($);
848
849    return (
850      <Box flexDirection="column" gap={1}>
851        <Box>
852          <Text color="blue" bold>
853            optimAIzr
854          </Text>
855          <Text color={status.color} bold>{`   ● ${status.text}`}</Text>
856        </Box>
857
858        <Box flexDirection="column">
859          {state.switchedWas === 0 ? (
860            <Text dimColor>no switch yet · press Y in optimaizr live</Text>
861          ) : (state.saved ?? 0) < 0 ? (
862            <Text color="yellow">{`reload ${usd(-(state.saved ?? 0))} not won back yet`}</Text>
863          ) : (
864            <Box>
865              <Text color="green" bold>{`saved ~${usd(saved)}`}</Text>
866              {cheaper !== null && cheaper > 0 && (
867                <Text color="green">{`  ${cheaper}% cheaper`}</Text>
868              )}
869              {ofWindow !== null && (
870                <Text color="green">{`  ≈${share(ofWindow)} of your 5h window`}</Text>
871              )}
872            </Box>
873          )}
874          <Text dimColor>
875            {[
876              spent !== null ? `spent ${usd(spent)}` : null,
877              rate !== null ? `${usd(rate)}/h` : null,
878              `${state.requests} requests`,
879              cacheHits !== null ? `cache ${percent(cacheHits * 100)}` : null,
880            ]
881              .filter(Boolean)
882              .join(" · ")}
883          </Text>
884        </Box>
885
886        {five && gauge("5h", five.percentUsed, paceNote(five, now))}
887        {week && gauge("7d", week.percentUsed, "")}
888
889        {turns.length > 1 && (
890          <Box flexDirection="column">
891            <Box>
892              <Text dimColor>{"turns  "}</Text>
893              {turns.map((v) => (
894                <Text
895                  color={v / (top || 1) > 0.66 ? "red" : v / (top || 1) > 0.33 ? "yellow" : "green"}
896                >
897                  {sparkline([v, top]).charAt(0)}
898                </Text>
899              ))}
900            </Box>
901            <Text dimColor>{`    priciest #${priciest} ${usd(top)} · last ${turns.length}`}</Text>
902          </Box>
903        )}
904
905        {lines[0] !== undefined && <Text>{lines[0]}</Text>}
906        {lines[1] !== undefined && <Text>{lines[1]}</Text>}
907        {waiting && <Text color="yellow">{waiting}</Text>}
908        {cache && <Text color="yellow">{`${cache.label.padEnd(10)}${cache.text}`}</Text>}
909        {state.held > 0 && (
910          <Text
911            dimColor
912          >{`guard  ${state.held} ${state.held === 1 ? "retry" : "retries"} held`}</Text>
913        )}
914
915        <Box gap={2}>
916          {switchable && (
917            <Button
918              key="pause"
919              label={state.paused ? "resume switch" : "pause switch"}
920              hotkey="p"
921              onPress={() => {
922                state.paused = !state.paused;
923                void $.ui.invalidate("ui.render");
924              }}
925            />
926          )}
927          <Text dimColor>Esc closes</Text>
928        </Box>
929      </Box>
930    );
931  });
932};
933
934/** A new conversation that starts heavy is told once a session what fills it. */
935function heavyStart($: Api, u: Tokens | null | undefined): void {
936  if (!u || state.startTold) return;
937  const note = startNote(
938    u.input_tokens + u.cache_read_input_tokens + u.cache_creation_input_tokens,
939  );
940  if (!note) return;
941  state.startTold = true;
942  void $.ui.toast(note, { timeoutMs: 12_000 });
943}
944
945/** Once a conversation passes LONG_CONTEXT, say what each request now re-reads. */
946function longNote($: Api): void {
947  const context = state.usage?.context.tokens ?? 0;
948  const cost = carryCost(state.model, context);
949  if (state.convo.long || context < LONG_CONTEXT || !cost) return;
950  state.convo.long = true;
951  void $.ui.toast(
952    `optimAIzr: this conversation is past ${kTokens(LONG_CONTEXT)}. Each request re-reads all ${kTokens(context)} (${usd(cost.read)}). At a natural break: /compact shrinks it to a summary and carries on, or /optimaizr handoff saves a note and /clear starts fresh from it.`,
953    { timeoutMs: 10_000 },
954  );
955}
956
957/** The pill at the top of the HUD: what the mod is doing right now. */
958function hudStatus(): { text: string; color: string } {
959  if (state.paused) return { text: "paused", color: "yellow" };
960  if (waitingNote()) return { text: "waiting", color: "yellow" };
961  const model = activeSwitches().find((o) => !o.effort);
962  if (model) {
963    return { text: `on ${modelLabel(model.to)}${model.auto ? " (auto)" : ""}`, color: "green" };
964  }
965  const effort = activeSwitches().find((o) => o.effort);
966  if (effort) return { text: `${effort.effort} effort`, color: "green" };
967  return { text: "watching", color: "blue" };
968}
969
970/** The 5-hour window's outlook: when it runs out at this pace, or that it lasts. */
971function paceNote(
972  five: { resetsAt?: string; percentUsed: number; kind: string },
973  now: number,
974): string {
975  const note = windowNote(five, state.window, now).replace(/^ · /, "");
976  return note.startsWith("lasts") ? `${note} ✓` : note;
977}
978
979/** Why a switch for this conversation is waiting, if one is. */
980function waitingNote(): string | null {
981  const w = state.waiting;
982  if (!w || state.paused || state.convo.loaded.has(w.o.to)) return null;
983  const back = Number.isFinite(w.payback)
984    ? `pays back in ~${Math.ceil(w.payback)} requests`
985    : "would not pay back";
986  return `waiting   ${describeSwitch(w.o)} · reload ${usd(w.reload)} ${back} · subagents switch now`;
987}
988
989/** Switches that moved a request here and are still in overrides.json. */
990function activeSwitches(): Override[] {
991  return [...state.applied.values()].filter((a) =>
992    state.overrides.some((o) => slotOf(o) === slotOf(a) && o.to === a.to),
993  );
994}
995
996/** The band's lines under the window: the model switch, then the effort switch. */
997function switchLines(applied: readonly Override[]): string[] {
998  const back = state.paused ? "/optimaizr on to switch again" : "harder task? /optimaizr off";
999  const saved =
1000    !state.paused && state.saved !== undefined && state.saved >= 0.005
1001      ? ` · saved ~${usd(state.saved)}`
1002      : "";
1003  const lines: string[] = [];
1004  // While the main conversation waits, the waiting line says what subagents do.
1005  const model = waitingNote() ? undefined : applied.find((o) => !o.effort);
1006  if (model) {
1007    lines.push(
1008      `${state.paused ? "paused  " : "switched"}  ${describeSwitch(model)}${model.auto ? " (auto)" : ""}${saved} · ${back}`,
1009    );
1010  }
1011  const effort = applied.find((o) => o.effort);
1012  if (effort) {
1013    lines.push(`${state.paused ? "paused  " : "effort  "}  ${describeSwitch(effort)} · ${back}`);
1014  }
1015  return lines;
1016}
1017
1018/** The line left in the conversation the first time a switch moves a request. */
1019function switchNote(o: Override, sub: boolean): string {
1020  const who = sub || o.subagent === true ? "this session's subagents" : "this session";
1021  const how = o.auto ? `${o.rule}, automatically` : o.rule;
1022  if (o.effort) {
1023    return (
1024      `Lowered ${who} to ${o.effort} effort on ${modelLabel(o.from)} (${how}). ` +
1025      `Harder task? /optimaizr off goes back to its own effort.`
1026    );
1027  }
1028  return (
1029    `Switched ${who} from ${modelLabel(o.from)} to ${modelLabel(o.to)} (${how}). ` +
1030    `Harder task? /optimaizr off goes back to ${modelLabel(o.from)}.`
1031  );
1032}
1033
1034function pauseText(here: readonly Override[], paused: boolean): string {
1035  const o = here.find((x) => !x.effort) ?? here[0];
1036  if (!o) return "No switch is active in this project.";
1037  if (o.effort) {
1038    return paused
1039      ? `Switches are off for this session: requests use their own effort again. ` +
1040          `/optimaizr on lowers it to ${o.effort} again; optimaizr undo ${o.rule} removes it everywhere.`
1041      : `Switches are on again for this session: requests use ${o.effort} effort.`;
1042  }
1043  return paused
1044    ? `Switches are off for this session: requests go to ${modelLabel(o.from)} again. ` +
1045        `/optimaizr on switches back to ${modelLabel(o.to)}; ` +
1046        `optimaizr undo ${o.rule} removes it everywhere.`
1047    : `Switches are on again for this session: requests go to ${modelLabel(o.to)}.`;
1048}
1049
hooks/meter.ts 647 lines
1// Pure helpers for register.tsx. Nothing here touches `$`, so the figures the
2// band, the spinner and /optimaizr show can be tested on their own.
3
4import { PRICES, type Price, type Rates } from "./prices.ts";
5
6export type RateLimit = { kind: string; percentUsed: number; resetsAt?: string };
7
8/** One reading of the 5-hour window: when, and how full. */
9export type Sample = { t: number; pct: number };
10
11/** The readings of one 5-hour window, kept in $.store so every session shares them. */
12export type Window = { resetsAt: string; samples: Sample[] };
13
14/** An entry of ~/.optimaizr/overrides.json, as `optimaizr live` writes it. */
15export type Override = {
16  rule: string;
17  source?: string;
18  project: string;
19  subagent?: boolean;
20  from: string;
21  to: string;
22  /** An effort switch: the same model, asked to think less. */
23  effort?: string;
24  /** Applied by `optimaizr live --auto`, with no one pressing Y. */
25  auto?: boolean;
26};
27
28/** A request's token counts, as the API reports them. */
29export type Tokens = {
30  input_tokens: number;
31  output_tokens: number;
32  cache_read_input_tokens: number;
33  cache_creation_input_tokens: number;
34};
35
36const MINUTE = 60_000;
37const HOUR = 60 * MINUTE;
38
39export const fiveHour = (limits: readonly RateLimit[] | undefined) =>
40  limits?.find((l) => l.kind === "five_hour");
41
42export const sevenDay = (limits: readonly RateLimit[] | undefined) =>
43  limits?.find((l) => l.kind === "seven_day");
44
45/**
46 * The meters as the session file carries them, so `optimaizr profile` and
47 * `optimaizr live` can show Claude Code's real windows. Undefined when neither
48 * meter is reported (an API-key session has none).
49 */
50export function windowsOf(limits: readonly RateLimit[] | undefined, at: number) {
51  const pick = (l: RateLimit | undefined) =>
52    l ? { percentUsed: l.percentUsed, ...(l.resetsAt ? { resetsAt: l.resetsAt } : {}) } : undefined;
53  const five = pick(fiveHour(limits));
54  const seven = pick(sevenDay(limits));
55  if (!five && !seven) return undefined;
56  return {
57    at: new Date(at).toISOString(),
58    ...(five ? { fiveHour: five } : {}),
59    ...(seven ? { sevenDay: seven } : {}),
60  };
61}
62
63/** `claude-opus-5-5[1m]` and `claude-opus-5-5-20260915` are `claude-opus-5-5`. */
64export function baseModel(id: string): string {
65  return id
66    .toLowerCase()
67    .replace(/\[[^\]]*\]$/, "")
68    .replace(/-\d{8}$/, "");
69}
70
71/** `claude-sonnet-5-5` is `Sonnet 5.5`; an id it can't read is shown as given. */
72export function modelLabel(id: string): string {
73  const m = /^claude-(opus|sonnet|haiku|fable)-(\d+)(?:-(\d{1,2}))?$/.exec(baseModel(id));
74  if (!m) return id;
75  const family = m[1]!;
76  return `${family[0]!.toUpperCase()}${family.slice(1)} ${m[2]}${m[3] ? `.${m[3]}` : ""}`;
77}
78
79export function usd(n: number): string {
80  return `$${n.toFixed(2)}`;
81}
82
83export function percent(n: number): string {
84  return `${Math.round(n)}%`;
85}
86
87/** `45m`, `2h 05m`. */
88export function duration(ms: number): string {
89  const m = Math.max(1, Math.round(ms / MINUTE));
90  return m < 60 ? `${m}m` : `${Math.floor(m / 60)}h ${String(m % 60).padStart(2, "0")}m`;
91}
92
93/** How long a turn took: `42s`, `2m 10s`, `1h 05m`. */
94export function elapsed(ms: number): string {
95  const s = Math.max(0, Math.round(ms / 1000));
96  if (s < 60) return `${s}s`;
97  const m = Math.floor(s / 60);
98  if (m < 60) return `${m}m ${String(s % 60).padStart(2, "0")}s`;
99  return `${Math.floor(m / 60)}h ${String(m % 60).padStart(2, "0")}m`;
100}
101
102/** Local wall-clock time, `01:00`. */
103export function clock(iso: string): string {
104  const d = new Date(iso);
105  return `${String(d.getHours()).padStart(2, "0")}:${String(d.getMinutes()).padStart(2, "0")}`;
106}
107
108/**
109 * A saving as a share of the 5-hour window, from how far the window moved
110 * against what was spent meanwhile. Null until it has moved a whole point;
111 * other sessions on the account move it too, so it is an estimate.
112 */
113export function windowShare(saved: number, spent: { usd: number; pct: number }): number | null {
114  if (spent.pct < 1 || spent.usd <= 0 || saved <= 0) return null;
115  return saved / (spent.usd / spent.pct);
116}
117
118/** `0.4%`, `2.1%`, `12%`. */
119export function share(pct: number): string {
120  return pct < 10 ? `${pct.toFixed(1)}%` : `${Math.round(pct)}%`;
121}
122
123/**
124 * The dollars per 1% of the 5h window `optimaizr live` or `sessions` learned
125 * from the plan meter. The meter only shows whole percents, so a turn's own
126 * share comes from its cost. Null when the file is missing or unreadable.
127 */
128export function parseWindowRate(text: string): number | null {
129  try {
130    const r = JSON.parse(text)?.usdPerPercent;
131    return typeof r === "number" && Number.isFinite(r) && r > 0 ? r : null;
132  } catch {
133    return null;
134  }
135}
136
137/** The meter's colour as the window fills: calm, then a warning, then urgent. */
138export function meterColor(pct: number): "green" | "yellow" | "red" {
139  return pct < 60 ? "green" : pct < 85 ? "yellow" : "red";
140}
141
142/** A sparkline of turn costs, one cell each, scaled to the largest. */
143export function sparkline(values: readonly number[]): string {
144  const cells = "▁▂▃▄▅▆▇█";
145  const top = Math.max(...values, 0);
146  return values.map((v) => cells[top > 0 ? Math.min(7, Math.round((v / top) * 7)) : 0]).join("");
147}
148
149/** The window levels that earn a toast, and the session savings that do. */
150export const WINDOW_ALERTS = [80, 95];
151export const SAVED_MILESTONES = [0.5, 1, 2, 5, 10, 20, 50];
152
153/** The highest threshold crossed going from `was` to `now`, if any. */
154export function crossed(thresholds: readonly number[], was: number, now: number): number | null {
155  const hit = thresholds.filter((t) => was < t && now >= t);
156  return hit.length > 0 ? hit[hit.length - 1]! : null;
157}
158
159/** The filled and empty halves of a meter `width` cells wide. */
160export function bar(pct: number, width: number): [string, string] {
161  const n = Math.round((Math.min(100, Math.max(0, pct)) / 100) * width);
162  return ["█".repeat(n), "░".repeat(width - n)];
163}
164
165export function projectName(p: string): string {
166  return p.split(/[\\/]/).filter(Boolean).slice(-1)[0] ?? p;
167}
168
169/** `shop-api subagents: Opus 5.5 → Sonnet 5.5`, or `shop-api: Opus 5.5 at low effort`. */
170export function describeSwitch(o: Override): string {
171  const who = o.subagent === true ? " subagents" : o.subagent === false ? " main" : "";
172  const what = o.effort
173    ? `${modelLabel(o.from)} at ${o.effort} effort`
174    : `${modelLabel(o.from)} → ${modelLabel(o.to)}`;
175  return `${projectName(o.project)}${who}: ${what}`;
176}
177
178function isOverride(v: unknown): v is Override {
179  const o = v as Override;
180  return (
181    typeof o === "object" &&
182    o !== null &&
183    o.source === "claude-code" &&
184    typeof o.rule === "string" &&
185    typeof o.project === "string" &&
186    typeof o.from === "string" &&
187    typeof o.to === "string" &&
188    (o.subagent === undefined || typeof o.subagent === "boolean") &&
189    (o.effort === undefined || EFFORTS.includes(o.effort)) &&
190    (o.auto === undefined || typeof o.auto === "boolean")
191  );
192}
193
194/** Claude Code's entries of overrides.json; anything unreadable is no switch at all. */
195export function parseOverrides(text: string): Override[] {
196  try {
197    const file = JSON.parse(text) as { overrides?: unknown };
198    return Array.isArray(file?.overrides) ? file.overrides.filter(isOverride) : [];
199  } catch {
200    return [];
201  }
202}
203
204const slash = (p: string) => p.replace(/\\/g, "/").replace(/\/+$/, "");
205
206/** Is `cwd` the project, or a folder inside it? */
207export function inProject(cwd: string, project: string): boolean {
208  const c = slash(cwd);
209  const p = slash(project);
210  return c === p || c.startsWith(`${p}/`);
211}
212
213const covers = (o: Override, req: { cwd: string; model: string; subagent: boolean }) =>
214  inProject(req.cwd, o.project) &&
215  (o.subagent === undefined || o.subagent === req.subagent) &&
216  baseModel(o.from) === baseModel(req.model);
217
218/** The model switch for one request: its project, agent and model. */
219export function switchFor(
220  list: readonly Override[],
221  req: { cwd: string; model: string; subagent: boolean },
222): Override | undefined {
223  return list.find((o) => !o.effort && covers(o, req) && baseModel(o.to) !== baseModel(req.model));
224}
225
226/** Lowest first. A number, or a level not listed, is never lowered. */
227const EFFORTS: readonly string[] = ["low", "medium", "high", "xhigh", "max"];
228
229/** The effort switch for one request, only when it asks for less than the request does. */
230export function effortFor(
231  list: readonly Override[],
232  req: { cwd: string; model: string; subagent: boolean; effort?: string | number },
233): Override | undefined {
234  const now = typeof req.effort === "string" ? EFFORTS.indexOf(req.effort) : -1;
235  return list.find(
236    (o) => o.effort !== undefined && covers(o, req) && EFFORTS.indexOf(o.effort) < now,
237  );
238}
239
240const priceOf = (model: string): Price | undefined => PRICES[baseModel(model)];
241
242/** The rates a request of `promptTokens` pays: a tiered model costs more past its threshold. */
243const ratesAt = (p: Price, promptTokens: number): Rates =>
244  p.above && promptTokens > p.above.tokens ? p.above : p;
245
246/**
247 * What a request's tokens cost at a model's rates. `warm`: its cache writes would
248 * have been reads. `hour`: the main conversation caches for an hour, at 2x input;
249 * subagents for 5 minutes, at 1.25x, as the engine prices them.
250 */
251export function costAt(
252  model: string,
253  t: Tokens,
254  opts: { warm?: boolean; hour?: boolean } = {},
255): number | null {
256  const price = priceOf(model);
257  if (!price) return null;
258  const p = ratesAt(
259    price,
260    t.input_tokens + t.cache_read_input_tokens + t.cache_creation_input_tokens,
261  );
262  const write = opts.warm ? p.cacheRead : opts.hour ? p.cacheWrite1h : p.cacheWrite;
263  return (
264    (t.input_tokens * p.input +
265      t.output_tokens * p.output +
266      t.cache_read_input_tokens * p.cacheRead +
267      t.cache_creation_input_tokens * write) /
268    1_000_000
269  );
270}
271
272/**
273 * What a switched request saved: the same tokens at the original model's rates,
274 * less what they cost on the new one. The first request on the new model writes
275 * the conversation to its cache, where the original model would have read it,
276 * so that one is priced warm and can come out negative.
277 */
278/** What reloading a conversation of `contextTokens` into the new model's cache costs, over reading it on the old one. */
279export function reloadCost(o: Override, contextTokens: number): number | null {
280  const fromPrice = priceOf(o.from);
281  const toPrice = priceOf(o.to);
282  if (!fromPrice || !toPrice) return null;
283  const from = ratesAt(fromPrice, contextTokens);
284  const to = ratesAt(toPrice, contextTokens);
285  return (contextTokens * (to.cacheWrite1h - from.cacheRead)) / 1_000_000;
286}
287
288// Switching a conversation under way waits until the reload is won back within this many requests.
289export const PAYBACK_REQUESTS = 10;
290
291/**
292 * Requests until a mid-conversation switch pays for its reload, from this
293 * session's average request. Infinity when a request saves nothing.
294 */
295export function paybackRequests(o: Override, contextTokens: number, avg: Tokens): number {
296  const reload = reloadCost(o, contextTokens);
297  const was = costAt(o.from, avg, { hour: true });
298  const is = costAt(o.to, avg, { hour: true });
299  if (reload === null || was === null || is === null) return Infinity;
300  if (reload <= 0) return 0;
301  return was > is ? reload / (was - is) : Infinity;
302}
303
304export function savedBy(o: Override, t: Tokens, first: boolean, hour = true): number | null {
305  const was = costAt(o.from, t, { warm: first, hour });
306  const is = costAt(o.to, t, { hour });
307  return was === null || is === null ? null : was - is;
308}
309
310/** `340K`. */
311export function kTokens(n: number): string {
312  return `${Math.round(n / 1_000)}K`;
313}
314
315// Below this, writing the conversation again costs about what a fresh start does.
316export const COLD_MIN_CONTEXT = 50_000;
317// Past this, each request re-reads far more than the work in front of it needs.
318export const LONG_CONTEXT = 200_000;
319// The band counts down this long before the cache expires.
320export const COUNTDOWN_MS = 15 * MINUTE;
321// One toast this close to expiry, when coming back would cost at least EXPIRY_TOAST_USD.
322export const EXPIRY_TOAST_MS = 5 * MINUTE;
323export const EXPIRY_TOAST_USD = 0.5;
324
325/**
326 * What carrying the conversation costs on one request: read from a warm cache,
327 * or written to it again at the 1-hour rate once it expired.
328 */
329export function carryCost(
330  model: string,
331  contextTokens: number,
332): { read: number; rewrite: number } | null {
333  const price = priceOf(model);
334  if (!price) return null;
335  const p = ratesAt(price, contextTokens);
336  return {
337    read: (contextTokens * p.cacheRead) / 1_000_000,
338    rewrite: (contextTokens * p.cacheWrite1h) / 1_000_000,
339  };
340}
341
342/**
343 * What to say about the conversation's cache while the prompt waits: a
344 * countdown before it expires, what coming back costs after, or what each
345 * request re-reads once the conversation is long. Null when none applies.
346 */
347export function cacheNote(c: {
348  model: string;
349  context: number;
350  idleMs: number;
351  ttlMs: number;
352}): { label: "cache" | "context"; text: string } | null {
353  if (c.context < COLD_MIN_CONTEXT) return null;
354  const cost = carryCost(c.model, c.context);
355  if (!cost) return null;
356  const left = c.ttlMs - c.idleMs;
357  const size = kTokens(c.context);
358  if (left <= 0) {
359    return {
360      label: "cache",
361      text: `expired · the next message writes ${size} again (${usd(cost.rewrite)})`,
362    };
363  }
364  if (left <= COUNTDOWN_MS) {
365    return {
366      label: "cache",
367      text: `warm ${duration(left)} more, then ${size} is written again (${usd(cost.rewrite)}) · leaving? /optimaizr handoff`,
368    };
369  }
370  if (c.context >= LONG_CONTEXT) {
371    return {
372      label: "context",
373      text: `${size} · each request re-reads it (${usd(cost.read)}) · fresh start: /optimaizr handoff`,
374    };
375  }
376  return null;
377}
378
379// A handoff on an expired cache goes ahead when it is run again within this long.
380export const HANDOFF_CONFIRM_MS = 2 * MINUTE;
381
382/**
383 * What a handoff note costs once the cache has expired: the note is forked from
384 * the whole conversation, which is written to the cache again, as the next
385 * message would. Null while the cache is warm or the conversation is short.
386 */
387export function coldHandoff(c: {
388  model: string;
389  context: number;
390  idleMs: number;
391  ttlMs: number;
392}): number | null {
393  if (c.idleMs <= c.ttlMs || c.context < COLD_MIN_CONTEXT) return null;
394  return carryCost(c.model, c.context)?.rewrite ?? null;
395}
396
397// A usual first request: system prompt, built-in tools and a short CLAUDE.md.
398export const USUAL_START = 30_000;
399// From here a start loads more than it should: MCP tools, agents, skills, memory files.
400export const HEAVY_START = 60_000;
401// A new conversation's first request carries the prompt and a few attachments; /resume carries it all.
402export const OPENING_MESSAGES = 10;
403
404/** What a new conversation's first request says when it starts heavy, or null. */
405export function startNote(context: number): string | null {
406  if (context < HEAVY_START) return null;
407  return `optimAIzr: this conversation started at ${kTokens(context)} before any work, where a usual start is about ${kTokens(USUAL_START)}, and every message re-reads it. /context shows what fills it: MCP tools, agents, skills, memory files.`;
408}
409
410// A handoff note is used once, by a conversation started within this long.
411export const HANDOFF_TTL_MS = 12 * HOUR;
412
413/** What Claude is asked for: a note a fresh conversation can start from. */
414export const HANDOFF_PROMPT =
415  "Write a handoff note so a fresh conversation can carry on this work without this one. " +
416  "Plain text, four lines, under 100 words in all: 'Done:' what changed and what was decided, " +
417  "'Dropped:' what was tried and did not work, so it is not tried again (or 'nothing'), " +
418  "'Next:' the first thing to do, 'File:' the file to open first, with the command or error " +
419  "if there is one. Exact paths. No preamble, and no tool calls.";
420
421export type Handoff = {
422  version: 1;
423  root: string;
424  /** The session and conversation it was written in, which never read it back. */
425  session: string;
426  conversation: number;
427  at: string;
428  text: string;
429  usedAt?: string;
430};
431
432export function isHandoff(v: unknown): v is Handoff {
433  const h = v as Handoff;
434  return (
435    typeof h === "object" &&
436    h !== null &&
437    h.version === 1 &&
438    typeof h.root === "string" &&
439    typeof h.session === "string" &&
440    typeof h.conversation === "number" &&
441    typeof h.at === "string" &&
442    typeof h.text === "string"
443  );
444}
445
446/** One note per project: `/work/shop-api` keeps `work-shop-api.json`. */
447export function handoffFile(dir: string, root: string): string {
448  const key =
449    slash(root)
450      .replace(/[^A-Za-z0-9._-]+/g, "-")
451      .replace(/^-+|-+$/g, "") || "root";
452  return `${dir}/mod/handoffs/${key}.json`;
453}
454
455/**
456 * The note a new conversation should start from, if one is waiting: same
457 * project, unused, recent, and written in another conversation.
458 */
459export function handoffFor(
460  v: unknown,
461  at: { root: string; session: string; conversation: number; now: number },
462): Handoff | null {
463  if (!isHandoff(v) || v.usedAt || slash(v.root) !== slash(at.root)) return null;
464  if (v.session === at.session && v.conversation === at.conversation) return null;
465  const age = at.now - Date.parse(v.at);
466  return age >= 0 && age <= HANDOFF_TTL_MS ? v : null;
467}
468
469/** The context block the next conversation reads. */
470export function handoffBlock(h: Handoff): string {
471  return (
472    `A handoff note from the previous conversation in this project, written by Claude at ` +
473    `${clock(h.at)} and saved by optimAIzr. Check it against the code before relying on it.\n\n` +
474    h.text.trim()
475  );
476}
477
478export function isWindow(v: unknown): v is Window {
479  const w = v as Window;
480  return (
481    typeof w === "object" &&
482    w !== null &&
483    typeof w.resetsAt === "string" &&
484    Array.isArray(w.samples)
485  );
486}
487
488/** Add a reading. A new window, or one that went down, starts the history over. */
489export function record(w: Window | undefined, limit: RateLimit, t: number): Window {
490  const resetsAt = limit.resetsAt ?? "";
491  const pct = limit.percentUsed;
492  const last = w?.samples.at(-1);
493  if (!w || w.resetsAt !== resetsAt || (last && pct < last.pct)) {
494    return { resetsAt, samples: [{ t, pct }] };
495  }
496  if (last && last.pct === pct) return w;
497  return { resetsAt, samples: [...w.samples, { t, pct }].slice(-120) };
498}
499
500/**
501 * When the window runs out at the pace of the last hour, as epoch ms. Null
502 * until there are 10 minutes and one point of use to go on.
503 */
504export function runsOutAt(w: Window): number | null {
505  const last = w.samples.at(-1);
506  const base = w.samples.find((s) => last && s.t >= last.t - HOUR);
507  if (!last || !base) return null;
508  const span = last.t - base.t;
509  const used = last.pct - base.pct;
510  if (span < 10 * MINUTE || used < 1) return null;
511  return last.t + ((100 - last.pct) / used) * span;
512}
513
514/** What follows the percent in the band: the pace, then the reset. */
515export function windowNote(five: RateLimit, w: Window | undefined, now: number): string {
516  const resets = five.resetsAt ? clock(five.resetsAt) : null;
517  const end = w && w.resetsAt === (five.resetsAt ?? "") ? runsOutAt(w) : null;
518  const resetAt = five.resetsAt ? Date.parse(five.resetsAt) : null;
519  if (end !== null && resetAt !== null && end >= resetAt) return ` · lasts to the ${resets} reset`;
520  const pace = end === null ? "" : ` · ~${duration(Math.max(0, end - now))} left at this pace`;
521  return `${pace}${resets ? ` · resets ${resets}` : ""}`;
522}
523
524/** What the spinner shows after its word: the switched model, the turn so far, the window. */
525export function meterText(m: {
526  usd: number | null;
527  five?: RateLimit;
528  model?: string;
529  saved?: number;
530}): string {
531  const parts: string[] = [];
532  if (m.model) parts.push(m.model);
533  if (m.usd !== null && m.usd >= 0.005) parts.push(usd(m.usd));
534  if (m.saved !== undefined && m.saved >= 0.005) parts.push(`saved ~${usd(m.saved)}`);
535  if (m.five) parts.push(`${percent(m.five.percentUsed)} of 5h`);
536  return parts.length > 0 ? ` · ${parts.join(" · ")}` : "";
537}
538
539const plural = (n: number, one: string, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
540
541/**
542 * The line under an answer. Claude Code puts the plugin's name in front of it.
543 * A switched turn leads with its difference against the same tokens on the
544 * original model, so the basis of the number reads with it.
545 */
546export function turnLine(t: {
547  usd: number;
548  calls: number;
549  /** The model switch this turn ran under: labels, and what it saved (null: unpriced). */
550  switched?: { from: string; to: string; saved: number | null };
551  effort?: string;
552  held?: number;
553  /** How long the turn took. */
554  ms?: number;
555  /** Its own share of the 5h window, in percent. */
556  of5h?: number;
557}): string {
558  const parts: string[] = [];
559  const s = t.switched;
560  if (s && s.saved !== null && s.saved >= 0.005) {
561    parts.push(
562      `~${usd(s.saved)} less than the same tokens on ${s.from}`,
563      `this turn ${usd(t.usd)} on ${s.to}`,
564    );
565  } else if (s) {
566    parts.push(`this turn ${usd(t.usd)} on ${s.to}`);
567  } else {
568    parts.push(`this turn ${usd(t.usd)}${t.effort ? ` at ${t.effort} effort` : ""}`);
569  }
570  if (t.ms !== undefined) parts.push(elapsed(t.ms));
571  parts.push(plural(t.calls, "request"));
572  if (s && s.saved !== null && s.saved <= -0.005) {
573    parts.push(`${usd(-s.saved)} more than ${s.from} once, to load the conversation`);
574  }
575  if (t.held) parts.push(`${plural(t.held, "retry", "retries")} held`);
576  // Its own share, not the meter before and after: other sessions move the meter too.
577  if (t.of5h !== undefined) parts.push(`${t.of5h < 0.1 ? "<0.1" : `~${share(t.of5h)}`} of 5h`);
578  return parts.join(" · ");
579}
580
581/** What /optimaizr prints. */
582export function summary(s: {
583  usd?: number;
584  requests: number;
585  startedAt: number;
586  limits: readonly RateLimit[];
587  window?: Window;
588  now: number;
589  switches: readonly Override[];
590  paused?: boolean;
591  /** Net saving of this session's switched requests, when any were priced. */
592  saved?: number;
593  held?: number;
594  /** What each recent turn cost, oldest first. */
595  turns?: readonly number[];
596  /** Why a switch for this conversation is waiting, when one is. */
597  note?: string;
598  /** The conversation's cache, when there is something to say about it. */
599  cache?: { label: string; text: string };
600}): string {
601  const rows: Array<[string, string]> = [];
602  const onPlan = s.limits.length > 0;
603  const spent = s.usd === undefined ? "not reported" : usd(s.usd);
604  rows.push([
605    "Spend",
606    `${spent}${onPlan ? " at API rates" : ""} over ${plural(s.requests, "request")} since ${clock(new Date(s.startedAt).toISOString())}`,
607  ]);
608  if (s.saved !== undefined && s.saved < 0) {
609    rows.push([
610      "Saved",
611      `not yet: reloading the conversation cost ${usd(-s.saved)} more than the switch has saved so far`,
612    ]);
613  } else if (s.saved !== undefined) {
614    rows.push([
615      "Saved",
616      `~${usd(s.saved)} by switching models: the same tokens at the original model's rates, less what they cost`,
617    ]);
618  }
619  if (s.held) rows.push(["Guard", `${plural(s.held, "retry", "retries")} held`]);
620  if (s.turns && s.turns.length > 1) {
621    rows.push([
622      "Turns",
623      `${sparkline(s.turns)}  last ${s.turns.length}, up to ${usd(Math.max(...s.turns))}`,
624    ]);
625  }
626  const five = fiveHour(s.limits);
627  if (five)
628    rows.push(["5h window", `${percent(five.percentUsed)}${windowNote(five, s.window, s.now)}`]);
629  const week = sevenDay(s.limits);
630  if (week) {
631    const resets = week.resetsAt
632      ? ` · resets ${new Date(week.resetsAt).toDateString().slice(0, 3)} ${clock(week.resetsAt)}`
633      : "";
634    rows.push(["7d window", `${percent(week.percentUsed)}${resets}`]);
635  }
636  if (s.cache) rows.push([s.cache.label === "cache" ? "Cache" : "Context", s.cache.text]);
637  for (const [i, o] of s.switches.entries()) {
638    const how = s.paused
639      ? "off in this session: /optimaizr on"
640      : `/optimaizr off here, optimaizr undo ${o.rule} everywhere`;
641    rows.push([i === 0 ? "Switch" : "", `${describeSwitch(o)} · ${how}`]);
642  }
643  if (s.switches.length === 0) rows.push(["Switch", "none: accept one with Y in optimaizr live"]);
644  if (s.note) rows.push(["", s.note.replace(/^waiting\s+/, "waiting: ")]);
645  return rows.map(([k, v]) => `${k.padEnd(11)}${v}`).join("\n");
646}
647
hooks/prices.ts 138 lines
1// Generated by apps/cli/scripts/mod-prices.mjs from the engine's catalogue.
2// Don't edit by hand: run `npm run mod:prices` in apps/cli.
3
4export type Rates = {
5  input: number;
6  output: number;
7  cacheRead: number;
8  cacheWrite: number;
9  cacheWrite1h: number;
10};
11
12/** `above`: the rates once a request's prompt is over `tokens`. */
13export type Price = Rates & { label: string; above?: Rates & { tokens: number } };
14
15/** USD per million tokens, the rates in force when this file was written. */
16export const PRICES: Record<string, Price> = {
17  "claude-fable-5-1": {
18    label: "Fable 5.1",
19    input: 10,
20    output: 50,
21    cacheRead: 0.25,
22    cacheWrite: 12.5,
23    cacheWrite1h: 20,
24  },
25  "claude-mythos-5-1": {
26    label: "Mythos 5.1",
27    input: 10,
28    output: 50,
29    cacheRead: 0.25,
30    cacheWrite: 12.5,
31    cacheWrite1h: 20,
32  },
33  "claude-fable-5": {
34    label: "Fable 5",
35    input: 10,
36    output: 50,
37    cacheRead: 1,
38    cacheWrite: 12.5,
39    cacheWrite1h: 20,
40  },
41  "claude-mythos-5": {
42    label: "Mythos 5",
43    input: 10,
44    output: 50,
45    cacheRead: 1,
46    cacheWrite: 12.5,
47    cacheWrite1h: 20,
48  },
49  "claude-opus-5-5": {
50    label: "Opus 5.5",
51    input: 4,
52    output: 20,
53    cacheRead: 0.2,
54    cacheWrite: 5,
55    cacheWrite1h: 8,
56  },
57  "claude-opus-5": {
58    label: "Opus 5",
59    input: 5,
60    output: 25,
61    cacheRead: 0.5,
62    cacheWrite: 6.25,
63    cacheWrite1h: 10,
64  },
65  "claude-opus-4-8": {
66    label: "Opus 4.8",
67    input: 5,
68    output: 25,
69    cacheRead: 0.5,
70    cacheWrite: 6.25,
71    cacheWrite1h: 10,
72  },
73  "claude-opus-4-7": {
74    label: "Opus 4.7",
75    input: 5,
76    output: 25,
77    cacheRead: 0.5,
78    cacheWrite: 6.25,
79    cacheWrite1h: 10,
80  },
81  "claude-opus-4-6": {
82    label: "Opus 4.6",
83    input: 5,
84    output: 25,
85    cacheRead: 0.5,
86    cacheWrite: 6.25,
87    cacheWrite1h: 10,
88  },
89  "claude-sonnet-5-5": {
90    label: "Sonnet 5.5",
91    input: 2,
92    output: 10,
93    cacheRead: 0.2,
94    cacheWrite: 2.5,
95    cacheWrite1h: 4,
96  },
97  "claude-sonnet-5": {
98    label: "Sonnet 5",
99    input: 2,
100    output: 10,
101    cacheRead: 0.2,
102    cacheWrite: 2.5,
103    cacheWrite1h: 4,
104  },
105  "claude-sonnet-4-6": {
106    label: "Sonnet 4.6",
107    input: 3,
108    output: 15,
109    cacheRead: 0.3,
110    cacheWrite: 3.75,
111    cacheWrite1h: 6,
112  },
113  "claude-haiku-5-5": {
114    label: "Haiku 5.5",
115    input: 0.1,
116    output: 0.5,
117    cacheRead: 0.01,
118    cacheWrite: 0.125,
119    cacheWrite1h: 0.2,
120    above: {
121      tokens: 100000,
122      input: 0.5,
123      output: 2.5,
124      cacheRead: 0.05,
125      cacheWrite: 0.625,
126      cacheWrite1h: 1,
127    },
128  },
129  "claude-haiku-4-5": {
130    label: "Haiku 4.5",
131    input: 1,
132    output: 5,
133    cacheRead: 0.1,
134    cacheWrite: 1.25,
135    cacheWrite1h: 2,
136  },
137};
138