Context budget guard and handoff relay: measures real context use per model request, stops subagents that run too long or too big, and hands work over to a…

Pass the work on before the context runs out.
baton is a Claude Code mod that keeps long sessions and subagent orchestration from drowning in context. It measures the real context fill after every model request, stops subagents that run too long or grow too big, and makes the main agent hand its remaining work over to a fresh session instead of degrading in a full one.
baton ctx 42% (84k/200k) Δ+3.1k · work 60k, wrap-up at 140k · agents 2 (max work 28k)
A band above the prompt shows the same budget at a glance: the phase (on track, wrap up, handoff saved), a bar of main's context toward its wrap-up limit, and the running subagents with the biggest one's working context against its limit. It stacks with other mods' bands (cache-meter, relay) and draws in their style. Its header line ▾ baton · … folds the band to one line and back; the choice is kept across sessions. mod-switch turns baton off entirely.
handoff tool with the remaining work. The status line switches to WRAP UP. If the agent keeps going, baton reminds it every 5 points./baton shows the five biggest bumps, main's fill, the engine's own percent for cross-checking, every subagent's state, and the stored handoff.All measurements live in the session's plugin state under baton (main, agents, bumps, phase, enginePercent, window), so other mods can read them.
/plugin install baton --marketplace hal-9/claude-mods
Answer y to add the marketplace, pick the user scope, accept or change the three limits.
WRAP UP, let the agent finish; it calls handoff by itself. Then start a fresh session in the same directory. That is all./baton prints the report. /baton clear drops a stored handoff you do not want picked up.| Option | Default | Meaning |
|---|---|---|
| Main agent wrap-up at % of compaction window | 70 | One of main's three limits; the tightest wins. |
| Subagent working limit % of compaction window | 30 | A subagent whose working context passes this is stopped and asked for a handoff. |
| Subagent time limit (minutes) | 20 | A subagent running longer is stopped and asked for a handoff. |
| Working-token cap | 250000 | Absolute cap on working context above the baseline, main and subagents alike. |
Change them in /config under baton.
Context fill = input + cache_read + cache_creation + output tokens of the last response, over the model's window. That is the sum the next request re-sends, read per request from the API's usage block, not estimated. The engine's own status-line percent is kept beside it (engine says N% in /baton) so you can see when the two drift apart.
Baseline and working context. A loop's first request is its baseline: system prompt, tools, memory files, skills. That is fixed overhead, not work, and on a loaded setup it can be a quarter of a 1M window. Working context is what grew after it. Caps on subagents and the absolute cap are on working context, so a heavy baseline does not eat the budget.
Why three limits for main. Long-context studies (Chroma's context-rot report, Anthropic's context-engineering post) show quality degrading gradually with absolute input length, not at a fraction of the window. So there is an absolute cap. The engine's auto-compaction is a lossy summary and known to drop CLAUDE.md rules, so baton wraps up before it fires. The percent of the compaction window is the knob you turn when the other two do not fit.
claude plugin validate <folder>
claude plugin test <folder>hooks/register.tsx 489 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, ModelUsage, Register } from 'claude-code'
3
4import type { AgentStats, Bump, Handoff, LoopStats, Phase, Window } from '../types'
5
6const main = atom({ plugin: 'baton', key: 'main' } as const, null)
7const agents = atom({ plugin: 'baton', key: 'agents' } as const, {})
8const bumps = atom({ plugin: 'baton', key: 'bumps' } as const, [])
9const phase = atom({ plugin: 'baton', key: 'phase' } as const, 'ok')
10const enginePercent = atom({ plugin: 'baton', key: 'enginePercent' } as const, null)
11const windowState = atom({ plugin: 'baton', key: 'window' } as const, null)
12
13const HANDOFF_TOOL = 'mcp__baton__handoff'
14const STORE_KEY = 'handoff'
15// Wrap up this far into the engine's auto-compaction threshold, so the handoff lands before the summary does.
16const COMPACT_HEADROOM = 0.85
17
18type $ = EngineInterface
19
20// What the next request re-sends (the status line's context_tokens formula).
21const contextOf = (u: ModelUsage) =>
22 u.input_tokens + u.output_tokens + u.cache_read_input_tokens + u.cache_creation_input_tokens
23
24const k = (n: number) => (Math.abs(n) >= 1000 ? `${(n / 1000).toFixed(Math.abs(n) >= 10_000 ? 0 : 1)}k` : String(n))
25const minutes = (ms: number) => Math.round(ms / 60_000)
26const text = (t: string) => ({ type: 'text' as const, text: t })
27
28const stopText = (reason: string) => `[baton] STOP. ${reason}.
29Do not start new work and do not call more tools unless a single call is needed to finish a sentence of work already in flight.
30Reply now with a HANDOFF for the REMAINING work only, in this shape:
311. Done: one line per finished item, with file paths.
322. Remaining: concrete, ordered items.
333. Next step: the exact first action a fresh agent should take.
344. Gotchas: anything that cost you time.
35Your reply is forwarded to the main agent, which starts a fresh agent on the remaining work.`
36
37const stoppedNote = (a: AgentStats) =>
38 `[baton] Subagent "${a.description}" (${a.id}) was stopped early: ${a.stopReason}. Its result is a HANDOFF of the remaining work, not a finished task. Spawn a fresh subagent whose prompt is that handoff to continue; do not redo what it lists as done.`
39
40const wrapUpNote = (reason: string) => `[baton] ${reason}. Wrap up now:
411. Start no new work. Let running subagents finish; spawn new ones only to continue a stopped one.
422. Update the files your work touched (task plan, docs, memory) so nothing lives only in this conversation.
433. Call the ${HANDOFF_TOOL} tool with a handoff for the REMAINING work only: done, remaining, exact next step, gotchas, files.
444. Then tell the user to start a fresh session in this directory; the handoff is injected there automatically.`
45
46const handoffNote = (h: Handoff) => `[baton] Handoff from your previous session in this directory (written ${new Date(h.writtenAt).toISOString()} at ${h.percent}% context). Continue from it; do not redo what it lists as done. When baton tells you to wrap up, write the next handoff with the ${HANDOFF_TOOL} tool.
47
48${h.text}`
49
50// Filled by register(); top-level so the helpers below can read it.
51const cfg = { mainMax: 70, agentMax: 30, agentMaxMs: 20 * 60_000, maxWorking: 250_000 }
52// ponytail: one window for every loop; subagents on another model read slightly off.
53const win: Window = { model: 200_000, compact: 200_000 }
54
55// The engine's figures: model window, compaction window, auto-compact threshold.
56async function refreshWindow($: $) {
57 try {
58 const u = await $.session.usage({ breakdown: 'summary' })
59 win.model = u.context.window || win.model
60 win.compact = u.context.breakdown?.rawMaxTokens || win.model
61 win.autoCompactAt = u.context.breakdown?.autoCompactThreshold
62 } catch {
63 // not bound yet; keep what we have
64 }
65 await update($, windowState, () => ({ ...win }))
66}
67
68// Where main must wrap up: the tightest of its percent of the compaction window, the headroom
69// before auto-compaction, and the absolute working budget above its baseline. `[limit, why]`.
70function mainLimit(baseline: number): [number, string] {
71 const candidates: [number, string][] = [
72 [Math.round((cfg.mainMax / 100) * win.compact), `${cfg.mainMax}% of the ${k(win.compact)} compaction window`],
73 [baseline + cfg.maxWorking, `${k(cfg.maxWorking)} working tokens above the ${k(baseline)} baseline`],
74 ]
75 if (win.autoCompactAt) {
76 candidates.push([Math.round(COMPACT_HEADROOM * win.autoCompactAt), `${Math.round(COMPACT_HEADROOM * 100)}% of the ${k(win.autoCompactAt)} auto-compaction threshold`])
77 }
78 return candidates.reduce((a, b) => (b[0] < a[0] ? b : a))
79}
80
81// A subagent's working budget: its percent of the compaction window or the absolute cap, whichever is smaller.
82function agentWorkingLimit(): [number, string] {
83 const byPercent = Math.round((cfg.agentMax / 100) * win.compact)
84 return byPercent < cfg.maxWorking ? [byPercent, `${cfg.agentMax}% of the compaction window`] : [cfg.maxWorking, 'the absolute working cap']
85}
86
87async function showStatus($: $) {
88 const m = await read($, main)
89 if (!m) return $.ui.status(undefined)
90 const running = Object.values(await read($, agents)).filter(a => !a.endedAt)
91 const ph = await read($, phase)
92 let line = `baton ctx ${m.percent}% (${k(m.tokens)}/${k(m.window)}) Δ${m.lastDelta >= 0 ? '+' : ''}${k(m.lastDelta)} · work ${k(m.working)}, wrap-up at ${k(m.limit)}`
93 if (running.length) line += ` · agents ${running.length} (max work ${k(Math.max(...running.map(a => a.working)))})`
94 if (ph === 'wrap-up') line += ` · WRAP UP → call ${HANDOFF_TOOL}`
95 if (ph === 'handoff-written') line += ' · handoff saved → start a fresh session'
96 $.ui.status(line)
97}
98
99async function stopAgent($: $, a: AgentStats, reason: string) {
100 const now = await $.clock.now()
101 await update($, agents, all => ({ ...all, [a.id]: { ...all[a.id]!, stoppedAt: now, stopReason: reason } }))
102 try {
103 await $.session.append({ agentId: a.id, message: { type: 'user', content: [text(stopText(reason))] } })
104 $.ui.toast(`baton: stopping subagent "${a.description}": ${reason}`)
105 } catch {
106 // the loop already ended; nothing to stop
107 }
108}
109
110async function checkDurations($: $) {
111 const now = await $.clock.now()
112 for (const a of Object.values(await read($, agents))) {
113 if (a.endedAt || a.stoppedAt || now - a.startedAt < cfg.agentMaxMs) continue
114 await stopAgent($, a, `running ${minutes(now - a.startedAt)} min (limit ${minutes(cfg.agentMaxMs)} min)`)
115 }
116}
117
118// ---------------------------------------------------------------------------
119// The band above the prompt, in cache-meter's look so stacked bands read as one family.
120// The desktop wraps sibling elements, so its row is one SVG.
121
122// $.state refs are read as literals in the file that renders them.
123const MAIN = { plugin: 'baton', key: 'main' } as const
124const AGENTS = { plugin: 'baton', key: 'agents' } as const
125const PHASE = { plugin: 'baton', key: 'phase' } as const
126const COLLAPSED = { plugin: 'baton', key: 'collapsed' } as const
127
128// Collapsed or not, remembered across sessions.
129async function setCollapsed($: $, isCollapsed: boolean) {
130 await $.state.set(COLLAPSED, isCollapsed)
131 await $.store.set('collapsed', isCollapsed)
132}
133
134const ACCENT = '#8f8cf4'
135const WARM = '#5fbf8f'
136const AMBER = '#e0a43a'
137const RED = '#e5675a'
138const FONT = "-apple-system,BlinkMacSystemFont,'SF Pro Text','Segoe UI',sans-serif"
139const H = 22
140const BAR_H = 14
141const CELL = 3
142const SEGMENTS = 16
143
144const PILL: Record<Phase, [label: string, hex: string, tone: 'success' | 'warning']> = {
145 ok: ['on track', ACCENT, 'success'],
146 'wrap-up': ['wrap up', AMBER, 'warning'],
147 'handoff-written': ['handoff saved', WARM, 'success'],
148}
149const budgetHex = (p: number) => (p < 70 ? ACCENT : p < 100 ? AMBER : RED)
150const budgetTone = (p: number) => (p < 70 ? 'success' : p < 100 ? 'warning' : 'error')
151
152const noise = (x: number, y: number) => {
153 const s = Math.sin(x * 12.9898 + y * 78.233) * 43758.5453
154 return s - Math.floor(s)
155}
156// ponytail: per-class width estimate for the system font; every string here is ours.
157const charW = (c: string) => (/[il.,:;'|· ()]/.test(c) ? 0.3 : /[mwMW]/.test(c) ? 0.86 : /[A-Z0-9$%]/.test(c) ? 0.64 : 0.54)
158const textW = (s: string, size: number) => Math.round([...s].reduce((w, c) => w + charW(c), 0) * size)
159
160// A rounded track, dithered up to `percent`, sparse at the start and dense toward the head.
161function ditherBar(x: number, w: number, percent: number, color: string) {
162 const y = (H - BAR_H) / 2
163 const cols = Math.floor((w * Math.min(100, percent)) / 100 / CELL)
164 const dots: string[] = []
165 for (let c = 0; c < cols; c++) {
166 const density = 0.35 + 0.6 * Math.pow(c / Math.max(1, cols), 1.2)
167 for (let r = 0; r < Math.floor(BAR_H / CELL); r++) {
168 if (noise(c + 3, r) < density) dots.push(`<rect x="${c * CELL + 1}" y="${r * CELL + 1}" width="2" height="2"/>`)
169 }
170 }
171 return `<g transform="translate(${x},${y})"><clipPath id="bb"><rect width="${w}" height="${BAR_H}" rx="${BAR_H / 2}"/></clipPath>
172<rect class="k" width="${w}" height="${BAR_H}" rx="${BAR_H / 2}"/><g clip-path="url(#bb)" fill="${color}">${dots.join('')}</g></g>`
173}
174
175type Figure = { value: string; word: string }
176type BandRow = { phase: Phase; budget: number; used: Figure; agents: Figure | null }
177
178function bandSvg(r: BandRow, barW: number) {
179 const [pill, pillHex] = PILL[r.phase]
180 const parts: string[] = []
181 const figure = (x: number, f: Figure) => {
182 parts.push(`<text x="${x}" y="${H / 2 + 4.5}" font-size="12.5"><tspan class="t" font-weight="600">${f.value}</tspan><tspan class="m" dx="5">${f.word}</tspan></text>`)
183 return x + textW(f.value, 12.5) + 5 + textW(f.word, 12.5)
184 }
185 parts.push(`<circle cx="5" cy="${H / 2}" r="4" fill="${pillHex}"/>`)
186 parts.push(`<text class="t" x="16" y="${H / 2 + 4.5}" font-size="13" font-weight="500">Baton</text>`)
187 // The pill starts where cache-meter's do, so the bands line up.
188 const pillX = 16 + textW('Keepwarm', 13) + 8
189 const pillW = 16 + textW(pill, 11)
190 parts.push(`<rect x="${pillX}" y="${(H - 16) / 2}" width="${pillW}" height="16" rx="8" fill="${pillHex}"/>`)
191 parts.push(`<text x="${pillX + pillW / 2}" y="${H / 2 + 4}" text-anchor="middle" font-size="11" font-weight="600" fill="#ffffff">${pill}</text>`)
192 let x = pillX + pillW + 10
193 parts.push(ditherBar(x, barW, r.budget, budgetHex(r.budget)))
194 x = figure(x + barW + 8, r.used)
195 if (r.agents) {
196 x += 14
197 parts.push(`<rect class="tk" x="${x}" y="${H / 2 - 6}" width="1" height="12"/>`)
198 x = figure(x + 15, r.agents)
199 }
200 const W = x + 4
201 const source = `<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${H}" viewBox="0 0 ${W} ${H}" font-family="${FONT}" font-variant-numeric="tabular-nums">
202<style>.t{fill:#1f1f1f}.m{fill:#8a8a8a}.k{fill:#e4e4e2}.tk{fill:#c4c4c0}
203@media (prefers-color-scheme: dark){.t{fill:#ececec}.m{fill:#9a9a9a}.k{fill:#2c2c2c}.tk{fill:#4a4a4a}}</style>
204${parts.join('\n')}</svg>`
205 return { W, source }
206}
207
208// A hairline that sets this band apart from the mod bands drawn beneath it.
209const dividerSvg = (w: number) =>
210 `<svg xmlns="http://www.w3.org/2000/svg" width="${w}" height="9" viewBox="0 0 ${w} 9" preserveAspectRatio="none"><style>rect{fill:#00000026}@media (prefers-color-scheme: dark){rect{fill:#ffffff38}}</style><rect y="4" width="${w}" height="1"/></svg>`
211
212// ---------------------------------------------------------------------------
213
214export const register: Register = (on, options) => {
215 cfg.mainMax = Number(options.mainWrapUpPercent ?? 70)
216 cfg.agentMax = Number(options.agentMaxPercent ?? 30)
217 cfg.agentMaxMs = Number(options.agentMaxMinutes ?? 20) * 60_000
218 cfg.maxWorking = Number(options.maxWorkingTokens ?? 250_000)
219 const lastTools: Record<string, string[]> = {}
220 let nagAt = 0
221 let handoff: Handoff | null = null
222
223 on('session.start', async ($, e, next) => {
224 await refreshWindow($)
225 await $.tool.register({
226 name: 'handoff',
227 description:
228 'Save a handoff for the next session: what is done, what remains, the exact next step, gotchas and files. Call it when baton tells you to wrap up. The next session started in this directory reads it automatically.',
229 inputSchema: {
230 type: 'object',
231 properties: { text: { type: 'string', description: 'The handoff, markdown, remaining work only.' } },
232 required: ['text'],
233 },
234 isDeferred: false,
235 })
236 await $.command.register({
237 name: 'baton',
238 description: 'Context budget, subagent guard and handoff status',
239 argumentHint: '[clear]',
240 })
241
242 const stored = (await $.store.get(STORE_KEY)) as Handoff | undefined
243 const sessionId = await $.session.id()
244 const isOurs = stored?.cwd === e.cwd && stored.sessionId !== sessionId && (!stored.takenBy || stored.takenBy === sessionId)
245 if (stored && isOurs) {
246 handoff = { ...stored, takenBy: sessionId }
247 if (!stored.takenBy) {
248 await $.store.set(STORE_KEY, handoff)
249 $.ui.toast(`baton: picked up the handoff written ${new Date(stored.writtenAt).toLocaleString()}`)
250 }
251 }
252 await $.state.set(COLLAPSED, (await $.store.get('collapsed')) === true)
253 $.clock.every(30_000, () => void checkDurations($))
254 await showStatus($)
255 return next(e)
256 })
257
258 on('turn.start', async ($, e, next) => {
259 if (handoff && !handoff.injectedAt) {
260 handoff = { ...handoff, injectedAt: await $.clock.now() }
261 await $.store.set(STORE_KEY, handoff)
262 await $.session.append({ message: { type: 'user', content: [text(handoffNote(handoff))] } })
263 }
264 return next(e)
265 })
266
267 on('agent.spawn', async ($, e, next) => {
268 const r = await next(e)
269 if ('agentId' in r && r.agentId) {
270 const id = r.agentId
271 const now = await $.clock.now()
272 const [limit] = agentWorkingLimit()
273 await update($, agents, all => ({
274 ...all,
275 [id]: {
276 id, description: e.description, type: e.subagentType, startedAt: now,
277 tokens: 0, window: win.model, percent: 0, steps: 0, lastDelta: 0, baseline: 0, working: 0, limit, updatedAt: now,
278 },
279 }))
280 }
281 return r
282 })
283
284 on('turn.step', async function* ($, e, next) {
285 const r = yield* next(e)
286 if (!r.usage) return r
287 const now = await $.clock.now()
288 const key = e.agentId ?? 'main'
289 const tools = lastTools[key] ?? []
290 lastTools[key] = r.toolUses.map(t => t.name)
291 const tokens = contextOf(r.usage)
292 const percent = Math.round((tokens / win.model) * 100)
293 // The first request's size is the loop's baseline (system prompt, tools, memory); work is what grew after it.
294 const baselineOf = (prev: LoopStats | null | undefined) => (prev?.steps ? prev.baseline : tokens)
295 const grow = (prev: LoopStats | null | undefined, limit: number): LoopStats => {
296 const baseline = baselineOf(prev)
297 return { tokens, window: win.model, percent, steps: (prev?.steps ?? 0) + 1, lastDelta: tokens - (prev?.tokens ?? 0), baseline, working: tokens - baseline, limit, updatedAt: now }
298 }
299 let delta = 0
300
301 if (e.agentId) {
302 const id = e.agentId
303 const [workLimit, why] = agentWorkingLimit()
304 const prev = (await read($, agents))[id]
305 const stats: AgentStats = {
306 ...(prev ?? { id, description: '(unlisted)', type: 'unknown', startedAt: now }),
307 ...grow(prev, baselineOf(prev) + workLimit),
308 }
309 delta = stats.lastDelta
310 await update($, agents, cur => ({ ...cur, [id]: stats }))
311 if (!stats.stoppedAt && stats.working >= workLimit) {
312 await stopAgent($, stats, `your working context grew to ${k(stats.working)} tokens (limit ${k(workLimit)}, ${why})`)
313 }
314 } else {
315 const prev = await read($, main)
316 const [limit, why] = mainLimit(baselineOf(prev))
317 const stats = grow(prev, limit)
318 delta = stats.lastDelta
319 await update($, main, () => stats)
320 const ph = await read($, phase)
321 if (ph !== 'handoff-written' && tokens >= limit && percent >= nagAt + 5) {
322 nagAt = percent
323 await update($, phase, () => 'wrap-up')
324 await $.session.append({ message: { type: 'user', content: [text(wrapUpNote(`Your context is at ${k(tokens)} tokens (${percent}%), past the wrap-up limit of ${k(limit)}: ${why}`))] } })
325 $.ui.toast(`baton: context at ${k(tokens)} (${percent}%), wrapping up`)
326 }
327 }
328
329 const bump: Bump = { at: now, agentId: e.agentId, delta, tools: tools.length ? tools : ['(start)'], percentAfter: percent }
330 await update($, bumps, list => [...list, bump].slice(-60))
331 await showStatus($)
332 return r
333 })
334
335 on('turn.complete', async ($, e, next) => {
336 if (e.agentId) {
337 const id = e.agentId
338 const now = await $.clock.now()
339 const a = (await read($, agents))[id]
340 await update($, agents, all => (all[id] ? { ...all, [id]: { ...all[id]!, endedAt: now } } : all))
341 if (a?.stoppedAt) {
342 await $.session.append({ message: { type: 'user', content: [text(stoppedNote(a))] } })
343 }
344 await showStatus($)
345 }
346 return next(e)
347 })
348
349 on('session.measure', async ($, e, next) => {
350 await refreshWindow($)
351 await update($, enginePercent, () => e.context.percent ?? null)
352 return next(e)
353 })
354
355 on('tool.call', { tool: HANDOFF_TOOL }, async ($, e) => {
356 if (e.agentId) return { deny: 'Subagents do not save handoffs; reply with the handoff as your final message instead.' }
357 const body = String(e.text ?? '').trim()
358 if (!body) return { deny: 'A handoff needs text.' }
359 // the tool may run before this step's usage landed in `main`; the engine's figure is current
360 const percent = (await $.session.usage()).context.percent ?? (await read($, main))?.percent ?? 0
361 const h: Handoff = { cwd: await $.session.cwd(), sessionId: await $.session.id(), writtenAt: await $.clock.now(), percent, text: body }
362 await $.store.set(STORE_KEY, h)
363 await update($, phase, () => 'handoff-written')
364 $.ui.toast('baton: handoff saved, start a fresh session to continue')
365 await showStatus($)
366 return { result: 'Handoff saved. Tell the user to start a fresh session in this directory; baton injects the handoff there.' }
367 })
368
369 on('command.run', { command: 'baton' }, async ($, e) => {
370 if (e.args.trim() === 'clear') {
371 await $.store.delete(STORE_KEY)
372 handoff = null
373 return { text: 'baton: stored handoff cleared.' }
374 }
375 const m = await read($, main)
376 const ph = await read($, phase)
377 const eng = await read($, enginePercent)
378 const list = Object.values(await read($, agents))
379 const stored = (await $.store.get(STORE_KEY)) as Handoff | undefined
380 const now = await $.clock.now()
381 const [, mainWhy] = mainLimit(m?.baseline ?? 0)
382 const [agentLimit, agentWhy] = agentWorkingLimit()
383 const lines = [
384 `baton · context budget`,
385 `window: ${k(win.model)} model, ${k(win.compact)} compaction${win.autoCompactAt ? `, auto-compacts at ${k(win.autoCompactAt)}` : ', auto-compaction off'}`,
386 m
387 ? `main: ${m.percent}% (${k(m.tokens)} / ${k(m.window)}), baseline ${k(m.baseline)}, working ${k(m.working)}, ${m.steps} requests${eng === null ? '' : `, engine says ${eng}%`}`
388 : 'main: no model request measured yet',
389 `phase: ${ph}${m ? ` (wrap-up at ${k(m.limit)}: ${mainWhy})` : ''}`,
390 `agents (working limit ${k(agentLimit)}: ${agentWhy}; ${minutes(cfg.agentMaxMs)} min):`,
391 ...(list.length
392 ? list.map(a => {
393 const state = a.endedAt ? 'ended ' : a.stoppedAt ? 'stopped' : 'running'
394 const reason = a.stopReason ? ` · ${a.stopReason}` : ''
395 return ` ${state} work ${k(a.working).padStart(5)} ${String(minutes((a.endedAt ?? now) - a.startedAt)).padStart(3)} min "${a.description}"${reason}`
396 })
397 : [' none']),
398 'biggest context bumps:',
399 ...[...(await read($, bumps))]
400 .sort((x, y) => y.delta - x.delta)
401 .slice(0, 5)
402 .map(b => ` +${k(b.delta).padStart(6)} → ${b.percentAfter}% ${b.tools.join(', ')}${b.agentId ? ' (agent)' : ''}`),
403 stored
404 ? `handoff: saved ${new Date(stored.writtenAt).toLocaleString()} at ${stored.percent}% · ${stored.takenBy ? `taken by ${stored.takenBy === (await $.session.id()) ? 'this session' : 'an earlier session'}` : 'not yet taken'} · /baton clear removes it`
405 : 'handoff: none stored',
406 ]
407 return { text: lines.join('\n') }
408 })
409
410 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
411 const { value: m } = await $.state.get(MAIN)
412 if (!m || e.props.hasSurvey) return next(e)
413 const { value: all = {} } = await $.state.get(AGENTS)
414 const { value: ph = 'ok' } = await $.state.get(PHASE)
415 const ui = $.ui.resolve(e)
416 const { Box, Button, Text } = ui
417 // Another mod's band rides along beneath this one; the engine's own band is empty.
418 const drawn = await next(e)
419 const below = drawn.type !== 'engine' ? drawn : null
420 const isDesktop = e.surface !== 'terminal' && 'Svg' in ui
421 const cols = e.props.bodyColumns || 100
422
423 // How far main is toward its wrap-up limit, and the biggest running subagent.
424 const budget = Math.round((m.tokens / Math.max(1, m.limit)) * 100)
425 const used = { value: k(m.tokens), word: `of ${k(m.limit)} wrap-up` }
426 const running = Object.values(all).filter(a => !a.endedAt)
427 const agents = running.length
428 ? { value: String(running.length), word: `${running.length === 1 ? 'agent' : 'agents'}, max work ${k(Math.max(...running.map(a => a.working)))} of ${k(agentWorkingLimit()[0])}` }
429 : null
430 const [pill, , tone] = PILL[ph]
431 const alt = `baton ${pill}, ${used.value} ${used.word}${agents ? `, ${agents.value} ${agents.word}` : ''}`
432
433 let row
434 if (isDesktop) {
435 const { W, source } = bandSvg({ phase: ph, budget, used, agents }, Math.max(48, Math.min(200, Math.floor((cols * 8 - 520) / 2))))
436 row = <ui.Svg key="baton" source={source} alt={alt} width={W} height={H} />
437 } else {
438 const filled = Math.round((Math.min(100, budget) / 100) * SEGMENTS)
439 row = (
440 <Box key="baton" gap="sm" alignItems="center">
441 <Text tabular>
442 <Text color={tone}>● </Text>
443 <Text dimColor>baton </Text>
444 <Text color={tone} weight="medium">{pill}</Text>
445 <Text> </Text>
446 <Text color={budgetTone(budget)}>{'▮'.repeat(filled)}</Text>
447 <Text color="inactive">{'▯'.repeat(SEGMENTS - filled)}</Text>
448 <Text weight="semibold"> {used.value}</Text>
449 <Text dimColor> {used.word}</Text>
450 </Text>
451 {agents && <Text dimColor>│</Text>}
452 {agents && (
453 <Text tabular>
454 <Text weight="semibold">{agents.value}</Text>
455 <Text dimColor> {agents.word}</Text>
456 </Text>
457 )}
458 </Box>
459 )
460 }
461 // An accordion like cache-meter's and relay's: the header line folds and unfolds the row.
462 const { value: isCollapsed = false } = await $.state.get(COLLAPSED)
463 const band = (
464 <Box key="band" flexDirection="column" gap={isDesktop ? 'xs' : 0} paddingX={isDesktop ? 'xs' : 0} hover={{ backgroundColor: '#8080801a' }}>
465 <Button
466 key="toggle"
467 plain
468 dimColor
469 hover={{ dimColor: false, bold: true }}
470 label={`${isCollapsed ? '▸' : '▾'} baton · ${pill} · ${used.value} of ${k(m.limit)}${agents ? ` · ${agents.value} ${running.length === 1 ? 'agent' : 'agents'}` : ''}`}
471 onPress={() => void setCollapsed($, !isCollapsed)}
472 />
473 {!isCollapsed && row}
474 </Box>
475 )
476 if (!below) return band
477 const dividerW = Math.max(180, Math.min(1600, cols * 8 - 96))
478 return (
479 <Box flexDirection="column" gap={isDesktop ? 'sm' : 0} paddingTop={isDesktop ? 'xs' : 0}>
480 {band}
481 {isDesktop
482 ? <ui.Svg source={dividerSvg(dividerW)} alt="" width={dividerW} height={9} />
483 : <Text dimColor>{'─'.repeat(Math.max(8, cols - 2))}</Text>}
484 {below}
485 </Box>
486 )
487 })
488}
489types/index.d.ts 82 lines1/** Context fill of one model loop, measured from the API's own usage figures. */
2export type LoopStats = {
3 /** Tokens the next request re-sends: input + cache read + cache write + output of the last response. */
4 tokens: number
5 /** The model's context window, in tokens. */
6 window: number
7 /** tokens over window, whole percent. */
8 percent: number
9 /** Model requests counted so far. */
10 steps: number
11 /** Growth since the previous request. */
12 lastDelta: number
13 /** The loop's first request: system prompt, tools, memory. Fixed overhead, not work. */
14 baseline: number
15 /** tokens minus baseline: what the work added. */
16 working: number
17 /** The token count at which baton acts on this loop (wrap-up for main, stop for a subagent). */
18 limit: number
19 updatedAt: number
20}
21
22/** The engine's context figures baton measures against. */
23export type Window = {
24 /** The model's context window. */
25 model: number
26 /** The auto-compaction window; smaller than `model` when one is configured. */
27 compact: number
28 /** Where the engine auto-compacts; absent when auto-compaction is off. */
29 autoCompactAt?: number
30}
31
32export type AgentStats = LoopStats & {
33 id: string
34 description: string
35 type: string
36 startedAt: number
37 /** Set once baton told the agent to stop and hand off. */
38 stoppedAt?: number
39 stopReason?: string
40 endedAt?: number
41}
42
43/** One context growth step, attributed to the tool calls that preceded it. */
44export type Bump = {
45 at: number
46 agentId?: string
47 delta: number
48 tools: string[]
49 percentAfter: number
50}
51
52export type Phase = 'ok' | 'wrap-up' | 'handoff-written'
53
54/** What a session leaves for the next one, kept in $.store under "handoff". */
55export type Handoff = {
56 cwd: string
57 sessionId: string
58 writtenAt: number
59 percent: number
60 text: string
61 /** The session that picked it up; a handoff is injected into exactly one session. */
62 takenBy?: string
63 /** When that session's first turn injected it; a reload never injects it again. */
64 injectedAt?: number
65}
66
67declare module 'claude-code' {
68 interface PluginState {
69 baton: {
70 main: LoopStats | null
71 agents: Record<string, AgentStats>
72 bumps: Bump[]
73 phase: Phase
74 /** The engine's own status-line percent, from session.measure, for cross-checking. */
75 enginePercent: number | null
76 window: Window | null
77 /** The band above the prompt is folded to its header line; kept in $.store across sessions. */
78 collapsed: boolean
79 }
80 }
81}
82