Write a handover when a Claude Code session gets long, type /clear, and the next session picks up where you left off with nothing to paste.

Clear the chat. Keep the goal, the next step and the decisions.
Before you /clear a long Claude Code chat, type /clear-resume:handover. Claude writes a short note about the work, called a handover: the goal, the next action, where things stand, the decisions made and what already failed. The plugin saves it. After /clear, the fresh session starts with the handover already loaded, so you type go and Claude carries on. Nothing to paste.
Coming back to a 390k-token session after the prompt cache expired cost US$1.56; a handover written while the cache was warm, plus a fresh session reading it, cost US$0.15 to US$0.17 (Sonnet 5.5, n=3 each, 10 Oct 2026). The handover is a plain text file you can read and edit. On a 30-item build, the relay and Claude Code's auto-compaction each finished 5 of 6 runs at about the same tokens.
/clear-resume:handover: Claude reads your branch, your changes and your last few commits, then writes and saves the handover./clear: the fresh session loads it.go: Claude carries on from it.Optional settings, all off by default:
auto_nudge): when the chat's context passes Nudge at (250k tokens by default), Claude is asked to save a handover, and asked again at a turn end (up to 3 asks in all) if it neither saved one nor replied "Nothing to hand over." or "Handover not yet: ...".relay): after Claude saves a handover, the plugin runs /clear and submits the prompt that continues from it, up to the number of clears you allow. It stops when the budget is used or when two continued sessions in a row make no new commit. Needs Claude Code 2.1.275 or later.idle_handover: off, toast or auto; with cache_ttl_minutes, default 60, and idle_min_tokens, default 100000): when you have been away until about 5 minutes before the prompt cache would expire and the context is at least idle_min_tokens, show a status message (toast) or ask Claude for a handover and clear, leaving the new session waiting for you (auto), or the same where Claude may answer "Nothing to hand over." when the work is finished and then nothing is saved or cleared (smart); auto and smart need cache_ttl_minutes of 10 or more, else they act as toast. Once per session, in interactive sessions, with the relay on or off. Measured on Sonnet 5.5, 390k tokens, 60 minute cache, 10 Oct 2026 (the 5 minute API-key default was not measured): resuming cold cost US$1.56 (n=3), a handover written while the cache was warm US$0.15 to US$0.17 in all (n=3), and the saving exists only if you come back. Details: HOW-IT-WORKS.SessionStart (startup, clear and compact) loads a waiting handover. PostToolUse and Stop check the context size for the nudge and the relay. Each hook runs node on a script in this plugin, and exits quietly if Node 18 or later is missing.git in your repo to read the branch, status and recent commits. It never switches your branch or touches your index or files, and outside web mode (below) it never commits or pushes.~/.clear-resume. Each loaded handover is also copied to ~/.clear-resume/loaded/ for 30 days. Keep secrets out of them.CLEAR_RESUME_WEB=1, for Claude Code on the web) pushes each handover to its own clear-resume/<branch> branch on your repo's origin, and runs one git fetch origin at session start. Handovers found in git are listed as untrusted and never loaded on their own.hooks/relay.ts)A mod is a function-hooks module that runs inside Claude Code. This one runs the relay. It also runs the optional idle handover (below), and nothing else.
relay setting, or /relay typed in that window. Otherwise it registers the /relay command and the status line, and nothing more.git rev-parse HEAD in the current repo, with a 5 second timeout (the headOf function). The stall guard compares the commit before and after each continued session, to stop when two in a row make no new commit. If git is missing or fails, it carries on without the check. With idle_handover on, it can also run node <plugin>/scripts/context-tokens.mjs <transcript> (see Idle handover below). It starts no other program./clear, once after Claude saves a handover, and only while the number of clears used is below the budget you set.~/.clear-resume/relay/<key>.json (or $CLEAR_RESUME_HOME/relay/<key>.json). Fields: v, key, cwd, sessions (this window's session ids, up to 100), limit, configured, used, stalled, applied, updatedAt. Only the VS Code status bar reads it (the extension that ships with clear-resume), to show the clears left. The mod also reads <key>.set.json beside it, which the status bar writes to change the budget. It writes no settings, build, start-up or instructions file.idle_handover is toast or auto, with the relay on or off. It then reads the clock after each reply that finished normally, counts the tool calls and turns in flight, and every 30 seconds looks at whether the cache is about to expire. Only when that is due does it read the context size: from $.session.usage(), else by running one extra program, node <plugin>/scripts/context-tokens.mjs <transcript>, on the session transcript under ~/.claude/projects (or $CLAUDE_CONFIG_DIR/projects), with a 15 second timeout. It then sets a status line message that stays until your next turn and shows a toast or, with auto, submits "Write a clear-resume handover now, with the /clear-resume:handover skill. The user is away. If a question is open, the Next action is to wait for their answer; do not guess." as if you typed it, and runs /clear once that handover is saved (it does not submit the continue prompt). With smart it submits "The user is away and the prompt cache is about to expire. If the work is finished and no step remains, do not save a handover: reply "Nothing to hand over." and stop. Otherwise write a clear-resume handover now, with the /clear-resume:handover skill. If a question is open, the Next action is to wait for their answer; do not guess." instead, and clears only if a handover was saved. It writes one marker file, ~/.clear-resume/.idle/<session id>, so it acts once per session; it does not touch the .nudged mark. It sends nothing anywhere./relay command (off, on, unlimited or a number), the status line entry that shows the clears left, and toasts that report a stop or a refused command.tool.call and turn.start hooks. Registered only when idle_handover is not off; with it off they do not exist. They only count calls and turns in flight, and turn.start clears the idle status message. They do not filter, rewrite or deny anything,. On an unanswered AskUserQuestion in smart or auto mode, once the cache is about to expire, the mod saves a handover by script (no prompt, no /clear) and shows a toast and status line saying which handover was saved and when. It never changes your answer.command.run hook. It is the handler for the plugin's own /relay command, and it only answers that command. It does not filter, rewrite or decide on any other command.Node 18 or later and git. On Windows, Claude Code runs plugin hooks through Git Bash, which comes with Git for Windows.
/compact and --resume: https://github.com/m4cd4r4/clear-resumeMIT licence.
hooks/relay.ts 783 lines1import type { Register } from 'claude-code'
2
3// The relay: after Claude saves a handover, run /clear and submit the prompt
4// that continues from it, so nobody has to type anything. Opt-in through the
5// `relay` option, which is also the budget: how many clears this process may
6// run before it stops and leaves the next one to the user. /relay overrides
7// the option for this window (this process) only, and the status line shows
8// what is left while it is on.
9//
10// The module lives in the process and /clear keeps the process, so `pending`
11// and `used` survive the clear. A reload (a config change, an update) starts
12// them over. No session.start fires after a clear: session.end with reason
13// 'clear' is the signal that the new conversation is there, and by then the
14// SessionStart hook has loaded the handover.
15//
16// The VS Code extension's status bar reads this window's relay from a state file
17// the module writes, <store>/relay/<key>.json, and changes this window's budget
18// by writing <key>.set.json beside it, which the module reads before each clear.
19// Its "Hand over" button writes <key>.handover.json; the module polls for it once
20// a second, idle or not, and runs the handover skill, which the relay then clears
21// and continues from as after any other save. With the relay off it only saves.
22
23// What save.mjs prints on a good save (plugin/scripts/save.mjs).
24export const SAVED = 'Saved handover "'
25export const SAVE_SCRIPT = /scripts\/save\.mjs/
26
27export const RESUME_TEXT = 'Continue from the clear-resume handover that was just loaded.'
28
29// What the status bar's "Hand over" button runs, and the prompt sent instead if
30// the command is refused (a host that does not list plugin skills as commands).
31export const HANDOVER_COMMAND = 'clear-resume:handover'
32export const HANDOVER_TEXT = 'Write a clear-resume handover now, with the /clear-resume:handover skill.'
33const POLL_MS = 1000
34
35// Idle handover. The prompt cache lasts cache_ttl_minutes after the last reply;
36// a handover written before it lapses is read from the cache, one written after
37// pays a full rewrite of the context. The mod acts IDLE_MARGIN_MS before the lapse
38// (or half the TTL when the TTL is short), and only once the context is large.
39// Measured once (n=1, Sonnet 5.5, 390k tokens): README, "Idle handover".
40export const IDLE_MARGIN_MS = 5 * 60_000
41export const IDLE_TICK_MS = 30_000
42export const DEFAULT_TTL_MIN = 60
43export const DEFAULT_IDLE_MIN_TOKENS = 100_000
44export type IdleMode = 'off' | 'toast' | 'smart' | 'auto'
45// auto and smart submit a prompt while the user is away; with a short TTL the window
46// is too narrow to trust that, so they behave as toast (see idleEffective).
47export const AUTO_MIN_TTL_MIN = 10
48
49// What the idle handover asks for. Unlike the 180k nudge nobody is at the keyboard,
50// so the fresh session must wait for the user rather than carry on.
51export const IDLE_HANDOVER_TEXT =
52 HANDOVER_TEXT + ' The user is away. If a question is open, the Next action is to wait for their answer; do not guess.'
53
54// smart: the same ask, but the model may decline when nothing is left to do. The
55// check rides on the warm turn the ask already pays for. A wrong "finished" costs
56// the cold rewrite the user would have paid anyway, never lost work: no save, no clear.
57export const IDLE_SMART_TEXT =
58 'The user is away and the prompt cache is about to expire. If the work is finished and no step remains, ' +
59 'do not save a handover: reply "Nothing to hand over." and stop. Otherwise write a clear-resume handover now, ' +
60 'with the /clear-resume:handover skill. If a question is open, the Next action is to wait for their answer; do not guess.'
61
62// "toast", "smart" or "auto"; anything else, or unset, is off.
63export function idleMode(raw: unknown): IdleMode {
64 const s = String(raw ?? 'off').trim().toLowerCase()
65 return s === 'toast' || s === 'smart' || s === 'auto' ? s : 'off'
66}
67
68// The mode picked in the VS Code status bar, from <key>.idle.json: one of the four,
69// else undefined and the plugin option stands.
70export function idleOverride(raw: unknown): IdleMode | undefined {
71 try {
72 const m = JSON.parse(String(raw))?.mode
73 return m === 'off' || m === 'toast' || m === 'smart' || m === 'auto' ? m : undefined
74 } catch {
75 return undefined
76 }
77}
78
79// A positive number from an option, else the default.
80export function positive(raw: unknown, fallback: number): number {
81 const n = Number(raw)
82 return Number.isFinite(n) && n > 0 ? n : fallback
83}
84
85// How long after the last reply the mod acts, in ms: the TTL less the margin.
86export function idleFireAfterMs(ttlMin: number): number {
87 const ttl = ttlMin * 60_000
88 return ttl - Math.min(IDLE_MARGIN_MS, ttl / 2)
89}
90
91// True while the cache is about to expire but has not: from the fire time up to
92// the TTL. Past the TTL a handover would pay the full rewrite itself.
93export function idleDue(idleMs: number, ttlMin: number): boolean {
94 return idleMs >= idleFireAfterMs(ttlMin) && idleMs < ttlMin * 60_000
95}
96
97// A gap far past one tick since the last look means the machine was asleep.
98export function idleWoke(lastTickAt: number | undefined, now: number): boolean {
99 return lastTickAt !== undefined && now - lastTickAt > 2 * IDLE_TICK_MS
100}
101
102// auto and smart need a TTL of at least AUTO_MIN_TTL_MIN; below that it is toast.
103export function idleEffective(mode: IdleMode, ttlMin: number): IdleMode {
104 return (mode === 'auto' || mode === 'smart') && ttlMin < AUTO_MIN_TTL_MIN ? 'toast' : mode
105}
106
107export const idleToast = (leftMin: number): string =>
108 `The prompt cache expires in about ${Math.max(1, Math.round(leftMin))} min. ` +
109 'Measured once: a handover now was about 5x cheaper than resuming cold. Run /clear-resume:handover, then /clear.'
110
111// "off" or unset is 0, "unlimited" has no cap, a number is that many clears.
112export function budget(raw: unknown): number {
113 const s = String(raw ?? 'off').trim().toLowerCase()
114 if (s === 'unlimited') return Infinity
115 const n = Number(s)
116 return Number.isInteger(n) && n > 0 ? n : 0
117}
118
119// The state file's shape. The extension reads it (plugin/packages/store/relay-state.mjs).
120export type RelayFile = {
121 v: 1
122 key: string
123 cwd: string
124 // This window's session ids, oldest first: one per clear, the chain.
125 sessions: string[]
126 limit: number | 'unlimited'
127 configured: number | 'unlimited'
128 used: number
129 stalled: number
130 // The `at` of the last override taken from <key>.set.json, or of the last
131 // /relay typed in the window; 0 for none.
132 applied: number
133 updatedAt: number
134}
135
136const asJson = (n: number): number | 'unlimited' => (n === Infinity ? 'unlimited' : n)
137
138type Engine = Parameters<Parameters<Parameters<Register>[0]>[2]>[0]
139
140// HEAD of the session's repo, or undefined with no git (or no $.process, which
141// is CLI only). Unknown counts as progress: the stall guard stands aside and the
142// budget still holds.
143async function headOf($: Engine): Promise<string | undefined> {
144 try {
145 const r = await $.process.run(['git', 'rev-parse', 'HEAD'], { timeoutMs: 5000 })
146 return r.exitCode === 0 ? r.stdout.trim() || undefined : undefined
147 } catch {
148 return undefined
149 }
150}
151
152// What /relay takes: off, on, unlimited or a number. "on" is the option's own
153// budget when that is on, else 3. Anything else is undefined: not understood.
154export function parseRelay(args: string, fallback: number): number | undefined {
155 const s = args.trim().toLowerCase()
156 if (s === 'on') return fallback > 0 ? fallback : 3
157 if (s === 'off') return 0
158 const n = budget(s)
159 return n === 0 ? undefined : n
160}
161
162export function relayStatus(limit: number, used: number): string {
163 if (limit === 0) return 'relay: off'
164 if (limit === Infinity) return `relay: on, unlimited (${used} used)`
165 return `relay: ${Math.max(0, limit - used)} of ${limit} left`
166}
167
168// <store>/relay, the store being CLEAR_RESUME_HOME or ~/.clear-resume as in
169// packages/store/store.mjs. Undefined when there is no home to put it under.
170export async function relayDir($: Engine): Promise<string | undefined> {
171 const own = await $.env.get('CLEAR_RESUME_HOME')
172 if (own) return `${own.replace(/[/\\]+$/, '')}/relay`
173 const home = (await $.env.get('USERPROFILE')) || (await $.env.get('HOME'))
174 return home ? `${home.replace(/[/\\]+$/, '')}/.clear-resume/relay` : undefined
175}
176
177async function headlessRun($: Engine): Promise<boolean> {
178 return /^(1|true|on|yes)$/i.test((await $.env.get('CLEAR_RESUME_HEADLESS')) ?? '')
179}
180
181// One process's relay. The module lives in the process, so this outlives /clear.
182type Relay = {
183 configured: number
184 // The status_line option: off, the relay writes no status line
185 showStatus: boolean
186 limit: number
187 // This process's name in the relay folder. A reload starts the count over, so a
188 // new file is right; the extension reads the newest one for its folder.
189 key: string
190 sessions: string[]
191 applied: number
192 used: number
193 pending: boolean
194 // The stall guard, as in the headless runner (scripts/lib/run.mjs): HEAD at the
195 // last relay, and how many continued sessions in a row ended without a commit.
196 lastHead: string | undefined
197 stalled: number
198 headless: boolean
199 // The `at` of the last hand-over request taken from <key>.handover.json, and
200 // whether the poll for it is running. The poll's timer outlives /clear.
201 asked: number
202 polling: boolean
203 // The session last warned that the nudge went unanswered, so it warns once.
204 warned: string | undefined
205 // Idle handover: the settings, the clock reading and context size at the end of
206 // the last main-thread reply, tool calls and turns now running, and the timer.
207 idle: IdleMode
208 // The plugin option's mode, which stands when no mode is picked in the status bar.
209 idleBase: IdleMode
210 ttlMin: number
211 minTokens: number
212 lastReplyAt: number | undefined
213 // Tool calls in flight, and the ids of turns running (a Set: a subagent's turn
214 // can start and end inside the main one).
215 tools: number
216 turns: Set<string>
217 ticking: boolean
218 // The clock reading at the last tick, to tell a machine that just woke.
219 lastTickAt: number | undefined
220 // False when session.start said this is not an interactive session (the VS Code extension counts as one).
221 interactive: boolean
222 // A save went through save.mjs this session, so idle has nothing to ask for.
223 saved: boolean
224 // The idle handover was asked for by prompt: its save clears and does not resume.
225 idleAsked: boolean
226 // The idle status entry is showing, until the next turn starts.
227 idleShown: boolean
228 // A question the user has not answered yet (AskUserQuestion, main thread): when it
229 // was asked and what it says. The turn stays open while it waits, so idleCheck
230 // would never look; this is what lets it save a handover without a model turn.
231 question: { at: number; text: string } | undefined
232 // The note for the user once they answer a question whose wait saved a handover.
233 openSaved: string | undefined
234}
235
236// Told after a nudged turn ends with no save through save.mjs. Seen 2026-10-07: a
237// user's own skill also named "handover" saved by its own script, the relay never
238// armed, and nothing said so.
239export const UNARMED_TEXT =
240 'clear-resume relay: no handover was saved with /clear-resume:handover after the context nudge, so the relay will not clear. ' +
241 'If the work goes on, run /clear-resume:handover (another handover skill does not count), or type /clear.'
242
243// The nudge (scripts/lib/nudge.mjs) marks a session it has asked to hand over at
244// <store>/.nudged/<slug of the session id>, the slug as in scripts/lib/store.mjs.
245async function nudged($: Engine, id: string): Promise<boolean> {
246 const dir = await relayDir($)
247 const slug = id.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 50)
248 if (!dir || !slug) return false
249 try {
250 await $.fs.read(`${dir.replace(/[/\\]relay$/, '')}/.nudged/${slug}`)
251 return true
252 } catch {
253 return false
254 }
255}
256
257// A finished turn with the relay on and nothing saved: if the nudge has asked this
258// session for a handover, say once that the relay will not clear.
259async function warnUnarmed($: Engine, r: Relay, reason: string): Promise<void> {
260 if (r.limit === 0 || reason !== 'answer' || (await headlessRun($))) return
261 const id = await $.session.id()
262 if (!id || r.warned === id || !(await nudged($, id))) return
263 r.warned = id
264 $.ui.toast(UNARMED_TEXT, { timeoutMs: 20000 })
265}
266
267// The standing status entry: what is left while the relay is on, nothing while off.
268const shown = (r: Relay) => (!r.showStatus || r.limit === 0 || r.headless ? undefined : relayStatus(r.limit, r.used))
269
270// Write this window's state for the status bar. A failure never reaches the relay.
271async function publish($: Engine, r: Relay): Promise<void> {
272 try {
273 if (await headlessRun($)) return
274 const dir = await relayDir($)
275 if (!dir) return
276 const id = await $.session.id()
277 if (id && r.sessions.at(-1) !== id) r.sessions.push(id)
278 if (r.sessions.length > 100) r.sessions.splice(0, r.sessions.length - 100)
279 const file: RelayFile = {
280 v: 1,
281 key: r.key,
282 cwd: await $.session.cwd(),
283 sessions: r.sessions,
284 limit: asJson(r.limit),
285 configured: asJson(r.configured),
286 used: r.used,
287 stalled: r.stalled,
288 applied: r.applied,
289 updatedAt: Date.now(),
290 }
291 await $.fs.write(`${dir}/${r.key}.json`, JSON.stringify(file))
292 } catch {
293 // The status bar is a view; the relay works without it.
294 }
295}
296
297// A new budget for this window: the count and the stall guard start over.
298function setLimit(r: Relay, limit: number, at: number): void {
299 r.applied = at
300 r.limit = limit
301 r.used = 0
302 r.stalled = 0
303 r.lastHead = undefined
304 if (limit === 0) r.pending = false
305}
306
307// A budget set from the status bar, newer than the last one taken, replaces this
308// window's budget.
309async function takeOverride($: Engine, r: Relay): Promise<void> {
310 try {
311 const dir = await relayDir($)
312 if (!dir) return
313 const set = JSON.parse(String(await $.fs.read(`${dir}/${r.key}.set.json`)))
314 if (typeof set?.at !== 'number' || set.at <= r.applied) return
315 setLimit(r, budget(set.limit), set.at)
316 $.ui.status(shown(r))
317 } catch {
318 // No override file, or a bad one: keep the budget there is.
319 }
320}
321
322// A hand-over request from the status bar, newer than the last one taken: run the
323// handover skill. Queued until the session is idle, so a click mid-turn waits.
324async function takeHandover($: Engine, r: Relay): Promise<void> {
325 let at: unknown
326 try {
327 const dir = await relayDir($)
328 if (!dir) return
329 at = JSON.parse(String(await $.fs.read(`${dir}/${r.key}.handover.json`)))?.at
330 } catch {
331 // No request file, or a bad one: nothing asked.
332 return
333 }
334 if (typeof at !== 'number' || at <= r.asked) return
335 r.asked = at
336 $.ui.toast('Writing a handover', { timeoutMs: 5000 })
337 try {
338 await $.command.run({ command: HANDOVER_COMMAND, args: '' })
339 } catch {
340 await $.prompt.submit({ text: HANDOVER_TEXT, asUser: true }).catch(err => {
341 $.ui.toast(`Hand-over refused: ${String(err)}`, { timeoutMs: 15000 })
342 })
343 }
344}
345
346// Start the poll once per process, from whichever of session.start and the first
347// turn's end comes first. Not under the headless runner, which has no button.
348async function poll($: Engine, r: Relay): Promise<void> {
349 if (r.polling) return
350 r.polling = true
351 if (await headlessRun($)) return
352 let busy = false
353 $.clock.every(POLL_MS, () => {
354 if (busy) return
355 busy = true
356 void takeHandover($, r).finally(() => {
357 busy = false
358 })
359 })
360}
361
362// The context size after the last reply. $.session.usage() has it; if the host
363// has no figure (older builds), read the transcript the way the Stop-hook nudge
364// does, through the same function (scripts/lib/nudge.mjs, run as
365// scripts/context-tokens.mjs because a mod may not import node:fs). Undefined when
366// neither knows: the idle handover then stays quiet.
367async function contextTokens($: Engine): Promise<number | undefined> {
368 try {
369 const t = (await $.session.usage())?.context?.tokens
370 if (typeof t === 'number' && Number.isFinite(t)) return t
371 } catch {
372 // No usage on this build: fall through to the transcript.
373 }
374 try {
375 const id = await $.session.id()
376 const cwd = await $.session.cwd()
377 const home = (await $.env.get('USERPROFILE')) || (await $.env.get('HOME'))
378 const cfg = (await $.env.get('CLAUDE_CONFIG_DIR')) || (home ? `${home.replace(/[/\\]+$/, '')}/.claude` : '')
379 if (!id || !cwd || !cfg) return undefined
380 const file = `${cfg.replace(/[/\\]+$/, '')}/projects/${cwd.replace(/[^a-zA-Z0-9]/g, '-')}/${id}.jsonl`
381 const r = await $.process.run(['node', `${$.plugin.root}/scripts/context-tokens.mjs`, file], { timeoutMs: 15000 })
382 const t = r.exitCode === 0 ? Number(r.stdout.trim()) : NaN
383 return Number.isFinite(t) && t > 0 ? t : undefined
384 } catch {
385 return undefined
386 }
387}
388
389// Claim the idle handover's own once-per-session mark, <store>/.idle/<slug>. It is
390// not the .nudged mark: the 180k Stop nudge and this can each fire once. True when
391// this call made the mark; false when it was there already or cannot be written
392// (then do nothing rather than repeat).
393async function claimIdle($: Engine, id: string): Promise<boolean> {
394 const dir = await relayDir($)
395 const slug = id.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 50)
396 if (!dir || !slug) return false
397 const mark = `${dir.replace(/[/\\]relay$/, '')}/.idle/${slug}`
398 try {
399 await $.fs.read(mark)
400 return false
401 } catch {
402 // Not there yet: claim it.
403 }
404 try {
405 await $.fs.write(mark, new Date().toISOString())
406 return true
407 } catch {
408 return false
409 }
410}
411
412// Forget the idle state: a new conversation, or one just compacted, starts over.
413function resetIdle(r: Relay): void {
414 r.lastReplyAt = undefined
415 r.lastTickAt = undefined
416 r.turns.clear()
417 r.saved = false
418 r.idleAsked = false
419 r.question = undefined
420 r.openSaved = undefined
421}
422
423// "25 Oct, 6:04 am" style, in the machine's own time zone.
424function stamp(ms: number): string {
425 return new Date(ms).toLocaleString('en-AU', { day: 'numeric', month: 'short', hour: 'numeric', minute: '2-digit' })
426}
427
428// The session is waiting on a question and the cache is about to expire. Save a
429// handover by script: no prompt (it would queue behind the open dialog and run the
430// moment the user answers) and no /clear (they are still mid-conversation). The
431// user is told once, when they answer.
432async function openQuestionSave($: Engine, r: Relay, now: number, woke: boolean): Promise<void> {
433 const q = r.question
434 if (!q || r.saved || r.pending || r.idleAsked || r.openSaved) return
435 if ((r.idle !== 'smart' && r.idle !== 'auto') || woke) return
436 if (!idleDue(now - q.at, r.ttlMin) || (await headlessRun($))) return
437 const tokens = await contextTokens($)
438 if (tokens === undefined || tokens < r.minTokens) return
439 const id = await $.session.id()
440 const cwd = await $.session.cwd()
441 if (!id || !cwd || !(await claimIdle($, id))) return
442 const run = await $.process
443 .run(
444 [
445 'node',
446 `${$.plugin.root}/scripts/save-open-question.mjs`,
447 '--session', id,
448 '--cwd', cwd,
449 '--asked-at', stamp(q.at),
450 '--question', q.text,
451 ],
452 { timeoutMs: 60000 },
453 )
454 .catch(() => undefined)
455 const saved = /\(id ([^)]+)\)/.exec(run?.stdout ?? '')
456 if (run?.exitCode !== 0 || !saved) return
457 r.openSaved = `Cache was about to expire: handover ${saved[1]} saved at ${stamp(now)}. Nothing was cleared; /clear picks it up.`
458 $.ui.status(r.openSaved)
459 $.ui.toast(r.openSaved, { timeoutMs: 15000 })
460}
461
462// The mode this window runs on: the one picked in the status bar (<key>.idle.json)
463// while that file holds a valid mode, else the plugin option. Read on every look, so
464// a pick takes effect in a running session; dropping the file puts the option back.
465async function takeIdleMode($: Engine, r: Relay): Promise<void> {
466 let picked: IdleMode | undefined
467 try {
468 const dir = await relayDir($)
469 if (dir) picked = idleOverride(await $.fs.read(`${dir}/${r.key}.idle.json`))
470 } catch {
471 // No file: the plugin option stands.
472 }
473 r.idle = idleEffective(picked ?? r.idleBase, r.ttlMin)
474}
475
476// One look at the idle state. Acts at most once per session.
477async function idleCheck($: Engine, r: Relay): Promise<void> {
478 const now = await $.clock.now()
479 await takeIdleMode($, r)
480 // A gap far past one tick means the machine was asleep: the cache clock moved
481 // while this one did not, so nothing is submitted on that look.
482 const woke = idleWoke(r.lastTickAt, now)
483 r.lastTickAt = now
484 if (r.idle === 'off' || !r.interactive) return
485 // A question in the session's first turn has no earlier reply, so this comes first.
486 if (r.question) return openQuestionSave($, r, now, woke)
487 if (r.lastReplyAt === undefined) return
488 if (r.turns.size > 0 || r.saved || r.pending || r.idleAsked) return
489 const idle = now - r.lastReplyAt
490 if (!idleDue(idle, r.ttlMin) || (await headlessRun($))) return
491 // Read the context size only now that everything else says to act.
492 const tokens = await contextTokens($)
493 if (tokens === undefined || tokens < r.minTokens) return
494 const id = await $.session.id()
495 if (!id || !(await claimIdle($, id))) return
496 const left = Math.max(1, Math.round((r.ttlMin * 60_000 - idle) / 60_000))
497 // Auto needs a quiet session: a tool call in flight may be waiting on a
498 // permission prompt, and a submitted prompt would queue behind it. Message then.
499 const smart = r.idle === 'smart'
500 if ((r.idle === 'auto' || smart) && r.tools === 0 && !woke) {
501 r.idleAsked = true
502 $.ui.toast(
503 `Idle, the cache expires in about ${left} min. ${smart ? 'Checking whether a handover is needed.' : 'Writing a handover now.'}`,
504 { timeoutMs: 10000 },
505 )
506 await $.prompt.submit({ text: smart ? IDLE_SMART_TEXT : IDLE_HANDOVER_TEXT, asUser: true }).catch(err => {
507 r.idleAsked = false
508 $.ui.toast(`Idle handover refused: ${String(err)}`, { timeoutMs: 15000 })
509 })
510 return
511 }
512 // The message stays in the status line until the next turn starts. It is the
513 // user's to act on, so the toast is only a nudge to look.
514 r.idleShown = true
515 $.ui.status(idleToast(left))
516 $.ui.toast(idleToast(left), { timeoutMs: 8000 })
517}
518
519// The idle check's timer, once per process. Not under the headless runner.
520async function idleTick($: Engine, r: Relay): Promise<void> {
521 // Runs with idle off too: a mode picked in the status bar can turn it on later.
522 if (r.ticking) return
523 r.ticking = true
524 if (await headlessRun($)) return
525 let busy = false
526 $.clock.every(IDLE_TICK_MS, () => {
527 if (busy) return
528 busy = true
529 void idleCheck($, r)
530 .catch(() => {})
531 .finally(() => {
532 busy = false
533 })
534 })
535}
536
537// What the end of a main-thread turn does with a pending save.
538async function decide($: Engine, r: Relay, reason: string): Promise<void> {
539 if (!r.pending) {
540 // The turn the idle prompt started ended with nothing saved: drop the ask.
541 // In smart mode that is the model's answer, so say the session was left alone.
542 const declined = r.idleAsked && r.idle === 'smart' && reason === 'answer'
543 r.idleAsked = false
544 if (declined) $.ui.toast('Idle check: no handover saved, the session is left as it is.', { timeoutMs: 10000 })
545 return warnUnarmed($, r, reason)
546 }
547 // An idle handover saves and clears, whatever the relay's budget, and does not
548 // continue: the user is away, so the fresh session waits for them. The saved
549 // handover still loads at the start of the new session.
550 if (r.idleAsked) {
551 r.idleAsked = false
552 r.pending = false
553 if (reason !== 'answer' || (await headlessRun($))) return
554 if (r.showStatus) $.ui.status('Clearing...')
555 $.clock.after(300, () => {
556 $.command.run({ command: 'clear' }).catch(err => {
557 $.ui.status(shown(r))
558 $.ui.toast(`clear-resume idle handover: /clear refused: ${String(err)}`, { timeoutMs: 15000 })
559 })
560 })
561 return
562 }
563 // Turned off for this window: drop the save quietly.
564 if (r.limit === 0) {
565 r.pending = false
566 return
567 }
568 // The headless runner (run.mjs) ends the process instead; it has its own budget.
569 if (await headlessRun($)) {
570 r.pending = false
571 return
572 }
573 // An interrupted or failed turn is the user's to finish: do not clear under them.
574 if (reason !== 'answer') {
575 r.pending = false
576 return
577 }
578 if (r.used >= r.limit) {
579 r.pending = false
580 $.ui.toast(`clear-resume relay: budget of ${r.limit} used. Type /clear to continue from the handover.`, {
581 timeoutMs: 15000,
582 })
583 return
584 }
585 const head = await headOf($)
586 r.stalled = head !== undefined && head === r.lastHead ? r.stalled + 1 : 0
587 r.lastHead = head
588 if (r.stalled >= 2) {
589 r.pending = false
590 $.ui.toast(
591 'clear-resume relay: stopped. Two continued sessions in a row made no new commit. Type /clear to continue from the handover.',
592 { timeoutMs: 15000 },
593 )
594 return
595 }
596 r.used++
597 if (r.showStatus) $.ui.status('Clearing...')
598 // Not awaited: command.run rejects inside a hook the turn is waiting on,
599 // and the clear is queued until the session is idle anyway.
600 $.clock.after(300, () => {
601 $.command.run({ command: 'clear' }).catch(err => {
602 r.pending = false
603 $.ui.status(shown(r))
604 $.ui.toast(`clear-resume relay: /clear refused: ${String(err)}`, { timeoutMs: 15000 })
605 })
606 })
607}
608
609export const register: Register = (on, options) => {
610 // Off still registers: /relay and the status bar can turn it on for this window.
611 const configured = budget(options.relay)
612 const r: Relay = {
613 configured,
614 showStatus: options.status_line !== false,
615 limit: configured,
616 key: `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`,
617 sessions: [],
618 applied: 0,
619 used: 0,
620 pending: false,
621 lastHead: undefined,
622 stalled: 0,
623 headless: false,
624 asked: 0,
625 polling: false,
626 warned: undefined,
627 idle: idleEffective(idleMode(options.idle_handover), positive(options.cache_ttl_minutes, DEFAULT_TTL_MIN)),
628 idleBase: idleMode(options.idle_handover),
629 ttlMin: positive(options.cache_ttl_minutes, DEFAULT_TTL_MIN),
630 minTokens: positive(options.idle_min_tokens, DEFAULT_IDLE_MIN_TOKENS),
631 lastReplyAt: undefined,
632 tools: 0,
633 turns: new Set(),
634 ticking: false,
635 lastTickAt: undefined,
636 interactive: true,
637 saved: false,
638 idleAsked: false,
639 idleShown: false,
640 question: undefined,
641 openSaved: undefined,
642 }
643
644 on('session.start', async ($, e, next) => {
645 const result = await next(e)
646 r.headless = await headlessRun($)
647 resetIdle(r)
648 // A session that is not interactive (-p, the SDK) has nobody to message. The VS Code
649 // extension also reports isInteractive:false (surface null), but a person is there;
650 // its entrypoint variable tells it apart from -p and the SDK.
651 r.interactive =
652 (e as { isInteractive?: boolean }).isInteractive !== false || (await $.env.get('CLAUDE_CODE_ENTRYPOINT')) === 'claude-vscode'
653 await $.command.register({
654 name: 'relay',
655 description: 'Clear and continue by itself in this window: off, on, unlimited or a number',
656 argumentHint: '[off|on|unlimited|<n>]',
657 immediate: true,
658 })
659 $.ui.status(shown(r))
660 await publish($, r)
661 await poll($, r)
662 await idleTick($, r)
663 return result
664 })
665
666 // Bare /relay reports; with an argument it sets this window's budget and starts
667 // the count and the stall guard over. Typed later than any status-bar choice not
668 // yet taken, so it wins over that one.
669 on('command.run', { command: 'relay' }, async ($, e) => {
670 if (e.args.trim() === '') return { text: relayStatus(r.limit, r.used) }
671 const set = parseRelay(e.args, configured)
672 if (set === undefined) return { text: `relay: "${e.args.trim()}" not understood. Use off, on, unlimited or a number.` }
673 setLimit(r, set, Date.now())
674 $.ui.status(shown(r))
675 await publish($, r)
676 return { text: relayStatus(r.limit, r.used) }
677 })
678
679 // Count tool calls in flight, any thread (one may be waiting on a permission
680 // prompt), and turns running. Registered with the idle handover off too: a mode
681 // picked in the status bar can turn it on in a session that began without it.
682 on('tool.call', async ($, e, next) => {
683 r.tools++
684 try {
685 return await next(e)
686 } finally {
687 r.tools = Math.max(0, r.tools - 1)
688 }
689 })
690
691 // A question waiting for the user: remember it while it is open. Extending the
692 // answer's text with a note does not work: VS Code builds that result itself
693 // (rig, 2026-10-25), so the note is the toast and status line only.
694 on('tool.call', { tool: 'AskUserQuestion' }, async ($, e, next) => {
695 if (e.agentId !== undefined) return next(e)
696 const asked = (e as unknown as { questions?: { question?: string; options?: { label?: string }[] }[] }).questions ?? []
697 r.question = {
698 at: await $.clock.now(),
699 text: asked
700 .map(x => `${x.question ?? ''} [${(x.options ?? []).map(o => o.label ?? '').join(' | ')}]`)
701 .join(' / ')
702 .slice(0, 1500),
703 }
704 // The timer starts at the end of a turn; this turn has not ended and may be the first.
705 await idleTick($, r)
706 try {
707 return await next(e)
708 } finally {
709 r.question = undefined
710 r.openSaved = undefined
711 }
712 })
713
714 on('turn.start', async ($, e, next) => {
715 r.turns.add(e.turnId)
716 // The idle message stays until the user is back and a turn starts.
717 r.idleShown = false
718 $.ui.status(shown(r))
719 return next(e)
720 })
721
722 on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
723 const ran = await next(e)
724 if (
725 e.agentId === undefined &&
726 SAVE_SCRIPT.test(e.command.replace(/\\/g, '/')) &&
727 ran.deny === undefined &&
728 ran.isError !== true &&
729 (ran.text ?? '').includes(SAVED)
730 ) {
731 r.pending = true
732 r.saved = true
733 }
734 return ran
735 })
736
737 on('turn.complete', async ($, e, next) => {
738 const result = await next(e)
739 // Any thread's turn ends here, so its id leaves the running set.
740 r.turns.delete(e.turnId)
741 if (e.agentId !== undefined) return result
742 // Only a turn that answered counts as the user's last reply: an aborted or
743 // failed one did not refresh the cache the way a finished request does.
744 if (e.reason === 'answer') r.lastReplyAt = await $.clock.now()
745 await takeOverride($, r)
746 await decide($, r, e.reason)
747 await publish($, r)
748 await poll($, r)
749 await idleTick($, r)
750 return result
751 })
752
753 // A compacted conversation is a new, small one: the idle state starts over.
754 on('session.compact', async ($, e, next) => {
755 const result = await next(e)
756 if (e.agentId === undefined) resetIdle(r)
757 return result
758 })
759
760 on('session.end', async ($, e, next) => {
761 const result = await next(e)
762 resetIdle(r)
763 if (e.reason !== 'clear' || !r.pending) return result
764 r.pending = false
765 if (r.showStatus) $.ui.status('Continuing...')
766 $.clock.after(1000, () => {
767 $.prompt
768 .submit({ text: RESUME_TEXT, asUser: true })
769 .then(() => {
770 $.ui.status(shown(r))
771 // The VS Code panel draws no status line; a toast is the count it can show.
772 $.ui.toast(`clear-resume ${relayStatus(r.limit, r.used)}`, { timeoutMs: 8000 })
773 return publish($, r)
774 })
775 .catch(err => {
776 $.ui.status(shown(r))
777 $.ui.toast(`clear-resume relay: submit refused: ${String(err)}`, { timeoutMs: 15000 })
778 })
779 })
780 return result
781 })
782}
783