Writes a session handoff when about 5 minutes of the 1h prompt cache remain on an idle session, then, once that cache has gone cold, opens a new conversation…

A Claude Code mod that saves you from paying to re-cache a long conversation after you step away.
Claude Code keeps your conversation in a prompt cache for about an hour. If you come back after the cache has expired, your next prompt sends the whole transcript again at the full price. cache-handoff writes a short handoff note while the cache is still warm, and once the cache has gone cold it opens a fresh conversation that starts from that note.
Times count from the end of your last turn, on the usual 1 hour cache.
| When | What happens |
|---|---|
| 0 min | Your turn ends. The mod starts watching, but only if the conversation holds 50k context tokens or more. Smaller ones are cheap to re-cache, so it leaves them alone. |
| 54 min | The mod asks Claude for a handoff note (goal, progress, decisions, files, next step) while the cache is still warm. If the work is finished, Claude says so and nothing is saved. |
| 54 to 114 min | The cache is still warm. Come back now and you simply continue the full conversation; the saved note is discarded. |
| 114 min | The cache is cold. The mod runs /clear and renames the new conversation to <old name>_YYYYMMDD_HHMMSS if the old one had a name. A stamp left by an earlier handoff is replaced, so task_20261015_150400 becomes task_20261015_170432, not a longer chain. |
| 114 min | The handoff note is shown on the new conversation's screen, so you can see where the work stopped and what comes next before you type. The model does not read this copy. |
| Later | The first prompt you type there carries the handoff note in front of your text, once. |
Your old conversation is never changed. The carried handoff ends with the command to reopen it in full: claude --resume <old id>.
On the 5 minute cache tier there is not enough time to write a handoff, so the mod does nothing for that conversation: no handoff and no reminder.
Left unset, Claude Code picks the tier itself: 1 hour on a subscription within its usage limits, 5 minutes on an API key, Bedrock, Vertex or Foundry. To keep the 1 hour tier, and with it the handoff, add "promptCacheTtl": "1h" to your settings.json (or set CLAUDE_CODE_PROMPT_CACHE_TTL=1h). A 1 hour cache write costs more than a 5 minute one, so this is your call.
/plugin marketplace add pnam16/claude-mods
/plugin install cache-handoff@ame-mods
This needs a Claude Code build that supports mods (hooks modules loaded from hooks/hooks.json).
The mod runs on its own. The /handoff command controls it for the current session:
| Command | Effect |
|---|---|
/handoff | Show whether it is armed and whether a handoff is stored. |
/handoff off | Stop watching this session. |
/handoff on | Start watching again from the next turn. |
/handoff now | Open the new conversation from the stored handoff right away, for example after you resumed a session with claude --resume. |
Set coldAction in /plugin configure:
| Value | When the cache goes cold |
|---|---|
new (default) | Open a new conversation from the handoff, as described above. |
notice | Only show a reminder under the prompt; /handoff now still opens the new conversation when you want it. |
off | Do nothing at cold. The handoff is still written at 54 min and kept until your next turn. |
To try the whole cycle in a few minutes, shorten the timings before starting Claude Code:
$env:CACHE_HANDOFF_TTL_MIN = 3; $env:CACHE_HANDOFF_LEAD_MIN = 1; claude
CACHE_HANDOFF_TTL_MIN=3 CACHE_HANDOFF_LEAD_MIN=1 claude
tail and grep when they are on PATH, to find the cache tier and the conversation name.FLOW.md has the full decision flow, the API each step uses, and the live test record.
hooks/register.ts 526 lines1import type {EngineInterface, Register, Timer} from "claude-code";
2
3const MINUTE_MS = 60_000;
4const POLL_MS = 30_000;
5// A conversation smaller than this costs little to re-cache, so the mod
6// leaves it alone.
7const MIN_CONTEXT_TOKENS = 50_000;
8// Rows read back from the transcript's end when looking for the cache tier.
9const TIER_SCAN_ROWS = 400;
10// Stored handoffs nobody came back for are dropped after this long.
11const STORE_MAX_AGE_MS = 7 * 24 * 60 * MINUTE_MS;
12const STORE_PREFIX = "handoff:";
13const NO_HANDOFF = "NO_HANDOFF";
14
15const HANDOFF_PROMPT = [
16 "This session has been idle and its prompt cache is about to expire.",
17 "Write a handoff note so a fresh session can resume this work without the transcript.",
18 "Cover: the goal, what is done, decisions made and why, files and paths touched,",
19 "open questions, and the exact next step. Plain Markdown, at most 400 words, no preamble.",
20 `If the work is finished and nothing is left to resume, reply with exactly ${NO_HANDOFF} and nothing else.`,
21].join(" ");
22
23type CacheTier = "1h" | "5m" | "unknown";
24type ColdAction = "new" | "notice" | "off";
25type StoredHandoff = {text: string; writtenAt: number; cwd: string};
26
27// The settings: coldAction from /plugin configure, the timings from the
28// environment so a live test can shorten them.
29const config = {
30 cacheTtlMs: 60 * MINUTE_MS,
31 coldAction: "new" as ColdAction,
32 leadMs: 6 * MINUTE_MS,
33};
34
35// The main loop's idle clock; the module's own, so a reload starts it over.
36const idle = {
37 // The handoff fork read the cache and so refreshed it: the cache goes cold
38 // one TTL after the later of this and the last turn.
39 forkedAt: undefined as number | undefined,
40 isArmed: false,
41 isColdHandled: false,
42 isDisabled: false,
43 // The fork said the work is finished: nothing to do at cold.
44 isFinished: false,
45 isInTurn: false,
46 isNoticeShown: false,
47 // A prompt typed while the handoff forks: turn.start cannot tell that turn
48 // from the fork's own, so prompt.submit marks it.
49 isPromptedWhileWriting: false,
50 isWriting: false,
51 lastTurnEndAt: undefined as number | undefined,
52 // The handoff the next typed prompt of the new conversation carries, and
53 // the store key it came from.
54 pendingHandoff: undefined as string | undefined,
55 pendingKey: undefined as string | undefined,
56 transcriptPath: undefined as string | undefined,
57};
58
59let poller: Timer | undefined;
60let lastPollAt = 0;
61
62const storeKey = (sessionId: string) => `${STORE_PREFIX}${sessionId}`;
63
64const readStored = async (
65 $: EngineInterface,
66 key: string,
67): Promise<StoredHandoff | undefined> => {
68 const value = (await $.store.get(key)) as Partial<StoredHandoff> | undefined;
69 return typeof value?.text === "string" && typeof value.writtenAt === "number"
70 ? {
71 cwd: String(value.cwd ?? ""),
72 text: value.text,
73 writtenAt: value.writtenAt,
74 }
75 : undefined;
76};
77
78const pruneStore = async ($: EngineInterface, now: number) => {
79 for (const key of await $.store.keys()) {
80 if (!key.startsWith(STORE_PREFIX)) continue;
81 const stored = await readStored($, key);
82 if (stored === undefined || now - stored.writtenAt > STORE_MAX_AGE_MS)
83 await $.store.delete(key);
84 }
85};
86
87const minutesToMs = (value: string | undefined, fallbackMs: number) => {
88 const minutes = Number(value);
89 return value !== undefined && Number.isFinite(minutes) && minutes > 0
90 ? minutes * MINUTE_MS
91 : fallbackMs;
92};
93
94// The tier of the newest main-thread cache write; a turn that only read the
95// cache writes nothing, so older rows are searched until one wrote.
96const cacheTier = (transcript: string): CacheTier => {
97 const rows = transcript.split("\n");
98 for (
99 let i = rows.length - 1;
100 i >= 0 && i >= rows.length - TIER_SCAN_ROWS;
101 i--
102 ) {
103 const row = rows[i];
104 if (row === undefined || !row.includes('"cache_creation"')) continue;
105 try {
106 const entry = JSON.parse(row);
107 if (entry.type !== "assistant" || entry.isSidechain) continue;
108 const written = entry.message?.usage?.cache_creation;
109 if (written?.ephemeral_1h_input_tokens > 0) return "1h";
110 if (written?.ephemeral_5m_input_tokens > 0) return "5m";
111 } catch {
112 // a row still being written
113 }
114 }
115 return "unknown";
116};
117
118const homeDir = async ($: EngineInterface) => {
119 return (await $.env.get("USERPROFILE")) ?? (await $.env.get("HOME")) ?? "";
120};
121
122// classic.Stop may not reach this plugin (an organization's managed settings
123// keep it from installed plugins), so the path is also derived the way Claude
124// Code names its project folders.
125const transcriptPath = async ($: EngineInterface) => {
126 if (idle.transcriptPath !== undefined) return idle.transcriptPath;
127 const project = (await $.session.cwd()).replace(/[^a-zA-Z0-9]/g, "-");
128 return `${await homeDir($)}/.claude/projects/${project}/${await $.session.id()}.jsonl`;
129};
130
131const readTier = async ($: EngineInterface): Promise<CacheTier> => {
132 const path = await transcriptPath($);
133 // A long transcript is past the 4 MiB that $.fs.read takes, so read its tail.
134 try {
135 const tail = await $.process.run([
136 "tail",
137 "-n",
138 String(TIER_SCAN_ROWS),
139 path,
140 ]);
141 if (tail.exitCode === 0) return cacheTier(tail.stdout);
142 } catch {
143 // no tail on PATH
144 }
145 try {
146 return cacheTier(String(await $.fs.read(path)));
147 } catch {
148 return "unknown";
149 }
150};
151
152// The name /rename last gave this session; /rename writes it to the
153// transcript as a custom-title row, anywhere in the file.
154const sessionTitle = async ($: EngineInterface) => {
155 try {
156 const found = await $.process.run([
157 "grep",
158 "-F",
159 '"type":"custom-title"',
160 await transcriptPath($),
161 ]);
162 const rows = found.stdout.trim().split("\n");
163 const title = JSON.parse(rows[rows.length - 1] ?? "").customTitle;
164 return typeof title === "string" && title.trim() !== ""
165 ? title.trim()
166 : undefined;
167 } catch {
168 return undefined;
169 }
170};
171
172const writeHandoff = async ($: EngineInterface, now: number) => {
173 const forked = await $.model.fork({prompt: HANDOFF_PROMPT});
174 if (!forked.isAnswered) {
175 $.ui.log(`cache-handoff: no handoff written (${forked.reason})`);
176 return;
177 }
178 if (idle.isPromptedWhileWriting) {
179 // The person came back while the fork ran: the handoff is moot, and their
180 // own turn arms the next one.
181 idle.isColdHandled = true;
182 $.ui.log("cache-handoff: the person is back, no handoff kept");
183 return;
184 }
185 idle.forkedAt = now;
186 if (forked.text.trim() === NO_HANDOFF) {
187 idle.isFinished = true;
188 $.ui.log("cache-handoff: the work is finished, no handoff kept");
189 return;
190 }
191 const stored: StoredHandoff = {
192 cwd: await $.session.cwd(),
193 text: forked.text,
194 writtenAt: now,
195 };
196 await $.store.set(storeKey(await $.session.id()), stored);
197 $.ui.toast(`Cache handoff written at ${clockTime(now)}.`);
198};
199
200const pad = (n: number) => String(n).padStart(2, "0");
201
202const clockTime = (ms: number) => {
203 const at = new Date(ms);
204 return `${pad(at.getHours())}:${pad(at.getMinutes())}`;
205};
206
207const dateTime = (ms: number) => {
208 const at = new Date(ms);
209 return `${at.getFullYear()}-${pad(at.getMonth() + 1)}-${pad(at.getDate())} ${clockTime(ms)}`;
210};
211
212// Appended to a renamed conversation's title: YYYYMMDD_HHMMSS, no spaces.
213const titleStamp = (ms: number) => {
214 const at = new Date(ms);
215 const date = `${at.getFullYear()}${pad(at.getMonth() + 1)}${pad(at.getDate())}`;
216 return `${date}_${pad(at.getHours())}${pad(at.getMinutes())}${pad(at.getSeconds())}`;
217};
218
219// The title without the stamps earlier handoffs appended, in this format or
220// 0.4.0's "_YYYY-MM-DD HH:MM", so a conversation handed off again gets one
221// fresh stamp instead of a growing chain.
222const TRAILING_STAMP = /(?:_\d{8}_\d{6}|[_ ]\d{4}-\d{2}-\d{2} \d{2}:\d{2})$/;
223
224const baseTitle = (title: string) => {
225 let base = title;
226 while (TRAILING_STAMP.test(base)) base = base.replace(TRAILING_STAMP, "");
227 return base;
228};
229
230const coldNotice = (coldAt: number, stored: StoredHandoff | undefined) => {
231 const cold = `Prompt cache cold since ${clockTime(coldAt)}`;
232 if (stored === undefined) {
233 return `${cold}. The next prompt re-caches the whole transcript; /clear first to start lean.`;
234 }
235 return `${cold}. Handoff written at ${clockTime(stored.writtenAt)}; /handoff now opens a new conversation from it.`;
236};
237
238const showNotice = ($: EngineInterface, text: string) => {
239 // The status line stays until the person is back; a toast of the same
240 // text would only repeat it.
241 idle.isNoticeShown = true;
242 $.ui.status(text);
243};
244
245// Swaps the cold conversation for a new one that the handoff opens, named
246// after the old one, so the next prompt caches the handoff, not the transcript.
247const startFromHandoff = async (
248 $: EngineInterface,
249 key: string,
250 stored: StoredHandoff,
251 now: number,
252) => {
253 const oldId = await $.session.id();
254 const title = await sessionTitle($);
255 await $.command.run({command: "clear"});
256 idle.transcriptPath = undefined;
257 idle.lastTurnEndAt = undefined;
258 idle.isArmed = false;
259 idle.pendingKey = key;
260 idle.pendingHandoff = [
261 `<handoff from="session ${oldId}" written="${dateTime(stored.writtenAt)}">`,
262 stored.text,
263 "</handoff>",
264 `The previous conversation is still there: claude --resume ${oldId}`,
265 ].join("\n");
266 if (title !== undefined) {
267 // The new conversation is already open and carries the handoff, so a
268 // refused rename only leaves it unnamed.
269 try {
270 await $.command.run({
271 args: `${baseTitle(title)}_${titleStamp(now)}`,
272 command: "rename",
273 });
274 } catch (error) {
275 $.ui.log(
276 `cache-handoff: rename refused, the new conversation stays unnamed: ${errorText(error)}`,
277 );
278 }
279 }
280 // The cleared screen is otherwise blank: show the person the handoff as a
281 // notice the model never reads, since their first prompt already carries it.
282 try {
283 const notice = [
284 `Handoff from the previous conversation, written ${dateTime(stored.writtenAt)}:`,
285 "",
286 stored.text,
287 "",
288 `Full conversation: claude --resume ${oldId}`,
289 ].join("\n");
290 await $.session.append({
291 message: {content: [{text: notice, type: "text"}], type: "system"},
292 });
293 } catch (error) {
294 $.ui.log(`cache-handoff: could not show the handoff: ${errorText(error)}`);
295 }
296 showNotice(
297 $,
298 `New conversation started from the handoff of ${clockTime(stored.writtenAt)}; your next prompt carries it.`,
299 );
300};
301
302const handoffIfDue = async ($: EngineInterface, now: number) => {
303 if (
304 !idle.isArmed ||
305 now - (idle.lastTurnEndAt ?? now) < config.cacheTtlMs - config.leadMs
306 )
307 return;
308 // Disarm before forking: the fork reads the cache and so refreshes its TTL,
309 // and only a real turn may arm the next handoff.
310 idle.isArmed = false;
311 // Past the TTL (the machine slept through the lead) the cache is already
312 // cold: a fork would re-cache the whole transcript, so the notice comes alone.
313 if (now - (idle.lastTurnEndAt ?? now) >= config.cacheTtlMs) {
314 $.ui.log("cache-handoff: cache already cold, no handoff written");
315 return;
316 }
317 idle.isWriting = true;
318 idle.isPromptedWhileWriting = false;
319 try {
320 // The turn's end may have come before its cache write reached the
321 // transcript, so the tier is read again here.
322 if ((await readTier($)) === "5m") {
323 idle.isColdHandled = true;
324 $.ui.log("cache-handoff: 5 minute cache tier, no handoff written");
325 return;
326 }
327 await writeHandoff($, now);
328 } finally {
329 idle.isWriting = false;
330 }
331};
332
333// After the handoff step, so the cold time counts the fork's refresh.
334const actIfCold = async ($: EngineInterface, now: number) => {
335 if (
336 config.coldAction === "off" ||
337 idle.isFinished ||
338 idle.isColdHandled ||
339 idle.isArmed
340 )
341 return;
342 if (idle.lastTurnEndAt === undefined) return;
343 const coldAt =
344 Math.max(idle.lastTurnEndAt, idle.forkedAt ?? 0) + config.cacheTtlMs;
345 if (now < coldAt) return;
346 idle.isColdHandled = true;
347 const key = storeKey(await $.session.id());
348 const stored = await readStored($, key);
349 if (config.coldAction === "new" && stored !== undefined) {
350 try {
351 await startFromHandoff($, key, stored, now);
352 return;
353 } catch (error) {
354 $.ui.log(
355 `cache-handoff: new conversation failed, showing the notice: ${errorText(error)}`,
356 );
357 }
358 }
359 showNotice($, coldNotice(coldAt, stored));
360};
361
362const errorText = (error: unknown) =>
363 error instanceof Error ? error.message : String(error);
364
365const poll = async ($: EngineInterface) => {
366 const now = await $.clock.now();
367 lastPollAt = now;
368 if (idle.isInTurn || idle.isWriting || idle.lastTurnEndAt === undefined)
369 return;
370 await handoffIfDue($, now);
371 await actIfCold($, now);
372};
373
374// Starts the poll, or starts it again when it has gone quiet: no session.start
375// fires after /clear, so a turn is the next chance to notice.
376const ensurePoller = async ($: EngineInterface) => {
377 const now = await $.clock.now();
378 if (poller !== undefined && now - lastPollAt < 3 * POLL_MS) return;
379 poller?.cancel();
380 lastPollAt = now;
381 poller = $.clock.every(POLL_MS, () => void poll($));
382};
383
384const handoffCommand = async ($: EngineInterface, args: string) => {
385 const word = args.trim().toLowerCase();
386 if (word === "off") {
387 idle.isDisabled = true;
388 idle.isArmed = false;
389 return "cache-handoff is off for this session.";
390 }
391 if (word === "on") {
392 idle.isDisabled = false;
393 return "cache-handoff is on; it arms when the next turn ends.";
394 }
395 const key = storeKey(await $.session.id());
396 const stored = await readStored($, key);
397 if (word === "now") {
398 if (stored === undefined) return "No handoff is stored for this session.";
399 // $.command.run waits for the session to be idle, which it is not while
400 // this command runs, so the switch happens just after.
401 $.clock.after(0, () => {
402 void (async () => {
403 try {
404 idle.isColdHandled = true;
405 await startFromHandoff($, key, stored, await $.clock.now());
406 } catch (error) {
407 $.ui.toast(
408 `cache-handoff: could not open the new conversation: ${errorText(error)}`,
409 );
410 }
411 })();
412 });
413 return `Opening a new conversation from the handoff of ${clockTime(stored.writtenAt)}.`;
414 }
415 const state = idle.isDisabled
416 ? "off"
417 : idle.isArmed
418 ? "armed"
419 : "waiting for the next turn";
420 const handoff =
421 stored === undefined
422 ? "no handoff stored"
423 : `handoff stored at ${clockTime(stored.writtenAt)}`;
424 return `cache-handoff: ${state}, ${handoff}, coldAction ${config.coldAction}. Usage: /handoff off | on | now`;
425};
426
427export const register: Register = (on, options) => {
428 const action = options.coldAction;
429 // 0.3.0 called the default new-session.
430 config.coldAction = action === "notice" || action === "off" ? action : "new";
431
432 on("session.start", async ($, e, next) => {
433 config.cacheTtlMs = minutesToMs(
434 await $.env.get("CACHE_HANDOFF_TTL_MIN"),
435 60 * MINUTE_MS,
436 );
437 config.leadMs = minutesToMs(
438 await $.env.get("CACHE_HANDOFF_LEAD_MIN"),
439 6 * MINUTE_MS,
440 );
441 await $.command.register({
442 argumentHint: "off | on | now",
443 description:
444 "Cache handoff: off, on, or now to open a new conversation from the stored handoff",
445 name: "handoff",
446 });
447 await ensurePoller($);
448 const now = await $.clock.now();
449 await pruneStore($, now);
450 // A session resumed after Claude Code closed before its cache went cold.
451 const stored = await readStored($, storeKey(await $.session.id()));
452 if (stored !== undefined) {
453 showNotice(
454 $,
455 `A handoff from ${dateTime(stored.writtenAt)} is stored; /handoff now opens a new conversation from it.`,
456 );
457 }
458 return next(e);
459 });
460
461 on("command.run", {command: "handoff"}, async ($, e) => ({
462 text: await handoffCommand($, e.args),
463 }));
464
465 // The first prompt the person types in the new conversation opens with the
466 // handoff; a notification or a peer's message does not take it.
467 on("prompt.submit", async ($, e, next) => {
468 if (idle.isWriting && !e.isMeta && e.origin.kind === "composer")
469 idle.isPromptedWhileWriting = true;
470 if (
471 idle.pendingHandoff === undefined ||
472 e.command !== undefined ||
473 e.isMeta ||
474 e.origin.kind !== "composer"
475 ) {
476 return next(e);
477 }
478 const text = `${idle.pendingHandoff}\n\n${e.text}`;
479 if (idle.pendingKey !== undefined) await $.store.delete(idle.pendingKey);
480 idle.pendingHandoff = undefined;
481 idle.pendingKey = undefined;
482 return next({...e, text});
483 }).catch((_$, e, next) => next(e));
484
485 // Turns raised while the handoff forks are the mod's own, never the person's.
486 on("turn.start", async ($, e, next) => {
487 if (e.agentId === undefined && !idle.isWriting) {
488 idle.isInTurn = true;
489 // The person is back in this conversation: its handoff is moot.
490 if (idle.pendingHandoff === undefined)
491 await $.store.delete(storeKey(await $.session.id()));
492 if (idle.isNoticeShown) {
493 idle.isNoticeShown = false;
494 $.ui.status(undefined);
495 }
496 }
497 return next(e);
498 });
499
500 on("turn.complete", async ($, e, next) => {
501 if (e.agentId === undefined && !idle.isWriting) {
502 idle.isInTurn = false;
503 idle.lastTurnEndAt = await $.clock.now();
504 idle.forkedAt = undefined;
505 idle.isFinished = false;
506 const tokens = (await $.session.usage()).context.tokens ?? 0;
507 // On the 5m tier the cache is cold long before a handoff could be
508 // written, so the mod sits that gap out too.
509 const isWatched =
510 !idle.isDisabled &&
511 tokens >= MIN_CONTEXT_TOKENS &&
512 (await readTier($)) !== "5m";
513 // A gap the mod sits out ends quietly, with no notice at cold either.
514 idle.isColdHandled = !isWatched;
515 idle.isArmed = isWatched;
516 await ensurePoller($);
517 }
518 return next(e);
519 });
520
521 on("classic.Stop", (_$, e, next) => {
522 idle.transcriptPath = e.transcript_path;
523 return next(e);
524 }).catch((_$, e, next) => next(e));
525};
526