Shrink a long session by replacing old tool results in the session file with saved-file placeholders, then reloading it

A Claude Code 2.1.304 mod (function-hook plugin). It shrinks a long session while you keep working in it: at an idle point it replaces old, large tool results in the session file with a <persisted-output> placeholder that points to a saved copy. Every other line stays as it is. Then it queues /resume <same session id>, so the session loads the shaken file at once.
The mod uses no compaction. On a Team or Enterprise login, the built-in cc-plugin-sec-default guard skips the session.compact hook of a user plugin, so the compaction route of 0.3.x did not work there.
The plugin name is shake, because Claude Code reserves names that start with claude-.
The design decisions live in the agents repo, not here. These links assume both repos are checked out side by side under ~/Repos.
docs/research/ holds frozen copies of the reports and reviews the ADR cites. Update the ADR, not the copies.
thresholdTokens, and the shake frees at least floorShare of it, the mod shakes. After a try, the next one waits until the context grows by floorShare.ephemeral_1h_input_tokens (60 minutes) or ephemeral_5m_input_tokens (5 minutes). This follows CLAUDE_CODE_PROMPT_CACHE_TTL, promptCacheTtl and the plan default without reading them. With no cache write found, the mod uses 60./shake. It has no floor.<project dir>/<session id>/shake/<tool_use_id>.txt (file mode 600, directory mode 700, never overwritten). Its text becomes the native placeholder: Output too large (…). Full output saved to: <path> and a 500-character preview that ends on a code point.[shaken:, <persisted-output> or <truncated-output> is never shaken again. Claude Code itself saves large new results as <persisted-output> (measured on 2.1.304: a 25,000-character Bash output), so these are not shaken.bin/shake_io.py shake):content of each selected tool_result block, in every row that holds it, and changes no other line. tool_use blocks, ids, is_error flags, thinking, attachment rows and toolUseResult records stay;<session>.jsonl.shake-bak.<ns>) exists until the rename succeeded. If rows reached the old file during the rename, the rewrite copies them to the new file and keeps that backup. After each rewrite, only the newest backup of the session stays.A prompt that you send during the rewrite waits for it.
/resume <same session id> with $.command.run. It runs when the main loop is idle and redraws the transcript from the file. Background shells and background subagents keep running across it, and their results still reach the session (measured). Classic SessionEnd and SessionStart hooks run with the source resume.Shook N tool results (~X tokens freed)., as omp shows it. /shake with nothing to shake shows Nothing to shake.20 x kept / freed requests with the 1 h cache.python3 on PATH. The file work runs in bin/shake_io.py, because the mod environment has no rename, fsync or file modes.-p) session has no /resume command: the mod shakes the file, and the session loads it at its next --resume.Install from GitHub:
claude plugin marketplace add serhiichuk/claude-shake
claude plugin install shake@claude-shake
To get a new version, run claude plugin marketplace update claude-shake.
Load the plugin from a local clone for one session:
claude --plugin-dir /path/to/claude-shake
--plugin-dir overrides an installed copy of the same plugin for that session.
Four values are plugin settings. Change them in /config, or in settings.json under pluginConfigs.shake.options.
| Setting | Default | Meaning |
|---|---|---|
thresholdTokens | 150000 | Used context that starts a threshold shake |
floorShare | 0.33 | Least share of the used context a threshold shake must free |
idleShake | true | Shake with no floor when the prompt cache expires |
cacheTtlMinutes | 0 | Cache lifetime override; 0 reads it from the session |
The other values are in CONFIG in hooks/shake.ts:
| Key | Default | Meaning |
|---|---|---|
keepTokens | 16000 | Newest tool output that is never shaken |
tokensPerChar | 0.34 | Token estimate for one character |
minResultChars | 2000 | Smallest result that is shaken |
With --plugin-dir, a saved edit reloads the module in the running session.
bin/shake-fork <session id or path>: copies a session to a new id in the same project directory. Only the sessionId values change; cost-state rows are left out. The source file is read only, and its sha256 is checked before and after. It prints the claude --resume command with a cd to the cwd of the first row: Claude Code finds a session through the project directory of the directory the session started in, not the last cwd. If that cwd does not map to the project directory name, it prints a warning.bin/shake-check <session.jsonl>: prints rows, boundaries with or without anchors, and what the loader would load: duplicate message blocks, tool_use ids and tool_result ids, dangling parents, thinking blocks, shaken results and saved files present. It mirrors the 2.1.293 loader on a best-effort basis.Each step that sends a prompt to the model costs API tokens.
bin/shake-fork <session id>. Expected: source sha256 (unchanged), a fork: path and a cd … && claude --resume <new id> --plugin-dir … command.bin/shake-check <fork path>. Keep the output as the baseline.claude --debug shows the plugin's lines in the debug log./context and note the used tokens./shake. Expected: the transcript redraws, then the dim line Shook N tool results (~X tokens freed)., or Nothing to shake.bin/shake-check <fork path>. Expected:duplicate_* counts are 0;dangling_parents is 0;saved_files_missing is 0.Reply with ok. Expected: a normal answer./context. Expected: fewer used tokens than in step 5./context shows about the same usage as in step 9.thresholdTokens to a value under the current usage (or cacheTtlMinutes to 1 for the idle shake, which then fires 90 s after the last request), and send one prompt. Expected: the same redraw and line as in step 6..jsonl file and the <project dir>/<new id>/ directory.Live tests on 2.1.304 with the Team login and the guard active (Haiku forks, 2026-10-20; report in ~/.agents/artifacts/claude-shake/main/20261020-file-route-spike/):
/resume <same id> loaded an edited file: a fork with 2 results replaced sent 7,019 fewer tokens than the unedited control.turn.complete shook 11 results. The next request sent 140,250 tokens against 171,658 before.cacheTtlMinutes: 1) and shook 8 results.bin/shake-check reported 0 duplicates, 0 dangling parents and 0 missing saved files.SessionStart hooks add their context again./rewind and fork after a shake, Monitor tasks and cron jobs across the reload.claude plugin validate .
claude plugin test . # selection, placeholder and preview unit checks
python3 test/test_io.py # save, shake, cache, check and fork on a copied fixture
test/test_io.py takes a session file with large tool results as its argument. The default is the e3 file of the live-shake research run. The fixture is only copied.
Type-check: after one load with --plugin-dir, the engine writes .claude-plugin/types/, and tsc -p . works. Before that, use the tsconfig.json from the header of the types file that the plugin-authoring skill writes.
hooks/register.ts 131 lines1import type { EngineInterface, Register, Timer } from 'claude-code'
2
3import { CONFIG, type Config, freedTokens, placeholder, selectOld } from './shake'
4
5type Trigger = 'manual' | 'threshold' | 'idle'
6
7const DEFAULT_CACHE_TTL_MINUTES = 60
8// Waits past the TTL with a margin, as omp does (90 min for the 1 h TTL): a shake on a still-warm cache pays a full cache write.
9const CACHE_EXPIRY_MARGIN = 1.5
10
11const runHelper = async ($: EngineInterface, args: string[], stdin?: string) =>
12 $.process.run(['python3', `${$.plugin.root}/bin/shake_io.py`, ...args], { stdin, timeoutMs: 60_000 })
13
14const runJson = async <T>($: EngineInterface, args: string[], stdin: unknown): Promise<T> => {
15 const run = await runHelper($, args, JSON.stringify(stdin))
16 if (run.exitCode !== 0) throw new Error(`shake_io ${args[0]} exit ${run.exitCode}: ${run.stdout.trim()}`)
17 return JSON.parse(run.stdout) as T
18}
19
20let writing: Promise<void> | undefined
21let retryAboveTokens = 0
22let idleShake: Timer | undefined
23let idleArmings = 0
24
25const plural = (count: number, noun: string): string => `${count} ${noun}${count === 1 ? '' : 's'}`
26
27// Rewrites the tool results in the session file; the live process sends them only after the queued /resume reloads it.
28const shake = async ($: EngineInterface, config: Config, trigger: Trigger): Promise<void> => {
29 const old = selectOld(await $.session.messages())
30 if (old.length === 0) {
31 if (trigger === 'manual') $.ui.log('Nothing to shake.')
32 return
33 }
34 if (trigger === 'threshold') {
35 const tokens = (await $.session.usage()).context.tokens ?? 0
36 if (tokens < config.thresholdTokens || tokens < retryAboveTokens) return
37 // Also stops a retry each turn when the reload fails (headless): the next try waits until the context grows.
38 retryAboveTokens = tokens * (1 + config.floorShare)
39 if (freedTokens(old) < config.floorShare * tokens) return
40 }
41 const id = await $.session.id()
42 const write = (async () => {
43 const items = old.map(result => ({ id: result.tool_use_id, text: result.text }))
44 const saved = await runJson<Record<string, string>>($, ['save', id], { items })
45 const replacements = Object.fromEntries(
46 old.filter(result => saved[result.tool_use_id]).map(r => [r.tool_use_id, placeholder(saved[r.tool_use_id]!, r.text)]),
47 )
48 return runJson<{ replaced: string[] }>($, ['shake', id], replacements)
49 })()
50 writing = write.then(() => undefined, () => undefined)
51 const { replaced } = await write.finally(() => {
52 writing = undefined
53 })
54 if (replaced.length === 0) {
55 if (trigger === 'manual') $.ui.log('Nothing to shake.')
56 return
57 }
58 await $.command.run({ command: 'resume', args: id })
59 retryAboveTokens = 0
60 // An id repeats in the list for each row it was replaced in (copies from before a compaction boundary).
61 const shaken = old.filter(result => replaced.includes(result.tool_use_id))
62 $.ui.log(`Shook ${plural(shaken.length, 'tool result')} (~${Math.round(freedTokens(shaken))} tokens freed).`)
63}
64
65let shaking: Promise<void> | undefined
66
67const startShake = ($: EngineInterface, config: Config, trigger: Trigger): void => {
68 shaking ??= shake($, config, trigger)
69 .catch(error => $.ui.log(`${trigger} shake failed: ${String(error)}`, { to: 'debug' }))
70 .finally(() => {
71 shaking = undefined
72 })
73}
74
75type CacheState = { lastRequestMs: number | null; ttlMinutes: number | null }
76
77const readCache = async ($: EngineInterface): Promise<CacheState> => {
78 const run = await runHelper($, ['cache', await $.session.id()])
79 if (run.exitCode !== 0) throw new Error('shake could not read the session cache state', { cause: run })
80 return JSON.parse(run.stdout) as CacheState
81}
82
83// Fires when the prompt cache expires: then the next request writes it whole anyway, so a shake is free.
84const armIdleShake = async ($: EngineInterface, config: Config, lastRequestMs?: number): Promise<void> => {
85 const arming = ++idleArmings
86 idleShake?.cancel()
87 if (!config.idleShake) return
88 const cache = await readCache($)
89 const since = lastRequestMs ?? cache.lastRequestMs
90 if (since === null) return
91 const ttlMinutes = config.cacheTtlMinutes || cache.ttlMinutes || DEFAULT_CACHE_TTL_MINUTES
92 const delay = Math.max(0, since + ttlMinutes * CACHE_EXPIRY_MARGIN * 60_000 - (await $.clock.now()))
93 if (arming !== idleArmings) return
94 idleShake = $.clock.after(delay, () => startShake($, config, 'idle'))
95}
96
97const logIdleError = ($: EngineInterface) => (error: unknown) =>
98 $.ui.log(`idle shake timer failed: ${String(error)}`, { to: 'debug' })
99
100export const register: Register = (on, options) => {
101 const config = { ...CONFIG, ...options } as Config
102
103 on('session.start', async ($, e, next) => {
104 await $.command.register({ name: 'shake', description: 'shake: replace old tool results now' })
105 void armIdleShake($, config).catch(logIdleError($))
106 return next(e)
107 })
108
109 on('command.run', { command: 'shake' }, async $ => {
110 // The engine refuses a command run from inside the running command's own hook.
111 $.clock.after(0, () => startShake($, config, 'manual'))
112 return {}
113 })
114
115 on('prompt.submit', async (_, e, next) => {
116 idleArmings += 1
117 idleShake?.cancel()
118 // Waits for the file rewrite only: the queued /resume runs after this turn.
119 if (!e.turnId && writing) await writing
120 return next(e)
121 })
122
123 on('turn.complete', async ($, e, next) => {
124 const completed = await next(e)
125 if (e.agentId) return completed
126 void (async () => armIdleShake($, config, await $.clock.now()))().catch(logIdleError($))
127 if (e.reason === 'answer') startShake($, config, 'threshold')
128 return completed
129 })
130}
131hooks/shake.ts 66 lines1import type { SessionMessage, ToolResultSummary } from 'claude-code'
2
3export const CONFIG = {
4 thresholdTokens: 150_000,
5 floorShare: 0.33,
6 idleShake: true,
7 cacheTtlMinutes: 0,
8 keepTokens: 16_000,
9 tokensPerChar: 0.34,
10 minResultChars: 2_000,
11}
12
13export type Config = typeof CONFIG
14
15const PREVIEW_CHARS = 500
16const PLACEHOLDER_OVERHEAD_CHARS = PREVIEW_CHARS + 300
17const SHAKEN_PREFIXES = ['[shaken:', '<persisted-output>', '<truncated-output>']
18
19export const isShaken = (text: string): boolean => {
20 const head = text.trimStart()
21 return SHAKEN_PREFIXES.some(prefix => head.startsWith(prefix))
22}
23
24const resultsOf = (messages: readonly SessionMessage[]): ToolResultSummary[] =>
25 messages.flatMap(message => message.toolResults ?? [])
26
27export const selectOld = (messages: readonly SessionMessage[], config: Config = CONFIG): ToolResultSummary[] => {
28 const keepChars = config.keepTokens / config.tokensPerChar
29 const old: ToolResultSummary[] = []
30 let newerChars = 0
31 for (const result of resultsOf(messages).reverse()) {
32 if (isShaken(result.text)) continue
33 const isInKeepWindow = newerChars < keepChars
34 newerChars += result.text.length
35 if (!isInKeepWindow && result.text.length > config.minResultChars) old.push(result)
36 }
37 return old.reverse()
38}
39
40export const freedTokens = (old: readonly ToolResultSummary[], config: Config = CONFIG): number =>
41 old.reduce((sum, result) => sum + Math.max(0, result.text.length - PLACEHOLDER_OVERHEAD_CHARS), 0) * config.tokensPerChar
42
43const isHighSurrogate = (code: number): boolean => code >= 0xd800 && code <= 0xdbff
44
45export const preview = (text: string, maxChars: number = PREVIEW_CHARS): { text: string; hasMore: boolean } => {
46 if (text.length <= maxChars) return { text, hasMore: false }
47 const newline = text.lastIndexOf('\n', maxChars - 1)
48 let cut = newline > maxChars / 2 ? newline : maxChars
49 if (isHighSurrogate(text.charCodeAt(cut - 1))) cut -= 1
50 return { text: text.slice(0, cut), hasMore: true }
51}
52
53const formatSize = (chars: number): string => {
54 if (chars < 1024) return `${chars} bytes`
55 if (chars < 1024 * 1024) return `${Number((chars / 1024).toFixed(1))}KB`
56 return `${Number((chars / (1024 * 1024)).toFixed(1))}MB`
57}
58
59export const placeholder = (path: string, text: string): string => {
60 const cut = preview(text)
61 return (
62 `<persisted-output>\nOutput too large (${formatSize(text.length)}). Full output saved to: ${path}\n\n` +
63 `Preview (first ${formatSize(PREVIEW_CHARS)}):\n${cut.text}${cut.hasMore ? '\n...\n' : '\n'}</persisted-output>`
64 )
65}
66