Keeps an idle session's prompt cache warm once at 50 minutes, then writes a handoff doc at 100 and pins it above the prompt.

A Claude Code mod for long conversations you walk away from. The prompt cache goes cold after 60 idle minutes, and re-caching a 300k-token conversation is expensive. cache-keeper keeps it warm once, then hands you a clean way to continue.
After Claude finishes a reply, an idle clock starts:
$TMPDIR/handoff-<session>-<time>.md./clear, and also posts them in the chat and copies the prompt to your clipboard. /clear (or open a new window) and paste.While the conversation sits idle, cache-keeper also stops Claude Code from compacting it on its own. /compact, and compactions Claude Code needs mid-turn, still run.
Any new message resets the clock, and /clear stops it. The ping and the handoff request never enter the transcript. The status line shows when the next step is due.
At the prompt of a terminal Claude Code session:
/plugin install cache-keeper --marketplace razzamatazm/cache-keeper
Answer y to add the marketplace, then press Enter to pick the user scope.
claude plugin validate .
claude plugin test .
The timings are PING_AFTER_MS and HANDOFF_AFTER_MS at the top of hooks/register.ts.
hooks/register.tsx 167 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface as Engine, Register } from 'claude-code'
3
4import type { Handoff } from '../types'
5
6// The prompt cache lapses after 60 idle minutes. One read at 50 refreshes it;
7// at 100 it is still warm from that read, so the handoff costs a cache read too.
8export const PING_AFTER_MS = 50 * 60 * 1000
9export const HANDOFF_AFTER_MS = 50 * 60 * 1000
10
11const NEXT_MARKER = '===NEXT SESSION PROMPT==='
12
13const PING_PROMPT = 'Keep-alive check. Reply with the single word: ok'
14
15const HANDOFF_PROMPT = `Write a handoff document summarising this conversation so a fresh agent with none of this context can continue the work.
16
17- Make the first line a Markdown heading, "# " then a title of six words or fewer naming the work, so the person can tell this handoff from others at a glance.
18- Then open with the goal, where things stand, and the exact next step.
19- List decisions made and why, open questions, and anything tried that failed.
20- Reference files, branches, PRs, issues, specs and commits by path or URL instead of copying their content.
21- Include a "Suggested skills" section naming the skills the next agent should call the Skill tool for.
22- Redact secrets, API keys, passwords and personal information.
23
24Reply with the Markdown document, no preamble. Then, on a line of its own, write ${NEXT_MARKER} followed by the opening prompt for the next session: two to four sentences in the user's voice, addressed to the next agent, naming the concrete next step and what done looks like for it, plus any constraint the agent must not miss. It is pasted after a line telling the agent to read the doc, so do not repeat the doc or mention reading it.`
25
26const FALLBACK_NEXT = 'Continue the work from where it leaves off.'
27const FALLBACK_TITLE = 'Handoff'
28
29const handoffAtom = atom({ plugin: 'cache-keeper', key: 'handoff' } as const, null)
30
31// Splits the fork's reply into the doc, its title and the tailored opening prompt.
32export function splitReply(reply: string) {
33 const at = reply.lastIndexOf(NEXT_MARKER)
34 const doc = (at === -1 ? reply : reply.slice(0, at)).trim()
35 const next = at === -1 ? '' : reply.slice(at + NEXT_MARKER.length).trim()
36 const title = doc.match(/^#\s+(.+)$/m)?.[1]?.trim() || FALLBACK_TITLE
37 return { doc, title, next: next || FALLBACK_NEXT }
38}
39
40type Timer = { cancel: () => void }
41
42let timer: Timer | undefined
43// True from a prompt until its turn completes; a compaction outside that window is the engine's idle one.
44let isBusy = false
45
46function stop($: Engine) {
47 timer?.cancel()
48 timer = undefined
49 $.ui.status(undefined)
50}
51
52async function at($: Engine, ms: number) {
53 return new Date((await $.clock.now()) + ms).toTimeString().slice(0, 5)
54}
55
56async function handoff($: Engine) {
57 timer = undefined
58 $.ui.status('cache-keeper: writing handoff…')
59 const reply = await $.model.fork({ prompt: HANDOFF_PROMPT })
60 if (!reply.isAnswered) {
61 $.ui.status(undefined)
62 $.ui.log(`cache-keeper: handoff not written (${reply.reason})`)
63 return
64 }
65
66 const tmp = ((await $.env.get('TMPDIR')) ?? '/tmp').replace(/\/$/, '')
67 const stamp = new Date(await $.clock.now()).toISOString().slice(0, 16).replace(/[:T]/g, '-')
68 const path = `${tmp}/handoff-${(await $.session.id()).slice(0, 8)}-${stamp}.md`
69 const { doc, title, next } = splitReply(reply.text)
70 await $.fs.write(path, doc + '\n')
71
72 const resume = `Read the handoff doc at ${path}. ${next}`
73 await update($, handoffAtom, () => ({ title, path, resume }))
74 await $.ui.copy({ text: resume }).catch(() => undefined)
75 await $.session.append({
76 message: {
77 type: 'system',
78 content: [
79 {
80 type: 'text',
81 text: [
82 `cache-keeper handoff: ${title}`,
83 `Written to ${path}`,
84 'To continue, /clear (or open a new window) and paste:',
85 '',
86 resume,
87 ].join('\n'),
88 },
89 ],
90 },
91 })
92 $.ui.status(undefined)
93 $.ui.toast(`cache-keeper: handoff ready, ${title}`)
94}
95
96async function ping($: Engine) {
97 const reply = await $.model.fork({ prompt: PING_PROMPT })
98 if (!reply.isAnswered) {
99 timer = undefined
100 $.ui.status(undefined)
101 if (reply.reason !== 'nothing-to-fork') $.ui.log(`cache-keeper: warm ping failed (${reply.reason})`)
102 return
103 }
104 const read = reply.usage.cache_read_input_tokens ?? 0
105 $.ui.log(`cache-keeper: warm ping read ${Math.round(read / 1000)}k cached tokens`, { to: 'debug' })
106 timer = $.clock.after(HANDOFF_AFTER_MS, () => void handoff($))
107 $.ui.status(`cache-keeper: handoff at ${await at($, HANDOFF_AFTER_MS)}`)
108}
109
110async function arm($: Engine) {
111 stop($)
112 timer = $.clock.after(PING_AFTER_MS, () => void ping($))
113 $.ui.status(`cache-keeper: warm ping at ${await at($, PING_AFTER_MS)}`)
114}
115
116export const register: Register = on => {
117 on('prompt.submit', ($, e, next) => {
118 isBusy = true
119 return next(e)
120 })
121
122 on('turn.start', async ($, e, next) => {
123 isBusy = true
124 stop($)
125 await update($, handoffAtom, () => null)
126 return next(e)
127 })
128
129 on('turn.complete', async ($, e, next) => {
130 const done = await next(e)
131 isBusy = false
132 await arm($)
133 return done
134 })
135
136 on('session.end', async ($, e, next) => {
137 stop($)
138 await update($, handoffAtom, () => null)
139 return next(e)
140 })
141
142 // Claude Code compacts a large conversation on its own while it sits idle. Only /compact and
143 // compactions during a turn (threshold, prompt too long) go through.
144 on('session.compact', (_$, e, next) => {
145 const isIdleCompact = !isBusy && !e.agentId && (e.trigger === 'auto' || e.trigger === 'precompute')
146 return isIdleCompact ? { skip: 'cache-keeper: no compaction while idle' } : next(e)
147 })
148
149 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
150 const handoff: Handoff | null = await read($, handoffAtom)
151 if (e.props.hasSurvey || !handoff) return next(e)
152
153 const { Box, Button, Text } = $.ui.resolve(e)
154 return (
155 <Box flexDirection="column" borderStyle="round" paddingX={1}>
156 <Text bold>cache-keeper handoff: {handoff.title}</Text>
157 <Text dimColor>{handoff.path}</Text>
158 <Text>/clear, then paste: {handoff.resume}</Text>
159 <Box>
160 <Button key="copy" label="Copy prompt" onPress={() => $.ui.copy({ text: handoff.resume }).then(() => undefined, () => undefined)} />
161 <Button key="dismiss" label="Dismiss" onPress={() => update($, handoffAtom, () => null)} />
162 </Box>
163 </Box>
164 )
165 })
166}
167types/index.d.ts 8 lines1export type Handoff = { title: string; path: string; resume: string }
2
3declare module 'claude-code' {
4 interface PluginState {
5 'cache-keeper': { handoff: Handoff | null }
6 }
7}
8