SLOPSHOPPER

auto-resume

When a turn dies on a rate limit (or an overloaded API), counts down to the reset and sends "continue" for you.

newbandcommandtoaststatusprompt
★ 1v0.1.0no licenseupdated 2026-10-04seanrobertwright/claude-mods/mods/auto-resume
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · auto-resume
› 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 › /auto-resume ⎿ auto-resume: Auto-resume is idle; it arms itself when a turn hits a rate limit. ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts
README

🧩 claude-mods

Small TypeScript mods that live inside Claude Code: a pane that knows your next step, one-click replies, a rate-limit countdown that resumes for you, your repo's pull requests and issues beside the conversation, a shelf of paths you use every day, presets that switch the model and the effort with one press, a chime when a long turn ends, a guard for the Office file you left open, a question before a commit or push on the default branch, a question before Claude reads a .env or key file, a list of the files this session made, a list of the ones it read, a check that keeps banned claims out of a pull request, a gate that runs your checks and hands back only the failures, a nudge to fetch fresh tab IDs when a browser tab is gone, a name for the session from its first prompt, and one dialog for every mod's settings.

Claude Code 2.1.289+ 20 mods TypeScript strict Checks: tsc, ESLint, validate, test

claude-mods is one developer's personal toolbox of Claude Code mods, shared as a plugin marketplace so anyone can install them. The mods are built for the author's own workflow first, and you are a welcome guest: install one, install all twenty, or read the source and write your own.

What is a mod?

A mod is a plugin of function hooks: TypeScript that runs inside Claude Code and changes what it shows (a pane in the side panel, a band of buttons above the prompt, the status line) or what it does between turns. The mod's own code decides when to act, even when what it does is send the model a prompt.

Runs asWho decides when it acts
ModTypeScript function hooks inside Claude CodeThe mod's own code
SkillInstructions the model readsThe model
Plain pluginCommands, agents or shell hooksYou, or a shell script

The mods

ModWhere it showsWhat it does
🧭 whats-nextPane in the side panelLists the next steps of your workflow, each with a prompt ready to paste
⚡ quick-replyBand above the promptOne-click replies, including the options Claude just offered, Pass, Fail and Skip for a verdict, and the next wayfinder ticket
⏳ auto-resumeBand and status lineCounts down to a rate limit's reset, then sends "continue"
🐙 github-panelPane in the side panelThe repo's open pull requests and issues, one click from the browser or from /implement and /wayfinder in the prompt; the issue a /wayfinder run works on, pinned with its next ticket; a toast when your branch's checks turn green or red
📚 shelfBand above the promptNamed folders and files; one click drops a path into what you are typing
🔔 turn-chimeSound and toastTells you when a long turn ends or Claude stops to ask you something
🔒 open-file-guardQuestion dialogAsks you to close a Word, Excel or PowerPoint file before Claude uses it
🌿 branch-guardQuestion dialogAsks you before Claude commits or pushes on the default branch
🔑 env-guardQuestion dialogAsks you before Claude reads a .env or key file, and refuses when no one is there to answer
🩹 bash-quoting-rescueRefused tool callStops a shell command that does not parse, such as an unclosed quote, before any of it runs
📂 outputsPane in the side panelThe files this session made or changed, newest first; click one to open it
🔎 sourcesPane in the side panelThe files Claude read, grouped by where they came from, with a lock to the project folder
📊 hudTwo lines under the promptModel, effort, context window, rate limits, turn timer, tool calls, agents, git state, worktree, cost, session length and folder, each named and in colour
🧹 post-merge-cleanupQuestion dialog and toastAfter a PR merges, /cleanup switches to the default branch, pulls and deletes the branch
🧾 pre-pr-claims-checkRefusal Claude readsRefuses gh pr create and gh pr edit while the pull request cites a file and line, holds a placeholder, or spells out a count
🚦 lint-test-gateBand above the promptRuns your checks on a press and before Claude's git commit, and hands back only the failures
🔄 chrome-tab-self-healNote after a browser tool's errorWhen a Claude in Chrome tab is gone, tells Claude to fetch the current tab IDs before it tries again
🏷 session-auto-namerBand above the promptSuggests a name for the session from its first prompt; one press renames it
🧠 model-effort-presetsBand above the promptPlan and execute presets: one press switches the model and the effort together
⚙ mod-settingsGear on each pane; a dialogChange and save any mod's settings without leaving the session

