Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/bin/bash
- # `~/.claude/hooks/cache-timestamp.sh`
- # Stop hook: stamps the cache expiry time so the statusline can render a live countdown.
- # Reads the transcript JSONL, finds the last assistant turn that touched the cache
- # (read OR creation > 0), and writes (that turn's timestamp + TTL) as epoch seconds to
- # /tmp/cache_expiry_<session_id>.
- # - Creation matters because the first turn of a session only *writes* the cache
- # (cache_read is still 0) yet the cache is warm for the full TTL.
- # - Anchoring to the turn's own timestamp (when the cache was actually touched) rather
- # than "now" keeps the countdown honest on long turns, where Stop can fire minutes
- # after the API response that (re)set the TTL.
- # Change to 300 for the default 5 minute prompt cache TTL.
- CACHE_TTL_SECONDS=3600
- INPUT=$(cat)
- SESSION_ID=$(printf '%s' "$INPUT" | jq -r '.session_id // "default"')
- TRANSCRIPT=$(printf '%s' "$INPUT" | jq -r '.transcript_path // ""')
- [ -z "$TRANSCRIPT" ] || [ ! -f "$TRANSCRIPT" ] && exit 0
- # Epoch (seconds) of the last assistant turn that touched the cache, or empty if none.
- LAST_TOUCH=$(python3 -c "
- import json, datetime
- ts = ''
- with open('$TRANSCRIPT') as f:
- for line in f:
- try:
- d = json.loads(line)
- if d.get('type') == 'assistant':
- u = d.get('message', {}).get('usage', {})
- if u.get('cache_read_input_tokens', 0) + u.get('cache_creation_input_tokens', 0) > 0:
- ts = d.get('timestamp') or ts
- except:
- pass
- if ts:
- try:
- print(int(datetime.datetime.fromisoformat(ts.replace('Z', '+00:00')).timestamp()))
- except Exception:
- pass
- " 2>/dev/null)
- if [ -n "$LAST_TOUCH" ] 2>/dev/null; then
- echo $(( LAST_TOUCH + CACHE_TTL_SECONDS )) > "/tmp/cache_expiry_${SESSION_ID}"
- fi
- ##################################################
- # and then this goes in your statusline-command.sh
- ##################################################
- # Cache warmth countdown (1h TTL). Expiry is stamped by hooks/cache-timestamp.sh.
- # green: first 5min yellow: middle red: last 5min ❄: expired dim: idle
- cache_part=" \033[90mcache idle\033[0m"
- exp_file="/tmp/cache_expiry_${session}"
- if [ -f "$exp_file" ]; then
- exp=$(cat "$exp_file" 2>/dev/null)
- remain=$((${exp:-0} - $(date +%s)))
- if [ "$remain" -gt 0 ]; then
- ts=$(printf '%d:%02d' "$((remain / 60))" "$((remain % 60))")
- if [ "$remain" -gt 3300 ]; then
- c='\033[32m'
- elif [ "$remain" -gt 300 ]; then
- c='\033[33m'
- else
- c='\033[31m'
- fi
- cache_part=" ${c}cache ${ts}\033[0m"
- else
- cache_part=" ❄"
- fi
- fi
Advertisement
Add Comment
Please, Sign In to add comment