SLOPSHOPPER

command-hub

Discover slash commands: essentials explained in plain language, searchable list of everything installed, a form to create your own, and tips when a command…

newpanecommandtoastprompt
★ 5v0.1.1MITupdated 2026-10-05mishgoldenberg/claude-mods/plugins/command-hub
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · command-hub
│ ┃ Commands ✕ › fix the failing auth test and add an audit log call │ ┃ ● command-hub 2 commands installed │ ┃ ⏺ Read(src/auth.ts) │ ┃ [ essentials ] [ all ] [ + create ] ⎿ Read 6 lines │ ┃ ⏺ Update(src/auth.ts) │ ┃ A slash command is a saved prompt. Use ⎿ Added 2 lines, removed 1 line │ ┃ $ARGUMENTS where text typed after the ⏺ Bash(bun test) │ ┃ command should go. ⎿ 3 pass, 1 fail │ ┃ │ ┃ Name /: e.g. ship ● Done. refresh now rejects expired claims and logs an audit event. │ ┃ │ ┃ Shown in menu: e.g. Run tests, then commit a ✻ Worked for 42s · done 4:20 PM │ ┃ │ ┃ Prompt: e.g. Run the test suite. If green, c › /cmds │ ┃ ⎿ command-hub: Command hub opened. │ ┃ Save for: This project (.claude/commands, sh │ ┃ │ ┃ [ Save command ] [ Draft it with Claude ] │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · Commands
● command-hub 2 commands installed [ essentials ] [ all ] [ + create ] A slash command is a saved prompt. Use $ARGUMENTS where text typed after the command should go. Name /: e.g. ship Shown in menu: e.g. Run tests, then commit and push Prompt: e.g. Run the test suite. If green, commit with a goo Save for: This project (.claude/commands, shareable via git) [ Save command ] [ Draft it with Claude ]
README

🧩 claude-mods

Panels, guardrails and quality-of-life mods for Claude Code: see what fills your context, how fast you burn your plan, and what the agent is running right now, and block the commands you never want run.

CI Claude Code TypeScript Mods License: MIT

<img src="docs/demo-guardrails.gif" alt="guardrails blocking an agent's oc delete all --all before it runs" width="900">

<sub>If a mod saves you from one bad approve, a ⭐ on this repo helps other people find it.</sub>


What is this?

Claude Code is a black box while it works. You can't see the context window filling up until it compacts away the decision you made an hour ago. You find out you've burned your 5-hour limit when it stops answering. You approve a command, tab away, and come back ten minutes later to find it has been waiting on a second approval the whole time. And most people discover /rewind only after the edit they wanted to undo.

claude-mods is a set of small plugins that open that box. Each mod is a standalone Claude Code plugin built on function hooks, the in-process plugin API: it sees every prompt, tool call and turn as it happens, and it can draw panels, toasts and status lines inside Claude Code itself. Install all eleven or only the ones you want.

They are deliberately boring about tokens. Nine of the eleven never call a model. The two that do (prompt-coach's review and context-keeper's handoff note) say so and are easy to turn off.


✨ Features

🧩 mod-managerOne panel (/mods) to install, turn on or off, update, or remove each mod, with presets (Safety only, Essentials, Zero tokens, Everything). Shows when a mod has a newer version. Install this first and pick the rest
🚦 quickbarOne line above the prompt: live context % and a button for every claude-mods panel you have installed. Start here
🧠 context-keeperWhat fills your context window, tips to trim it, and checkpoints: a handoff note (goal, decisions, files, TODOs) saved to .claude/checkpoints/ so /clear and /compact stop losing the thread. Archives the raw transcript before every compaction, for zero tokens
📈 usage-meter5-hour and 7-day plan-limit bars with reset countdown, burn rate and "full in ~2.3h", session cost, cache hit ratio (and why it's low), tokens-per-turn sparkline (drawn as charts in the desktop app)
🔔 notifyNotification inbox plus native OS notifications (Windows, macOS, Linux) when a long turn ends, a subagent or background task finishes, Claude asks you something, or an approval has been waiting 15s
👀 activityWhat Claude is doing this second: thinking, running $ npm test for 0m42s, waiting for YOUR approval, which subagents run, and its todo plan with progress
🛡️ guardrailsClickable safety rules with presets (Safe defaults, Locked to project, Read-only review): block rm -rf, mass kubectl/oc deletes, terraform destroy, force-push, destructive git, .env and key files, sudo, installs, network; keep Claude inside the project; add your own patterns. Checks scripts the agent wrote before they run, and keeps a weekly log of what it blocked
✍️ prompt-coachBefore a vague prompt is sent, a small fast model suggests a sharper one. You pick Send improved / Send mine / Edit. Never rewrites silently, never touches "yes" or "continue"
🧰 toolboxEvery tool Claude can use (built-in and MCP, grouped by server) in plain language, how often each was used, and suggestions for the project you're in
⌨️ command-hubThe built-in commands you're probably missing, each with when to use it; a searchable list of everything installed; a form to create your own slash command; tips when your prompt matches one ("undo that" → /rewind)
📝 changesEvery file Claude created or edited this session with +/- counts from git, plus one-click why?, summarize all and self-review
🔁 loop-breakerNotices Claude going in circles (the same command failing 3×, the same code rewritten 3× in a turn), tells you, and tells Claude to stop and rethink

🎬 See it in action

activity: what Claude is running right now, and the moment it's waiting on you

<img src="docs/demo-activity.gif" alt="activity panel showing thinking, waiting for approval, then completed tool calls" width="900">

context-keeper + usage-meter: what fills the window, a checkpoint saved to disk, plan limits

<img src="docs/demo-context.gif" alt="context panel, writing a checkpoint, then the usage meter" width="900">

prompt-coach: a vague prompt, a suggested rewrite, you choose

<img src="docs/demo-coach.gif" alt="prompt coach suggesting a sharper prompt and sending it" width="900">

command-hub: the built-in commands worth knowing, explained

<img src="docs/demo-commands.gif" alt="command hub listing essential slash commands" width="900">


🏗️ How it works

              You ──prompt──▶ ┌──────────────────────────────┐
                              │        Claude Code engine     │
                              │                               │
                              │  prompt.submit   tool.call    │
                              │  turn.start      turn.complete│
                              │  session.compact ui.render    │
                              └──────┬─────────────────▲──────┘
                       events, in    │                 │  allow · deny · rewrite
                       order, live   ▼                 │  panes · toasts · status
                              ┌──────────────────────────────┐
                              │  claude-mods (one plugin each)│
                              │                               │
                              │  guardrails ── may deny ──────┤
                              │  prompt-coach ─ may ask you ──┤
                              │  activity · changes · notify  │
                              │  usage-meter · context-keeper │──▶ .claude/checkpoints/
                              │  toolbox · command-hub ...    │──▶ OS notifications
                              └──────────────────────────────┘

What a mod sees. Each mod registers hooks on engine events. A tool.call hook sits in front of every tool the agent runs (Bash, Edit, MCP tools, subagents) and sees its real arguments before anything executes. That is how activity can show the exact command and guardrails can refuse it.

What it can change. A hook either passes the event on, rewrites it, or answers it itself. Guardrails answers with a denial the model reads ("blocked by the user's guardrails, don't work around it"). Prompt-coach never rewrites on its own: it asks you first, in Claude Code's own question dialog.

What it draws. Panels are ui.render hooks returning a small element tree (Box, Text, Button, Input) that Claude Code draws natively in the terminal and the desktop app. State lives in the engine ($.state), so panels survive a hot reload and redraw only when their data changes.

What it costs. Nothing, for nine of the mods. They read numbers the engine already has ($.session.usage(), $.tool.list(), $.command.list()). The two model calls are opt-out and listed under Honest limits.


🚀 Quick Start

Prerequisites: Claude Code 2.1.286 or newer (claude update). Panels dock beside the chat in the desktop app or a terminal ≥ 144 columns wide, and open inline in narrower terminals.

1. Add the marketplace and the manager

From any terminal:

claude plugin marketplace add mishgoldenberg/claude-mods
claude plugin install mod-manager@claude-mods

(In the Claude Code CLI you can also use /plugin marketplace add mishgoldenberg/claude-mods and the /plugin menu.)

2. Pick your mods

Restart Claude Code. The first session says hello once ("claude-mods ready: /mods to pick your set"). Type /mods: the manager lists every mod with what it does, whether it uses tokens, and whether an update is available. Install, turn on or off, update, or remove each one with a click, or apply a preset:

PresetWhat you get
Safety onlyguardrails, notify
Essentialsguardrails, activity, notify, context-keeper, usage-meter
Zero tokensevery mod that never calls a model
Everythingall eleven

Presets turn off what they don't list and never remove anything. Changes apply in your next session.

3. Use the quickbar

With quickbar installed, a one-line bar sits above the prompt: live context % and a button for every installed panel. /quickbar (or its ×) hides it; /quickbar again brings it back.

Or just ask Claude: "Install the claude-mods plugins from github.com/mishgoldenberg/claude-mods. Follow its INSTALL-FOR-CLAUDE.md."

VS Code

The VS Code extension has no /plugin menu, so install from a terminal with the two commands in step 1, then use /mods inside VS Code. Mods need the extension to run Claude Code 2.1.286 or newer.

for m in quickbar context-keeper usage-meter notify activity guardrails          prompt-coach toolbox command-hub changes loop-breaker; do
  claude plugin install "$m@claude-mods"
done

Try one without installing

git clone https://github.com/mishgoldenberg/claude-mods.git
claude --plugin-dir claude-mods/plugins/activity --plugin-dir claude-mods/plugins/guardrails

💬 Commands

CommandModWhat it does
/modsmod-managerInstall, turn on or off, update, or remove mods; apply a preset
/quickbarquickbarShow or hide the launcher above the prompt
/ctxcontext-keeperOpen the context panel
/checkpointcontext-keeperSave a handoff note of this session now
/resume-checkpointcontext-keeperLoad the latest checkpoint into the prompt box (use after /clear)
/meterusage-meterOpen plan limits, burn rate and cost
/notificationsnotifyOpen the notification inbox
`/mute [on\off]`notifyMute or unmute notifications
/activityactivityOpen the live activity panel
/guardguardrailsOpen the rules panel
`/guard-preset <safe\locked\review\off>`guardrailsApply a preset
/guard-log [json]guardrailsWhat guardrails blocked in the last 7 days
`/coach [on\off]`prompt-coachTurn the prompt coach on or off
/toolstoolboxOpen the tools panel and project suggestions
/cmdscommand-hubOpen the command hub
/new-commandcommand-hubCreate your own slash command
/changeschangesOpen the changed-files panel

⚙️ Configuration Reference

Options appear in /config once a mod is installed, or go in ~/.claude/settings.json under pluginConfigs.<mod>.

context-keeper

OptionDefaultDescription
warnAt70Toast a tip when context passes this %
checkpointAt85Write a handoff note automatically at this % (0 = off)

usage-meter

OptionDefaultDescription
warnAt80Toast when a plan window passes this % (a second toast always fires at 95%)

notify

OptionDefaultDescription
minSeconds30Only notify for turns at least this long
osNotifytrueAlso raise a native OS notification
approvalWaitSeconds15Ping when an approval has waited this long (-1 = off)

activity · prompt-coach · loop-breaker

ModOptionDefaultDescription
activityautoOpenfalseDock the panel on session start when there is room
prompt-coachenabledtrueReview prompts before sending
prompt-coachmodelclaude-haiku-4-5Reviewer model; small keeps the delay near a second
prompt-coachminChars8Never review prompts shorter than this
loop-breakerfailLimit3Same failing command this many times in a row
loop-breakereditLimit3Times the same code is rewritten in one turn (separate edits to different parts of a file never count)

guardrails rules

RuleBlocksIn preset
no-rm-rfrm -rf, rm -fr, Remove-Item -Recurse -Force, rmdir /sSafe · Locked
no-mass-deletekubectl/oc delete --all or -A, delete namespace/project, helm uninstall, terraform destroySafe · Locked · Review
no-force-pushgit push --force / -f (--force-with-lease allowed)Safe · Locked
no-history-rewritegit reset --hard, git clean -f, git checkout -- ., branch -D, stash drop, fetch/pull --prune, remote pruneSafe · Locked
protect-secretsreading or writing .env*, *.pem, *.key, id_rsa, credentials filesSafe · Locked · Review
no-sudosudo, su -, runasSafe · Locked · Review
no-installsnpm i, pip install, cargo add, brew/apt/winget install …Review
no-networkWebFetch, WebSearch, curl, wget, Invoke-WebRequest—
jail-writesWrite/Edit outside the project folder—
jail-allany file tool outside the project, cd out of itLocked
read-onlyall edits; shell limited to look-only commandsReview

Guardrails turns on Safe defaults the first time it loads. /guard-preset off turns everything off.

Whatever the preset, while any rule is on:

  • Scripts are checked before they run. A file the agent creates with Write in this session (and edits after that) is remembered, and when a shell command runs it (bash cleanup.sh, python tools/x.py, ./run, node a.mjs), its code is checked against your enabled rules and patterns first. os.system("rm -rf …") inside a Python file counts.
  • The agent can't edit guardrails' own settings. Write/Edit on them, and the obvious shell writes (sed -i, >, tee, cp, mv, rm), are denied with the same "ask the user" message.
  • Blocks are logged. Every block is kept for 30 days on this machine. The panel shows the last 7 days by rule, /guard-log prints a summary (/guard-log json for the raw list), and clear wipes it. Commands are cut to 200 characters.

🔒 Is it safe to install?

Mods run inside Claude Code with your permissions and no sandbox, so this is the right question to ask about any mod, including these. What these ones do:

  • No network. No mod makes a web request, and there is no telemetry. Nothing leaves your machine except the two opt-in model calls below, which go through your own Claude Code session like any prompt.
  • Processes they start, all of them: git diff --numstat (changes), the claude plugin CLI when you open /mods or click in it (mod-manager; only Install, Update and Check for updates go online, through Claude Code's own plugin installer), your OS notification tool (notify), and gh --version to see whether the GitHub CLI exists (toolbox).
  • Files they write: checkpoints and pre-compaction archives under .claude/checkpoints/ (context-keeper), and a new slash command file when you use the form (command-hub). Settings, and guardrails' 30-day block log, live in Claude Code's own plugin store under ~/.claude. Nothing else.
  • Model calls: prompt-coach and context-keeper's handoff note, both listed below and both easy to turn off.

Every mod is a few hundred lines of TypeScript in plugins/<mod>/hooks/register.tsx. Read the ones you install.


⚠️ Honest limits

  • Guardrails is a seatbelt, not a sandbox. Rules are pattern checks on the commands and paths the agent passes to tools. Scripts the agent wrote this session are checked before they run, but a script that arrives another way (downloaded, generated by a shell command, already in the repo) or an obfuscated command gets through, and so can a shell trick that rewrites guardrails' settings. Quoted prose (commit messages, text written to files) is ignored so that mentioning rm -rf doesn't block you, except when the text is handed to a shell (bash -c, | sh, powershell -Command), which is checked. For hard guarantees use Claude Code's permission rules and sandboxing; use guardrails to catch the honest mistakes.
  • prompt-coach costs a little. A reviewed prompt waits about a second for a small model, and uses a few hundred tokens. When you send the improved version, the chat still shows what you typed; a dim "prompt-coach sent the improved version" line below it shows what was actually sent. Short replies are never reviewed. /coach off turns it off.
  • context-keeper's handoff note costs a little. It asks the model for a summary over the already-cached conversation, so it is mostly cache reads. The pre-compaction archive costs nothing.
  • Function hooks are early access. A Claude Code update can break a mod. CI validates every mod against the engine's own validator, and issues are welcome.

🗂️ Project Structure

claude-mods/
├── .claude-plugin/
│   └── marketplace.json        The marketplace: one entry per mod
├── plugins/
│   ├── activity/
│   │   ├── .claude-plugin/
│   │   │   └── plugin.json     Name, description, userConfig options
│   │   ├── hooks/
│   │   │   ├── hooks.json      Points at the hooks module
│   │   │   └── register.tsx    The mod: hooks, commands, panel
│   │   ├── tests/
│   │   │   └── surfaces.test.tsx   The panel draws on every surface (claude plugin test)
│   │   └── types/
│   │       └── index.d.ts      Its $.state contract
│   ├── guardrails/             …same shape for every mod
│   └── …
├── docs/
│   └── design.md               The shared design spec and kit every mod copies
├── tests/
│   ├── guardrails-rules.test.mjs   Every rule against real commands
│   └── design-kit.test.mjs     Every mod's kit matches docs/design.md
├── INSTALL-FOR-CLAUDE.md       Steps Claude follows when asked to install
└── tsconfig.json               Type-checks all mods against the engine API

🔧 Extending it

Add a guardrail rule. Append an entry to RULES in plugins/guardrails/hooks/register.tsx (an id, a title, and a test that returns the offending text) and add cases to tests/guardrails-rules.test.mjs. The panel and presets pick it up automatically.

Add an essential command. One line in ESSENTIALS in plugins/command-hub/hooks/register.tsx. It only shows when that command exists in the user's Claude Code.

Write a new mod. Copy plugins/changes (a small mod with a panel) or plugins/loop-breaker (no UI), rename it everywhere, and add it to marketplace.json. Or ask Claude Code to "make a mod that …": it has a built-in skill for exactly this, with hot reload.


🤝 Contributing

Issues and pull requests are welcome. Start with CONTRIBUTING.md, which has the mod checklist.

npm install
npm run typecheck
npm test
claude plugin validate plugins/<mod>
claude plugin test plugins/<mod>

Every mod follows one design spec, docs/design.md: theme colors only (Claude orange as the single accent), the same pane header, glyphs, hotkeys and empty states, so the set feels like one product in any theme.

Two house rules worth knowing before you write anything, because the validator enforces both:

  • Helpers that take $ must be top-level function declarations. A closure inside register that receives $ is rejected.
  • Every $.state key is declared in the mod's types/index.d.ts, under the mod's name.

Found a way around guardrails, or another security problem? Please report it privately; see SECURITY.md.


📄 License

MIT © 2026 Michael Goldenberg

Source 2 files
hooks/register.tsx 299 lines
1import { atom, read, update } from 'claude-code'
2import type { ElementTable, EngineInterface, Register, RenderChildren } from 'claude-code'
3
4import type { CommandDraft, CommandRow } from '../types'
5
6// ── claude-mods kit v1 (docs/design.md): identical in every mod ──
7const TONE = { accent: 'claude', ok: 'success', warn: 'warning', bad: 'error', dim: 'inactive' } as const
8const GLYPH = { on: '●', off: '○', warn: '▲', ok: '✓', fail: '✗' } as const
9type Kit = Pick<ElementTable, 'Box' | 'Text'>
10
11/** Pane header: state glyph, mod name, one-line live status. */
12function header({ Box, Text }: Kit, glyph: string, tone: string, name: string, status: string) {
13  return (
14    <Box gap={1}>
15      <Text color={tone}>{glyph}</Text>
16      <Text bold>{name}</Text>
17      <Text dimColor wrap="truncate-end">{status}</Text>
18    </Box>
19  )
20}
21
22/** A section: a dim label (with optional small controls beside it), then its rows. */
23function section({ Box, Text }: Kit, label: string, rows: RenderChildren, aside?: RenderChildren) {
24  return (
25    <Box flexDirection="column">
26      <Box gap={1}>
27        <Text dimColor>{label}</Text>
28        {aside}
29      </Box>
30      {rows}
31    </Box>
32  )
33}
34
35/** A number right-aligned in a fixed-width cell. */
36function num({ Box, Text }: Kit, value: string, width: number, color?: string) {
37  return (
38    <Box width={width} flexShrink={0} justifyContent="flex-end">
39      <Text color={color}>{value}</Text>
40    </Box>
41  )
42}
43
44/** Empty state: what will show up here, and how to get it. */
45function empty({ Text }: Kit, text: string) {
46  return <Text dimColor>{text}</Text>
47}
48// ── end kit ──
49
50const PANE = 'command-hub'
51const commands = atom({ plugin: 'command-hub', key: 'commands' } as const, [])
52const query = atom({ plugin: 'command-hub', key: 'query' } as const, '')
53const tab = atom({ plugin: 'command-hub', key: 'tab' } as const, 'essentials' as 'essentials' | 'all' | 'create')
54const draft = atom({ plugin: 'command-hub', key: 'draft' } as const, { name: '', description: '', body: '', scope: 'project' } as CommandDraft)
55
56/** The built-in commands people most often don't know about, and when to reach for them. Shown only if present. */
57const ESSENTIALS: { name: string; when: string }[] = [
58  { name: 'compact', when: 'Context getting full? Summarizes the chat to free space. Add text to say what to keep: /compact keep the API design' },
59  { name: 'clear', when: 'Switching to an unrelated task: fresh context, same window. Cheaper and sharper than one endless chat.' },
60  { name: 'context', when: 'See exactly what is eating your context window (files, MCP tools, messages).' },
61  { name: 'rewind', when: 'Undo: roll code and/or conversation back to an earlier message (also Esc Esc).' },
62  { name: 'resume', when: 'Reopen an earlier session with its full history.' },
63  { name: 'btw', when: 'Ask a quick side question without derailing the main task.' },
64  { name: 'init', when: 'New project? Generates CLAUDE.md so Claude knows your build/test commands and conventions.' },
65  { name: 'memory', when: 'Edit the CLAUDE.md files loaded every session: put "always do X" rules here.' },
66  { name: 'model', when: 'Switch model: bigger for hard design/debugging, smaller for quick edits.' },
67  { name: 'effort', when: 'Trade speed for depth of thinking.' },
68  { name: 'plan', when: 'Make Claude propose a plan before touching code.' },
69  { name: 'permissions', when: 'Tired of approving the same command? Allow-list it (or deny things forever).' },
70  { name: 'add-dir', when: 'Let Claude work in another folder too (e.g. a shared library repo).' },
71  { name: 'agents', when: 'Create specialised subagents (reviewer, tester…) with their own prompts and tools.' },
72  { name: 'mcp', when: 'Connect or debug MCP servers (databases, browsers, issue trackers…).' },
73  { name: 'hooks', when: 'Run your own scripts automatically: format after edit, block commands, notify…' },
74  { name: 'review', when: 'Have Claude review a pull request or your local changes.' },
75  { name: 'code-review', when: 'Review the current diff for bugs at an effort level you choose.' },
76  { name: 'security-review', when: 'Security pass over your pending changes.' },
77  { name: 'export', when: 'Save the conversation to a file or the clipboard.' },
78  { name: 'usage', when: 'Your plan limits and when they reset.' },
79  { name: 'plugin', when: 'Browse and install plugins and mod collections like this one.' },
80  { name: 'statusline', when: 'Customise the line under the prompt (branch, cost, context…).' },
81  { name: 'doctor', when: 'Something broken? Diagnoses your install and settings.' },
82]
83
84/** Phrases in a prompt that mean a built-in command would do the job better. */
85const HINTS: { re: RegExp; name: string; tip: string }[] = [
86  { re: /\b(undo|revert|go back|roll ?back)\b/i, name: 'rewind', tip: '/rewind (or Esc Esc) restores code and chat to an earlier point.' },
87  { re: /\b(remember|from now on|always (use|do)|every time)\b/i, name: 'memory', tip: 'For rules that should stick across sessions, put them in CLAUDE.md via /memory.' },
88  { re: /\b(new task|unrelated|different (topic|thing)|start over)\b/i, name: 'clear', tip: 'Switching topics? /clear gives a fresh, cheaper context.' },
89  { re: /\b(yesterday|last session|previous session|earlier session)\b/i, name: 'resume', tip: '/resume reopens an earlier session with its full history.' },
90  { re: /\b(another|other|second) (folder|directory|repo)\b/i, name: 'add-dir', tip: '/add-dir gives Claude access to another folder.' },
91  { re: /\b(stop asking|keeps asking|approve every)\b/i, name: 'permissions', tip: '/permissions lets you allow-list commands you trust.' },
92  { re: /\bsecurity\b|\bvulnerab/i, name: 'security-review', tip: '/security-review runs a dedicated security pass on your changes.' },
93  { re: /\breview (my|the|this) (pr|pull request|changes|diff|code)\b/i, name: 'review', tip: '/review is built for exactly this.' },
94]
95
96const NAME_OK = /^[a-z0-9][a-z0-9-]{0,40}$/
97
98async function loadCommands($: EngineInterface) {
99  const list = await $.command.list()
100  await update($, commands, () => list.map(c => ({ name: c.name, description: c.description, source: c.plugin ? `plugin: ${c.plugin}` : c.source })))
101}
102
103async function saveDraft($: EngineInterface) {
104  const d = await read($, draft)
105  const name = d.name.trim().replace(/^\//, '')
106  if (!NAME_OK.test(name)) {
107    $.ui.toast('Name: lowercase letters, digits and dashes only.')
108    return
109  }
110  if (d.body.trim() === '') {
111    $.ui.toast('Write what the command should tell Claude to do.')
112    return
113  }
114  if ((await read($, commands)).some(c => c.name === name)) {
115    $.ui.toast(`/${name} already exists; pick another name.`)
116    return
117  }
118  const home = (await $.env.get('HOME')) ?? (await $.env.get('USERPROFILE')) ?? ''
119  const dir = d.scope === 'user' ? `${home}/.claude/commands` : `${await $.session.root()}/.claude/commands`
120  const path = `${dir}/${name}.md`.replace(/\\/g, '/')
121  if (await $.fs.exists(path)) {
122    $.ui.toast(`${path} exists already.`)
123    return
124  }
125  const hasArgs = d.body.includes('$ARGUMENTS')
126  const front = [`description: ${d.description.trim() || name}`, ...(hasArgs ? ['argument-hint: <details>'] : [])].join('\n')
127  await $.fs.write(path, `---\n${front}\n---\n\n${d.body.trim()}\n`)
128  await update($, draft, (): CommandDraft => ({ name: '', description: '', body: '', scope: d.scope }))
129  $.ui.toast(`Saved /${name} → ${path}. It shows in the / menu (restart if it doesn't yet).`, { timeoutMs: 9000 })
130}
131
132async function open($: EngineInterface, view: 'essentials' | 'all' | 'create') {
133  await loadCommands($)
134  await update($, tab, () => view)
135  await $.ui.open({ id: PANE, title: 'Commands' })
136}
137
138export const register: Register = on => {
139  const tipped = new Set<string>()
140
141  on('session.start', async ($, e, next) => {
142    await $.command.register({ name: 'cmds', description: 'Command hub: discover, search and create slash commands' })
143    await $.command.register({ name: 'new-command', description: 'Create your own slash command (opens the form)' })
144    void loadCommands($)
145
146    return next(e)
147  })
148
149  on('command.run', { command: 'cmds' }, async $ => {
150    await open($, 'essentials')
151
152    return { text: 'Command hub opened.' }
153  })
154
155  on('command.run', { command: 'new-command' }, async $ => {
156    await open($, 'create')
157
158    return { text: 'Command creator opened.' }
159  })
160
161  on('prompt.submit', async ($, e, next) => {
162    const available = new Set((await read($, commands)).map(c => c.name))
163    for (const hint of HINTS) {
164      if (!tipped.has(hint.name) && available.has(hint.name) && hint.re.test(e.text)) {
165        tipped.add(hint.name)
166        $.ui.toast(`Tip: ${hint.tip}`, { timeoutMs: 9000 })
167        break
168      }
169    }
170
171    return next(e)
172  })
173
174  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
175    const els = $.ui.resolve(e)
176    const { Box, Text, Button } = els
177    const Input = 'Input' in els ? els.Input : undefined
178    const Select = 'Select' in els ? els.Select : undefined
179    const list = await read($, commands)
180    const view = await read($, tab)
181    const q = (await read($, query)).toLowerCase()
182    const d = await read($, draft)
183    const names = new Set(list.map(c => c.name))
184    const use = (name: string) => () => void $.prompt.fill({ text: `/${name} ` })
185    const kit = { Box, Text }
186    const top = header(kit, GLYPH.on, TONE.accent, 'command-hub', list.length === 0 ? 'reading commands…' : `${list.length} commands installed`)
187
188    const tabs = (
189      <Box gap={1}>
190        {(['essentials', 'all', 'create'] as const).map((v, i) => (
191          <Button key={`tab-${v}`} hotkey={String(i + 1)} variant={view === v ? 'primary' : 'secondary'} label={v === 'create' ? '+ create' : v} onPress={() => void update($, tab, () => v)} />
192        ))}
193      </Box>
194    )
195
196    if (view === 'essentials') {
197      const shown = ESSENTIALS.filter(x => names.has(x.name))
198
199      return (
200        <Box flexDirection="column" gap={1}>
201          {top}
202          {tabs}
203          {section(
204            kit,
205            'Built-ins worth knowing · click one to put it in the prompt box',
206            <Box flexDirection="column">
207              {shown.length === 0 && empty(kit, 'Reading the commands this Claude Code has… they appear here in a moment.')}
208              {shown.map(x => (
209                <Box flexDirection="column">
210                  <Button key={`use-${x.name}`} plain label={`/${x.name}`} onPress={use(x.name)} />
211                  <Box paddingLeft={3}>
212                    <Text dimColor>{x.when}</Text>
213                  </Box>
214                </Box>
215              ))}
216            </Box>,
217          )}
218        </Box>
219      )
220    }
221
222    if (view === 'all') {
223      const filtered = list.filter(c => q === '' || c.name.toLowerCase().includes(q) || c.description.toLowerCase().includes(q))
224      const bySource = new Map<string, CommandRow[]>()
225      for (const c of filtered) bySource.set(c.source, [...(bySource.get(c.source) ?? []), c])
226
227      return (
228        <Box flexDirection="column" gap={1}>
229          {top}
230          {tabs}
231          {Input !== undefined && <Input key="search" placeholder="search commands…" value={q} onInput={(v: string) => void update($, query, () => v)} onSubmit={(v: string) => void update($, query, () => v)} />}
232          <Text dimColor>
233            {filtered.length} of {list.length} commands
234          </Text>
235          {filtered.length === 0 && empty(kit, q === '' ? 'Reading the installed commands… they appear here in a moment.' : `No command matches "${q}". Try a shorter word, or clear the search.`)}
236          {[...bySource.entries()].map(([source, rows]) =>
237            section(
238              kit,
239              source,
240              rows.map(c => (
241                <Box gap={1}>
242                  <Button key={`all-${c.name}`} plain label={`/${c.name}`} onPress={use(c.name)} />
243                  <Text dimColor wrap="truncate-end">
244                    {c.description}
245                  </Text>
246                </Box>
247              )),
248            ),
249          )}
250        </Box>
251      )
252    }
253
254    return (
255      <Box flexDirection="column" gap={1}>
256        {top}
257        {tabs}
258        <Text dimColor>A slash command is a saved prompt. Use $ARGUMENTS where text typed after the command should go.</Text>
259        {Input === undefined ? (
260          <Text>This surface has no text input; use /new-command in the terminal or desktop app.</Text>
261        ) : (
262          <Box flexDirection="column" gap={1}>
263            <Input key="name" label="Name  /" placeholder="e.g. ship" value={d.name} onInput={(v: string) => void update($, draft, x => ({ ...x, name: v }))} onSubmit={(v: string) => void update($, draft, x => ({ ...x, name: v }))} />
264            <Input key="desc" label="Shown in menu" placeholder="e.g. Run tests, then commit and push" value={d.description} onInput={(v: string) => void update($, draft, x => ({ ...x, description: v }))} onSubmit={(v: string) => void update($, draft, x => ({ ...x, description: v }))} />
265            <Input
266              key="body"
267              label="Prompt"
268              placeholder="e.g. Run the test suite. If green, commit with a good message and push. Focus: $ARGUMENTS"
269              value={d.body}
270              onInput={(v: string) => void update($, draft, x => ({ ...x, body: v }))}
271              onSubmit={(v: string) => void update($, draft, x => ({ ...x, body: v }))}
272            />
273            {Select !== undefined && (
274              <Select
275                key="scope"
276                label="Save for"
277                value={d.scope}
278                options={[
279                  { value: 'project', label: 'This project (.claude/commands, shareable via git)' },
280                  { value: 'user', label: 'Me, everywhere (~/.claude/commands)' },
281                ]}
282                onSelect={(v: string) => void update($, draft, (x): CommandDraft => ({ ...x, scope: v === 'user' ? 'user' : 'project' }))}
283              />
284            )}
285            <Box gap={1}>
286              <Button key="save" variant="primary" label="Save command" onPress={() => void saveDraft($)} />
287              <Button
288                key="help"
289                label="Draft it with Claude"
290                onPress={() => void $.prompt.fill({ text: `Help me write a Claude Code slash command (a markdown file in .claude/commands) that ${d.description || d.body || '…'}. Ask me anything you need, then create it.` })}
291              />
292            </Box>
293          </Box>
294        )}
295      </Box>
296    )
297  })
298}
299
types/index.d.ts 15 lines
1export type CommandRow = { name: string; description: string; source: string }
2
3export type CommandDraft = { name: string; description: string; body: string; scope: 'project' | 'user' }
4
5declare module 'claude-code' {
6  interface PluginState {
7    'command-hub': {
8      commands: CommandRow[]
9      query: string
10      tab: 'essentials' | 'all' | 'create'
11      draft: CommandDraft
12    }
13  }
14}
15