Compacts between turns when the context is full enough, sooner after a commit, PR, approved plan or finished todo list, or when the prompt cache is about to go…

Live panes, prompt bands, status line entries, toasts, and hooks for Claude Code, each shipped as a plugin.
/plugin marketplace add tartinerlabs/claude-code-mods
/plugin install <mod> --marketplace tartinerlabs/claude-code-mods
| | Mod | Where it shows | In one line | | :-: | --- | --- | --- | | ⏸ | auto-resume | Status line, toast | Picks a turn back up once a usage limit resets | | 🏷 | auto-session-name | Session title | Names each session from its first prompt and keeps the name current as the work moves on | | ⏱ | cache-clock | Band above the prompt | Counts down to the prompt cache going cold | | 📊 | limit-watch | Band above the prompt, toasts | Shows the 5-hour and weekly usage limits and the session's cost | | 🛫 | pr-pilot | Band above the prompt, toasts | Shows the branch's PR checks and merges it with /merge | | 📝 | release-notes | Band above the prompt, toast | Drafts App Store release notes for Xcode projects when the version is bumped | | 📱 | resource-watch | Band above the prompt, toast | Shows which session is using each simulator, Claude Design project or the Xcode app, and messages the other session on a clash | | 🗜 | smart-compact | Toast | Compacts between turns, sooner at checkpoints or when the cache is cooling | | ⛅ | token-weather | Band above the prompt | Forecasts how full the context window is |
When a turn stops on a usage limit, waits until the limit resets and sends continue. Typing a prompt yourself or running /auto-resume cancel stops the wait.
⏸ auto-resume in 1h 12m ← status line
Usage limit reset, resuming ← toast
<sub>📁 plugins/auto-resume</sub>
Names each session from its first prompt using Haiku and can give it a prompt bar colour, so it is easy to find with claude -r after a crash. When the first prompt is short, such as continue or look at this, it titles the session again from the last four prompts on the fourth. Every eighth prompt it checks the title against the last four prompts and renames the session only when the work has moved to a different task; small shifts keep the title. Sessions already named with -n or /rename are left alone, and a rename stops any re-title. Set the color option to red, blue, green, yellow, purple, orange, pink or cyan to colour named sessions; default leaves the colour alone.
> fix the flaky retry test in the upload worker
→ session titled "Fix flaky upload retry test"
<sub>📁 plugins/auto-session-name</sub>
Draws a countdown above the prompt to when the prompt cache goes cold, with the last request's hit rate. Once cold, it shows how much the next turn re-writes. Set the ttl option to 1h when extended caching is on.
🔥 cache 3:42 left · 96% hit ← green, yellow under a minute
🧊 cache cold · next turn re-writes 84.3k ← red
<sub>📁 plugins/cache-clock</sub>
Draws the 5-hour and weekly usage limits above the prompt with live reset countdowns, green under 60%, yellow to 80% and red past it. Toasts once a window passes 80% and again at 95%. Any other window the API reports, such as a gateway spend limit, shows under its own name. The session's cost so far follows the limits.
🕔 5h 42% · 2h17m 📅 7d 81% · 3d4h 💰 $2.36 ← band
7d limit at 81%, resets in 3d4h ← toast
<sub>📁 plugins/limit-watch</sub>
Draws the current branch's open pull request above the prompt with its checks and whether it can merge, refreshed each minute and after every turn. Toasts when a run of checks finishes. /merge merges it with gh and deletes the branch, but only once every check has passed and nothing blocks it. On a gh-stack layer the band shows its place in the stack, and /merge merges the whole stack with gh stack merge once every unmerged layer has passed its checks and has no unpushed commits, then switches to the trunk and deletes every layer's branch, local and remote, once all of them have merged. Set the method option to merge (default), squash or rebase. Needs the GitHub CLI, signed in.
🔀 PR #42 ⏳ 3/5 checks waiting ← band
PR #42 ✗ 1 failing: SonarCloud blocked ← red
PR #42 ✓ 5/5 checks ready · /merge ← green
PR #42 stack 2/3 ✓ 5/5 checks ready · /merge ← a gh-stack layer
PR #42 checks passed, ready to /merge ← toast
<sub>📁 plugins/pr-pilot</sub>
In an Xcode project, draws the app's MARKETING_VERSION and build above the prompt with the commits since the last release. When a turn, or anything between sessions, changes the version, Haiku drafts App Store "What's New" notes from those commits and a toast says where they went. With fastlane they go to fastlane/metadata/<locale>/release_notes.txt for the default locale, else en-US, else the first. Without fastlane they become a ## <version> section in CHANGELOG.md, and a section that is already there is left alone. The last release is the newest tag, or the commit that set the previous version when the repository has no tags. The first time it sees a repository it only records the version. /draft-release-notes drafts the notes again, replacing what is there.
📝 v2.4.0 (41) 12 commits since v2.3.0 notes drafted ← band
Release notes for 2.4.0 drafted in fastlane/metadata/en-US/release_notes.txt ← toast
<sub>📁 plugins/release-notes</sub>
Shows which Claude Code session is using each shared thing on the machine, so parallel agents do not fight over one. Booted Apple simulators and Claude Design projects are the baseline; the Xcode app sits on top.
simctl or xcodebuild names it by UDID or name, or uses booted or an Xcode MCP run while only one is booted; commands that only look, as simctl list or xcodebuild -showdestinations, do not count.claude-design tool call on it.A hold lasts the hold option's minutes (10 by default) after the last call, and ends with the session. Sessions share their holds as files in ~/.claude/resource-watch/, labelled by their project's folder. A simulator call on one another session holds is refused the first time: the holding session is asked, and the agent is told to wait for its reply, then repeat the call to go ahead, and never to switch to or create another simulator without asking you. The holder tells the waiting sessions once it is done: after StopProject or DeviceInteractionEndSession, when its hold runs out, or when it ends. For a Claude Design project or the Xcode app nothing is refused: it toasts, messages the holding session so its agent can reply asking it to wait, and tells its own agent who holds it; a session that ends tells the sessions it shared with.
📱 iPhone 18 Pro (iOS 27.2) · this session 🛠 the Xcode app · ⚠ also the web session ← band
iPhone 18 Pro is in use by the web session; asked it, waiting ← toast
<sub>📁 plugins/resource-watch</sub>
Compacts the conversation between turns, never during one, weighing several factors against the context's fill. Past the threshold option (60, 70 default, or 80%) it compacts about ten seconds after a turn ends. It compacts sooner when compacting is cheapest or most worth it:
gh pr, gh stack), had a plan approved, finished its todo list, or switched branch or worktree. The summary is told what to keep for each, such as the approved plan verbatim. A checkpoint counts only until the next turn starts. Set checkpoints to off to ignore them.Nothing takes it under the floor option (30, 40 default, or 50%), and it tries at most once per idle stretch. The ttl option defaults to auto: 1h on a subscription, 5m on an API key or cloud provider. Set it to 5m while a subscription draws on usage credits, or to 1h when you set a one-hour cache yourself.
Set continue to tasks to carry on after compacting while todos or tasks are still open. It sends Continue with the remaining tasks., unless the turn was interrupted or ended on a question.
Compacted at 52%: committed ← toast
Compacted at 55%: cache cooling ← toast
Compacted at 74%: context high, 5h limit at 86% ← toast
Compacted at 75%: context high; continuing ← toast
<sub>📁 plugins/smart-compact</sub>
Draws a forecast of the context window above the prompt, with tokens used, a sparkline of the last 12 turns and the change since the last turn.
⛅ Cloudy 38% of context 76.4k / 200k last turns ▁▂▂▃▄▄▅▆ ▲ +4.1k last turn
| 🌞 Clear | ⛅ Cloudy | ☔ Showers | ⚡ Storm | 🚨 Compact soon | | :-: | :-: | :-: | :-: | :-: | | under 25% | under 50% | under 75% | under 90% | 90% and up |
<sub>📁 plugins/token-weather</sub>
hooks/register.ts 271 lines1import { atom, read, update } from 'claude-code'
2import type { Register } from 'claude-code'
3
4import type { Checkpoint, SmartCompactTurn } from '../types'
5
6const TTL_MS = { '5m': 5 * 60_000, '1h': 60 * 60_000 } as const
7const TICK_MS = 15_000
8// Compact this close to the cache going cold, so the summary still reads it warm.
9const COOLING_MS = 60_000
10// Leave the person a moment to type a follow-up before compacting under them.
11const SETTLE_MS = 10_000
12const CONTINUE_PROMPT = 'Continue with the remaining tasks.'
13
14const CHECKPOINTS: Record<Checkpoint, { reason: string; instructions: string }> = {
15 commit: {
16 reason: 'committed',
17 instructions:
18 'The work so far was just committed. Say in a line or two what the commit holds, and keep open follow-ups, decisions and anything not yet committed.',
19 },
20 pr: {
21 reason: 'PR opened',
22 instructions:
23 'A pull request was just opened. Keep its number, branch and what reviewers should know; summarise the rest briefly.',
24 },
25 merge: {
26 reason: 'PR merged',
27 instructions: 'A pull request was just merged. Keep its number and any follow-ups; summarise the rest briefly.',
28 },
29 plan: {
30 reason: 'plan approved',
31 instructions: 'A plan was just approved. Keep the approved plan verbatim and summarise how it was reached in a few lines.',
32 },
33 todos: {
34 reason: 'todos done',
35 instructions: 'Every task on the todo list is done. Summarise what was done briefly and keep anything left open.',
36 },
37 switch: {
38 reason: 'switched task',
39 instructions:
40 'The session moved to another branch or worktree. Summarise the earlier work briefly and keep what the new task needs.',
41 },
42}
43
44// Held by the host, so a hot reload mid-turn still knows a turn is running.
45const turn = atom({ plugin: 'smart-compact', key: 'turn' } as const, { isBusy: false, endedAt: null } as SmartCompactTurn)
46// The last checkpoint the current or just-ended turn reached.
47const checkpoint = atom({ plugin: 'smart-compact', key: 'checkpoint' } as const, null as Checkpoint | null)
48// Task ids made with TaskCreate and not yet completed or deleted.
49const openTasks = atom({ plugin: 'smart-compact', key: 'openTasks' } as const, [] as readonly string[])
50// Items not yet completed on the latest TodoWrite list.
51const openTodos = atom({ plugin: 'smart-compact', key: 'openTodos' } as const, 0)
52
53export type Factors = {
54 percent: number
55 idleMs: number
56 ttlMs: number
57 fiveHourPercent?: number
58 checkpoint?: Checkpoint | null
59}
60
61export type Limits = { threshold: number; floor: number }
62
63export type Decision = { compact: boolean; threshold: number; reasons: string[] }
64
65export const register: Register = (on, options) => {
66 const limits: Limits = {
67 threshold: Number(options.threshold ?? 70),
68 floor: Number(options.floor ?? 40),
69 }
70 const isWatchingCheckpoints = options.checkpoints !== 'off'
71 const isContinuing = options.continue === 'tasks'
72 let isCompacting = false
73
74 on('session.start', async ($, e, next) => {
75 const result = await next(e)
76
77 $.clock.every(TICK_MS, async () => {
78 const state = await read($, turn)
79
80 if (isCompacting || state.isBusy || state.endedAt === null) {
81 return
82 }
83
84 const idleMs = (await $.clock.now()) - state.endedAt
85
86 if (idleMs < SETTLE_MS) {
87 return
88 }
89
90 const { context, rateLimits } = await $.session.usage()
91
92 // No reading until the first response after a start or a compaction.
93 if (context.percent === undefined) {
94 return
95 }
96
97 const reached = await read($, checkpoint)
98 const fiveHour = rateLimits.find(limit => limit.kind === 'five_hour')
99 const ttlMs = TTL_MS[cacheTtl(options.ttl, rateLimits)]
100 const decision = decide(
101 { percent: context.percent, idleMs, ttlMs, fiveHourPercent: fiveHour?.percentUsed, checkpoint: reached },
102 limits,
103 )
104
105 if (!decision.compact) {
106 return
107 }
108
109 isCompacting = true
110
111 try {
112 const instructions = reached ? CHECKPOINTS[reached].instructions : undefined
113 const compacted = await $.session.compact(instructions ? { instructions } : undefined)
114
115 if (!('skip' in compacted && compacted.skip !== undefined)) {
116 const isUnfinished = (await read($, openTasks)).length > 0 || (await read($, openTodos)) > 0
117
118 if (isContinuing && state.canContinue && isUnfinished) {
119 $.ui.toast(`Compacted at ${context.percent}%: ${decision.reasons.join(', ')}; continuing`)
120 await $.prompt.submit({ text: CONTINUE_PROMPT })
121 } else {
122 $.ui.toast(`Compacted at ${context.percent}%: ${decision.reasons.join(', ')}`)
123 }
124 }
125 } catch {
126 // A turn started between the check and the call; try again once it ends.
127 } finally {
128 isCompacting = false
129 // One try per idle stretch: a skip waits for the next turn to end.
130 await update($, turn, state => ({ ...state, endedAt: null }))
131 await update($, checkpoint, () => null)
132 }
133 })
134
135 return result
136 })
137
138 on('turn.start', async ($, e, next) => {
139 await update($, turn, state => ({ ...state, isBusy: true }))
140 // A checkpoint counts for the idle stretch after its own turn alone.
141 await update($, checkpoint, () => null)
142
143 return next(e)
144 })
145
146 on('turn.complete', async ($, e, next) => {
147 const result = await next(e)
148
149 // Main loop only: a subagent's turn ending leaves the session busy.
150 if (!e.agentId) {
151 const endedAt = await $.clock.now()
152 // Stopped by the person, or waiting on their answer: not ours to carry on.
153 const canContinue = !e.isAborted && !e.answer.trimEnd().endsWith('?')
154 await update($, turn, () => ({ isBusy: false, endedAt, canContinue }))
155 }
156
157 return result
158 })
159
160 if (!isWatchingCheckpoints && !isContinuing) {
161 return
162 }
163
164 on('tool.call', async ($, e, next) => {
165 const ran = await next(e)
166
167 // A subagent's commits and plans are its own; a failed call reaches nothing.
168 if (e.agentId || ran.deny !== undefined || ran.isError === true) {
169 return ran
170 }
171
172 let reached: Checkpoint | null = null
173
174 if (e.tool === 'Bash') {
175 reached = bashCheckpoint(e.command)
176 } else if (e.tool === 'ExitPlanMode') {
177 reached = 'plan'
178 } else if (e.tool === 'EnterWorktree' || e.tool === 'ExitWorktree') {
179 reached = 'switch'
180 } else if (e.tool === 'TodoWrite') {
181 await update($, openTodos, () => e.todos.filter(todo => todo.status !== 'completed').length)
182 reached = areAllDone(e.todos) ? 'todos' : null
183 } else if (e.tool === 'TaskCreate') {
184 const created = ran.result as { task?: { id?: string } }
185 const id = created.task?.id
186
187 if (id) {
188 await update($, openTasks, ids => [...ids, id])
189 }
190 } else if (e.tool === 'TaskUpdate' && (e.status === 'completed' || e.status === 'deleted')) {
191 const before = await read($, openTasks)
192 const after = before.filter(id => id !== e.taskId)
193 await update($, openTasks, () => after)
194 reached = e.status === 'completed' && before.length > 0 && after.length === 0 ? 'todos' : null
195 }
196
197 if (reached && isWatchingCheckpoints) {
198 await update($, checkpoint, () => reached)
199 }
200
201 return ran
202 }).catch(($, e, next) => next(e)) // Only watches: a fault here must never cost the call.
203}
204
205export function bashCheckpoint(command: string): Checkpoint | null {
206 if (/\bgh\s+(?:pr|stack)\s+merge\b/.test(command)) {
207 return 'merge'
208 }
209
210 if (/\bgh\s+(?:pr\s+create|stack\s+submit)\b/.test(command)) {
211 return 'pr'
212 }
213
214 if (/\bgit\s+(?:-C\s+\S+\s+)?commit\b/.test(command)) {
215 return 'commit'
216 }
217
218 // `git checkout -- file` and `git checkout .` restore files; they do not move branch.
219 if (/\bgit\s+(?:-C\s+\S+\s+)?(?:switch|checkout)\s+(?!--(?:\s|$)|\.(?:\s|$))\S/.test(command)) {
220 return 'switch'
221 }
222
223 return null
224}
225
226export function areAllDone(todos: readonly { status: string }[]) {
227 return todos.length > 0 && todos.every(todo => todo.status === 'completed')
228}
229
230// A subscription reports its plan windows and caches the main conversation for an hour;
231// an API key or cloud provider reports none and caches for five minutes.
232export function cacheTtl(option: unknown, rateLimits: readonly { kind: string }[]): keyof typeof TTL_MS {
233 if (option === '5m' || option === '1h') {
234 return option
235 }
236
237 return rateLimits.some(limit => limit.kind === 'five_hour' || limit.kind === 'seven_day') ? '1h' : '5m'
238}
239
240export function decide(factors: Factors, limits: Limits): Decision {
241 const { percent, idleMs, ttlMs, fiveHourPercent, checkpoint: reached } = factors
242 const reasons: string[] = []
243 let threshold = limits.threshold
244
245 if (reached) {
246 // A finished piece of work: the summary loses the least that matters now.
247 threshold -= 20
248 reasons.push(CHECKPOINTS[reached].reason)
249 }
250
251 // Once cold, the summary would re-read everything uncached, so only cooling counts.
252 if (idleMs < ttlMs && ttlMs - idleMs <= COOLING_MS) {
253 // About to go cold: the summary reads the prefix from cache while it still can.
254 threshold -= 20
255 reasons.push('cache cooling')
256 }
257
258 if (fiveHourPercent !== undefined && fiveHourPercent >= 80) {
259 threshold -= 10
260 reasons.push(`5h limit at ${fiveHourPercent}%`)
261 }
262
263 threshold = Math.max(threshold, limits.floor)
264
265 if (percent >= limits.threshold) {
266 reasons.unshift('context high')
267 }
268
269 return { compact: percent >= threshold, threshold, reasons }
270}
271types/index.d.ts 15 lines1export type SmartCompactTurn = { isBusy: boolean; endedAt: number | null; canContinue?: boolean }
2
3export type Checkpoint = 'commit' | 'pr' | 'merge' | 'plan' | 'todos' | 'switch'
4
5declare module 'claude-code' {
6 interface PluginState {
7 'smart-compact': {
8 turn: SmartCompactTurn
9 checkpoint: Checkpoint | null
10 openTasks: readonly string[]
11 openTodos: number
12 }
13 }
14}
15