Resumes the session and its idle workers when a usage limit resets, and gives Claude the current 5h and weekly usage

Claude Code mods for running orchestrator and worker sessions. Built and tested on Claude Code v2.1.289.
| Mod | What it does |
|---|---|
limit-resume | When the 5-hour limit resets, sends "Continue" to the session and nudges idle workers. A dim usage tail on the prompt hint line from 80%, /limits, and a one-line usage note for Claude each turn. Publishes the current 5h and weekly limits to ~/.claude/usage/limits.json for other sessions and scripts. An optional, machine-local ~/.claude/usage-window.json (re-read each turn) sets a usage window: { "warnPercent": 90, "pausePercent": 98, "resumeDelayMinutes": 3, "until": "2026-10-12T08:00:00+02:00", "peers": ["vokko-vice"] }, every field optional. At warnPercent it toasts once per window and the note asks Claude to warn peers; at pausePercent it pauses as if cut, and the note tells Claude to stop its workers and peers; it resumes resumeDelayMinutes after the reset (default 1) and never after until. peers only appear in the note. /limits shows the active window. Without the file nothing changes. |
workers | /workers opens a pane with every worker: state, branch, commits ahead of main, changed files, last message, and who needs you. /workers all shows every session. |
identity-keeper | Remembers the session name (from /rename or "You are <name>" in the first prompt), restores it after a restart, and gives Claude a short role card after each compaction. /identity, /identity forget. |
proof-gate | When a worker reports done without screenshots, asks it for them. When proof arrives, sends the files to you and shows a band above the prompt with Approve and Ask changes. |
effort-gate | Denies a subagent or claude --bg session that runs Opus at xhigh or max effort unless you said so: your own next prompt (terminal or Remote Control) must mention Opus and xhigh/max, e.g. "ok opus xhigh". The OK lasts until your next prompt. Sonnet, Haiku, and the main session are not gated. Also denies a claude --bg with no --model (or --agent that sets one), since it would silently run Opus, and an Opus one with no --effort (settings could raise it). It fails closed on claude --bg text it cannot read, so a message that merely mentions claude --bg is denied too. It only sees the literal command text: variables, aliases or functions, scripts written then run, and xargs get through. |
route-ledger | Records every subagent and claude --bg launch (model, effort, agent, label, never the prompt) and, for subagents (background ones too), ok/error, duration and tokens. A relaunch with the same label in the same session marks the earlier run retried or escalated. /routing-review [days] prints launches, outcomes, retries, escalations and median tokens and time per model@effort. Background sessions are launch-only: their outcome is not visible to the mod. |
config-sync | At session start (at most every 10 minutes per device) pulls ~/.claude/shared (the claude-config repo) with --ff-only. Tells you when the pull fails, when there are unpushed local changes, or when settings.shared.json changed; /config-sync apply then runs the installer, /config-sync shows the status. Skips private CLAUDE_CONFIG_DIR setups. |
savvy-progress | A progress bar above the prompt and /agents-info, a panel of every subagent with model, context, cost and time. scout, builder and reviewer get their own crabs: a ranger with binoculars, a builder with a hammer, a reviewer in a mortarboard with a clipboard. The bar's crab is the orchestrator, a conductor with a baton. Also lists related background sessions and draws the crabs as half-block text in the terminal. Copy of johnnyvizz/claude-kit (MIT). |
cache-tax | Keeps the one-hour prompt cache warm: every session starts an 8-hour keepwarm window that pings after 50 idle minutes, and a cold send shows its rewrite cost. Changed from upstream: keepwarm is always on for 8h, and the guard warns instead of dropping the message. /keepwarm off turns it off on this device. Pings stop after 3h idle and while weekly usage is 75% or more. Pings cost usage. Copy of karanb192/cache-tax (MIT). |
claude plugin marketplace add Berkay2002/berkays-mods
claude plugin install limit-resume@berkays-mods
claude plugin install workers@berkays-mods
claude plugin install identity-keeper@berkays-mods
claude plugin install proof-gate@berkays-mods
claude plugin install effort-gate@berkays-mods
claude plugin install route-ledger@berkays-mods
claude plugin install config-sync@berkays-mods
claude plugin install savvy-progress@berkays-mods
claude plugin install cache-tax@berkays-mods
Plugins carry no version, so each commit is a new version:
claude plugin marketplace update berkays-mods
claude plugin update workers@berkays-mods # and the others
Then run /reload-plugins in open sessions.
Work against the checkout, not the installed copy:
claude --plugin-dir plugins/workers
claude plugin validate plugins/workers
(cd plugins/workers && claude plugin test)
MIT
hooks/register.ts 495 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, SessionRateLimit, Timer } from 'claude-code'
3
4const tail = atom({ plugin: 'limit-resume', key: 'tail' } as const, '')
5
6const RESUME_TEXT = 'Continue. The usage limit has reset.'
7const NUDGE_TEXT = 'Usage limit has reset. Continue your task.'
8// Wait a minute past the reset so the first request lands in the new window (the default; usage-window.json can change it).
9const GRACE_MS = 60_000
10// When a turn dies on a rate limit but no window reports a reset time, try again this much later.
11const UNKNOWN_RESET_MS = 30 * 60_000
12// The hint tail stays empty below this 5h percentage.
13const WARN_PERCENT = 80
14const MINUTE = 60_000
15const DAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
16
17// isPause: the 5h window reached usage-window.json's pausePercent before the engine cut the session.
18type Pending = { cutAt: number; resetsAt: number; isGuessed: boolean; isPause?: boolean }
19// ~/.claude/usage-window.json, machine-local and optional; every field is optional.
20type UsageWindow = {
21 warnPercent: number | null
22 pausePercent: number
23 resumeDelayMs: number
24 until: number | null
25 untilText: string
26 peers: string[]
27}
28// warnedFor: the 5h reset whose window already had its warnPercent toast.
29type Saved = { pending: Pending | null; handled: number[]; workers: string[]; warnedFor?: number }
30type Agent = { pid?: number; sessionId?: string; name?: string; status?: string }
31
32// Module state: starts over on a reload; what must survive one lives in $.store.
33let sessionId = ''
34let limits: readonly SessionRateLimit[] = []
35let saved: Saved = { pending: null, handled: [], workers: [] }
36let timer: Timer | undefined
37let ticker: Timer | undefined
38let isBusy = false
39let lastAnswerAt = 0
40// Re-read from disk on every event that uses it, so edits apply without a restart. null: no file, today's behaviour.
41let usageWindow: UsageWindow | null = null
42let paths: { config: string; limits: string; isWindows: boolean } | undefined
43let lastPublished = ''
44
45function key() {
46 return `session:${sessionId}`
47}
48
49function save($: EngineInterface) {
50 return $.store.set(key(), saved)
51}
52
53function hhmm(ms: number) {
54 const d = new Date(ms)
55 return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
56}
57
58// "15:04" today, "Tue 09:00" on another day.
59function when(ms: number, now: number) {
60 const isToday = new Date(ms).toDateString() === new Date(now).toDateString()
61 return isToday ? hhmm(ms) : `${DAYS[new Date(ms).getDay()]} ${hhmm(ms)}`
62}
63
64function duration(ms: number) {
65 const minutes = Math.max(1, Math.ceil(ms / MINUTE))
66 return minutes < 60 ? `${minutes}m` : `${Math.floor(minutes / 60)}h ${minutes % 60}m`
67}
68
69function plural(n: number, word: string) {
70 return `${n} ${word}${n === 1 ? '' : 's'}`
71}
72
73function resetOf(row: SessionRateLimit | undefined) {
74 const t = row?.resetsAt ? Date.parse(row.resetsAt) : NaN
75 return Number.isNaN(t) ? null : t
76}
77
78const slash = (p: string) => p.replace(/\\/g, '/').replace(/\/+$/, '')
79
80async function locate($: EngineInterface) {
81 if (paths) return paths
82 const orEmpty = (v: Promise<string | undefined>) => v.then(s => s ?? '', () => '')
83 const isWindows = (await orEmpty($.env.get('OS'))) === 'Windows_NT'
84 const userProfile = await orEmpty($.env.get('USERPROFILE'))
85 const homeVar = await orEmpty($.env.get('HOME'))
86 // `||`: an empty variable falls through. On Windows HOME can be a network drive; USERPROFILE is the real one.
87 const home = slash(isWindows ? userProfile || homeVar : homeVar || userProfile)
88 if (!home) return undefined
89 paths = { config: `${home}/.claude/usage-window.json`, limits: `${home}/.claude/usage/limits.json`, isWindows }
90 return paths
91}
92
93function parseWindow(text: string): UsageWindow | null {
94 let raw: unknown
95 try {
96 raw = JSON.parse(text)
97 } catch {
98 return null
99 }
100 if (!raw || typeof raw !== 'object') return null
101 const o = raw as Record<string, unknown>
102 const num = (v: unknown) => (typeof v === 'number' && Number.isFinite(v) ? v : undefined)
103 const until = typeof o.until === 'string' ? Date.parse(o.until) : NaN
104 return {
105 warnPercent: num(o.warnPercent) ?? null,
106 pausePercent: Math.min(100, Math.max(1, num(o.pausePercent) ?? 100)),
107 resumeDelayMs: Math.max(0, num(o.resumeDelayMinutes) ?? GRACE_MS / MINUTE) * MINUTE,
108 until: Number.isNaN(until) ? null : until,
109 untilText: Number.isNaN(until) ? '' : String(o.until),
110 peers: Array.isArray(o.peers) ? o.peers.filter((p): p is string => typeof p === 'string' && p !== '') : [],
111 }
112}
113
114// Reads the config again; a scheduled resume moves with an edited delay.
115async function loadWindow($: EngineInterface) {
116 const where = await locate($)
117 const text = where
118 ? await $.fs.read(where.config).then(
119 t => (typeof t === 'string' ? t : null),
120 () => null,
121 )
122 : null
123 const before = saved.pending ? resumeAt(saved.pending) : null
124 usageWindow = text === null ? null : parseWindow(text)
125 if (saved.pending && timer && before !== resumeAt(saved.pending)) await schedule($)
126}
127
128function windowEnded(now: number) {
129 return usageWindow?.until != null && now >= usageWindow.until
130}
131
132function resumeAt(p: Pending) {
133 return p.resetsAt + (usageWindow?.resumeDelayMs ?? GRACE_MS)
134}
135
136// The window ends before this resume would: nothing will fire.
137function isPastUntil(p: Pending) {
138 return usageWindow?.until != null && resumeAt(p) >= usageWindow.until
139}
140
141// Under an hour away counts down; further out reads as a clock time.
142function resumeLabel(p: Pending, now: number) {
143 const left = resumeAt(p) - now
144 if (isPastUntil(p)) return `no resume · window ends ${when(usageWindow!.until!, now)}`
145 if (p.isGuessed) return `retries ~${hhmm(resumeAt(p))}`
146 return left < 60 * MINUTE ? `resumes in ${duration(left)}` : `resumes ${when(resumeAt(p), now)}`
147}
148
149async function refreshStatus($: EngineInterface) {
150 const now = await $.clock.now()
151 const p = saved.pending
152 if (p) {
153 const n = saved.workers.length
154 // A pause is a real alert: it keeps the pinned notice, and the hint tail stays empty.
155 $.ui.status(`⏸ ${p.isPause ? 'paused' : 'limit'} · ${resumeLabel(p, now)}${n ? ` · ${plural(n, 'worker')}` : ''}`)
156 await update($, tail, () => '')
157 return
158 }
159 // Clears a pause notice left from before the resume.
160 $.ui.status(undefined)
161 const five = limits.find(r => r.kind === 'five_hour')
162 if (!five || five.percentUsed < WARN_PERCENT) {
163 await update($, tail, () => '')
164 return
165 }
166 const reset = resetOf(five)
167 await update($, tail, () => `5h ${five.percentUsed}%${reset === null ? '' : ` · resets ${when(reset, now)}`}`)
168}
169
170async function schedule($: EngineInterface) {
171 const p = saved.pending
172 if (!p) return
173 timer?.cancel()
174 ticker?.cancel()
175 const delay = Math.max(0, resumeAt(p) - (await $.clock.now()))
176 timer = $.clock.after(delay, () => void fire($))
177 ticker = $.clock.every(MINUTE, () => void refreshStatus($))
178 await refreshStatus($)
179}
180
181// The window that is used up and resets last decides when work can go on.
182function exhaustedReset(rows: readonly SessionRateLimit[]) {
183 const times = rows
184 .filter(r => r.percentUsed >= 100)
185 .map(resetOf)
186 .filter((t): t is number => t !== null)
187 return times.length ? Math.max(...times) : null
188}
189
190// The 5h window at or past usage-window.json's pausePercent (below 100): pause before the engine cuts.
191function pauseReset(rows: readonly SessionRateLimit[]) {
192 const pausePercent = usageWindow?.pausePercent ?? 100
193 if (pausePercent >= 100) return null
194 const five = rows.find(r => r.kind === 'five_hour')
195 return five && five.percentUsed >= pausePercent ? resetOf(five) : null
196}
197
198async function markCut($: EngineInterface, isRateLimitError: boolean) {
199 const now = await $.clock.now()
200 let resetsAt = exhaustedReset(limits)
201 let isGuessed = false
202 let isPause = false
203 if (resetsAt === null) {
204 resetsAt = pauseReset(limits)
205 isPause = resetsAt !== null
206 }
207 if (resetsAt === null) {
208 if (!isRateLimitError) return
209 const fiveHour = resetOf(limits.find(r => r.kind === 'five_hour'))
210 if (fiveHour !== null && fiveHour > now) {
211 resetsAt = fiveHour
212 } else {
213 resetsAt = now + UNKNOWN_RESET_MS
214 isGuessed = true
215 }
216 }
217 if (saved.handled.includes(resetsAt)) return
218 if (saved.pending && (saved.pending.resetsAt === resetsAt || (!isGuessed && saved.pending.resetsAt > resetsAt))) return
219 const isFirstHit = saved.pending === null
220 const pending: Pending = isPause ? { cutAt: now, resetsAt, isGuessed, isPause } : { cutAt: now, resetsAt, isGuessed }
221 saved = { ...saved, pending }
222 await save($)
223 await schedule($)
224 if (isFirstHit) {
225 const five = limits.find(r => r.kind === 'five_hour')
226 const head = isPause ? `Usage window: 5h at ${five?.percentUsed ?? '?'}% · pausing` : 'Usage limit reached'
227 const resume = isPastUntil(pending)
228 ? `no resume, the window ends ${hhmm(usageWindow!.until!)}`
229 : `${isGuessed ? 'retrying around' : 'resuming at'} ${hhmm(resumeAt(pending))}`
230 $.ui.toast(`${head} · ${resume}`)
231 }
232}
233
234async function listAgents($: EngineInterface): Promise<Agent[]> {
235 try {
236 const { exitCode, stdout } = await $.process.run(['claude', 'agents', '--json'], { timeoutMs: 15_000 })
237 if (exitCode !== 0) return []
238 const parsed: unknown = JSON.parse(stdout)
239 return Array.isArray(parsed) ? (parsed as Agent[]) : []
240 } catch {
241 return []
242 }
243}
244
245// A recipient is spelled as SendMessage spells it: a session name, a session id, or a uds:/.../<pid>.sock address.
246function findAgent(agents: Agent[], address: string) {
247 const pid = /cc-socks\/(\d+)\.sock/.exec(address)?.[1]
248 return agents.find(
249 a => a.name === address || a.sessionId === address || (pid !== undefined && String(a.pid) === pid),
250 )
251}
252
253async function fire($: EngineInterface) {
254 const p = saved.pending
255 if (!p || saved.handled.includes(p.resetsAt)) return
256 timer = undefined
257 ticker?.cancel()
258 ticker = undefined
259 saved = { ...saved, pending: null, handled: [...saved.handled, p.resetsAt].slice(-20) }
260 await save($)
261
262 // The run is over: no resume and no nudges after usage-window.json's `until`.
263 await loadWindow($)
264 if (windowEnded(await $.clock.now())) {
265 await refreshStatus($)
266 $.ui.toast(`Usage window ended at ${usageWindow!.untilText}: not resuming`)
267 return
268 }
269
270 // Someone already got this session going again after the cut: leave it alone.
271 // After a pause Claude answers once more (stopping its workers), so only a running turn counts there.
272 const isResumed = isBusy || (!p.isPause && lastAnswerAt > p.cutAt)
273 if (!isResumed) {
274 void $.prompt.submit({ text: RESUME_TEXT }).catch(() => undefined)
275 }
276
277 let nudged = 0
278 if (saved.workers.length) {
279 const agents = await listAgents($)
280 const seen = new Set<string>()
281 for (const address of saved.workers) {
282 const agent = findAgent(agents, address)
283 if (!agent?.sessionId || agent.sessionId === sessionId || seen.has(agent.sessionId)) continue
284 seen.add(agent.sessionId)
285 if (agent.status !== 'idle') continue
286 const sent = await $.session.send({ to: { sessionId: agent.sessionId }, text: NUDGE_TEXT }).catch(() => null)
287 if (sent?.isDelivered) nudged += 1
288 }
289 }
290
291 await refreshStatus($)
292 const head = isResumed ? 'Already running' : 'Resumed'
293 $.ui.toast(nudged ? `${head} · ${plural(nudged, 'worker')} nudged` : head)
294}
295
296function isNearLimit(five: SessionRateLimit | undefined) {
297 const warn = usageWindow?.warnPercent
298 return warn != null && five !== undefined && five.percentUsed >= warn
299}
300
301// The 5h window reached warnPercent: one toast per window (per 5h reset).
302async function warnIfNear($: EngineInterface) {
303 const five = limits.find(r => r.kind === 'five_hour')
304 if (saved.pending || !isNearLimit(five)) return
305 const reset = resetOf(five) ?? 0
306 if (saved.warnedFor === reset) return
307 saved = { ...saved, warnedFor: reset }
308 await save($)
309 $.ui.toast(`Usage window: 5h at ${five!.percentUsed}% · warn peers (near limit)`)
310}
311
312async function addWorker($: EngineInterface, address: string) {
313 if (!address || saved.workers.includes(address)) return
314 saved = { ...saved, workers: [...saved.workers, address].slice(-30) }
315 await save($)
316 if (saved.pending) await refreshStatus($)
317}
318
319function usageLine(rows: readonly SessionRateLimit[]) {
320 const five = rows.find(r => r.kind === 'five_hour')
321 const week = rows.find(r => r.kind === 'seven_day')
322 if (!five && !week) return null
323 const parts: string[] = []
324 if (five) {
325 const reset = resetOf(five)
326 parts.push(`5h ${five.percentUsed}%${reset === null ? '' : ` (resets ${hhmm(reset)})`}`)
327 }
328 if (week) parts.push(`week ${week.percentUsed}%`)
329 return `Usage: ${parts.join(', ')}`
330}
331
332// The usage-window line of the note for Claude: none without a config.
333function windowLine(rows: readonly SessionRateLimit[], now: number) {
334 const w = usageWindow
335 if (!w) return null
336 if (windowEnded(now)) return `Usage window ended at ${w.untilText}: stop all work and workers.`
337 const five = rows.find(r => r.kind === 'five_hour')
338 const peers = w.peers.length ? ` Peers: ${w.peers.join(', ')}.` : ''
339 const p = saved.pending
340 if (p?.isPause) {
341 const resume = isPastUntil(p)
342 ? `no auto-resume, the window ends at ${w.untilText}`
343 : `auto-resume at ${hhmm(resumeAt(p))}`
344 return `Usage window: 5h at ${five?.percentUsed ?? '?'}% (pause at ${w.pausePercent}%). Pause now: stop your workers and peers per the Usage window rule in CLAUDE.md; ${resume}.${peers}`
345 }
346 if (isNearLimit(five)) return `Usage window: 5h at ${five!.percentUsed}%, warn peers (NEAR LIMIT) per CLAUDE.md.${peers}`
347 const until = w.until === null ? '' : `, ends ${when(w.until, now)}`
348 return `Usage window: pause at ${w.pausePercent}% of 5h${until}.${peers}`
349}
350
351// The active window, for /limits.
352function windowReport(now: number) {
353 const w = usageWindow
354 if (!w) return null
355 if (windowEnded(now)) return `Window ended ${when(w.until!, now)} · no auto-resume`
356 const parts = [
357 ...(w.warnPercent === null ? [] : [`Window: warn at ${w.warnPercent}%`]),
358 `${w.warnPercent === null ? 'Window: pause' : 'pause'} at ${w.pausePercent}%`,
359 `resume reset +${duration(w.resumeDelayMs)}`,
360 ]
361 if (w.until !== null) parts.push(`ends ${when(w.until, now)}`)
362 if (w.peers.length) parts.push(`peers ${w.peers.join(', ')}`)
363 return parts.join(' · ')
364}
365
366// ~/.claude/usage/limits.json, for other sessions and scripts: a tmp file, then a rename over the old one.
367async function publish($: EngineInterface, rows: readonly SessionRateLimit[]) {
368 const where = await locate($)
369 if (!where) return
370 const row = (kind: SessionRateLimit['kind']) => {
371 const r = rows.find(x => x.kind === kind)
372 return r ? { percentUsed: r.percentUsed, resetsAt: r.resetsAt ?? null } : null
373 }
374 const body = { fiveHour: row('five_hour'), week: row('seven_day') }
375 if (!body.fiveHour && !body.week) return
376 const unchanged = JSON.stringify(body)
377 if (unchanged === lastPublished) return
378 lastPublished = unchanged
379 const text = `${JSON.stringify({ ...body, updatedAt: new Date(await $.clock.now()).toISOString() }, null, 2)}\n`
380 const tmp = `${where.limits}.${sessionId || 'session'}.tmp`
381 try {
382 await $.fs.write(tmp, text)
383 const native = (p: string) => p.replace(/\//g, '\\')
384 const argv = where.isWindows
385 ? ['cmd', '/c', 'move', '/y', native(tmp), native(where.limits)]
386 : ['mv', '-f', tmp, where.limits]
387 const { exitCode } = await $.process.run(argv, { timeoutMs: 5_000 })
388 // The rename failed: a plain write still beats a stale file.
389 if (exitCode !== 0) await $.fs.write(where.limits, text)
390 } catch {
391 lastPublished = ''
392 }
393}
394
395function limitsReport(rows: readonly SessionRateLimit[], now: number) {
396 const lines: string[] = []
397 for (const [kind, label] of [['five_hour', '5h'], ['seven_day', 'Week']] as const) {
398 const row = rows.find(r => r.kind === kind)
399 if (!row) continue
400 const reset = resetOf(row)
401 lines.push(`${label} ${row.percentUsed}%${reset === null ? '' : ` · resets ${when(reset, now)}`}`)
402 }
403 if (!lines.length) lines.push('No usage reading yet')
404 const p = saved.pending
405 const n = saved.workers.length
406 lines.push(
407 p
408 ? `⏸ ${resumeLabel(p, now)}${n ? ` · ${plural(n, 'worker')} to nudge` : ''}`
409 : `No resume pending${n ? ` · ${plural(n, 'worker')} known` : ''}`,
410 )
411 const w = windowReport(now)
412 if (w) lines.push(w)
413 return lines.join('\n')
414}
415
416export const register: Register = on => {
417 on('session.start', async ($, e, next) => {
418 sessionId = await $.session.id()
419 const stored = (await $.store.get(key())) as Saved | undefined
420 if (stored && Array.isArray(stored.handled) && Array.isArray(stored.workers)) saved = stored
421 limits = (await $.session.usage()).rateLimits
422 await loadWindow($)
423 await publish($, limits)
424 await $.command.register({ name: 'limits', description: 'Show usage windows and any pending resume', immediate: true })
425 if (saved.pending && !saved.handled.includes(saved.pending.resetsAt)) await schedule($)
426 else await refreshStatus($)
427 return next(e)
428 })
429
430 // The 5h reading rides the hint line as a dim tail, after any tail another hook already set.
431 on('ui.render', { component: 'PromptHint' }, async ($, e, next) => {
432 const line = await read($, tail)
433 if (!line) return next(e)
434 return next({ ...e, props: { ...e.props, tail: e.props.tail ? `${e.props.tail} · ${line}` : line } })
435 })
436
437 on('command.run', { command: 'limits' }, async $ => {
438 limits = (await $.session.usage()).rateLimits
439 await loadWindow($)
440 await publish($, limits)
441 return { text: limitsReport(limits, await $.clock.now()) }
442 })
443
444 on('session.measure', async ($, e, next) => {
445 limits = e.rateLimits
446 if (e.changed.includes('rateLimits')) {
447 await loadWindow($)
448 await publish($, limits)
449 await markCut($, false)
450 await warnIfNear($)
451 if (!saved.pending) await refreshStatus($)
452 }
453 return next(e)
454 })
455
456 on('classic.StopFailure', async ($, e, next) => {
457 if (e.error === 'rate_limit') await markCut($, true)
458 return next(e)
459 })
460
461 on('turn.start', ($, e, next) => {
462 isBusy = true
463 return next(e)
464 })
465
466 on('turn.complete', async ($, e, next) => {
467 if (e.agentId === undefined) {
468 isBusy = false
469 if (e.reason === 'answer') lastAnswerAt = await $.clock.now()
470 }
471 return next(e)
472 })
473
474 on('session.send', async ($, e, next) => {
475 const result = await next(e)
476 if (e.origin.kind === 'model' && e.agentId === undefined && result.isDelivered) await addWorker($, e.to)
477 return result
478 })
479
480 on('session.receive', async ($, e, next) => {
481 // Peer deliveries carry the sender in their envelope; best effort, the text format is the engine's.
482 const from = e.agentId === undefined ? /from="([^"]+)"/.exec(e.text)?.[1] : undefined
483 if (from) await addWorker($, from)
484 return next(e)
485 })
486
487 on('prompt.submit', async ($, e, next) => {
488 if (e.turnId !== undefined) return next(e)
489 const rows = (await $.session.usage()).rateLimits
490 await loadWindow($)
491 const lines = [usageLine(rows), windowLine(rows, await $.clock.now())].filter((l): l is string => l !== null)
492 return lines.length ? next({ ...e, context: [...(e.context ?? []), ...lines] }) : next(e)
493 })
494}
495types/index.d.ts 12 lines1/** The 5h usage line shown dim at the end of the prompt hint. */
2export type HintTail = string
3
4declare module 'claude-code' {
5 interface PluginState {
6 'limit-resume': {
7 /** The 5h usage line for the prompt hint's tail; empty while below the warning level or paused. */
8 tail: string
9 }
10 }
11}
12