Frees the memory of idle Claude Code sessions (desktop app, VS Code, CLI) by stopping their process trees (desktop sessions stay in the sidebar), optionally…

A Claude Code mod for Windows: the Claude desktop app, the VS Code extension and the CLI. Every few minutes it:
claude.exe, its MCP servers, shells and helpers). The session stays in the sidebar, keeps its conversation, and the app starts a fresh process when you open it again and send a message. Running sessions, and sessions whose side session is still working, are skipped, except a session still shown as running with no activity for stuckMinutes (default 12 hours). Pinned sessions are released like any other. The session doing the work releases itself last once it is idle too, so the next active session takes over.claude.exe included. Each such session records when its last turn started or ended; a session with a turn in progress is skipped. A background task (shell, monitor, subagent, workflow) or a scheduled wakeup (/loop, CronCreate, ScheduleWakeup) does not keep it: the only event that reports them, Stop, never reaches an installed plugin where cc-plugin-sec-default is seated. The conversation stays in its transcript on disk.archiveMinutes, off by default). Running and pinned sessions are skipped; the app itself also refuses sessions that are open on screen or still have background work. Archived sessions can be restored from the Archived list.claude.exe started (MCP servers, dev servers, shells). Once that claude.exe is gone, a tree is stopped only when every process in it is at least 60 minutes old and used almost no CPU since the previous check. chrome.exe, msedge.exe, Code.exe, claude.exe, explorer.exe and WindowsTerminal.exe are never stopped (a released session's own claude.exe is the one exception).Every open session loads the mod. Each one reports its own claude.exe to the plugin store once, so the sessions can be mapped to their processes; a heartbeat in the plugin store picks one session to do the work. Releasing and archiving desktop sessions have one leader per desktop app instance, because the app lists only its own sessions; two instances with different data folders each release their own. Releasing VS Code and CLI sessions and orphan cleanup have one leader for the whole machine: a desktop session takes it over from a CLI or VS Code session, which leads only while no desktop session runs.
Each desktop Code session keeps its own claude.exe (about 0.4 GB) plus its own copy of every MCP server, about 1.6 to 3.2 GB per session in all, and none of it goes away while the session sits in the sidebar. On a 32 GB machine, a day of work left 38 claude.exe (15 GB) and 88 node.exe (8 GB) processes running, the commit charge reached 47.1 of 47.6 GB, and Chrome crashed with an out-of-memory error. Releasing the idle sessions frees that memory without losing the sessions.
C:\Windows (the process steps run C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe by its fixed path and read Win32_Process).ccd_session_mgmt server.permissions.allow in ~/.claude/settings.json: "mcp__ccd_session_mgmt__archive_session"
The rule also lets Claude archive sessions in any chat without asking.
/plugin install session-reaper --marketplace IT-BAER/claude-forge
| Option | Default | Meaning |
|---|---|---|
idleMinutes | 60 | Release a session idle for this many minutes (stop its process tree; a desktop session stays in the sidebar, a VS Code or CLI session in its transcript) |
stuckMinutes | 720 | Release a session the app still shows as running after this many minutes without activity; 0 = never |
archiveMinutes | 0 | Also archive a session idle for this many minutes; 0 = never |
orphanMinutes | 60 | Minimum age of every process in a left-behind tree |
cpuIdleMs | 1000 | Most CPU time (ms) a process may use between two checks and still count as idle |
intervalMinutes | 5 | How often the active session checks |
Only sessions that loaded this version of the mod can be released (a session loads it when it starts), and only processes seen under a running claude.exe while the mod runs are tracked as orphans; trees left behind before the mod loaded are not touched.
hooks/register.ts 298 lines1import type { EngineInterface as Engine, Register } from 'claude-code'
2
3type Row = { pid: number; ppid: number; name: string; created: string; cpu: number }
4type Proc = { pid: number; created: string }
5type Tracked = Record<string, { cpu: number }>
6// The app's session id -> the claude.exe that session runs in, reported by that session's own mod instance.
7type Owned = Record<string, Proc>
8type Session = { sessionId: string; isArchived?: boolean; isRunning?: boolean; pinned?: boolean; lastActivityAt?: string; startedBy?: string; title?: string }
9
10const MIN = 60_000
11const SERVER = 'ccd_session_mgmt'
12// Never stopped: shared browsers, editors, the app itself and the shell.
13const SPARED = new Set(['chrome.exe', 'msedge.exe', 'code.exe', 'claude.exe', 'explorer.exe', 'windowsterminal.exe'])
14// A released session loses its own claude.exe (the session process and its claude-in-chrome helper).
15const SPARED_IN_SESSION = new Set([...SPARED].filter(n => n !== 'claude.exe'))
16
17const key = (r: Proc) => `${r.pid}:${r.created}`
18// procs.ps1 prints creation as FILETIME (100 ns since 1601); dropping 4 digits keeps the number exact.
19const createdMs = (created: string) => Number(created.slice(0, -4)) - 11_644_473_600_000
20
21type Cfg = { idleMs: number; archiveMs: number; orphanMs: number; cpuIdle: number; intervalMs: number; stuckMs: number }
22
23function log($: Engine, text: string) {
24 return $.ui.log(`session-reaper: ${text}`, { to: 'debug' })
25}
26
27// Fixed exe path (not SystemRoot, which a project's settings env can set) and the plugin folder as cwd.
28// shortcut: assumes Windows in C:\Windows; elsewhere the process steps fail and only archiving runs.
29const POWERSHELL = 'C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe'
30
31function procs($: Engine, args: string[]) {
32 const script = `${$.plugin.root}/hooks/procs.ps1`
33 return $.process.run([POWERSHELL, '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', script, ...args], { cwd: $.plugin.root, timeoutMs: 60_000 })
34}
35
36function text(res: { isError?: boolean; content: readonly unknown[] }) {
37 const t = res.content.find(c => (c as { type: string }).type === 'text') as { text: string } | undefined
38 return res.isError || !t ? undefined : t.text
39}
40
41// Leader for orphan cleanup, shared by every host. desk: the session reaches the app's session tools; a desk
42// session takes over a live leader without them. shortcut: last writer wins on a simultaneous takeover.
43async function isLeader($: Engine, now: number, cfg: Cfg, desk: boolean) {
44 const me = await $.session.id()
45 const lead = (await $.store.get('leader')) as { id: string; at: number; desk?: boolean } | undefined
46 if (lead && lead.id !== me && now - lead.at < 2.5 * cfg.intervalMs && (lead.desk || !desk)) return false
47 await $.store.set('leader', { id: me, at: now, desk })
48 return true
49}
50
51// Leader for releasing and archiving, one per app instance: list_sessions only returns the caller's own
52// app's sessions. app is the instance's main claude.exe; entries of closed instances are pruned on write.
53async function isAppLeader($: Engine, now: number, cfg: Cfg, app: string) {
54 const me = await $.session.id()
55 const apps = ((await $.store.get('apps')) ?? {}) as Record<string, { id: string; at: number }>
56 const lead = apps[app]
57 if (lead && lead.id !== me && now - lead.at < 2.5 * cfg.intervalMs) return false
58 for (const [k, v] of Object.entries(apps)) if (now - v.at >= 2.5 * cfg.intervalMs) delete apps[k]
59 apps[app] = { id: me, at: now }
60 await $.store.set('apps', apps)
61 return true
62}
63
64// A session without the app's session tools (VS Code, CLI) keeps its own activity record under
65// `cli:<its claude.exe>`, one store key per session so concurrent writers never overwrite each other.
66type Activity = { at: number; busy: boolean }
67type Me = { proc?: Proc; app?: string; sessionId?: string; act: Activity; saved?: string }
68const CLI = 'cli:'
69
70async function saveActivity($: Engine, me: Me) {
71 if (!me.proc || me.sessionId) return
72 const json = JSON.stringify(me.act)
73 if (json === me.saved) return
74 await $.store.set(CLI + key(me.proc), me.act)
75 me.saved = json
76}
77
78async function note($: Engine, me: Me, change: Partial<Activity>) {
79 me.act = { ...me.act, ...change, at: await $.clock.now() }
80 await saveActivity($, me).catch(err => log($, `activity save failed: ${String(err).slice(0, 200)}`))
81}
82
83// Each session publishes its own claude.exe once; the leader needs it to release the session later.
84async function reportSelf($: Engine, me: Me) {
85 if (!me.proc) {
86 const who = await procs($, ['-Self'])
87 if (who.exitCode !== 0) return log($, 'self report failed')
88 const { pid, created, app } = JSON.parse(who.stdout) as Proc & { app?: Proc | null }
89 me.proc = { pid, created }
90 me.app = app ? key(app) : 'desk'
91 }
92 if (!me.sessionId) {
93 const got = text(await $.mcp.call(SERVER, 'get_session', { session_id: 'self' }))
94 if (!got) return saveActivity($, me)
95 me.sessionId = (JSON.parse(got) as Session).sessionId
96 // A desktop session whose app tools answered late may have written a record already.
97 if (me.saved) await $.store.delete(CLI + key(me.proc))
98 }
99 const owned = ((await $.store.get('owned')) ?? {}) as Owned
100 const have = owned[me.sessionId]
101 if (have && have.pid === me.proc.pid && have.created === me.proc.created) return
102 owned[me.sessionId] = me.proc
103 await $.store.set('owned', owned)
104}
105
106async function listSessions($: Engine) {
107 const got = text(await $.mcp.call(SERVER, 'list_sessions', { limit: 200 }))
108 if (!got) { await log($, 'list_sessions failed'); return [] }
109 return JSON.parse(got) as Session[]
110}
111
112const idle = (s: Session, now: number, ms: number) => now - Date.parse(s.lastActivityAt ?? '') > ms
113// Releasable: idle past the limit; a session the app still shows as running only once stuck past stuckMs (0: never).
114const quiet = (s: Session, now: number, cfg: Cfg) =>
115 idle(s, now, cfg.idleMs) && (!s.isRunning || (cfg.stuckMs > 0 && idle(s, now, cfg.stuckMs)))
116
117async function archiveIdle($: Engine, now: number, cfg: Cfg, sessions: Session[]) {
118 for (const s of sessions) {
119 if (s.isArchived || s.isRunning || s.pinned || !idle(s, now, cfg.archiveMs)) continue
120 const done = await $.mcp.call(SERVER, 'archive_session', {
121 session_id: s.sessionId,
122 reason: `idle for ${Math.round((now - Date.parse(s.lastActivityAt ?? '')) / MIN)} min (session-reaper)`,
123 })
124 log($, `archive ${s.title ?? s.sessionId}: ${done.isError ? 'refused' : 'ok'}`)
125 }
126}
127
128type Snap = { rows: Row[]; parent: (r: Row) => Row | undefined; tree: (r: Row) => Row[] }
129async function snapshot($: Engine): Promise<Snap | undefined> {
130 const snap = await procs($, [])
131 if (snap.exitCode !== 0) { await log($, `snapshot failed: ${snap.stderr.slice(0, 200)}`); return }
132 const rows = JSON.parse(snap.stdout) as Row[]
133 const byPid = new Map(rows.map(r => [r.pid, r]))
134 // A parent counts only if it is older than the child; a younger one reused the PID.
135 const parent = (r: Row) => {
136 const p = byPid.get(r.ppid)
137 return p && p.pid !== r.pid && createdMs(p.created) <= createdMs(r.created) ? p : undefined
138 }
139 const children = new Map<number, Row[]>()
140 for (const r of rows) {
141 const p = parent(r)
142 if (p) children.set(p.pid, [...(children.get(p.pid) ?? []), r])
143 }
144 const tree = (r: Row): Row[] => [r, ...(children.get(r.pid) ?? []).flatMap(tree)]
145 return { rows, parent, tree }
146}
147
148// Stops the process tree of each idle session. The session stays in the sidebar; the app starts
149// a fresh process when it is opened again.
150async function releaseIdle($: Engine, now: number, cfg: Cfg, sessions: Session[], me: string | undefined) {
151 const owned = ((await $.store.get('owned')) ?? {}) as Owned
152 const snap = await snapshot($)
153 if (!snap) return
154 const live = new Map(snap.rows.map(r => [key(r), r]))
155 // A session whose side session still works is kept: the side session reports back to it.
156 const parents = new Set(sessions.filter(s => s.isRunning && s.startedBy).map(s => s.startedBy))
157 const kill: Row[] = []
158 let changed = false
159 for (const [id, proc] of Object.entries(owned)) {
160 const root = live.get(key(proc))
161 if (!root || root.name.toLowerCase() !== 'claude.exe') { delete owned[id]; changed = true; continue }
162 const s = sessions.find(x => x.sessionId === id)
163 if (!s || id === me || s.isArchived || parents.has(id) || !quiet(s, now, cfg)) continue
164 const members = snap.tree(root).filter(r => !SPARED_IN_SESSION.has(r.name.toLowerCase()))
165 kill.push(...members)
166 delete owned[id]
167 changed = true
168 log($, `release ${s.title ?? id}: ${members.length} processes`)
169 }
170 if (changed) await $.store.set('owned', owned)
171 if (!kill.length) return
172 const res = await procs($, ['-Kill', kill.map(key).join(',')])
173 log($, `released ${kill.map(r => `${r.name}(${r.pid})`).join(' ')}: ${res.stdout.slice(0, 300)}`)
174}
175
176// list_sessions leaves out the caller, so the app leader judges itself by get_session. Once idle it hands the
177// lead on and stops its own tree, its claude.exe last; the next active session of the app leads.
178async function releaseSelf($: Engine, now: number, cfg: Cfg, sessions: Session[], me: Me) {
179 if (me.act.busy || !me.proc || !me.app || !me.sessionId) return
180 if (sessions.some(s => s.isRunning && s.startedBy === me.sessionId)) return
181 const got = text(await $.mcp.call(SERVER, 'get_session', { session_id: 'self' }))
182 if (!got) return
183 const s = JSON.parse(got) as Session
184 if (s.isArchived || !quiet(s, now, cfg)) return
185 const snap = await snapshot($)
186 const root = snap?.rows.find(r => key(r) === key(me.proc!))
187 if (!snap || !root) return
188 const apps = ((await $.store.get('apps')) ?? {}) as Record<string, unknown>
189 delete apps[me.app]
190 await $.store.set('apps', apps)
191 const owned = ((await $.store.get('owned')) ?? {}) as Owned
192 delete owned[me.sessionId]
193 await $.store.set('owned', owned)
194 const members = snap.tree(root).slice(1).filter(r => !SPARED_IN_SESSION.has(r.name.toLowerCase()))
195 await log($, `release self ${s.title ?? me.sessionId}: ${members.length + 1} processes`)
196 await procs($, ['-Kill', [...members, root].map(key).join(',')])
197}
198
199// Stops the whole tree of each VS Code or CLI session idle past the limit, its claude.exe included:
200// those hosts have no sidebar that keeps the session, so the conversation continues only by resuming it.
201async function releaseCli($: Engine, now: number, cfg: Cfg, snap: Snap, mine: Proc | undefined) {
202 const live = new Map(snap.rows.map(r => [key(r), r]))
203 const kill: Row[] = []
204 for (const k of (await $.store.keys()).filter(k => k.startsWith(CLI))) {
205 const id = k.slice(CLI.length)
206 const root = live.get(id)
207 if (!root || root.name.toLowerCase() !== 'claude.exe') { await $.store.delete(k); continue }
208 const a = (await $.store.get(k)) as Activity | undefined
209 if (!a || a.busy || (mine && id === key(mine)) || now - a.at < cfg.idleMs) continue
210 const members = snap.tree(root).filter(r => !SPARED_IN_SESSION.has(r.name.toLowerCase()))
211 kill.push(...members)
212 await $.store.delete(k)
213 log($, `release cli ${id}: ${members.length} processes, idle ${Math.round((now - a.at) / MIN)} min`)
214 }
215 if (!kill.length) return
216 const res = await procs($, ['-Kill', kill.map(key).join(',')])
217 log($, `released ${kill.map(r => `${r.name}(${r.pid})`).join(' ')}: ${res.stdout.slice(0, 300)}`)
218}
219
220async function stopOrphans($: Engine, now: number, cfg: Cfg, snap: Snap) {
221 const { rows, parent, tree } = snap
222 const underClaude = (r: Row) => {
223 for (let p = parent(r), hops = 0; p && hops < 64; p = parent(p), hops++) if (p.name.toLowerCase() === 'claude.exe') return true
224 return false
225 }
226
227 const before = ((await $.store.get('tracked')) ?? {}) as Tracked
228 const tracked: Tracked = {}
229 const orphans = new Map<string, Row>()
230 for (const r of rows) {
231 if (r.name.toLowerCase() === 'claude.exe') continue
232 if (underClaude(r)) tracked[key(r)] = { cpu: r.cpu }
233 else if (before[key(r)]) { tracked[key(r)] = { cpu: r.cpu }; orphans.set(key(r), r) }
234 }
235 await $.store.set('tracked', tracked)
236
237 const isIdle = (r: Row) =>
238 SPARED.has(r.name.toLowerCase()) ||
239 (now - createdMs(r.created) >= cfg.orphanMs && r.cpu - before[key(r)]!.cpu <= cfg.cpuIdle)
240
241 const kill: Row[] = []
242 for (const root of orphans.values()) {
243 const p = parent(root)
244 if (p && orphans.has(key(p))) continue
245 const members = tree(root)
246 if (members.every(isIdle)) kill.push(...members.filter(m => !SPARED.has(m.name.toLowerCase())))
247 }
248 if (!kill.length) return
249 const res = await procs($, ['-Kill', kill.map(key).join(',')])
250 log($, `stopped ${kill.map(r => `${r.name}(${r.pid})`).join(' ')}: ${res.stdout.slice(0, 300)}`)
251}
252
253async function tick($: Engine, cfg: Cfg, me: Me) {
254 const now = await $.clock.now()
255 try { await reportSelf($, me) } catch (err) { log($, `self report failed: ${String(err).slice(0, 200)}`) }
256 if (me.sessionId && me.app && (await isAppLeader($, now, cfg, me.app))) {
257 const sessions = await listSessions($)
258 if (cfg.archiveMs) try { await archiveIdle($, now, cfg, sessions) } catch (err) { log($, `archive failed: ${String(err).slice(0, 200)}`) }
259 try { await releaseIdle($, now, cfg, sessions, me.sessionId) } catch (err) { log($, `release failed: ${String(err).slice(0, 200)}`) }
260 try { await releaseSelf($, now, cfg, sessions, me) } catch (err) { log($, `self release failed: ${String(err).slice(0, 200)}`) }
261 }
262 if (!(await isLeader($, now, cfg, !!me.sessionId))) return
263 const snap = await snapshot($)
264 if (!snap) return
265 try { await releaseCli($, now, cfg, snap, me.proc) } catch (err) { log($, `cli release failed: ${String(err).slice(0, 200)}`) }
266 try { await stopOrphans($, now, cfg, snap) } catch (err) { log($, `orphans failed: ${String(err).slice(0, 200)}`) }
267}
268
269export const register: Register = (on, options) => {
270 const num = (v: unknown, d: number) => (typeof v === 'number' && v > 0 ? v : d)
271 const idleMs = num(options.idleMinutes, 60) * MIN
272 const archiveMs = num(options.archiveMinutes, 0) * MIN
273 const orphanMs = num(options.orphanMinutes, 60) * MIN
274 const cpuIdle = num(options.cpuIdleMs, 1000) * 10_000
275 const intervalMs = num(options.intervalMinutes, 5) * MIN
276 const stuckMs = (typeof options.stuckMinutes === 'number' && options.stuckMinutes >= 0 ? options.stuckMinutes : 720) * MIN
277 const cfg: Cfg = { idleMs, archiveMs, orphanMs, cpuIdle, intervalMs, stuckMs }
278 const me: Me = { act: { at: 0, busy: false } }
279
280 on('session.start', async ($, e, next) => {
281 const started = await next(e)
282 me.act.at = await $.clock.now()
283 void reportSelf($, me).catch(err => log($, `self report failed: ${String(err).slice(0, 200)}`))
284 $.clock.every(intervalMs, () => void tick($, cfg, me))
285 return started
286 })
287 // Main loop only: a subagent's run happens inside a main turn or is a background task.
288 on('turn.start', async ($, e, next) => {
289 if (e.agentId === undefined) await note($, me, { busy: true })
290 return next(e)
291 })
292 on('turn.complete', async ($, e, next) => {
293 const done = await next(e)
294 if (e.agentId === undefined) await note($, me, { busy: false })
295 return done
296 })
297}
298