When more than one mod has a pane open, Claude Code shows them as tabs in the side panel.

🧭 whats-next

A pane listing the next steps of your workflow for the project folder, kept between sessions. A skill of your choosing answers "what's next" in a headless run beside your session, and the mod turns the answer into steps.

What's next                        refresh
updated 3 min ago

Fix the failing parse test
working on it  done
The check is red, so nothing else can merge.

Open a pull request for the fix
Review comes before the next feature starts.

Triage the two new issues
They arrived while you were heads-down.
flowchart LR
    A[Skill answers<br/>what's next] --> B[Steps in the pane]
    B --> C[You read a step's prompt<br/>and send it yourself]
    C --> D[Step glows:<br/>working on it]
    D --> E{Laya, Jev or Haiku:<br/>is the step finished?}
    E -- not yet --> D
    E -- yes --> F[Step leaves the list]
  • You stay in charge. A step's prompt reaches the model only when you read it and send it yourself. Click a step to see its prompt, then paste it, paste it into a fresh session (after your prime command, if you name one), or copy it.
  • It notices when you are done. After each answered turn, a System One model is asked whether the step is finished, as your System One models setting allows, and Haiku when none answers surely enough. A finished step leaves the list. Press d to drop it yourself.
  • The run that asks is read-only. By default it gets only read commands of git and gh plus Read, Glob and Grep. git push, git config, git -c, gh api and --output are always denied.
Command or keyWhat it does
/whats-nextBring the pane to the front
/whats-next refreshAsk the skill again
rRefresh
1 to 9Show that step's prompt in the pane
p, n, cPaste the shown prompt, paste it after /clear (and the prime command, once its turn ends), or copy it
bBack to the list
dMark the active step done
SettingKeyDefaultMeaning
Skillskill/ask-seanThe skill that answers "what's next", written as you would run it: / followed by letters, digits, _, :, . or -
Most stepsmaxSteps5How many steps to ask for (1-9)
Refresh on startrefreshOnStartonAsk for a fresh list when a session starts in a git repository
Tools the headless run may useallowedToolsempty: the read-only setComma-separated permission rules for the headless run
Modelmodelempty: your defaultModel for the headless run, as an alias (haiku) or a full id
Prime commandprimeCommandempty: noneA slash command, with any arguments, run after /clear and before the paste (/lril:prime); the prompt is filled once the turn it starts ends, finished or not. A value that is not one slash command on one line is never run, and the step view says so
System One modelsmodelChoicelocal onlyWhich System One model judges whether a turn finished the active step: local only (Laya on this machine, or Haiku as before), local first (Laya, and TypeSafe's hosted Jev while Laya is unavailable) or hosted first (Jev, and Laya while Jev is unavailable)
Jev API keyjevApiKeyemptyYour key for Jev, from console.typesafe.ai, kept in secure storage. Sent only to https://api.typesafe.ai, and only while System One models allows Jev
Laya portlayaPort8000The port your laya-serve listens on at 127.0.0.1 (1-65535)

/ask-sean is the author's own skill, so point the Skill setting at a skill of yours that answers "what should I do next?" (how to set it):

echo '{"skill": "/next-steps", "maxSteps": "3", "model": "haiku"}' | claude plugin configure whats-next@claude-mods --values-stdin

The read-only set, used while Tools is empty, is Bash(git status:*), Bash(git log:*), Bash(git diff:*), Bash(git show:*), Bash(git rev-parse:*), Bash(git branch --show-current), Bash(git branch -vv), Bash(git remote -v), Bash(gh issue list:*), Bash(gh issue view:*), Bash(gh pr list:*), Bash(gh pr view:*), Bash(gh pr checks:*), Bash(gh run list:*), Read, Glob and Grep.

  • A list you write replaces that set; it does not add to it. To widen the set, write all of it plus your additions.
  • Each rule is a tool name, optionally followed by (...). One rule that is not, such as one starting with -, discards your whole list and the read-only set is used.
  • The run can always call Skill, so a skill that calls another still works. MCP servers load only when a rule names an mcp__ tool.

What the judge sends to a System One model, once after each answered turn while a step is active:

  • To Jev, only while System One models allows it and the folder is not marked local-only: the active step's title, reason and prompt and the last 8,000 characters of Claude's answer. Never the contents of a file the mod read itself.
  • To Laya, which keeps it on this machine: the same, fitted to Laya's small window. The step's prompt is dropped first, then the start of the answer, so the end of the answer, where Claude says whether the work is done, is kept.
  • Sure answers only. "Done" counts at a probability of 0.9 or more and "not done" at 0.1 or less. Anything between, a model that is busy or fails, or no answer within 5 s leaves the step to Haiku, as before.
  • A key it cannot use is named. While System One models allows Jev, a missing key, one that is not a key, or one TypeSafe rejects is named on a line in the pane, and the list stays. A rejected key stays off until the mod reloads.
  • A changed key takes effect once the mod reloads. Saving it in the settings dialog reloads the mod; a key changed any other way waits for the next start of Claude Code.

Needs: the claude CLI on the PATH, and the skill named in the Skill setting. Laya and a Jev key are optional: with neither, the judge is Haiku, as before.

⚡ quick-reply

One row of buttons above the prompt after each answer. When Claude ends on a question, the band offers the choices Claude asked you to pick from, then your replies to a question. After any other answer it offers your other replies. You set both lists in the settings below.

Reply:  [a: Keep the copies]  [b: Add a sync script]  [Yes]  [Go with your recommendation]  [No]
  • A choice's button sends its marker with its label, so the model cannot misread it.
  • A numbered report before a yes-or-no question ("Shall I commit?") is not offered as choices.
  • When the answer recommends something, the "recommend" reply is the highlighted one. Advice against something does not count.
  • The band stays out of the way while Claude is working, and after a subagent's turn.
  • A model can read the ending too. After each answered turn, a System One model is asked how the answer ends, as your System One models setting allows: whether it asks you something, whether its numbered items are choices, and which one it recommends. The band shows its own reading at once, and a sure answer that arrives within 2 s takes its place, so a numbered report closed by "push now or wait?" is not offered as choices.

Verdicts. When Claude asks for a pass/fail verdict on a test or a check, as a UAT or /gsd:verify-work step does ("Pass or fail?", "Did it pass?", "Type pass or describe what's wrong"), the band offers a verdict in place of your replies:

Reply:  [Pass]  [Fail…]  [Skip]

Pass sends "pass" and Skip sends "skip", as your own message. Fail… sends nothing: it puts "Fail: " in the prompt, where you say what went wrong and can paste a screenshot. A test's numbered steps are not offered as choices, and a question that only mentions passing ("Shall I make the tests pass?") gets your usual replies.

Next ticket. When you work a map with the wayfinder skill, the band leads with the next ticket after each turn that closes one or charts the map:

Reply:  [Next ticket: /wayfinder 135]  [Continue]  [Commit and push]

One press runs /clear and then /wayfinder 135, the loop you would otherwise type. It is offered only in a session that ran the wayfinder skill, after a turn whose gh issue close worked; after charting it names the map the turn created. A close made some other way (gh api, the web) is not seen, so no button shows, and once a turn closes the map itself the loop ends.

SettingKeyDefaultMeaning
Replies to a questionquestionReplies`Yes\Go with your recommendation\No`Shown after Claude asks something, separated by `\`; empty shows only the choices Claude offered
Replies otherwiseidleReplies`Continue\Commit and push`Shown after any other answer; empty hides the band then, except for Next ticket
Offer the next wayfinder ticketwayfinderNexttrueAfter a wayfinder turn closes a ticket or charts a map, offer Next ticket
System One modelsmodelChoicelocal onlyWhich System One model reads how each answer ends: local only (Laya on this machine, or the band's own reading as before), local first (Laya, and TypeSafe's hosted Jev while Laya is unavailable) or hosted first (Jev, and Laya while Jev is unavailable)
Jev API keyjevApiKeyemptyYour key for Jev, from console.typesafe.ai, kept in secure storage. Sent only to https://api.typesafe.ai, and only while System One models allows Jev
Laya portlayaPort8000The port your laya-serve listens on at 127.0.0.1 (1-65535)

Each list holds up to six replies. A reply longer than 120 characters is cut short, and a repeat is dropped. For example, to answer questions with your own three replies and hide the band after other answers (how to set it):

echo '{"questionReplies": "Yes|No|Explain that first", "idleReplies": ""}' | claude plugin configure quick-reply@claude-mods --values-stdin

What the band sends to a System One model, once after each answered turn:

  • To Jev, only while System One models allows it and the folder is not marked local-only: the last 8,000 characters of Claude's answer and the labels of the choices found in it. Never the contents of a file the mod read itself.
  • To Laya, which keeps it on this machine: the answer's closing lines that fit Laya's small window, where the question is, and at most 9 labels of at most 40 characters.
  • Sure answers only. Each part of the reading counts only when the model is sure of it, at 0.9 or more (0.1 or less for "these are not choices"). Anything less, a model that is busy or fails, a reading Laya reports as cut, or no answer within 2 s leaves the band's own reading. So does a reading that arrives after your next prompt.
  • A key it cannot use is named. While System One models allows Jev, a missing key, one that is not a key, or one TypeSafe rejects is named on a dim line under the replies, until your next prompt. A rejected key stays off until the mod reloads.

Laya and a Jev key are optional: with neither, the band reads each answer as before.

⏳ auto-resume

When a turn dies on a rate limit or an overloaded API, auto-resume counts down to the reset and sends "continue" for you. Go to lunch, and come back to finished work.

⏳ rate limited:  sending "continue" in 1 h 12 min  [Resume now]  [Cancel]
  • The countdown shows above the prompt and in the status line.
  • Send a prompt of your own and it steps aside: you took over.
  • It gives up after too many resumes in a row without a successful answer.
CommandWhat it does
/auto-resumeSay what is waiting, if anything
/auto-resume nowSend the resume now
/auto-resume cancelCancel the wait
/auto-resume in <minutes>Schedule a resume yourself (1 to 1440)
SettingKeyDefaultMeaning
Resume prompttextcontinueWhat is sent when the wait is over; empty sends continue
Grace after reset (s)graceSeconds60Extra seconds to wait past the limit's reset time (0-900)
Retry overloaded/server errorsretryOverloadedonAlso resume after an overloaded or server error, backing off from one minute
Most retries in a rowmaxRetries5Give up after this many resumes without a successful answer (1-20)

For example, to send a longer prompt and wait two minutes past the reset (how to set it):

echo '{"text": "continue where you left off", "graceSeconds": "120"}' | claude plugin configure auto-resume@claude-mods --values-stdin

🐙 github-panel

A GitHub pane beside What's next listing the repo's open pull requests and issues. Click one to open it in the browser. Under each issue, implement and wayfinder put /implement or /wayfinder and the issue's URL in the prompt. Nothing is sent. While a /wayfinder effort is under way, its issue is pinned at the top, with the next ticket to take.

octocat/hello-world                refresh
updated just now

Decide how shared code is copied unpin
3 done · 1 takeable · 1 claimed · 2 blocked
next: Pick the drift check decision
work next

Pull requests 2                        all
#41 Add a drift check for copied guards
  draft · @octocat
#40 Bring the asked pane to the front
  ✗ checks failing · @hubot           fix

Issues 2                               all
#39 Share the headless-session check
  blocked by #12 · ready… implement wayfinder
#12 Decide how shared code is copied
  needs-triage · @hubot implement wayfinder
  • An issue blocked by an open issue has a red line under it. Hover it to see what blocks it.
  • In a narrow pane the implement and wayfinder buttons take a line of their own.
  • The lists refresh on a timer, after a turn once they are a minute old, and on r.
  • The pull request of the branch you are on is watched: when its checks turn green or red, a toast says "Checks passed on #40" or "Checks failed on #40". The first refresh, and the first after you switch branch, only notes where the checks stand.
  • While that pull request's checks fail, its row has a fix button. It fills the prompt box with the failed checks' names, the last 40 lines of the failed run's log, and "Fix it." Nothing is sent: you read it and send it yourself. The log is fetched only when you press fix; when gh cannot fetch it, such as while the run is still going, the prompt holds the names alone.
  • Running /wayfinder on an issue of this repo (/wayfinder 12, /wayfinder #12 or the issue's URL) pins that issue and brings the pane to the front. Anything else, such as prose or another repo's issue, pins nothing. The pin is kept for the repo across sessions, one at a time: a run on another issue replaces it. It goes when you press unpin, or once the issue is closed.
  • The pinned issue's sub-issues are its tickets, each counted once: closed ones are done, open ones with an open blocker are blocked, assigned ones are claimed, and the rest are takeable. next is the first takeable ticket in the order the issue lists its sub-issues, with its wayfinder: type label; click it to open it on GitHub. With nothing takeable it says so; an issue with no sub-issues yet says no tickets yet.
  • work next fills /wayfinder and the pinned issue's URL into the prompt, without sending it, so the skill takes the frontier ticket fresh when it runs.
  • The pinned issue is read in the same refresh as the lists. When a refresh fails, the last section stays and the error shows.
Command or keyWhat it does
/githubBring the pane to the front and refresh it
rRefresh
allOpen the whole list on GitHub
implement, wayfinderFill the command and the issue's URL into the prompt, without sending it
fixFill a request to fix the current branch's failing checks into the prompt box
unpinDrop the pinned issue
work nextFill /wayfinder and the pinned issue's URL into the prompt, without sending it
SettingKeyDefaultMeaning
Most items per listlimit30How many open pull requests and issues to list each (1-100)
Refresh every (minutes)refreshMinutes5How often to refresh (0-120); 0 refreshes only on open, after turns and on r
Implement button fillsimplementCommand/implementThe slash command the implement button fills before the issue's URL; empty hides the button
Wayfinder button fillswayfinderCommand/wayfinderThe slash command the wayfinder and work next buttons fill before the issue's URL, and the skill whose runs pin an issue; empty hides the button and turns pinning off

A command must start with / and hold no spaces. Any other value falls back to the default, and a message says so when the session starts. A button is labelled with its command, without the /.

For example, to list fifty of each and stop the timer (how to set it):

echo '{"limit": "50", "refreshMinutes": "0"}' | claude plugin configure github-panel@claude-mods --values-stdin

Needs: the GitHub CLI, logged in, and a folder with a GitHub remote.

📚 shelf

A row of named folders and files above the prompt, for the paths you type again and again. Click a name and its path lands at the cursor in what you are typing. Nothing is sent.

Shelf:  [brand]  [records]  [kb]
  • A path with a space arrives in double quotes, ready to use.
  • The shelf is the same in every project folder and every session.
  • When the names do not fit one row, the band shows those that do and counts the rest; /shelf always lists them all.
CommandWhat it does
/shelfList the shelf with each path
/shelf add <name> [path]Put a path on the shelf; with no path, the project folder
/shelf remove <name>Take one off

The shelf has no settings: you fill it with /shelf add.

/shelf add brand "N:/Marketing/Brand Kit"
/shelf add records N:/RECORDS
/shelf add kb
/shelf remove brand
  • A name is one word of up to 24 characters. Adding a name already on the shelf, whatever its capitals, replaces that entry where it stands.
  • The path is k
Source 3 files
hooks/register.tsx 204 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, Timer } from 'claude-code'
3
4import type { Pending } from '../types'
5import { formatWait, parseConfig, parseMinutes, planResume } from './plan'
6import type { Config } from './plan'
7
8const TICK = 30_000
9
10const pending = atom({ plugin: 'auto-resume', key: 'pending' } as const, null)
11const attempts = atom({ plugin: 'auto-resume', key: 'attempts' } as const, 0)
12const now = atom({ plugin: 'auto-resume', key: 'now' } as const, 0)
13
14// Timers die with the module on a reload; session.start re-arms from $.state.
15let fire: Timer | undefined
16let tick: Timer | undefined
17// Counts attaches, so a surfaces check answered before an attach cannot stop
18// the countdown that attach kept going.
19let attaches = 0
20
21function report($: EngineInterface): (error: unknown) => void {
22  return error => $.ui.toast(`auto-resume: ${error instanceof Error ? error.message : String(error)}`)
23}
24
25/**
26 * Whether any surface shows the session right now. Asked before arming a
27 * resume and before each countdown tick, and never kept: a reload or a missed
28 * attach would leave a kept flag wrong. The resume itself is not gated on it:
29 * it was set going while the session was shown. Each mod carries its own copy
30 * (ADR-0001).
31 */
32async function isShown($: EngineInterface): Promise<boolean> {
33  return (await $.session.surfaces()).length > 0
34}
35
36function stopTick(): void {
37  tick?.cancel()
38  tick = undefined
39}
40
41function stopTimers(): void {
42  fire?.cancel()
43  fire = undefined
44  stopTick()
45}
46
47/** Ticks the countdown; a tick that finds no surface stops it until the next attach. */
48async function startTick($: EngineInterface, config: Config): Promise<void> {
49  stopTick()
50  const own = $.clock.every(TICK, () => {
51    void (async () => {
52      const seen = attaches
53      if (await isShown($)) await showStatus($, config)
54      else if (tick === own && attaches === seen) stopTick()
55    })().catch(report($))
56  })
57  tick = own
58  await showStatus($, config)
59}
60
61async function showStatus($: EngineInterface, config: Config): Promise<void> {
62  const at = await $.clock.now()
63  await update($, now, () => at)
64  const waiting = await read($, pending)
65  $.ui.status(waiting === null ? undefined : `⏳ "${config.text}" in ${formatWait(waiting.resumeAt - at)}`)
66}
67
68async function disarm($: EngineInterface): Promise<void> {
69  stopTimers()
70  await update($, pending, () => null)
71  $.ui.status(undefined)
72}
73
74/** Sends the resume once: the timer and a press racing it both get here, and only the one that takes `pending` sends. */
75async function resume($: EngineInterface, config: Config): Promise<void> {
76  let isTaken = false
77  await update($, pending, current => {
78    isTaken = current !== null
79    return null
80  })
81  if (!isTaken) return
82  await disarm($)
83  await update($, attempts, count => count + 1)
84  await $.prompt.submit({ text: config.text, asUser: true })
85}
86
87/**
88 * Sets the resume going at `plan.resumeAt`. It is sent then whether or not a
89 * surface still shows the session; the countdown ticks only while one does.
90 */
91async function arm($: EngineInterface, config: Config, plan: Pending): Promise<void> {
92  stopTimers()
93  await update($, pending, () => plan)
94  const wait = Math.max(0, plan.resumeAt - (await $.clock.now()))
95  fire = $.clock.after(wait, () => void resume($, config).catch(report($)))
96  if (await isShown($)) await startTick($, config)
97}
98
99export const register: Register = (on, options) => {
100  const config = parseConfig(options)
101
102  on('session.start', async ($, e, next) => {
103    await $.command.register({
104      name: 'auto-resume',
105      description: "Rate-limit auto-resume: '/auto-resume' for status, 'now', 'cancel', or 'in <minutes>'",
106    })
107    // A resume armed before a reload was set going while the session was shown:
108    // it is still sent, with or without a surface now.
109    const waiting = await read($, pending)
110    if (waiting !== null) await arm($, config, waiting)
111    return next(e)
112  })
113
114  // A surface joining brings the countdown up to date, and restarts it if it had stopped.
115  on('session.attach', async ($, e, next) => {
116    attaches += 1
117    const done = await next(e)
118    if ((await read($, pending)) === null) return done
119    if (tick === undefined) await startTick($, config)
120    else await showStatus($, config)
121    return done
122  })
123
124  on('session.detach', async ($, e, next) => {
125    const seen = attaches
126    const done = await next(e)
127    if (!(await isShown($)) && attaches === seen) stopTick()
128    return done
129  })
130
131  on('prompt.submit', async ($, e, next) => {
132    // The person, or the SDK host driving the session, sent a prompt of its own: it has taken over.
133    const isTakeOver = e.origin.kind === 'composer' || e.origin.kind === 'bridge' || e.origin.kind === 'sdk'
134    if (isTakeOver && (await read($, pending)) !== null) {
135      await disarm($)
136      $.ui.toast('Auto-resume cancelled: you took over.')
137    }
138    return next(e)
139  })
140
141  on('turn.complete', async ($, e, next) => {
142    const done = await next(e)
143    if (e.agentId === undefined && e.reason === 'answer') await update($, attempts, () => 0)
144    return done
145  })
146
147  on('classic.StopFailure', async ($, e, next) => {
148    const done = await next(e)
149    // Nobody is waiting on a headless session: arm nothing, say nothing.
150    if (!(await isShown($))) return done
151    const at = await $.clock.now()
152    const { rateLimits } = await $.session.usage()
153    const plan = planResume({ error: e.error, rateLimits, now: at, attempts: await read($, attempts), config })
154    if (plan === undefined) {
155      if (e.error === 'rate_limit') $.ui.toast('Auto-resume gave up: too many retries in a row.')
156      return done
157    }
158    await arm($, config, plan)
159    $.ui.toast(`${plan.reason}: sending "${config.text}" in ${formatWait(plan.resumeAt - at)}.`)
160    return done
161  })
162
163  on('command.run', { command: 'auto-resume' }, async ($, e) => {
164    const [verb = '', amount = ''] = e.args.trim().split(/\s+/)
165    if (verb === 'now') {
166      if ((await read($, pending)) === null) return { text: 'Nothing is waiting to resume.' }
167      void resume($, config).catch(report($))
168      return { text: `Sending "${config.text}" now.` }
169    }
170    if (verb === 'cancel') {
171      await disarm($)
172      return { text: 'Auto-resume cancelled.' }
173    }
174    if (verb === 'in') {
175      const minutes = parseMinutes(amount)
176      if (minutes === undefined) return { text: 'Usage: /auto-resume in <minutes>, 1 to 1440.' }
177      await arm($, config, { resumeAt: (await $.clock.now()) + minutes * 60_000, reason: 'scheduled by you' })
178      return { text: `Will send "${config.text}" in ${formatWait(minutes * 60_000)}.` }
179    }
180    if (verb !== '') return { text: 'Usage: /auto-resume [now | cancel | in <minutes>]' }
181    const waiting = await read($, pending)
182    if (waiting === null) return { text: 'Auto-resume is idle; it arms itself when a turn hits a rate limit.' }
183    return { text: `${waiting.reason}: sending "${config.text}" in ${formatWait(waiting.resumeAt - (await $.clock.now()))}.` }
184  })
185
186  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
187    const waiting = await read($, pending)
188    if (waiting === null || e.props.hasSurvey || e.props.view.agentId !== undefined) return next(e)
189    const at = await read($, now)
190    const { Box, Text, Button } = $.ui.resolve(e)
191
192    return (
193      <Box flexDirection="row" flexWrap="wrap" columnGap={1} width={e.props.bodyColumns}>
194        <Text color="yellow">{'⏳'} {waiting.reason}:</Text>
195        <Text>
196          sending "{config.text}" in {formatWait(waiting.resumeAt - at)}
197        </Text>
198        <Button key="now" variant="primary" label="Resume now" onPress={() => void resume($, config).catch(report($))} />
199        <Button key="cancel" label="Cancel" onPress={() => void disarm($).catch(report($))} />
200      </Box>
201    )
202  })
203}
204
hooks/plan.ts 109 lines
1import type { SessionRateLimit } from 'claude-code'
2
3import type { Pending } from '../types'
4
5const MINUTE = 60_000
6const MAX_BACKOFF = 15 * MINUTE
7/** Never resume sooner than this after a failure, whatever a window says. */
8const FLOOR = 30_000
9
10export type Config = {
11  text: string
12  graceMs: number
13  retryOverloaded: boolean
14  maxRetries: number
15}
16
17/** Parses the manifest's userConfig values; a value out of range falls back to its default. */
18export function parseConfig(options: Readonly<Record<string, unknown>>): Config {
19  const text = typeof options.text === 'string' ? options.text.replace(/\p{Cc}/gu, ' ').trim() : ''
20  const grace = options.graceSeconds
21  const retries = options.maxRetries
22  return {
23    text: text === '' ? 'continue' : text,
24    graceMs: typeof grace === 'number' && Number.isFinite(grace) && grace >= 0 && grace <= 900 ? grace * 1000 : MINUTE,
25    retryOverloaded: typeof options.retryOverloaded === 'boolean' ? options.retryOverloaded : true,
26    maxRetries: typeof retries === 'number' && Number.isInteger(retries) && retries >= 1 && retries <= 20 ? retries : 5,
27  }
28}
29
30/**
31 * The mod's one date helper: an ISO 8601 instant to milliseconds since the
32 * epoch. A string without a zone (`Z` or an offset) is refused rather than
33 * read as local time.
34 */
35export function instantMs(iso: string): number | undefined {
36  if (!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:?\d{2})$/.test(iso)) return undefined
37  const ms = Date.parse(iso)
38  return Number.isFinite(ms) ? ms : undefined
39}
40
41const WINDOW_NAMES: Readonly<Record<string, string>> = {
42  five_hour: '5-hour',
43  seven_day: 'weekly',
44  spend_limit: 'spend',
45}
46
47function windowName(kind: string): string {
48  return Object.hasOwn(WINDOW_NAMES, kind) ? (WINDOW_NAMES[kind] ?? kind) : kind.replace(/_/g, ' ')
49}
50
51/**
52 * When to resume after a turn died on `error`: at the latest reset of an
53 * exhausted rate-limit window plus the grace, or else on a backoff of one
54 * minute doubling to fifteen. Undefined when the error is not worth waiting
55 * out or the retries are spent.
56 */
57export function planResume(input: {
58  error: string
59  rateLimits: readonly SessionRateLimit[]
60  now: number
61  attempts: number
62  config: Config
63}): Pending | undefined {
64  const { error, rateLimits, now, attempts, config } = input
65  if (attempts >= config.maxRetries) return undefined
66  const isRateLimit = error === 'rate_limit'
67  const isTransient = error === 'overloaded' || error === 'server_error'
68  if (!isRateLimit && !(isTransient && config.retryOverloaded)) return undefined
69
70  if (isRateLimit) {
71    let latest: { at: number; kind: string } | undefined
72    for (const window of rateLimits) {
73      const at = window.resetsAt === undefined ? undefined : instantMs(window.resetsAt)
74      if (window.percentUsed < 100 || at === undefined) continue
75      if (latest === undefined || at > latest.at) latest = { at, kind: window.kind }
76    }
77    if (latest !== undefined) {
78      return {
79        resumeAt: Math.max(latest.at + config.graceMs, now + FLOOR),
80        reason: `${windowName(latest.kind)} limit reached`,
81      }
82    }
83  }
84
85  const backoff = Math.min(MINUTE * 2 ** attempts, MAX_BACKOFF)
86  return {
87    resumeAt: now + backoff,
88    reason: isRateLimit ? 'rate limited' : error === 'overloaded' ? 'API overloaded' : 'API server error',
89  }
90}
91
92/** A wait as people say it: `45 s`, `12 min`, `1 h 12 min`. */
93export function formatWait(ms: number): string {
94  const seconds = Math.max(0, Math.ceil(ms / 1000))
95  if (seconds < 60) return `${seconds} s`
96  const minutes = Math.ceil(seconds / 60)
97  if (minutes < 60) return `${minutes} min`
98  const hours = Math.floor(minutes / 60)
99  const rest = minutes % 60
100  return rest === 0 ? `${hours} h` : `${hours} h ${rest} min`
101}
102
103/** `/auto-resume in <minutes>`: a whole number of minutes from 1 to 1440, else undefined. */
104export function parseMinutes(text: string): number | undefined {
105  if (!/^\d{1,4}$/.test(text)) return undefined
106  const minutes = Number.parseInt(text, 10)
107  return minutes >= 1 && minutes <= 1440 ? minutes : undefined
108}
109
types/index.d.ts 20 lines
1/** A resume waiting on the clock. */
2export type Pending = {
3  /** Milliseconds since the epoch at which the resume prompt is sent. */
4  resumeAt: number
5  /** Why it waits, as the band and status line say it. */
6  reason: string
7}
8
9declare module 'claude-code' {
10  interface PluginState {
11    'auto-resume': {
12      pending: Pending | null
13      /** Resumes sent since the last successful answer. */
14      attempts: number
15      /** The clock as of the last tick, so the countdown redraws. */
16      now: number
17    }
18  }
19}
20