Keeps the prompt cache warm while you are away, asks before a prompt that would re-cache a large conversation, and with Jev (TypeSafe) keeps the context lean…

A Claude Code mod that keeps the prompt cache warm while you are away, asks before a prompt that would re-cache a large conversation, and, with Jev (TypeSafe's fast judgment model), keeps the context lean: large tool output is trimmed to what the agent needs, and a conversation compacts in about a second. Everything but the Jev parts works without Jev.
The Claude Code port of pi-cache-guard, with the same core (hooks/core.ts, the clock and the settings), the same Jev logic (hooks/lean.ts, the trimming and compaction, with no harness imports) and the same settings file.
Keeps the cache warm. A cached prefix lives for its TTL from the start of the last request that used it: 1 hour for the main conversation on a Claude subscription within plan usage, 5 minutes with an API key, a cloud provider or usage credits. The mod reads the tier off the session's own cache writes in the transcript. At 90% of the TTL with no request since, it calls $.model.fork, which re-sends the main thread's last request (same model, system prompt, tools and messages) with one short question after it, tools denied and its own tail never cached. The API serves the prefix from the cache, which restarts its clock.
Each refresh has to pay for itself by Pi's rule:
15% x miss cost - refresh cost; during a long tool run it is the whole miss cost.kept the prompt cache warm (601k tokens read, ~$0.12 at API prices). The model never sees these lines.Warns. A prompt you type while idle onto an expired cache asks first when the rewrite would cost at least warn.minCost (default $0.50 at API prices):
Prompt cache miss. The prompt cache expired 10m ago: this prompt re-caches 601k tokens (~$4.69 at API prices). What now?
1. Keep the prompt
2. New conversation (~$0)
3. Compact first (~$0 with Jev)
4. Send anyway (~$4.81)
The options:
/clear and sends the prompt as the new conversation's first.up to ~$2.40). It then sends the prompt onto the summary. If the compaction is skipped or fails, the prompt goes back in the box.Without Jev the question ends with a tip: /cache-guard jev sets it up, or turns it (and the tip) off.
The headline cost is what the miss adds over a cache hit; the costs in the options are each path's total. Images attached to a held prompt are not resent by the New conversation and Compact paths. /cache-guard off stops asking in the session. Resumed and forked sessions are judged from the transcript, or from the SessionStart hook input (seconds_since_last_response, context_tokens) when the transcript is not written yet. Prompts from loops, peers, notifications, the SDK and -p are never held, and neither are slash commands.
Trims tool output (Jev). Large text results (over 12k characters from Bash, Grep, Glob, LS, WebFetch, WebSearch and MCP tools; over 50k from Read) are trimmed as their row is stored (session.append), before the model reads them, so the prompt cache is never disturbed. Jev reads the agent's current step (your request, what the agent said since, the tool and its arguments) and the output, split into at most 150 blocks, and says which blocks hold what the agent needs: errors, failures, warnings, requested values, results. The kept blocks plus the first 5 and last 20 lines stay, in order, with [… N lines omitted …] markers, and a footer points at the full output saved under ~/.claude/cache-guard/tool-output/<session>/<call>.txt (under $CLAUDE_CONFIG_DIR when set), to read with offset/limit. The output is saved first; if that fails it stays whole.
Output too large for one Jev request is pre-filtered in code first (head, tail, every line that looks like an error with two lines of context, and an even sample). Nothing is trimmed when Jev thinks the agent wants the whole output, when more than 70% would be kept, when the same tool and arguments were already trimmed this turn (asking again returns everything), when the tool reported an error, or when Jev is unavailable or slow (jev.timeoutMs, 2.5 s). Edits, writes, agents, todos and every other tool are never touched. Each trim logs a dim line (trimmed Bash output to 23 of 1,104 lines (Jev, 412 ms); full output: ...); /cache-guard status shows the tokens kept out so far.
Subagents are left alone: their tool output never enters the main conversation (the Agent tool returns their answer), and their transcripts go when they finish. Only the main loop's results are trimmed.
Compacts with Jev. Jev sorts every message and tool call being compacted into verbatim (requirements, decisions, exact values, open errors), summarize, or drop (superseded or noise), in batches of up to 120, compact.concurrency requests at a time.
/cache-guard compact [focus] write the summary in code, with no LLM, in about a second: the earlier summary (Claude Code's or Jev's, when the conversation starts with one), your requests, the verbatim items, one-line notes for the rest, and the files read and modified. The conversation becomes that one message. Strict: if Jev fails, the compaction is skipped and nothing is spent./compact and automatic compaction run Claude Code's own summarizer on the conversation with dropped items removed and summarized ones shortened (user text to 1.5k characters, assistant text to 1k, tool results to 600), then add the verbatim items as one more message after the summary ("compact": { "filter": false } leaves them to Claude Code alone). Any failure falls back to the normal compaction.precompute compaction (the engine summarizing ahead of time) and a subagent's own are never touched.Status. Claude Code reports the cache to the status line itself (prompt_cache.warm, expires_at, ttl, recache_tokens_if_cold). A mod cannot ship a status line, so the countdown belongs in your status line script, e.g. jq '.prompt_cache.expires_at'. The mod draws none.
Tells herdr. Inside a herdr pane, the mod sets the pane token cache with herdr pane report-metadata --source cache-guard. The token reads ❄ 601k once the cache has expired and the next prompt would re-cache at least the warning threshold. It is cleared while the cache is warm or small, and when the session ends. An expiry timer flips it on time. herdr's agents sidebar shows it with { token = "$cache" } in a [ui.sidebar.agents] row. Set "herdr": { "enabled": false } to turn it off.
Claude Code's own guards stay in place: /model and /effort ask while the cache is warm, and /resume offers to resume from a summary after a long break.
Claude Code reaches Jev through TypeSafe's own API (https://api.typesafe.ai/v1/systemone, via $.http.fetch), so it needs a TypeSafe API key from console.typesafe.ai/keys. Give it either way; the plugin option wins:
typesafe_api_key. It is declared sensitive, so Claude Code keeps the value in secure storage (the keychain), not in settings.json. Set it with /plugin configure cache-guard@inline in Claude Code (cache-guard@<marketplace> when installed from one), or from a shell: echo '{"typesafe_api_key": "<key>"}' | claude plugin configure cache-guard@inline --values-stdin
A mod cannot set a sensitive option itself ($.config.set only reaches the /config rows, which leave sensitive fields out), so /cache-guard jev shows these steps instead of asking for the key. The option is read when the mod loads: restart Claude Code after setting it.
TYPESAFE_API_KEY in the environment Claude Code starts in./cache-guard jev shows which key is in use and checks that Jev answers (Jev: typesafe/jev-latest (key from TYPESAFE_API_KEY), answered in 312 ms.), and can turn Jev off. With no key it explains the setup and offers to turn Jev off, tips included. Its choice is saved as jev.enabled in ~/.claude/cache-guard.json (merged into the file; a file that is not a JSON object is left alone). jev.model picks the model (jev-latest when empty); jev.provider must be empty or typesafe here (the other ports can reach Jev through other providers; this one reports any other value as "not set up").
/cache-guard or /cache-guard status: the last request, TTL and its source, time left or how long since it expired, the keep-warm state, and which Jev is in use./cache-guard warm: a refresh now, whatever the schedule and the expected saving say. Use it to bridge a break, or to check that refreshes hit./cache-guard compact [focus]: a Jev compaction now, judged against the focus (or your last two requests). Without Jev it offers Claude Code's summary instead./cache-guard jev: set up, check, or turn off Jev./cache-guard on, /cache-guard off: the keep-warm and the warning, for this session. Trimming and compaction follow the settings.~/.config/agents/cache-guard.json (shared with the other ports), then ~/.claude/cache-guard.json, then the project's .agents/cache-guard.json and .claude/cache-guard.json. Later files win; objects merge. The files are read again at every turn. The defaults, as this port reads them:
{
"enabled": true,
"warn": { "enabled": true, "minCost": 0.5 },
"warm": { "enabled": true, "continuationProbability": 0.15, "minSavings": 0.05,
"idleMinutes": { "5m": 30, "1h": 120 },
"prompt": "Cache keep-alive. Do not use tools or think. Reply with exactly: ok" },
"herdr": { "enabled": true },
"jev": { "enabled": true, "provider": "", "model": "", "timeoutMs": 2500 },
"trim": { "enabled": true, "minChars": 12000, "readMinChars": 50000, "maxBlocks": 150, "stateBudgetChars": 60000,
"keepThreshold": 0.4, "needsAllThreshold": 0.6, "maxKeptShare": 0.7, "headLines": 5, "tailLines": 20 },
"compact": { "filter": true, "timeoutMs": 10000, "concurrency": 4 }
}
warn.minTokens, warn.confirmSeconds and warn.idleMinutes are for the other ports (Claude Code always has prices and a TTL). "enabled": false turns everything off, Jev included; "jev": { "enabled": false } only the Jev parts.
It is a plugin directory with a hooks module. Load it with claude --plugin-dir <checkout>, or list it in CLAUDE_CODE_PLUGIN_DIRS. It needs Claude Code 2.1.287 or newer; the Jev parts use session.append, session.compact and $.http.fetch as Claude Code 2.1.289 declares them.
prompt_cache.last_miss_cause reports those; this mod only judges time.hooks/core.ts). Unknown models are priced as Opus 5.5./compact: a plugin's own $.session.compact skips its own hooks, so the mod runs /compact through $.command.run and answers (or filters) the compaction in its session.compact hook. Another plugin answering session.compact first would take the Jev compaction's place; the mod then reports that the compaction did not reach it and spends nothing.$.http.fetch has none): a slow request is given up on, not cancelled.claude plugin validate . # static analysis of the hooks module
claude plugin test # tests/, no session or network (Jev is stubbed)
tsc -p . # after one load, which writes .claude-plugin/types/
hooks/core.ts and hooks/lean.ts are copied verbatim from pi-cache-guard; change them there. hooks/jev.ts (the HTTP translation) and hooks/units.ts (Claude Code's transcript in and out of lean.ts) are pure; every $ call is in hooks/register.ts, as the host requires.
hooks/register.ts 1003 lines1// cache-guard: keeps Claude Code's prompt cache warm while you are away, and asks before a prompt
2// that would re-cache a large conversation.
3//
4// The clock: every main-loop model request (turn.step) reads or writes the cache, and the entry
5// lives for its TTL from that request's start. The TTL is the tier the session's own cache writes
6// use, read off the transcript (1h on a subscription within plan usage, 5m otherwise).
7//
8// Keep-warm: at 90% of the TTL with no request since, `$.model.fork` re-sends the main thread's
9// last request (same model, system prompt, tools and messages) with one short question after it,
10// tools denied and its own tail never cached, so the API serves the prefix from the cache and
11// restarts its clock. Pi's rule decides each refresh (expected saving at least $0.05, with a 15%
12// chance you come back before it lapses while idle), and refreshing stops 30 minutes (5m tier) or
13// 2 hours (1h tier) after the last real request. A refresh that misses stops it.
14//
15// Warning: a prompt typed while idle onto an expired cache, when the rewrite would cost at least
16// warn.minCost at API prices, asks first; keeping it puts the text back in the prompt box.
17//
18// Lean context (with Jev, TypeSafe's judgment model, over its HTTP API): large tool output is
19// trimmed to the blocks the agent needs as its row is stored (`session.append`), so the model
20// never reads the rest and the prompt cache is never disturbed; and `session.compact` either
21// answers a summary written in code from Jev's verbatim/summarize/drop choices (the cold-cache
22// menu, /cache-guard compact) or filters what Claude Code's own summarizer reads (/compact and
23// automatic compaction). Without Jev none of that runs.
24//
25// The status line shows the cache itself (Claude Code's prompt_cache input), so this mod draws none.
26//
27// The host reads on(...) and $.noun.method(...) from source, so calls are spelled in full and
28// helpers that take $ are top-level functions in this file (jev.ts and units.ts are pure).
29import type { EngineInterface, On, PluginOptions, SessionCompactResult, SessionMessage } from 'claude-code'
30
31import {
32 DEFAULT_SETTINGS,
33 NAME,
34 ONE_HOUR,
35 FIVE_MINUTES,
36 HERDR_SOURCE,
37 HERDR_TOKEN,
38 type Settings,
39 claudePrice,
40 decideWarm,
41 describeMiss,
42 formatClock,
43 formatCost,
44 formatDuration,
45 formatTokens,
46 choiceCosts,
47 compactionFocus,
48 herdrCacheValue,
49 mergeSettings,
50 missCost,
51 warmDeadline,
52 warmDelayMs,
53 worthWarning,
54} from './core'
55import { ENDPOINT, type JevState, type JevTarget, PROBE, describeFailure, label, readReply, requestBody, resolveJev } from './jev'
56import {
57 type Answer,
58 JEV_KEY_URL,
59 JEV_PITCH,
60 type Keep,
61 type Question,
62 type Unit,
63 batches,
64 blocksFor,
65 codeSummary,
66 keepAnswers,
67 keepCounts,
68 keepQuestions,
69 keepState,
70 trimQuestions,
71 trimState,
72 trimVerdict,
73 verbatimSection,
74} from './lean'
75import { settingsFiles } from './settings'
76import { parseTail, transcriptPath } from './transcript'
77import { extractUnits, fileOps, filterMessages, lastUserMessages, persistedPath, resultText, trimFloor, withResultText } from './units'
78
79const COMMAND = NAME
80const KEEP = 'Keep the prompt'
81const FRESH = 'New conversation'
82const COMPACT = 'Compact first'
83const SEND = 'Send anyway'
84const SUMMARY_DEFAULT = 'Default summary'
85const SUMMARY_FOCUS = 'Focus on this prompt'
86/** The compaction choices with Jev: its own, or Claude Code's summary (which Jev filters first). */
87const COMPACT_JEV = 'Compact with Jev'
88const SUMMARY_JEV_DEFAULT = 'Compact with a summary'
89const SUMMARY_JEV_FOCUS = 'Compact with a summary focused on this prompt'
90/** Under the cold-cache question while Jev is not set up (and not turned off). */
91export const JEV_TIP = 'Tip: /cache-guard jev sets up Jev, which compacts in about a second for ~$0 (or turns this tip off).'
92/** The /cache-guard jev and /cache-guard compact choices. */
93const JEV_DONE = 'Done'
94const JEV_ON = 'Turn Jev on'
95const JEV_LEAVE_OFF = 'Leave it off'
96const JEV_OFF = 'Turn Jev off'
97const JEV_OFF_TIPS = 'Turn Jev off (no more tips)'
98const JEV_SHOW_SETUP = 'Show the setup'
99const COMPACT_SUMMARY = "Compact with Claude Code's summary"
100const JEV_SETUP = 'Set up Jev'
101/** How many tool calls' inputs are remembered for their results (the rest trim without arguments). */
102const CALLS_REMEMBERED = 200
103/** How much of a transcript's end to read: enough for the last few responses. */
104const TAIL_BYTES = 400_000
105const TAIL_SCRIPT = 'f=$1; [ -f "$f" ] || f=$(ls "$2"/*/"$3" 2>/dev/null | head -n 1); [ -n "$f" ] && tail -c "$4" "$f"'
106
107interface Clock {
108 /** Start of the last request that read or wrote the cache (a real one or a refresh). */
109 lastAt: number
110 /** Start of the last real request. */
111 lastRealAt: number
112 /** The last request's prompt: what a refresh should read from the cache. */
113 promptTokens: number
114 /** Prompt plus reply: what the next real request re-sends. */
115 tokens: number
116 model: string
117}
118
119interface State {
120 settings: Settings
121 sessionOn: boolean
122 interactive: boolean
123 clock?: Clock
124 /** The transcript file, from the settings-hook SessionStart input. */
125 transcript?: string
126 ttl: { ms: number; source: string }
127 timer?: { cancel: () => void }
128 stepsInFlight: number
129 busy: boolean
130 warming: boolean
131 warms: number
132 /** Why no refresh is scheduled, for /cache-guard. */
133 stopped: string
134 /** Fires when the cache expires, to tell herdr. */
135 expiry?: { cancel: () => void }
136 /** The `cache` token last reported to herdr; null before the first report. */
137 herdrLast: string | undefined | null
138 /** The plugin's userConfig values (`typesafe_api_key`). */
139 options: PluginOptions
140 lean: Lean
141}
142
143/** The Jev parts: which Jev, what is armed, what was trimmed. */
144interface Lean {
145 jev: JevState
146 /** The settings the Jev state was resolved from, to resolve again when they change. */
147 jevKey: string
148 /** The next compaction is Jev's, written in code; strict: nothing is spent if Jev fails. */
149 armed?: { goal?: string }
150 /** Why the last Jev compaction did not run, if it did not. */
151 failure?: string
152 /** The last compaction this plugin's hook saw. */
153 last?: { mode: 'jev' | 'filtered' | 'plain'; counts?: Record<Keep, number>; latencyMs?: number }
154 /** How many compactions this plugin's hook has seen. */
155 compactions: number
156 /** Characters trimmed from tool output this session. */
157 saved: number
158 /** Tool+input keys trimmed this turn: asked again, the output comes whole. */
159 trimmedThisTurn: Set<string>
160 /** The main loop's tool calls in flight, by id: the name and input their result row is judged with. */
161 calls: Map<string, { tool: string; input: Record<string, unknown> }>
162 /** The current turn's request and the assistant's latest text: Jev's `intent` for a trim. */
163 turnText: { user: string; assistant: string }
164 /** A strict (armed) compaction is being judged: a failure must skip, not summarize. */
165 strictInFlight?: boolean
166}
167
168export function register(on: On, options: PluginOptions = {}): void {
169 const s: State = {
170 settings: DEFAULT_SETTINGS,
171 sessionOn: true,
172 interactive: false,
173 ttl: { ms: FIVE_MINUTES, source: 'default' },
174 stepsInFlight: 0,
175 busy: false,
176 warming: false,
177 warms: 0,
178 stopped: 'waiting for the first response',
179 herdrLast: null,
180 options,
181 lean: {
182 jev: { kind: 'missing', reason: 'not checked yet' },
183 jevKey: '',
184 compactions: 0,
185 saved: 0,
186 trimmedThisTurn: new Set(),
187 calls: new Map(),
188 turnText: { user: '', assistant: '' },
189 },
190 }
191
192 on('session.start', async ($, e, next) => {
193 const result = await next(e)
194 s.interactive = e.isInteractive
195 s.settings = await loadSettings($)
196 await refreshJev($, s)
197 await $.command.register({
198 name: COMMAND,
199 description: 'cache-guard: prompt cache status, warm (refresh now), on/off (this session), compact [focus] (with Jev), jev (set up or check Jev)',
200 argumentHint: '[status|warm|on|off|compact [focus]|jev]',
201 immediate: true,
202 })
203 // A resumed session: its last response and TTL come from the transcript.
204 await readTranscript($, s, true)
205 await syncHerdr($, s)
206 return result
207 })
208
209 on('session.end', async ($, e, next) => {
210 s.expiry?.cancel()
211 await reportHerdr($, s, undefined)
212 return next(e)
213 })
214
215 // The settings-hook SessionStart: its transcript_path, and on a resume or fork how long ago the
216 // last response was and how big it was. A forked session's transcript is only written with its
217 // first message, so this is the one record of the conversation's cache until then.
218 on('classic.SessionStart', async ($, e, next) => {
219 const result = await next(e)
220 s.transcript = e.transcript_path
221 const seconds = e.seconds_since_last_response
222 if (seconds !== undefined && e.context_tokens !== undefined && e.context_tokens > 0) {
223 const at = (await $.clock.now()) - seconds * 1000
224 if (!s.clock || s.clock.lastAt < at) {
225 s.clock = { lastAt: at, lastRealAt: at, promptTokens: e.context_tokens, tokens: e.context_tokens, model: e.model ?? (await $.session.model()) }
226 }
227 }
228 await syncHerdr($, s)
229 return result
230 })
231
232 on('turn.start', async ($, e, next) => {
233 s.busy = true
234 s.lean.turnText = { user: e.text, assistant: '' }
235 s.lean.trimmedThisTurn.clear()
236 s.lean.calls.clear()
237 // Settings edited since (a key added, trimming turned off) apply from the next turn.
238 s.settings = await loadSettings($)
239 return next(e)
240 })
241
242 on('turn.complete', async ($, e, next) => {
243 const result = await next(e)
244 if (e.agentId === undefined) {
245 s.busy = false
246 await readTranscript($, s, false)
247 await schedule($, s)
248 }
249 return result
250 })
251
252 on('turn.step', async function* ($, e, next) {
253 if (e.agentId !== undefined) return yield* next(e)
254 const startedAt = await $.clock.now()
255 s.stepsInFlight++
256 s.timer?.cancel()
257 s.timer = undefined
258 try {
259 const result = yield* next(e)
260 const usage = result.usage
261 const prompt = usage ? usage.input_tokens + usage.cache_read_input_tokens + usage.cache_creation_input_tokens : 0
262 if (usage && prompt > 0) {
263 s.clock = { lastAt: startedAt, lastRealAt: startedAt, promptTokens: prompt, tokens: prompt + usage.output_tokens, model: usage.model }
264 }
265 if (result.answer.trim()) s.lean.turnText.assistant = result.answer
266 return result
267 } finally {
268 s.stepsInFlight--
269 // A long tool run between steps can outlast a 5-minute TTL: keep warming then too.
270 if (s.stepsInFlight === 0) await schedule($, s)
271 }
272 })
273
274 // Every main-loop tool call: its name and input, for the trim of its result row.
275 on('tool.call', async ($, e, next) => {
276 if (e.agentId === undefined && typeof e.tool_use_id === 'string') {
277 const { tool, tool_use_id, agentId: _agentId, consent: _consent, ...input } = e as Record<string, unknown> & { tool: string; tool_use_id: string }
278 if (s.lean.calls.size >= CALLS_REMEMBERED) s.lean.calls.delete(s.lean.calls.keys().next().value as string)
279 s.lean.calls.set(tool_use_id, { tool, input })
280 }
281 return next(e)
282 }).catch(($, e, next) => (next.called ? undefined : next(e)))
283
284 // A tool result about to be stored: trimmed to the blocks the agent needs, before the model reads
285 // it. Main loop only: a subagent's transcript is its own and is dropped when it finishes.
286 on('session.append', { door: 'tool-result' }, async ($, e, next) => {
287 if (e.agentId !== undefined || !s.settings.enabled || !s.settings.trim.enabled) return next(e)
288 const index = e.message.content.findIndex((block) => block.type === 'tool_result')
289 const block = e.message.content[index]
290 if (!block) return next(e)
291 const id = String(block.tool_use_id ?? '')
292 const call = s.lean.calls.get(id)
293 const tool = call?.tool ?? (e.origin.kind === 'tool' ? e.origin.tool : '')
294 const floor = trimFloor(tool, s.settings.trim)
295 if (floor === undefined || block.is_error === true) return next(e)
296 // Claude Code put a large result in a file and left a preview: trim the whole of it instead.
297 const shown = resultText(block.content)
298 const persisted = persistedPath(shown)
299 const text = persisted ? await readPersisted($, persisted) : shown
300 if (text === undefined || text.length <= floor) return next(e)
301 // The agent asked again for something already trimmed this turn: give it everything.
302 const key = call ? `${tool}:${JSON.stringify(call.input)}` : undefined
303 if (key !== undefined && s.lean.trimmedThisTurn.has(key)) return next(e)
304 const jev = await currentJev($, s)
305 if (jev.kind !== 'ready') return next(e)
306
307 const { lines, blocks } = blocksFor(text, s.settings.trim)
308 const state = trimState({ user_request: s.lean.turnText.user, agent_said: s.lean.turnText.assistant, tool, arguments: JSON.stringify(call?.input ?? {}) }, blocks)
309 const outcome = await askJev($, jev.target, s.settings.jev.timeoutMs, state, trimQuestions(blocks))
310 if (!outcome.ok) {
311 $.ui.log(`${tool} output not trimmed: Jev ${outcome.reason}`, { to: 'debug' })
312 return next(e)
313 }
314 const fullPath = persisted ?? (await outputPath($, s, id))
315 const verdict = trimVerdict(lines, blocks, outcome.answers, s.settings.trim, fullPath)
316 if (!verdict.trim) {
317 $.ui.log(`${tool} output kept whole (${verdict.totalLines} lines; needs all: ${verdict.needsAll.toFixed(2)}, would keep ${verdict.keptLines}; Jev ${outcome.latencyMs} ms)`, { to: 'debug' })
318 return next(e)
319 }
320 try {
321 if (!persisted) await $.fs.write(fullPath, text)
322 } catch (error) {
323 $.ui.log(`${tool} output not trimmed: could not save it to ${fullPath} (${error instanceof Error ? error.message : String(error)})`, { to: 'debug' })
324 return next(e)
325 }
326 if (key !== undefined) s.lean.trimmedThisTurn.add(key)
327 s.lean.saved += text.length - verdict.text.length
328 $.ui.log(`trimmed ${tool} output to ${verdict.keptLines} of ${verdict.totalLines} lines (Jev, ${outcome.latencyMs} ms); full output: ${fullPath}`)
329 const content = e.message.content.map((b, i) => (i === index ? { ...b, content: withResultText(b.content, verdict.text) } : b))
330 return next({ ...e, message: { ...e.message, content } })
331 }).catch(($, e, next) => (next.called ? undefined : next(e)))
332
333 // Compaction: Jev's own when armed (strict: a Jev failure skips it, so nothing is spent), else
334 // Claude Code's summarizer over what Jev did not drop, plus the verbatim items.
335 on('session.compact', async ($, e, next) => {
336 if (e.agentId !== undefined || e.trigger === 'precompute') return next(e)
337 const request = s.lean.armed
338 s.lean.armed = undefined
339 s.lean.failure = undefined
340 s.lean.compactions++
341 const jevOnly = request !== undefined
342 s.lean.strictInFlight = jevOnly
343 s.lean.last = { mode: 'plain' }
344 // A Jev problem: an armed compaction is skipped (strict), any other runs as it would have.
345 const fail = (reason: string): SessionCompactResult | Promise<SessionCompactResult> => {
346 s.lean.failure = reason
347 s.lean.strictInFlight = false
348 return jevOnly ? { skip: `Jev compaction: ${reason}` } : next(e)
349 }
350 if (!s.settings.enabled) return fail('cache-guard is off')
351 if (!jevOnly && !s.settings.compact.filter) return next(e)
352 const jev = await currentJev($, s)
353 if (jev.kind !== 'ready') return fail(jev.kind === 'off' ? 'Jev is off' : `Jev is not set up (${jev.reason})`)
354 const { units, previousSummary } = extractUnits(e.messages)
355 if (!units.length) return fail('nothing for Jev to judge')
356 const goal = request?.goal?.trim() || e.instructions?.trim() || lastUserMessages(e.messages, 2)
357 const judged = await judgeUnits($, s, jev.target, units, goal)
358 if (!judged.ok) return fail(judged.reason)
359 const { keep } = judged
360 const counts = keepCounts(keep)
361
362 if (jevOnly) {
363 const summary = codeSummary({ units, keep, previousSummary, fileOps: fileOps(e.messages), instructions: request?.goal ?? e.instructions })
364 s.lean.last = { mode: 'jev', counts, latencyMs: judged.latencyMs }
365 s.lean.strictInFlight = false
366 return { messages: [{ role: 'user', text: summary, toolUses: [] }] }
367 }
368
369 let filtered: SessionMessage[]
370 try {
371 filtered = filterMessages(e.messages, units, keep) as SessionMessage[]
372 } catch (error) {
373 return fail(`filtering failed (${error instanceof Error ? error.message : String(error)})`)
374 }
375 s.lean.last = { mode: 'filtered', counts, latencyMs: judged.latencyMs }
376 const result = await next({ ...e, messages: filtered })
377 if (result.skip !== undefined) return result
378 const verbatim = verbatimSection(units, keep)
379 if (!verbatim) return result
380 // One more user message after the summary (the summary's own row is the engine's).
381 return { ...result, messages: [...result.messages, { role: 'user', text: verbatim, toolUses: [] }] }
382 }).catch(($, e, next) => {
383 if (next.called) return undefined
384 if (!s.lean.strictInFlight) return next(e)
385 // Armed and failed before answering: strict, so nothing is spent.
386 s.lean.strictInFlight = false
387 s.lean.failure = `Jev compaction failed (${next.error.message})`
388 return { skip: s.lean.failure }
389 })
390
391 on('prompt.submit', async ($, e, next) => {
392 if (!s.sessionOn || e.origin.kind !== 'composer' || e.turnId !== undefined) return next(e)
393 const text = e.text.trim()
394 if (!text || text.startsWith('/')) return next(e)
395 const miss = await assess($, s)
396 if (!miss) return next(e)
397 const jev = await currentJev($, s)
398 const ready = jev.kind === 'ready'
399 // Keep first, so a reflexive Enter (or Esc) spends nothing; then cheapest to dearest. The dialog
400 // takes four options, so with Jev the two compactions are the next question's.
401 const compactCost = `${s.settings.compact.filter && ready ? 'up to ' : ''}~${formatCost(miss.costs.compact)}`
402 const labels = {
403 keep: KEEP,
404 fresh: `${FRESH} (~$0)`,
405 compact: ready ? `${COMPACT} (~$0 with Jev)` : `${COMPACT} (~${formatCost(miss.costs.compact)})`,
406 send: `${SEND} (~${formatCost(miss.costs.send)})`,
407 }
408 const tip = jev.kind === 'missing' ? `\n${JEV_TIP}` : ''
409 let answer: string | undefined
410 try {
411 answer = await $.ui.ask(`Prompt cache miss. ${miss.line} What now?${tip}`, { header: 'Cache', options: [labels.keep, labels.fresh, labels.compact, labels.send] })
412 } catch {
413 answer = undefined // dismissed: keep it
414 }
415 if (answer === labels.send) return next(e)
416 if (answer === labels.fresh) {
417 $.clock.after(0, () => {
418 void startFresh($, s, e.text)
419 })
420 return { drop: 'Starting a new conversation with your prompt.' }
421 }
422 if (answer === labels.compact) {
423 const jevLabel = `${COMPACT_JEV} (~1s, ~$0)`
424 const plainLabel = ready ? `${SUMMARY_JEV_DEFAULT} (${compactCost})` : SUMMARY_DEFAULT
425 const focusLabel = ready ? `${SUMMARY_JEV_FOCUS} (${compactCost})` : SUMMARY_FOCUS
426 const choices = ready ? [jevLabel, plainLabel, focusLabel] : [plainLabel, focusLabel]
427 const question = ready
428 ? 'Compact how? Jev judges the history against your prompt and writes the summary in code, in about a second. (Type your own guidance for a summary under Other.)'
429 : 'What should the summary keep? (Type your own guidance under Other.)'
430 let how: string | undefined
431 try {
432 how = await $.ui.ask(question, { header: 'Compact', options: choices })
433 } catch {
434 how = undefined
435 }
436 if (how === jevLabel) {
437 $.clock.after(0, () => {
438 void compactWithJevThenSend($, s, e.text)
439 })
440 return { drop: 'Compacting with Jev, then sending your prompt.' }
441 }
442 if (how !== undefined) {
443 const instructions = how === plainLabel ? undefined : how === focusLabel ? compactionFocus(e.text) : how
444 $.clock.after(0, () => {
445 void compactThenSend($, s, e.text, instructions)
446 })
447 return { drop: 'Compacting, then sending your prompt.' }
448 }
449 }
450 await $.prompt.fill({ text: e.text })
451 return { drop: `Kept in the prompt box. ${miss.line} /cache-guard off stops asking in this session.` }
452 })
453
454 on('command.run', { command: COMMAND }, async ($, e) => {
455 const arg = e.args.trim()
456 const word = arg.split(/\s+/u)[0] ?? ''
457 if (word === 'jev') return { text: await jevCommand($, s) }
458 if (word === 'compact') return { text: await compactCommand($, s, arg.slice(word.length).trim()) }
459 if (arg === 'on' || arg === 'off') {
460 s.sessionOn = arg === 'on'
461 if (s.sessionOn) await schedule($, s)
462 else {
463 cancel(s, 'turned off for this session')
464 await syncHerdr($, s)
465 }
466 return { text: `cache-guard ${arg} for this session` }
467 }
468 if (arg === 'warm') {
469 // A refresh now, whatever the schedule and the expected saving say (to bridge a break, or to check one works).
470 if (!s.clock) return { text: 'Nothing to keep warm yet.' }
471 await refresh($, s, true)
472 return { text: await status($, s) }
473 }
474 s.settings = await loadSettings($)
475 return { text: await status($, s) }
476 })
477}
478
479/** The shared settings files merged over the defaults; a missing file is skipped. */
480async function loadSettings($: EngineInterface): Promise<Settings> {
481 const home = (await $.env.get('HOME')) ?? ''
482 const xdg = await $.env.get('XDG_CONFIG_HOME')
483 const root = await $.session.root()
484 const texts: (string | undefined)[] = []
485 for (const file of settingsFiles(home, xdg, root)) {
486 texts.push(await $.fs.read(file).catch(() => undefined))
487 }
488 return mergeSettings(DEFAULT_SETTINGS, texts)
489}
490
491/** `~/.claude/cache-guard.json`: the Claude Code user file, which `/cache-guard jev` writes. */
492async function userSettingsFile($: EngineInterface): Promise<string> {
493 const home = (await $.env.get('HOME')) ?? ''
494 return `${home}/.claude/${NAME}.json`
495}
496
497/**
498 * Merges `patch` into the user settings file (objects merge, other values replace). Refuses, with
499 * the reason, when the file exists but is not a JSON object, rather than overwrite it.
500 */
501async function saveUserSettings($: EngineInterface, patch: Record<string, unknown>): Promise<string | undefined> {
502 const file = await userSettingsFile($)
503 let current: Record<string, unknown> = {}
504 const text = await $.fs.read(file).catch(() => undefined)
505 if (text !== undefined && text.trim()) {
506 let value: unknown
507 try {
508 value = JSON.parse(text)
509 } catch {
510 return `${file} is not valid JSON; fix it by hand`
511 }
512 if (typeof value !== 'object' || value === null || Array.isArray(value)) return `${file} is not a JSON object; fix it by hand`
513 current = value as Record<string, unknown>
514 }
515 try {
516 await $.fs.write(file, `${JSON.stringify(mergeObjects(current, patch), null, 2)}\n`)
517 } catch (error) {
518 return `could not write ${file} (${error instanceof Error ? error.message : String(error)})`
519 }
520 return undefined
521}
522
523function mergeObjects(base: Record<string, unknown>, over: Record<string, unknown>): Record<string, unknown> {
524 const out: Record<string, unknown> = { ...base }
525 for (const [key, value] of Object.entries(over)) {
526 const current = out[key]
527 out[key] = isRecord(current) && isRecord(value) ? mergeObjects(current, value) : value
528 }
529 return out
530}
531
532function isRecord(value: unknown): value is Record<string, unknown> {
533 return typeof value === 'object' && value !== null && !Array.isArray(value)
534}
535
536// ---------------------------------------------------------------------------------------------
537// Jev
538
539/** Resolves which Jev to use from the settings and the key found; the state is kept on `s`. */
540async function refreshJev($: EngineInterface, s: State): Promise<JevState> {
541 s.lean.jevKey = JSON.stringify([s.settings.enabled, s.settings.jev])
542 s.lean.jev = resolveJev(s.settings, s.options.typesafe_api_key, await $.env.get('TYPESAFE_API_KEY'))
543 return s.lean.jev
544}
545
546/** Jev as last resolved, resolved again when the settings changed since. */
547async function currentJev($: EngineInterface, s: State): Promise<JevState> {
548 if (s.lean.jevKey !== JSON.stringify([s.settings.enabled, s.settings.jev])) await refreshJev($, s)
549 return s.lean.jev
550}
551
552type JevOutcome =
553 | { ok: true; answers: Record<string, Answer>; latencyMs: number; inputTokens?: number }
554 | { ok: false; reason: string }
555
556/** One Jev request over TypeSafe's API. Never throws: every failure is `{ ok: false, reason }`. */
557async function askJev($: EngineInterface, target: JevTarget, timeoutMs: number, state: Record<string, unknown>, questions: Record<string, Question>): Promise<JevOutcome> {
558 const started = await $.clock.now()
559 let timer: { cancel: () => void } | undefined
560 const timeout = new Promise<string>((resolve) => {
561 timer = $.clock.after(timeoutMs, () => resolve('timed out'))
562 })
563 const request = $.http
564 .fetch(ENDPOINT, {
565 method: 'POST',
566 headers: { authorization: `Bearer ${target.apiKey}`, 'content-type': 'application/json' },
567 body: requestBody(target.model, state, questions),
568 })
569 .then(
570 (response) => response,
571 (error: unknown) => describeFailure(undefined, error instanceof Error ? error.message : String(error)),
572 )
573 const response = await Promise.race([request, timeout])
574 timer?.cancel()
575 if (typeof response === 'string') return { ok: false, reason: response }
576 if (!response.ok) return { ok: false, reason: describeFailure(response.status) }
577 const reply = readReply(response.text)
578 if (!reply) return { ok: false, reason: 'unreadable response' }
579 return { ok: true, answers: reply.answers, latencyMs: (await $.clock.now()) - started, ...(reply.inputTokens !== undefined ? { inputTokens: reply.inputTokens } : {}) }
580}
581
582/** Jev's verdict on every unit, in batches, `compact.concurrency` requests at a time. */
583async function judgeUnits($: EngineInterface, s: State, target: JevTarget, units: Unit[], goal: string): Promise<{ ok: true; keep: Map<string, Keep>; latencyMs: number } | { ok: false; reason: string }> {
584 const started = await $.clock.now()
585 const keep = new Map<string, Keep>()
586 const queue = batches(units)
587 let reason: string | undefined
588 const worker = async () => {
589 for (let batch = queue.shift(); batch && !reason; batch = queue.shift()) {
590 const outcome = await askJev($, target, s.settings.compact.timeoutMs, keepState(goal, batch), keepQuestions(batch))
591 if (!outcome.ok) {
592 reason = outcome.reason
593 return
594 }
595 keepAnswers(batch, outcome.answers, keep)
596 }
597 }
598 await Promise.all(Array.from({ length: Math.max(1, Math.floor(s.settings.compact.concurrency)) }, worker))
599 if (reason) return { ok: false, reason: `Jev failed (${reason})` }
600 return { ok: true, keep, latencyMs: (await $.clock.now()) - started }
601}
602
603/** Where a trimmed tool result's full output is saved. */
604async function outputPath($: EngineInterface, s: State, toolUseId: string): Promise<string> {
605 const home = (await $.env.get('HOME')) ?? ''
606 const configDir = (await $.env.get('CLAUDE_CONFIG_DIR')) || `${home}/.claude`
607 const session = (await $.session.id().catch(() => 'session')) || 'session'
608 const safe = (text: string) => text.replace(/[^\w.-]/gu, '_')
609 return `${configDir}/${NAME}/tool-output/${safe(session)}/${safe(toolUseId)}.txt`
610}
611
612/** The Jev line of /cache-guard status. */
613function jevLine(s: State): string {
614 const jev = s.lean.jev
615 if (jev.kind === 'off') return 'Jev: off (/cache-guard jev turns it on).'
616 if (jev.kind === 'missing') return `Jev: not set up (${jev.reason}); /cache-guard jev.`
617 const saved = s.lean.saved > 0 ? ` (−${Math.round(s.lean.saved / 4_000)}k tokens so far)` : ''
618 const trim = s.settings.trim.enabled ? `trimming on${saved}` : 'trimming off'
619 const compaction = `Jev compaction from the cold-cache menu and /cache-guard compact${s.settings.compact.filter ? '; it filters /compact too' : ''}`
620 return `Jev: ${label(jev.target)} (key from ${jev.target.keySource}); ${trim}; ${compaction}.`
621}
622
623/** How to set Jev up, for /cache-guard jev and the tip. */
624function jevSetupText(): string {
625 return [
626 JEV_PITCH,
627 `It needs a TypeSafe API key from ${JEV_KEY_URL}. Either set the plugin option (kept in secure storage, not settings.json):`,
628 ` /plugin configure ${NAME}@inline (${NAME}@<marketplace> when installed from one), or in a shell`,
629 ` echo '{"typesafe_api_key": "<key>"}' | claude plugin configure ${NAME}@inline --values-stdin`,
630 'then restart Claude Code; or export TYPESAFE_API_KEY before starting it. /cache-guard jev checks it.',
631 ].join('\n')
632}
633
634/** `/cache-guard jev`: whether Jev is set up and answers; or how to set it up; on or off. */
635async function jevCommand($: EngineInterface, s: State): Promise<string> {
636 s.settings = await loadSettings($)
637 if (!s.settings.enabled) return 'cache-guard is off in its settings ("enabled": false), Jev included.'
638 const ask = async (question: string, options: string[]): Promise<string | undefined> => {
639 try {
640 return await $.ui.ask(question, { header: 'Jev', options })
641 } catch {
642 return undefined
643 }
644 }
645 const turnOff = async (): Promise<string> => {
646 const problem = await saveUserSettings($, { jev: { enabled: false } })
647 if (problem) return `Could not save the setting: ${problem}`
648 s.settings = await loadSettings($)
649 await refreshJev($, s)
650 return 'Jev is off: no trimming, no Jev compaction, no tips. /cache-guard jev turns it back on.'
651 }
652 if (!s.settings.jev.enabled) {
653 const pick = await ask(`Jev is off: no trimming, no Jev compaction, no tips. Turn it on?\n${JEV_PITCH}`, [JEV_ON, JEV_LEAVE_OFF])
654 if (pick !== JEV_ON) return 'Jev stays off.'
655 const problem = await saveUserSettings($, { jev: { enabled: true } })
656 if (problem) return `Could not save the setting: ${problem}`
657 s.settings = await loadSettings($)
658 }
659 const state = await refreshJev($, s)
660 if (state.kind === 'ready') {
661 const answer = await askJev($, state.target, 10_000, PROBE.state, PROBE.questions)
662 const head = answer.ok
663 ? `Jev: ${label(state.target)} (key from ${state.target.keySource}), answered in ${answer.latencyMs} ms.`
664 : `Jev: ${label(state.target)} (key from ${state.target.keySource}) did not answer (${answer.reason}).`
665 const pick = await ask(`${head} It trims large tool output and compacts in about a second (the cold-cache menu, /cache-guard compact).`, [JEV_DONE, JEV_OFF, JEV_SHOW_SETUP])
666 if (pick === JEV_OFF) return turnOff()
667 if (pick === JEV_SHOW_SETUP) return `${head}\n${jevSetupText()}`
668 return head
669 }
670 if (state.kind === 'off') return 'Jev is off.'
671 const text = `Jev is not set up: ${state.reason}.\n${jevSetupText()}`
672 const pick = await ask(`${text}\nWhat now?`, [JEV_DONE, JEV_OFF_TIPS])
673 if (pick === JEV_OFF_TIPS) return turnOff()
674 return text
675}
676
677/** `/cache-guard compact [focus]`: Jev's compaction, written in code; nothing is spent if Jev fails. */
678async function compactCommand($: EngineInterface, s: State, focus: string): Promise<string> {
679 const jev = await currentJev($, s)
680 if (jev.kind !== 'ready') {
681 const why = jev.kind === 'off' ? 'Jev is off' : `Jev is not set up (${jev.reason})`
682 let pick: string | undefined
683 try {
684 pick = await $.ui.ask(`${why}. Compact with Claude Code's summary instead?`, { header: 'Compact', options: [COMPACT_SUMMARY, JEV_SETUP] })
685 } catch {
686 pick = undefined
687 }
688 if (pick === JEV_SETUP) return jevCommand($, s)
689 if (pick !== COMPACT_SUMMARY) return `${why}; nothing compacted.`
690 $.clock.after(0, () => {
691 void runCompaction($, s, focus || undefined).then((outcome) => {
692 $.ui.log(outcome.ok ? 'compacted' : `compaction did not run (${outcome.reason})`)
693 })
694 })
695 return 'Compacting with a summary.'
696 }
697 $.clock.after(0, () => {
698 void runJevCompaction($, s, focus || undefined).then((outcome) => {
699 $.ui.log(outcome.ok ? `compacted with Jev in ${(outcome.latencyMs / 1000).toFixed(1)} s (${describeCounts(outcome.counts)})` : `compaction with Jev did not run: ${outcome.reason}`)
700 })
701 })
702 return 'Compacting with Jev.'
703}
704
705function describeCounts(counts: Record<Keep, number> | undefined): string {
706 if (!counts) return 'no counts'
707 return `${counts.verbatim} kept verbatim, ${counts.summarize} noted, ${counts.drop} dropped`
708}
709
710type CompactionOutcome = { ok: true; latencyMs: number; counts?: Record<Keep, number> } | { ok: false; reason: string }
711
712/**
713 * A Jev compaction of the main conversation: armed, then `/compact` run as the person would, which
714 * reaches this plugin's own `session.compact` hook (a plugin's `$.session.compact` skips its own
715 * hooks). Strict: if the hook skipped, or never ran, nothing was spent.
716 */
717async function runJevCompaction($: EngineInterface, s: State, goal: string | undefined): Promise<CompactionOutcome> {
718 s.lean.armed = { goal }
719 s.lean.failure = undefined
720 const started = await $.clock.now()
721 try {
722 await $.command.run({ command: 'compact' })
723 } catch (error) {
724 s.lean.armed = undefined
725 return { ok: false, reason: s.lean.failure ?? (error instanceof Error ? error.message : String(error)) }
726 }
727 if (s.lean.armed) {
728 s.lean.armed = undefined
729 return { ok: false, reason: 'the compaction did not reach cache-guard (another plugin answered session.compact first?)' }
730 }
731 if (s.lean.failure) return { ok: false, reason: s.lean.failure }
732 if (s.lean.last?.mode !== 'jev') return { ok: false, reason: 'the compaction was not Jev\'s' }
733 s.clock = undefined
734 return { ok: true, latencyMs: (await $.clock.now()) - started, counts: s.lean.last.counts }
735}
736
737/**
738 * Claude Code's own compaction (with the guidance), run as `/compact` so that this plugin's hook
739 * filters it with Jev. It counted as done when the transcript got shorter.
740 */
741async function runCompaction($: EngineInterface, s: State, instructions: string | undefined): Promise<CompactionOutcome> {
742 s.lean.armed = undefined
743 const before = await $.session.messages().then((m) => m.length, () => undefined)
744 const seen = s.lean.compactions
745 const started = await $.clock.now()
746 try {
747 await $.command.run({ command: 'compact', ...(instructions ? { args: instructions } : {}) })
748 } catch (error) {
749 return { ok: false, reason: error instanceof Error ? error.message : String(error) }
750 }
751 const after = await $.session.messages().then((m) => m.length, () => undefined)
752 if (before !== undefined && after !== undefined && after >= before) {
753 return { ok: false, reason: s.lean.compactions > seen ? 'the conversation is unchanged (skipped, or too small)' : 'nothing compacted' }
754 }
755 s.clock = undefined
756 return { ok: true, latencyMs: (await $.clock.now()) - started, counts: s.lean.last?.counts }
757}
758
759/**
760 * Reads the transcript's tail for the TTL the session's cache writes use and, when `seed` (a new or
761 * resumed session) or nothing was tracked yet, the last response as the clock.
762 */
763async function readTranscript($: EngineInterface, s: State, seed: boolean): Promise<void> {
764 try {
765 const home = (await $.env.get('HOME')) ?? ''
766 const configDir = (await $.env.get('CLAUDE_CONFIG_DIR')) || `${home}/.claude`
767 const id = await $.session.id()
768 // The project directory is the session root with every non-alphanumeric turned into '-', but
769 // of the path as Claude Code saw it (/private/tmp, not /tmp): try that, then look the id up.
770 const run = await $.process.run(
771 ['sh', '-c', TAIL_SCRIPT, 'cache-guard', s.transcript ?? transcriptPath(configDir, await $.session.root(), id), `${configDir}/projects`, `${id}.jsonl`, String(TAIL_BYTES)],
772 { timeoutMs: 5_000 },
773 )
774 if (run.exitCode !== 0) {
775 s.ttl = await configuredTtl($, s.ttl)
776 return
777 }
778 const tail = parseTail(run.stdout)
779 s.ttl = tail.ttlMs !== undefined ? { ms: tail.ttlMs, source: 'transcript' } : await configuredTtl($, s.ttl)
780 if (tail.compacted) {
781 s.clock = undefined
782 return
783 }
784 if ((seed || !s.clock) && tail.at !== undefined && tail.tokens !== undefined && tail.promptTokens !== undefined) {
785 s.clock = { lastAt: tail.at, lastRealAt: tail.at, promptTokens: tail.promptTokens, tokens: tail.tokens, model: tail.model ?? '' }
786 }
787 } catch {
788 // No transcript (a -p run with --no-session-persistence, a host without tail): keep what we have.
789 }
790}
791
792/** The TTL Claude Code is configured to request, when the transcript shows no write yet. */
793async function configuredTtl($: EngineInterface, current: { ms: number; source: string }): Promise<{ ms: number; source: string }> {
794 if (current.source === 'transcript') return current
795 if ((await $.env.get('FORCE_PROMPT_CACHING_5M')) === '1') return { ms: FIVE_MINUTES, source: 'FORCE_PROMPT_CACHING_5M' }
796 const env = (await $.env.get('CLAUDE_CODE_PROMPT_CACHE_TTL'))?.trim()
797 if (env === '5m' || env === '1h') return { ms: env === '1h' ? ONE_HOUR : FIVE_MINUTES, source: 'CLAUDE_CODE_PROMPT_CACHE_TTL' }
798 const usage = await $.session.usage().catch(() => undefined)
799 // Rate-limit windows are reported to subscribers only; within plan usage the main conversation gets 1h.
800 if (usage?.rateLimits.some((r) => r.kind === 'five_hour' || r.kind === 'seven_day')) return { ms: ONE_HOUR, source: 'subscription' }
801 if ((await $.env.get('ENABLE_PROMPT_CACHING_1H')) === '1') return { ms: ONE_HOUR, source: 'ENABLE_PROMPT_CACHING_1H' }
802 // Before the first response reports rate limits: no API key or cloud provider means a Claude login.
803 const keyed = [
804 await $.env.get('ANTHROPIC_API_KEY'),
805 await $.env.get('ANTHROPIC_AUTH_TOKEN'),
806 await $.env.get('CLAUDE_CODE_USE_BEDROCK'),
807 await $.env.get('CLAUDE_CODE_USE_VERTEX'),
808 await $.env.get('CLAUDE_CODE_USE_FOUNDRY'),
809 ].some((value) => !!value)
810 return keyed ? { ms: FIVE_MINUTES, source: 'API key or cloud provider' } : { ms: ONE_HOUR, source: 'Claude login' }
811}
812
813function cancel(s: State, why: string): void {
814 s.timer?.cancel()
815 s.timer = undefined
816 s.stopped = why
817}
818
819/** Arms the next refresh (and the expiry report to herdr) after the cache was used. */
820async function schedule($: EngineInterface, s: State): Promise<void> {
821 await arm($, s)
822 await syncHerdr($, s)
823}
824
825/** Arms the next refresh at 90% of the TTL after the last cache use, inside the idle limit. */
826async function arm($: EngineInterface, s: State): Promise<void> {
827 s.timer?.cancel()
828 s.timer = undefined
829 const clock = s.clock
830 if (!clock) return cancel(s, 'no cached request yet')
831 if (!s.interactive) return cancel(s, 'not an interactive session')
832 if (!s.sessionOn || !s.settings.enabled || !s.settings.warm.enabled) return cancel(s, 'keep-warm is off')
833 const delay = warmDelayMs(s.ttl.ms)
834 if (delay === undefined) return cancel(s, 'TTL too short')
835 const due = clock.lastAt + delay
836 if (due > warmDeadline(clock.lastRealAt, s.ttl.ms, s.settings)) {
837 return cancel(s, `idle limit reached (${s.settings.warm.idleMinutes[s.ttl.ms >= ONE_HOUR ? '1h' : '5m']}m after the last request)`)
838 }
839 const now = await $.clock.now()
840 s.stopped = ''
841 s.timer = $.clock.after(Math.max(0, due - now), () => {
842 void refresh($, s)
843 })
844}
845
846/** One keep-warm request, when Pi's rule says it pays; reschedules after a hit, stops otherwise. */
847async function refresh($: EngineInterface, s: State, forced = false): Promise<void> {
848 if (!forced) s.timer = undefined
849 const clock = s.clock
850 if (!clock || s.stepsInFlight > 0 || s.warming) return
851 const now = await $.clock.now()
852 // A timer that fired late (sleep, a blocked loop) would pay a full write, not a refresh.
853 if (!forced && now >= clock.lastAt + s.ttl.ms - 1_000) return cancel(s, 'missed the refresh window (the cache expired first)')
854 const price = claudePrice(clock.model)
855 const decision = decideWarm(clock.promptTokens, price, s.ttl.ms, !s.busy, s.settings)
856 if (!forced && decision.action === 'stop') {
857 return cancel(s, `expected saving ${formatCost(decision.expectedSavings)} is under ${formatCost(s.settings.warm.minSavings)}`)
858 }
859 s.warming = true
860 try {
861 const result = await $.model.fork({ prompt: s.settings.warm.prompt })
862 const usage = 'usage' in result ? result.usage : undefined
863 const read = usage?.cache_read_input_tokens ?? 0
864 if (s.clock !== clock) return // a real request went out meanwhile and took over the clock
865 const cost = usage
866 ? (read * price.cacheRead + (usage.input_tokens + usage.cache_creation_input_tokens * 1.25) * price.input + usage.output_tokens * price.input * 5) / 1e6
867 : 0
868 if (read >= 0.8 * clock.promptTokens) {
869 s.clock = { ...clock, lastAt: now }
870 s.warms++
871 $.ui.log(`kept the prompt cache warm (${forced ? 'on request, ' : ''}${formatTokens(read)} tokens read, ~${formatCost(cost)} at API prices)`)
872 await schedule($, s)
873 } else {
874 const why = result.isAnswered || result.reason === 'empty-reply'
875 ? `the refresh read only ${formatTokens(read)} of ${formatTokens(clock.promptTokens)} tokens from the cache`
876 : `the refresh failed (${result.reason})`
877 $.ui.log(`stopped keeping the prompt cache warm: ${why}`)
878 cancel(s, why)
879 }
880 } catch (error) {
881 cancel(s, `the refresh failed (${error instanceof Error ? error.message : String(error)})`)
882 } finally {
883 s.warming = false
884 }
885}
886
887/** Why the next prompt misses the cache and what that costs, when it is worth asking about. */
888async function assess($: EngineInterface, s: State): Promise<{ line: string; costs: { send: number; compact: number } } | undefined> {
889 if (!s.settings.enabled || !s.settings.warn.enabled) return undefined
890 if (!s.clock) await readTranscript($, s, true)
891 const clock = s.clock
892 if (!clock) return undefined
893 const now = await $.clock.now()
894 const left = clock.lastAt + s.ttl.ms - now
895 if (left > 0) return undefined
896 const cost = missCost(clock.tokens, claudePrice(clock.model), s.ttl.ms)
897 if (!worthWarning(clock.tokens, cost, s.settings)) return undefined
898 return { line: describeMiss({ kind: 'expired', idleMs: -left }, clock.tokens, cost), costs: choiceCosts(clock.tokens, claudePrice(clock.model), s.ttl.ms) }
899}
900
901async function status($: EngineInterface, s: State): Promise<string> {
902 const now = await $.clock.now()
903 const clock = s.clock
904 const lines: string[] = []
905 if (!clock) {
906 lines.push('No cached request in this session yet (or it was just compacted).')
907 } else {
908 const left = clock.lastAt + s.ttl.ms - now
909 lines.push(`Last request: ${clock.model}, ${formatTokens(clock.tokens)} tokens, ${formatDuration(now - clock.lastRealAt)} ago` +
910 (clock.lastAt > clock.lastRealAt ? `; kept warm ${s.warms}x, last ${formatDuration(now - clock.lastAt)} ago.` : '.'))
911 lines.push(`TTL: ${s.ttl.ms >= ONE_HOUR ? '1h' : '5m'} (${s.ttl.source}). ${left > 0 ? `Warm, ${formatClock(left)} left.` : describeMiss({ kind: 'expired', idleMs: -left }, clock.tokens, missCost(clock.tokens, claudePrice(clock.model), s.ttl.ms))}`)
912 }
913 const on = s.sessionOn && s.settings.enabled
914 lines.push(`Keep-warm: ${on && s.settings.warm.enabled ? (s.timer ? 'next refresh scheduled' : `idle (${s.stopped || 'nothing to keep'})`) : 'off'}.`)
915 lines.push(`Warning: ${on && s.settings.warn.enabled ? `on, from ${formatCost(s.settings.warn.minCost)} at API prices` : 'off'}.`)
916 await currentJev($, s)
917 lines.push(jevLine(s))
918 return lines.join('\n')
919}
920
921/**
922 * herdr's `cache` pane token: "❄ 664k" once the cache has expired with a re-cache worth a
923 * warning, nothing while it is warm (an expiry timer re-checks then) or small. Inside herdr only.
924 */
925async function syncHerdr($: EngineInterface, s: State): Promise<void> {
926 s.expiry?.cancel()
927 s.expiry = undefined
928 const clock = s.clock
929 let value: string | undefined
930 if (clock && s.sessionOn && s.stepsInFlight === 0) {
931 const now = await $.clock.now()
932 const left = clock.lastAt + s.ttl.ms - now
933 if (left > 0) {
934 s.expiry = $.clock.after(left + 1_000, () => {
935 void syncHerdr($, s)
936 })
937 } else {
938 value = herdrCacheValue({ kind: 'expired', idleMs: -left }, clock.tokens, missCost(clock.tokens, claudePrice(clock.model), s.ttl.ms), s.settings)
939 }
940 }
941 await reportHerdr($, s, value)
942}
943
944/** One `herdr pane report-metadata` call when the token changes; any failure is ignored. */
945async function reportHerdr($: EngineInterface, s: State, value: string | undefined): Promise<void> {
946 if (value === s.herdrLast) return
947 if ((await $.env.get('HERDR_ENV')) !== '1') return
948 const pane = await $.env.get('HERDR_PANE_ID')
949 if (!pane) return
950 s.herdrLast = value
951 const change = value === undefined ? ['--clear-token', HERDR_TOKEN] : ['--token', `${HERDR_TOKEN}=${value}`, '--ttl-ms', '86400000']
952 await $.process.run(['herdr', 'pane', 'report-metadata', pane, '--source', HERDR_SOURCE, '--agent', 'claude', ...change], { timeoutMs: 3_000 }).catch(() => undefined)
953}
954
955/** /clear, then the held prompt as the new conversation's first. */
956async function startFresh($: EngineInterface, s: State, text: string): Promise<void> {
957 try {
958 await $.command.run({ command: 'clear' })
959 s.clock = undefined
960 s.timer?.cancel()
961 s.timer = undefined
962 await $.prompt.submit({ text, asUser: true })
963 } catch (error) {
964 $.ui.log(`could not start a new conversation (${error instanceof Error ? error.message : String(error)}); your prompt is back in the box`)
965 await $.prompt.fill({ text })
966 }
967}
968
969/** Compaction (with the chosen guidance), then the held prompt onto the summary. */
970async function compactThenSend($: EngineInterface, s: State, text: string, instructions: string | undefined): Promise<void> {
971 const outcome = await runCompaction($, s, instructions)
972 if (!outcome.ok) {
973 $.ui.log(`compaction did not run (${outcome.reason}); your prompt is back in the box`)
974 await $.prompt.fill({ text })
975 return
976 }
977 await $.prompt.submit({ text, asUser: true }).catch(async (error: unknown) => {
978 $.ui.log(`could not send your prompt (${error instanceof Error ? error.message : String(error)}); it is back in the box`)
979 await $.prompt.fill({ text })
980 })
981}
982
983/** A Jev compaction judged against the held prompt, then the prompt onto the summary; on failure the prompt goes back. */
984async function compactWithJevThenSend($: EngineInterface, s: State, text: string): Promise<void> {
985 const outcome = await runJevCompaction($, s, text)
986 if (!outcome.ok) {
987 $.ui.log(`compaction with Jev did not run: ${outcome.reason}; your prompt is back in the box`)
988 await $.prompt.fill({ text })
989 return
990 }
991 $.ui.log(`compacted with Jev in ${(outcome.latencyMs / 1000).toFixed(1)} s (${describeCounts(outcome.counts)})`)
992 await $.prompt.submit({ text, asUser: true }).catch(async (error: unknown) => {
993 $.ui.log(`could not send your prompt (${error instanceof Error ? error.message : String(error)}); it is back in the box`)
994 await $.prompt.fill({ text })
995 })
996}
997
998/** A result Claude Code persisted, when it is still there and at most 8 MB. */
999async function readPersisted($: EngineInterface, file: string): Promise<string | undefined> {
1000 const text = await $.fs.read(file).catch(() => undefined)
1001 return typeof text === 'string' && text.length <= 8_000_000 ? text : undefined
1002}
1003hooks/core.ts 329 lines1// cache-guard core: the prompt-cache clock, the cost of a miss, when a keep-warm request or a
2// warning pays, and the settings of every part (`lean.ts` holds the Jev trimming and compaction).
3// Shared verbatim by pi-cache-guard, claude-cache-guard, opencode-cache-guard and
4// codex-cache-guard; keep it free of imports so each port can copy this file as is.
5//
6// The model is Anthropic's: a cached prefix lives for its TTL from the start of the last request
7// that read or wrote it (the API guarantees that minimum and deletes soon after), and a request
8// after that re-writes the whole prefix. Prices are dollars per million tokens at API list rates;
9// on a subscription they stand for plan usage in the same proportions.
10
11export const NAME = "cache-guard";
12
13export interface Price {
14 /** Uncached input. */
15 input: number;
16 /** A cache read (hit or refresh). */
17 cacheRead: number;
18 /** A 5-minute cache write; 1.25x input when absent. A 1-hour write is always 2x input. */
19 cacheWrite?: number;
20}
21
22export interface Settings {
23 enabled: boolean;
24 warn: {
25 enabled: boolean;
26 /** Ask before a prompt whose re-cache costs at least this many dollars (when prices are known). */
27 minCost: number;
28 /** Without prices, ask when at least this many tokens would be re-sent uncached. */
29 minTokens: number;
30 /** Where a harness can only block, sending the same prompt again within this window sends it. */
31 confirmSeconds: number;
32 /** Providers that publish no TTL (OpenAI, Codex): warn after this long idle. */
33 idleMinutes: number;
34 };
35 warm: {
36 enabled: boolean;
37 /** Chance a real request arrives before the entry expires while idle (Pi's measured constant). */
38 continuationProbability: number;
39 /** A refresh is sent only when it is expected to save at least this many dollars. */
40 minSavings: number;
41 /** Stop refreshing this long after the last real request, per TTL tier. */
42 idleMinutes: { "5m": number; "1h": number };
43 /** What a keep-warm request asks, where the harness has to send a message. */
44 prompt: string;
45 };
46 herdr: {
47 /** Report the pane token `cache` to herdr (inside a herdr pane) so its agents sidebar can show doomed sessions. */
48 enabled: boolean;
49 };
50 jev: {
51 /** Use Jev, TypeSafe's judgment model, to trim tool output and to compact. Off: neither, and no setup hints. */
52 enabled: boolean;
53 /** Where to reach Jev. Empty: the first that works (Pi: any provider that serves Jev; elsewhere TypeSafe's API). */
54 provider: string;
55 /** Jev's model id at that provider. Empty: the provider's default. */
56 model: string;
57 /** One trimming request's limit, in milliseconds; past it the output stays whole. */
58 timeoutMs: number;
59 };
60 trim: {
61 /** Trim large tool output to the blocks the agent needs, before it enters the context. */
62 enabled: boolean;
63 /** Trim text results longer than this many characters. */
64 minChars: number;
65 /** For whole-file reads, trim only results longer than this. */
66 readMinChars: number;
67 /** At most this many blocks are judged. */
68 maxBlocks: number;
69 /** Characters of output sent to Jev; larger output is pre-filtered first. */
70 stateBudgetChars: number;
71 /** Keep blocks whose probability of being needed reaches this. */
72 keepThreshold: number;
73 /** Do not trim when Jev thinks the agent asked for the whole output. */
74 needsAllThreshold: number;
75 /** Do not trim when more than this share of lines would be kept. */
76 maxKeptShare: number;
77 headLines: number;
78 tailLines: number;
79 };
80 compact: {
81 /** Jev also filters what the harness's own summarizer reads (Pi's /compact and automatic compaction). */
82 filter: boolean;
83 /** The whole Jev pass over a conversation, in milliseconds per request. */
84 timeoutMs: number;
85 /** Jev requests in flight at once. */
86 concurrency: number;
87 };
88}
89
90export const DEFAULT_SETTINGS: Settings = {
91 enabled: true,
92 warn: { enabled: true, minCost: 0.5, minTokens: 100_000, confirmSeconds: 120, idleMinutes: 180 },
93 warm: {
94 enabled: true,
95 continuationProbability: 0.15,
96 minSavings: 0.05,
97 idleMinutes: { "5m": 30, "1h": 120 },
98 prompt: "Cache keep-alive. Do not use tools or think. Reply with exactly: ok",
99 },
100 herdr: { enabled: true },
101 jev: { enabled: true, provider: "", model: "", timeoutMs: 2_500 },
102 trim: {
103 enabled: true,
104 minChars: 12_000,
105 readMinChars: 50_000,
106 maxBlocks: 150,
107 stateBudgetChars: 60_000,
108 keepThreshold: 0.4,
109 needsAllThreshold: 0.6,
110 maxKeptShare: 0.7,
111 headLines: 5,
112 tailLines: 20,
113 },
114 compact: { filter: true, timeoutMs: 10_000, concurrency: 4 },
115};
116
117/** The herdr pane token the ports report (`herdr pane report-metadata --source cache-guard`). */
118export const HERDR_TOKEN = "cache";
119export const HERDR_SOURCE = NAME;
120
121export const FIVE_MINUTES = 5 * 60_000;
122export const ONE_HOUR = 60 * 60_000;
123
124/** "5m" or "1h": the tier a TTL bills as (anything from an hour up writes at 2x). */
125export function tier(ttlMs: number): "5m" | "1h" {
126 return ttlMs >= ONE_HOUR ? "1h" : "5m";
127}
128
129/** Refresh at 90% of the TTL, keeping at least ten seconds of margin (Pi's rule). */
130export function warmDelayMs(ttlMs: number): number | undefined {
131 if (ttlMs <= 10_000) return undefined;
132 return Math.max(1, Math.floor(Math.min(ttlMs * 0.9, ttlMs - 10_000)));
133}
134
135/** Milliseconds the entry written or refreshed at `lastAt` has left; 0 once expired. */
136export function remainingMs(lastAt: number, ttlMs: number, now: number): number {
137 return Math.max(0, lastAt + ttlMs - now);
138}
139
140export function writePrice(price: Price, ttlMs: number): number {
141 return tier(ttlMs) === "1h" ? price.input * 2 : (price.cacheWrite ?? price.input * 1.25);
142}
143
144/** What a miss costs over a hit: the prefix written again instead of read. */
145export function missCost(tokens: number, price: Price, ttlMs: number): number {
146 return Math.max(0, (tokens * (writePrice(price, ttlMs) - price.cacheRead)) / 1e6);
147}
148
149/** What one refresh costs: the prefix read (plus a token or two, ignored). */
150export function warmCost(tokens: number, price: Price): number {
151 return (tokens * price.cacheRead) / 1e6;
152}
153
154export interface WarmDecision {
155 action: "warm" | "stop";
156 warmCost: number;
157 missCost: number;
158 expectedSavings: number;
159}
160
161/**
162 * Pi's rule: refresh when `p * missCost - warmCost` is at least `minSavings`, with p = 1 while the
163 * agent is still running (its next request is certain) and the idle constant otherwise.
164 */
165export function decideWarm(tokens: number, price: Price, ttlMs: number, idle: boolean, settings: Settings): WarmDecision {
166 const miss = missCost(tokens, price, ttlMs);
167 const warm = warmCost(tokens, price);
168 const p = idle ? settings.warm.continuationProbability : 1;
169 const expectedSavings = p * miss - warm;
170 return { action: expectedSavings >= settings.warm.minSavings ? "warm" : "stop", warmCost: warm, missCost: miss, expectedSavings };
171}
172
173/** The last moment a refresh may be sent for a cache last used by a real request at `lastRealAt`. */
174export function warmDeadline(lastRealAt: number, ttlMs: number, settings: Settings): number {
175 return lastRealAt + settings.warm.idleMinutes[tier(ttlMs)] * 60_000;
176}
177
178/** Whether a re-cache of `tokens` (costing `cost`, when prices are known) is worth asking about. */
179export function worthWarning(tokens: number, cost: number | undefined, settings: Settings): boolean {
180 if (!settings.enabled || !settings.warn.enabled) return false;
181 return cost !== undefined ? cost >= settings.warn.minCost : tokens >= settings.warn.minTokens;
182}
183
184export type ColdReason =
185 | { kind: "expired"; idleMs: number }
186 | { kind: "model"; from: string; to: string }
187 | { kind: "idle"; idleMs: number };
188
189/**
190 * The herdr `cache` token: `❄ 664k` (or `❄? 180k` when only idle time suggests it) while the
191 * next prompt would re-cache at least the warning threshold, else undefined (clear the token).
192 * Warm and small caches report nothing, so the sidebar lists only the doomed sessions.
193 */
194export function herdrCacheValue(reason: ColdReason | undefined, tokens: number, cost: number | undefined, settings: Settings): string | undefined {
195 if (!reason || !settings.enabled || !settings.herdr.enabled) return undefined;
196 const big = cost !== undefined ? cost >= settings.warn.minCost : tokens >= settings.warn.minTokens;
197 if (!big) return undefined;
198 return `${reason.kind === "idle" ? "❄?" : "❄"} ${formatTokens(tokens)}`;
199}
200
201/**
202 * Rough costs, in dollars at list prices, of the two ways through a cold cache that keep the
203 * history: send the prompt and write the whole prefix to the cache again, or compact first, which
204 * reads it once uncached (plus a summary, not counted) and continues on a small context. Starting
205 * fresh costs about nothing.
206 */
207export function choiceCosts(tokens: number, price: Price, ttlMs: number): { send: number; compact: number } {
208 return { send: (tokens * writePrice(price, ttlMs)) / 1e6, compact: (tokens * price.input) / 1e6 };
209}
210
211/** Compaction guidance that keeps what the held prompt needs. */
212export function compactionFocus(prompt: string): string {
213 return `Keep what is needed to continue with the user's next request, quoted below, and drop the rest.\n\n${prompt.trim()}`;
214}
215
216/** One line saying why the next request misses and what that costs. */
217export function describeMiss(reason: ColdReason, tokens: number, cost: number | undefined): string {
218 const amount = `${formatTokens(tokens)} tokens${cost === undefined ? "" : ` (~${formatCost(cost)} at API prices)`}`;
219 switch (reason.kind) {
220 case "expired":
221 return `The prompt cache expired ${formatDuration(reason.idleMs)} ago: this prompt re-caches ${amount}.`;
222 case "idle":
223 return `Idle ${formatDuration(reason.idleMs)}: the prompt cache has probably expired, so this prompt may re-cache ${amount}.`;
224 case "model":
225 return `${reason.to} has no cache of this conversation (it was cached for ${reason.from}): this prompt re-caches ${amount}.`;
226 }
227}
228
229/** Remembers a blocked prompt so the same prompt sent again within the window goes through. */
230export class ConfirmMemo {
231 private pending?: { key: string; text: string; at: number };
232
233 /** True when `text` repeats the prompt blocked for `key` within `windowMs`; clears it either way. */
234 confirmed(key: string, text: string, now: number, windowMs: number): boolean {
235 const pending = this.pending;
236 this.pending = undefined;
237 return pending !== undefined && pending.key === key && pending.text === text.trim() && now - pending.at <= windowMs;
238 }
239
240 arm(key: string, text: string, now: number): void {
241 this.pending = { key, text: text.trim(), at: now };
242 }
243}
244
245/** "4:05" under an hour, "1h05m" above, "0:00" once gone. */
246export function formatClock(ms: number): string {
247 const seconds = Math.max(0, Math.ceil(ms / 1000));
248 if (seconds >= 3600) return `${Math.floor(seconds / 3600)}h${String(Math.floor((seconds % 3600) / 60)).padStart(2, "0")}m`;
249 return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, "0")}`;
250}
251
252/** "45s", "12m", "3h20m", "2d4h". */
253export function formatDuration(ms: number): string {
254 const seconds = Math.max(0, Math.round(ms / 1000));
255 if (seconds < 60) return `${seconds}s`;
256 const minutes = Math.floor(seconds / 60);
257 if (minutes < 60) return `${minutes}m`;
258 const hours = Math.floor(minutes / 60);
259 if (hours < 48) return `${hours}h${minutes % 60 ? `${minutes % 60}m` : ""}`;
260 return `${Math.floor(hours / 24)}d${hours % 24 ? `${hours % 24}h` : ""}`;
261}
262
263export function formatTokens(n: number): string {
264 if (n >= 1e6) return `${(n / 1e6).toFixed(n >= 1e7 ? 0 : 1)}M`;
265 if (n >= 1e3) return `${Math.round(n / 1e3)}k`;
266 return String(Math.round(n));
267}
268
269export function formatCost(dollars: number): string {
270 return dollars >= 10 ? `$${dollars.toFixed(0)}` : `$${dollars.toFixed(2)}`;
271}
272
273/**
274 * List prices of the Claude models, for harnesses that do not carry a model catalog (Claude Code,
275 * Codex has no use for it). Longest prefix wins; unknown models price as Opus 5.5.
276 */
277const CLAUDE_PRICES: ReadonlyArray<readonly [string, Price]> = [
278 ["claude-fable-5-1", { input: 10, cacheRead: 0.25 }],
279 ["claude-fable-5", { input: 10, cacheRead: 1 }],
280 ["claude-mythos-5-1", { input: 10, cacheRead: 0.25 }],
281 ["claude-opus-5-5", { input: 4, cacheRead: 0.2 }],
282 ["claude-opus-5", { input: 5, cacheRead: 0.5 }],
283 ["claude-opus-4", { input: 5, cacheRead: 0.5 }],
284 ["claude-sonnet-5", { input: 2, cacheRead: 0.2 }],
285 ["claude-sonnet-4", { input: 3, cacheRead: 0.3 }],
286 ["claude-haiku-5", { input: 0.1, cacheRead: 0.01 }],
287 ["claude-haiku-4", { input: 1, cacheRead: 0.1 }],
288];
289
290export function claudePrice(model: string): Price {
291 const id = model.toLowerCase().replace(/^.*\//, "").replace(/\[.*$/, "");
292 let best: Price | undefined;
293 let length = 0;
294 for (const [prefix, price] of CLAUDE_PRICES) {
295 if (id.startsWith(prefix) && prefix.length > length) {
296 best = price;
297 length = prefix.length;
298 }
299 }
300 return best ?? { input: 4, cacheRead: 0.2 };
301}
302
303export function mergeSettings(base: Settings, texts: readonly (string | undefined)[]): Settings {
304 let merged: Record<string, unknown> = structuredClone(base) as unknown as Record<string, unknown>;
305 for (const text of texts) {
306 if (text === undefined) continue;
307 try {
308 const value: unknown = JSON.parse(text);
309 if (isRecord(value)) merged = merge(merged, value);
310 } catch {
311 // Invalid JSON: keep what the earlier files said.
312 }
313 }
314 return merged as unknown as Settings;
315}
316
317function merge(base: Record<string, unknown>, over: Record<string, unknown>): Record<string, unknown> {
318 const out: Record<string, unknown> = { ...base };
319 for (const [key, value] of Object.entries(over)) {
320 const current = out[key];
321 out[key] = isRecord(current) && isRecord(value) ? merge(current, value) : value;
322 }
323 return out;
324}
325
326function isRecord(value: unknown): value is Record<string, unknown> {
327 return typeof value === "object" && value !== null && !Array.isArray(value);
328}
329hooks/jev.ts 136 lines1// Jev, TypeSafe's judgment model, over its HTTP API (https://docs.typesafe.ai/api.md): the request
2// and response shapes, translated to and from lean.ts's Pi-style questions and answers. lean.ts
3// asks `bool` questions; the API's type is `noul`, answered as `{ type: "noul", noul }`. Pure: the
4// `$.http.fetch` call itself is in register.ts, where `$` is.
5import type { Answer, Question } from './lean'
6
7export const ENDPOINT = 'https://api.typesafe.ai/v1/systemone'
8export const DEFAULT_MODEL = 'jev-latest'
9
10/** The API's question shapes. */
11type ApiQuestion =
12 | { type: 'noul'; instructions: string; criteria?: { true: string; false: string } }
13 | { type: 'choice'; instructions: string; criteria: Record<string, string> }
14 | { type: 'score'; instructions: string; criteria: readonly string[] }
15
16type ApiAnswer =
17 | { type: 'noul'; noul: number }
18 | { type: 'choice'; choice: string; probabilities: Record<string, number>; confidence: number }
19 | { type: 'score'; score: number; confidence: number }
20
21export interface JevTarget {
22 model: string
23 /** Where the key came from, for /cache-guard jev. */
24 keySource: 'plugin config' | 'TYPESAFE_API_KEY'
25 apiKey: string
26}
27
28export type JevState =
29 | { kind: 'ready'; target: JevTarget }
30 | { kind: 'missing'; reason: string }
31 | { kind: 'off' }
32
33/**
34 * Which Jev to use, from the settings and the credentials found: the plugin's `typesafe_api_key`
35 * option first, then `TYPESAFE_API_KEY`. Only TypeSafe's own API is reachable from here, so any
36 * other `jev.provider` is "missing" with that reason. Never throws.
37 */
38export function resolveJev(
39 settings: { enabled: boolean; jev: { enabled: boolean; provider: string; model: string } },
40 configKey: unknown,
41 envKey: string | undefined,
42): JevState {
43 if (!settings.enabled || !settings.jev.enabled) return { kind: 'off' }
44 const provider = settings.jev.provider.trim()
45 if (provider && provider !== 'typesafe') {
46 return { kind: 'missing', reason: `jev.provider "${provider}" is not supported here; Claude Code reaches Jev through TypeSafe's API only (leave it empty or "typesafe")` }
47 }
48 const model = settings.jev.model.trim() || DEFAULT_MODEL
49 const fromConfig = typeof configKey === 'string' ? configKey.trim() : ''
50 if (fromConfig) return { kind: 'ready', target: { model, keySource: 'plugin config', apiKey: fromConfig } }
51 const fromEnv = envKey?.trim() ?? ''
52 if (fromEnv) return { kind: 'ready', target: { model, keySource: 'TYPESAFE_API_KEY', apiKey: fromEnv } }
53 return { kind: 'missing', reason: 'no TypeSafe API key (the plugin option typesafe_api_key, or TYPESAFE_API_KEY in the environment)' }
54}
55
56export function label(target: JevTarget): string {
57 return `typesafe/${target.model}`
58}
59
60/** lean.ts questions as the API takes them: `bool` becomes `noul`. */
61export function toApiQuestions(questions: Record<string, Question>): Record<string, ApiQuestion> {
62 const out: Record<string, ApiQuestion> = {}
63 for (const [id, question] of Object.entries(questions)) {
64 out[id] = question.type === 'bool' ? { type: 'noul', instructions: question.instructions, criteria: question.criteria } : question
65 }
66 return out
67}
68
69/** The request body for one Jev call. */
70export function requestBody(model: string, state: Record<string, unknown>, questions: Record<string, Question>): string {
71 return JSON.stringify({ model, state, questions: toApiQuestions(questions) })
72}
73
74export interface JevReply {
75 answers: Record<string, Answer>
76 model: string
77 inputTokens?: number
78}
79
80/** The API's answers as lean.ts reads them: `noul` becomes `bool`. Undefined when the body has no answers. */
81export function readReply(text: string): JevReply | undefined {
82 let body: { model?: unknown; answers?: unknown; usage?: { input_tokens?: unknown } }
83 try {
84 body = JSON.parse(text) as typeof body
85 } catch {
86 return undefined
87 }
88 if (!body || typeof body !== 'object' || !body.answers || typeof body.answers !== 'object') return undefined
89 const answers: Record<string, Answer> = {}
90 for (const [id, raw] of Object.entries(body.answers as Record<string, ApiAnswer | undefined>)) {
91 const answer = fromApiAnswer(raw)
92 if (answer) answers[id] = answer
93 }
94 const inputTokens = body.usage?.input_tokens
95 return {
96 answers,
97 model: typeof body.model === 'string' ? body.model : '',
98 ...(typeof inputTokens === 'number' && Number.isFinite(inputTokens) ? { inputTokens } : {}),
99 }
100}
101
102function fromApiAnswer(raw: ApiAnswer | undefined): Answer | undefined {
103 if (!raw || typeof raw !== 'object') return undefined
104 switch (raw.type) {
105 case 'noul':
106 return Number.isFinite(raw.noul) ? { type: 'bool', probability: raw.noul } : undefined
107 case 'choice':
108 return typeof raw.choice === 'string'
109 ? { type: 'choice', choice: raw.choice, probabilities: raw.probabilities ?? {}, confidence: Number(raw.confidence) || 0 }
110 : undefined
111 case 'score':
112 return Number.isFinite(raw.score) ? { type: 'score', score: raw.score, confidence: Number(raw.confidence) || 0 } : undefined
113 default:
114 return undefined
115 }
116}
117
118/** One line for an HTTP status or a transport error. */
119export function describeFailure(status: number | undefined, message?: string): string {
120 if (status !== undefined) {
121 if (status === 401 || status === 403) return 'invalid API key'
122 if (status === 429) return 'rate limited (HTTP 429)'
123 return `HTTP ${status}`
124 }
125 const text = (message ?? '').replace(/\s+/gu, ' ').trim()
126 if (/timed out|timeout|ETIMEDOUT/iu.test(text)) return 'timed out'
127 if (/CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC|nonessential/iu.test(text)) return 'network calls are off (CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC)'
128 return text.slice(0, 160) || 'unknown error'
129}
130
131/** A one-question request, to check that Jev answers with the key found. */
132export const PROBE: { state: Record<string, unknown>; questions: Record<string, Question> } = {
133 state: { message: 'The tests pass now, thanks.' },
134 questions: { approved: { type: 'bool', instructions: 'Is the user satisfied?', criteria: { true: 'Satisfied', false: 'Not satisfied' } } },
135}
136hooks/lean.ts 369 lines1// cache-guard lean: keeping the context small with Jev, TypeSafe's judgment model. Trims large tool
2// output to the blocks the agent needs, and sorts a conversation being compacted into what must
3// survive word for word, what a note covers, and what can go. Shared verbatim by pi-cache-guard,
4// claude-cache-guard, opencode-cache-guard and codex-cache-guard; it imports nothing, so each port
5// can copy this file as is. How a port reaches Jev and reads its transcript stays in the port.
6//
7// Questions and answers use Pi's classifier shapes (`bool`, `choice`, `score`). Ports that call
8// Jev's HTTP API directly translate `bool` to its `noul` type and back.
9
10export type Question =
11 | { type: "bool"; instructions: string; criteria: { true: string; false: string } }
12 | { type: "choice"; instructions: string; criteria: Record<string, string> }
13 | { type: "score"; instructions: string; criteria: string[] };
14
15export type Answer =
16 | { type: "bool"; probability: number }
17 | { type: "choice"; choice: string; probabilities: Record<string, number>; confidence: number }
18 | { type: "score"; score: number; confidence: number };
19
20/** One line for setup hints: what Jev adds. */
21export const JEV_PITCH =
22 "Jev, TypeSafe's judgment model, trims large tool output to what the agent needs and compacts a conversation in about a second, without an LLM summary.";
23
24/** Where to get a key for Jev's own API (TYPESAFE_API_KEY). */
25export const JEV_KEY_URL = "https://console.typesafe.ai/keys";
26
27export function boolAnswer(answers: Record<string, Answer>, id: string): number | undefined {
28 const answer = answers[id];
29 return answer?.type === "bool" && Number.isFinite(answer.probability) ? answer.probability : undefined;
30}
31
32export function choiceAnswer(answers: Record<string, Answer>, id: string): string | undefined {
33 const answer = answers[id];
34 return answer?.type === "choice" ? answer.choice : undefined;
35}
36
37export function clip(text: string, max: number): string {
38 return text.length > max ? `${text.slice(0, max - 1)}…` : text;
39}
40
41export function clipTail(text: string, max: number): string {
42 return text.length > max ? `…${text.slice(-(max - 1))}` : text;
43}
44
45// ---------------------------------------------------------------------------------------------
46// Trimming tool output
47
48export interface TrimLimits {
49 /** Trim text results longer than this many characters. */
50 minChars: number;
51 /** For whole-file reads, trim only results longer than this. */
52 readMinChars: number;
53 /** At most this many blocks are judged. */
54 maxBlocks: number;
55 /** Characters of output sent to Jev; larger output is pre-filtered first. */
56 stateBudgetChars: number;
57 /** Keep blocks whose probability of being needed reaches this. */
58 keepThreshold: number;
59 /** Do not trim when Jev thinks the agent asked for the whole output. */
60 needsAllThreshold: number;
61 /** Do not trim when more than this share of lines would be kept. */
62 maxKeptShare: number;
63 headLines: number;
64 tailLines: number;
65}
66
67const SIGNAL = /error|\bERR!?\b|warn|fail|panic|assert|exception|traceback|fatal|could not|cannot|can't|not found|denied|refused|conflict|exit code|✗|×/iu;
68
69export interface Block {
70 id: string;
71 /** Line indices (0-based) of the original output in this block. */
72 lines: number[];
73 text: string;
74}
75
76/**
77 * Lines worth judging when the output is too large for one request: the first 40, the last 80,
78 * every line that looks like an error or warning (with two lines of context), and an even sample
79 * of the rest up to the budget.
80 */
81export function prefilter(lines: readonly string[], budgetChars: number): number[] {
82 const n = lines.length;
83 const keep = new Set<number>();
84 for (let i = 0; i < Math.min(40, n); i++) keep.add(i);
85 for (let i = Math.max(0, n - 80); i < n; i++) keep.add(i);
86 for (let i = 0; i < n; i++) {
87 if (SIGNAL.test(lines[i] as string)) {
88 for (let j = Math.max(0, i - 2); j <= Math.min(n - 1, i + 2); j++) keep.add(j);
89 }
90 }
91 let used = [...keep].reduce((sum, i) => sum + (lines[i] as string).length + 1, 0);
92 const rest = [...Array(n).keys()].filter((i) => !keep.has(i));
93 if (rest.length && used < budgetChars) {
94 const average = rest.reduce((sum, i) => sum + (lines[i] as string).length + 1, 0) / rest.length || 1;
95 const room = Math.floor((budgetChars - used) / average);
96 const step = Math.max(1, Math.ceil(rest.length / Math.max(1, room)));
97 for (let k = 0; k < rest.length; k += step) {
98 const i = rest[k] as number;
99 const size = (lines[i] as string).length + 1;
100 if (used + size > budgetChars) break;
101 keep.add(i);
102 used += size;
103 }
104 }
105 return [...keep].sort((a, b) => a - b);
106}
107
108/** Group the candidate lines into at most `maxBlocks` blocks of consecutive candidates. */
109export function makeBlocks(lines: readonly string[], candidates: readonly number[], maxBlocks: number): Block[] {
110 const size = Math.max(1, Math.ceil(candidates.length / maxBlocks));
111 const blocks: Block[] = [];
112 for (let k = 0; k < candidates.length; k += size) {
113 const group = candidates.slice(k, k + size);
114 const id = `B${String(blocks.length + 1).padStart(3, "0")}`;
115 blocks.push({ id, lines: group, text: group.map((i) => clip(lines[i] as string, 400)).join("\n") });
116 }
117 return blocks;
118}
119
120/** The blocks of `text` Jev judges: all lines, or a pre-filtered selection when it is too large. */
121export function blocksFor(text: string, limits: TrimLimits): { lines: string[]; blocks: Block[] } {
122 const lines = text.split("\n");
123 const candidates = text.length > limits.stateBudgetChars ? prefilter(lines, limits.stateBudgetChars) : [...lines.keys()];
124 return { lines, blocks: makeBlocks(lines, candidates, limits.maxBlocks) };
125}
126
127/**
128 * Jev's state for a trim: what the agent is doing (`intent`: the request, what it said since, the
129 * tool and its arguments) and the output's blocks.
130 */
131export function trimState(intent: { user_request: string; agent_said: string; tool: string; arguments: string }, blocks: readonly Block[]) {
132 return {
133 intent: {
134 user_request: clip(intent.user_request, 1_500),
135 agent_said: clipTail(intent.agent_said, 2_000) || "(nothing; see the tool call)",
136 tool: intent.tool,
137 arguments: clip(intent.arguments, 1_000),
138 },
139 output: Object.fromEntries(blocks.map((b) => [b.id, b.text])),
140 };
141}
142
143export function trimQuestions(blocks: readonly Block[]): Record<string, Question> {
144 const questions: Record<string, Question> = {
145 needs_all: {
146 type: "bool",
147 instructions:
148 "Given `intent`, did the agent run this to read the complete output verbatim (for example to copy, review, or count all of it), rather than to find specific results in it?",
149 criteria: { true: "The agent needs the whole output", false: "The agent needs only the relevant parts" },
150 },
151 };
152 for (const block of blocks) {
153 questions[`block::${block.id}`] = {
154 type: "bool",
155 instructions: `Does \`output.${block.id}\` contain information the agent needs for \`intent\`: errors, failures, warnings, requested values, or results it would act on?`,
156 criteria: {
157 true: "The agent should read these lines",
158 false: "Routine progress, passing output, boilerplate, or repetition the agent can skip",
159 },
160 };
161 }
162 return questions;
163}
164
165export interface Assembly {
166 text: string;
167 keptLines: number;
168 totalLines: number;
169}
170
171/**
172 * The kept lines (kept blocks plus the head and tail) in original order, with
173 * `[… N lines omitted …]` markers, and a footer pointing at the full output.
174 */
175export function assemble(lines: readonly string[], keptBlocks: readonly Block[], limits: TrimLimits, fullPath: string): Assembly {
176 const keep = new Set<number>();
177 for (let i = 0; i < Math.min(limits.headLines, lines.length); i++) keep.add(i);
178 for (let i = Math.max(0, lines.length - limits.tailLines); i < lines.length; i++) keep.add(i);
179 for (const block of keptBlocks) for (const i of block.lines) keep.add(i);
180 const out: string[] = [];
181 let omitted = 0;
182 for (let i = 0; i < lines.length; i++) {
183 if (keep.has(i)) {
184 if (omitted) out.push(`[… ${omitted} line${omitted === 1 ? "" : "s"} omitted …]`);
185 omitted = 0;
186 out.push(lines[i] as string);
187 } else omitted++;
188 }
189 if (omitted) out.push(`[… ${omitted} line${omitted === 1 ? "" : "s"} omitted …]`);
190 out.push("", `[Trimmed by Jev: kept ${keep.size} of ${lines.length} lines that matter for this step. Full output: ${fullPath} (read it with offset/limit).]`);
191 return { text: out.join("\n"), keptLines: keep.size, totalLines: lines.length };
192}
193
194export interface TrimVerdict extends Assembly {
195 /** False when the output should stay whole: the agent wants all of it, or most would be kept. */
196 trim: boolean;
197 needsAll: number;
198}
199
200/** Jev's answers turned into the trimmed text, and whether trimming is worth it. */
201export function trimVerdict(lines: readonly string[], blocks: readonly Block[], answers: Record<string, Answer>, limits: TrimLimits, fullPath: string): TrimVerdict {
202 const needsAll = boolAnswer(answers, "needs_all") ?? 0;
203 const kept = blocks.filter((b) => (boolAnswer(answers, `block::${b.id}`) ?? 1) >= limits.keepThreshold);
204 const result = assemble(lines, kept, limits, fullPath);
205 const trim = needsAll <= limits.needsAllThreshold && result.keptLines / result.totalLines <= limits.maxKeptShare;
206 return { ...result, trim, needsAll };
207}
208
209// ---------------------------------------------------------------------------------------------
210// Compaction
211
212/** One thing in the conversation Jev decides about: a message, an assistant text, or a tool call with its result. */
213export interface Unit {
214 id: string;
215 kind: "user" | "assistant" | "tool" | "other";
216 /** Full text for the summary (user/assistant text, tool call and result). */
217 text: string;
218 tool?: { name: string; args: string; result: string; isError: boolean; callId: string };
219 /** Index of the message the unit starts in. */
220 message: number;
221}
222
223export type Keep = "verbatim" | "summarize" | "drop";
224
225/** The short form Jev reads: user 1.5k, assistant 1k, tool call 300 and result 600 characters. */
226export function unitForJev(unit: Unit): Record<string, unknown> {
227 if (unit.tool) {
228 return { kind: "tool", call: clip(`${unit.tool.name}(${unit.tool.args})`, 300), result: clip(unit.tool.result, 600), ...(unit.tool.isError ? { failed: true } : {}) };
229 }
230 return { kind: unit.kind, text: clip(unit.text, unit.kind === "user" ? 1_500 : 1_000) };
231}
232
233/** Fill in each tool unit's text from its call and result. */
234export function finishUnits(units: Unit[]): Unit[] {
235 for (const unit of units) {
236 if (unit.tool) unit.text = `${unit.tool.name}(${unit.tool.args})\n${unit.tool.isError ? "[error] " : ""}${unit.tool.result}`;
237 }
238 return units;
239}
240
241/** Batches of at most `maxUnits` units and `maxChars` characters of state each. */
242export function batches(units: readonly Unit[], maxUnits = 120, maxChars = 60_000): Unit[][] {
243 const out: Unit[][] = [];
244 let current: Unit[] = [];
245 let chars = 0;
246 for (const unit of units) {
247 const size = JSON.stringify(unitForJev(unit)).length;
248 if (current.length && (current.length >= maxUnits || chars + size > maxChars)) {
249 out.push(current);
250 current = [];
251 chars = 0;
252 }
253 current.push(unit);
254 chars += size;
255 }
256 if (current.length) out.push(current);
257 return out;
258}
259
260/** Jev's state for one batch: the goal the conversation continues toward, and the units. */
261export function keepState(goal: string, batch: readonly Unit[]) {
262 return { current_goal: goal.trim() || "(continue the work)", units: Object.fromEntries(batch.map((u) => [u.id, unitForJev(u)])) };
263}
264
265export function keepQuestions(units: readonly Unit[]): Record<string, Question> {
266 return Object.fromEntries(
267 units.map((unit) => [
268 `keep::${unit.id}`,
269 {
270 type: "choice",
271 instructions: `The conversation is being compacted to continue \`current_goal\`. How should \`units.${unit.id}\` be kept?`,
272 criteria: {
273 verbatim: "Must survive word for word: user requirements or preferences, decisions, exact values, names or paths still needed, or errors that are still open",
274 summarize: "Useful context, but a one-line note is enough",
275 drop: "Superseded, resolved, or noise: routine exploration, passing checks, repeated or abandoned attempts",
276 },
277 } satisfies Question,
278 ]),
279 );
280}
281
282/** Jev's answer for each unit of a batch; anything unanswered is summarized. */
283export function keepAnswers(batch: readonly Unit[], answers: Record<string, Answer>, into = new Map<string, Keep>()): Map<string, Keep> {
284 for (const unit of batch) {
285 const answer = choiceAnswer(answers, `keep::${unit.id}`);
286 into.set(unit.id, answer === "verbatim" || answer === "drop" ? answer : "summarize");
287 }
288 return into;
289}
290
291export function keepCounts(keep: ReadonlyMap<string, Keep>): Record<Keep, number> {
292 const counts = { verbatim: 0, summarize: 0, drop: 0 };
293 for (const k of keep.values()) counts[k]++;
294 return counts;
295}
296
297const VERBATIM_ITEM_CHARS = 1_500;
298const VERBATIM_TOTAL_CHARS = 24_000;
299
300/** The verbatim units as Markdown, newest kept first when over the budget, in conversation order. */
301export function verbatimSection(units: readonly Unit[], keep: ReadonlyMap<string, Keep>): string {
302 const chosen = units.filter((u) => keep.get(u.id) === "verbatim");
303 const rendered: string[] = [];
304 let used = 0;
305 for (let i = chosen.length - 1; i >= 0; i--) {
306 const item = renderUnit(chosen[i] as Unit);
307 if (used + item.length > VERBATIM_TOTAL_CHARS) break;
308 rendered.unshift(item);
309 used += item.length;
310 }
311 return rendered.length ? `## Kept verbatim\n\n${rendered.join("\n\n")}` : "";
312}
313
314function renderUnit(unit: Unit): string {
315 if (unit.tool) {
316 return `**Tool \`${unit.tool.name}\`** \`${clip(unit.tool.args, 300)}\`${unit.tool.isError ? " (failed)" : ""}\n\`\`\`\n${clip(unit.tool.result, VERBATIM_ITEM_CHARS)}\n\`\`\``;
317 }
318 const who = unit.kind === "user" ? "User" : unit.kind === "assistant" ? "Assistant" : "Note";
319 return `**${who}:** ${clip(unit.text, VERBATIM_ITEM_CHARS)}`;
320}
321
322export interface FileOps {
323 read: Iterable<string>;
324 written: Iterable<string>;
325 edited: Iterable<string>;
326}
327
328/** The summary Jev's compaction writes in code, without any LLM. */
329export function codeSummary(input: {
330 units: readonly Unit[];
331 keep: ReadonlyMap<string, Keep>;
332 previousSummary?: string;
333 fileOps?: FileOps;
334 instructions?: string;
335}): string {
336 const { units, keep } = input;
337 const sections: string[] = [];
338 const counts = { verbatim: 0, summarize: 0, drop: 0 };
339 for (const unit of units) counts[keep.get(unit.id) ?? "summarize"]++;
340 sections.push(
341 `# Compacted with Jev\n\nJev kept ${counts.verbatim} item${counts.verbatim === 1 ? "" : "s"} word for word, noted ${counts.summarize} and dropped ${counts.drop}; no LLM wrote this summary.${input.instructions ? `\nFocus: ${input.instructions}` : ""}`,
342 );
343 if (input.previousSummary?.trim()) sections.push(`## Earlier summary\n\n${clip(input.previousSummary.trim(), 4_000)}`);
344 const goals = units.filter((u) => u.kind === "user" && keep.get(u.id) !== "drop").map((u) => `- ${clip(u.text.replace(/\s+/gu, " "), 500)}`);
345 if (goals.length) sections.push(`## Goal\n\nWhat the user asked for, in order:\n${goals.join("\n")}`);
346 const verbatim = verbatimSection(units, keep);
347 if (verbatim) sections.push(verbatim);
348 const notes = units
349 .filter((u) => (keep.get(u.id) ?? "summarize") === "summarize" && u.kind !== "user")
350 .map((u) => {
351 const first = u.tool ? `${u.tool.name} ${clip(u.tool.args, 120)}${u.tool.isError ? " (failed)" : ""}` : (u.text.split("\n").find((l) => l.trim()) ?? "");
352 return `- ${clip(first.trim(), 200)}`;
353 });
354 if (notes.length) sections.push(`## Notes\n\n${notes.join("\n")}`);
355 const files = fileLines(input.fileOps);
356 if (files) sections.push(`## Files\n\n${files}`);
357 return sections.join("\n\n");
358}
359
360function fileLines(ops: FileOps | undefined): string {
361 if (!ops) return "";
362 const modified = [...new Set([...ops.written, ...ops.edited])].sort();
363 const read = [...new Set(ops.read)].filter((f) => !modified.includes(f)).sort();
364 const lines: string[] = [];
365 if (modified.length) lines.push(`Modified: ${modified.join(", ")}`);
366 if (read.length) lines.push(`Read: ${read.join(", ")}`);
367 return lines.join("\n");
368}
369hooks/settings.ts 17 lines1// Settings shared with the pi, opencode and Codex ports: `~/.config/agents/cache-guard.json` (or
2// under $XDG_CONFIG_HOME) and `<project>/.agents/cache-guard.json`, with Claude Code's own
3// `~/.claude/cache-guard.json` and `<project>/.claude/cache-guard.json` as overrides. Later files
4// win; objects merge, other values replace.
5import { NAME } from './core'
6
7/** The settings files, lowest precedence first. */
8export function settingsFiles(home: string, xdgConfigHome: string | undefined, root: string): string[] {
9 const shared = xdgConfigHome || `${home}/.config`
10 return [
11 `${shared}/agents/${NAME}.json`,
12 `${home}/.claude/${NAME}.json`,
13 `${root}/.agents/${NAME}.json`,
14 `${root}/.claude/${NAME}.json`,
15 ]
16}
17hooks/transcript.ts 74 lines1// Reads the tail of a Claude Code transcript (~/.claude/projects/<slug>/<session>.jsonl): the last
2// main-conversation response, and which TTL the session's cache writes use. The usage rows carry
3// `cache_creation.ephemeral_1h_input_tokens` / `ephemeral_5m_input_tokens`, which nothing in the
4// mod API reports.
5
6export interface TranscriptTail {
7 /** When the last main-thread response was written (its end, so later than the request's start). */
8 at?: number;
9 /** Its prompt: input + cache reads + cache writes. */
10 promptTokens?: number;
11 /** Prompt plus the reply: what the next request re-sends. */
12 tokens?: number;
13 model?: string;
14 /** The tier of the most recent main-thread cache write in the tail. */
15 ttlMs?: number;
16 /** A compaction after the last response: the next request carries a fresh context. */
17 compacted?: boolean;
18}
19
20interface Usage {
21 input_tokens?: number;
22 output_tokens?: number;
23 cache_read_input_tokens?: number;
24 cache_creation_input_tokens?: number;
25 cache_creation?: { ephemeral_1h_input_tokens?: number; ephemeral_5m_input_tokens?: number };
26}
27
28/** The transcript file Claude Code writes for `sessionId` started in `root`. */
29export function transcriptPath(configDir: string, root: string, sessionId: string): string {
30 return `${configDir}/projects/${root.replace(/[^a-zA-Z0-9]/g, '-')}/${sessionId}.jsonl`
31}
32
33/** Parses JSONL text (possibly starting mid-line) from the end back. */
34export function parseTail(text: string): TranscriptTail {
35 const out: TranscriptTail = {}
36 const lines = text.split('\n')
37 for (let i = lines.length - 1; i >= 0; i--) {
38 const line = lines[i]
39 if (!line || line[0] !== '{') continue
40 let row: Record<string, any>
41 try {
42 row = JSON.parse(line)
43 } catch {
44 continue // the first, cut line
45 }
46 if (out.at === undefined && row.type === 'system' && row.subtype === 'compact_boundary') {
47 out.compacted = true
48 continue
49 }
50 if (row.type !== 'assistant' || row.isSidechain === true) continue
51 const message = row.message ?? {}
52 if (message.model === '<synthetic>' || row.isApiErrorMessage === true) continue
53 const usage: Usage | undefined = message.usage
54 if (!usage) continue
55 const prompt = (usage.input_tokens ?? 0) + (usage.cache_read_input_tokens ?? 0) + (usage.cache_creation_input_tokens ?? 0)
56 if (prompt <= 0) continue
57 if (out.at === undefined) {
58 const at = Date.parse(row.timestamp)
59 if (!Number.isFinite(at)) continue
60 out.at = at
61 out.promptTokens = prompt
62 out.tokens = prompt + (usage.output_tokens ?? 0)
63 out.model = String(message.model ?? '')
64 }
65 const oneHour = usage.cache_creation?.ephemeral_1h_input_tokens ?? 0
66 const fiveMinutes = usage.cache_creation?.ephemeral_5m_input_tokens ?? 0
67 if (oneHour > 0 || fiveMinutes > 0) {
68 out.ttlMs = oneHour >= fiveMinutes ? 3_600_000 : 300_000
69 break
70 }
71 }
72 return out
73}
74hooks/units.ts 199 lines1// Claude Code's transcript (SessionMessage rows) in and out of lean.ts: the units Jev judges for
2// a compaction, the filtered conversation Claude Code's summarizer reads, the earlier summary, the
3// files the conversation touched, and the last requests. Pure: no `$`.
4import { type FileOps, type Keep, type Unit, clip, finishUnits } from './lean'
5
6/** The part of a SessionMessage this reads; what it writes back is the same shape. */
7export interface MessageLike {
8 role: 'user' | 'assistant'
9 text: string
10 toolUses: readonly ToolUseLike[]
11 toolResults?: readonly ToolResultLike[]
12 handle?: string
13}
14
15export interface ToolUseLike {
16 tool_use_id: string
17 tool: string
18 input: Record<string, unknown>
19 text?: string
20 isError?: true
21 result?: unknown
22 [extra: string]: unknown
23}
24
25export interface ToolResultLike {
26 tool_use_id: string
27 text: string
28 isError: boolean
29 result?: unknown
30}
31
32/** How Claude Code's own summary opens, and how a Jev summary does. */
33const SUMMARY_PREFIXES = ['This session is being continued from a previous conversation', '# Compacted with Jev']
34
35export function isSummary(message: MessageLike): boolean {
36 if (message.role !== 'user' || message.toolResults?.length || message.toolUses.length) return false
37 const text = message.text.trimStart()
38 return SUMMARY_PREFIXES.some((prefix) => text.startsWith(prefix))
39}
40
41/**
42 * Split the transcript into units, each tool call with its outcome (from the assistant row's
43 * `toolUses`, which carry the result once answered). A leading summary of an earlier compaction
44 * is returned apart, as the previous summary.
45 */
46export function extractUnits(messages: readonly MessageLike[]): { units: Unit[]; previousSummary?: string } {
47 const units: Unit[] = []
48 let previousSummary: string | undefined
49 const id = () => `U${String(units.length + 1).padStart(3, '0')}`
50 messages.forEach((message, index) => {
51 if (index === 0 && isSummary(message)) {
52 previousSummary = message.text
53 return
54 }
55 if (message.role === 'user') {
56 // A row carrying tool results is the engine's; its text, if any, is a reminder.
57 if (message.toolResults?.length) return
58 const text = message.text.trim()
59 if (text) units.push({ id: id(), kind: 'user', text, message: index })
60 return
61 }
62 const text = message.text.trim()
63 if (text) units.push({ id: id(), kind: 'assistant', text, message: index })
64 for (const use of message.toolUses) {
65 units.push({
66 id: id(),
67 kind: 'tool',
68 text: '',
69 tool: { name: use.tool, args: JSON.stringify(use.input ?? {}), result: use.text ?? '', isError: use.isError === true, callId: use.tool_use_id },
70 message: index,
71 })
72 }
73 })
74 return { units: finishUnits(units), ...(previousSummary !== undefined ? { previousSummary } : {}) }
75}
76
77/**
78 * The transcript Claude Code's summarizer reads: dropped units removed, summarized ones clipped
79 * (user text to 1.5k, assistant text to 1k, tool results to 600 characters), verbatim ones as they
80 * are (they are also appended to the summary). A changed row loses its `handle`, so the engine
81 * builds it from the text and tool blocks; an unchanged row keeps it.
82 */
83export function filterMessages(messages: readonly MessageLike[], units: readonly Unit[], keep: ReadonlyMap<string, Keep>): MessageLike[] {
84 const byMessage = new Map<number, Unit[]>()
85 for (const unit of units) byMessage.set(unit.message, [...(byMessage.get(unit.message) ?? []), unit])
86 const callKeep = new Map<string, Keep>()
87 for (const unit of units) if (unit.tool) callKeep.set(unit.tool.callId, keep.get(unit.id) ?? 'summarize')
88 const out: MessageLike[] = []
89 messages.forEach((message, index) => {
90 const own = byMessage.get(index) ?? []
91 if (message.role === 'user') {
92 if (message.toolResults?.length) {
93 // Each result follows its call: dropped with it, clipped with it.
94 const results = message.toolResults.filter((r) => callKeep.get(r.tool_use_id) !== 'drop')
95 if (!results.length && !message.text.trim()) return
96 const clipped = results.map((r) => (callKeep.get(r.tool_use_id) === 'summarize' && r.text.length > 600 ? { ...r, text: clip(r.text, 600) } : r))
97 const changed = clipped.length !== message.toolResults.length || clipped.some((r, i) => r !== results[i])
98 out.push(changed ? withoutHandle({ ...message, toolResults: clipped }) : message)
99 return
100 }
101 const unit = own[0]
102 const k = unit ? (keep.get(unit.id) ?? 'summarize') : 'verbatim'
103 if (k === 'drop') return
104 if (k === 'summarize' && message.text.length > 1_500) out.push(withoutHandle({ ...message, text: clip(message.text, 1_500) }))
105 else out.push(message)
106 return
107 }
108 const textUnit = own.find((u) => u.kind === 'assistant')
109 const k = textUnit ? (keep.get(textUnit.id) ?? 'summarize') : 'drop'
110 const text = k === 'drop' ? '' : k === 'summarize' ? clip(message.text, 1_000) : message.text
111 const uses = message.toolUses.filter((u) => callKeep.get(u.tool_use_id) !== 'drop')
112 const clippedUses = uses.map((u) => (callKeep.get(u.tool_use_id) === 'summarize' && (u.text?.length ?? 0) > 600 ? { ...u, text: clip(u.text ?? '', 600) } : u))
113 if (!text.trim() && !clippedUses.length) return
114 const changed = text !== message.text || clippedUses.length !== message.toolUses.length || clippedUses.some((u, i) => u !== message.toolUses[i])
115 out.push(changed ? withoutHandle({ ...message, text, toolUses: clippedUses }) : message)
116 })
117 return out
118}
119
120function withoutHandle(message: MessageLike): MessageLike {
121 const { handle: _handle, ...rest } = message
122 return rest
123}
124
125/** The last `count` prompts, oldest first: the goal when none is given. */
126export function lastUserMessages(messages: readonly MessageLike[], count: number): string {
127 const texts: string[] = []
128 for (let i = messages.length - 1; i >= 0 && texts.length < count; i--) {
129 const message = messages[i] as MessageLike
130 if (message.role !== 'user' || message.toolResults?.length || isSummary(message)) continue
131 const text = message.text.trim()
132 if (text) texts.unshift(clip(text, 1_500))
133 }
134 return texts.join('\n---\n')
135}
136
137const READ_TOOLS = new Set(['Read'])
138const WRITE_TOOLS = new Set(['Write'])
139const EDIT_TOOLS = new Set(['Edit', 'MultiEdit', 'NotebookEdit'])
140
141/** The files the conversation read, wrote and edited, from the file tools' arguments. */
142export function fileOps(messages: readonly MessageLike[]): FileOps {
143 const read = new Set<string>()
144 const written = new Set<string>()
145 const edited = new Set<string>()
146 for (const message of messages) {
147 if (message.role !== 'assistant') continue
148 for (const use of message.toolUses) {
149 if (use.isError) continue
150 const path = use.input?.file_path ?? use.input?.notebook_path
151 if (typeof path !== 'string' || !path) continue
152 if (READ_TOOLS.has(use.tool)) read.add(path)
153 else if (WRITE_TOOLS.has(use.tool)) written.add(path)
154 else if (EDIT_TOOLS.has(use.tool)) edited.add(path)
155 }
156 }
157 return { read, written, edited }
158}
159
160/** Which tools' output may be trimmed, and from what size; undefined for the rest. */
161export function trimFloor(tool: string, limits: { minChars: number; readMinChars: number }): number | undefined {
162 if (tool === 'Read') return limits.readMinChars
163 if (['Bash', 'Grep', 'Glob', 'LS', 'WebFetch', 'WebSearch'].includes(tool) || tool.startsWith('mcp__')) return limits.minChars
164 return undefined
165}
166
167/**
168 * Where Claude Code saved a result too large for the context: its `<persisted-output>` row keeps
169 * only a 2 KB preview and this path. Undefined for an ordinary result.
170 */
171export function persistedPath(text: string): string | undefined {
172 const match = /^<persisted-output>\s*\nOutput too large \([^)]*\)\. Full output saved to: (\S+)/u.exec(text)
173 return match?.[1]
174}
175
176/** The text of a tool_result block's `content`: a string, or its text blocks joined. */
177export function resultText(content: unknown): string {
178 if (typeof content === 'string') return content
179 if (!Array.isArray(content)) return ''
180 return content
181 .flatMap((block) => (block && typeof block === 'object' && (block as { type?: unknown }).type === 'text' ? [String((block as { text?: unknown }).text ?? '')] : []))
182 .join('\n')
183}
184
185/** The same `content` with its text replaced: a string stays a string; blocks keep their non-text blocks. */
186export function withResultText(content: unknown, text: string): unknown {
187 if (typeof content === 'string' || !Array.isArray(content)) return text
188 const out: unknown[] = []
189 let placed = false
190 for (const block of content) {
191 if (block && typeof block === 'object' && (block as { type?: unknown }).type === 'text') {
192 if (!placed) out.push({ type: 'text', text })
193 placed = true
194 } else out.push(block)
195 }
196 if (!placed) out.push({ type: 'text', text })
197 return out
198}
199