SLOPSHOPPER

modpack

The claude-mods modpack: statusline, smart-compact, delegate, cells, eta, seek and draft, installed together and built to work together, and route, an optional…

panecommandprocessnetworktimer
v0.9.3MITupdated 2026-10-19HarzerHeribert/claude-modpack/modpack
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · modpack
│ ┃ Mods ✕ › fix the failing auth test and add an audit log call │ ┃ ╭──────────────────────────────────────────╮ │ ┃ │ statusline not installed │ ⏺ Read(src/auth.ts) │ ┃ │ one line under the prompt: model, │ ⎿ Read 6 lines │ ┃ │ context, plan use │ ⏺ Update(src/auth.ts) │ ┃ │ /plugin install statusline --marketplace │ ⎿ Added 2 lines, removed 1 line │ ┃ │ HarzerHeribert/claude-modpack │ ⏺ Bash(bun test) │ ┃ ╰──────────────────────────────────────────╯ ⎿ 3 pass, 1 fail │ ┃ ╭──────────────────────────────────────────╮ │ ┃ │ smart-compact not installed │ ● Done. refresh now rejects expired claims and logs an audit event. │ ┃ │ keeps the prompt cache warm or compacts │ │ ┃ │ before it expires │ ✻ Worked for 42s · done 4:20 PM │ ┃ │ /plugin install smart-compact │ │ ┃ │ --marketplace │ › /update │ ┃ │ HarzerHeribert/claude-modpack │ │ ┃ ╰──────────────────────────────────────────╯ │ ┃ ╭──────────────────────────────────────────╮ │ ┃ │ delegate not installed │ │ ┃ │ hands a task to a cheaper worker model │ │ ┃ │ and checks its work │ │ ┃ │ /plugin install delegate --marketplace │ │ ┃ │ HarzerHeribert/claude-modpack │ │ ┃ ╰──────────────────────────────────────────╯ │ ┃ ╭──────────────────────────────────────────╮ │ ┃ │ cells not installed │ │ ┃ │ several edits and their check in one │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · Mods
╭──────────────────────────────────────────────────────────╮ │ statusline not installed │ │ one line under the prompt: model, context, plan use │ │ /plugin install statusline --marketplace │ │ HarzerHeribert/claude-modpack │ ╰──────────────────────────────────────────────────────────╯ ╭──────────────────────────────────────────────────────────╮ │ smart-compact not installed │ │ keeps the prompt cache warm or compacts before it │ │ expires │ │ /plugin install smart-compact --marketplace │ │ HarzerHeribert/claude-modpack │ ╰──────────────────────────────────────────────────────────╯ ╭──────────────────────────────────────────────────────────╮ │ delegate not installed │ │ hands a task to a cheaper worker model and checks its │ │ work │ │ /plugin install delegate --marketplace │ │ HarzerHeribert/claude-modpack │ ╰──────────────────────────────────────────────────────────╯ ╭──────────────────────────────────────────────────────────╮ │ cells not installed │ │ several edits and their check in one step │ │ /plugin install cells --marketplace │ │ HarzerHeribert/claude-modpack │ ╰──────────────────────────────────────────────────────────╯ ╭──────────────────────────────────────────────────────────╮ │ eta not installed │ │ a percentage and finish time for long-running jobs │ │ /plugin install eta --marketplace │ │ HarzerHeribert/claude-modpack │ ╰──────────────────────────────────────────────────────────╯ ╭──────────────────────────────────────────────────────────╮ │ seek not installed │ │ has Claude look around your code in few, lean steps │ │ /plugin install seek --marketplace │ │ HarzerHeribert/claude-modpack │ ╰──────────────────────────────────────────────────────────╯ ╭──────────────────────────────────────────────────────────╮ │ draft not installed │ │ writing to a word limit in one draft, not in rounds of │ │ rewrites │ │ /plugin install draft --marketplace │ │ HarzerHeribert/claude-modpack │ ╰──────────────────────────────────────────────────────────╯ ╭──────────────────────────────────────────────────────────╮ │ route not installed │ │ optional: sends feature and test work to delegate's │ │ worker; needs an outside classifier (a Jev or ScaleDown │ │ key), off until you turn it on │ │ /plugin install route --marketplace │ │ HarzerHeribert/claude-modpack │ ╰──────────────────────────────────────────────────────────╯
README

<img alt="claude-modpack: eight Claude Code mods, each measured on real tasks before it shipped, built to work together. statusline, smart-compact, delegate, cells, eta, seek, draft, route." src="assets/banner-light.svg" width="880">

<h3>Install in Claude Code</h3>

/plugin install modpack --marketplace HarzerHeribert/claude-modpack

