Skip to content
Back to search

cachebeat

A tiny Claude Code skill that keeps your prompt cache warm during idle sessions, so your next message reads from cache instead of paying full price.

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/arahim3--cachebeat/badge.svg)](/listings/arahim3--cachebeat)

HTML

<a href="/listings/arahim3--cachebeat"><img src="/api/listings/arahim3--cachebeat/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

User-level (all projects):

mkdir -p ~/.claude/skills/cachebeat
cp SKILL.md beat.sh ~/.claude/skills/cachebeat/

Or project-level: copy both files into `<your-project>/.claude/skills/cachebeat/`.

That's the whole setup — two small files: the skill, and the watcher script its hook runs. Then in any Claude Code session, type `/cachebeat` and you're done. There is nothing to approve: hooks don't ask for permission, and Claude never runs a command for it.

Requirements: a recent Claude Code (tested on 2.1.288) with hooks enabled — skill-frontmatter hooks and `asyncRewake` are standard features, but an organization policy that disables hooks (`disableAllHooks`, `allowManagedHooksOnly`) also disables cachebeat.

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

SKILL.md · Manifest · 59 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. ---
  2. name: cachebeat
  3. description: Keep the Anthropic prompt cache warm by firing a tiny heartbeat only after N minutes of true session inactivity (any exchange resets the clock), so the next real turn reads the conversation at cached price / cached quota instead of a full uncached re-read. The heartbeat is a background Stop hook this skill registers (asyncRewake) - it re-arms itself after every turn, with no tool calls and no permission prompts. Use when the session may sit idle (training runs, CI, downloads, the user stepping away) longer than the cache TTL. Args - idle threshold in minutes (default 50), optional max hours (default 8), or "stop".
  4. hooks:
  5. Stop:
  6. - hooks:
  7. - type: command
  8. command: 'sh "${CLAUDE_PLUGIN_ROOT}/beat.sh"'
  9. asyncRewake: true
  10. timeout: 90000
  11. rewakeMessage: "[cachebeat]"
  12. rewakeSummary: "cachebeat heartbeat"
  13. SessionEnd:
  14. - hooks:
  15. - type: command
  16. command: 'sh "${CLAUDE_PLUGIN_ROOT}/beat.sh"'
  17. timeout: 5
  18. ---
  19. # cachebeat — prompt-cache keepalive heartbeat
  20. ## What you do when invoked
  21. `/cachebeat [minutes] [hours]` arms the heartbeat; `/cachebeat stop` turns it off. **There is nothing
  22. for you to run.** The heartbeat is the Stop hook in this skill's frontmatter: Claude Code registered it
  23. when this skill loaded, and when this turn ends the hook reads these same arguments from the transcript.
  24. - `minutes`: idle threshold — how long the session may sit silent before a beat. Default **50**,
  25. clamped to **5–55** (past ~55 the 1-hour cache TTL can lapse before a beat lands).
  26. - `hours`: auto-stop deadline. Default **8**, clamped to 1–24 — the abandoned-session guard: every beat
  27. costs a small cached-price request, so a forgotten heartbeat must end itself.
  28. - `stop` (or `off`): disarm.
  29. Reply in **ONE line** and call no tools — arming: the idle threshold, the auto-stop time, and that
  30. `/cachebeat stop` ends it sooner; stopping: that it is off. Nothing more.
  31. If the user asks in plain words to start, change or stop the heartbeat, invoke this skill (Skill tool)
  32. with the matching arguments: the hook only reads `/cachebeat` invocations.
  33. ## When the heartbeat wakes you
  34. A system reminder starting with `[cachebeat]` (on some Claude Code versions: "Stop hook blocking error …"
  35. followed by the same text) comes from the hook. It is not the user, and it is not an error.
  36. - **"idle heartbeat …"** — reply with exactly `.` and nothing else: no tools, no summary, no status. The
  37. wake-up itself already re-read the conversation from cache, which is the whole point, and every token
  38. you add is re-read by every later request. If a real task of yours is mid-flight, ignore the reminder
  39. and carry on with the task instead.
  40. - **It stopped itself, or reached its auto-stop time** — tell the user in one short line. Do not re-arm
  41. unless they ask.
  42. ## Rules
  43. - Never start `beat.sh` yourself, and never "re-arm" after a beat: the next turn's Stop hook does that.
  44. - If the user reports beats arriving but bills still showing uncached input, their session likely has
  45. the short (5-minute) cache TTL, where no practical heartbeat helps — stop it. (The hook also checks
  46. each beat's own usage record and stops itself in that case.)
  47. - This skill changes nothing about the work itself; it pays ~10% cached-read price per beat to avoid
  48. paying full price once. If the user does not plan to return to the session, advise stopping it.
README.md · README · 220 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. <div align="center">
  2. # cachebeat 🫀
  3. **Stop paying full price to say "I'm back" to your own Claude Code session.**
  4. </div>
  5. A tiny Claude Code skill that keeps your prompt cache warm while a session sits idle — so your
  6. next message reads the conversation from cache instead of re-billing it from scratch. Anthropic
  7. bills cache reads at **0.1× the input rate** (published ratio, every model) — an uncached return
  8. costs ~10× more.
  9. **This is not just an API-billing thing.** On Pro/Max subscriptions the same accounting drains
  10. your **5-hour window and weekly usage limit**: come back to a long session cold, and one "how's
  11. it going?" can eat a visible chunk of your quota that a warm cache would barely have touched.
  12. ## Why this exists
  13. It was born in a real session: a **multi-day model fine-tune babysat by Claude** — training runs
  14. that took hours, checkpoints landing overnight, a human who occasionally sleeps. Every time the
  15. session went quiet for longer than the cache window, the next "how's it going?" re-billed the
  16. **entire conversation history at full input price**. On a long, tool-heavy session that's hundreds
  17. of thousands of tokens, re-billed every single time you stepped away too long.
  18. One inactivity-triggered heartbeat later, it didn't.
  19. ## The problem, concretely
  20. Claude is stateless: your whole conversation is re-sent to the API on every turn. Anthropic's
  21. prompt caching makes this affordable — cached input costs **~10 %** of the normal rate — but the
  22. cache expires after a TTL (up to 1 hour on long-TTL sessions). The failure mode:
  23. 1. You run something long (training, CI, a big download) or just step away.
  24. 2. The session is silent past the TTL. The cache dies.
  25. 3. You come back, type one line — and the **entire history is re-processed uncached**: ~10× the
  26. tokens a cached read would have counted. On the API that's money; on a subscription that's
  27. your 5-hour window and weekly limit draining for nothing.
  28. Do that a few times a day on a long-running session and the "idle tax" quietly becomes the
  29. biggest line in your bill — or the reason you hit your usage limit by mid-week.
  30. ## The fix
  31. `/cachebeat` arms a silent background watcher inside your session. **It's an inactivity timer, not a
  32. metronome**: it fires only when the session has been truly silent for N minutes — any message, reply,
  33. or answered background event already refreshed the cache and resets the clock. On firing, Claude
  34. wakes, answers with a single `.`, and the cache TTL restarts. The next timer starts by itself.
  35. **Break-even math:** going cold once costs as much as **ten** heartbeats. Come back to the session
  36. even once and the heartbeat has paid for itself many times over — and the bigger the session, the
  37. bigger the absolute savings (the 10× ratio is flat; the token count isn't).
  38. It also kills itself after a deadline (default 8 h), so an abandoned session doesn't drip-bill forever.
  39. > **Note (Oct 2026):** Claude Code 2.1.285 put a lifetime on background shell commands (30 min by
  40. > default, 2 h at most) and tells Claude not to restart one that hit the 2 h cap. The previous
  41. > cachebeat ran as exactly such a command, so it was killed before its first 50-minute beat (or at
  42. > 2 h on a busy session) and never came back ([#1](https://github.com/ARahim3/cachebeat/issues/1)).
  43. > cachebeat now runs as an **`asyncRewake` Stop hook** declared in the skill itself: no lifetime cap,
  44. > no re-arm tool call, no permission prompt, and one request per beat instead of two. **Upgrading?**
  45. > Copy both files again (see [Install](#install)), then run `/cachebeat` once in each session you want
  46. > covered. A session still running the old instructions stops at its next re-arm instead of looping.
  47. ## Install
  48. User-level (all projects):
  49. ```bash
  50. mkdir -p ~/.claude/skills/cachebeat
  51. cp SKILL.md beat.sh ~/.claude/skills/cachebeat/
  52. ```
  53. Or project-level: copy both files into `<your-project>/.claude/skills/cachebeat/`.
  54. That's the whole setup — two small files: the skill, and the watcher script its hook runs. Then in any
  55. Claude Code session, type `/cachebeat` and you're done. There is nothing to approve: hooks don't ask
  56. for permission, and Claude never runs a command for it.
  57. Requirements: a recent Claude Code (tested on 2.1.288) with hooks enabled — skill-frontmatter hooks and
  58. `asyncRewake` are standard features, but an organization policy that disables hooks
  59. (`disableAllHooks`, `allowManagedHooksOnly`) also disables cachebeat.
  60. ## Usage
  61. ```
  62. /cachebeat # fire after 50 min of inactivity, auto-stop after 8 h
  63. /cachebeat 40 # custom idle threshold in minutes (clamped to 5–55)
  64. /cachebeat 40 4 # custom threshold + auto-stop after 4 h
  65. /cachebeat stop # stop it
  66. ```
  67. You can also just ask Claude ("keep the cache warm while this trains") — it invokes the skill for you.
  68. ## Verifying it's working
  69. You don't have to take it on faith — you can watch the cache stay warm.
  70. - **The heartbeat itself.** When a beat fires you'll see a `⏺ cachebeat heartbeat` line and Claude
  71. answering `.` — proof the timer is alive and resetting the TTL. If instead Claude tells you
  72. cachebeat stopped itself, the beat fired on schedule but the cache had *still* expired: your
  73. session's TTL is too short for any heartbeat to bridge.
  74. - **The status line.** Claude Code's token readout looks like `tok:312.0k/0.0k` — *total / served
  75. from cache*. When you return to an idle session, the second number should be a large fraction of
  76. the first (warm). If it reads `…/0.0k`, the whole context was re-read uncached — the cache had
  77. died. With cachebeat armed on a long-TTL session, it should stay warm across your idle gaps.
  78. - **The transcript (exact numbers).** Every assistant reply records what it cost. Run this inside the
  79. session (prefix a shell command with `!`):
  80. ```bash
  81. F=$(ls ~/.claude/projects/*/"$CLAUDE_CODE_SESSION_ID".jsonl 2>/dev/null | head -1)
  82. echo "cache_read: $(tail -n 400 "$F" | grep -oE '"cache_read_input_tokens":[0-9]+' | tail -1 | grep -oE '[0-9]+')"
  83. echo "cache_creation: $(tail -n 400 "$F" | grep -oE '"cache_creation_input_tokens":[0-9]+' | tail -1 | grep -oE '[0-9]+')"
  84. ```
  85. A **warm** turn shows a big `cache_read` and a tiny `cache_creation`. A **cold** turn is the
  86. reverse — a large `cache_creation` means the context was rebuilt from scratch at full price.
  87. ## How it works
  88. The skill's frontmatter declares a **Stop hook** with `asyncRewake: true`. Claude Code registers it when
  89. you invoke `/cachebeat`, and from then on runs [`beat.sh`](beat.sh) **in the background at the end of
  90. every turn**. Each run is one inactivity timer. If the hook exits with code 2, Claude Code wakes Claude
  91. and shows it what the hook printed:
  92. 1. A turn ends → the Stop hook starts a timer (and any older timer notices and exits).
  93. 2. Every 30 s the timer checks **when the last real model response was written** to the session
  94. transcript (`~/.claude/projects/<slug>/<session-id>.jsonl`). A new response resets the clock.
  95. 3. After N idle minutes it prints a one-line heartbeat note and exits 2 → Claude wakes, reads the
  96. conversation from cache (that read *is* the heartbeat), and answers `.`.
  97. 4. That reply ends a turn → step 1. Claude never re-arms anything.
  98. The heart of it:
  99. ```bash
  100. while :; do
  101. sleep 30
  102. [ "$(cat "$S.pid")" = $$ ] || exit 0 # a newer turn started a newer timer
  103. SIG=$(sig "$(last_resp)") # the last real model response
  104. [ "$SIG" != "$PREV" ] && { PREV=$SIG; LAST=$NOW; } # new request -> reset the clock
  105. IDLE=$((NOW - LAST))
  106. [ "$IDLE" -ge $((N*60)) ] && { echo "idle heartbeat …" >&2; exit 2; } # exit 2 wakes Claude
  107. done
  108. ```
  109. | exit | meaning | what Claude does |
  110. |---|---|---|
  111. | `0` | nothing to say: not armed, stopped, superseded, or the cache is already cold | nothing — no wake-up |
  112. | `2` + "idle heartbeat" | the session sat idle for the threshold | replies `.` (the reply's turn starts the next timer) |
  113. | `2` + "stopped itself" | the last beat *still* came back uncached — TTL too short to bridge | tells you, stays off |
  114. | `2` + "auto-stop" | the deadline passed | tells you, stays off |
  115. Details that keep it honest:
  116. - **Arguments without a tool call.** The hook reads them from the newest `/cachebeat` in the transcript
  117. (typed, or Claude's own Skill call) and keeps them, with the auto-stop deadline, in
  118. `$TMPDIR/cachebeat-<session-id>`. Invoking `/cachebeat` again re-arms with the new values; `/cachebeat
  119. stop` disarms. The match is on raw JSON structure, so a transcript that merely *quotes* those lines
  120. (say, while debugging cachebeat) can't arm it.
  121. - **Only real requests count as activity.** Claude Code also appends lines without any model request —
  122. `queue-operation` entries when a Workflow's agents finish background commands, `mode`,
  123. `away_summary`, its own `"model":"<synthetic>"` notices for usage limits and API errors. Those don't
  124. refresh the cache, so they don't reset the clock (they used to, and a busy Workflow could keep the
  125. old watcher from ever firing while the cache died).
  126. - **Never mid-tool.** While a tool is still running (or waiting on a permission prompt), the timer
  127. doesn't fire: a wake-up couldn't be delivered before the tool returns anyway.
  128. - **Every beat is audited.** After a beat, the next timer reads that beat's own usage record. A large
  129. `cache_creation` (or 5-minute-TTL cache writes) means the cache had already expired, so it stops
  130. and tells you instead of pretending to help.
  131. - **No beat into a cold cache.** If the machine slept past the TTL, the cache is already gone and a beat
  132. would only pay to rebuild it — the timer stands down until you're back.
  133. - **No beat into the wrong conversation.** A wake-up goes to the Claude Code process, not to a session,
  134. so the skill also registers a `SessionEnd` hook: `/clear`, `/resume` and exit disarm the timer before
  135. it can beat into the next conversation. If Claude Code dies outright, the timer notices its parent is
  136. gone and exits.
  137. - **The hook's `timeout` matters.** Claude Code kills an `asyncRewake` hook at its `timeout` — 10 minutes
  138. unless set — so the skill sets `timeout: 90000` (25 h, past the longest deadline). Without it every
  139. timer would die before a 50-minute beat, which is the old failure all over again.
  140. - **Nothing on stderr but the note.** On exit 2, Claude sees everything the hook wrote to stderr; the
  141. script sends all other stderr to `/dev/null` so stray errors can't leak into the conversation.
  142. > **Why a hook, and not a background command, a monitor, or a cron job?** The wake-up needs something
  143. > that can stay silent for ~50 minutes and then make Claude take a turn:
  144. >
  145. > | mechanism | lifetime | why not |
  146. > |---|---|---|
  147. > | Monitor | ≤ 30 min | every expiry wakes Claude: forced ~28-min metronome, idle or not |
  148. > | background Bash (`run_in_background`) | 30 min default, 2 h max (since 2.1.285) | killed before a 50-min beat unless re-armed with `timeout`; at the 2 h cap Claude is told not to restart it |
  149. > | CronCreate | 7 days | wall-clock metronome; under 60 min apart means ≥ 2 beats an hour, +10% jitter, even while you're chatting |
  150. > | **Stop hook + `asyncRewake`** | hook's own `timeout` (we set 25 h) | — re-armed by Claude Code itself on every turn end; no tool call, no permission prompt |
  151. ## Compatibility
  152. Linux, WSL2, and macOS. The watcher uses only portable tools — `tail`, `grep`, `sed`, `cut`, `tr`,
  153. `date +%s` — with no `stat`, no `jq` and no timestamp parsing, so there are no GNU-vs-BSD differences to
  154. trip over (tested with bash-as-`sh`, dash and ksh). Native Windows (non-WSL) is untested — the watcher
  155. assumes a POSIX shell.
  156. It reads Claude Code's session transcript (the path comes from the hook's input) — an internal format
  157. rather than a documented API, so a future Claude Code change could require an update here.
  158. ## Honest caveats
  159. - **Only helps on sessions with the long (1-hour) cache TTL.** Some sessions run a 5-minute TTL; no
  160. practical heartbeat can bridge that. cachebeat detects it on the first beat and stops itself.
  161. - Each beat costs one small cached-read request plus a few output tokens, and each beat's exchange is
  162. appended to the context that later requests re-read. Cheap, not free.
  163. - **Resuming a session** (`claude --resume`) doesn't bring the hook back — run `/cachebeat` again.
  164. - If a beat's own request fails (API error, usage limit), the timer is not restarted until your next
  165. message — nothing can warm the cache while requests fail anyway.
  166. - A wake-up can't be delivered while a long *foreground* tool is running (e.g. a subagent Claude is
  167. waiting on); if that takes over an hour, the cache expires regardless.
  168. - The idle threshold must stay **under** the TTL — the default 50 min leaves ~10 min of margin
  169. against the 1-hour TTL.
  170. - If you're *not* coming back to the session, any heartbeat is pure waste. That's what the
  171. auto-stop deadline is for.
  172. ## License
  173. MIT — do whatever you like with it.

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.