SLOPSHOPPER

auto-handoff

Shows a context bar with a red handoff mark, the prompt-cache countdown and per-request tokens. When context passes a threshold it writes a handoff summary…

bandguardcommandtoastpromptmodel
v0.6.0MITupdated 2026-10-12Amel-DZRV/claude-code-auto-handoff
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · auto-handoff
› fix the failing auth test and add an audit log call ╭────────────────────────────────────────────╮ │ auto-handoff │ ⏺ Read(src/auth.ts) │ requested with /handoff-now. Writing a │ ⎿ Read 6 lines │ handoff summary, then starting a fresh │ ⏺ Update(src/auth.ts) │ session that picks up where this one left │ ⎿ Added 2 lines, removed 1 line ╰────────────────────────────────────────────╯ ⏺ Bash(bun test) ╭────────────────────────────────────────────╮ ⎿ 3 pass, 1 fail │ auto-handoff │ │ handoff saved to │ ● Done. refresh now rejects expired claims │ /work/app/.claude/handoffs/2025-10-09-085320-auto-handoff-preview-.md. │ │ Starting a fresh session… │ ✻ Worked for 42s · done 4:20 PM ╰────────────────────────────────────────────╯ › /auto-handoff ⎿ auto-handoff: auto-handoff is on · threshold 50% · clear automatically: yes · resume automatically: no · bar: shown · cache Context ████████████████████┃░░░░░░░░░░░░░░░░░░░ 49% handoff at 50% Cache: no request yet ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
Context ████████████████████┃░░░░░░░░░░░░░░░░░░░ 49% handoff at 50% Cache: no request yet
README

auto-handoff

A Claude Code mod (a plugin of JS/TS event hooks) that keeps an eye on your context window.

Context ███████░░░░░░░┃░░░░░░░░░░░░░░░░  23%  handoff at 50%        Cache warm 59m left
Last request · Input: 233k (99% cached, 2k new) · Output: 351
Keepwarm 1h20m left · next ping in 38m · 1 ping, about $0.05 · last ping read 233k ($0.05)
  • Context bar, always above the prompt, scaled 0-100% with a red line at the handoff threshold (default 50%). Green, then yellow, then red as it nears and passes the line. The desktop app draws a vector bar; the terminal draws block characters.
  • Prompt-cache countdown at the right of the bar: how long the cache stays warm after the last request.
  • Last request: the full input size, how much of it came from the cache, how much was new, and the output tokens.
  • Keepwarm (opt-in): /keepwarm 90m sends a cheap ping while you are away so the prompt cache does not lapse, and a third bar row shows the window and the last ping. Pings spend tokens; see Keepwarm.
  • Cold-send estimate: when you send a prompt into a cache that has gone cold, the mod logs what the rewrite will cost (and what a warm turn would have). It never holds the prompt back.
  • Auto-handoff: when context passes the threshold, the mod asks the model for a handoff summary (from the cached transcript when it is still warm), saves it (see below), runs /clear, and loads the summary into the fresh session once. The summary uses the same sections and frontmatter as the writing-handoffs skill, so writing-handoffs can resume from it.

Status

Early. The mod uses Claude Code's early-access plugin API, which may change without notice. Requires Claude Code 2.1.285 or later.

Seen working in Claude Code Desktop: the bar, the cache countdown, the per-request line, the slash commands, and the handoff itself (the summary is saved, the session is cleared, the summary is loaded into the fresh session, and the mod keeps running after the clear). Not yet verified live: keepwarm (a real ping reading the real cache, the cold-send estimate, a handoff with a window armed; run /keepwarm 1h every 1m after a request to see one ping read the cache before relying on it), the threshold trigger (the handoff has been run from /handoff-now), and the home-folder slots used by scratch sessions (covered by tests only). If /clear is refused, the summary is still saved and the mod says so in the transcript.

Install

