Compacts or keeps warm the prompt cache of sessions with more than 200k tokens of context before it lapses, winds turns down near the plan limit, and continues…

Keeps a Claude Code session with more than 200k tokens of context from paying for its whole context uncached. Compaction and resumption happen while the main conversation's prompt cache is still warm. The cache lifetime comes from the promptCacheTtl setting: 5m, or one hour otherwise.
$.model.fork) reads the cache and keeps it alive instead. The fork leaves out the waiting model reply, whose tool call has no result yet, so only that reply is written to the cache again when the turn continues. When a fork finds the cache already gone, pinging stops until the next model request.A compaction counts only once the context has actually shrunk; a failed one is retried while the cache is warm. The thresholds are POLICY in hooks/activity.ts.
/plugin install idle-compact --marketplace bence-boer/agent-resources
Or load the working copy in every session, reloading on save, even in sessions without a terminal such as Remote Control's, through the env block of ~/.claude/settings.json:
"env": {
"CLAUDE_CODE_PLUGIN_DIRS": "~/projects/agent-resources/plugins/idle-compact",
"CLAUDE_CODE_PLUGIN_DIR_WATCH": "1"
}
hooks/activity.ts: the session's activity as a pure state machine, transition(activity, event), and the effect a check claims, claimedEffect.hooks/register.ts: wires engine events and a one-minute check into that state machine and performs the effects.types/index.d.ts: the $.state contract for Activity.claude --plugin-dir plugins/idle-compact # loads it with hot reload and lays its types for tsc
claude plugin validate plugins/idle-compact
claude plugin test plugins/idle-compacthooks/register.ts 110 lines1import { atom, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import { INITIAL_ACTIVITY, POLICY, cacheLifetimeMilliseconds, claimedEffect, transition, warningFor } from './activity'
5import type { ActivityEvent, Effect, Observation } from './activity'
6
7const activity = atom({ plugin: 'idle-compact', key: 'activity' } as const, INITIAL_ACTIVITY)
8
9const KEEP_ALIVE_PROMPT = 'This is an automated prompt-cache keep-alive, not a task: call no tools and reply with the single word OK.'
10
11const RESUME_PROMPT =
12 'The usage limit has reset. Continue the task you were on when the limit stopped you or idle-compact asked you to wrap up, starting from your handoff note if you wrote one.'
13
14const warningText = (resetsAt: number | undefined): string =>
15 [
16 `idle-compact: plan usage is above ${POLICY.limitWarningPercent}%`,
17 resetsAt === undefined ? '' : ` and resets at ${new Date(resetsAt).toISOString()}`,
18 '. Wrap up now: finish or pause the current step, stop the background agents you started, write what you need to pick the work back up into a short handoff note, then end your turn.',
19 ` The session is compacted while the prompt cache is warm, and if the turn has not ended by ${POLICY.limitAbortPercent}% usage it is stopped.`,
20 resetsAt === undefined ? '' : ' After the reset you are prompted to continue.',
21 ].join('')
22
23const record = ($: EngineInterface, event: ActivityEvent) =>
24 update($, activity, current => transition(current, event))
25
26const observe = async ($: EngineInterface): Promise<Observation> => {
27 const [now, usage, settings] = await Promise.all([$.clock.now(), $.session.usage(), $.settings.read()])
28 return {
29 now,
30 contextTokens: usage.context.tokens ?? 0,
31 rateLimits: usage.rateLimits
32 .map(window => ({
33 kind: window.kind,
34 percentUsed: window.percentUsed,
35 ...(window.resetsAt !== undefined && { resetsAt: Date.parse(window.resetsAt) }),
36 }))
37 .filter(window => window.resetsAt === undefined || window.resetsAt > now),
38 cacheLifetimeMilliseconds: cacheLifetimeMilliseconds(settings.promptCacheTtl),
39 }
40}
41
42const perform = async ($: EngineInterface, effect: Effect) => {
43 switch (effect.kind) {
44 case 'compact': {
45 await $.command.run({ command: 'compact' })
46 await record($, { kind: 'compaction-finished', observation: await observe($) })
47 return
48 }
49 case 'keep-alive': {
50 const reply = await $.model.fork({ prompt: KEEP_ALIVE_PROMPT })
51 const cacheReadTokens = 'usage' in reply ? reply.usage.cache_read_input_tokens : 0
52 await record($, { kind: 'kept-alive', at: await $.clock.now(), cacheReadTokens })
53 $.ui.log(
54 `idle-compact: keep-alive fork read ${cacheReadTokens} tokens from the prompt cache` +
55 (reply.isAnswered ? '' : ` (no reply: ${reply.reason})`),
56 )
57 return
58 }
59 case 'abort-turn':
60 $.ui.log(`idle-compact: stopping the turn above ${POLICY.limitAbortPercent}% plan usage`)
61 await $.turn.abort({ turnId: effect.turnId })
62 return
63 case 'resume':
64 $.prompt.submit({ text: RESUME_PROMPT }).catch((error: unknown) => $.ui.log(`idle-compact: ${String(error)}`))
65 return
66 }
67}
68
69const check = async ($: EngineInterface) => {
70 const observation = await observe($)
71 const effect = claimedEffect(await record($, { kind: 'checked', observation }), observation)
72 if (effect !== undefined) await perform($, effect)
73}
74
75export const register: Register = on => {
76 on('session.start', async ($, e, next) => {
77 $.clock.every(POLICY.checkIntervalMilliseconds, () => {
78 check($).catch((error: unknown) => $.ui.log(`idle-compact: ${String(error)}`))
79 })
80 return next(e)
81 })
82
83 on('turn.start', async ($, e, next) => {
84 await record($, { kind: 'turn-started', turnId: e.turnId, at: await $.clock.now() })
85 return next(e)
86 })
87
88 on('turn.step', async function* ($, e, next) {
89 if (e.agentId === undefined) await record($, { kind: 'requested', at: await $.clock.now() })
90 return yield* next(e)
91 })
92
93 on('classic.PostToolBatch', async ($, e, next) => {
94 const result = await next(e)
95 const toolUseId = e.tool_calls[0]?.tool_use_id
96 if (e.agent_id !== undefined || toolUseId === undefined) return result
97 const warning = warningFor(await record($, { kind: 'tool-batch-completed', toolUseId }), toolUseId)
98 if (warning === undefined) return result
99 return { ...result, additionalContext: [...(result.additionalContext ?? []), warningText(warning.resetsAt)] }
100 }).catch(($, e, next) => {
101 $.ui.log(`idle-compact: the usage warning failed: ${next.error.message}`)
102 return undefined
103 })
104
105 on('turn.complete', async ($, e, next) => {
106 if (e.agentId === undefined) await record($, { kind: 'turn-completed', reason: e.reason, observation: await observe($) })
107 return next(e)
108 })
109}
110hooks/activity.ts 183 lines1import type { TurnCompleteReason } from 'claude-code'
2
3import type { Activity, Cache, LimitResponse } from '../types'
4
5const MINUTE = 60 * 1000
6
7export const POLICY = {
8 contextTokenThreshold: 200_000,
9 limitWarningPercent: 95,
10 limitAbortPercent: 98,
11 maximumCacheRefreshLeadMilliseconds: 5 * MINUTE,
12 checkIntervalMilliseconds: MINUTE,
13 resumeDelayMilliseconds: MINUTE,
14} as const
15
16export const INITIAL_ACTIVITY: Activity = { kind: 'unobserved' }
17
18export type RateLimitWindow = {
19 readonly kind: string
20 readonly percentUsed: number
21 readonly resetsAt?: number
22}
23
24export type Observation = {
25 readonly now: number
26 readonly contextTokens: number
27 readonly rateLimits: readonly RateLimitWindow[]
28 readonly cacheLifetimeMilliseconds: number
29}
30
31export type ActivityEvent =
32 | { readonly kind: 'turn-started'; readonly turnId: string; readonly at: number }
33 | { readonly kind: 'requested'; readonly at: number }
34 | { readonly kind: 'tool-batch-completed'; readonly toolUseId: string }
35 | { readonly kind: 'turn-completed'; readonly reason: TurnCompleteReason; readonly observation: Observation }
36 | { readonly kind: 'checked'; readonly observation: Observation }
37 | { readonly kind: 'compaction-finished'; readonly observation: Observation }
38 | { readonly kind: 'kept-alive'; readonly at: number; readonly cacheReadTokens: number }
39
40export type Effect =
41 | { readonly kind: 'compact' }
42 | { readonly kind: 'keep-alive' }
43 | { readonly kind: 'abort-turn'; readonly turnId: string }
44 | { readonly kind: 'resume' }
45
46const NO_LIMIT_RESPONSE: LimitResponse = { kind: 'none' }
47
48const isLarge = ({ contextTokens }: Observation): boolean => contextTokens > POLICY.contextTokenThreshold
49
50const mostUsedWindow = ({ rateLimits }: Observation): RateLimitWindow | undefined =>
51 rateLimits.reduce<RateLimitWindow | undefined>(
52 (most, window) => (most === undefined || window.percentUsed > most.percentUsed ? window : most),
53 undefined,
54 )
55
56const percentUsed = (window: RateLimitWindow | undefined): number => window?.percentUsed ?? 0
57
58const isExhausted = (window: RateLimitWindow | undefined): boolean => percentUsed(window) >= 100
59
60const isNearLimit = (window: RateLimitWindow | undefined): boolean => percentUsed(window) > POLICY.limitWarningPercent
61
62const cacheAge = (cache: Cache, { now }: Observation): number =>
63 cache.kind === 'warm' ? now - cache.touchedAt : Number.POSITIVE_INFINITY
64
65const isCacheWarm = (cache: Cache, observation: Observation): boolean =>
66 cacheAge(cache, observation) < observation.cacheLifetimeMilliseconds
67
68const isCacheExpiring = (cache: Cache, observation: Observation): boolean => {
69 const lead = Math.min(POLICY.maximumCacheRefreshLeadMilliseconds, observation.cacheLifetimeMilliseconds / 2)
70 return isCacheWarm(cache, observation) && cacheAge(cache, observation) >= observation.cacheLifetimeMilliseconds - lead
71}
72
73const resumeAfterTurn = (
74 limit: LimitResponse,
75 reason: TurnCompleteReason,
76 observation: Observation,
77): number | undefined => {
78 if (limit.kind === 'aborting') return limit.resetsAt
79 if (limit.kind === 'warned' && reason !== 'aborted') return limit.resetsAt
80 const window = mostUsedWindow(observation)
81 return reason === 'error' && isExhausted(window) ? window?.resetsAt : undefined
82}
83
84const afterTurn = (
85 working: Extract<Activity, { kind: 'working' }>,
86 reason: TurnCompleteReason,
87 observation: Observation,
88): Activity => {
89 const resetsAt = resumeAfterTurn(working.limit, reason, observation)
90 return {
91 kind: 'resting',
92 cache: working.cache,
93 compaction: { kind: 'due' },
94 ...(resetsAt !== undefined && { resume: { kind: 'scheduled', at: resetsAt + POLICY.resumeDelayMilliseconds } }),
95 }
96}
97
98const checkWorking = (working: Extract<Activity, { kind: 'working' }>, observation: Observation): Activity => {
99 if (!isLarge(observation)) return working
100 const window = mostUsedWindow(observation)
101 if (isExhausted(window)) return working
102 if (percentUsed(window) >= POLICY.limitAbortPercent && working.limit.kind !== 'aborting') {
103 return { ...working, limit: { kind: 'aborting', claimedAt: observation.now, resetsAt: window?.resetsAt } }
104 }
105 if (isNearLimit(window) && working.limit.kind === 'none') {
106 return { ...working, limit: { kind: 'warning-due', resetsAt: window?.resetsAt } }
107 }
108 if (working.keepAlive === undefined && isCacheExpiring(working.cache, observation)) {
109 return { ...working, keepAlive: { claimedAt: observation.now } }
110 }
111 return working
112}
113
114const checkResting = (resting: Extract<Activity, { kind: 'resting' }>, observation: Observation): Activity => {
115 if (resting.resume?.kind === 'scheduled' && observation.now >= resting.resume.at) {
116 return { ...resting, resume: { kind: 'sent', claimedAt: observation.now } }
117 }
118 if (resting.compaction.kind !== 'due' || !isLarge(observation)) return resting
119 if (!isCacheWarm(resting.cache, observation)) return { ...resting, compaction: { kind: 'lapsed' } }
120 const window = mostUsedWindow(observation)
121 if (isExhausted(window)) return resting
122 if (isNearLimit(window) || isCacheExpiring(resting.cache, observation)) {
123 return { ...resting, compaction: { kind: 'running', claimedAt: observation.now } }
124 }
125 return resting
126}
127
128export const transition = (activity: Activity, event: ActivityEvent): Activity => {
129 switch (event.kind) {
130 case 'turn-started':
131 return { kind: 'working', turnId: event.turnId, cache: { kind: 'warm', touchedAt: event.at }, limit: NO_LIMIT_RESPONSE }
132 case 'requested':
133 return activity.kind === 'working' ? { ...activity, cache: { kind: 'warm', touchedAt: event.at } } : activity
134 case 'tool-batch-completed':
135 return activity.kind === 'working' && activity.limit.kind === 'warning-due'
136 ? { ...activity, limit: { kind: 'warned', toolUseId: event.toolUseId, resetsAt: activity.limit.resetsAt } }
137 : activity
138 case 'turn-completed':
139 return activity.kind === 'working' ? afterTurn(activity, event.reason, event.observation) : activity
140 case 'checked':
141 if (activity.kind === 'working') return checkWorking(activity, event.observation)
142 if (activity.kind === 'resting') return checkResting(activity, event.observation)
143 return activity
144 case 'compaction-finished':
145 return activity.kind === 'resting' && activity.compaction.kind === 'running'
146 ? { ...activity, compaction: isLarge(event.observation) ? { kind: 'due' } : { kind: 'done' } }
147 : activity
148 case 'kept-alive':
149 if (activity.kind !== 'working' || activity.keepAlive === undefined) return activity
150 return {
151 kind: 'working',
152 turnId: activity.turnId,
153 limit: activity.limit,
154 cache: event.cacheReadTokens > 0 ? { kind: 'warm', touchedAt: event.at } : { kind: 'lost' },
155 }
156 }
157}
158
159export const claimedEffect = (activity: Activity, { now }: Observation): Effect | undefined => {
160 if (activity.kind === 'working') {
161 if (activity.limit.kind === 'aborting' && activity.limit.claimedAt === now) {
162 return { kind: 'abort-turn', turnId: activity.turnId }
163 }
164 if (activity.keepAlive?.claimedAt === now) return { kind: 'keep-alive' }
165 }
166 if (activity.kind === 'resting') {
167 if (activity.resume?.kind === 'sent' && activity.resume.claimedAt === now) return { kind: 'resume' }
168 if (activity.compaction.kind === 'running' && activity.compaction.claimedAt === now) return { kind: 'compact' }
169 }
170 return undefined
171}
172
173export const warningFor = (
174 activity: Activity,
175 toolUseId: string,
176): Extract<LimitResponse, { kind: 'warned' }> | undefined =>
177 activity.kind === 'working' && activity.limit.kind === 'warned' && activity.limit.toolUseId === toolUseId
178 ? activity.limit
179 : undefined
180
181export const cacheLifetimeMilliseconds = (promptCacheTtl: unknown): number =>
182 promptCacheTtl === '5m' ? 5 * MINUTE : 60 * MINUTE
183types/index.d.ts 40 lines1export type Claim = { readonly claimedAt: number }
2
3export type LimitResponse =
4 | { readonly kind: 'none' }
5 | { readonly kind: 'warning-due'; readonly resetsAt?: number }
6 | { readonly kind: 'warned'; readonly toolUseId: string; readonly resetsAt?: number }
7 | { readonly kind: 'aborting'; readonly claimedAt: number; readonly resetsAt?: number }
8
9export type Compaction =
10 | { readonly kind: 'due' }
11 | { readonly kind: 'running'; readonly claimedAt: number }
12 | { readonly kind: 'done' }
13 | { readonly kind: 'lapsed' }
14
15export type Resume = { readonly kind: 'scheduled'; readonly at: number } | { readonly kind: 'sent'; readonly claimedAt: number }
16
17export type Cache = { readonly kind: 'warm'; readonly touchedAt: number } | { readonly kind: 'lost' }
18
19export type Activity =
20 | { readonly kind: 'unobserved' }
21 | {
22 readonly kind: 'working'
23 readonly turnId: string
24 readonly cache: Cache
25 readonly limit: LimitResponse
26 readonly keepAlive?: Claim
27 }
28 | {
29 readonly kind: 'resting'
30 readonly cache: Cache
31 readonly compaction: Compaction
32 readonly resume?: Resume
33 }
34
35declare module 'claude-code' {
36 interface PluginState {
37 'idle-compact': { activity: Activity }
38 }
39}
40