Runs /compact while the session sits idle waiting on background work, right before the prompt cache expires.

Automatically runs /compact when a session has been left waiting on background work, right before the prompt cache expires.
It compacts when all of these hold:
/idle-compact on is set.minContextTokens (default 100,000) tokens.It compacts at most once per idle stretch; the next model request re-arms it. When a turn ends with background work running, it sets a timer for the moment the idle time runs out and checks the conditions again when it fires.
The idle time counts from when a request is sent, because that is when the prompt cache's lifetime is refreshed. Compacting just before the lifetime runs out means the compaction request still reads the conversation from cache, and the session wakes to a smaller context when the background work reports back. It is a minute short of the cache's lifetime, which it works out as Claude Code picks it:
FORCE_PROMPT_CACHING_5M, CLAUDE_CODE_PROMPT_CACHE_TTL, the promptCacheTtl setting and ENABLE_PROMPT_CACHING_1H override that, in that order, as they do the cache itself.Whether the session is on a subscription is read from the usage limits each response reports, and kept through /clear. The lifetime is the one the last model request was sent under, so usage limits moving while the session sits idle do not change it. Until the first response is measured it takes the one-hour cache, and moves the timer once it is. Set idleMinutes to pick the idle time yourself.
While a compaction is scheduled and the context is big enough for it, the plugin pins idle-compact scheduled for HH:MM (local time) as its own status line under the prompt. The line clears when a turn starts, when it compacts, or when there's nothing left to compact for. When it compacts, it also shows a toast.
/idle-compact [auto|on|off]Sets when it compacts, for the rest of the session (a /clear keeps it):
auto (the default): only while background work runs, as above.on: whenever the session sits idle, background work or not.off: never.With no argument it says what it is set to, the idle time, the context size it waits for and the cache lifetime it worked out, then when it will next compact or why nothing is scheduled. It runs at once, even mid-turn.
| Option | Type | Default | Description |
|---|---|---|---|
idleMinutes | number | 0 | Minutes since the last model request before an idle session is compacted. 0 follows the prompt cache: 4 under its five-minute lifetime, 59 under its one-hour lifetime. |
minContextTokens | number | 100000 | Only compact when the context holds at least this many tokens. |
Set them from /config, or in settings:
{ "pluginConfigs": { "idle-compact": { "options": { "idleMinutes": 57, "minContextTokens": 150000 } } } }
turn.complete). An interrupted turn, or one an API error ended, does not count, so nothing is compacted until a turn ends normally.Bash or PowerShell command run in the background (or moved there with Ctrl+B), a Monitor, a Workflow, a background or remote Agent. A subagent's own shell commands and monitors report to that subagent, so they are not counted. They are checked again just before compacting:$.agent.list()); one that is not pending, running or waiting does not count.TaskStop./config) carries on where it was. /clear resets it.hooks/register.ts 395 lines1import { atom, read, update } from 'claude-code';
2import type { EngineInterface, Register, Timer } from 'claude-code';
3
4import type { IdleCompactMode, IdleCompactTask, IdleCompactTracker } from '../types';
5
6// A minute short of the prompt cache's lifetime, so the compaction's request
7// still reads the cache.
8const IDLE_MINUTES = { '5m': 4, '1h': 59 } as const;
9const DEFAULT_MIN_CONTEXT_TOKENS = 100_000;
10const MODES: readonly IdleCompactMode[] = ['auto', 'on', 'off'];
11// A subagent still doing work; `idle` is a teammate waiting on a message.
12const ACTIVE_AGENT = new Set(['pending', 'running', 'waiting']);
13// How a task notification says its task has ended.
14const ENDED = new Set(['completed', 'failed', 'killed']);
15
16// `idleMinutes` is null when it follows the prompt cache's lifetime.
17type Limits = { idleMinutes: number | null; minContextTokens: number };
18type CacheLifetime = keyof typeof IDLE_MINUTES;
19
20const IDLE: IdleCompactTracker = {
21 lastModelCallAt: null,
22 contextTokens: null,
23 backgroundTasks: [],
24 hasCompacted: false,
25 isIdle: false,
26 rateLimits: null,
27 cacheLifetime: null,
28};
29
30// Kept in the session's state, so a reload of the module carries on where it
31// was rather than waiting for the next turn.
32const tracker = atom({ plugin: 'idle-compact', key: 'tracker' } as const, IDLE);
33// Set by /idle-compact, and kept through a /clear.
34const mode = atom({ plugin: 'idle-compact', key: 'mode' } as const, 'auto' as IdleCompactMode);
35
36function track($: EngineInterface, change: Partial<IdleCompactTracker>) {
37 return update($, tracker, current => ({ ...current, ...change }));
38}
39
40// What a /clear keeps: the mode, and what the usage limits tell of the
41// account. Held here as well as in the state, should the state start afresh
42// with the new conversation, and written back by the first hook after it.
43let carried: { mode: IdleCompactMode; rateLimits: IdleCompactTracker['rateLimits'] } | undefined;
44
45async function restore($: EngineInterface) {
46 if (carried === undefined) return;
47 const { mode: kept, rateLimits } = carried;
48 carried = undefined;
49 await update($, mode, () => kept);
50 await update($, tracker, current => ({ ...current, rateLimits: current.rateLimits ?? rateLimits }));
51}
52
53function isEnabled(value: string | undefined) {
54 return value !== undefined && value !== '' && value !== '0' && value.toLowerCase() !== 'false';
55}
56
57function lifetime(value: unknown): CacheLifetime | null {
58 return value === '5m' || value === '1h' ? value : null;
59}
60
61// How long a request sent now would have its prompt cache live, worked out as
62// Claude Code picks it: the environment and settings that force one, then an
63// hour on a subscription within its plan's usage and five minutes otherwise
64// (an API key, a cloud provider, a Claude gateway's spend limit, usage past
65// the plan). Null until a response tells whether the session is on a
66// subscription.
67async function detectLifetime($: EngineInterface): Promise<CacheLifetime | null> {
68 if (isEnabled(await $.env.get('FORCE_PROMPT_CACHING_5M'))) return '5m';
69 const fromEnv = lifetime(await $.env.get('CLAUDE_CODE_PROMPT_CACHE_TTL'));
70 if (fromEnv) return fromEnv;
71 const fromSettings = lifetime((await $.settings.read()).promptCacheTtl);
72 if (fromSettings) return fromSettings;
73 if (isEnabled(await $.env.get('ENABLE_PROMPT_CACHING_1H'))) return '1h';
74 const { rateLimits } = await read($, tracker);
75 if (rateLimits === null) return null;
76 // A gateway's spend limit has no one-hour cache, whatever else it reports.
77 if (rateLimits.some(limit => limit.kind === 'spend_limit')) return '5m';
78 return rateLimits.length > 0 && rateLimits.every(limit => limit.percentUsed < 100) ? '1h' : '5m';
79}
80
81// The lifetime of the cache the last model request wrote, which is the one
82// that matters while idle; the hour when it is not yet known.
83function lastLifetime(session: IdleCompactTracker): CacheLifetime {
84 return session.cacheLifetime ?? '1h';
85}
86
87async function idleMs($: EngineInterface, limits: Limits) {
88 return (limits.idleMinutes ?? IDLE_MINUTES[lastLifetime(await read($, tracker))]) * 60_000;
89}
90
91// Whether a session the last turn left with `backgroundTasks` compacts once idle.
92function isWaiting(current: IdleCompactMode, backgroundTasks: readonly unknown[]) {
93 return current === 'on' || (current === 'auto' && backgroundTasks.length > 0);
94}
95
96// The one pending compaction. A plain variable: a reload cancels the timer
97// along with the module, and `session.start` arms it again from the state.
98let timer: Timer | undefined;
99
100function disarm($: EngineInterface) {
101 timer?.cancel();
102 timer = undefined;
103 $.ui.status(undefined);
104}
105
106// The time of day `at` falls on, as hours and minutes.
107function clockTime(at: number) {
108 const date = new Date(at);
109 return `${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
110}
111
112// Pins when the armed timer will compact, if the context is big enough for it
113// to; clears it otherwise. The status line is this plugin's own, beside the
114// engine's pinned notices, so it covers nothing else on screen.
115async function showSchedule($: EngineInterface, limits: Limits) {
116 const session = await read($, tracker);
117 const isDue = timer !== undefined && (session.contextTokens ?? 0) >= limits.minContextTokens;
118 $.ui.status(
119 isDue && session.lastModelCallAt !== null
120 ? `idle-compact scheduled for ${clockTime(session.lastModelCallAt + (await idleMs($, limits)))}`
121 : undefined,
122 );
123}
124
125// Sets the timer for when the session will have sat idle for the idle time,
126// if it sits between turns waiting on background work (or the mode is on)
127// and has not compacted since its last model request.
128async function arm($: EngineInterface, limits: Limits) {
129 disarm($);
130 const session = await read($, tracker);
131 if (!session.isIdle || session.hasCompacted || session.lastModelCallAt === null) return;
132 if (!isWaiting(await read($, mode), session.backgroundTasks)) return;
133 const remainingMs = session.lastModelCallAt + (await idleMs($, limits)) - (await $.clock.now());
134 timer = $.clock.after(Math.max(remainingMs, 0), () => compactIfIdle($, limits));
135 await showSchedule($, limits);
136}
137
138// Adds a task started in the background, or forgets the ones that ended.
139function addTask($: EngineInterface, task: IdleCompactTask) {
140 return update($, tracker, current => ({
141 ...current,
142 backgroundTasks: [...current.backgroundTasks.filter(each => each.id !== task.id), task],
143 }));
144}
145
146function endTasks($: EngineInterface, ids: readonly string[]) {
147 return update($, tracker, current => ({
148 ...current,
149 backgroundTasks: current.backgroundTasks.filter(each => !ids.includes(each.id)),
150 }));
151}
152
153// The background task a tool call started, from its result: a shell command
154// run in the background (or moved there with Ctrl+B), a monitor, a workflow,
155// a background or remote subagent.
156function startedTask(tool: string, result: unknown): IdleCompactTask | undefined {
157 if (typeof result !== 'object' || result === null) return undefined;
158 const fields = result as Record<string, unknown>;
159 const text = (key: string) => (typeof fields[key] === 'string' ? (fields[key] as string) : undefined);
160 if (tool === 'Bash' || tool === 'PowerShell') {
161 const id = text('backgroundTaskId');
162 return id === undefined ? undefined : { id, type: 'shell' };
163 }
164 if (tool === 'Monitor') {
165 const id = text('taskId');
166 return id === undefined ? undefined : { id, type: 'monitor' };
167 }
168 if (tool === 'Workflow') {
169 const id = text('taskId');
170 return id === undefined ? undefined : { id, type: text('taskType') ?? 'local_workflow' };
171 }
172 if (tool === 'Agent') {
173 const agentId = text('agentId');
174 if (fields.status === 'async_launched' && agentId !== undefined) return { id: agentId, type: 'subagent' };
175 const taskId = text('taskId');
176 if (fields.status === 'remote_launched' && taskId !== undefined) return { id: taskId, type: 'remote_agent' };
177 }
178 return undefined;
179}
180
181// The tasks a task notification reports as ended: each `<task-notification>`
182// block's `<task-id>`, when its `<status>` is one a task ends on. A monitor's
183// events come the same way, with no such status, and leave it running.
184function endedTasks(text: string) {
185 const ids: string[] = [];
186 for (const [block] of text.matchAll(/<task-notification>[\s\S]*?<\/task-notification>/g)) {
187 const id = /<task-id>\s*([^<]*?)\s*<\/task-id>/.exec(block)?.[1];
188 const status = /<status>\s*([^<]*?)\s*<\/status>/.exec(block)?.[1];
189 if (id && status !== undefined && ENDED.has(status)) ids.push(id);
190 }
191 return ids;
192}
193
194// The tracked tasks still running now. Subagents are checked live; shell and
195// monitor tasks have no live listing, but each sends a notification when it
196// ends (killed too), which forgets it.
197async function runningTasks($: EngineInterface, tasks: IdleCompactTracker['backgroundTasks']) {
198 if (!tasks.some(task => task.type === 'subagent')) return tasks;
199 const activeAgents = new Set(
200 (await $.agent.list()).filter(agent => ACTIVE_AGENT.has(agent.status)).map(agent => agent.id),
201 );
202 return tasks.filter(task => task.type !== 'subagent' || activeAgents.has(task.id));
203}
204
205async function compactIfIdle($: EngineInterface, limits: Limits) {
206 timer = undefined;
207 $.ui.status(undefined);
208 const session = await read($, tracker);
209 const current = await read($, mode);
210 if (!session.isIdle || session.hasCompacted || session.lastModelCallAt === null) return;
211 if (!isWaiting(current, session.backgroundTasks)) return;
212 if ((session.contextTokens ?? 0) < limits.minContextTokens) return;
213 // Not yet, should the timer have fired early: wait out the rest.
214 if ((await $.clock.now()) - session.lastModelCallAt < (await idleMs($, limits))) {
215 await arm($, limits);
216 return;
217 }
218
219 // On compacts whatever is running; auto only while some background work is.
220 if (current === 'auto') {
221 const backgroundTasks = await runningTasks($, session.backgroundTasks);
222 if (backgroundTasks.length < 1) {
223 await track($, { backgroundTasks });
224 return;
225 }
226 }
227
228 // Counted whether it lands or not, so a failure is not retried; the next
229 // model request re-arms it.
230 await track($, { hasCompacted: true });
231 try {
232 const result = await $.session.compact();
233 if ('skip' in result) $.ui.log(`idle-compact: compaction skipped: ${result.skip}`);
234 else $.ui.toast('idle-compact: compacted the idle session');
235 } catch (error) {
236 $.ui.log(`idle-compact: compaction failed: ${error instanceof Error ? error.message : String(error)}`);
237 }
238}
239
240function positive(value: unknown) {
241 const number = Number(value);
242 return number > 0 ? number : null;
243}
244
245// What /idle-compact answers: the mode, and when it compacts in it.
246function tokens(count: number) {
247 return count < 1000 ? String(count) : `${Math.round(count / 1000)}k`;
248}
249
250// What /idle-compact answers: the mode, when it compacts in it, and whether
251// it is set to now and why not. The engine puts the plugin's name before it.
252async function describe($: EngineInterface, limits: Limits) {
253 const current = await read($, mode);
254 if (current === 'off') return 'off for this session';
255 const session = await read($, tracker);
256 const cache = session.lastModelCallAt === null ? ((await detectLifetime($)) ?? '1h') : lastLifetime(session);
257 const minutes = limits.idleMinutes ?? IDLE_MINUTES[cache];
258 const when = current === 'on' ? 'whenever the session sits idle' : 'while background work runs';
259 const cacheName = cache === '5m' ? 'five-minute' : 'one-hour';
260 const rule = `${current}: compacts after ${minutes} idle minutes ${when}, once the context holds ${tokens(limits.minContextTokens)} tokens (${cacheName} prompt cache)`;
261 return `${rule}\n${await whyNow($, limits, current, session)}`;
262}
263
264async function whyNow($: EngineInterface, limits: Limits, current: IdleCompactMode, session: IdleCompactTracker) {
265 if (session.contextTokens !== null && session.contextTokens < limits.minContextTokens) {
266 return `Nothing scheduled: the context holds ${tokens(session.contextTokens)} tokens`;
267 }
268 if (timer !== undefined && session.lastModelCallAt !== null) {
269 return `Scheduled for ${clockTime(session.lastModelCallAt + (await idleMs($, limits)))}`;
270 }
271 if (session.hasCompacted) return 'Nothing scheduled: compacted since the last model request';
272 if (!session.isIdle) return 'Nothing scheduled until a turn ends';
273 if (current === 'auto' && session.backgroundTasks.length < 1) return 'Nothing scheduled: no background work is running';
274 return 'Nothing scheduled';
275}
276
277export const register: Register = (on, options) => {
278 const limits: Limits = {
279 idleMinutes: positive(options.idleMinutes),
280 minContextTokens: positive(options.minContextTokens) ?? DEFAULT_MIN_CONTEXT_TOKENS,
281 };
282
283 // Fires again on every reload, which arms the timer from the session state.
284 on('session.start', async ($, e, next) => {
285 await restore($);
286 await $.command.register({
287 name: 'idle-compact',
288 description: 'Compact the session when idle: auto (with background work), on (always) or off',
289 argumentHint: '[auto|on|off]',
290 immediate: true,
291 });
292 await arm($, limits);
293 return next(e);
294 });
295
296 // With no argument it says what it is set to; a mode sets it for the session.
297 on('command.run', { command: 'idle-compact' }, async ($, e) => {
298 await restore($);
299 const choice = e.args.trim().toLowerCase();
300 if (choice !== '') {
301 const chosen = MODES.find(each => each === choice);
302 if (chosen === undefined) return { text: 'usage: /idle-compact [auto|on|off]' };
303 await update($, mode, () => chosen);
304 await arm($, limits);
305 }
306 return { text: await describe($, limits) };
307 });
308
309 // A /clear starts the conversation over.
310 on('session.end', async ($, e, next) => {
311 if (e.reason === 'clear') {
312 disarm($);
313 const { rateLimits } = await read($, tracker);
314 carried = { mode: await read($, mode), rateLimits };
315 await track($, { ...IDLE, rateLimits });
316 }
317 return next(e);
318 });
319
320 // Whether the session is on a subscription, and within its plan, comes with
321 // each response's rate limits: none off a subscription. The first tells the
322 // lifetime of the cache the session's first request wrote. Arming again
323 // moves a timer set before then, whichever of this and the turn's end
324 // comes first.
325 on('session.measure', async ($, e, next) => {
326 await restore($);
327 await track($, {
328 contextTokens: e.context.tokens ?? null,
329 rateLimits: e.rateLimits.map(({ kind, percentUsed }) => ({ kind, percentUsed })),
330 });
331 if ((await read($, tracker)).cacheLifetime === null) await track($, { cacheLifetime: await detectLifetime($) });
332 await arm($, limits);
333 return next(e);
334 });
335
336 on('turn.start', async ($, e, next) => {
337 await restore($);
338 disarm($);
339 await track($, { isIdle: false });
340 return next(e);
341 });
342
343 on('turn.step', async function* ($, e, next) {
344 // Each request's cache lives as long as it is set to when it is sent.
345 if (e.agentId === undefined) {
346 await restore($);
347 await track($, {
348 lastModelCallAt: await $.clock.now(),
349 hasCompacted: false,
350 cacheLifetime: await detectLifetime($),
351 });
352 }
353 return yield* next(e);
354 });
355
356 // A main-loop turn that ended on its answer leaves the session idle; an
357 // interrupted turn, or one an API error ended, leaves it waiting on the
358 // person and is not counted. Tracking is best effort: should it fail, the
359 // turn still ends as it would have.
360 on('turn.complete', async ($, e, next) => {
361 const result = await next(e);
362 if (e.agentId === undefined && e.reason !== 'aborted' && e.reason !== 'error') {
363 await restore($);
364 await track($, { isIdle: true });
365 await arm($, limits);
366 }
367 return result;
368 }).catch(($, e, next) => next(e));
369
370 // Background work is counted from the calls that start it, and forgotten
371 // when TaskStop stops it. A subagent's own shells and monitors notify that
372 // subagent, not the main conversation, so only the subagents it starts
373 // count, which are checked live.
374 on('tool.call', async ($, e, next) => {
375 const ran = await next(e);
376 if (ran.deny === undefined && ran.isError !== true) {
377 const started = startedTask(e.tool, ran.result);
378 if (started !== undefined && (e.agentId === undefined || started.type === 'subagent')) await addTask($, started);
379 const stopped = e.tool === 'TaskStop' ? (ran.result as { task_id?: unknown } | undefined)?.task_id : undefined;
380 if (typeof stopped === 'string') await endTasks($, [stopped]);
381 }
382 return ran;
383 }).catch(($, e, next) => next(e));
384
385 // A task's notification, whether it wakes the idle session or reaches a
386 // running turn, tells when it ended.
387 on('prompt.submit', async ($, e, next) => {
388 if (e.origin.kind === 'task-notification') {
389 const ended = endedTasks(e.text);
390 if (ended.length > 0) await endTasks($, ended);
391 }
392 return next(e);
393 }).catch(($, e, next) => next(e));
394};
395types/index.d.ts 36 lines1export type IdleCompactTask = { id: string; type: string };
2
3// What /idle-compact sets for the session: `auto` compacts an idle session
4// waiting on background work, `on` any idle session, `off` none.
5export type IdleCompactMode = 'auto' | 'on' | 'off';
6
7// What the plugin tracks of the main conversation, kept in the session's
8// state so a reload (an option changed in /config, /reload-plugins) keeps it.
9export type IdleCompactTracker = {
10 // When the last model request was sent (the prompt cache's lifetime runs
11 // from there), in `$.clock.now()` milliseconds; null before the first.
12 lastModelCallAt: number | null;
13 // The input tokens of the last response; null until one is measured.
14 contextTokens: number | null;
15 // The background tasks in flight: added by the tool call that started each,
16 // dropped when its notification says it ended or TaskStop stops it.
17 backgroundTasks: IdleCompactTask[];
18 // One compaction per idle stretch: the next model request re-arms it.
19 hasCompacted: boolean;
20 // Between turns: set when one stops, cleared when the next starts.
21 isIdle: boolean;
22 // The subscription's usage windows as the last response reported them,
23 // empty off a subscription; null until one is measured.
24 rateLimits: { kind: string; percentUsed: number }[] | null;
25 // How long the cache the last model request wrote lives, as worked out
26 // when it was sent; null until the session is known to be on a
27 // subscription or not.
28 cacheLifetime: '5m' | '1h' | null;
29};
30
31declare module 'claude-code' {
32 interface PluginState {
33 'idle-compact': { tracker: IdleCompactTracker; mode: IdleCompactMode };
34 }
35}
36