Answer y, then run /modpack:setup to set everything up step by step.<br> Or from your terminal, guided through both steps: bash <(curl -fsSL https://raw.githubusercontent.com/HarzerHeribert/claude-modpack/main/install.sh) (read it first).<br> Prefer doing it by hand? SETUP.md has every step.

Release License: MIT Claude Code 2.1.296 Quality: no loss seen 8 mods Lab notes

Claude Code with fewer wasted steps, and a clear view of what it's doing.

Eight free add-ons that work on their own. One command installs them, and there is nothing new to learn.<br> Every number on this page was measured, including where it doesn't help.

Install · What you get · Honest numbers · The site: ideas and evidence · Lab notes · Questions

<img alt="Animated: the cost per job with and without the pack, as bars that grow: in a long session $0.44 against $0.29 (−33%), bigger jobs in a fresh session $0.55 against $0.51 (−8%), quick questions in a fresh session $0.23 against $0.24 (+2%, about even); then what was measured since: −17% on 12 jobs beyond code with the pack as 0.7.0 ships it, −22% on a feature a cheaper model builds from your plan, −11% writing to a word limit in one draft, and compacting a 70k-token session in 4 ms instead of 15 s with the summary written ahead; then 2,550 graded runs, no quality loss seen." src="assets/numbers.gif" width="880">

Why it saves

Every time Claude takes a step (reads a file, makes an edit, runs the tests), it reads your whole conversation again. That re-reading is most of what a session costs, and it grows the longer you work. So the cheapest step is the one Claude never has to take.

The pack takes out steps that need no thinking. Several edits and their test run as one step. A search for a name in your code comes back with the exact answer. And when you approve a plan, a cheaper model does the building while Claude checks the result. The work comes out the same; Claude just gets there in fewer round trips.

What you get

<img alt="A real Claude Code session with the pack, six moments cut together, each with a caption: a bar and a finish time for long jobs (eta); several edits and the test run in one step (cells); an approved plan built by a cheaper model and checked (delegate); asked for at most 300 words, one draft that fits (draft); compacted at once, its summary written ahead, with that setting on (smart-compact); every mod with a switch that acts at once (/mods). Under the prompt throughout, the status line: model, context, the plan's 5-hour and weekly use." src="assets/demo-tour.gif" width="880">

Always know where your plan stands

One line under the prompt: the model, how full the conversation is, and how much of your plan's 5-hour and weekly limits you have used, with when each one resets. Long jobs get a progress bar and a finish time above the prompt. And when you step away, your session is kept ready, or tidied up before it goes cold, whichever costs less; the line tells you which.

These are the statusline, eta and smart-compact mods.

No waiting when a conversation gets long

When a conversation fills up, Claude Code summarizes it so the work can go on, and you wait while it writes: 15 seconds at 67k tokens and 102 seconds at 436k in our sessions. Turn on compacting after a turn (afterTurnPayback) and smart-compact compacts a long conversation shortly after a turn ends, when that pays back soon. Its summary is written in the background as the turn ends, so the compaction itself takes 3 to 5 ms. Against /compact from the same session, the next job cost 14% less, at full marks in 16 of 18 runs against 14 of 18 (lab note 15).

That's the smart-compact mod (compacting after a turn is off until you turn it on).

Several changes in one step, and you can still undo them

Claude makes several edits and runs the tests as one step, and you watch each part happen in a live card. Every edit still goes through Claude Code's own edit tool: you see each change, and /rewind undoes it.

That's the cells mod.

A cheaper model builds what you approved

When you approve a plan, Claude hands the building to Sonnet, a cheaper model, and checks its work before reporting back. In our tests that made a feature 22% cheaper and new tests 26% cheaper, with every result correct (corrected 16 Oct: worker costs were undercounted; it was 27% and 33%). You can watch the helper work in its card, and /delegate shows every step it took.

That's the delegate mod.

Optional: feature work goes to the cheaper model by itself

An optional mod, off until you turn it on, and the one that needs an outside classifier model: an API key for TypeSafe's Jev or ScaleDown. That classifier reads each prompt you send. Only when it is feature or test work is Claude told to hand it straight to delegate's worker: the worker reads the code and builds, delegate checks the result itself, and Claude reports after two steps of its own. On a TypeScript feature that made the job 51% cheaper and 42% faster than the pack alone, with every result correct (corrected 16 Oct: worker costs were undercounted; it was 57%); everything else stays with Claude. The classifier is an outside service (TypeSafe's Jev or ScaleDown), so this is off until you turn it on and give it a key: from then on, the start of each prompt goes to it, in the US, to be classified. In real sessions it saves less than on the benchmark: in the author's, the turns it would hand off were 13% of the spend, so at most 4 to 7% saved, nearer 3 to 6% with the hand-offs that were not feature or test work; more if most of your work is building features, and less if you already plan in plan mode, where delegate hands an approved plan to the worker without route.

That's the route mod (optional; it needs an outside classifier and its key).

Fewer, leaner steps when Claude looks around

Before Claude changes anything, it looks around your code, and everything it reads stays in the conversation, read again with every later step. Beside the first prompt you send in a session, and again as the session grows, the pack passes on your preference to look around in few, lean steps: the searches it can already name in one go, the lines that matter rather than whole files, nothing read twice. Against the pack without it, that made jobs 12% cheaper in a fresh session, 16% on a TypeScript library and 10 to 16% in long sessions, at the same quality. It runs on your machine and sends nothing anywhere.

That's the seek mod.

Writing to a word limit, in one draft

Ask for a text of at most so many words, and Claude tends to write all of it, count, find it a third too long, and write all of it again, several times. With a limit in your prompt, the pack passes on your preference to give each part its share and aim a little under, to keep every fact you asked for (and say so if they cannot all fit), and after each write it shows the word count and, when the text is well over, each section's target, so one more write lands it. On six writing tasks that made them 11% cheaper at the same quality. Without a word limit in your prompt it does nothing.

That's the draft mod.

You stay in control

/mods lists the eight and turns any of them on or off, right away, with a click or by typing, such as /mods statusline off. When something can't fully work on your computer, the pack tells you once, with the command that fixes it. When another plugin's permission or notification hook hangs (Warp's does outside the Warp terminal), the pack stops waiting for it after 10 seconds, so Claude Code can't freeze, and tells you which one it was. It keeps itself up to date (or only lets you know, if you prefer).

That's the modpack plugin, which installs the other eight.

Install

In Claude Code, type:

/plugin install modpack --marketplace HarzerHeribert/claude-modpack

Answer y to add the marketplace, then pick where to install it. That installs all eight. Then, in the project you work in:

/modpack:setup

It checks your machine, asks once what you want on (route stays off unless you say yes), sets each mod up in order, and checks that each one works. Done. /mods shows what's on.

By hand instead: SETUP.md has every step.

Each mod installs on its own the same way, for example /plugin install smart-compact --marketplace HarzerHeribert/claude-modpack. delegate and cells use a language server where you have one installed and work without it: Language servers.

Honest numbers

We measured the pack on Claude Opus 5.5 doing seven real jobs in an open-source project (click), from a one-line lookup to building a feature, on two days, 13 and 15 October. Every result was checked by hidden tests. The same jobs ran with the pack and without it, and we compared what they cost at API prices.

Cost per jobWithoutWith the pack
In a long session (Claude has already read the whole project)$0.44$0.29−33%
Bigger jobs in a long session (a feature, tests, a rename)$0.91$0.57−37%
In a fresh session$0.37$0.35−4%
Bigger jobs in a fresh session$0.55$0.51−8%, and 15% faster
Quick questions in a fresh session$0.23$0.24+2%, about even
  • Where it doesn't help: quick questions in a brand-new session. The pack's tools come along with every step, and a three-step lookup has little to save: 5% more one day, 4% less the next, about even.
  • Writing tests: the pack alone saves nothing there (−2%, 12 runs each way): every step waits on the last test run. route hands it to the worker instead (−36% to −46%, below).
  • Nothing got worse: all 224 runs behind this table produced a correct result, with the pack and without.
  • The 95% ranges: long session −39% to −27%; fresh −7% to −1%; bigger jobs fresh −12% to −3%; quick questions −1% to +6%. The long session is two runs per job each day, and the days differ: −26% on one, −40% on the other, mostly from the feature (plain needed 12 requests one day, 16 the next).
  • The same on other code: on a TypeScript library (chrono) the pack cost 7.6% less (−12% to −3%) and took fewer steps on all eight jobs. On 30 real bug reports from SWE-bench Verified it fixed 30 against 29, with 23% fewer steps; the cost, −12%, is not certain at one attempt per bug (−33% to +12%). On PocketBase, Trail-Code's own 15 tasks: −21% with 0.6.0, at one run per task as Trail-Code ran them (the average task −18%, between −27% and −8%; lab notes 3).
  • Beyond click, new in 0.7.0: on 12 tasks in a React and TypeScript app, a small service to run and fix, and documents and data to write and analyse, the pack as 0.7.0 ships it cost 17% less than plain Claude Code (−22% to −12%, 48 runs, all but four at full marks): web code −28%, operating software −8%, prose and data −5% (−10% to +1%), so prose is where it does least.
  • A plan handed to a cheaper model: −22% on a feature, −26% on tests, against Opus doing it alone with the pack (16 runs, all correct).
  • With route turned on: a further −14% on click's eight jobs (route 0.1). With 0.6.0's verified hand-offs, against the pack in the same batch on TypeScript: a feature −51% and 42% faster, writing tests −36%; Claude itself takes 2 steps instead of 6 to 11 (24 runs, all correct).
  • Corrected 16 Oct: worker costs were undercounted. A worker's transcript records its output as each response began, and our bench counted it from there, so every number with a hand-off in it came out too good. Corrected from Claude Code's own totals: a planned feature −22% (was −27%), tests −26% (was −33%), route on click −14% (was −17%), the TypeScript feature −51% (was −57%). Every saving is still a saving, a smaller one. The table above has no hand-offs and did not change. Each claim, old and new: CORRECTION-1016.md.
  • With seek (new in 0.6.0, measured against the pack rather than plain Claude Code, so not in the table above): −12% fresh on click, −16% on TypeScript, −10% to −16% in long sessions (seek, below).
  • With draft (new in 0.8.0, measured against the pack): −10.7% on six writing tasks, from −14.9% to −6.3%, at the same quality (0.987 against 0.990), and no run over its word limit (draft, below).
  • Two days, two versions: the 13 October runs used the pack as of 0.3.0 and Claude Code 2.1.296, the 15 October runs 0.4.0 and 2.1.299. What changed in the pack between them (on/off switches, setup, messages shown when a worker is refused) never reached the model in these runs: its first request was 26.7k tokens plain and 30.6k with the pack on both days. The second day's plain runs were done twice, because the first try had the pack installed by mistake: lab notes 8 tells how we caught it.

<img alt="Cost per task, plain Claude Code against the modpack, in a fresh session and in a session already holding 216k tokens." src="assets/cost-light.svg" width="880">

<img alt="Model requests per task, plain Claude Code against the modpack: 3.2 against 5.6 in a session already holding 216k tokens." src="assets/requests-light.svg" width="880">

<img alt="Cost per task, Opus alone against a plan handed to a worker: feature work 22% less, tests 26% less." src="assets/delegate-light.svg" width="880">

How we measured, every run's record, and the scripts to run it all again are in benchmarks/, starting with SUITE.md. What we tried that did not make it is in the lab notes (as Markdown), among it a 10,000-star code graph, Trail-Code, which installed into Claude Code saved nothing we could measure: alone −1.8% against plain Claude Code (−5.9% to +2.7%), beside the pack +13% (lab notes 3). Not measured: what smart-compact saves you while you're away (worked out from prices, not tested) and Windows.

Questions

Will Claude's work get worse? Not that we have seen. Every run is graded by hidden tests or fixed rules, and the same jobs run with the pack and without it. In the batches that did both, 6 of 349 runs without the pack and 8 of 407 with it fell short of full marks. Of all 2,586 graded runs that ship with this release, 96 fell short: seven on one TypeScript explanation whose answers sometimes leave out one term of its list, with the pack and without; five with Trail-Code, whose hook replaced the answer; seven with Haiku as the main model, in two experiments we dropped; one TypeScript type question; and six on PocketBase. There, two questions left out terms of their answer key in both arms, and plain Claude Code missed one term of a third. On that third question the pack scored 0: lsp-plus held a search while Go's language server was still loading, Claude Code moved it to the background, and Claude's last message answered the notice that followed instead of the question. lsp-plus 0.4.2 then gave the language server 8 seconds at most, and lsp-plus has since left the pack. Seven more are 0.7.0's: five on one prose revision whose checks are strict, in every arm, plain Claude Code too; one runbook and one rename. And 22 are 0.8.0's: nine in the writing tasks, three with draft and three without in one batch and three more with draft in the next (a removed command named as current, a follow-up missing from a brief); thirteen in the compaction benchmark, spread over every arm, ten of them one option check of one task and three a rename that kept a deprecated alias of the old name. Six are 0.9.0's, from the benchmark of the summary written ahead against /compact: five that same option check, two with the summary written ahead and three with /compact, and one rename under /compact that left the old name in one file. And 29 ship with the lab notes of 19 October: 28 from draft's first writing batches, with draft and without, graded before three of their graders were fixed (a removed command named in a history sentence, a code-span check, a stale base; lab note 13), and one with steer, a system-prompt experiment we did not ship. And six ship with 0.9.3, from the next-task benchmark of two shorter summaries, three each: the same option check three times, and the rename three times (twice a docstring note naming the old name, once the old name left in one file). Apart from the PocketBase run, the pack changes how many steps Claude takes, not whether it gets there.

Where did lsp-plus go? It left the pack in 0.7.0. Measured twice, 120 runs on renames and traces in click, a TypeScript library and a React app and on web, operating and prose work, the pack cost no more without it (−1.8% and −1.6%, both ranges across zero), and it kept a language server running per language in every session, hundreds of MB each. Its answer to a grep came from the language server, and in untyped code a server finds about half the uses of a name, where a plain word search finds them all (lab notes 12). The update removes it once and says so in one line; installed again on purpose, it stays. Its last version, 0.4.2, is in this repository's v0.6.1 tag.

Is it safe? It's open source (MIT), so every line is here to read. Code that Claude runs inside a cell runs in a sandbox with no network access. Edits go through Claude Code's own edit tool, so your usual permission prompts and /rewind still apply. The pack sends nothing anywhere except a once-a-day check on GitHub for a new release, which you can turn off, and, only if you turn route on, the start of each prompt to the classifier you chose (TypeSafe or ScaleDown).

Does the pack add anything to my prompts? Your prompt itself is never changed. Beside it, Claude can get a short note in your name: seek's setting to look around in few, lean steps (with the first prompt of a session, and again after a compaction), and, only if you turn route on, the order to hand feature or test work to the worker; delegate gives the same order when you approve a plan of 20 lines or more. A subagent Claude starts gets cells' and seek's settings at the end of its task, since your prompts never reach it. /mods seek off and /mods route off stop theirs; subagents: false in cells or seek stops theirs for subagents.

I'm on a Pro or Max plan. Does this help me? You don't pay per job, but every step counts against your 5-hour and weekly limits. We measured cost at API prices, not plan usage, so we can't promise a number. Fewer, lighter steps should leave more of your limits, and the status line shows exactly where you stand.

Does it work in the desktop app? Yes, cards, progress and the status line included. One limit: in auto mode the desktop app doesn't let an add-on start a helper model, so plans aren't handed off there (turn route off there too); in manual mode, or in the terminal, they are. Windows hasn't been tested yet.

How do I turn it off? /mods switches each part off or on, right away. /plugin removes them.

Were any of these numbers wrong? Yes, the hand-off ones. On 16 October we found that our bench had counted a worker's output only as each of its responses began, so every saving that involved a worker came out too large: a planned feature was −27% and is −22%. They are corrected here, the old and new number side by side in CORRECTION-1016.md. The pack-against-plain numbers had no workers and stand.

What does it cost? Nothing. It's free and open source.

The mods in depth

One line under the prompt, drawn in Claude Code's own hint row so the mode indicator and the status share it:

⏵⏵ auto mode on       Opus 5.5 xhigh   412k ━━━━━━──────   5h 34% ↺2h14   7d 12% ↺3d   ● ready · cold in 44m
  • Its own segments: the model and its effort, the context against the auto-compact point (a highlight sweeps along it while Claude works), and how much of the plan's 5-hour and 7-day windows is used, with when each resets: quiet under half, plain past it, amber from 80%.
  • Other mods' segments: a mod calls $.statusline.set({ id, priority, parts, short?, side? }) and lists statusline among its dependencies. A part is text, a countdown ({ until, prefix?, warnMs? }, counted by the line) or a spinner ({ spin: true }), so a mod sends a segment when it changes, not every second. $.statusline.remove({ id }) takes it off.
  • Narrow terminals drop the least important first: the model, then the windows' resets, the windows, the gauge, and another mod's countdown before its own words.
  • Published pages: a pill on the left lists the pages this session published with the Artifact tool.
  • Phone and IDE: where no line is drawn, the same line is the session's status text, in a session the phone or IDE hosts. A terminal session watched over Remote Control (/rc) from the desktop app, the web or the phone gets no mod drawing and no status text as of Claude Code 2.1.296.
OptionDefault
enabledtruefalse turns the mod off; /mods does it for all of the pack.
placementlinetail: appended dim to Claude Code's hint. band: above the prompt. off.
limitsalwayshalf: a plan window only once it is half used. off: never.
animatetrueThe highlight along the gauge.

An idle session's prompt cache expires after its TTL: 1 hour on a subscription, 5 minutes in ove

Source 2 files
hooks/register.ts 316 lines
1import type { EngineInterface, Register } from 'claude-code'
2
3import { loadedMods, MODS, modRows, modsPane, modsText, type Elements } from './mods'
4
5type Engine = EngineInterface
6
7// Hook guard: another plugin's PermissionRequest or Notification command hook that hangs must not freeze
8// Claude Code. Skipping only these two is safe (PermissionRequest skipped: Claude Code asks the person; Notification
9// is cosmetic). PreToolUse is never touched.
10
11const FIRST_LIMIT_MS = 10_000
12const AFTER_HANG_LIMIT_MS = 2_000
13
14/** Marks that the limit ran out before the chain beneath answered. */
15const TIMED_OUT = Symbol('timed out')
16
17type Race<R> = { timedOut: false; result: R } | { timedOut: true }
18
19/**
20 * Waits for `run()` (the `next(e)` call) at most `limitMs`, by racing it against a `$.clock.sleep`.
21 * The sleep counts against the hook's own budget (a $.clock wait is the one `$` call that does), so
22 * the limit is cut to stay under what `budget.remainingMs` leaves; the hook's `.catch` is the net.
23 */
24async function race<R>($: Engine, run: () => Promise<R>, limitMs: number, remainingMs: number): Promise<Race<R>> {
25  const stop = new AbortController()
26  const ms = Math.max(0, Math.min(limitMs, remainingMs - 500))
27  const timer = $.clock.sleep(ms, { signal: stop.signal }).then(
28    () => TIMED_OUT,
29    // Aborted because the chain answered first: this side never wins.
30    () => new Promise<never>(() => undefined),
31  )
32  const chain = run()
33  // If the timer wins, a later rejection of the abandoned chain must not surface.
34  chain.catch(() => undefined)
35  try {
36    const r = await Promise.race([chain, timer])
37    return r === TIMED_OUT ? { timedOut: true } : { timedOut: false, result: r as R }
38  } finally {
39    stop.abort()
40  }
41}
42
43type HookEntry = { hooks?: { type?: string; command?: string }[] }
44
45const hasCommand = (v: unknown, event: string): boolean => {
46  const list = (v as Record<string, unknown> | undefined)?.[event]
47  return (
48    Array.isArray(list) &&
49    (list as HookEntry[]).some(h => Array.isArray(h?.hooks) && h.hooks.some(c => (c?.type ?? 'command') === 'command'))
50  )
51}
52
53/** The enabled plugins and settings that define a command hook for `event`: best effort, may be empty. */
54async function hookSources($: Engine, event: string): Promise<string[]> {
55  const out: string[] = []
56  try {
57    const settings = (await $.settings.read()) as { enabledPlugins?: Record<string, unknown> }
58    const home = (await $.env.get('HOME')) ?? ''
59    // The merged settings carry the plugins' hooks too: the person's own are in their files.
60    const cwd = await $.session.cwd()
61    for (const f of [`${home}/.claude/settings.json`, `${home}/.claude/settings.local.json`, `${cwd}/.claude/settings.json`, `${cwd}/.claude/settings.local.json`]) {
62      const own = await $.fs.read(f).then(t => JSON.parse(t) as { hooks?: unknown }).catch(() => undefined)
63      if (own !== undefined && hasCommand(own.hooks, event)) {
64        out.push('your settings')
65        break
66      }
67    }
68    for (const [id, on] of Object.entries(settings.enabledPlugins ?? {})) {
69      if (on === false) continue
70      const [name, market] = id.split('@')
71      const dir = `${home}/.claude/plugins/cache/${market}/${name}`
72      const versions = await $.fs.list(dir).catch(() => [])
73      for (const v of versions) {
74        if (v.kind === 'file') continue
75        const path = `${dir}/${v.name}/hooks/hooks.json`
76        if (!(await $.fs.exists(path).catch(() => false))) continue
77        const json = JSON.parse(await $.fs.read(path)) as { hooks?: unknown }
78        if (hasCommand(json.hooks ?? json, event)) {
79          out.push(id)
80          break
81        }
82      }
83    }
84  } catch {
85    // unreadable settings: name no source
86  }
87  return out
88}
89
90function notice(event: string, sources: readonly string[], limitMs: number): string {
91  const who = sources.length ? ` (${sources.join(', ')})` : ''
92  return `a ${event} hook${who} ran over ${limitMs / 1000} s, so Claude Code went on without it. hookGuard: off in the modpack settings turns this off.`
93}
94
95async function loaded($: Engine) {
96  const commands = await $.command.list().catch(() => [])
97  const tools = await $.tool.list().catch(() => [])
98  return loadedMods(commands, tools)
99}
100
101const REPO = 'HarzerHeribert/claude-modpack'
102const MARKETPLACE = 'claude-modpack'
103const PLUGINS = ['modpack', 'statusline', 'smart-compact', 'delegate', 'cells', 'eta', 'seek', 'draft', 'route']
104
105/** Mods that left the pack. A release no longer ships them, and an update cannot reach them, so the first session on
106 * the new modpack removes each from a marketplace install, once, and says why in one line. */
107export const RETIRED: ReadonlyArray<{ name: string; release: string; why: string }> = [
108  {
109    name: 'lsp-plus',
110    release: '0.7.0',
111    why: 'in two benchmarks (120 runs) the pack cost no more without it, and it kept a language server running per language in every session (hundreds of MB each)',
112  },
113]
114const THROTTLE_MS = 20 * 3_600_000
115
116const MODS_PANE = 'mods'
117
118let mode = 'auto'
119let hung = false
120let told = false
121
122const parts = (v: string) => v.replace(/^v/, '').split('.').map(p => Number.parseInt(p, 10) || 0)
123
124/** True when semver `b` is newer than `a` (numeric per part; a leading "v" is allowed). */
125export function newer(a: string, b: string): boolean {
126  const x = parts(a)
127  const y = parts(b)
128  for (let i = 0; i < Math.max(x.length, y.length); i++) {
129    const d = (y[i] ?? 0) - (x[i] ?? 0)
130    if (d !== 0) return d > 0
131  }
132  return false
133}
134
135/** The release's version from the GitHub API's JSON: tag_name "v0.3.0" gives "0.3.0". */
136export function releaseVersion(json: unknown): string | undefined {
137  let o: unknown = json
138  if (typeof json === 'string') {
139    try {
140      o = JSON.parse(json)
141    } catch {
142      return undefined
143    }
144  }
145  const tag = (o as { tag_name?: unknown } | null | undefined)?.tag_name
146  return typeof tag === 'string' && tag.trim() !== '' ? tag.trim().replace(/^v/, '') : undefined
147}
148
149const url = (latest: string) => `https://github.com/${REPO}/releases/tag/v${latest}`
150
151async function claude($: Engine, args: string[]) {
152  return $.process.run(['claude', ...args], { timeoutMs: 120_000 }).catch(() => undefined)
153}
154
155const firstLine = (s: string | undefined) => (s ?? '').trim().split('\n')[0] || 'no error text'
156
157/** Runs the marketplace update and each plugin's; the outcome as the line the person reads. */
158async function install($: Engine, latest: string, current: string): Promise<string> {
159  const m = await claude($, ['plugin', 'marketplace', 'update', MARKETPLACE])
160  if (m === undefined || m.exitCode !== 0) return failed(latest, m?.stderr)
161  let own: Awaited<ReturnType<typeof claude>>
162  for (const name of PLUGINS) {
163    const r = await claude($, ['plugin', 'update', `${name}@${MARKETPLACE}`])
164    // A mod new in this release (route in 0.5.0, seek in 0.6.0, draft in 0.8.0) is not installed yet: update cannot reach it, install does.
165    if (name !== 'modpack' && (r === undefined || r.exitCode !== 0)) await claude($, ['plugin', 'install', `${name}@${MARKETPLACE}`])
166    if (name === 'modpack') own = r
167  }
168  if (own === undefined || own.exitCode !== 0) return failed(latest, own?.stderr)
169  return `claude-modpack ${latest} is installed (you were on ${current}): it loads the next time Claude Code starts; claude --continue keeps this conversation. What's new: ${url(latest)}`
170}
171
172const failed = (latest: string, stderr: string | undefined) =>
173  `claude-modpack ${latest} is out, but the update failed: ${firstLine(stderr)}. /modpack:update tries again.`
174
175/** The line the person reads when a retired mod was removed. */
176export function retiredLine(r: { name: string; release: string; why: string }): string {
177  return `claude-modpack ${r.release} retired ${r.name} and removed it: ${r.why}. The numbers: ${url(r.release)}`
178}
179
180/**
181 * Removes the retired mods a marketplace install still has, each once: a record in ~/.claude/mods/modpack/retired.json
182 * keeps a person who installs one again on purpose from being overruled. The lines to show, one per mod handled.
183 */
184async function retire($: Engine): Promise<string[]> {
185  const home = (await $.env.get('HOME')) ?? ''
186  const record = `${home}/.claude/mods/modpack/retired.json`
187  const done = await $.fs.read(record).then(t => JSON.parse(t) as string[]).catch(() => [] as string[])
188  const enabled = ((await $.settings.read().catch(() => ({}))) as { enabledPlugins?: Record<string, unknown> }).enabledPlugins ?? {}
189  const lines: string[] = []
190  const now = [...done]
191  for (const r of RETIRED) {
192    const id = `${r.name}@${MARKETPLACE}`
193    if (done.includes(id) || !(id in enabled)) continue
194    const res = await claude($, ['plugin', 'uninstall', id])
195    now.push(id)
196    lines.push(res !== undefined && res.exitCode === 0 ? retiredLine(r) : `claude-modpack ${r.release} retired ${r.name}, but removing it failed: ${firstLine(res?.stderr)}. /plugin uninstall ${id} removes it.`)
197  }
198  if (now.length !== done.length) await $.fs.write(record, JSON.stringify(now)).catch(() => undefined)
199  return lines
200}
201
202type Outcome = { text?: string; current: string; latest?: string; folder?: boolean; root: string }
203
204/** The check, and the install when `install` is set. `force` ignores the throttle. Undefined text: nothing to say. */
205async function check($: Engine, force: boolean, doInstall: boolean): Promise<Outcome> {
206  // MODPACK_PLUGIN_ROOT stands in for $.plugin.root: a seam for tests, which cannot move the real one.
207  const root = (await $.env.get('MODPACK_PLUGIN_ROOT')) || $.plugin.root
208  const home = (await $.env.get('HOME')) ?? ''
209  const current = JSON.parse(await $.fs.read(`${root}/.claude-plugin/plugin.json`)).version as string
210  if (!root.startsWith(`${home}/.claude/plugins/`)) return { current, folder: true, root }
211  const statePath = `${home}/.claude/mods/modpack/update.json`
212  const now = await $.clock.now()
213  if (!force) {
214    const st = await $.fs.exists(statePath).catch(() => false)
215    const saved = st ? await $.fs.read(statePath).then(t => JSON.parse(t) as { checkedAt?: number }).catch(() => undefined) : undefined
216    if (typeof saved?.checkedAt === 'number' && now - saved.checkedAt < THROTTLE_MS) return { current, root }
217  }
218  const res = await $.http.fetch(`https://api.github.com/repos/${REPO}/releases/latest`, {
219    headers: { Accept: 'application/vnd.github+json', 'User-Agent': 'claude-modpack' },
220  }).catch(() => undefined)
221  const latest = res?.ok ? releaseVersion(res.text) : undefined
222  if (latest === undefined) return { current, root }
223  let text: string | undefined
224  if (newer(current, latest)) {
225    if (doInstall) text = await install($, latest, current)
226    else text = `claude-modpack ${latest} is out (you have ${current}): /modpack:update installs it. What's new: ${url(latest)}`
227  }
228  await $.fs.write(statePath, JSON.stringify({ checkedAt: now, latest })).catch(() => undefined)
229  return { text, current, latest, root }
230}
231
232async function guarded(event: string, $: Engine, e: unknown, next: unknown, guard: boolean) {
233  const n = next as ((e: unknown) => Promise<unknown>) & { budget: { remainingMs: number } }
234  if (!guard) return n(e)
235  const limit = hung ? AFTER_HANG_LIMIT_MS : FIRST_LIMIT_MS
236  const r = await race($, () => n(e), limit, n.budget.remainingMs)
237  if (!r.timedOut) return r.result
238  hung = true
239  if (!told) {
240    told = true
241    const sources = await hookSources($, event)
242    await $.ui.log(notice(event, sources, limit))
243  }
244  return {} // no decision: Claude Code goes on to its own dialog
245}
246
247async function setMod($: Engine, mod: string, action: string | undefined): Promise<string> {
248  const names = MODS.map(m => m[0])
249  if (!names.includes(mod as never)) return `No mod called ${mod}. The pack's mods: ${names.join(', ')}.`
250  if (action !== undefined && action !== 'on' && action !== 'off') return `Say /mods ${mod} on or /mods ${mod} off.`
251  const config = await $.config.list()
252  const row = modRows(config, await loaded($)).find(r => r.name === mod)
253  if (row === undefined || row.state === 'not installed') return `${mod} is not installed: ${row?.install ?? ''}`
254  if (row.folder) return `${mod} is loaded from a folder, so it has no row in /config: its switch is \`enabled\` under pluginConfigs in your settings.`
255  const key = `${mod}.enabled`
256  const cfg = config.find(r => r.key === key)
257  if (cfg === undefined) return `${mod} has no on/off switch.`
258  if (cfg.isLocked) return `${mod}'s switch is locked by your settings policy; /mods cannot change it.`
259  const value = action === undefined ? cfg.value === false : action === 'on'
260  await $.config.set({ key, value })
261  await $.ui.invalidate('ui.render')
262  return `${mod} is now ${value ? 'on' : 'off'}. /mods ${mod} ${value ? 'off' : 'on'} turns it back ${value ? 'off' : 'on'}.`
263}
264
265export const register: Register = (on, options) => {
266  const u = options.updates
267  mode = u === 'notify' || u === 'off' ? u : 'auto'
268
269  on('session.start', async ($, e, next) => {
270    await $.command.register({ name: 'update', description: 'Update claude-modpack and its mods to the newest release' })
271    await $.command.register({ name: 'mods', description: "See the pack's mods, and turn each on or off", argumentHint: '[mod] [on|off]' })
272    // Retired mods go whatever the update setting: this modpack is already the release that retired them.
273    $.clock.after(0, () => {
274      void retire($).then(lines => {
275        for (const line of lines) $.ui.log(line)
276      }).catch(() => undefined)
277    })
278    if (mode !== 'off') {
279      $.clock.after(0, () => {
280        void check($, false, mode === 'auto').then(o => {
281          if (o.text) $.ui.log(o.text)
282        }).catch(() => undefined)
283      })
284    }
285    return next(e)
286  })
287
288  on('command.run', { command: 'update' }, async $ => {
289    const o = await check($, true, true)
290    if (o.folder) return { text: `claude-modpack is loaded from ${o.root}: update it there (git pull); a folder copy reloads by itself.` }
291    if (o.latest === undefined) return { text: 'Could not reach GitHub to look for a new release. Try again later.' }
292    return { text: o.text ?? `Already the newest: ${o.current}.` }
293  })
294  on('command.run', { command: 'mods' }, async ($, e) => {
295    const argv = (e.args ?? '').trim().split(/\s+/).filter(Boolean)
296    if (argv.length > 0) return { text: await setMod($, argv[0] as string, argv[1]) }
297    const text = modsText(modRows(await $.config.list(), await loaded($)))
298    await $.ui.open({ id: MODS_PANE, title: 'Mods' }).catch(() => undefined)
299    return { text }
300  })
301
302  // The hook guard: next(e) raced against a $.clock wait; see guard.ts.
303  hung = false
304  told = false
305  const guard = options.hookGuard !== false
306  // The hook's 10 s budget can end before a 10 s wait does: the handler then also answers with no decision.
307  on('classic.PermissionRequest', ($, e, next) => guarded('PermissionRequest', $, e, next, guard) as never).catch(() => ({}))
308  on('classic.Notification', ($, e, next) => guarded('Notification', $, e, next, guard) as never).catch(() => ({}))
309
310  on('ui.render', { component: 'Pane', requestId: MODS_PANE }, async ($, e) => {
311    const flip = (key: string, value: boolean) =>
312      void $.config.set({ key, value }).then(() => $.ui.invalidate('ui.render')).catch(() => undefined)
313    return modsPane($.ui.resolve(e) as unknown as Elements, modRows(await $.config.list(), await loaded($)), flip)
314  })
315}
316
hooks/mods.tsx 89 lines
1// /mods: which of the pack's mods are loaded, and a button on each to turn it off or on.
2
3import type { BoxProps, ButtonProps, ConfigRow, ElementConstructor, RenderElement, TextProps } from 'claude-code'
4
5export type Elements = {
6  Box: ElementConstructor<BoxProps>
7  Text: ElementConstructor<TextProps>
8  Button: ElementConstructor<ButtonProps>
9}
10
11const MARKETPLACE = 'HarzerHeribert/claude-modpack'
12
13const FOLDER = "loaded from a folder: its `enabled` setting is in your settings' pluginConfigs"
14
15export const MODS = [
16  ['statusline', 'one line under the prompt: model, context, plan use'],
17  ['smart-compact', 'keeps the prompt cache warm or compacts before it expires'],
18  ['delegate', 'hands a task to a cheaper worker model and checks its work'],
19  ['cells', 'several edits and their check in one step'],
20  ['eta', 'a percentage and finish time for long-running jobs'],
21  ['seek', 'has Claude look around your code in few, lean steps'],
22  ['draft', 'writing to a word limit in one draft, not in rounds of rewrites'],
23  ['route', 'optional: sends feature and test work to delegate\'s worker; needs an outside classifier (a Jev or ScaleDown key), off until you turn it on'],
24] as const
25
26export type ModRow = {
27  name: string
28  does: string
29  state: 'on' | 'off' | 'not installed'
30  /** The key to flip and the value to set; absent when not installed or locked. */
31  flip?: { key: string; value: boolean }
32  install?: string
33  /** Loaded without /config rows (a folder): no button; its setting lives in pluginConfigs. */
34  folder?: boolean
35}
36
37/** The mods seen through commands, tool names (folder-loaded plugins have no /config rows). */
38export function loadedMods(commands: readonly { plugin?: string }[], tools: readonly { name: string }[]): Set<string> {
39  const out = new Set<string>()
40  for (const [name] of MODS) {
41    if (commands.some(c => c.plugin === name) || tools.some(t => t.name.startsWith(`mcp__${name}__`))) out.add(name)
42  }
43  return out
44}
45
46
47
48/** One row per mod of the pack, from the /config rows; `loaded` names mods seen another way (a folder has no rows). */
49export function modRows(config: readonly ConfigRow[], loaded: ReadonlySet<string> = new Set()): ModRow[] {
50  return MODS.map(([name, does]) => {
51    const key = `${name}.enabled`
52    const row = config.find(r => r.key === key)
53    if (row === undefined) {
54      if (config.some(r => r.key.startsWith(`${name}.`))) return { name, does, state: 'on' as const }
55      if (loaded.has(name)) return { name, does, state: 'on' as const, folder: true }
56      return { name, does, state: 'not installed' as const, install: `/plugin install ${name} --marketplace ${MARKETPLACE}` }
57    }
58    const on = row.value !== false
59    return { name, does, state: on ? ('on' as const) : ('off' as const), ...(row.isLocked ? {} : { flip: { key, value: !on } }) }
60  })
61}
62
63export function modsText(rows: readonly ModRow[]): string {
64  const lines = rows.map(r => `${r.name}: ${r.state} (${r.does})${r.install ? `\n  ${r.install}` : ''}${r.folder ? `\n  ${FOLDER}` : ''}`)
65  return `The pack's mods:\n${lines.join('\n')}\n/mods opens a pane where each installed one turns on or off.`
66}
67
68export function modsPane(el: Elements, rows: readonly ModRow[], onFlip: (key: string, value: boolean) => void): RenderElement {
69  const { Box, Text, Button } = el
70  return (
71    <Box flexDirection="column">
72      {rows.map(r => (
73        <Box key={r.name} flexDirection="column" borderStyle="round" borderColor={r.state === 'on' ? 'claude' : 'subtle'} paddingX={1}>
74          <Box>
75            <Text bold color={r.state === 'on' ? 'claude' : undefined} dimColor={r.state !== 'on'}>{r.name}</Text>
76            <Text dimColor>{`  ${r.state}`}</Text>
77          </Box>
78          <Text dimColor>{r.does}</Text>
79          {r.folder === true && <Text dimColor>{FOLDER}</Text>}
80          {r.install !== undefined && <Text dimColor>{r.install}</Text>}
81          {r.flip !== undefined && (
82            <Button key={`toggle-${r.name}`} plain label={r.state === 'on' ? 'turn off' : 'turn on'} onPress={() => onFlip((r.flip as { key: string }).key, (r.flip as { value: boolean }).value)} />
83          )}
84        </Box>
85      ))}
86    </Box>
87  )
88}
89