From the marketplace in this repo (any machine, terminal or the Desktop app's Code tab):

claude plugin marketplace add Amel-DZRV/claude-code-auto-handoff
claude plugin install auto-handoff@amel-mods

Add .claude/handoffs/ to your global gitignore (git config --global core.excludesfile) so handoffs are never committed.

Run /reload-plugins in an open session. Update later with claude plugin marketplace update amel-mods; bump version in .claude-plugin/plugin.json when you push a change.

Other options:

Hot reloading, for trying it out: copy this folder to ~/.claude/dev-mods/<session-id>/auto-handoff/ and answer "Enable for this session" when Claude Code asks.

For every session: clone the repo and add its absolute path to the env block of ~/.claude/settings.json (several folders are separated by ; on Windows, : elsewhere):

{
  "env": {
    "CLAUDE_CODE_PLUGIN_DIRS": "C:\\dev\\claude-code-auto-handoff"
  }
}

New sessions load the mod from that folder and reload it when a file in it is saved. In a terminal you can use claude --plugin-dir <folder> instead.

Do not keep two copies of the mod loaded at once. They share a name, and an older copy can answer the commands before the newer one.

Commands

CommandWhat it does
/auto-handoff or statusSettings and the last handoff's outcome
/auto-handoff <percent>Set the threshold (5 to 95)
/auto-handoff on / offTurn auto-handoff on or off
/auto-handoff clear on / offRun /clear automatically after saving
/auto-handoff resume on / offSend a "continue" prompt in the fresh session
/auto-handoff bar on / offShow or hide the bar
/auto-handoff ttl <minutes>How long the prompt cache lives after its last use (default 60; the API gives 5 or 60)
/auto-handoff tokensThe last 10 requests, plus main-thread and subagent totals
/handoff-nowWrite the handoff now
/keepwarm <window>Keep the prompt cache warm for a window such as 90m, 2h or 2h30m (up to 24h). Pings spend tokens
/keepwarm <window> every <period>Ping more often than the default, at least 1m; applies to that window only
/keepwarm or statusWhere the window stands, or the cost warning when it is off. Never arms pings
/keepwarm off (also stop, cancel)Cancel the window and its pings

Keepwarm

/keepwarm 90m
keepwarm on for 1h30m: a ping each time the cache has sat idle for 50m, at most 1. The next ping is in 50m. Pings spend tokens: each one re-reads the whole cached context and gets a one-word answer. Each re-reads about 201k tokens, about $0.04 before its answer; up to 1 in this window is about $0.04. A cold rewrite of the same context would cost about $0.80. /keepwarm off stops it; a handoff that clears the session does too.

The prompt cache lasts about an hour after its last use (the ttl setting). Run /keepwarm 90m before a break and, after the cache has been idle for 50 minutes (ten minutes short of the ttl; a fifth of the ttl for a short one, never closer than a minute), the mod sends one ping. The ping is a fork over the session's own cached transcript with a fixed one-word prompt, so it reads the cache and resets its clock. Then it waits another 50 minutes, until the window ends.

Pings cost money. Every ping re-reads the whole cached context (a cache read, about a tenth of the input price) and bills whatever the model answers, since a fork has no output cap. The reply to /keepwarm prints the estimate for the current context and model, next to what a cold rewrite would cost, so you can judge whether the window is worth it. The mod uses list prices it carries in hooks/keepwarm.ts (September 2026); on a subscription the dollars are a yardstick, not the bill, and a model it has no price for prints no dollars. Pick a window you expect to return within.

Safety limits:

  • Nothing is armed by default and bare /keepwarm only reports. A window needs an explicit duration, at most 24 hours.
  • A window sends at most 100 pings.
  • Every ping's reading is checked: a ping that reads nothing, or writes a tenth of what it reads or more, means the cache was already gone, so the window stops (the ping already paid for a rewrite; more would pay again).
  • Any failure stops the window with the reason (a refused or interrupted call, an API error, an empty reply), and it is never retried.
  • A cache that is already cold is not pinged. Pings wait for your next request to warm it. The same goes for a new transcript after a compaction or /clear.
  • Pings count from the cache's last use, and the main thread's requests (also inside a long turn) push the next ping back. Subagent requests do not.
  • The window belongs to its session. It survives a plugin reload, and another session never inherits it.

With auto-handoff

  • A ping is not a turn. It appends nothing to the transcript, adds no prompt to the model's context, does not move the context bar, and never runs the threshold check, so a ping cannot start a handoff. Pings are also kept out of the "Last request" line and the request list in /auto-handoff tokens; that command shows them on a line of their own.
  • A ping that comes due while a handoff is writing its summary waits (the summary reads the same cache and warms it too).
  • A handoff that is about to /clear ends the window first, with a toast: the old cache is being thrown away, so another ping would only warm it. A handoff that leaves the session running (clear off, a background agent still running, or a prompt typed meanwhile) leaves the window running. A /clear you type ends it too.
  • A ping counts as cache use, so the bar's "Cache warm" countdown restarts after each ping, and a cache kept warm raises no cold-send estimate.
  • /auto-handoff ttl <minutes> changes the ping period with it.

Develop

claude plugin validate .
CLAUDE_CODE_ENABLE_FUNCTION_HOOKS=1 claude plugin test .

The test command refuses to run hooks modules without that variable while the plugin API is early access.

claude plugin test runs the files in tests/ against the engine with stubbed host calls.

Notes

  • Percent comes from $.session.usage().context.percent; request tokens come from the API's usage on each turn.step.
  • The cache countdown assumes a cache lifetime (the ttl setting); the mod cannot read the real value.
  • Where the handoff is saved: in a project, <project>/.claude/handoffs/YYYY-MM-DD-HHMMSS-auto-handoff-<session>.md, the same folder the writing-handoffs skill uses. Add .claude/handoffs/ to the repo's .gitignore (or your global one): handoffs summarise your conversation and should not be committed. A session with no project folder works in a scratch workspace that is deleted with the session, so it saves to ~/.claude/handoffs/handoff-1.md to handoff-5.md instead, reusing the oldest slot when all five exist.
  • The automatic handoff only runs when a turn ends, right after the last request, so the prompt cache is warm and the summary reuses it. The threshold is the only knob; there is no separate "early" setting. /handoff-now can run any time and warns when the cache is cold.
  • Claude Code also compacts the context on its own when it gets full. Keep the threshold below that point, or the built-in compaction runs first and the handoff never fires. Check /config for the compaction setting on your version.
  • A long turn can pass the threshold well before it ends. From then on, one tool result tells the model to finish the step it is on and end the turn, so the handoff can run before the built-in compaction does.
  • Background agents: /clear would cut off subagents that are still running. At the threshold, the handoff waits until they finish, saying so once; each agent's result arrives as a new turn, and the check runs again when that turn ends. /handoff-now still saves the file, but does not clear while agents run. If an automatic compaction gets there first, its summary is told to keep the running agents (id, name, task) so the compacted session still waits for them.
  • Managed settings can restrict which models a plugin may call. If the fallback summary model is refused, the mod says so and leaves the session untouched.
  • Keepwarm and the cold-send estimate use a built-in price table (cache read, 1-hour cache write, output, per million tokens), not prices read from your account, so the dollar figures are estimates and can go stale. The cache-write figure is an upper bound: it counts the last request's whole prompt. A resumed session has no estimate until its first request, and the mod cannot see the real cache, only the clock.
  • Not done, on purpose: refusing or delaying a cold send, arming keepwarm automatically after a cold write, an "always on" setting, and a session cost total. Every one of them spends or withholds something without being asked.

License

MIT, see LICENSE.

Source 3 files
hooks/register.tsx 1035 lines
1import { atom, read, update } from 'claude-code'
2import type { Register } from 'claude-code'
3
4import type { ContextBar, Keepwarm, RequestRow, Requests } from '../types'
5import {
6  BIG_TOKENS,
7  MAX_PINGS,
8  MAX_WINDOW_MS,
9  MIN_EVERY_MS,
10  PING_PROMPT,
11  coldRewriteCost,
12  defaultEveryMs,
13  effectiveEveryMs,
14  isWarmPing,
15  parseDuration,
16  pingCost,
17  priceOf,
18  usd,
19  warmReadCost,
20} from './keepwarm'
21
22type Settings = {
23  enabled: boolean
24  threshold: number
25  autoClear: boolean
26  autoResume: boolean
27  showBar: boolean
28  cacheTtlMinutes: number
29}
30
31type Pending = { path: string; sessionId: string; root: string; savedAt: number }
32
33const DEFAULTS: Settings = { enabled: true, threshold: 50, autoClear: true, autoResume: false, showBar: true, cacheTtlMinutes: 60 }
34
35const bar = atom({ plugin: 'auto-handoff', key: 'bar' } as const, {
36  percent: null,
37  threshold: DEFAULTS.threshold,
38  isEnabled: DEFAULTS.enabled,
39  isShown: DEFAULTS.showBar,
40} satisfies ContextBar)
41
42const requestsRef = { plugin: 'auto-handoff', key: 'requests' } as const
43const INITIAL_REQUESTS: Requests = { rows: [], ttlMinutes: DEFAULTS.cacheTtlMinutes, tick: 0 }
44const requests = atom(requestsRef, INITIAL_REQUESTS)
45
46const keepwarmRef = { plugin: 'auto-handoff', key: 'keepwarm' } as const
47const INITIAL_KEEPWARM: Keepwarm = { until: null, customEveryMs: null, pings: 0, spent: 0, lastPing: null, stopped: null }
48const keepwarm = atom(keepwarmRef, INITIAL_KEEPWARM)
49
50const MAX_ROWS = 200
51const TICK_MS = 30_000
52const BAR_MAX_CELLS = 40
53const BAR_MIN_CELLS = 10
54const SVG_WIDTH = 300
55const SVG_HEIGHT = 18
56const SVG_COLORS = { green: '#2da44e', yellow: '#d4a72c', red: '#e5484d' } as const
57const MAX_PENDING_AGE_MS = 6 * 60 * 60 * 1000
58const HANDOFFS_DIR = '.claude/handoffs'
59const KEPT_DIR = '.claude/handoffs'
60const KEPT_SLOTS = 5
61
62// The store is shared by every session, so each project keeps its own pending handoff.
63const pendingKey = (root: string): string => `pending:${root}`
64
65// Every session that has handed off, newest last; one id in one key let two sessions re-arm each other.
66const MAX_HANDED_OFF = 20
67const handedOffIds = async ($: any): Promise<string[]> => {
68  const ids = await $.store.get('handedOff')
69  return Array.isArray(ids) ? ids : []
70}
71const markHandedOff = async ($: any, sessionId: string): Promise<void> => {
72  const ids = await handedOffIds($)
73  await $.store.set('handedOff', [...ids.filter(id => id !== sessionId), sessionId].slice(-MAX_HANDED_OFF))
74}
75
76const pad = (n: number) => String(n).padStart(2, '0')
77// Local time, then the session's first 8 characters, so two sessions in the same second never share a file.
78const handoffFileName = (now: number, sessionId: string): string => {
79  const d = new Date(now)
80  const stamp = `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}-${pad(d.getHours())}${pad(d.getMinutes())}${pad(d.getSeconds())}`
81  return `${stamp}-auto-handoff-${sessionId.slice(0, 8)}.md`
82}
83
84const SUMMARY_PROMPT = `Write a handoff for a fresh Claude Code session that will continue this work with no memory of this conversation.
85Use exactly these sections, in markdown, starting with the first heading (no frontmatter, no title):
86
87## Summary
882-3 sentences: what this work is about, its current status, who it is for.
89
90## Current State
91Checkboxes: done, half-done, not started. Say what is broken right now.
92
93## Key Decisions
94Choices made and the reason for each, so they are not re-litigated.
95
96## Open Issues
97Blockers, known bugs, dead ends already tried.
98
99## Artifacts
100Files the next session needs, as file:line, one line each on why.
101
102## Next Steps
103Ordered, actionable. Item 1 is the very next thing to do.
104
105Prefer file:line references over pasted code. Be specific and terse. Output only the handoff.`
106
107// Module variables start over on a hot reload; the host's store does not.
108let isBusy = false
109// Counts prompts this process has seen; a handoff compares before and after its summary.
110let promptCount = 0
111// Set once the model was told mid-turn to wrap up; reset when the turn ends.
112let isNudged = false
113// The session told it is waiting for background agents, so the notice is said once.
114let waitingFor: string | undefined
115// The keepwarm timer: one ping, or the end of the window. A reload cancels it; session.start arms it again.
116let pingTimer: { cancel: () => void } | undefined
117// The session a keepwarm window was armed in, so its stored window is deleted even after /clear gives a new id.
118let armedSession: string | undefined
119// A compaction or /clear replaced the transcript: nothing of it is cached until the next request writes it.
120let isTranscriptNew = false
121const PING_RETRY_MS = 30_000
122
123// A /clear ends every agent still working, so a handoff waits for these.
124const BUSY_STATUSES = new Set(['pending', 'running', 'waiting'])
125type ActiveAgent = { id: string; description: string; type: string; status: string; name?: string }
126const activeAgents = async ($: any): Promise<ActiveAgent[]> => {
127  const agents: ActiveAgent[] = await $.agent.list().catch(() => [])
128  return agents.filter(agent => BUSY_STATUSES.has(agent.status))
129}
130const agentLine = (agent: ActiveAgent): string =>
131  `- ${agent.description} (${agent.type}, ${agent.status}, id ${agent.id}${agent.name === undefined ? '' : `, name ${agent.name}`})`
132const agentsPhrase = (count: number): string => (count === 1 ? '1 background agent is' : `${count} background agents are`)
133
134const loadSettings = async ($: any): Promise<Settings> => ({
135  ...DEFAULTS,
136  ...((await $.store.get('settings')) as Partial<Settings> | undefined),
137})
138
139// Keeps the bar's atom in step with the stored settings; the write redraws the band.
140const syncBar = ($: any, settings: Settings) =>
141  update($, bar, (b: ContextBar) =>
142    b.threshold === settings.threshold && b.isEnabled === settings.enabled && b.isShown === settings.showBar
143      ? b
144      : { ...b, threshold: settings.threshold, isEnabled: settings.enabled, isShown: settings.showBar },
145  )
146
147const saveSettings = async ($: any, settings: Settings) => {
148  await $.store.set('settings', settings)
149  await syncBar($, settings)
150  await update($, requests, (r: Requests) =>
151    r.ttlMinutes === settings.cacheTtlMinutes ? r : { ...r, ttlMinutes: settings.cacheTtlMinutes },
152  )
153}
154
155// Reads the live context fill into the bar; a write only when it has moved.
156const refreshBar = async ($: any): Promise<void> => {
157  const { context } = await $.session.usage()
158  const percent: number | null = context.percent === undefined ? null : Math.round(context.percent)
159  await update($, bar, (b: ContextBar) => (b.percent === percent ? b : { ...b, percent }))
160}
161
162const saveSettingsView = async ($: any, settings: Settings) => {
163  await syncBar($, settings)
164  await update($, requests, (r: Requests) =>
165    r.ttlMinutes === settings.cacheTtlMinutes ? r : { ...r, ttlMinutes: settings.cacheTtlMinutes },
166  )
167}
168
169const tickCountdown = async ($: any): Promise<void> => {
170  const now: number = await $.clock.now()
171  const tick = Math.floor(now / TICK_MS)
172  await update($, requests, (r: Requests) => (r.tick === tick ? r : { ...r, tick }))
173}
174
175// Says where a handoff stands: a toast, a transcript notice the model never reads, and a stored record.
176const say = async ($: any, text: string): Promise<void> => {
177  $.ui.toast(text)
178  await $.session.append({ message: { type: 'system', content: [{ type: 'text', text: `auto-handoff: ${text}` }] } }).catch(() => undefined)
179  const at: number = await $.clock.now()
180  await $.store.set('lastHandoff', { at, text }).catch(() => undefined)
181}
182
183const quietly = ($: any, work: Promise<unknown>, label = 'bar'): void => {
184  void work.catch((error: unknown) => $.ui.toast(`Auto-handoff ${label}: ${String(error)}`))
185}
186
187const kilo = (n: number): string => (n >= 1000 ? `${(n / 1000).toFixed(n >= 100000 ? 0 : 1)}k` : String(n))
188const promptTokens = (r: RequestRow): number => r.input + r.cacheRead + r.cacheWrite
189const hitPercent = (r: RequestRow): number => {
190  const total = promptTokens(r)
191  return total === 0 ? 0 : Math.round((r.cacheRead / total) * 100)
192}
193const clock = (ms: number): string => {
194  const d = new Date(ms)
195  return [d.getHours(), d.getMinutes(), d.getSeconds()].map(n => String(n).padStart(2, '0')).join(':')
196}
197const span = (ms: number): string => {
198  const minutes = Math.floor(ms / 60000)
199  if (minutes < 1) return '<1m'
200  return minutes < 60 ? `${minutes}m` : `${Math.floor(minutes / 60)}h${String(minutes % 60).padStart(2, '0')}m`
201}
202
203const lastMain = (rows: readonly RequestRow[]): RequestRow | undefined =>
204  [...rows].reverse().find(r => r.agentId === undefined)
205
206// Milliseconds the prompt cache has left after the main thread's last request, or after a keepwarm
207// ping if that came later; undefined with neither yet.
208const cacheLeft = (rows: readonly RequestRow[], ttlMinutes: number, now: number, pingedAt?: number): number | undefined => {
209  const last = lastMain(rows)
210  if (last === undefined && pingedAt === undefined) return undefined
211  return Math.max(last?.at ?? 0, pingedAt ?? 0) + ttlMinutes * 60000 - now
212}
213
214const getRequests = async ($: any): Promise<Requests> => {
215  const { value } = await $.state.get(requestsRef)
216  return value ?? INITIAL_REQUESTS
217}
218
219const getKeepwarm = async ($: any): Promise<Keepwarm> => {
220  const { value } = await $.state.get(keepwarmRef)
221  return value ?? INITIAL_KEEPWARM
222}
223
224// The keepwarm window is stored per session: the store is shared, and a second session must not inherit or end it.
225const keepwarmKey = (sessionId: string): string => `keepwarm:${sessionId}`
226
227type CacheView = {
228  kw: Keepwarm
229  now: number
230  ttlMinutes: number
231  /** The main thread's model, for prices. */
232  model: string | undefined
233  /** Milliseconds the cache has left; undefined when nothing is cached yet (no request, or a new transcript). */
234  left: number | undefined
235  /** Milliseconds between the cache's last use and a ping. */
236  every: number
237}
238
239const readCache = async ($: any): Promise<CacheView> => {
240  const settings = await loadSettings($)
241  const kw = await getKeepwarm($)
242  const seen = await getRequests($)
243  const now: number = await $.clock.now()
244  return {
245    kw,
246    now,
247    ttlMinutes: settings.cacheTtlMinutes,
248    model: lastMain(seen.rows)?.model,
249    left: isTranscriptNew ? undefined : cacheLeft(seen.rows, settings.cacheTtlMinutes, now, kw.lastPing?.at),
250    every: effectiveEveryMs(kw.customEveryMs ?? undefined, settings.cacheTtlMinutes),
251  }
252}
253
254// One line on where the window stands; undefined when keepwarm is off.
255const keepwarmLine = (c: CacheView): string | undefined => {
256  const { kw } = c
257  if (kw.stopped !== null) return `Keepwarm stopped: ${kw.stopped}`
258  if (kw.until === null || kw.until <= c.now) return undefined
259  const next = isTranscriptNew
260    ? 'waiting for the first request after the compaction or /clear'
261    : c.left === undefined
262      ? 'waiting for the first request'
263      : c.left <= 0
264        ? 'the cache is cold, so no ping until the next request'
265        : `next ping in ${span(Math.max(0, c.left - c.ttlMinutes * 60000 + c.every))}`
266  const spent = kw.pings === 0 ? '' : ` · ${kw.pings} ping${kw.pings === 1 ? '' : 's'}, about ${usd(kw.spent)}`
267  const last = kw.lastPing === null ? '' : ` · last ping read ${kilo(kw.lastPing.read)} (${usd(kw.lastPing.cost ?? undefined)})`
268  return `Keepwarm ${span(kw.until - c.now)} left · ${next}${spent}${last}`
269}
270
271const disarmKeepwarm = (): void => {
272  pingTimer?.cancel()
273  pingTimer = undefined
274}
275
276// Ends the window. A reason is toasted and shown in the bar (`remember`); null is a quiet end
277// (/keepwarm off, the window's own end). Only a window that was on says anything.
278const stopKeepwarm = async ($: any, why: string | null, remember = true): Promise<void> => {
279  disarmKeepwarm()
280  const wasOn = (await getKeepwarm($)).until !== null
281  for (const id of new Set([armedSession, await $.session.id()])) {
282    if (typeof id === 'string') await $.store.delete(keepwarmKey(id))
283  }
284  armedSession = undefined
285  if (why !== null && !wasOn) return
286  await update($, keepwarm, (k: Keepwarm) => (why === null || !remember ? INITIAL_KEEPWARM : { ...k, until: null, stopped: why }))
287  if (why !== null) $.ui.toast(`Auto-handoff keepwarm stopped: ${why}.`)
288}
289
290// Schedules the next ping, or only the end of the window when there is nothing warm to refresh.
291const armKeepwarm = async ($: any): Promise<void> => {
292  disarmKeepwarm()
293  const c = await readCache($)
294  if (c.kw.until === null) return
295  if (c.now >= c.kw.until) return stopKeepwarm($, null)
296  const wait = (ms: number) => {
297    pingTimer = $.clock.after(ms, () => quietly($, pingKeepwarm($), 'keepwarm'))
298  }
299  // A cold cache cannot be refreshed, only rewritten, and that is the next request's to pay for.
300  if (c.left === undefined || c.left <= 0) return wait(c.kw.until - c.now)
301  const lastUse = c.now + c.left - c.ttlMinutes * 60000
302  wait(Math.min(c.kw.until - c.now, c.left, Math.max(1000, lastUse + c.every - c.now)))
303}
304
305const FAILURES: Record<string, string> = {
306  'nothing-to-fork': 'there is no conversation to warm yet',
307  'empty-reply': 'the ping got no text back',
308  aborted: 'the ping was interrupted',
309}
310
311// A ping is a fork over the cached transcript with a one-word prompt. It is not a turn: nothing is
312// appended to the conversation, no prompt reaches the model's context, and neither the context
313// bar nor the handoff threshold sees it.
314const pingKeepwarm = async ($: any): Promise<void> => {
315  pingTimer = undefined
316  const c = await readCache($)
317  if (c.kw.until === null) return
318  const lastUse = c.left === undefined ? 0 : c.now + c.left - c.ttlMinutes * 60000
319  // The window ended, the cache lapsed, or a request got in first and re-armed the timer: this call is stale.
320  if (c.now >= c.kw.until || c.left === undefined || c.left <= 0 || c.now - lastUse < c.every - 1000) return armKeepwarm($)
321  // A handoff is writing its summary from this cache, which warms it just the same.
322  if (isBusy) {
323    pingTimer = $.clock.after(PING_RETRY_MS, () => quietly($, pingKeepwarm($), 'keepwarm'))
324    return
325  }
326  if (c.kw.pings >= MAX_PINGS) return stopKeepwarm($, `it reached the ${MAX_PINGS}-ping limit for one window`)
327
328  let reply: any
329  try {
330    reply = await $.model.fork({ prompt: PING_PROMPT })
331  } catch (error) {
332    return stopKeepwarm($, `the ping failed (${String(error)})`)
333  }
334  // Older releases answer null when the snapshot was cold or the call failed.
335  if (reply === null || reply === undefined) return stopKeepwarm($, 'the engine did not send the ping')
336  if (!reply.isAnswered) {
337    const status = reply.reason === 'api-error' && reply.status != null ? ` (${reply.status})` : ''
338    return stopKeepwarm($, reply.reason === 'api-error' ? `the API call failed${status}` : (FAILURES[reply.reason] ?? 'the ping failed'))
339  }
340
341  const u = reply.usage
342  const cost = pingCost(u, priceOf(c.model))
343  const at: number = await $.clock.now()
344  await update($, keepwarm, (k: Keepwarm) => ({
345    ...k,
346    pings: k.pings + 1,
347    spent: k.spent + (cost ?? 0),
348    lastPing: { at, read: u.cache_read_input_tokens, write: u.cache_creation_input_tokens, cost: cost ?? null },
349  }))
350  // A cold read means the prefix had already broken: the ping paid for a rewrite, so more would pay again.
351  if (!isWarmPing(u)) {
352    return stopKeepwarm(
353      $,
354      `a ping read ${kilo(u.cache_read_input_tokens)} and wrote ${kilo(u.cache_creation_input_tokens)} tokens (${usd(cost)}), so the cache was already gone`,
355    )
356  }
357  await armKeepwarm($)
358}
359
360// Opens the window, replacing one that was open.
361const startKeepwarm = async ($: any, windowMs: number, customEveryMs: number | null): Promise<void> => {
362  const now: number = await $.clock.now()
363  const sessionId: string = await $.session.id()
364  armedSession = sessionId
365  await $.store.set(keepwarmKey(sessionId), { until: now + windowMs, customEveryMs })
366  await update($, keepwarm, () => ({ ...INITIAL_KEEPWARM, until: now + windowMs, customEveryMs }))
367  await armKeepwarm($)
368}
369
370// A window outlives a hot reload and a restart of the same session; the timer does not.
371const restoreKeepwarm = async ($: any): Promise<void> => {
372  const sessionId: string = await $.session.id()
373  const saved = (await $.store.get(keepwarmKey(sessionId))) as { until?: number; customEveryMs?: number | null } | undefined
374  if (saved === undefined) return
375  const now: number = await $.clock.now()
376  if (typeof saved.until !== 'number' || saved.until <= now) {
377    await $.store.delete(keepwarmKey(sessionId))
378    return
379  }
380  armedSession = sessionId
381  await update($, keepwarm, (k: Keepwarm) =>
382    k.until === saved.until ? k : { ...INITIAL_KEEPWARM, until: saved.until!, customEveryMs: saved.customEveryMs ?? null },
383  )
384  await armKeepwarm($)
385}
386
387// What a send into a cold cache will cost, for a context big enough to matter; undefined when the cache is warm.
388const coldSendNote = async ($: any): Promise<string | undefined> => {
389  const c = await readCache($)
390  const last = lastMain((await getRequests($)).rows)
391  if (last === undefined || c.left === undefined || c.left > 0) return undefined
392  const tokens = promptTokens(last)
393  if (tokens < BIG_TOKENS) return undefined
394  const cold = coldRewriteCost(tokens, last.model, c.ttlMinutes)
395  const warm = warmReadCost(tokens, last.model)
396  return (
397    `the prompt cache went cold ${span(-c.left)} ago. Sending this re-writes up to ${tokens.toLocaleString('en-US')} tokens` +
398    (cold === undefined ? '' : ` = about ${usd(cold)}`) +
399    (warm === undefined ? '' : ` (a warm turn would have cost about ${usd(warm)})`) +
400    '. Sending anyway; /keepwarm <duration> holds the cache warm during a break.'
401  )
402}
403
404const recordRequest = async ($: any, agentId: string | undefined, usage: any): Promise<void> => {
405  const at: number = await $.clock.now()
406  const row: RequestRow = {
407    at,
408    model: String(usage.model),
409    ...(agentId === undefined ? {} : { agentId }),
410    input: usage.input_tokens,
411    output: usage.output_tokens,
412    cacheRead: usage.cache_read_input_tokens,
413    cacheWrite: usage.cache_creation_input_tokens,
414  }
415  await update($, requests, (r: Requests) => ({ ...r, rows: [...r.rows, row].slice(-MAX_ROWS) }))
416}
417
418const tokenReport = (r: Requests, now: number, kw: Keepwarm): string => {
419  if (r.rows.length === 0) return 'No requests recorded yet in this session.'
420  const sum = (rows: RequestRow[]) =>
421    rows.reduce(
422      (t, x) => ({ prompt: t.prompt + promptTokens(x), read: t.read + x.cacheRead, out: t.out + x.output }),
423      { prompt: 0, read: 0, out: 0 },
424    )
425  const main = r.rows.filter(x => x.agentId === undefined)
426  const sub = r.rows.filter(x => x.agentId !== undefined)
427  const m = sum(main)
428  const sb = sum(sub)
429  const left = cacheLeft(r.rows, r.ttlMinutes, now, kw.lastPing?.at)
430  const lines = r.rows.slice(-10).map(
431    x =>
432      `${clock(x.at)}  Input: ${kilo(promptTokens(x))} (${hitPercent(x)}% cached, ${kilo(x.input + x.cacheWrite)} new) · Output: ${kilo(x.output)}` +
433      ` · ${x.model}${x.agentId === undefined ? '' : ' · subagent'}`,
434  )
435  return [
436    `Last ${lines.length} of ${r.rows.length} requests:`,
437    ...lines,
438    `Main thread: ${main.length} requests, ${kilo(m.prompt)} prompt tokens sent (${kilo(m.read)} from cache), ${kilo(m.out)} out`,
439    ...(sub.length === 0 ? [] : [`Subagents: ${sub.length} requests, ${kilo(sb.prompt)} prompt tokens, ${kilo(sb.out)} out`]),
440    // Pings are not requests of the conversation, so they are not in the rows above.
441    ...(kw.pings === 0 ? [] : [`Keepwarm: ${kw.pings} ping${kw.pings === 1 ? '' : 's'} this window, about ${usd(kw.spent)}`]),
442    left === undefined
443      ? 'Cache: no main-thread request yet'
444      : left > 0
445        ? `Cache: warm, ${span(left)} left of ${r.ttlMinutes}m`
446        : `Cache: cold for ${span(-left)}`,
447  ].join('\n')
448}
449
450const summarize = async ($: any): Promise<string | undefined> => {
451  const forked = await $.model.fork({ prompt: SUMMARY_PROMPT })
452  if (forked.isAnswered && forked.text.trim() !== '') return forked.text
453
454  const messages = await $.session.messages()
455  const transcript = messages
456    .slice(-60)
457    .map((m: any) => `${m.role.toUpperCase()}: ${m.text}`)
458    .join('\n\n')
459    .slice(-60000)
460  // Managed settings can pin the model, so the fallback may be refused outright.
461  let completed: { isAnswered: boolean; text: string }
462  try {
463    completed = await $.model.complete({
464      model: 'sonnet',
465      prompt: `${SUMMARY_PROMPT}\n\n<transcript>\n${transcript}\n</transcript>`,
466      maxTokens: 4000,
467    })
468  } catch (error) {
469    throw new Error(`the fallback summary model was refused (${String(error)})`)
470  }
471  return completed.isAnswered && completed.text.trim() !== '' ? completed.text : undefined
472}
473
474const slash = (path: string): string => path.replace(/\\/g, '/').replace(/\/$/, '')
475
476// A session started with no project folder works in a scratch workspace that is deleted with it.
477const isScratch = (root: string): boolean => root.includes('/scratch-workspaces/')
478
479// The newest KEPT_SLOTS handoffs live in the home folder; there is no delete, so a full set reuses the oldest slot.
480const keepCopy = async ($: any, content: string): Promise<string | undefined> => {
481  const home = (await $.env.get('USERPROFILE')) ?? (await $.env.get('HOME'))
482  if (typeof home !== 'string' || home === '') return undefined
483  const dir = `${slash(home)}/${KEPT_DIR}`
484  const entries: { name: string; mtimeMs: number }[] = await $.fs.list(dir).catch(() => [])
485  const slots = Array.from({ length: KEPT_SLOTS }, (_, i) => `handoff-${i + 1}.md`)
486  const taken = new Map(entries.map(entry => [entry.name, entry.mtimeMs]))
487  const free = slots.find(name => !taken.has(name))
488  const oldest = [...slots].sort((a, b) => (taken.get(a) ?? 0) - (taken.get(b) ?? 0))[0]
489  const path = `${dir}/${free ?? oldest}`
490  await $.fs.write(path, content)
491  return path
492}
493
494const handoff = async ($: any, why: string): Promise<string> => {
495  if (isBusy) return 'A handoff is already running.'
496  isBusy = true
497  const promptsBefore = promptCount
498  try {
499    const settings = await loadSettings($)
500    await say(
501      $,
502      `${why}. Writing a handoff summary` +
503        (settings.autoClear ? ', then starting a fresh session that picks up where this one left off.' : '. Run /clear afterwards to load it into a fresh session.'),
504    )
505    const seen = await getRequests($)
506    const left = cacheLeft(seen.rows, seen.ttlMinutes, await $.clock.now(), (await getKeepwarm($)).lastPing?.at)
507    const last = lastMain(seen.rows)
508    if (left !== undefined && left <= 0 && last !== undefined) {
509      const cost = coldRewriteCost(promptTokens(last), last.model, seen.ttlMinutes)
510      $.ui.toast(
511        `Auto-handoff: the prompt cache is cold, so the summary re-bills about ${kilo(promptTokens(last))} tokens` +
512          `${cost === undefined ? '' : ` (about ${usd(cost)})`}.`,
513      )
514    }
515    const sessionId: string = await $.session.id()
516    const root = slash(String(await $.session.root()))
517    // A failure pauses the automatic handoff for this session, so it does not re-fork on every turn.
518    const PAUSED = 'Automatic handoff is paused for this session; run /handoff-now to try again.'
519    let text: string | undefined
520    try {
521      text = await summarize($)
522    } catch (error) {
523      await markHandedOff($, sessionId)
524      await say($, `could not write a summary: ${String(error)}; nothing was cleared. ${PAUSED}`)
525      return 'Could not write a summary; the session is untouched.'
526    }
527    if (text === undefined) {
528      await markHandedOff($, sessionId)
529      await say($, `could not write a summary, so nothing was cleared. ${PAUSED}`)
530      return 'Could not write a summary; the session is untouched.'
531    }
532
533    const now: number = await $.clock.now()
534    // The writing-handoffs skill's frontmatter, so its resume mode can read the file. A JSON
535    // string is a valid YAML scalar, so a path with ' #' or ': ' still parses.
536    const header =
537      `---\n` +
538      `date: ${new Date(now).toISOString()}\n` +
539      `author: auto-handoff (session ${sessionId})\n` +
540      `type: session\n` +
541      `status: in-progress\n` +
542      `project: ${JSON.stringify(root)}\n` +
543      `reason: ${JSON.stringify(why)}\n` +
544      `---\n\n`
545    const content = header + text.trim() + '\n'
546    // A project gets its own timestamped file, as the writing-handoffs skill does; a scratch
547    // workspace is deleted with the session, so it uses the home-folder slots instead.
548    const projectPath = isScratch(root) ? undefined : `${root}/${HANDOFFS_DIR}/${handoffFileName(now, sessionId)}`
549    // A repo that cannot be written (read-only, permissions) falls back to the home-folder slots.
550    const savedInProject =
551      projectPath !== undefined && (await $.fs.write(projectPath, content).then(() => true, () => false))
552    const path = savedInProject ? projectPath : await keepCopy($, content).catch(() => undefined)
553    if (path === undefined) {
554      await markHandedOff($, sessionId)
555      await say($, `could not save the handoff anywhere, so nothing was cleared. ${PAUSED}`)
556      return 'Could not save the handoff; the session is untouched.'
557    }
558    await $.store.set(pendingKey(root), { path, sessionId, root, savedAt: now } satisfies Pending)
559    // In the store, so a hot reload or a /auto-handoff bar change does not trigger a second handoff.
560    await markHandedOff($, sessionId)
561
562    if (!settings.autoClear) {
563      await say($, `handoff saved to ${path}. Run /clear and it loads into the new session.`)
564      return `Handoff saved to ${path}. Run /clear to start fresh with it.`
565    }
566
567    await say($, `handoff saved to ${path}. Starting a fresh session…`)
568    // Checked last, right before the /clear, which would wipe a prompt the user sent during the handoff.
569    if (promptCount !== promptsBefore) {
570      await say($, `handoff saved to ${path}, but you sent a new prompt meanwhile, so the session was not cleared. Run /clear yourself when ready.`)
571      return `Handoff saved to ${path}; the session was not cleared. Run /clear yourself.`
572    }
573    // The /clear would cut off agents still working; their results belong to this session.
574    const busy = await activeAgents($)
575    if (busy.length > 0) {
576      await say($, `handoff saved to ${path}, but ${agentsPhrase(busy.length)} still running, so the session was not cleared. Run /clear yourself once they finish.`)
577      return `Handoff saved to ${path}; the session was not cleared while ${agentsPhrase(busy.length)} running. Run /clear yourself.`
578    }
579    // The old session is going away, and so is its cache; a ping now would only warm what is thrown out.
580    await stopKeepwarm($, 'a handoff is clearing this session').catch(() => undefined)
581    try {
582      await $.command.run({ command: 'clear' })
583    } catch (error) {
584      await say($, `handoff saved, but /clear failed (${String(error)}). Run /clear yourself.`)
585      return `Handoff saved to ${path}, but /clear failed. Run /clear yourself.`
586    }
587    if (settings.autoResume) {
588      void $.prompt.submit({ text: 'Continue from the handoff notes in your context.' })
589    }
590    return `Handoff saved to ${path}; session cleared.`
591  } finally {
592    isBusy = false
593  }
594}
595
596const checkContext = async ($: any): Promise<void> => {
597  const settings = await loadSettings($)
598  if (!settings.enabled) return
599  const sessionId: string = await $.session.id()
600  if ((await handedOffIds($)).includes(sessionId)) return
601  const { context } = await $.session.usage()
602  if ((context.percent ?? 0) < settings.threshold) return
603  // Each background agent's result arrives as a new turn, so the next turn end checks again.
604  const busy = await activeAgents($)
605  if (busy.length > 0) {
606    if (waitingFor !== sessionId) {
607      waitingFor = sessionId
608      await say($, `context at ${Math.round(context.percent)}%, but ${agentsPhrase(busy.length)} still running. The handoff waits until they finish.`)
609    }
610    return
611  }
612  await handoff($, `context at ${Math.round(context.percent)}%`)
613}
614
615// Whether the main thread is past the threshold with a handoff still to come.
616const isPastThreshold = async ($: any, percent: number | undefined): Promise<boolean> => {
617  const settings = await loadSettings($)
618  if (!settings.enabled || (percent ?? 0) < settings.threshold) return false
619  return !(await handedOffIds($)).includes(await $.session.id())
620}
621
622const WRAP_UP =
623  'auto-handoff: the context is past the handoff threshold. The handoff runs only once this turn ends, ' +
624  'and the session may be compacted first if the turn keeps going. Finish the step in hand, ' +
625  'do not start new long work or new background agents, and end the turn soon.'
626
627const describe = (s: Settings) =>
628  `auto-handoff is ${s.enabled ? 'on' : 'off'} · threshold ${s.threshold}% · ` +
629  `clear automatically: ${s.autoClear ? 'yes' : 'no'} · resume automatically: ${s.autoResume ? 'yes' : 'no'} · ` +
630  `bar: ${s.showBar ? 'shown' : 'hidden'} · cache ttl: ${s.cacheTtlMinutes}m`
631
632const USAGE =
633  'Usage: /auto-handoff [on|off|status|<percent>|clear on|off|resume on|off|bar on|off|ttl <minutes>|tokens]'
634
635const KEEPWARM_WARNING = 'Pings spend tokens: each one re-reads the whole cached context and gets a one-word answer.'
636const KEEPWARM_USAGE =
637  'Usage: /keepwarm <window> [every <period>] | status | off. A window is 90m, 2h or 2h30m (up to 24h). ' +
638  `The period is a shorter gap than the default between pings, at least ${span(MIN_EVERY_MS)}. ${KEEPWARM_WARNING}`
639
640// The reply to /keepwarm <window>: when pings go, and what they and a cold rewrite would cost.
641const keepwarmArmed = async ($: any, windowMs: number): Promise<string> => {
642  const c = await readCache($)
643  const last = lastMain((await getRequests($)).rows)
644  const tokens = last === undefined ? undefined : promptTokens(last)
645  const pings = Math.min(MAX_PINGS, Math.max(1, Math.floor(windowMs / c.every)))
646  const perPing = tokens === undefined ? undefined : warmReadCost(tokens, c.model)
647  const cold = tokens === undefined ? undefined : coldRewriteCost(tokens, c.model, c.ttlMinutes)
648  const when =
649    c.left === undefined
650      ? 'The first ping waits for the first request.'
651      : c.left <= 0
652        ? 'The cache is cold now, so no ping goes out until your next request warms it.'
653        : `The next ping is in ${span(Math.max(0, c.left - c.ttlMinutes * 60000 + c.every))}.`
654  const cost =
655    perPing === undefined
656      ? ''
657      : ` Each re-reads about ${kilo(tokens!)} tokens, about ${usd(perPing)} before its answer; up to ${pings} in this window is about ${usd(perPing * pings)}.` +
658        (cold === undefined ? '' : ` A cold rewrite of the same context would cost about ${usd(cold)}.`)
659  return (
660    `keepwarm on for ${span(windowMs)}: a ping each time the cache has sat idle for ${span(c.every)}, at most ${pings}. ${when} ${KEEPWARM_WARNING}${cost} ` +
661    `/keepwarm off stops it; a handoff that clears the session does too.`
662  )
663}
664
665// Green while well under the mark, yellow as it nears, red once past it.
666const fillColor = (percent: number, threshold: number): 'red' | 'yellow' | 'green' =>
667  percent >= threshold ? 'red' : percent >= threshold * 0.8 ? 'yellow' : 'green'
668
669// One toast, the first time the mod runs for this user, so the auto-clear is not a surprise.
670const introduce = async ($: any): Promise<void> => {
671  if ((await $.store.get('introduced')) === true) return
672  const settings = await loadSettings($)
673  $.ui.toast(
674    `auto-handoff is on: at ${settings.threshold}% context it writes a handoff and clears the session. ` +
675      `/auto-handoff clear off keeps the session; /auto-handoff off disables it.`,
676  )
677  await $.store.set('introduced', true)
678}
679
680export const register: Register = on => {
681  on('session.start', async ($, e, next) => {
682    await $.command.register({
683      name: 'auto-handoff',
684      description: 'Configure auto-handoff: on, off, a threshold percent, clear on|off, resume on|off',
685    })
686    await $.command.register({
687      name: 'handoff-now',
688      description: 'Write the handoff file now, and clear the session when auto-clear is on',
689    })
690    await $.command.register({
691      name: 'keepwarm',
692      description: 'Keep the prompt cache warm with pings while you are away: /keepwarm 90m, status, off. Pings spend tokens',
693      argumentHint: '<90m | 2h30m | status | off>',
694      immediate: true,
695    })
696    quietly($, restoreKeepwarm($), 'keepwarm')
697    quietly($, loadSettings($).then(settings => saveSettingsView($, settings)).then(() => refreshBar($)))
698    quietly($, introduce($))
699    // Redraws the cache countdown; timers die with a reload and start again here.
700    $.clock.every(TICK_MS, () => {
701      quietly($, tickCountdown($))
702    })
703    return next(e)
704  })
705
706  // One row per model request, from the usage the API reported; passes the stream through.
707  on('turn.step', async function* ($, e, next) {
708    const result = yield* next(e)
709    if (result.usage !== null) await recordRequest($, e.agentId, result.usage).catch((error: unknown) => $.ui.toast(`Auto-handoff tokens: ${String(error)}`))
710    if (result.usage !== null && e.agentId === undefined) isTranscriptNew = false
711    return result
712  })
713
714  // Each tool call follows a model response, so the bar fills while a long turn runs.
715  // Past the threshold mid-turn, the result tells the model to end the turn so the handoff can run.
716  on('tool.call', async ($, e, next) => {
717    if (e.agentId !== undefined) return next(e)
718    quietly($, refreshBar($))
719    const result = await next(e)
720    if (isNudged || result.deny !== undefined || result.isError === true) return result
721    const isPast = await $.session
722      .usage()
723      .then(({ context }: any) => isPastThreshold($, context.percent))
724      .catch(() => false)
725    if (!isPast) return result
726    isNudged = true
727    return { ...result, context: [...(result.context ?? []), WRAP_UP] }
728  }).catch(($, e, next) => next(e))
729
730  // An automatic compaction got there before the handoff: keep the running agents in what survives it.
731  on('session.compact', { trigger: 'auto' }, async ($, e, next) => {
732    if (e.agentId !== undefined) return next(e)
733    const busy = await activeAgents($)
734    if (busy.length === 0) return next(e)
735    const keep =
736      'Background agents are still running and will report back to this session. ' +
737      'Keep each one in the summary, with its id and name, what it was asked to do and that its result is still awaited:\n' +
738      busy.map(agentLine).join('\n')
739    void say($, `the session is being compacted before the handoff ran; the summary keeps the ${busy.length} running background agent(s).`)
740    return next({ ...e, instructions: e.instructions === undefined ? keep : `${e.instructions}\n\n${keep}` })
741  }).catch(($, e, next) => next(e))
742
743  // Any compaction replaces the transcript, and the cache holds none of it: pings wait for the next request.
744  on('session.compact', async ($, e, next) => {
745    const result = await next(e)
746    if (e.agentId === undefined) {
747      isTranscriptNew = true
748      quietly($, armKeepwarm($), 'keepwarm')
749    }
750    return result
751  }).catch(($, e, next) => next(e))
752
753  // A /clear starts a new conversation: the old window and the old cache belong to the one thrown out.
754  on('classic.SessionStart', async ($, e, next) => {
755    const result = await next(e)
756    if (e.source === 'clear') {
757      isTranscriptNew = true
758      quietly($, stopKeepwarm($, 'the session was cleared', false), 'keepwarm')
759    }
760    return result
761  }).catch(($, e, next) => next(e))
762
763  // A send into a cold cache pays to rewrite it; say how much before it goes. The prompt is never held back.
764  on('prompt.submit', async ($, e, next) => {
765    if (e.origin?.kind === 'plugin' || typeof e.text !== 'string' || e.text.trimStart().startsWith('/')) return next(e)
766    const note = await coldSendNote($).catch(() => undefined)
767    if (note !== undefined) $.ui.log(`auto-handoff: ${note}`)
768    return next(e)
769  }).catch(($, e, next) => next(e))
770
771  // The turn has ended: the session is idle enough for a fork and a queued /clear.
772  on('turn.complete', async ($, e, next) => {
773    const result = await next(e)
774    if (e.agentId !== undefined) return result
775    // Any ended turn used the cache, so the next ping counts from here; a stale timer re-checks itself.
776    quietly($, armKeepwarm($), 'keepwarm')
777    if (e.reason !== 'answer') return result
778    isNudged = false
779    quietly($, refreshBar($))
780    void checkContext($).catch((error: unknown) => {
781      void say($, `failed: ${String(error)}`)
782    })
783    return result
784  })
785
786  // The first prompt of a conversation carries the handoff the previous session left.
787  on('prompt.context', async ($, e, next) => {
788    promptCount += 1
789    const result = await next(e)
790    const key = pendingKey(slash(String(await $.session.root())))
791    const pending = (await $.store.get(key)) as Pending | undefined
792    if (pending === undefined) return result
793    const now: number = await $.clock.now()
794    const isStale = now - pending.savedAt > MAX_PENDING_AGE_MS
795    if (isStale) {
796      await $.store.delete(key)
797      return result
798    }
799    if (pending.sessionId === (await $.session.id())) return result
800
801    const text = await $.fs.read(pending.path).catch(() => undefined)
802    await $.store.delete(key)
803    if (typeof text !== 'string') return result
804    $.ui.toast('Loaded the handoff from your previous session.')
805    return {
806      ...result,
807      blocks: [
808        ...result.blocks,
809        {
810          name: 'handoff',
811          text:
812            'Handoff from the previous session, which ended at its context threshold. ' +
813            'Treat it as the starting state and continue the work it describes.\n\n' +
814            text,
815        },
816      ],
817    }
818  })
819
820  // Detached: a command hook may not wait on a /clear queued behind itself.
821  on('command.run', { command: 'handoff-now' }, async $ => {
822    void handoff($, 'requested with /handoff-now').then(
823      (outcome: string) => say($, outcome),
824      (error: unknown) => say($, `failed: ${String(error)}`),
825    )
826    return { text: 'Writing the handoff…' }
827  })
828
829  on('command.run', { command: 'keepwarm' }, async ($, e) => {
830    const words = e.args.trim().toLowerCase().split(/\s+/).filter(Boolean)
831    const [first, second, third] = words
832
833    if (first === undefined || first === 'status') {
834      const line = keepwarmLine(await readCache($))
835      return { text: line ?? `keepwarm is off. /keepwarm 90m keeps the cache warm for 90 minutes. ${KEEPWARM_WARNING}` }
836    }
837    if (first === 'off' || first === 'stop' || first === 'cancel') {
838      const wasOn = (await getKeepwarm($)).until !== null
839      await stopKeepwarm($, null)
840      return { text: wasOn ? 'keepwarm is off; no more pings.' : 'keepwarm is off.' }
841    }
842
843    const windowMs = parseDuration(first)
844    if (windowMs === undefined || words.length === 2 || words.length > 3 || (second !== undefined && second !== 'every')) {
845      return { text: KEEPWARM_USAGE }
846    }
847    if (windowMs > MAX_WINDOW_MS) return { text: `A keepwarm window is at most ${span(MAX_WINDOW_MS)}. ${KEEPWARM_WARNING}` }
848    let customEveryMs: number | null = null
849    if (second === 'every') {
850      const period = parseDuration(third ?? '')
851      const ttl = (await loadSettings($)).cacheTtlMinutes
852      if (period === undefined || period < MIN_EVERY_MS || period > defaultEveryMs(ttl)) {
853        return { text: `every takes a period from ${span(MIN_EVERY_MS)} to ${span(defaultEveryMs(ttl))} (the default for a ${ttl}m cache).` }
854      }
855      customEveryMs = period
856    }
857    await startKeepwarm($, windowMs, customEveryMs)
858    return { text: await keepwarmArmed($, windowMs) }
859  })
860
861  on('command.run', { command: 'auto-handoff' }, async ($, e) => {
862    const settings = await loadSettings($)
863    const before = { ...settings }
864    const words = e.args.trim().toLowerCase().split(/\s+/).filter(Boolean)
865    const [first, second] = words
866
867    if (first === 'tokens') return { text: tokenReport(await getRequests($), await $.clock.now(), await getKeepwarm($)) }
868    if (first === 'status' || first === undefined) {
869      const last = (await $.store.get('lastHandoff')) as { at: number; text: string } | undefined
870      const when = last === undefined ? '' : ` · last handoff ${clock(last.at)}: ${last.text}`
871      const warm = keepwarmLine(await readCache($))
872      return { text: describe(settings) + when + (warm === undefined ? '' : ` · ${warm}`) }
873    }
874    if (first === 'on' || first === 'off') settings.enabled = first === 'on'
875    else if (first === 'bar' && (second === 'on' || second === 'off')) settings.showBar = second === 'on'
876    else if (first === 'ttl') {
877      const minutes = Number(second)
878      if (!Number.isInteger(minutes) || minutes < 1 || minutes > 120) {
879        return { text: 'Cache ttl must be 1 to 120 minutes (the API gives 5 or 60).' }
880      }
881      settings.cacheTtlMinutes = minutes
882    }
883    else if ((first === 'clear' || first === 'resume') && (second === 'on' || second === 'off')) {
884      if (first === 'clear') settings.autoClear = second === 'on'
885      else settings.autoResume = second === 'on'
886    } else if (/^\d+%?$/.test(first)) {
887      const percent = parseInt(first, 10)
888      if (percent < 5 || percent > 95) return { text: 'Threshold must be between 5 and 95.' }
889      settings.threshold = percent
890    } else return { text: USAGE }
891
892    await saveSettings($, settings)
893    // The ping period follows the cache lifetime.
894    if (before.cacheTtlMinutes !== settings.cacheTtlMinutes) quietly($, armKeepwarm($), 'keepwarm')
895    // A new threshold or turning it back on is a fresh decision; the bar, clear, resume and ttl are not.
896    if (before.enabled !== settings.enabled || before.threshold !== settings.threshold) {
897      await $.store.delete('handedOff')
898    }
899    return { text: describe(settings) }
900  })
901
902  // The bar: cells filled for the context used, a mark at the handoff threshold.
903  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
904    const state = await read($, bar)
905    if (e.props.hasSurvey || !state.isShown) return next(e)
906
907    const table = $.ui.resolve(e)
908    const { Box, Text } = table
909    const usage = await read($, requests)
910    const kw = await read($, keepwarm)
911    const now: number = await $.clock.now()
912    const left = cacheLeft(usage.rows, usage.ttlMinutes, now, kw.lastPing?.at)
913    const last = lastMain(usage.rows)
914    const cacheColor = left === undefined ? undefined : left <= 0 ? 'red' : left < 5 * 60000 ? 'yellow' : 'green'
915    const cacheText =
916      left === undefined ? 'Cache: no request yet' : left > 0 ? `Cache warm ${span(left)} left` : `Cache cold ${span(-left)}`
917    const fresh = last === undefined ? 0 : last.input + last.cacheWrite
918    // The cache state sits at the right of the bar's row; the last request's tokens take the row below.
919    const cacheLine = (
920      <Text color={cacheColor} dimColor={cacheColor === undefined}>
921        {cacheText}
922      </Text>
923    )
924    const requestLine =
925      last === undefined ? null : (
926        <Text dimColor>
927          {`Last request · Input: ${kilo(promptTokens(last))} (${hitPercent(last)}% cached, ${kilo(fresh)} new) · Output: ${kilo(last.output)}`}
928        </Text>
929      )
930    // A third row only while keepwarm is on, or after it stopped by itself and has something to say.
931    const keepText = keepwarmLine({
932      kw,
933      now,
934      ttlMinutes: usage.ttlMinutes,
935      model: last?.model,
936      left: isTranscriptNew ? undefined : left,
937      every: effectiveEveryMs(kw.customEveryMs ?? undefined, usage.ttlMinutes),
938    })
939    const keepLine =
940      keepText === undefined ? null : (
941        <Text color={kw.stopped === null ? undefined : 'yellow'} dimColor={kw.stopped === null}>
942          {keepText}
943        </Text>
944      )
945    const layout = (barRow: any) => (
946      <Box flexDirection="column">
947        <Box flexDirection="row" justifyContent="space-between">
948          {barRow}
949          {cacheLine}
950        </Box>
951        {requestLine}
952        {keepLine}
953      </Box>
954    )
955    const percent = state.percent ?? 0
956    const label = state.percent === null ? ' --%' : ` ${String(percent).padStart(2)}%`
957    const tail = state.isEnabled ? `  handoff at ${state.threshold}%` : '  handoff off'
958
959    // The desktop draws proportional text, so a row of block glyphs would not
960    // line up: it gets a real vector bar, 0-100 across, with the red line.
961    if (e.surface === 'desktop' && 'Svg' in table) {
962      const { Svg } = table
963      const color = SVG_COLORS[fillColor(percent, state.threshold)]
964      const isPast = state.isEnabled && percent >= state.threshold
965      const fillWidth = Math.max(0, Math.min(100, percent)) * (SVG_WIDTH / 100)
966      const markX = Math.min(SVG_WIDTH - 1, Math.max(1, state.threshold * (SVG_WIDTH / 100)))
967      const source =
968        `<svg xmlns="http://www.w3.org/2000/svg" width="${SVG_WIDTH}" height="${SVG_HEIGHT}" viewBox="0 0 ${SVG_WIDTH} ${SVG_HEIGHT}">` +
969        `<rect x="0" y="5" width="${SVG_WIDTH}" height="8" rx="4" fill="#8a8a8a" fill-opacity="0.3"/>` +
970        (fillWidth > 0 ? `<rect x="0" y="5" width="${fillWidth}" height="8" rx="4" fill="${color}"/>` : '') +
971        (state.isEnabled
972          ? `<rect x="${markX - 2}" y="0" width="4" height="${SVG_HEIGHT}" fill="#ffffff" fill-opacity="0.85"/>` +
973            `<rect x="${markX - 1}" y="0" width="2" height="${SVG_HEIGHT}" fill="${SVG_COLORS.red}"/>`
974          : '') +
975        `</svg>`
976
977      return layout(
978        <Box flexDirection="row" alignItems="center">
979          <Text dimColor>Context </Text>
980          <Svg
981            source={source}
982            alt={`Context ${state.percent === null ? 'unknown' : `${percent}%`}, handoff at ${state.threshold}%`}
983            width={SVG_WIDTH}
984            height={SVG_HEIGHT}
985          />
986          <Text color={isPast ? 'red' : undefined} bold={isPast}>
987            {label}
988          </Text>
989          <Text dimColor>{tail}</Text>
990        </Box>,
991      )
992    }
993    const cells = Math.max(
994      BAR_MIN_CELLS,
995      Math.min(BAR_MAX_CELLS, e.props.bodyColumns - 'Context '.length - label.length - tail.length - 2),
996    )
997
998    const filled = Math.round((percent / 100) * cells)
999    const mark = Math.min(cells - 1, Math.round((state.threshold / 100) * cells))
1000    const color = fillColor(percent, state.threshold)
1001    const isPast = state.isEnabled && percent >= state.threshold
1002
1003    // Cells [from, to): filled ones in the fill color, the rest dim.
1004    const run = (from: number, to: number) => {
1005      const fillCount = Math.max(0, Math.min(to, filled) - from)
1006      const emptyCount = Math.max(0, to - from - fillCount)
1007      return (
1008        <Box flexDirection="row">
1009          <Text color={color}>{'█'.repeat(fillCount)}</Text>
1010          <Text dimColor>{'░'.repeat(emptyCount)}</Text>
1011        </Box>
1012      )
1013    }
1014
1015    return layout(
1016      <Box flexDirection="row">
1017        <Text dimColor>Context </Text>
1018        {run(0, mark)}
1019        {state.isEnabled ? (
1020          <Text color={isPast ? 'white' : 'red'} bold>
1021            ┃
1022          </Text>
1023        ) : (
1024          run(mark, mark + 1)
1025        )}
1026        {run(mark + 1, cells)}
1027        <Text color={color} bold={isPast}>
1028          {label}
1029        </Text>
1030        <Text dimColor>{tail}</Text>
1031      </Box>,
1032    )
1033  })
1034}
1035
hooks/keepwarm.ts 91 lines
1// The pure parts of /keepwarm: durations, prices and the ping schedule. No host calls live here.
2
3export const MIN_MS = 60_000
4export const MIN_EVERY_MS = MIN_MS
5export const MAX_WINDOW_MS = 24 * 60 * MIN_MS
6// Pings stop after this many in one window, whatever the window says.
7export const MAX_PINGS = 100
8// Below this many tokens a cold rewrite is cheap enough that the estimate is noise.
9export const BIG_TOKENS = 50_000
10export const PING_PROMPT = 'Reply with the single word: warm'
11
12// $ per million tokens, [cache read, 1h cache write, output], list prices September 2026.
13// Longer family names first: a model id matches the first row it contains. Prices change;
14// check them against Anthropic's pricing page, and an unknown model prints no dollars.
15const PRICES: [string, number, number, number][] = [
16  ['fable-5-1', 0.25, 20, 50],
17  ['fable-5', 1, 20, 50],
18  ['opus-5', 0.5, 10, 25],
19  ['opus-4', 0.5, 10, 25],
20  ['sonnet-5', 0.2, 4, 10],
21  ['sonnet', 0.3, 6, 15],
22  ['haiku', 0.1, 2, 5],
23]
24
25export type Price = { read: number; write: number; output: number }
26export type PingUsage = {
27  input_tokens: number
28  output_tokens: number
29  cache_read_input_tokens: number
30  cache_creation_input_tokens: number
31}
32
33export const priceOf = (model: string | undefined): Price | undefined => {
34  const id = (model ?? '').toLowerCase().replace(/[\s.]+/g, '-')
35  const row = PRICES.find(([family]) => id.includes(family))
36  return row === undefined ? undefined : { read: row[1], write: row[2], output: row[3] }
37}
38
39// "90m", "2h", "2h30m"; anything else is undefined, and so is zero.
40export const parseDuration = (text: string): number | undefined => {
41  const match = /^(?:(\d+)h)?(?:(\d+)m)?$/.exec(text.trim().toLowerCase())
42  if (match === null || (match[1] === undefined && match[2] === undefined)) return undefined
43  const ms = (Number(match[1] ?? 0) * 60 + Number(match[2] ?? 0)) * MIN_MS
44  return ms > 0 ? ms : undefined
45}
46
47export const usd = (amount: number | undefined): string =>
48  amount === undefined ? 'n/a' : `$${amount >= 100 ? amount.toFixed(0) : amount.toFixed(2)}`
49
50// What the API bills for one fork: the cache read, any cache write, uncached input at the base rate
51// (half the 1h write rate) and the answer, which a fork does not cap.
52export const pingCost = (u: PingUsage, price: Price | undefined): number | undefined =>
53  price === undefined
54    ? undefined
55    : (u.cache_read_input_tokens * price.read +
56        u.cache_creation_input_tokens * price.write +
57        (u.input_tokens * price.write) / 2 +
58        u.output_tokens * price.output) /
59      1e6
60
61// The 5-minute cache write costs 1.25x the base input rate, the 1-hour write 2x.
62const writeRate = (price: Price, ttlMinutes: number): number => (ttlMinutes > 5 ? price.write : price.write * 0.625)
63
64// Re-writing `tokens` of context into a cold cache.
65export const coldRewriteCost = (tokens: number, model: string | undefined, ttlMinutes: number): number | undefined => {
66  const price = priceOf(model)
67  return price === undefined ? undefined : (tokens * writeRate(price, ttlMinutes)) / 1e6
68}
69
70// Reading `tokens` of context from a warm cache: the floor of one ping.
71export const warmReadCost = (tokens: number, model: string | undefined): number | undefined => {
72  const price = priceOf(model)
73  return price === undefined ? undefined : (tokens * price.read) / 1e6
74}
75
76// A warm ping reads the prefix and writes only its own message; a write of a tenth of the
77// read or more means the prefix broke and the ping paid for a rewrite.
78export const isWarmPing = (u: PingUsage): boolean =>
79  u.cache_read_input_tokens > 0 && u.cache_creation_input_tokens < 0.1 * u.cache_read_input_tokens
80
81// How long after the cache's last use the ping goes: ten minutes inside a one-hour cache,
82// a fifth of the lifetime inside a short one, never closer than a minute.
83export const defaultEveryMs = (ttlMinutes: number): number => {
84  const ttl = ttlMinutes * MIN_MS
85  return ttl - Math.max(MIN_MS, Math.min(10 * MIN_MS, ttl / 5))
86}
87
88// A custom period can only be shorter than the default: a longer one would let the cache lapse.
89export const effectiveEveryMs = (customMs: number | undefined, ttlMinutes: number): number =>
90  Math.max(MIN_EVERY_MS, Math.min(customMs ?? Infinity, defaultEveryMs(ttlMinutes)))
91
types/index.d.ts 54 lines
1export type ContextBar = {
2  /** Context window used, 0 to 100; null until the session's first response. */
3  percent: number | null
4  /** The handoff mark, 5 to 95. */
5  threshold: number
6  isEnabled: boolean
7  isShown: boolean
8}
9
10/** One model request, as the API reported its usage. */
11export type RequestRow = {
12  /** When the response arrived, ms since the epoch. */
13  at: number
14  model: string
15  /** Set for a subagent's request; absent on the main thread. */
16  agentId?: string
17  /** Uncached input tokens. */
18  input: number
19  output: number
20  cacheRead: number
21  cacheWrite: number
22}
23
24export type Requests = {
25  /** The latest requests, oldest first, capped. */
26  rows: RequestRow[]
27  /** Minutes the prompt cache lives after its last use. */
28  ttlMinutes: number
29  /** Bumped by a timer so the cache countdown redraws. */
30  tick: number
31}
32
33/** The /keepwarm window: pings that keep the prompt cache from lapsing while the user is away. */
34export type Keepwarm = {
35  /** When the window ends, ms since the epoch; null when keepwarm is off or has stopped. */
36  until: number | null
37  /** A shorter ping period than the default, ms; null for the default. */
38  customEveryMs: number | null
39  /** Pings sent in this window. */
40  pings: number
41  /** Dollars those pings cost by the list prices; a model with no known price counts as 0. */
42  spent: number
43  /** The latest ping, as the API reported it; kept after a stop so the reason has its receipt. */
44  lastPing: { at: number; read: number; write: number; cost: number | null } | null
45  /** Why the window ended by itself or at a handoff; null while it runs and after /keepwarm off. */
46  stopped: string | null
47}
48
49declare module 'claude-code' {
50  interface PluginState {
51    'auto-handoff': { bar: ContextBar; requests: Requests; keepwarm: Keepwarm }
52  }
53}
54