The agent compacts its own context between tasks, with a focus it writes for the compactor, and carries on by itself

TL;DR: the agent compacts itself gracefully: at a moment of its own choosing, between tasks, with the one it is on finished. Settings: ask the agent, "what are the smart-compact settings?"
claude plugin marketplace add zienag/alfreds-plugins
claude plugin install smart-compact@alfreds-plugins
Auto-compact fires at a fixed size, high up in a 1M window, at a random point of the task. The model does not see it coming and finishes nothing before it, so the work can come out broken. A lower limit does not help: for some tasks the right call is to go on a little and finish, then compact. A hard line is the wrong tool.
This mod asks instead. A compaction is the first step of a piece of work: the next subtask of a long job, or the task the user has just handed over. Past a certain size, tool results and the user's messages carry a reminder to compact that way, more insistent as the context grows, each step said once. The agent calls compact_me with a tweet-sized focus for the compactor (the task it continues with, the ones that are done) and ends the turn. The mod runs /compact with that focus and sends "Context compacted. Continue the task." Nobody has to be at the keyboard.
A subagent has no auto-compact at all, and the main agent can hand the same subagent task after task while its context grows unwatched. So on the same steps of its own context a subagent is asked to finish at a good point and return to its parent either the finished work or a hand-over for a fresh agent.
Nudges start at 250k, 300k and 400k tokens in a 1M window, at 60%, 70% and 80% of a smaller one.
startAt: first nudge, in thousands of tokens; the later steps follow in proportion (150 gives 150k, 180k, 240k). 0 is the ladder above.beforeCompact: a step the agent takes first, e.g. run the debrief skill.summaryNote: an instruction the compactor gets every time, e.g. the language of the summary.Ask the agent, or run claude plugin configure smart-compact@alfreds-plugins.
claude --plugin-dir plugins/smart-compact loads the folder, claude plugin test plugins/smart-compact runs the tests, and docs/smart-compact.md holds the engine facts the design rests on.
hooks/register.ts 129 lines1import type { EngineInterface, Register } from 'claude-code'
2
3import {
4 FOCUS_DOC, FOCUS_LIMIT, compactInstructions, contextTokens, decide, handoverText, levelsFor, nudgeText, resumeText, squash,
5 toolDescription,
6} from './ladder'
7
8const NAME = 'compact_me'
9const TOOL = 'mcp__smart-compact__compact_me'
10
11const focus = { plugin: 'smart-compact', key: 'focus' } as const
12const resuming = { plugin: 'smart-compact', key: 'resuming' } as const
13
14export const register: Register = (on, options) => {
15 const before = String(options.beforeCompact ?? '').trim()
16 const note = String(options.summaryNote ?? '').trim()
17 const startAt = Math.max(0, Number(options.startAt ?? 0) || 0) * 1000
18 const main: Main = { nudged: 0, queued: false, startAt, before }
19 const agents = new Map<string, { tokens: number; nudged: number }>()
20
21 on('session.start', async ($, e, next) => {
22 await $.tool.register({
23 name: NAME,
24 description: toolDescription(before),
25 inputSchema: {
26 type: 'object',
27 properties: { focus: { type: 'string', description: FOCUS_DOC } },
28 required: ['focus'],
29 },
30 isDeferred: false,
31 })
32 const started = await next(e)
33 await resume($)
34 return started
35 })
36
37 on('tool.call', { tool: TOOL }, async ($, e) => {
38 if (e.agentId !== undefined) return { deny: `${NAME}: only the main session compacts.` }
39 const text = squash(typeof e.focus === 'string' ? e.focus : '')
40 if (text === '') return { deny: `${NAME}: focus is empty. Name the task the work continues with. Nothing queued.` }
41 if (text.length > FOCUS_LIMIT) {
42 return { deny: `${NAME}: focus is ${text.length} characters, limit ${FOCUS_LIMIT}. Shorten it. Nothing queued.` }
43 }
44 await $.state.set(focus, text)
45 main.queued = true
46 return { result: 'Queued: the conversation is compacted once this turn ends, and the task continues after it. End the turn now, with one line saying what follows.' }
47 }).catch(($, e, next) => (next.called ? next(e) : { deny: `${NAME}: failed, nothing queued.` }))
48
49 on('turn.step', async function* ($, e, next) {
50 const step = yield* next(e)
51 if (e.agentId !== undefined && step.usage !== null) {
52 agents.set(e.agentId, { tokens: contextTokens(step.usage), nudged: agents.get(e.agentId)?.nudged ?? 0 })
53 }
54 return step
55 })
56
57 on('prompt.submit', async ($, e, next) => {
58 const nudge = await mainNudge($, main)
59 return next(nudge === null ? e : { ...e, context: [...(e.context ?? []), nudge] })
60 }).catch(($, e, next) => next(e))
61
62 on('tool.call', async ($, e, next) => {
63 const ran = await next(e)
64 if (e.tool === TOOL || ran.deny !== undefined) return ran
65 const agent = e.agentId
66 if (agent === undefined) {
67 const nudge = await mainNudge($, main)
68 return nudge === null ? ran : { ...ran, context: [...(ran.context ?? []), nudge] }
69 }
70 const levels = levelsFor((await $.session.usage()).context.window, startAt)
71 const who = agents.get(agent)
72 if (who === undefined) return ran
73 const [due, remember] = decide(who.tokens, who.nudged, levels)
74 who.nudged = remember
75 if (due === null) return ran
76 return { ...ran, context: [...(ran.context ?? []), handoverText(who.tokens, levels)] }
77 }).catch(($, e, next) => next(e))
78
79 on('turn.complete', async ($, e, next) => {
80 const done = await next(e)
81 if (e.agentId !== undefined) {
82 agents.delete(e.agentId)
83 return done
84 }
85 main.queued = false
86 const { value: planned = null } = await $.state.get(focus)
87 if (planned === null) return done
88 await $.state.set(focus, null)
89 if (e.reason !== 'answer') {
90 $.ui.toast('smart-compact: the turn was interrupted, the queued compaction dropped')
91 return done
92 }
93 await $.state.set(resuming, resumeText())
94 $.clock.after(0, () => void compact($, compactInstructions(planned, before, note)))
95 return done
96 })
97}
98
99type Main = { nudged: number; queued: boolean; readonly startAt: number; readonly before: string }
100
101/** The main session's nudge when its context passed a new step, else null; none while a compaction is queued. */
102async function mainNudge($: EngineInterface, main: Main): Promise<string | null> {
103 if (main.queued) return null
104 const { tokens = 0, window } = (await $.session.usage()).context
105 const levels = levelsFor(window, main.startAt)
106 const [due, remember] = decide(tokens, main.nudged, levels)
107 main.nudged = remember
108 return due === null ? null : nudgeText(tokens, levels, main.before, TOOL)
109}
110
111async function compact($: EngineInterface, instructions: string): Promise<void> {
112 try {
113 await $.command.run({ command: 'compact', args: instructions })
114 } catch (error) {
115 await $.state.set(resuming, null)
116 $.ui.toast(`smart-compact: /compact failed: ${String(error)}`)
117 return
118 }
119 await resume($)
120}
121
122/** Submits the planned continue prompt once; a reload of the mod during /compact submits it from session.start. */
123async function resume($: EngineInterface): Promise<void> {
124 const { value: planned = null } = await $.state.get(resuming)
125 if (planned === null) return
126 await $.state.set(resuming, null)
127 await $.prompt.submit({ text: planned })
128}
129hooks/ladder.ts 95 lines1export type Levels = readonly (readonly [start: number, step: number])[]
2
3/** [start, step] for a 1M window, and the share of a smaller window a start is capped at. */
4const LADDER = [
5 [250_000, 25_000, 0.6],
6 [300_000, 20_000, 0.7],
7 [400_000, 10_000, 0.8],
8] as const
9export const FOCUS_LIMIT = 280
10
11export const FOCUS_DOC =
12 `A tweet-size instruction for the compactor, up to ${FOCUS_LIMIT} characters, so it understands your intent: ` +
13 'which task you will continue. A summary or a retelling of key numbers and facts is FORBIDDEN here. ' +
14 'Example: "focus on the auth bug fix; the deploy is finished".'
15
16/** startAt (tokens) moves the whole ladder in proportion to its first start, whatever the window; 0 is automatic. */
17export function levelsFor(window: number, startAt = 0): Levels {
18 return LADDER.map(([start, step, share]) => {
19 const scale = startAt > 0 ? startAt / LADDER[0][0] : Math.min(1, (share * window) / start)
20 return [Math.round(start * scale), Math.round(step * scale)] as const
21 })
22}
23
24export function levelFor(tokens: number, levels: Levels): number {
25 let level = 0
26 for (const [start, step] of levels) {
27 if (tokens >= start) level = start + Math.floor((tokens - start) / step) * step
28 }
29 return level
30}
31
32/** [level to nudge about or null, level to remember]; a size that fell re-arms the ladder. */
33export function decide(tokens: number, nudged: number, levels: Levels): [number | null, number] {
34 const level = levelFor(tokens, levels)
35 return [level > nudged ? level : null, level]
36}
37
38export function toolDescription(before: string): string {
39 return (
40 'Compacts the conversation once this turn ends, with `focus` as an instruction to the compactor, ' +
41 'then tells you to continue the task. ' +
42 'A compaction is the first step of a piece of work. Call this when the context reminder has come and ' +
43 'a piece of work lies ahead of you, before you touch it: the next subtask of a long job, or the task ' +
44 'the user has just handed you. Then end the turn with one line saying what follows; the piece begins ' +
45 `after the compaction.${before ? ` Before calling it, ${before}.` : ''}`
46 )
47}
48
49export function nudgeText(tokens: number, levels: Levels, before: string, tool: string): string {
50 const [[calm = 0] = [], [pressing = 0] = [], [urgent = 0] = []] = levels
51 const how = before ? `First ${before}, then call \`${tool}\`` : `Call \`${tool}\``
52 const k = (n: number) => Math.floor(n / 1000)
53 if (tokens >= urgent) {
54 return `Context ${k(tokens)}k > ${k(urgent)}k. Compact now, as the first step of whatever work is in front of you. ${how}; the work begins after the compaction.`
55 }
56 if (tokens >= pressing) {
57 return `Context ${k(tokens)}k > ${k(pressing)}k. Strongly advised: compact as the first step of the very next subtask, as soon as it is in front of you. ${how}; the subtask begins after the compaction.`
58 }
59 return `Context ${k(tokens)}k > ${k(calm)}k. Compact as the first step of the next piece of work, once that piece is in front of you: a subtask you are about to start, or a task the user has just given. ${how}; the piece begins after the compaction.`
60}
61
62const HANDOVER =
63 'write a hand-over for a fresh agent (done, left, next step, dead ends, touched files) to a new file ' +
64 'in the session scratchpad or a temporary directory and end. Open your reply with: the hand-over in <path> ' +
65 'is for the next agent, no need to read it, just give that agent the path instead of resuming me.'
66
67/** The subagent's ladder: nothing compacts a subagent, so it hands its work over instead. */
68export function handoverText(tokens: number, levels: Levels): string {
69 const [, [pressing = 0] = [], [urgent = 0] = []] = levels
70 const size = `Context ${Math.floor(tokens / 1000)}k`
71 if (tokens >= urgent) return `${size}. Stop now: ${HANDOVER}`
72 if (tokens >= pressing) {
73 return `${size}. Three quarters of your task done? Finish it. Less? At the next stopping point ${HANDOVER}`
74 }
75 return `${size}: a lot, not a limit. Two thirds of your task done? Carry on. Less? Finish the piece you are on, then ${HANDOVER}`
76}
77
78/** A request's whole context: what it read, cached or not, and what it wrote. */
79export function contextTokens(usage: { input_tokens: number; output_tokens: number; cache_read_input_tokens: number; cache_creation_input_tokens: number }): number {
80 return usage.input_tokens + usage.cache_read_input_tokens + usage.cache_creation_input_tokens + usage.output_tokens
81}
82
83export function squash(text: string): string {
84 return text.split(/\s+/).filter(Boolean).join(' ')
85}
86
87export function compactInstructions(focus: string, before: string, note: string): string {
88 const routine = `Omit the compaction routine itself: context nudges, ${before ? 'the step before compacting, ' : ''}compact_me.`
89 return [focus, routine, note].filter(Boolean).join(' ')
90}
91
92export function resumeText(): string {
93 return 'Context compacted. Continue the task.'
94}
95types/index.d.ts 15 lines1export type Focus = string | null
2
3declare module 'claude-code' {
4 interface PluginState {
5 'smart-compact': {
6 focus: Focus
7 resuming: string | null
8 }
9 }
10
11 interface McpToolInputs {
12 'mcp__smart-compact__compact_me': { focus: string }
13 }
14}
15