Looks up every package Claude installs on npm or PyPI before the command runs, and holds the install for a yes when the name is missing or under 30 days old

Small cards that sit under the Claude Code prompt, or docked beside the transcript in fullscreen. Each widget is its own mod, toggled with a slash command.
It started with a few useful ones (context, usage, file tree) and then got carried away: there are now 95 widgets, from git status and a turn timer to a pixel crab, a dungeon crawl and Tetris.
Try every widget in its own little terminal on the demo page: the real widget code runs in the browser against a simulated session, so you can type its slash commands, run a turn and play the games. It is a static page in docs/, published to GitHub Pages on every push to main that changes it; opening docs/index.html from a checkout works too.
Add the marketplace, then install the layout plugin and whichever widgets you want:
/plugin marketplace add oMaN-Rod/claude-code-widgets
/plugin install widgets@claude-code-widgets
/plugin install context-widget@claude-code-widgets
Every widget needs widgets, the layout plugin that places the cards.
Requires a Claude Code version with mod (function hook) support. The mod API is early access and may change between releases.
Required by every widget.
| Plugin | Command | What it shows | ||||||
|---|---|---|---|---|---|---|---|---|
widgets | `/widgets [side\ | above\ | below\ | close\ | <columns>\ | width <widget> <columns\ | reset>]` | Places the cards: below the prompt, above it, or docked beside the transcript in fullscreen |
What Claude is doing and what it is costing.
| Plugin | Command | What it shows | ||||||||
|---|---|---|---|---|---|---|---|---|---|---|
context-widget | `/context-widget [auto\ | detailed\ | grid\ | top\ | bar\ | line]` | The context window as a stacked bar, one colour per /context category | |||
usage-widget | /usage-widget | A bar per rate-limit window, time to reset, session cost | ||||||||
timer-widget | `/timer-widget [on\ | off\ | clear]` | The running turn's elapsed time, plus last, average and longest turn and a sparkline | ||||||
activity-widget | `/activity-widget [on\ | off\ | clear]` | The latest tool calls with their duration and whether they failed | ||||||
tasks-widget | `/tasks-widget [on\ | off\ | clear]` | The task list Claude is working through, with a progress bar | ||||||
checks-widget | `/checks-widget [on\ | off\ | clear]` | The latest test, lint and build runs: pass or fail, duration and how long ago | ||||||
timeline-widget | `/timeline-widget [on\ | off]` | The turn as a chart: one bar per tool call on a time axis, parallel calls stacked | |||||||
board-widget | `/board-widget [on\ | off\ | clear]` | A status board Claude writes itself through a pin tool: goal, findings and open questions | ||||||
forecast-widget | `/forecast-widget [on\ | off\ | clear]` | Context growth per turn as a chart, with the turns left before compaction; warns once when three or fewer are left | ||||||
guard-widget | `/guard-widget [on\ | off\ | clear]` | Permission checks this session: allowed, asked and denied, with what you keep being asked about | ||||||
stream-widget | `/stream-widget [on\ | off]` | A live tokens-per-second gauge and sparkline while Claude is writing (estimated from text length) | |||||||
sessions-widget | /relay <number> <message>, `/sessions-widget [on\ | off]` | Every Claude Code session open on this machine: folder, branch, working or waiting and for how long; /relay 1 <message> sends a line to one | |||||||
collision-widget | `/collision-widget [on\ | off\ | clear]` | Stops an edit to a file another Claude Code session on this machine changed since this one last read it, and has Claude read it again first | ||||||
sieve-widget | `/sieve-widget [on\ | off]` | A compaction that keeps every word you and Claude said and folds only the old tool traffic, with no summary and no tokens spent | |||||||
redact-widget | `/redact-widget [on\ | off\ | clear]` | Replaces API keys, tokens, private keys and passwords in command output and file reads before Claude sees them | ||||||
notebook-widget | `/notebook-widget [on\ | off\ | show\ | drop <number>\ | clear]` | Gives Claude a jot tool for writing down what its future self should know about this project, and reads the notes back next session | ||||
footnotes-widget | `/footnotes-widget [on\ | off\ | show\ | clear]` | Checks every file path, cited line and code symbol in Claude's last reply against the working tree, with no model call, and flags the ones that are not there | |||||
witness-widget | `/witness-widget [on\ | off\ | show\ | clear]` | Every line of hidden context the other widgets add to your prompts, word for word, with a running size | |||||
queue-widget | `/queue-widget [on\ | off\ | add <prompt>\ | until <command\ | off>\ | start\ | drop <number>\ | report\ | clear]` | A queue of prompts that run back to back while you are away, a gate command each must pass before the next starts, and a report of how each one ended |
done-widget | `/done-widget [on\ | off\ | add <criterion>\ | drop <number>\ | show\ | clear]` | A definition of done you write once: Claude ticks each item with evidence through its tick tool, and is pulled up when it says done with items open | |||
trial-widget | `/trial-widget [on\ | off\ | test <widget>\ | clear]` | A fair test of another widget: sessions alternate with it on and off, and the card compares how many turns end clean | |||||
aside-widget | `/aside-widget [on\ | off\ | ask <question>\ | clear]` | Ask a side question about the conversation, even mid-turn, and get the answer on a card without adding a turn to the transcript | |||||
tap-widget | `/tap-widget [on\ | off\ | list [word]\ | add <server> <tool> [json] [anyway]\ | run <n>\ | show <n>\ | drop <n>\ | clear]` | One line per tool of your connected MCP servers, called by the widget on a clock with no model: pull requests, errors, the next meeting | |
margin-widget | `/margin-widget [on\ | off\ | mark [remark]\ | drop <n>\ | send\ | clear]` | Mark passages of Claude's reply with the mouse, write a remark against each, and send them back as one quoted prompt | |||
loupe-widget | `/loupe-widget [on\ | off\ | look [text]\ | copy]` | Select a hash, path, name, timestamp or colour in the transcript with the mouse and the card says what it is, with no model call | |||||
strays-widget | `/strays-widget [on\ | off\ | stop <port>\ | forget <port>\ | clear]` | Servers this session started that still hold a port, with age and turn, one verb to stop one, and the survivors shown when the next session opens | ||||
premise-widget | `/premise-widget [on\ | off\ | show\ | fix <n>\ | clear]` | Quotes thinking-summary sentences that name a gap and a choice made anyway, unless the reply flags it, and starts your correction; no model call; needs "showThinkingSummaries": true in settings.json | ||||
earpiece-widget | `/earpiece-widget [on\ | off], /whisper <number> <note>` | Every running subagent with the tool it is on and its last sentence, and /whisper slips one of them a note without stopping the turn | |||||||
pen-widget | `/pen-widget [on\ | off\ | show\ | clear]` | The file, edit or command Claude is writing right now, drawn line by line as the tool call's arguments stream in, before the tool runs | |||||
outage-widget | `/outage-widget [on\ | off\ | check\ | clear]` | When a push or install fails on the network, checks the provider's status page and says whether GitHub, npm, PyPI or crates.io reports an incident | |||||
landmarks-widget | `/landmarks-widget [on\ | off\ | list\ | go <n>\ | clear]` | A numbered table of contents for the session, built as it happens from prompts, first edits, checks turning red or green, commits and questions; press a line to scroll the transcript to it | ||||
seen-widget | `/seen-widget [on\ | off\ | show\ | open [n]\ | clear]` | The pictures Claude looked at this session, image files it read and screenshots that came back from tools, drawn as Claude received them and opened full size with one command | ||||
amendments-widget | `/amendments-widget [on\ | off\ | show [n]\ | clear]` | What changed in the system prompt and the built-in tool descriptions Claude Code gives Claude since the version you last ran, with the before and after one command away | |||||
skimmed-widget | `/skimmed-widget [on\ | off\ | show\ | clear]` | The caveats in Claude's replies that left your screen while Claude was still writing and have not been back, quoted in full; it never claims that what was on screen was read | |||||
attic-widget | `/attic-widget [on\ | off\ | show\ | keep <tool>\ | stow <tool>\ | clear]` | Counts which tools Claude calls in this project, puts the unused ones behind ToolSearch, lists the daily ones up front, and reports how many schema tokens each request no longer carries | |||
rehearsal-widget | `/rehearsal-widget [on\ | off\ | show\ | forget <n>\ | clear]` | Which of the commands and edits Claude has made in this project would stop for permission or be refused right now, asked of the engine's own permission check without running anything | ||||
aim-widget | `/aim-widget [on\ | off\ | prod <word>\ | unprod <word>\ | show\ | clear]` | Where a command lands outside this folder: the kube context, cloud profile, Terraform workspace or database it is aimed at, named in the permission dialog | |||
earshot-widget | `/earshot-widget [on\ | off\ | last\ | clear]` | Whether Claude has got the message you typed while it was working: how late a request first carried it, and what Claude changed before it heard you |
The state of the working tree.
| Plugin | Command | What it shows | |||||
|---|---|---|---|---|---|---|---|
file-tree-widget | /file-tree-widget | The project directory; folders expand on click | |||||
git-widget | /git-widget | Branch, ahead/behind, staged, changed and untracked counts, and the last commit | |||||
changes-widget | `/changes-widget [on\ | off\ | clear]` | Files edited this session, most recent first, with an edit count each | |||
commits-widget | /commits-widget | The commits made since the session started | |||||
todos-widget | /todos-widget | TODO, FIXME, HACK and XXX comments in tracked files, counted and listed | |||||
diff-widget | `/diff-widget [on\ | off\ | clear]` | The last edit as a syntax-highlighted diff | |||
watch-widget | `/watch-widget [on\ | off\ | run\ | stop], /watch <command>` | /watch bun test reruns the command after every edit: a pass or fail light and the last failing lines | ||
map-widget | `/map-widget [on\ | off\ | clear]` | A pixel map of the tracked files, lit blue where Claude has read and green where it has edited | |||
stakes-widget | `/stakes-widget [on\ | off\ | clear]` | What a yes would lose, measured from git and written under the permission dialog for a destructive command | |||
ledger-widget | `/ledger-widget [on\ | off\ | scan\ | show\ | clear]` | What a project has cost across every session, from any folder or worktree in it: measured as each turn ends, and read back from the sessions Claude Code saved | |
squiggle-widget | `/squiggle-widget [on\ | off\ | check [text]]` | Underlines file names that do not exist, as you type them in the prompt box, and paints the ones that do green | |||
critic-widget | `/critic-widget [on\ | off\ | review\ | tell\ | clear]` | A second pair of eyes: a separate model reads the uncommitted diff and lists only real defects, which you can hand to Claude | |
customs-widget | `/customs-widget [on\ | off\ | show\ | trust <name>\ | clear]` | Looks up every package Claude installs on npm or PyPI before the command runs, and holds the install for a yes when the name is missing or under 30 days old. Scoped names and installs that name a registry, or sit beside a project .npmrc that does, are not looked up; user-level and environment registry settings, bunfig.toml, .yarnrc.yml and pip and uv config files are not seen | |
provenance-widget | `/provenance-widget [on\ | off\ | scan\ | look [<path>:<line>]\ | copy\ | clear]` | The conversation behind a line of code: for lines Claude is about to edit, or a path:line you ask about, the prompt you typed before they were written and the command that resumes that session |
green-widget | `/green-widget [on\ | off\ | tell\ | clear]` | What changed in the working tree since each test, lint or build command last passed, measured against a hidden git snapshot taken at that moment and handed to Claude on request |
Clocks, timers and reminders that do not depend on the session.
| Plugin | Command | What it shows | |||||
|---|---|---|---|---|---|---|---|
pomodoro-widget | `/pomodoro-widget [on\ | off\ | start\ | break\ | stop\ | <minutes>]` | A focus timer with a countdown, a progress bar and a count of finished sessions |
countdown-widget | `/countdown-widget [on\ | off\ | clear], /countdown <HH:MM\ | <n>m\ | <n>h> [label]` | Time left to a deadline you set, with a progress bar and a toast when it arrives | |
clocks-widget | `/clocks-widget [on\ | off\ | add <zone>\ | remove <zone>\ | clear]` | Your local time beside the time zones you add, such as Asia/Tokyo | |
notes-widget | `/notes-widget [on\ | off\ | clear], /note <text\ | done <n>>` | Pinned notes kept across sessions; /note <text> adds one, /note done <n> removes it | ||
coffee-widget | `/coffee-widget [on\ | off\ | refill\ | <minutes>]` | A cup that empties over 90 minutes and nudges you to take a break |
Pixel art that reacts to turns, tool calls, checks and context usage.
| Plugin | Command | What it shows | |||
|---|---|---|---|---|---|
pet-widget | `/pet-widget [on\ | off\ | <mood>]` | Clawd, a pixel crab: works during a turn, dizzy when a tool call fails, happy when tests pass. Earns XP and levels up across sessions, wears a hat once badges-widget has awarded a badge, and with two sessions open stays in the one you last prompted. Remembers each project and greets you with how long you were away and whether the checks were red | |
aquarium-widget | `/aquarium-widget [on\ | off\ | demo]` | A fish for every running tool call and agent | |
skyline-widget | `/skyline-widget [on\ | off\ | demo\ | clear]` | One building per turn, one floor per tool call |
train-widget | `/train-widget [on\ | off]` | A locomotive pulling one wagon per tool call this turn, coloured by tool | ||
garden-widget | `/garden-widget [on\ | off\ | reset]` | A plant: a leaf per tool call, a flower when checks pass, wilting when a call fails | |
campfire-widget | `/campfire-widget [on\ | off\ | stoke]` | A campfire that burns higher with tool calls and dies down to embers when idle | |
constellation-widget | `/constellation-widget [on\ | off\ | clear]` | A star per turn, joined into a constellation that gets a name after nine | |
fireworks-widget | `/fireworks-widget [on\ | off\ | demo]` | A night sky that sets off fireworks when checks pass, and a dud when they fail | |
invaders-widget | `/invaders-widget [on\ | off\ | demo\ | clear]` | An invader arrives for every failing check; passing checks shoot them down |
weather-widget | `/weather-widget [on\ | off\ | live\ | <percent>]` | Clear sky when context has room, a storm near compaction |
boss-widget | `/boss-widget [on\ | off]` | Context usage as a boss health bar; compaction defeats it and starts the next level | ||
sky-widget | `/sky-widget [on\ | off]` | The sky at your local time: sun by day, moon by night, more stars the longer the session runs | ||
world-widget | `/world-widget [on\ | off\ | clear]` | One scene for everything: sky by the clock, weather by context, a tower per turn, a train of tool calls and a wandering crab | |
quest-widget | `/quest-widget [on\ | off\ | reset]` | The session as a dungeon crawl: a room per turn, a monster per tool call, loot when checks pass; the hero is kept across sessions | |
race-widget | `/race-widget [on\ | off\ | clear]` | Parallel subagents as cars on a track, one stride per tool call, with a podium as they finish | |
moon-widget | `/moon-widget [on\ | off\ | north\ | south]` | The real moon right now, drawn for your hemisphere, with a countdown to the next full moon and what it means for your deploy |
Abstract pictures driven by tool activity.
| Plugin | Command | What it shows | |||
|---|---|---|---|---|---|
mosaic-widget | `/mosaic-widget [on\ | off\ | clear]` | One tile per tool call, coloured by tool; failures are red | |
sorting-widget | `/sorting-widget [on\ | off\ | step]` | A bar chart being sorted, one swap per tool call | |
equalizer-widget | `/equalizer-widget [on\ | off]` | Level meters that jump with each tool call and fall back to rest | ||
rain-widget | `/rain-widget [on\ | off]` | Falling code rain that speeds up the busier the turn gets | ||
orbit-widget | `/orbit-widget [on\ | off]` | A small solar system; the planets speed up while tool calls run | ||
life-widget | `/life-widget [on\ | off\ | reset]` | Conway's Game of Life; every tool call drops a glider | |
donut-widget | `/donut-widget [on\ | off]` | The spinning 3D donut; it spins faster while tool calls run | ||
pipes-widget | `/pipes-widget [on\ | off]` | The pipes screensaver; it grows while the session is idle and pauses while Claude works | ||
maze-widget | `/maze-widget [on\ | off\ | new]` | A first-person walk through a maze seeded by the project folder | |
marquee-widget | `/marquee-widget [on\ | off\ | clear\ | <text>]` | An LED ticker scrolling session events; any other text posts your own headline |
Snake, 2048 and Tetris play themselves until you click the board and take the keys.
| Plugin | Command | What it shows | ||
|---|---|---|---|---|
snake-widget | `/snake-widget [on\ | off]` | Snake; it plays itself until you take the keys | |
2048-widget | `/2048-widget [on\ | off]` | 2048; it plays itself until you take the keys | |
tetris-widget | `/tetris-widget [on\ | off]` | Tetris; it plays itself until you take the keys | |
minesweeper-widget | `/minesweeper-widget [on\ | off]` | Minesweeper: click to reveal, right-click or f to flag, r to restart | |
breakout-widget | `/breakout-widget [on\ | off\ | reset]` | A self-playing brick breaker; every tool call adds a row of bricks |
typer-widget | `/typer-widget [on\ | off]` | A typing game: words from your own file names fall, and you type them before they land |
| Plugin | Command | What it shows | |||
|---|---|---|---|---|---|
fortune-widget | `/fortune-widget [on\ | off\ | next]` | A one-line fortune that changes with every turn | |
8ball-widget | `/8ball-widget [on\ | off], /8ball <question>` | /8ball <question> gives an answer of doubtful reliability | ||
badges-widget | `/badges-widget [on\ | off\ | reset]` | Achievements earned across sessions, with a toast when one unlocks | |
sigil-widget | `/sigil-widget [on\ | off\ | clear]` | A pixel emblem generated from this session's activity, beside a gallery of the ones from earlier sessions | |
sound-widget | `/sound-widget [on\ | off\ | mute\ | test]` | A note per tool call, a chord when checks pass, a buzz on failure, with a piano roll (audio plays on macOS only) |
Placement, which widgets are on, and view modes are saved and restored in every session.
/widgets width pet 60 sets how wide one widget's card may grow (the default is 40 columns); /widgets width pet reset puts it back./widgets side docks the cards beside the transcript only in the fullscreen layout (/tui fullscreen). In the default layout it falls back to below the prompt.sound-widget plays audio on macOS only; elsewhere it stays silent and just draws the piano roll.board-widget registers a pin tool that Claude can call, so its description is part of the context while the board is on.watch-widget runs your command through sh -c, falling back to cmd /c.Each plugin under plugins/ is a mod: a manifest, a hooks module and its tests.
claude --plugin-dir plugins # load every plugin from this checkout
claude plugin validate plugins/<name> # check a manifest and hooks module
claude plugin test plugins/<name> # run its tests
Plugin storage ($.store) is read once per session, so a widget that has to see other live sessions keeps a file under its own folder instead ($.plugin.root).
Plugins cannot import from one another, so widgets shares card stacking and the pixel renderer as $.widgets (plugins/widgets/hooks/kit.tsx), which every widget calls.
docs/ is the demo page. bun run site/build.ts bundles every widget's hooks module into docs/mods.js and writes docs/catalog.js from the tables above, so a new widget appears on the page once it has a row here. docs/engine.js is a small stand-in for the mod engine (state, store, clock, commands, a made-up project and a scripted turn), and docs/view.js draws the card trees. bun run site/smoke.ts boots every widget in that engine and runs a turn; a widget that needs an engine call the stand-in lacks shows up there. docs/widgets.js holds recordings from the real interface, shown only if a widget fails to start.
New widgets are made by the Widget Factory in factory/: a crew of Claude Code agents that takes each widget through ideation, design, build, inspection and shipping, with a different agent inspecting than built it. Clone the repository and you can run your own:
https://github.com/user-attachments/assets/6833eb82-8b2e-4b4c-80ca-4194d48d10e7
bun run --cwd factory setup # checks what you need and prepares the floor
bun run --cwd factory floor # the factory floor in your browser
bun run --cwd factory line # opens a Claude Code session that runs the line
https://github.com/user-attachments/assets/d0953871-4935-4fa9-8ab3-f58b51739a17
factory/README.md explains the stations, the crew, the widget standard and how to contribute a widget.
MIT
hooks/register.tsx 463 lines1import { atom, read, update } from 'claude-code'
2import type { Elements, EngineInterface, PluginState, Register, RenderElement, RenderSurface, ToolCheckResult } from 'claude-code'
3import type { WidgetsPlace } from 'widgets'
4
5import { fit, plural } from './lib'
6
7type Tags = Pick<Elements[RenderSurface], 'Box' | 'Text'>
8type Entry = PluginState['customs-widget']['list'][number]
9type Registry = Entry['registry']
10type Found = Pick<Entry, 'kind' | 'fact' | 'line'>
11type Wanted = Pick<Entry, 'key' | 'name' | 'registry'> & { asked: string; isPrivate: boolean }
12type NpmRecord = { time?: { created?: unknown }; 'dist-tags'?: { latest?: unknown } } | null | undefined
13type PypiRecord = { info?: { version?: unknown }; releases?: Record<string, { upload_time_iso_8601?: unknown }[]> } | null | undefined
14
15const PANE = 'widgets'
16const CARD_COLUMNS = 40
17const CARD_FRAME = 4
18const WIDE_COLUMNS = 30
19const TITLE = 'Customs'
20const USAGE = 'Usage: /customs-widget [on|off|show|trust <name>|clear]'
21const EMPTY = 'Nothing checked yet. Each package Claude installs is looked up on npm or PyPI first; a missing or brand new name is held for your yes.'
22const NPM_URL = 'https://registry.npmjs.org'
23const DOWNLOADS_URL = 'https://api.npmjs.org/downloads/point/last-week'
24const PYPI_URL = 'https://pypi.org/pypi'
25const PUBLIC_NPM = '//registry.npmjs.org'
26const LIMIT_MS = 4000
27const DAY_MS = 86_400_000
28const NEW_DAYS = 30
29const MAX_KEYS = 8
30const MAX_LIST = 8
31const MAX_EARLIER = 5
32const MAX_TRUSTED = 100
33const FORMS: Record<Registry, string[]> = {
34 npm: ['npm install', 'npm i', 'npm add', 'pnpm add', 'pnpm install', 'pnpm i', 'yarn add', 'bun add', 'bun install', 'bun i'],
35 pypi: [
36 'pip install',
37 'pip3 install',
38 'python -m pip install',
39 'python3 -m pip install',
40 'py -m pip install',
41 'uv add',
42 'uv pip install',
43 ],
44}
45const VALUE_FLAGS = [
46 '-r -e -c -t -p -w -C -F -i -f --requirement --editable --constraint --constraints --target --prefix --python --filter',
47 '--workspace --cwd --dir --group --extra --optional --package --project --directory --script --marker --tag --branch --rev',
48 '--bounds --python-version --python-platform --platform --implementation --abi --root --src --upgrade-strategy',
49 '--upgrade-package --reinstall-package --no-binary --only-binary --no-binary-package --no-build-package --config-settings',
50 '--config-setting --progress-bar --root-user-action --report --log --timeout --retries --proxy --cert --client-cert',
51 '--trusted-host --exists-action --use-feature --use-deprecated --resolution --prerelease --exclude-newer --index-strategy',
52 '--keyring-provider --link-mode --override --overrides --loglevel --reporter --cache --cache-dir --cache-folder --store-dir',
53 '--modules-dir --modules-folder --userconfig --config --config-file --omit --include --otp --scope --before --save-prefix',
54 '--install-strategy --cpu --os --libc --backend --network-timeout --network-concurrency --mutex --color --registry',
55 '--index-url --extra-index-url --find-links --index --default-index',
56].flatMap(row => row.split(' '))
57const PRIVATE_FLAGS = ['--registry', '--index-url', '-i', '--extra-index-url', '--find-links', '-f', '--index', '--default-index']
58const ARCHIVES = ['.tgz', '.whl', '.gz', '.zip']
59const NPM_NAME = /^(@[a-z0-9._-]+\/)?[a-z0-9][a-z0-9._-]*$/
60const PYPI_NAME = /^([A-Za-z0-9][A-Za-z0-9._-]*)(\[[^\]]*\])?$/
61const BARE_NAME = /^[a-z0-9][a-z0-9._-]*$/
62const WORD = /(?:[^\s'"]|'[^']*'|"[^"]*")+/g
63const QUOTED = /'([^']*)'|"([^"]*)"/g
64const PLAIN_VERSION = /^(\d+)(\.\d+)*(-[\w.]+)?$/
65const REGISTRIES = { npm: 'npm', pypi: 'PyPI' } as const
66const MARKS = {
67 missing: { mark: '✗', color: 'red' },
68 new: { mark: '✗', color: 'red' },
69 behind: { mark: '!', color: 'yellow' },
70 ok: { mark: '✓', color: 'green' },
71 unchecked: { mark: '?', color: undefined },
72 skipped: { mark: '·', color: undefined },
73 checking: { mark: '…', color: undefined },
74} as const
75const SKIPPED: Found = { kind: 'skipped', fact: 'skipped', line: 'not looked up: private scope or registry' }
76const NONE: Entry[] = []
77const NO_NAMES: string[] = []
78const site = { plugin: 'widgets', key: 'site' } as const
79const widths = { plugin: 'widgets', key: 'widths' } as const
80const isOn = atom({ plugin: 'customs-widget', key: 'isOn' } as const, false)
81const list = atom({ plugin: 'customs-widget', key: 'list' } as const, NONE)
82const trusted = atom({ plugin: 'customs-widget', key: 'trusted' } as const, NO_NAMES)
83
84const bare = (name: string): string => name.toLowerCase().replace(/[-_.]+/g, '-')
85
86const cut = (text: string, columns: number): string => (text.length > columns ? `${text.slice(0, Math.max(0, columns - 1))}…` : text)
87
88const wrapped = (text: string, columns: number): string[] =>
89 text
90 .split(' ')
91 .map(word => cut(word, columns))
92 .reduce<string[]>((rows, word) => {
93 const last = rows.at(-1)
94
95 return last !== undefined && last.length + 1 + word.length <= columns ? [...rows.slice(0, -1), `${last} ${word}`] : [...rows, word]
96 }, [])
97
98const age = (days: number): string => {
99 if (days < 60) return plural(days, 'day')
100 if (days < 720) return plural(Math.floor(days / 30), 'month')
101
102 return plural(Math.floor(days / 365), 'year')
103}
104
105const weekly = (downloads: number | undefined): string => {
106 if (downloads === undefined) return ''
107 if (downloads < 1000) return `, ${plural(downloads, 'download')} last week`
108
109 return `, ${downloads < 1_000_000 ? `${Math.floor(downloads / 1000)}k` : `${Math.floor(downloads / 1_000_000)}M`} downloads last week`
110}
111
112const checking = (registry: Registry): Found => ({ kind: 'checking', fact: 'checking', line: `looking up on ${REGISTRIES[registry]}` })
113
114const unchecked = (registry: Registry): Found => ({ kind: 'unchecked', fact: 'unchecked', line: `unchecked: ${REGISTRIES[registry]} did not answer` })
115
116const missing = (item: Wanted): Found => ({ kind: 'missing', fact: 'not found', line: `no package named ${item.name} on ${REGISTRIES[item.registry]}` })
117
118const judged = (item: Wanted, created: number, latest: string, downloads: number | undefined, now: number): Found => {
119 const days = Math.max(0, Math.floor((now - created) / DAY_MS))
120 if (days < NEW_DAYS) return { kind: 'new', fact: age(days), line: `first published ${age(days)} ago${weekly(downloads)}` }
121
122 const asked = PLAIN_VERSION.exec(item.asked)?.[1]
123 const newest = /^\d+/.exec(latest)?.[0]
124 if (asked !== undefined && newest !== undefined && Number(asked) < Number(newest)) {
125 return { kind: 'behind', fact: `${item.asked} → ${latest}`, line: `asked ${item.asked}, latest is ${latest}` }
126 }
127
128 return { kind: 'ok', fact: latest, line: `on ${REGISTRIES[item.registry]} ${age(days)}${weekly(downloads)}, latest ${latest}` }
129}
130
131const isRedirection = (word: string): boolean => /[<>]/.test(word) && !/['"]/.test(word)
132
133const settled = (words: string[]): string[] =>
134 words.slice(0, words.includes('&') ? words.indexOf('&') : words.length).flatMap((word, at, all) => {
135 const before = all[at - 1] ?? ''
136 if (isRedirection(before) && /[<>&]$/.test(before)) return []
137 if (!isRedirection(word)) return [word.replace(QUOTED, '$1$2')]
138
139 const kept = word.slice(0, word.search(/[<>]/))
140
141 return kept === '' || kept === '&' || /^\d+$/.test(kept) ? [] : [kept]
142 })
143
144const uncommented = (row: string): string => {
145 const comment = [...row.matchAll(WORD)].find(word => word[0].startsWith('#'))
146
147 return comment === undefined ? row : row.slice(0, comment.index)
148}
149
150const isLocal = (word: string): boolean =>
151 /^[./~]/.test(word) ||
152 word.includes(':') ||
153 word.includes('\\') ||
154 (word.includes('/') && !word.startsWith('@')) ||
155 ARCHIVES.some(ending => word.endsWith(ending))
156
157const npmName = (word: string, isPrivate: boolean): Wanted | undefined => {
158 const at = word.lastIndexOf('@')
159 const name = at > 0 ? word.slice(0, at) : word
160 if (!NPM_NAME.test(name)) return undefined
161
162 const version = at > 0 ? word.slice(at + 1).replace(/^[\^~=<>v]+/, '') : ''
163
164 return { key: `npm:${name}`, name, registry: 'npm', asked: /^\d/.test(version) ? version : '', isPrivate }
165}
166
167const pypiName = (word: string, isPrivate: boolean): Wanted | undefined => {
168 if (/^[\d.]+$/.test(word)) return undefined
169
170 const at = word.search(/[=<>!~]/)
171 const found = PYPI_NAME.exec(at === -1 ? word : word.slice(0, at))?.[1]
172 if (found === undefined) return undefined
173
174 const name = bare(found)
175 const spec = at === -1 ? '' : word.slice(at)
176
177 return { key: `pypi:${name}`, name, registry: 'pypi', asked: /^==\d/.test(spec) ? spec.slice(2) : '', isPrivate }
178}
179
180const named = (segment: string): Wanted[] => {
181 if (/[$`(]/.test(segment)) return []
182
183 const words = segment.match(WORD) ?? []
184 const first = words.findIndex(word => word !== 'sudo' && !/^[A-Za-z_][A-Za-z0-9_]*=/.test(word))
185 const line = (first === -1 ? [] : words.slice(first)).join(' ')
186 const registry = (['npm', 'pypi'] as const).find(kind => FORMS[kind].some(form => line.startsWith(`${form} `)))
187 if (registry === undefined) return []
188
189 const form = FORMS[registry].find(start => line.startsWith(`${start} `)) ?? ''
190 const rest = settled(line.slice(form.length + 1).match(WORD) ?? [])
191 const isPrivate = rest.some(word => PRIVATE_FLAGS.some(flag => word === flag || word.startsWith(`${flag}=`)))
192
193 return rest
194 .filter((word, at) => !word.startsWith('-') && !VALUE_FLAGS.includes(rest[at - 1] ?? '') && !isLocal(word))
195 .flatMap(word => (registry === 'npm' ? npmName(word, isPrivate) : pypiName(word, isPrivate)) ?? [])
196}
197
198const parsed = (command: string): Wanted[] =>
199 command
200 .split('\n')
201 .map(uncommented)
202 .join('\n')
203 .split(/&&|\|\||[;|\n]/)
204 .flatMap(segment => named(segment.trim()))
205 .filter((item, at, all) => all.findIndex(other => other.key === item.key) === at)
206 .slice(0, MAX_KEYS)
207
208const json = (text: string): unknown => {
209 try {
210 return JSON.parse(text)
211 } catch {
212 return undefined
213 }
214}
215
216const moment = (value: unknown): number => (typeof value === 'string' ? Date.parse(value) : Number.NaN)
217
218const downloaded = async ($: EngineInterface, name: string): Promise<number | undefined> => {
219 try {
220 const answer = await $.http.fetch(`${DOWNLOADS_URL}/${name}`)
221 const count = answer.status === 200 ? (json(answer.text) as { downloads?: unknown } | null | undefined)?.downloads : undefined
222
223 return typeof count === 'number' ? count : undefined
224 } catch {
225 return undefined
226 }
227}
228
229const onNpm = async ($: EngineInterface, item: Wanted, now: number): Promise<Found> => {
230 const answer = await $.http.fetch(`${NPM_URL}/${item.name}`)
231 if (answer.status === 404) return missing(item)
232
233 const record = answer.status === 200 ? (json(answer.text) as NpmRecord) : undefined
234 const created = moment(record?.time?.created)
235 const latest = record?.['dist-tags']?.latest
236 if (typeof latest !== 'string' || !Number.isFinite(created)) return unchecked('npm')
237
238 return judged(item, created, latest, await downloaded($, item.name), now)
239}
240
241const onPypi = async ($: EngineInterface, item: Wanted, now: number): Promise<Found> => {
242 const answer = await $.http.fetch(`${PYPI_URL}/${item.name}/json`)
243 if (answer.status === 404) return missing(item)
244
245 const record = answer.status === 200 ? (json(answer.text) as PypiRecord) : undefined
246 const latest = record?.info?.version
247 const created = Math.min(
248 ...Object.values(record?.releases ?? {})
249 .flat()
250 .map(file => moment(file.upload_time_iso_8601))
251 .filter(Number.isFinite),
252 )
253 if (typeof latest !== 'string' || !Number.isFinite(created)) return unchecked('pypi')
254
255 return judged(item, created, latest, undefined, now)
256}
257
258const lookup = async ($: EngineInterface, item: Wanted, now: number): Promise<Found> => {
259 try {
260 return await (item.registry === 'npm' ? onNpm($, item, now) : onPypi($, item, now))
261 } catch {
262 return unchecked(item.registry)
263 }
264}
265
266const timeUp = async ($: EngineInterface, signal: AbortSignal | undefined): Promise<undefined> => {
267 try {
268 await $.clock.sleep(LIMIT_MS, signal === undefined ? {} : { signal })
269 } catch {
270 // The wait rejects when the check ends first; that is not a failure.
271 }
272
273 return undefined
274}
275
276const mirrored = async ($: EngineInterface): Promise<boolean> => {
277 try {
278 const text = await $.fs.read(`${await $.session.cwd()}/.npmrc`)
279
280 return text.split('\n').some(row => /^\s*registry\s*=/.test(row) && !row.includes(PUBLIC_NPM))
281 } catch {
282 return false
283 }
284}
285
286const merged = (fresh: readonly Entry[], held: readonly Entry[]): Entry[] =>
287 [...fresh, ...held.filter(entry => !fresh.some(other => other.key === entry.key))].slice(0, MAX_LIST)
288
289const gate = async (
290 $: EngineInterface,
291 input: unknown,
292 id: string | undefined,
293 verdict: ToolCheckResult,
294 signal: AbortSignal | undefined,
295): Promise<ToolCheckResult> => {
296 const command = (input as { command?: unknown } | null)?.command
297 if (id === undefined || typeof command !== 'string' || verdict.decision === 'deny') return verdict
298
299 const wanted = parsed(command)
300 if (wanted.length === 0) return verdict
301
302 const isMirrored = wanted.some(item => item.registry === 'npm') && (await mirrored($))
303 const isSkipped = (item: Wanted): boolean => item.isPrivate || (item.registry === 'npm' && (isMirrored || item.name.startsWith('@')))
304 const entry = (item: Wanted, found: Found): Entry => ({ key: item.key, name: item.name, registry: item.registry, ...found, held: false })
305 const now = await $.clock.now()
306 await update($, list, held => merged(wanted.map(item => entry(item, isSkipped(item) ? SKIPPED : checking(item.registry))), held ?? []))
307
308 const limit = timeUp($, signal)
309 const found = await Promise.all(
310 wanted.map(async item => (isSkipped(item) ? SKIPPED : ((await Promise.race([lookup($, item, now), limit])) ?? unchecked(item.registry)))),
311 )
312 const names = await read($, trusted)
313 const entries = wanted.map((item, at) => entry(item, found[at] ?? unchecked(item.registry)))
314 const flagged = entries.filter(item => (item.kind === 'missing' || item.kind === 'new') && !names.includes(bare(item.name)))
315 const isRaised = flagged.length > 0 && verdict.decision === 'allow'
316 const isOurs = (item: Entry): boolean => wanted.some(other => other.key === item.key)
317 const kept = await update($, list, (held = []) =>
318 held.some(isOurs) ? merged(entries.map(item => ({ ...item, held: isRaised && flagged.includes(item) })), held) : held,
319 )
320
321 const [first] = flagged
322 if (first === undefined || !kept.some(isOurs)) return verdict
323
324 const line = `${first.name}: ${first.line}${flagged.length > 1 ? ` (+${flagged.length - 1} more)` : ''}`
325 if (isRaised) return { decision: 'ask', reason: line }
326
327 try {
328 await $.ui.notice(id, line)
329 } catch {
330 // A call that is not open refuses the line; the verdict still stands.
331 }
332
333 return verdict
334}
335
336const row = (Text: Tags['Text'], entry: Entry, inner: number, isWide: boolean): RenderElement => {
337 const { mark, color } = MARKS[entry.kind]
338 const room = inner - 3 - entry.fact.length
339 const hasFact = isWide && room >= 3
340 const name = cut(entry.name, hasFact ? room : inner - 2)
341
342 return (
343 <Text wrap="truncate-end" dimColor={color === undefined}>
344 <Text color={color}>{mark}</Text> {name}
345 {hasFact ? `${' '.repeat(inner - 2 - name.length - entry.fact.length)}${entry.fact}` : ''}
346 </Text>
347 )
348}
349
350const show = async (
351 $: EngineInterface,
352 { Box, Text }: Tags,
353 beneath: RenderElement,
354 place: WidgetsPlace,
355 columns: number,
356): Promise<RenderElement> => {
357 if (!(await read($, isOn))) return beneath
358 if ((await $.state.get(site)).value !== place) return beneath
359
360 const width = fit((await $.state.get(widths)).value?.['customs-widget'] ?? CARD_COLUMNS, columns)
361 const entries = await read($, list)
362 const [latest, ...earlier] = entries
363 const inner = width - CARD_FRAME
364 const held = entries.filter(entry => entry.held).length
365 const note = held > 0 ? `${held} held` : plural(entries.length, 'package')
366 const isWide = width >= WIDE_COLUMNS
367
368 return $.widgets.card({
369 beneath,
370 width,
371 title: TITLE,
372 note: latest === undefined ? '' : note.length > inner - TITLE.length - 1 ? `${held > 0 ? held : entries.length}` : note,
373 body: (
374 <Box flexDirection="column">
375 {latest === undefined && wrapped(EMPTY, inner).map(text => <Text dimColor>{text}</Text>)}
376 {latest !== undefined && row(Text,latest, inner, isWide)}
377 {latest !== undefined &&
378 wrapped(latest.line, inner).map(text => (
379 <Text color={MARKS[latest.kind].color} dimColor={MARKS[latest.kind].color === undefined}>
380 {text}
381 </Text>
382 ))}
383 {earlier.slice(0, MAX_EARLIER).map(entry => row(Text,entry, inner, isWide))}
384 </Box>
385 ),
386 })
387}
388
389export const register: Register = on => {
390 on('session.start', async ($, e, next) => {
391 await $.command.register({
392 name: 'customs-widget',
393 description: 'Toggle the Customs card',
394 argumentHint: '[on|off|show|trust <name>|clear]',
395 })
396 if ((await $.store.get('isOn')) === true) await update($, isOn, () => true)
397
398 const names = await $.store.get('trusted')
399 if (Array.isArray(names)) await update($, trusted, () => names.filter(name => typeof name === 'string'))
400
401 return next(e)
402 })
403
404 on('command.run', { command: 'customs-widget' }, async ($, e) => {
405 const arg = e.args.trim().toLowerCase()
406 const [verb, name, ...more] = arg.split(/\s+/)
407 if (verb === 'show' || verb === 'clear' || verb === 'trust') {
408 if (verb === 'trust' ? name === undefined || more.length > 0 || !BARE_NAME.test(name) : name !== undefined) return { text: USAGE }
409 if (!(await read($, isOn))) return { text: 'Customs is off.' }
410
411 const names = await read($, trusted)
412 if (verb === 'show') {
413 const rows = (await read($, list)).map(
414 entry => `${entry.name} (${REGISTRIES[entry.registry]}): ${entry.line}${entry.held ? ' [held]' : ''}`,
415 )
416 const text = [...rows, ...(names.length === 0 ? [] : [`Trusted: ${names.join(', ')}`])].join('\n')
417
418 return { text: text === '' ? 'Nothing checked yet.' : text }
419 }
420
421 const kept = verb === 'clear' ? [] : names.includes(bare(name ?? '')) ? names : [...names, bare(name ?? '')].slice(-MAX_TRUSTED)
422 if (verb === 'clear') await update($, list, () => [])
423 if (kept !== names) {
424 await update($, trusted, () => kept)
425 await $.store.set('trusted', kept)
426 }
427
428 return { text: verb === 'clear' ? 'Customs cleared.' : `Customs trusts ${bare(name ?? '')}.` }
429 }
430 if (arg !== '' && arg !== 'on' && arg !== 'off') return { text: USAGE }
431
432 const isShown = await update($, isOn, shown => (arg === '' ? !(shown ?? false) : arg === 'on'))
433 await $.store.set('isOn', isShown)
434 if (!isShown) await update($, list, () => [])
435
436 return { text: isShown ? 'Customs on; /widgets places it.' : 'Customs off.' }
437 })
438
439 on('tool.check', { tool: 'Bash' }, async ($, e, next) => {
440 if (!(await read($, isOn))) return next(e)
441
442 return gate($, e.input, e.tool_use_id, await next(e), next.signal)
443 })
444
445 on('tool.check', { tool: 'PowerShell' }, async ($, e, next) => {
446 if (!(await read($, isOn))) return next(e)
447
448 return gate($, e.input, e.tool_use_id, await next(e), next.signal)
449 })
450
451 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e, next) =>
452 show($, $.ui.resolve(e), await next(e), 'side', e.props.bodyColumns),
453 )
454
455 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) =>
456 e.props.hasSurvey ? next(e) : show($, $.ui.resolve(e), await next(e), 'above', e.props.bodyColumns),
457 )
458
459 on('ui.render', { component: 'PromptHint' }, async ($, e, next) =>
460 show($, $.ui.resolve(e), await next(e), 'below', e.viewport?.columns ?? 80),
461 )
462}
463hooks/lib.ts 45 lines1const MIN_CARD = 20
2const BARS = '▁▂▃▄▅▆▇█'
3
4export const fit = (wanted: number, columns: number): number => Math.min(wanted, Math.max(MIN_CARD, columns))
5
6export const plural = (count: number, word: string): string => `${count} ${word}${count === 1 ? '' : 's'}`
7
8export const span = (ms: number): string => {
9 const seconds = Math.max(0, Math.round(ms / 1000))
10 if (seconds < 60) return `${seconds}s`
11 const minutes = Math.floor(seconds / 60)
12 if (minutes < 60) return `${minutes}m ${String(seconds % 60).padStart(2, '0')}s`
13 const hours = Math.floor(minutes / 60)
14 if (hours < 24) return `${hours}h ${String(minutes % 60).padStart(2, '0')}m`
15
16 return `${Math.floor(hours / 24)}d ${hours % 24}h`
17}
18
19export const spark = (values: readonly number[], width: number): string => {
20 const shown = width > 0 ? values.slice(-width) : []
21 const top = Math.max(...shown, 0)
22
23 return shown
24 .map(value => (top <= 0 ? BARS[0] : BARS[Math.min(BARS.length - 1, Math.round((Math.max(0, value) / top) * (BARS.length - 1)))]))
25 .join('')
26}
27
28export const hash = (text: string): number => {
29 let held = 2166136261
30 for (const letter of text) held = Math.imul(held ^ (letter.codePointAt(0) ?? 0), 16777619)
31
32 return held >>> 0
33}
34
35export const shade = (color: number, factor: number): number =>
36 (Math.round((color >> 16) * factor) << 16) |
37 (Math.round(((color >> 8) & 255) * factor) << 8) |
38 Math.round((color & 255) * factor)
39
40export const folder = (path: string): string => {
41 const flat = path.replaceAll('\\', '/').replace(/\/+$/, '')
42
43 return /^[a-z]:/i.test(flat) ? flat.toLowerCase() : flat
44}
45types/index.d.ts 20 lines1export type CustomsSwitch = boolean
2
3declare module 'claude-code' {
4 interface PluginState {
5 'customs-widget': {
6 isOn: CustomsSwitch
7 list: {
8 key: string
9 name: string
10 registry: 'npm' | 'pypi'
11 kind: 'checking' | 'missing' | 'new' | 'behind' | 'ok' | 'unchecked' | 'skipped'
12 fact: string
13 line: string
14 held: boolean
15 }[]
16 trusted: string[]
17 }
18 }
19}
20