SLOPSHOPPER

graceful-stop

Winds agents down cleanly as the session's credit runs out and has the orchestrator write a resume memo.

bandrowsguardcommandtoastnetwork
★ 1v0.4.4MITupdated 2026-10-09Rctt27/graceful-stop
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · graceful-stop
› fix the failing auth test and add an audit log call ⏺ Read(src/auth.ts) ⎿ Read 6 lines ⏺ Update(src/auth.ts) ⎿ Added 2 lines, removed 1 line ⏺ Bash(bun test) ⎿ 3 pass, 1 fail ● Done. refresh now rejects expired claims and logs an audit event. ✻ Worked for 42s · done 4:20 PM › /graceful-stop ⎿ graceful-stop: Phase: armed (thresholds session 90%, weekly 95%, overage budget $2.00, grace 5 calls) ⎿ graceful-stop: Credit: five_hour 31% ╭─────────────────────────────────────────────────────────────────────────────────────────────────────────────────── │ ⏹ graceful-stop ● ARMED clean stop at 90 % (5h) · 95 % (7d) · overage budget $2.00 · 5 grace calls [ Off ] [ │ │ Session 5h▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇ 31 % ╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────── ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
╭─────────────────────────────────────────────────────────────────────────────────────────────────── │ ⏹ graceful-stop ● ARMED clean stop at 90 % (5h) · 95 % (7d) · overage budget $2.00 · 5 grace c │ │ Session 5h▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇ 31 % ╰───────────────────────────────────────────────────────────────────────────────────────────────────
README

graceful-stop

Tested with Claude Code 2.1.295.

A Claude Code mod that stops your agents cleanly before your Pro or Max credit runs out, instead of letting the limit cut them off mid-task. They wrap up, report, and the orchestrator writes a memo you can resume from once your credit is back.

The graceful-stop card

How it works

  1. Armed: the mod watches your 5-hour and 7-day windows.
  2. Stopping: at 90% of the 5-hour window or 95% of the week, no new subagent can start. Running ones get 5 more tool calls to leave things consistent, then hand back a status report.
  3. Overage: if a window hits 100%, the stop can finish on extra usage, up to an estimated $2.
  4. Stopped: the orchestrator turns the reports into GRACEFUL-STOP_<date>.md at the root of your repo, and no more requests go out.

The weekly threshold is higher because the last 10% of a week is about one whole session.

Once your credit is back, Resume (or /gs resume) re-arms the mod and has the orchestrator pick up from the memo. Too early, and it tells you when:

Your credits have not been reset yet. Reset time: today 18:40 (in 2 h 13).

It also works from a new session in the same repo: the mod remembers the last memo, or takes the newest one at the root. claude --resume <session> brings back the conversation too.

The memo and the reports are written in your language. Anything the mod says in the conversation shows up in yellow, so you can tell it apart from the agent's own work.

Examples

  • A long job hits the limit overnight. Four subagents are refactoring a codebase when the 5-hour window reaches 90%. They finish their current step and report back. In the morning you find the memo at the root of the repo, and /gs resume relaunches what was left.
  • You need to step away. /gs stop winds everything down now, with the same memo, instead of waiting for a threshold.
  • You come back in a new session. In the same repo, /gs resume finds the last memo. If your credit isn't back yet, it tells you when it will be.

Commands

/gs is short for /graceful-stop.

Command
/gsShow the card
/gs stopStart the clean stop now
/gs resumeRe-arm and pick up from the memo
/gs on / offArm or disarm for this session

Commands run immediately, even mid-turn. In the panel, click the buttons (fullscreen terminal or desktop app), or press ctrl+x tab then o / r. ctrl+x ctrl+a folds the panel.

Settings

In /config, set the ▸ graceful-stop row to true to show the settings (reopen /config if they don't appear).

SettingDefault
Armed by default at session starttrue (false: each session starts disarmed, /gs on arms it)
Session threshold90%
Weekly threshold95%
Overage budget$2
Grace tool calls5

Install

claude plugin marketplace add Rctt27/graceful-stop
claude plugin install graceful-stop@graceful-stop

Then /reload-plugins. From a local clone: claude --plugin-dir /path/to/graceful-stop.

Requirements: Claude Code with mods (function-hook plugins, early access; tested on 2.1.289 – 2.1.295) and a Pro or Max subscription. Credit percentages only exist on a subscription: with an API key, only /gs stop works. Extra usage is optional; without it, the stop has to fit before 100%.

Good to know

  • The overage budget is an estimate at API prices, not your invoice. The monthly cap you set on claude.ai is the real safety net.
  • The gauges show your whole account, like /usage: every session and claude.ai count. The mod reads it once a minute, so usage elsewhere shows up within a minute and can start the stop. Reset times are shown in local time.
  • A tool already running isn't interrupted; the next call is refused.
  • Teammates in their own terminal pane are out of reach; subagents started by the Agent tool are covered.
  • Reports are captured from Claude Code's internal SubagentHandback tool. If that changes, the memo loses them but the rest still works.

What it touches

The mod makes one network call, once a minute: it reads your account's usage from Anthropic (api.anthropic.com/api/oauth/usage, the endpoint /usage uses). Claude Code adds your login to the request; the mod never sees it. Nothing else leaves your machine.

  • Reads: your account's usage, the session's credit windows and cost, the list of running subagents, and their status reports. Nothing else from the conversation.
  • Writes: the memo, GRACEFUL-STOP_<date>.md at the root of your repo, during a stop only. It copies the subagents' reports into it.
  • Keeps in Claude Code's plugin store, on your machine: the last credit reading and when it was taken, the last memo's path, and the memos already resumed from.
  • Acts on the session: it adds its notes to the conversation, submits the resume prompt when you resume, and refuses new subagents, tool calls past the grace calls, and requests once stopped.

Troubleshooting

  • No card above the prompt: it's folded. ctrl+x ctrl+a unfolds it, and /gs shows the card anyway.
  • "No credit reading yet": the account's usage hasn't come in yet; it comes within a minute, or with the first model answer. With an API key there is none, so only /gs stop works.
  • The gauges lag behind /usage: the account read failed (offline, or CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC set), so the card falls back on this session's own reading.
  • A setting seems ignored: an out-of-range value falls back to its default, and the session start says which one.
  • Resume finds no memo: it looks at the root of the current repo and skips memos already resumed from. You can still ask Claude to read a memo yourself.
  • A change doesn't show after an update: run /reload-plugins.

Support

Bugs and questions: GitHub issues. Security issues: report them privately from the repo's Security tab.

Development

claude plugin validate .
claude plugin test .

Load with --plugin-dir while editing: each save reloads the mod.

License

MIT, see LICENSE.

Source 2 files
hooks/register.tsx 1242 lines
1import { atom, read, update } from 'claude-code'
2import type { AgentInfo, EngineInterface, Register, ResolveInput, SessionRateLimit } from 'claude-code'
3
4import type { GracefulStopAgent, GracefulStopCredit, GracefulStopStatus } from '../types'
5
6const NAME = 'graceful-stop'
7// A short name for the same command: /gs.
8const ALIAS = 'gs'
9const COMMANDS = [NAME, ALIAS]
10const TAG = `[${NAME}]`
11const FALLBACK_MARK = `<!-- ${NAME}:fallback -->`
12const ACTIVE_AGENT = new Set(['pending', 'running', 'waiting'])
13// Main turns the orchestrator gets, once every agent is done, to write the
14// memo before the mod stops the session anyway.
15const MAX_IDLE_TURNS = 2
16// The tool a subagent hands its final report back with; never counted or cut off.
17const HANDBACK_TOOL = 'SubagentHandback'
18// The /config row that folds the mod's other rows away, like a chevron.
19const TOGGLE_KEY = `${NAME}.showSettings`
20// `$.store` keys, kept between sessions: the last credit reading and the last
21// memo, so a fresh session can still tell when to resume and from what.
22const CREDIT_KEY = 'credit'
23const CREDIT_AT_KEY = 'creditAt'
24const MEMO_KEY = 'memoPath'
25// The memos already resumed from, so no resume runs one twice; the last few.
26const RESUMED_KEY = 'resumed'
27const MAX_RESUMED = 50
28// Memos written before the mod was renamed keep the old prefix.
29const MEMO_FILE = /^(GRACEFUL-STOP|CLEAN-END-OF-SESSION)_.*\.md$/
30const SUBCOMMANDS = ['status', 'stop', 'resume', 'on', 'off']
31// Where Claude Code's /usage reads the account's windows, whatever session or
32// app spent them; asked with the session's own credential, held by the host.
33const USAGE_URL = 'https://api.anthropic.com/api/oauth/usage'
34const ACCOUNT_KINDS = ['five_hour', 'seven_day']
35const ACCOUNT_EVERY_MS = 60_000
36
37// The numeric settings: a value that is not a number within its bounds gives
38// way to the default, and the session start says so.
39const SETTINGS = {
40  sessionThreshold: { label: 'Session trigger threshold', fallback: 90, min: 1, max: 100 },
41  weeklyThreshold: { label: 'Weekly trigger threshold', fallback: 95, min: 1, max: 100 },
42  overageBudgetUsd: { label: 'Overage budget', fallback: 2, min: 0, max: Infinity },
43  graceToolCalls: { label: 'Grace tool calls', fallback: 5, min: 0, max: Infinity },
44}
45type SettingKey = keyof typeof SETTINGS
46
47const ARMED: GracefulStopStatus = {
48  phase: 'armed',
49  trigger: null,
50  resetsAt: null,
51  baselineUsd: null,
52  spentUsd: 0,
53  warned: {},
54  memoPath: null,
55  agents: [],
56  idleTurns: 0,
57  fallbackHash: null,
58}
59
60const OFF: GracefulStopStatus = { ...ARMED, phase: 'off' }
61
62const status = atom({ plugin: 'graceful-stop', key: 'status' } as const, ARMED)
63const credit = atom({ plugin: 'graceful-stop', key: 'credit' } as const, null)
64const account = atom({ plugin: 'graceful-stop', key: 'account' } as const, null)
65const minute = atom({ plugin: 'graceful-stop', key: 'minute' } as const, 0)
66const started = atom({ plugin: 'graceful-stop', key: 'started' } as const, false)
67
68type Engine = EngineInterface
69type Config = {
70  /** Trigger for the 5-hour session window, in percent. */
71  sessionThreshold: number
72  /** Trigger for the 7-day window: its last few percent are about one whole session. */
73  weeklyThreshold: number
74  budgetUsd: number
75  graceCalls: number
76  /** Whether a new session starts armed, else off until the person arms it. */
77  armAtStart: boolean
78  /** The labels of the settings whose value was not valid, replaced by their default. */
79  invalid: string[]
80}
81
82// A numeric setting, or null when it is not a number within its bounds; left
83// blank, its default.
84const settingOf = (raw: unknown, key: SettingKey) => {
85  const { fallback, min, max } = SETTINGS[key]
86  if (raw === undefined || raw === null || (typeof raw === 'string' && raw.trim() === '')) return fallback
87  const n = typeof raw === 'number' || typeof raw === 'string' ? Number(raw) : NaN
88
89  return Number.isFinite(n) && n >= min && n <= max ? n : null
90}
91
92const configOf = (options: Record<string, unknown>): Config => {
93  const keys = Object.keys(SETTINGS) as SettingKey[]
94  const read = Object.fromEntries(keys.map(k => [k, settingOf(options[k], k)])) as Record<SettingKey, number | null>
95  const value = (k: SettingKey) => read[k] ?? SETTINGS[k].fallback
96
97  return {
98    sessionThreshold: value('sessionThreshold'),
99    weeklyThreshold: value('weeklyThreshold'),
100    budgetUsd: value('overageBudgetUsd'),
101    graceCalls: Math.floor(value('graceToolCalls')),
102    armAtStart: options.armAtStart !== false,
103    invalid: keys.filter(k => read[k] === null).map(k => SETTINGS[k].label),
104  }
105}
106
107// Whether the main loop is in a turn; a reload forgets it, which only means
108// the next clean stop may judge the session idle and write no memo.
109let isMainBusy = false
110
111const isWatching = (s: GracefulStopStatus) => s.phase === 'stopping' || s.phase === 'overage'
112const isHalted = (s: GracefulStopStatus) => s.phase === 'stopped' || s.phase === 'braked'
113
114const usd = (n: number) => `$${n.toFixed(2)}`
115
116const peakOf = (windows: readonly SessionRateLimit[]) =>
117  windows.reduce<SessionRateLimit | null>(
118    (top, w) => (top === null || w.percentUsed > top.percentUsed ? w : top),
119    null,
120  )
121
122// The weekly window has its own threshold; the session window and any other
123// (a gateway's spend limit) take the session one.
124const thresholdOf = (cfg: Config, kind: string) =>
125  kind === 'seven_day' ? cfg.weeklyThreshold : cfg.sessionThreshold
126
127// The window past its threshold by the widest margin, or null.
128const crossedWindow = (cfg: Config, windows: readonly SessionRateLimit[]) =>
129  windows
130    .filter(w => w.percentUsed >= thresholdOf(cfg, w.kind))
131    .reduce<SessionRateLimit | null>(
132      (top, w) =>
133        top === null ||
134        w.percentUsed - thresholdOf(cfg, w.kind) > top.percentUsed - thresholdOf(cfg, top.kind)
135          ? w
136          : top,
137      null,
138    )
139
140const thresholdsText = (cfg: Config) =>
141  `session ${cfg.sessionThreshold}%, weekly ${cfg.weeklyThreshold}%`
142
143const describeWindow =(w: SessionRateLimit | null) =>
144  w === null ? 'credit unknown' : `${w.kind} at ${w.percentUsed}%`
145
146// A reading taken before its window reset counts as reset: once the brake
147// holds, no request refreshes it.
148const isPastReset = (w: SessionRateLimit, now: number) =>
149  w.resetsAt !== undefined && Date.parse(w.resetsAt) <= now
150
151// The windows whose reading still holds.
152const currentWindows = (windows: readonly SessionRateLimit[], now: number) =>
153  windows.filter(w => !isPastReset(w, now))
154
155// The windows still over their threshold.
156const blockingWindows = (cfg: Config, windows: readonly SessionRateLimit[], now: number) =>
157  currentWindows(windows, now).filter(w => w.percentUsed >= thresholdOf(cfg, w.kind))
158
159// Two readings of one window: their reset times agree, give or take the
160// rounding of each source, or one of them has none.
161const isSameWindow = (a: SessionRateLimit, b: SessionRateLimit) =>
162  a.resetsAt === undefined ||
163  b.resetsAt === undefined ||
164  Math.abs(Date.parse(a.resetsAt) - Date.parse(b.resetsAt)) < 10 * 60_000
165
166// One reading per window out of several sources, however old: the later
167// window, and within one window the higher figure, as a window's use only
168// grows until it resets.
169const mergeWindows = (...readings: (readonly SessionRateLimit[])[]) =>
170  readings.flat().reduce<SessionRateLimit[]>((out, w) => {
171    const i = out.findIndex(o => o.kind === w.kind)
172    const o = out[i]
173    if (o === undefined) return [...out, w]
174    const isNewer = isSameWindow(o, w)
175      ? w.percentUsed > o.percentUsed
176      : Date.parse(w.resetsAt ?? '') > Date.parse(o.resetsAt ?? '')
177
178    return isNewer ? out.map((x, j) => (j === i ? w : x)) : out
179  }, [])
180
181// The usage endpoint's answer as rate-limit windows: `utilization` 0 to 100,
182// `resets_at` ISO 8601; null when it reads as nothing.
183const parseAccount = (text: string): SessionRateLimit[] | null => {
184  let data: unknown
185  try {
186    data = JSON.parse(text)
187  } catch {
188    return null
189  }
190  if (typeof data !== 'object' || data === null) return null
191  const windows = ACCOUNT_KINDS.flatMap((kind): SessionRateLimit[] => {
192    const w = (data as Record<string, unknown>)[kind]
193    if (typeof w !== 'object' || w === null) return []
194    const { utilization, resets_at: resets } = w as { utilization?: unknown; resets_at?: unknown }
195    if (typeof utilization !== 'number' || !Number.isFinite(utilization)) return []
196    const percentUsed = Math.round(utilization * 10) / 10
197
198    return typeof resets === 'string' ? [{ kind, percentUsed, resetsAt: resets }] : [{ kind, percentUsed }]
199  })
200
201  return windows.length === 0 ? null : windows
202}
203
204// When the last blocking window resets: NaN when one of them gives no time.
205const lastResetOf = (windows: readonly SessionRateLimit[]) =>
206  Math.max(...windows.map(w => (w.resetsAt === undefined ? NaN : Date.parse(w.resetsAt))))
207
208const pad = (n: number) => String(n).padStart(2, '0')
209const DAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
210const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
211
212const dayOf = (at: Date, now: Date) => {
213  const startOf = (d: Date) => new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime()
214  const days = Math.round((startOf(at) - startOf(now)) / 86_400_000)
215  if (days === 0) return 'today'
216  if (days === 1) return 'tomorrow'
217
218  return `${DAYS[at.getDay()]} ${at.getDate()} ${MONTHS[at.getMonth()]}`
219}
220
221const remainingOf = (ms: number) => {
222  const minutes = Math.ceil(ms / 60_000)
223  if (minutes < 60) return `in ${minutes} min`
224  if (minutes < 24 * 60) return `in ${Math.floor(minutes / 60)} h ${pad(minutes % 60)}`
225
226  return `in ${Math.floor(minutes / 1440)} d ${Math.floor((minutes % 1440) / 60)} h`
227}
228
229// A time in the person's local time: `today 18:40`.
230const clockOf = (at: number, now: number) => {
231  const date = new Date(at)
232
233  return `${dayOf(date, new Date(now))} ${pad(date.getHours())}:${pad(date.getMinutes())}`
234}
235
236// A reset time in the person's local time: `today 18:40 (in 2 h 13)`.
237const whenText = (at: number, now: number) =>
238  Number.isNaN(at) ? 'at an unknown time' : `${clockOf(at, now)} (${remainingOf(at - now)})`
239
240// A memo's date in the person's local time: `2026-10-09_12h05`.
241const stamp = (ms: number) => {
242  const d = new Date(ms)
243
244  return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}_${pad(d.getHours())}h${pad(d.getMinutes())}`
245}
246
247// FNV-1a, enough to tell the mod's provisional memo from any other content.
248const hashOf = (text: string) => {
249  let h = 0x811c9dc5
250  for (let i = 0; i < text.length; i += 1) h = Math.imul(h ^ text.charCodeAt(i), 0x01000193) >>> 0
251
252  return h
253}
254
255// How a subagent's run ended, as its memo section says it.
256const ENDED: Record<string, string> = { answer: 'completed', aborted: 'interrupted', error: 'failed', refusal: 'refused' }
257// Ends the mod saw itself, which the agent list may not tell.
258const ENDED_BADLY = new Set(['interrupted', 'failed', 'refused'])
259
260const normalize = (path: string) => path.replace(/[\\/]+/g, '/').replace(/\/$/, '').toLowerCase()
261
262const isWithin = (path: string, dir: string) =>
263  normalize(path) === normalize(dir) || normalize(path).startsWith(`${normalize(dir)}/`)
264
265const handbackText = (input: object) => {
266  const message = (input as { message?: unknown }).message
267
268  return typeof message === 'string' ? message : null
269}
270
271const joinPath = (dir: string, file: string) => {
272  const sep = dir.includes('\\') ? '\\' : '/'
273
274  return dir.replace(/[\\/]+$/, '') + sep + file
275}
276
277const toRecord = (a: AgentInfo): GracefulStopAgent => ({
278  id: a.id,
279  description: a.description,
280  type: a.type,
281  status: a.status,
282  report: null,
283})
284
285const note = (text: string) => ({
286  message: { type: 'user' as const, content: [{ type: 'text' as const, text }] },
287})
288
289const agentWarning = (cfg: Config, trigger: string) =>
290  `${TAG} The Claude session credit is almost used up (${trigger}). Wind down cleanly: start no ` +
291  `new step. You have at most ${cfg.graceCalls} more tool calls to leave files in a consistent ` +
292  `state (finish or revert the change in progress), then your tools will be cut off. Your final ` +
293  `answer must be a status report: 1) what is done; 2) what is half done, with the files involved; ` +
294  `3) the exact next step to resume; 4) anything to watch out for. Write the report in the ` +
295  `language your task asks its results in, else in the language your task is written in, not ` +
296  `in the language of this note.`
297
298const AGENT_CUTOFF =
299  `${TAG} Tools cut off: the session credit is almost used up. Call no more tools. Write your ` +
300  `final answer now as a status report (done / half done with files / next step / watch-outs).`
301
302// Everything the mod says in the conversation is drawn in this colour, under
303// this label, so it never reads as the agent's own work.
304const MOD_COLOR = 'yellow'
305const MOD_LABEL = `⏹  ${NAME}`
306// The panel's frame: a neutral gray that reads on dark and light themes.
307const CARD_BORDER = '#71717a'
308
309const isModText = (text: string) => text.trimStart().startsWith(TAG)
310
311// The message without its tag, or a command's output without the plugin name
312// the engine prints before it.
313const modBody = (text: string) => {
314  const body = text.trimStart()
315  const prefix = [TAG, ...COMMANDS.map(c => `${c}:`)].find(p => body.startsWith(p)) ?? ''
316
317  return body.slice(prefix.length).trim()
318}
319
320const SPAWN_DENIED = `${TAG} Spawn refused: a clean stop is under way, the session credit is almost used up.`
321
322const mainNote = (cfg: Config, trigger: string, agents: number, memoPath: string) =>
323  `${TAG} The Claude session credit has reached ${trigger}. Clean stop started: take on no new ` +
324  `task and spawn no agent (spawning is blocked). ${agents} active subagent(s) were told to wind ` +
325  `down and return a status report. Finish what you are doing as briefly as you can. Write the ` +
326  `resume memo as soon as the last report is in, in that same turn (right away if there is no ` +
327  `agent): before ending any turn, check whether any agent is still running, and never end a ` +
328  `turn just to wait for reports that may already be in. Write it to ${memoPath}, fully ` +
329  `replacing the provisional file there: overall goal, each agent's state (done / partial / next ` +
330  `step / files), decisions made, and how to resume. Write the memo in the language the user ` +
331  `writes in (that of their latest messages if they switched), not in the language of this ` +
332  `note. Then stop. Past 100% of the credit, paid ` +
333  `overage of at most ${usd(cfg.budgetUsd)} is allowed for this clean stop only: be concise.`
334
335// How to pick the work up again; `back` is when the credit is back
336// (whenText), null when it already is.
337const resumeHint = (back: string | null) =>
338  back === null
339    ? `The credit is below the thresholds: /${NAME} resume picks the work up.`
340    : `Credit back ${back}: /${NAME} resume then picks the work up.`
341
342const haltText = (cfg: Config, s: GracefulStopStatus, back: string | null) => {
343  const why =
344    s.phase === 'braked'
345      ? `Overage budget used up (${usd(s.spentUsd)} of ${usd(cfg.budgetUsd)}).`
346      : `Session stopped cleanly (${s.trigger ?? 'threshold reached'}).`
347  const memo = s.memoPath === null ? '' : ` Resume memo: ${s.memoPath}.`
348
349  return `${TAG} ${why}${memo} No request was sent to the model. ${resumeHint(back)}`
350}
351
352const resumePrompt = (memoPath: string) =>
353  `${TAG} The credit is back: resume the work a clean stop interrupted. Read the resume memo at ` +
354  `${memoPath} first, then carry on from it: relaunch each unfinished task from its next step, ` +
355  `as subagents where the memo had them, and check the files it lists as half done before ` +
356  `building on them. Answer in the language the memo is written in, not in the language of ` +
357  `this note.`
358
359const notReset = (back: string) => `Your credits have not been reset yet. Reset time: ${back}.`
360
361async function activeAgents($: Engine) {
362  return (await $.agent.list()).filter(a => ACTIVE_AGENT.has(a.status))
363}
364
365const agentSection = (a: GracefulStopAgent) => [
366  `### ${a.description}`,
367  '',
368  `- Type: ${a.type}`,
369  `- Status: ${a.status}`,
370  `- Id: \`${a.id}\``,
371  '',
372  a.report === null ? '_No status report received._' : a.report.trim(),
373  '',
374]
375
376async function fallbackMemo($: Engine, s: GracefulStopStatus) {
377  const sessionId = await $.session.id()
378  const now = new Date(await $.clock.now()).toISOString()
379
380  return [
381    FALLBACK_MARK,
382    '# Resume memo (provisional)',
383    '',
384    `Written by the ${NAME} mod at ${now}. The orchestrator was to replace this file with a ` +
385      `full memo; if it is still here, the clean stop did not run to the end. Each agent's own ` +
386      `status report is copied below as it came in.`,
387    '',
388    `- Trigger: ${s.trigger ?? 'unknown'}`,
389    `- Credit resets at: ${s.resetsAt ?? 'unknown'}`,
390    `- Stop state: ${s.phase}${s.phase === 'braked' ? ` (overage ${usd(s.spentUsd)})` : ''}`,
391    `- Session: \`${sessionId}\``,
392    '',
393    '## Agents covered by the stop',
394    '',
395    ...(s.agents.length === 0 ? ['No subagent was running.', ''] : s.agents.flatMap(agentSection)),
396    '## To resume',
397    '',
398    `1. \`claude --resume ${sessionId}\` brings back the conversation and the agents' status reports.`,
399    '2. Otherwise, relaunch each task above from its report.',
400    '',
401  ].join('\n')
402}
403
404// Whether the memo file holds anything but the provisional memo the mod last
405// wrote, even one that kept its first line.
406async function isMemoReplaced($: Engine, s: GracefulStopStatus) {
407  if (s.memoPath === null || !(await $.fs.exists(s.memoPath))) return false
408  const current = await $.fs.read(s.memoPath)
409  if (typeof current !== 'string') return false
410  const written = s.fallbackHash ?? null
411
412  return written === null ? !current.startsWith(FALLBACK_MARK) : hashOf(current) !== written
413}
414
415// Writes the mod's own record of the stop, unless the orchestrator already
416// replaced it with the real memo; the agents' statuses are refreshed first.
417async function writeFallback($: Engine, s: GracefulStopStatus) {
418  if (s.memoPath === null || (await isMemoReplaced($, s))) return
419  const path = s.memoPath
420  const live = new Map((await $.agent.list()).map(a => [a.id, a.status as string]))
421  const agents = s.agents.map(a => ({
422    ...a,
423    status: ENDED_BADLY.has(a.status) ? a.status : (live.get(a.id) ?? a.status),
424  }))
425  const text = await fallbackMemo($, { ...s, agents })
426  await $.fs.write(path, text)
427  const hash = hashOf(text)
428  await update($, status, cur => (cur.memoPath === path ? { ...cur, fallbackHash: hash } : cur))
429}
430
431async function warnAgent($: Engine, cfg: Config, agentId: string, trigger: string) {
432  const text = agentWarning(cfg, trigger)
433  const appended = await $.session.append({ ...note(text), agentId }).catch(() => null)
434  if (appended === null || 'deny' in appended) {
435    await $.session.send({ to: { agentId }, text }).catch(() => undefined)
436  }
437}
438
439async function warnMain($: Engine, text: string) {
440  const appended = await $.session.append(note(text)).catch(() => null)
441  if (appended === null || 'deny' in appended) {
442    await $.session.send({ to: { sessionId: await $.session.id() }, text }).catch(() => undefined)
443  }
444}
445
446// The root of the repository the session works in, else its project root.
447async function memoDir($: Engine) {
448  const root = await $.session.root()
449  const repo = await $.session.repo()
450
451  return repo !== null && isWithin(root, repo.root) ? repo.root : root
452}
453
454// When the credit is back, as whenText says it, or null when it already is.
455const backOf = (cfg: Config, windows: readonly SessionRateLimit[], now: number) => {
456  const blocking = blockingWindows(cfg, windows, now)
457
458  return blocking.length === 0 ? null : whenText(lastResetOf(blocking), now)
459}
460
461async function creditBack($: Engine, cfg: Config) {
462  const { reading } = await readCredit($)
463
464  return backOf(cfg, reading?.windows ?? [], await $.clock.now())
465}
466
467async function haltMessage($: Engine, cfg: Config, s: GracefulStopStatus) {
468  return haltText(cfg, s, await creditBack($, cfg))
469}
470
471async function resumedMemos($: Engine) {
472  const kept = await $.store.get(RESUMED_KEY).catch(() => undefined)
473
474  return Array.isArray(kept) ? kept.filter((p): p is string => typeof p === 'string') : []
475}
476
477// The memo to resume from: this session's, the last one kept, else the newest
478// at the root the memos go to; never one of another project (the store is
479// shared by every project) nor one already resumed from.
480async function findMemo($: Engine, s: GracefulStopStatus) {
481  const dir = await memoDir($)
482  const resumed = new Set((await resumedMemos($)).map(normalize))
483  const isFree = (path: string) => isWithin(path, dir) && !resumed.has(normalize(path))
484  const kept = await $.store.get(MEMO_KEY).catch(() => undefined)
485  for (const path of [s.memoPath, typeof kept === 'string' ? kept : null]) {
486    if (path !== null && isFree(path) && (await $.fs.exists(path))) return path
487  }
488  const newest = (await $.fs.list(dir).catch(() => []))
489    .filter(f => f.kind === 'file' && MEMO_FILE.test(f.name) && isFree(joinPath(dir, f.name)))
490    .sort((a, b) => b.mtimeMs - a.mtimeMs || b.name.localeCompare(a.name))[0]
491
492  return newest === undefined ? null : joinPath(dir, newest.name)
493}
494
495// A free path for a new memo: two stops in the same minute get two files.
496async function freshMemoPath($: Engine) {
497  const dir = await memoDir($)
498  const base = `GRACEFUL-STOP_${stamp(await $.clock.now())}`
499  for (let n = 1; ; n += 1) {
500    const path = joinPath(dir, n === 1 ? `${base}.md` : `${base}-${n}.md`)
501    if (!(await $.fs.exists(path))) return path
502  }
503}
504
505// Hands the orchestrator its resume prompt as a turn of its own, once idle;
506// once it went through, the memo is never resumed from again.
507async function submitResume($: Engine, memoPath: string) {
508  const sent = await $.prompt.submit({ text: resumePrompt(memoPath) }).catch(() => null)
509  if (sent === null || sent.drop !== undefined) {
510    $.ui.toast(`${NAME}: the resume prompt did not go through${sent?.drop ? ` (${sent.drop})` : ''}.`)
511    return
512  }
513  const resumed = [...(await resumedMemos($)), memoPath].slice(-MAX_RESUMED)
514  await $.store.set(RESUMED_KEY, resumed).catch(() => undefined)
515}
516
517// `/graceful-stop resume`: re-arms and relaunches the work from the
518// memo, or says why not.
519async function resume($: Engine, cfg: Config) {
520  const s = await read($, status)
521  if (isWatching(s)) return `A clean stop is under way: resume once it has ended.`
522  const back = await creditBack($, cfg)
523  if (back !== null) return notReset(back)
524  const memoPath = await findMemo($, s)
525  if (memoPath === null) {
526    return `No resume memo found in ${await memoDir($)}. /${NAME} on re-arms without resuming.`
527  }
528
529  await update($, status, () => ARMED)
530  // A command may not submit a prompt itself (it would wait on its own run):
531  // a timer submits it once the command has answered.
532  $.clock.after(1, () => submitResume($, memoPath))
533
534  return `Re-armed at ${thresholdsText(cfg)}. Resuming from ${memoPath}.`
535}
536
537async function startStop($: Engine, cfg: Config, top: SessionRateLimit | null, trigger: string) {
538  if ((await read($, status)).phase !== 'armed') return
539
540  const agents = await activeAgents($)
541  const hasWork = agents.length > 0 || isMainBusy
542  const memoPath = hasWork ? await freshMemoPath($) : null
543  const stop: GracefulStopStatus = {
544    ...ARMED,
545    phase: hasWork ? 'stopping' : 'stopped',
546    trigger,
547    resetsAt: top?.resetsAt ?? null,
548    warned: Object.fromEntries(agents.map(a => [a.id, 0])),
549    memoPath,
550    agents: agents.map(toRecord),
551  }
552  await update($, status, () => stop)
553
554  if (memoPath === null) {
555    $.ui.toast(
556      `${NAME}: ${trigger}, nothing running. No more requests will leave. ` +
557        resumeHint(await creditBack($, cfg)),
558    )
559    return
560  }
561
562  await writeFallback($, stop)
563  await $.store.set(MEMO_KEY, memoPath).catch(() => undefined)
564  await Promise.all(agents.map(a => warnAgent($, cfg, a.id, trigger)))
565  await warnMain($, mainNote(cfg, trigger, agents.length, memoPath))
566  $.ui.toast(`${NAME}: ${trigger}, clean stop of ${agents.length} agent(s) started.`)
567}
568
569// Keeps an agent the stop did not see at its start (spawned just before it).
570async function adoptAgent($: Engine, id: string) {
571  const found = (await $.agent.list()).find(a => a.id === id)
572  const record: GracefulStopAgent = found === undefined
573    ? { id, description: 'unknown task', type: 'unknown', status: 'running', report: null }
574    : toRecord(found)
575  await update($, status, s =>
576    s.agents.some(a => a.id === id) ? s : { ...s, agents: [...s.agents, record] },
577  )
578}
579
580// Copies a subagent's status report into the memo: its hand-back message, or
581// its final answer when it handed nothing back; an empty answer keeps the
582// report already captured.
583async function recordReport($: Engine, id: string, report: string, agentStatus: string) {
584  if (!(await read($, status)).agents.some(a => a.id === id)) await adoptAgent($, id)
585  const text = report.trim() === '' ? null : report
586  await update($, status, s => ({
587    ...s,
588    agents: s.agents.map(a =>
589      a.id === id ? { ...a, status: agentStatus, report: text ?? a.report } : a,
590    ),
591  }))
592  await writeFallback($, await read($, status))
593}
594
595// A main turn ended with every agent done: the stop is over once the memo is
596// written, or after MAX_IDLE_TURNS turns that did not write it.
597async function settleMainTurn($: Engine, cfg: Config, s: GracefulStopStatus) {
598  const isWritten = s.memoPath === null || (await isMemoReplaced($, s))
599  if (isWritten || s.idleTurns + 1 >= MAX_IDLE_TURNS) {
600    await halt($, cfg, 'stopped')
601    return
602  }
603  await update($, status, cur => (isWatching(cur) ? { ...cur, idleTurns: cur.idleTurns + 1 } : cur))
604}
605
606async function halt($: Engine, cfg: Config, phase: 'stopped' | 'braked') {
607  await update($, status, s => (isWatching(s) ? { ...s, phase } : s))
608  const s = await read($, status)
609  if (s.phase !== phase) return
610  await writeFallback($, s)
611  const back = await creditBack($, cfg)
612  $.ui.toast(
613    (phase === 'braked'
614      ? `${NAME}: overage budget used up, no more requests leave.`
615      : `${NAME}: clean stop complete.`) + ` ${resumeHint(back)}`,
616  )
617}
618
619async function checkBudget($: Engine, cfg: Config, costUsd: number | undefined) {
620  const s = await read($, status)
621  if (s.phase !== 'overage' || s.baselineUsd === null || costUsd === undefined) return
622  const spent = Math.max(0, costUsd - s.baselineUsd)
623  await update($, status, cur => (cur.phase === 'overage' ? { ...cur, spentUsd: spent } : cur))
624  if (spent >= cfg.budgetUsd) await halt($, cfg, 'braked')
625}
626
627// A credit reading, this session's or the account's: past a threshold the
628// clean stop starts, at 100% it goes on in overage. A window whose reset time
629// has passed no longer counts, whatever it read.
630async function applyReading($: Engine, cfg: Config, windows: readonly SessionRateLimit[], costUsd: number | undefined) {
631  const current = currentWindows(windows, await $.clock.now())
632  const crossed = crossedWindow(cfg, current)
633  if (crossed !== null) await startStop($, cfg, crossed, describeWindow(crossed))
634  const top = peakOf(current)
635  if (top !== null && top.percentUsed >= 100) {
636    await update($, status, (s): GracefulStopStatus =>
637      s.phase === 'stopping' ? { ...s, phase: 'overage', baselineUsd: costUsd ?? 0 } : s,
638    )
639  }
640  await checkBudget($, cfg, costUsd)
641}
642
643// Keeps a reading for the next session, merged with the one kept: a session's
644// own reading may lag behind the account's.
645async function keepReading($: Engine, windows: readonly SessionRateLimit[], at: number) {
646  const kept = await $.store.get(CREDIT_KEY).catch(() => undefined)
647  const merged = mergeWindows(Array.isArray(kept) ? (kept as SessionRateLimit[]) : [], windows)
648  await $.store.set(CREDIT_KEY, merged).catch(() => undefined)
649  await $.store.set(CREDIT_AT_KEY, at).catch(() => undefined)
650}
651
652// The account's windows, as /usage reads them; null without a subscription
653// login, where the host refuses the request, or when the answer reads as
654// nothing.
655async function fetchAccount($: Engine) {
656  const auth = await $.session.authorize().catch(() => null)
657  if (auth === null || auth.kind !== 'bearer') return null
658  const res = await $.http
659    .fetch(USAGE_URL, { auth: auth.handle, headers: { 'anthropic-beta': 'oauth-2025-04-20' } })
660    .catch(() => null)
661
662  return res !== null && res.ok ? parseAccount(res.text) : null
663}
664
665// Reads the account's credit: the card shows it, and it starts the clean
666// stop whatever session or app spent it.
667async function refreshAccount($: Engine, cfg: Config) {
668  const windows = await fetchAccount($)
669  if (windows === null) return
670  const at = await $.clock.now()
671  await update($, account, () => ({ windows, at }))
672  await keepReading($, windows, at)
673  await applyReading($, cfg, windows, (await $.session.usage()).cost?.usd)
674}
675
676async function statusText($: Engine, cfg: Config) {
677  const s = await read($, status)
678  const { reading } = await readCredit($)
679  const windows = (reading?.windows ?? []).map(w => `${w.kind} ${w.percentUsed}%`).join(', ') || 'no reading yet'
680  const warned = Object.entries(s.warned)
681  const back = await creditBack($, cfg)
682  const lines = [
683    `Phase: ${s.phase} (thresholds ${thresholdsText(cfg)}, overage budget ${usd(cfg.budgetUsd)}, grace ${cfg.graceCalls} calls)`,
684    `Credit: ${windows}`,
685    back === null ? null : `Credit back: ${back}`,
686    s.trigger === null ? null : `Trigger: ${s.trigger}`,
687    s.phase === 'overage' || s.phase === 'braked' ? `Estimated overage: ${usd(s.spentUsd)}` : null,
688    warned.length === 0 ? null : `Agents warned: ${warned.map(([id, n]) => `${id} (${n} calls)`).join(', ')}`,
689    s.memoPath === null ? null : `Memo: ${s.memoPath}`,
690  ]
691
692  return lines.filter(l => l !== null).join('\n')
693}
694
695// The band above the prompt: a card with a status badge and the buttons, then
696// one gauge per credit window.
697
698const WINDOW_NAMES: Record<string, string> = { five_hour: 'Session 5h', seven_day: 'Week 7d', spend_limit: 'Spend' }
699const windowName = (kind: string) => WINDOW_NAMES[kind] ?? kind
700const windowRank = (kind: string) => {
701  const rank = Object.keys(WINDOW_NAMES).indexOf(kind)
702
703  return rank < 0 ? Number.MAX_SAFE_INTEGER : rank
704}
705
706// The card's left column: the icon, then the mod's name in the header and
707// each window's name under it, right-aligned on the mod's name; then a gap.
708// The badge and the gauges start at the same column whatever width the
709// terminal gives the icon.
710const ICON_CELLS = 3
711const NAME_CELLS = NAME.length
712const LEFT_CELLS = ICON_CELLS + NAME_CELLS + 2
713// Cells after the gauge for `  100 %`; the card's border and padding take 4.
714const PERCENT_CELLS = 7
715const CARD_CELLS = 4
716
717// Colors as 0xRRGGBB: the gauge fades from green to amber to red as it nears
718// the window's threshold, over a dark track.
719const GREEN = 0x22c55e
720const AMBER = 0xf59e0b
721const RED = 0xef4444
722const TRACK = 0x3a3a3a
723const MARK = 0xa1a1aa
724const hex = (rgb: number) => `#${rgb.toString(16).padStart(6, '0')}`
725
726const mix = (from: number, to: number, t: number) => {
727  const at = Math.min(1, Math.max(0, t))
728  const channel = (shift: number) => {
729    const a = (from >> shift) & 0xff
730    const b = (to >> shift) & 0xff
731
732    return Math.round(a + (b - a) * at) << shift
733  }
734
735  return channel(16) | channel(8) | channel(0)
736}
737
738// The gauge's color at `percent`: green well below the threshold, amber 15
739// points before it, red at it.
740const gradientAt = (percent: number, threshold: number) => {
741  const greenUntil = threshold - 35
742  const amberAt = threshold - 15
743  if (percent <= greenUntil) return GREEN
744  if (percent <= amberAt) return mix(GREEN, AMBER, (percent - greenUntil) / (amberAt - greenUntil))
745
746  return mix(AMBER, RED, (percent - amberAt) / (threshold - amberAt))
747}
748
749// A Raster color for the terminal's own background.
750const DEFAULT_BG = 0x01000000
751// The lower seven eighths of a cell: the eighth above stays the terminal's
752// background, a thin line between two gauges.
753const BAR = '▇'
754
755type Cell = { glyph: string; fg: number; bg: number }
756
757// The gauge's cells, filled to the eighth of a cell: the cell where the fill
758// ends blends its color with the track's. An empty cell is the track, and
759// the threshold a lighter cell of it. No cell paints a background of its own:
760// one would fill the line between the gauges, and the terminal may carry it
761// over to the cells after it.
762const gaugeCells = (percent: number, threshold: number, width: number): Cell[] => {
763  const eighths = Math.round((Math.min(100, Math.max(0, percent)) / 100) * width * 8)
764  const mark = Math.min(width - 1, Math.round((threshold / 100) * width))
765
766  return Array.from({ length: width }, (_, i) => {
767    const fill = eighths - i * 8
768    const color = gradientAt(((i + 0.5) / width) * 100, threshold)
769    if (fill >= 8) return { glyph: BAR, fg: color, bg: DEFAULT_BG }
770    if (fill > 0) return { glyph: BAR, fg: mix(TRACK, color, fill / 8), bg: DEFAULT_BG }
771    if (i === mark) return { glyph: BAR, fg: MARK, bg: DEFAULT_BG }
772
773    return { glyph: BAR, fg: TRACK, bg: DEFAULT_BG }
774  })
775}
776
777const BASE64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
778
779const toBase64 = (bytes: Uint8Array) => {
780  let out = ''
781  for (let i = 0; i < bytes.length; i += 3) {
782    const n = ((bytes[i] ?? 0) << 16) | ((bytes[i + 1] ?? 0) << 8) | (bytes[i + 2] ?? 0)
783    out += (BASE64[(n >> 18) & 63] ?? '') + (BASE64[(n >> 12) & 63] ?? '')
784    out += i + 1 < bytes.length ? (BASE64[(n >> 6) & 63] ?? '') : '='
785    out += i + 2 < bytes.length ? (BASE64[n & 63] ?? '') : '='
786  }
787
788  return out
789}
790
791// A Raster's cells: little-endian u32 triplets [code point, foreground, background].
792const rasterCells = (cells: readonly Cell[]) => {
793  const words = new Uint32Array(cells.length * 3)
794  cells.forEach((c, i) => words.set([c.glyph.codePointAt(0) ?? 0x20, c.fg, c.bg], i * 3))
795
796  return toBase64(new Uint8Array(words.buffer))
797}
798
799type Run = { text: string; fg: number; bg: number }
800
801// The same cells as text runs, for a surface without Raster.
802const textRuns = (cells: readonly Cell[]) =>
803  cells.reduce<Run[]>((runs, c) => {
804    const last = runs[runs.length - 1]
805    if (last !== undefined && last.fg === c.fg && last.bg === c.bg) last.text += c.glyph
806    else runs.push({ text: c.glyph, fg: c.fg, bg: c.bg })
807
808    return runs
809  }, [])
810
811type Gauge = { name: string; cells: Cell[]; color: string; percent: string; tail: string }
812
813// Each window as a gauge sized to the card; a reading whose reset time has
814// passed is drawn empty, as the next answer will read it.
815const gaugesOf = (cfg: Config, windows: readonly SessionRateLimit[], columns: number, now: number): Gauge[] =>
816  [...windows]
817    .sort((a, b) => windowRank(a.kind) - windowRank(b.kind))
818    .map(w => {
819      const threshold = thresholdOf(cfg, w.kind)
820      const resetsAt = w.resetsAt === undefined ? NaN : Date.parse(w.resetsAt)
821      const isReset = resetsAt <= now
822      const percent = isReset ? 0 : w.percentUsed
823      const said = isReset
824        ? `↻ reset since ${clockOf(resetsAt, now)}`
825        : Number.isNaN(resetsAt) ? '' : `↻ ${clockOf(resetsAt, now)} · ${remainingOf(resetsAt - now)}`
826      const room = columns - CARD_CELLS - LEFT_CELLS - PERCENT_CELLS
827      const width = Math.max(1, Math.min(gaugeSpan(cfg), room))
828      const tail = said === '' || room - width < said.length + 3 ? '' : `   ${said}`
829
830      return {
831        name: windowName(w.kind),
832        cells: gaugeCells(percent, threshold, width),
833        color: hex(gradientAt(percent, threshold)),
834        percent: `${String(Math.round(percent)).padStart(5)} %`,
835        tail,
836      }
837    })
838
839// The credit reading, the one source of the card, the brake and resume: the
840// account's, from the usage endpoint, merged with this session's own (the
841// engine's, the last measure's), so the newer figure of each window wins;
842// else the last one kept, which the band says is old. Reading the atoms also
843// redraws the band on a measure and on each account reading.
844async function readCredit($: Engine): Promise<{ reading: GracefulStopCredit | null; isKept: boolean }> {
845  const fetched = await read($, account)
846  const measured = await read($, credit)
847  const live = (await $.session.usage()).rateLimits
848  const merged = mergeWindows(fetched?.windows ?? [], live, measured?.windows ?? [])
849  if (merged.length > 0) {
850    const at = fetched?.at ?? measured?.at ?? (await $.clock.now())
851
852    return { reading: { windows: merged, at }, isKept: false }
853  }
854  const windows = await $.store.get(CREDIT_KEY).catch(() => undefined)
855  const at = await $.store.get(CREDIT_AT_KEY).catch(() => undefined)
856  if (!Array.isArray(windows) || windows.length === 0) return { reading: null, isKept: false }
857
858  return { reading: { windows: windows as SessionRateLimit[], at: typeof at === 'number' ? at : NaN }, isKept: true }
859}
860
861// The status badge: its word and colors, by phase.
862const BADGES: Record<GracefulStopStatus['phase'], { word: string; fg: string; bg: string }> = {
863  armed: { word: 'ARMED', fg: '#86efac', bg: '#14532d' },
864  off: { word: 'OFF', fg: '#d4d4d8', bg: '#3f3f46' },
865  stopping: { word: 'STOPPING', fg: '#fcd34d', bg: '#78350f' },
866  overage: { word: 'OVERAGE', fg: '#fdba74', bg: '#7c2d12' },
867  stopped: { word: 'STOPPED', fg: '#fca5a5', bg: '#7f1d1d' },
868  braked: { word: 'BRAKED', fg: '#fca5a5', bg: '#7f1d1d' },
869}
870
871// The settings, beside the badge while the mod is armed.
872const thresholdsPart = (cfg: Config) =>
873  `clean stop at ${cfg.sessionThreshold} % (5h) · ${cfg.weeklyThreshold} % (7d)`
874const settingsText = (cfg: Config) =>
875  `${thresholdsPart(cfg)} · overage budget ${usd(cfg.budgetUsd)} · ${cfg.graceCalls} grace calls`
876
877// The gauges span the armed header from the badge's left edge to the `·`
878// after the thresholds: the badge, the space before the detail, the
879// thresholds, then ` ·`.
880const gaugeSpan = (cfg: Config) => badgeText('armed').length + 1 + thresholdsPart(cfg).length + 2
881
882const badgeText = (phase: GracefulStopStatus['phase']) => ` ● ${BADGES[phase].word} `
883
884const phaseDetail = (cfg: Config, s: GracefulStopStatus, back: string | null) => {
885  const whenBack = back === null ? 'credit is back' : `credit back ${back}`
886  switch (s.phase) {
887    case 'armed':
888      return settingsText(cfg)
889    case 'off':
890      return 'off for this session'
891    case 'stopping':
892      return `clean stop under way (${s.trigger}) · ${Object.keys(s.warned).length} agent(s) warned`
893    case 'overage':
894      return `clean stop in overage · ${usd(s.spentUsd)} of ${usd(cfg.budgetUsd)}`
895    case 'braked':
896      return `overage budget used up · ${whenBack}`
897    case 'stopped':
898      return `stopped cleanly · ${whenBack}`
899  }
900}
901
902async function tick($: Engine) {
903  const now = Math.floor((await $.clock.now()) / 60_000)
904  await update($, minute, () => now)
905}
906
907// The band's Off / On button: the same as `/graceful-stop off|on`.
908async function toggle($: Engine) {
909  await update($, status, s => (s.phase === 'off' ? ARMED : OFF))
910}
911
912// The band's Resume button: the command's resume, said in a toast.
913async function pressResume($: Engine, cfg: Config, isWorking: boolean) {
914  const said = isWorking ? 'Claude is working: resume once the turn has ended.' : await resume($, cfg)
915  $.ui.toast(`${NAME}: ${said}`)
916}
917
918type PanelOptions = {
919  /** Cells the card may take. */
920  columns: number
921  /** Whether a model turn is running: Resume waits for it. */
922  isWorking: boolean
923  /** What a command just did, shown under the header; null for the panel. */
924  notice: string | null
925}
926
927// The mod's card, drawn above the prompt and as its command's output: its
928// state, a gauge per credit window, its settings, Off / On and Resume.
929async function drawPanel($: Engine, cfg: Config, e: ResolveInput, o: PanelOptions) {
930  const s = await read($, status)
931  await read($, minute)
932  const { reading, isKept } = await readCredit($)
933  const now = await $.clock.now()
934  const back = backOf(cfg, reading?.windows ?? [], now)
935  const canResume = !isWatching(s) && !o.isWorking && back === null
936  const gauges = gaugesOf(cfg, reading?.windows ?? [], o.columns, now)
937  const badge = BADGES[s.phase]
938
939  const ui = $.ui.resolve(e)
940  const { Box, Button, Text } = ui
941  // Raster paints each cell's colors: the terminal's alone (another surface's
942  // table may hold it as a fragment that draws nothing).
943  const Raster = e.surface === 'terminal' && 'Raster' in ui ? ui.Raster : null
944
945  return (
946    <Box flexDirection="column" borderStyle="round" borderColor={CARD_BORDER} paddingX={1}>
947      <Box flexDirection="row" justifyContent="space-between" gap={2}>
948        <Box flexDirection="row" flexShrink={1}>
949          <Box width={ICON_CELLS} flexShrink={0}>
950            <Text color={MOD_COLOR} bold>⏹</Text>
951          </Box>
952          <Box width={LEFT_CELLS - ICON_CELLS} flexShrink={0}>
953            <Text color={MOD_COLOR} bold>{NAME}</Text>
954          </Box>
955          <Text color={badge.fg} backgroundColor={badge.bg} bold>{badgeText(s.phase)}</Text>
956          <Text dimColor wrap="truncate">{` ${phaseDetail(cfg, s, isHalted(s) ? back : null)}`}</Text>
957        </Box>
958        <Box flexDirection="row" flexShrink={0} gap={1}>
959          <Button key="toggle" hotkey="o" onPress={() => toggle($)}>
960            {s.phase === 'off' ? 'On' : 'Off'}
961          </Button>
962          <Button
963            key="resume"
964            hotkey="r"
965            variant={canResume ? 'primary' : 'secondary'}
966            dimColor={!canResume}
967            onPress={() => pressResume($, cfg, o.isWorking)}
968          >
969            Resume
970          </Button>
971        </Box>
972      </Box>
973      {o.notice !== null && (
974        <Text key="notice" wrap="wrap">{`› ${o.notice}`}</Text>
975      )}
976      <Box height={1} />
977      {gauges.map(g => (
978        <Box key={`gauge-${g.name.trim()}`} flexDirection="row">
979          <Box width={ICON_CELLS} flexShrink={0} />
980          <Box width={NAME_CELLS} flexShrink={0} justifyContent="flex-end">
981            <Text bold>{g.name}</Text>
982          </Box>
983          <Box width={LEFT_CELLS - ICON_CELLS - NAME_CELLS} flexShrink={0} />
984          {Raster !== null ? (
985            <Raster key={`bar-${g.name.trim()}`} columns={g.cells.length} rows={1} cells={rasterCells(g.cells)} />
986          ) : (
987            textRuns(g.cells).map((r, i) => (
988              <Text key={`run-${i}`} color={hex(r.fg)} backgroundColor={r.bg === DEFAULT_BG ? undefined : hex(r.bg)}>
989                {r.text}
990              </Text>
991            ))
992          )}
993          <Text color={g.color} bold>{g.percent}</Text>
994          <Text dimColor wrap="truncate">{g.tail}</Text>
995        </Box>
996      ))}
997      {reading === null && (
998        <Text dimColor wrap="truncate">No credit reading yet: it comes with the first answer.</Text>
999      )}
1000      {isKept && reading !== null && (
1001        <Text dimColor wrap="truncate">
1002          {`Last reading ${Number.isNaN(reading.at) ? 'from an earlier session' : `at ${clockOf(reading.at, now)}`}: it refreshes with the first answer.`}
1003        </Text>
1004      )}
1005      {s.memoPath !== null && s.phase !== 'armed' && s.phase !== 'off' && (
1006        <Text dimColor wrap="truncate">{`Memo  ${s.memoPath}`}</Text>
1007      )}
1008    </Box>
1009  )
1010}
1011
1012// `/graceful-stop <args>` and `/gs <args>`.
1013async function runCommand($: Engine, cfg: Config, args: string) {
1014  const arg = args.trim().toLowerCase() || 'status'
1015
1016  if (arg === 'stop') {
1017    const top = peakOf(currentWindows((await $.session.usage()).rateLimits, await $.clock.now()))
1018    await update($, status, s => (s.phase === 'off' ? ARMED : s))
1019    await startStop($, cfg, top, `manual (${describeWindow(top)})`)
1020    const s = await read($, status)
1021
1022    return { text: `Clean stop: ${s.phase}${s.memoPath === null ? '' : `, memo ${s.memoPath}`}.` }
1023  }
1024  if (arg === 'resume') {
1025    return { text: await resume($, cfg) }
1026  }
1027  if (arg === 'on') {
1028    await update($, status, () => ARMED)
1029
1030    return { text: `Re-armed: the clean stop will start at ${thresholdsText(cfg)}.` }
1031  }
1032  if (arg === 'off') {
1033    await update($, status, () => OFF)
1034
1035    return { text: `Off for this session. /${NAME} on to re-arm.` }
1036  }
1037  if (arg !== 'status') {
1038    return { text: `Unknown subcommand "${args.trim()}". Use one of: ${SUBCOMMANDS.join(', ')}.` }
1039  }
1040
1041  return { text: await statusText($, cfg) }
1042}
1043
1044// Counts a subagent's tool call after its warning; the decision rests on the
1045// count the update wrote, so parallel calls neither pass the grace calls nor
1046// warn twice.
1047async function countCall($: Engine, cfg: Config, id: string, trigger: string) {
1048  const seen = { before: undefined as number | undefined }
1049  await update($, status, cur => {
1050    seen.before = cur.warned[id]
1051
1052    return { ...cur, warned: { ...cur.warned, [id]: (cur.warned[id] ?? 0) + 1 } }
1053  })
1054  if (seen.before === undefined) {
1055    await adoptAgent($, id)
1056    await warnAgent($, cfg, id, trigger)
1057  }
1058
1059  return (seen.before ?? 0) < cfg.graceCalls
1060}
1061
1062export const register: Register = (on, options) => {
1063  const cfg = configOf(options)
1064  const isOpen = options.showSettings === true
1065
1066  on('session.start', async ($, e, next) => {
1067    await $.command.register({
1068      name: NAME,
1069      description: 'Wind agents down cleanly before the session credit runs out',
1070      argumentHint: '[status|stop|resume|on|off]',
1071      immediate: true,
1072    })
1073    await $.command.register({
1074      name: ALIAS,
1075      description: `Short for /${NAME}`,
1076      argumentHint: '[status|stop|resume|on|off]',
1077      immediate: true,
1078    })
1079    // A change of the toggle reloads the module: redraw the rows it folds.
1080    $.ui.invalidate('config.describe')
1081    // A reload starts the session over for the module, not for the person.
1082    if (!(await read($, started))) {
1083      await update($, started, () => true)
1084      if (!cfg.armAtStart) await update($, status, s => (s.phase === 'armed' ? OFF : s))
1085    }
1086    if (cfg.invalid.length > 0) {
1087      $.ui.toast(`${NAME}: not a valid value in /config, the default applies: ${cfg.invalid.join(', ')}.`)
1088    }
1089    await tick($)
1090    $.clock.every(60_000, () => void tick($))
1091    // The account's reading, once the start has answered, then each minute.
1092    $.clock.after(1, () => refreshAccount($, cfg))
1093    $.clock.every(ACCOUNT_EVERY_MS, () => void refreshAccount($, cfg))
1094
1095    return next(e)
1096  })
1097
1098  on('config.describe', async ($, e, next) => {
1099    if (!e.key.startsWith(`${NAME}.`)) return next(e)
1100    const row = await next(e)
1101    if (e.key === TOGGLE_KEY) {
1102      return {
1103        ...row,
1104        label: `${isOpen ? '▾' : '▸'} ${NAME}`,
1105        description: isOpen ? `Hide the ${NAME} settings.` : `Show the ${NAME} settings.`,
1106      }
1107    }
1108
1109    return isOpen ? row : { ...row, isHidden: true }
1110  })
1111
1112  on('session.measure', async ($, e, next) => {
1113    if (e.changed.includes('rateLimits') && e.rateLimits.length > 0) {
1114      const at = await $.clock.now()
1115      await update($, credit, () => ({ windows: [...e.rateLimits], at }))
1116      await keepReading($, e.rateLimits, at)
1117    }
1118    await applyReading($, cfg, e.rateLimits, e.cost?.usd)
1119
1120    return next(e)
1121  })
1122
1123  on('turn.start', (_$, e, next) => {
1124    isMainBusy = true
1125
1126    return next(e)
1127  })
1128
1129  on('turn.complete', async ($, e, next) => {
1130    if (e.agentId !== undefined) {
1131      if (isWatching(await read($, status))) {
1132        await recordReport($, e.agentId, e.answer, ENDED[e.reason] ?? e.reason)
1133      }
1134
1135      return next(e)
1136    }
1137    isMainBusy = false
1138    const s = await read($, status)
1139    if (isWatching(s) && (await activeAgents($)).length === 0) await settleMainTurn($, cfg, s)
1140
1141    return next(e)
1142  })
1143
1144  on('turn.step', async function* ($, e, next) {
1145    const s = await read($, status)
1146    if (isHalted(s)) {
1147      const text = await haltMessage($, cfg, s)
1148      yield { kind: 'text' as const, index: 0, text }
1149
1150      return {
1151        turnId: e.turnId,
1152        index: e.index,
1153        answer: text,
1154        toolUses: [],
1155        stopReason: 'end_turn' as const,
1156        usage: null,
1157      }
1158    }
1159
1160    const result = yield* next(e)
1161    if (isWatching(await read($, status))) {
1162      await checkBudget($, cfg, (await $.session.usage()).cost?.usd)
1163    }
1164
1165    return result
1166  })
1167
1168  on('agent.spawn', async ($, e, next) => {
1169    const s = await read($, status)
1170
1171    return s.phase === 'armed' || s.phase === 'off' ? next(e) : { deny: SPAWN_DENIED }
1172  })
1173
1174  on('tool.call', async ($, e, next) => {
1175    const s = await read($, status)
1176    if (e.agentId !== undefined && String(e.tool) === HANDBACK_TOOL) {
1177      const report = handbackText(e)
1178      if (isWatching(s) && report !== null) await recordReport($, e.agentId, report, 'reporting')
1179
1180      return next(e)
1181    }
1182    if (isHalted(s)) return { deny: await haltMessage($, cfg, s) }
1183    if (!isWatching(s) || e.agentId === undefined) return next(e)
1184
1185    const isAllowed = await countCall($, cfg, e.agentId, s.trigger ?? 'threshold reached')
1186
1187    return isAllowed ? next(e) : { deny: AGENT_CUTOFF }
1188  })
1189
1190  for (const command of COMMANDS) {
1191    on('command.run', { command }, async ($, e) => runCommand($, cfg, e.args))
1192  }
1193
1194  // The mod's notes to the orchestrator and its agents: user-role rows.
1195  on('ui.render', { component: 'UserMessage' }, ($, e, next) => {
1196    if (!isModText(e.props.text)) return next(e)
1197    const { Box, Text } = $.ui.resolve(e)
1198
1199    return (
1200      <Box flexDirection="column" borderStyle="round" borderColor={MOD_COLOR} paddingX={1}>
types/index.d.ts 79 lines
1/**
2 * Where the clean stop stands:
3 * - `armed`: watching the credit windows, nothing happens.
4 * - `stopping`: threshold reached, agents warned, no new agent.
5 * - `overage`: past 100 %, the clean stop goes on within the overage budget.
6 * - `stopped`: the clean stop is over, no request leaves anymore.
7 * - `braked`: the overage budget ran out, no request leaves anymore.
8 * - `off`: the mod is off for this session (turned off, or not armed at start).
9 */
10export type GracefulStopPhase = 'armed' | 'stopping' | 'overage' | 'stopped' | 'braked' | 'off'
11
12/** A subagent the clean stop is waiting on, as it was when first seen. */
13export type GracefulStopAgent = {
14  id: string
15  description: string
16  type: string
17  /** Its last known status (AgentStatus), refreshed as the stop goes on. */
18  status: string
19  /** Its final answer, the status report, once its run ended. */
20  report: string | null
21}
22
23export type GracefulStopStatus = {
24  phase: GracefulStopPhase
25  /** What triggered the stop, e.g. "five_hour 90 %" or "manuel". */
26  trigger: string | null
27  /** When the credit window that triggered resets, ISO 8601. */
28  resetsAt: string | null
29  /** The session's cost when the windows passed 100 %, in USD. */
30  baselineUsd: number | null
31  /** Estimated overage spent since then, in USD. */
32  spentUsd: number
33  /** Subagents warned, by id: tool calls each made since its warning. */
34  warned: Record<string, number>
35  /** The resume memo's absolute path, once the stop wrote one. */
36  memoPath: string | null
37  /** Every subagent the stop covers, kept even once it finished. */
38  agents: GracefulStopAgent[]
39  /** Main turns ended with every agent done but the memo still provisional. */
40  idleTurns: number
41  /**
42   * A hash of the provisional memo the mod last wrote: any other content is
43   * the orchestrator's. Absent from a status kept by an older version.
44   */
45  fallbackHash?: number | null
46}
47
48/** A credit window as the engine reports it (SessionRateLimit). */
49export type GracefulStopWindow = {
50  /** `five_hour`, `seven_day`, or a gateway's `spend_limit`. */
51  kind: string
52  percentUsed: number
53  /** When the window resets, ISO 8601. */
54  resetsAt?: string
55}
56
57/** The session's last credit reading, as the band draws it. */
58export type GracefulStopCredit = {
59  windows: GracefulStopWindow[]
60  /** When it was read, in ms since the epoch. */
61  at: number
62}
63
64declare module 'claude-code' {
65  interface PluginState {
66    'graceful-stop': {
67      status: GracefulStopStatus
68      /** The last reading of this session; null before its first request. */
69      credit: GracefulStopCredit | null
70      /** The account's last reading, from Claude Code's usage endpoint; null before one came. */
71      account: GracefulStopCredit | null
72      /** The current minute, ticked so the band's reset countdowns move. */
73      minute: number
74      /** Whether this session's start was seen: a reload must not disarm it again. */
75      started: boolean
76    }
77  }
78}
79