Compact the conversation after a period without user input when the context is large

hooks/register.ts 39 lines1import type { Register, Timer } from 'claude-code'
2
3const IDLE_MS = 50 * 60 * 1000
4const MIN_CONTEXT_TOKENS = 30_000
5
6export const register: Register = on => {
7 let timer: Timer | undefined
8
9 const cancel = () => {
10 timer?.cancel()
11 timer = undefined
12 }
13
14 on('prompt.submit', ($, e, next) => {
15 cancel()
16 return next(e)
17 }).catch(($, e, next) => next(e))
18
19 on('turn.complete', async ($, e, next) => {
20 const result = await next(e)
21 if (e.agentId !== undefined) return result
22
23 cancel()
24 timer = $.clock.after(IDLE_MS, async () => {
25 timer = undefined
26 try {
27 const { context } = await $.session.usage()
28 if ((context.tokens ?? 0) < MIN_CONTEXT_TOKENS) return
29 await $.session.compact()
30 $.ui.toast(`idle-compact: compacted after 50 minutes idle (context ${context.tokens} tokens)`)
31 } catch {
32 // ignore
33 }
34 })
35
36 return result
37 })
38}
39