Slap your MacBook and Claude Code feels it: a face, a yelp, and optionally a stopped turn

Your MacBook has an accelerometer. Claude Code has plugins. You have feelings. Now they can finally meet.
Slap your MacBook (or the desk it sits on) and Claude Code feels it: a face pops up above the prompt, the laptop yelps back in Japanese, and a little counter keeps score of how your day is going. Optionally, Claude itself gets the message — and a hard enough slap stops it mid-turn.
<img src="plugin/assets/faces/sakura/level_1.png" width="96" alt="Sakura, level 1"> <img src="plugin/assets/faces/sakura/level_2.png" width="96" alt="Sakura, level 2"> <img src="plugin/assets/faces/sakura/level_3.png" width="96" alt="Sakura, level 3"> <img src="plugin/assets/faces/sakura/level_4.png" width="96" alt="Sakura, level 4"> <img src="plugin/assets/faces/sakura/level_5.png" width="96" alt="Sakura, level 5"> <img src="plugin/assets/faces/natsu/level_1.png" width="96" alt="Natsu, level 1"> <img src="plugin/assets/faces/natsu/level_2.png" width="96" alt="Natsu, level 2"> <img src="plugin/assets/faces/natsu/level_3.png" width="96" alt="Natsu, level 3"> <img src="plugin/assets/faces/natsu/level_4.png" width="96" alt="Natsu, level 4"> <img src="plugin/assets/faces/natsu/level_5.png" width="96" alt="Natsu, level 5"> <img src="plugin/assets/faces/aki/level_1.png" width="96" alt="Aki, level 1"> <img src="plugin/assets/faces/aki/level_2.png" width="96" alt="Aki, level 2"> <img src="plugin/assets/faces/aki/level_3.png" width="96" alt="Aki, level 3"> <img src="plugin/assets/faces/aki/level_4.png" width="96" alt="Aki, level 4"> <img src="plugin/assets/faces/aki/level_5.png" width="96" alt="Aki, level 5">
| Level | Hit (at 0.05 g) | Sakura says | Natsu says | Aki says | What probably happened |
|---|---|---|---|---|---|
| 1 | 0.050–0.106 g | んっ! | えっ! | ひゃっ! | A tap. Passive-aggressive at most. |
| 2 | 0.106–0.224 g | あっ! | うっ! | あれっ! | The tests failed again. |
| 3 | 0.224–0.473 g | いたっ! | いてっ! | いたぁ! | Claude "simplified" your code. |
| 4 | 0.473–1 g | きゃっ! | やっ! | いやっ! | Claude deleted the tests to make them pass. |
| 5 | 1 g and up | あぁっ…! | うわぁっ! | きゃあっ! | Production. |
The g ranges are for the default sensitivity, 0.05 g. The scale moves with yours (/slaps calibrate, or "Slap sensitivity" in /config): level 1 starts at your sensitivity, level 5 at 1 g, and the levels between are spread evenly. At 0.15 g, for example, they start at about 0.15, 0.24, 0.39, 0.62 and 1 g.
Two exceptions. Below 0.05 g the scale stays as it is at 0.05 g: softer taps count, as level 1, but a moderate slap doesn't turn into a level 4. Above 0.25 g, level 5 starts at 4 times your sensitivity instead of 1 g, so the levels don't bunch up.
Keep slapping, less than a second apart, and every tap counts, however soft: each is one level above the one before, or its own level if it hit harder, and the level never drops until you pause. Five soft taps make her scream. A harder slap cuts her off with its own yelp; one at the same level does too, but stays quiet if her last yelp is under 0.4 s old, so drumming doesn't stutter. The face says how many came in a row, and a combo puts up one toast as it starts and one as it ends, saying how far it got. The score (/slaps, the status line) still keeps what the sensor read.
Taps can come as fast as about 7 a second. A hard slap leaves the laptop ringing, so the next tap counts once that has died down, usually within a fraction of a second.
sudo there; older releases may want root (untested).xcode-select --install). The plugin builds its little sensor reader from Swift source on first run, so nothing precompiled ships in the repo.Two commands, no cloning:
claude plugin marketplace add slima4/spank-claude
claude plugin install spank@spank-claude
(or the same from inside Claude Code: /plugin marketplace add slima4/spank-claude, then /plugin install spank@spank-claude.)
Start Claude Code. The first session builds the sensor reader (the status line says spank: building the sensor reader, about 20 seconds), then shows spank: armed (0.05g). Go on. Slap it.
Updates: claude plugin update spank@spank-claude, then restart Claude Code. Each new version builds its sensor reader again on its first start. Uninstall: claude plugin uninstall spank@spank-claude.
| Command | Does |
|---|---|
/slaps | Your score: this session, all time, and the last hit. |
/slaps who | Lists the face series; the current one is marked. |
/slaps who natsu | Natsu gets slapped now (any series name works). |
/slaps calibrate | Type 6 s (no Enter), knock 3 times; it picks the sensitivity. |
/slaps off | Ignores every slap, in every session, until /slaps on. |
/slaps on | Slaps count again. |
/slaps mute | Silences her. The faces still judge you. |
/slaps unmute | She's back. |
/slaps claude on | Slaps reach Claude; a level 4+ slap or combo stops its turn. |
/slaps claude off | Claude stays blissfully unaware (the default). |
/slaps image | Checks whether your terminal can show real pictures. |
With /slaps claude on, every slap becomes a quiet note in the conversation: "The user just physically slapped their laptop 2 times (accelerometer; strongest hit level 3 of 5, 0.31g). Take it as nonverbal frustration…" Claude reads it on its next step, acknowledges it, and reconsiders what it was doing. Slaps that keep coming are told as one note once you pause, or 4 seconds after the first, whichever comes sooner. Slaps while it's idle are saved up and delivered as one note with your next message, so it gets the whole story at once.
A level 4+ slap while Claude is working stops the turn on the spot (the level is a setting). So does a combo that builds up to it and lasts at least half a second (so one slap that bounces doesn't), unless one of its slaps was a level 1 graze (so the steady shaking of a bumpy train doesn't). Fair warning: a shell command Claude already started keeps running in the background; the slap stops Claude, not the command.
Only the Claude Code session you used last reacts to a slap (the one you last typed a prompt or a /slaps command in). One laptop, one victim.
Each face series is one character: five faces, one per level, and a voice. Switch with /slaps who <series> (/slaps who lists them), or under "Face series" in /config.
| Series | Voice | Face |
|---|---|---|
sakura | sakura | <img src="plugin/assets/faces/sakura/level_1.png" width="48" alt="Sakura"> |
natsu | natsu | <img src="plugin/assets/faces/natsu/level_1.png" width="48" alt="Natsu"> |
aki | aki | <img src="plugin/assets/faces/aki/level_1.png" width="48" alt="Aki"> |
Faces are drawn as colored half-block characters, so they show up in any truecolor terminal (Warp, iTerm2, Ghostty, …), pixel-art style, in the biggest size that fits above your prompt.
Real, full-resolution pictures need a terminal with kitty graphics Unicode placeholders, which today means Ghostty or kitty. Run /slaps image to see what yours can do. Warp and Terminal.app currently can't (not our fault, we checked).
Open /config in Claude Code (or /plugin configure spank@spank-claude):
| Setting | Default | What it does |
|---|---|---|
| Slap sensitivity (g) | 0.05 | Smallest shake that counts, and where level 1 starts. Typing counts? Raise it. |
| Level that stops Claude | 4 | With /slaps claude on, this level or harder stops a turn. |
| Face series | sakura | sakura, natsu or aki: whose face pops up and voice yelps. |
| Face size | large | large (24 rows), medium (16), small (12), or off. |
| Voice volume | 1 | 0 is silent, up to 4 for open-plan offices. |
Changes apply right away. Not sure what sensitivity to pick? Run /slaps calibrate: type anything for 6 seconds (don't press Enter, or Claude gets it), then knock on the desk 3 times, and it sets the sensitivity between the two for you. The 6 seconds start at your first key and the knocking at your first knock, so take your time reading; it waits up to 30 seconds for each. The status line then shows it, e.g. spank: armed (0.077g).
MacBook IMU (AppleSPUHIDDevice, ~1 kHz)
│ IOKit HID reports, x/y/z in 1/65536 g
▼
slapd (Swift) ── removes gravity, finds the peak
│ {"type":"slap","ts":…,"peak":0.42} on stdout
▼
spank plugin (Claude Code hooks) ── grades it 1–5 for your sensitivity
├─ status line + toast
├─ face above the prompt (Raster cells, 3 s)
├─ voice clip per level
└─ optional: note to Claude / stop its turn
Run straight from a clone (uninstall the marketplace copy first, or you get two of her):
git clone https://github.com/slima4/spank-claude && cd spank-claude
claude --plugin-dir "$PWD/plugin"
make slapd # build the sensor reader by hand
make raw # watch the live shake
make faces # rebuild face cells from assets/faces/<series>/*.png
claude plugin validate . # the marketplace and the plugin
claude plugin test plugin # the tests
Installed copies are kept per version, so bump version in plugin/.claude-plugin/plugin.json when you ship a change.
To add a face series, say hana:
assets/faces/hana/level_<1-5>.png (square, on white)."hana" to the face_series options in plugin/.claude-plugin/plugin.json.make faces. It draws the cells into plugin/hooks/faces.ts, writes the 256px pictures to plugin/assets/faces/hana/, and warns if step 2 is missing.plugin/hooks/series.ts, add hana to SERIES. It can borrow an existing voice (voice: 'sakura'), or get its own: clips in plugin/assets/voices/hana/level_<1-5>.mp3 and their captions in VOICES.MIT. Slap responsibly.
hooks/register.tsx 857 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, PluginOptions, Register, Timer } from 'claude-code'
3
4import type { FaceShown, Slap } from '../types'
5import { FACES } from './faces'
6import type { SeriesId } from './faces'
7import { DEFAULT_SERIES, SERIES, VOICES, isSeries } from './series'
8
9const count = atom({ plugin: 'spank', key: 'count' } as const, 0)
10const last = atom({ plugin: 'spank', key: 'last' } as const, null)
11// The main thread's running turn, which a hard slap stops.
12const turn = atom({ plugin: 'spank', key: 'turn' } as const, null)
13const face = atom({ plugin: 'spank', key: 'face' } as const, null)
14// Whether /slaps image is drawing its test picture.
15const probe = atom({ plugin: 'spank', key: 'probe' } as const, false)
16
17// Slaps this close together during a turn reach Claude as one note, told at
18// most this long after the first, so slapping on and on still gets through.
19const BURST_MS = 1500
20const BURST_MAX_MS = 4000
21// Slaps at most this far apart, by the sensor's clock, are a combo: each
22// counts one level above the one before, or its own if that is harder. A
23// combo stops Claude only once it has lasted COMBO_STOP_MS, so one slap that
24// bounces never does.
25const COMBO_MS = 1000
26const COMBO_STOP_MS = 500
27// How long a slap's face stays above the prompt.
28const FACE_MS = 3000
29// How long a slap's toast stays.
30const TOAST_MS = 4000
31// How long a clip plays before a slap no harder than it may cut it off.
32const VOICE_MS = 400
33// The tallest face per face_size setting, in rows; 0 draws none.
34const FACE_ROWS: Record<string, number> = { large: 24, medium: 16, small: 12, off: 0 }
35// Room the face leaves beside it for its line.
36const FACE_TEXT_COLUMNS = 24
37// /slaps calibrate: how long each step listens (from the first key, and from
38// the first knock), how long it waits for either, and the least typing it
39// assumes. The sensor rests around 0.01g, so a calibration with no typing
40// still lands well above that.
41const CALIBRATE_TYPING_MS = 6000
42const CALIBRATE_KNOCKING_MS = 8000
43const CALIBRATE_WAIT_MS = 30000
44const CALIBRATE_FLOOR = 0.025
45// How long past its step's longest a calibration waits on its reader: past
46// this, a reader gone quiet is given up on, so it cannot keep swallowing slaps.
47const CALIBRATE_SLACK_MS = 5000
48// How long /slaps image shows its test picture.
49const PROBE_MS = 10000
50// The levels' scale, in g: level 1 starts at the sensitivity, but never
51// below LEVEL_1_G, so a lower one lets softer taps count (as level 1) without
52// making a moderate slap level 4; level 5 starts at LEVEL_5_G, a firm palm,
53// but at least LEVEL_SPAN times level 1, so a sensitivity near 1g still has
54// five levels.
55const LEVEL_1_G = 0.05
56const LEVEL_5_G = 1
57const LEVEL_SPAN = 4
58// The status line while /slaps off holds.
59const OFF_STATUS = 'spank: off (/slaps on)'
60
61// slapd's lines: it opened the sensor, heard a slap (when, and how hard), or
62// (with --raw, every 0.1s) the loudest shake of that moment.
63type Line = { type: 'start' } | { type: 'slap'; ts: number; peak: number } | { type: 'raw'; peak: number }
64
65function parseLine(line: string): Line | undefined {
66 try {
67 const v = JSON.parse(line) as Record<string, unknown>
68 if (v.type === 'start') return { type: 'start' }
69 if (v.type === 'raw' && typeof v.peak === 'number') return { type: 'raw', peak: v.peak }
70 if (v.type === 'slap' && typeof v.ts === 'number' && typeof v.peak === 'number') {
71 return { type: 'slap', ts: v.ts, peak: v.peak }
72 }
73 } catch {}
74 return undefined
75}
76
77// Splits a stream's text into whole lines, keeping a partial last line for the
78// next piece.
79function lineSplitter() {
80 let pending = ''
81 return (text: string) => {
82 pending += text
83 const lines = pending.split('\n')
84 pending = lines.pop() ?? ''
85 return lines
86 }
87}
88
89// A calibration's steps: waiting for the first key, typing, waiting for the
90// first knock, knocking. The prompt.edit hook notes when the first key came.
91type Calibration = { step: 'waiting' | 'typing' | 'ready' | 'knocking'; typedAt?: number }
92
93// When the slaps happened: during a turn, during a turn a hard one stopped,
94// during a turn a combo stopped, or between turns (told once, as the next
95// turn starts).
96type Moment = 'turn' | 'stopped' | 'combo' | 'idle'
97
98function note(slaps: readonly Slap[], moment: Moment) {
99 const strongest = slaps.reduce((a, b) => (b.peak > a.peak ? b : a))
100 const what = slaps.length === 1 ? 'slapped their laptop' : `slapped their laptop ${slaps.length} times`
101 const reading = `strongest hit level ${strongest.level} of 5, ${strongest.peak.toFixed(2)}g`
102 const when = moment === 'idle' ? 'Since your last reply the user physically' : 'The user just physically'
103 const how = moment === 'stopped' ? 'It was hard enough' : 'They came fast enough'
104 const ask =
105 moment === 'stopped' || moment === 'combo'
106 ? `${how} to stop your turn. Acknowledge the slap briefly and check with the user before redoing that work.`
107 : 'Take it as nonverbal frustration with what you are doing: acknowledge it briefly, reconsider your current approach, and ask what is wrong if it is not clear.'
108
109 return `[spank] ${when} ${what} (accelerometer; ${reading}). ${ask}`
110}
111
112// Slaps not yet told to Claude, when the first of them came, the timer that
113// tells it, the combo under way (its slaps, when the first and the last hit,
114// the softest level among them, and the level it is at), its end toast still
115// to come (the timer, and how to show it at once), the last slap toast (when,
116// and its level), the voice clip playing (its level, when it started, and how
117// to stop it), the timer that hides the face, a calibration under way, the
118// status line the sensor last set (which a calibration puts back), and what
119// slapd itself last said, armed or why not (which /slaps on puts back). Reset
120// by register, so each load starts clean.
121let burst: Slap[] = []
122let burstSince = 0
123let burstTimer: Timer | undefined
124let combo: { count: number; since: number; at: number; weakest: number; level: number } | undefined
125let comboEnd: { timer: Timer; show: () => Promise<void> } | undefined
126let toast: { at: number; level: number } | undefined
127let playing: { level: number; at: number; stop: AbortController } | undefined
128let faceTimer: Timer | undefined
129let calibration: Calibration | undefined
130let sensorStatus: string | undefined
131let sensorSaid: string | undefined
132// /slaps image's picture (PNG, base64), and the band's id for blitting it.
133let probePng: string | undefined
134let bandRequestId: string | undefined
135
136// The config menu's values (the manifest's userConfig). A change there reloads
137// the module, so register reads them afresh.
138// `levels` is where levels 2 to 5 start, in g, for the sensitivity.
139type Settings = {
140 threshold: number
141 levels: number[]
142 stopLevel: number
143 faceRows: number
144 volume: number
145 series: SeriesId
146}
147let settings: Settings = {
148 threshold: 0.05,
149 levels: levelStarts(0.05),
150 stopLevel: 4,
151 faceRows: 24,
152 volume: 1,
153 series: DEFAULT_SERIES,
154}
155
156function readSettings(options: PluginOptions): Settings {
157 const number = (key: string, fallback: number) => {
158 const value = options[key]
159 return typeof value === 'number' && Number.isFinite(value) ? value : fallback
160 }
161 const faceSize = options.face_size
162 // Within the manifest's 0.01-1g: the engine refuses options outside it.
163 const threshold = number('threshold', 0.05)
164 return {
165 threshold,
166 levels: levelStarts(threshold),
167 stopLevel: number('stop_level', 4),
168 faceRows: typeof faceSize === 'string' ? (FACE_ROWS[faceSize] ?? 24) : 24,
169 volume: number('volume', 1),
170 series: isSeries(options.face_series) ? options.face_series : DEFAULT_SERIES,
171 }
172}
173
174// Where levels 2 to 5 start for a sensitivity: evenly spaced on a log scale
175// between level 1 and level 5 (see LEVEL_1_G), each a fixed multiple above
176// the last.
177function levelStarts(threshold: number) {
178 const first = Math.max(threshold, LEVEL_1_G)
179 const fifth = Math.max(LEVEL_5_G, first * LEVEL_SPAN)
180 return [1, 2, 3, 4].map(k => first * (fifth / first) ** (k / 4))
181}
182
183// A slap's level, 1 to 5; any slap that counts is at least level 1.
184function levelOf(peak: number) {
185 return 1 + settings.levels.filter(start => peak >= start).length
186}
187
188// The chosen series' voice: its clips' folder and what each level says.
189function voiceOf() {
190 const id = SERIES[settings.series].voice
191 return { id, captions: VOICES[id].captions }
192}
193
194function setSensorStatus($: EngineInterface, text: string) {
195 sensorStatus = text
196 $.ui.status(text)
197}
198
199// /slaps off holds for every session until /slaps on: slapd keeps running,
200// and its slaps are dropped.
201async function isOff($: EngineInterface) {
202 return (await $.store.get('off')) === true
203}
204
205// Slaps going off, here or (seen on the next slap) in another session:
206// nothing of the slaps before goes on, and the status line says so.
207async function goOff($: EngineInterface) {
208 dropSlaps()
209 await update($, face, () => null)
210 setSensorStatus($, OFF_STATUS)
211}
212
213// Slaps back on, here or in another session: the off line gives way to what
214// slapd last said.
215function goOn($: EngineInterface) {
216 if (sensorStatus !== OFF_STATUS) return
217 sensorStatus = sensorSaid
218 $.ui.status(sensorSaid)
219}
220
221// Which session reacts when several are open: the one used last. Each session
222// writes itself into this file (in the per-user temp folder) when it starts,
223// on every prompt and on /slaps; a slap belongs to the session it names.
224async function activePath($: EngineInterface) {
225 const temp = (await $.env.get('TMPDIR')) ?? `${$.plugin.root}/`
226 return `${temp.endsWith('/') ? temp : `${temp}/`}spank-claude-active.json`
227}
228
229async function markActive($: EngineInterface) {
230 const session = await $.session.id()
231 await $.fs.write(await activePath($), JSON.stringify({ session, at: await $.clock.now() }))
232}
233
234// Unreadable or torn, the file names nobody, and every session reacts.
235async function isActive($: EngineInterface) {
236 try {
237 const { session } = JSON.parse(await $.fs.read(await activePath($))) as { session?: unknown }
238 return typeof session !== 'string' || session === (await $.session.id())
239 } catch {
240 return true
241 }
242}
243
244// The largest face of the chosen series for this level that fits the band,
245// if any does.
246function faceArt(level: number, maxRows: number, columns: number) {
247 const arts = FACES[settings.series][Math.min(Math.max(level, 1), 5) - 1] ?? []
248 return arts.findLast(art => art.rows <= Math.min(maxRows, settings.faceRows) && art.columns + FACE_TEXT_COLUMNS <= columns)
249}
250
251function showToast($: EngineInterface, at: number, level: number, text: string) {
252 toast = { at, level }
253 $.ui.toast(text, { timeoutMs: TOAST_MS })
254}
255
256// Takes back the combo's end toast still to come, showing it first if asked.
257function settleComboEnd(isShown: boolean) {
258 const end = comboEnd
259 comboEnd = undefined
260 end?.timer.cancel()
261 if (isShown) void end?.show().catch(() => {})
262}
263
264async function showFace($: EngineInterface, shown: FaceShown) {
265 faceTimer?.cancel()
266 await update($, face, () => shown)
267 faceTimer = $.clock.after(FACE_MS, () => void update($, face, () => null))
268}
269
270// Plays the level's clip, cutting off the one still playing: always if it is
271// harder, else only once that one has played VOICE_MS, so drumming at one
272// level does not stutter (a slap sooner than that stays quiet).
273function voice($: EngineInterface, level: number, now: number) {
274 if (settings.volume <= 0) return
275 if (playing !== undefined && level <= playing.level && now - playing.at < VOICE_MS) return
276 playing?.stop.abort()
277 const clip = { level, at: now, stop: new AbortController() }
278 playing = clip
279 const asset = `assets/voices/${voiceOf().id}/level_${level}.mp3`
280 $.audio
281 .play({ asset }, { signal: clip.stop.signal, gain: settings.volume })
282 .catch(() => {})
283 .finally(() => {
284 if (playing === clip) playing = undefined
285 })
286}
287
288function cancelBurstTimer() {
289 burstTimer?.cancel()
290 burstTimer = undefined
291}
292
293// Lets go of the slaps under way: their note still to tell Claude, their
294// combo and its end toast, the clip playing, and the timer that hides the
295// face.
296function dropSlaps() {
297 burst = []
298 burstSince = 0
299 cancelBurstTimer()
300 combo = undefined
301 settleComboEnd(false)
302 playing?.stop.abort()
303 playing = undefined
304 faceTimer?.cancel()
305 faceTimer = undefined
306}
307
308async function tellClaude($: EngineInterface, moment: Moment) {
309 cancelBurstTimer()
310 const slaps = burst
311 burst = []
312 if (slaps.length === 0) return
313 // Slaps heard before another session turned them off.
314 if (await isOff($)) return
315
316 const text = note(slaps, moment)
317 // A refused or failed note must not end the listen loop that called it.
318 try {
319 await $.session.append({ message: { type: 'user', content: [{ type: 'text', text }] } })
320 } catch (error) {
321 $.ui.log(`spank: could not tell Claude "${text}": ${String(error)}`, { to: 'debug' })
322 }
323}
324
325// The loudest typing, that at least CALIBRATE_FLOOR, and the bar a knock must
326// reach: half again the floored typing.
327function typingBar(typing: readonly number[]) {
328 const typingMax = Math.max(0, ...typing)
329 const floored = Math.max(CALIBRATE_FLOOR, typingMax)
330 return { typingMax, floored, bar: floored * 1.5 }
331}
332
333// The sensitivity between typing and knocking: the geometric mean of the
334// floored typing and the softest of the three strongest knocks, each of which
335// must reach the bar. A knock is a moment louder than the ones beside it, so a
336// knock split across two moments counts once. Also returns what it decided
337// on, to log.
338function pickThreshold(typing: readonly number[], knocking: readonly number[]) {
339 const { typingMax, floored, bar } = typingBar(typing)
340 const peaks = knocking
341 .filter((peak, i) => peak > (knocking[i - 1] ?? 0) && peak >= (knocking[i + 1] ?? 0))
342 .sort((a, b) => b - a)
343 const clear = peaks.filter(peak => peak >= bar)
344 const softest = clear[2]
345 if (softest === undefined) {
346 // A knock louder than typing but short of the bar, or none reaching it,
347 // was too soft; otherwise the missing ones ran together or never came.
348 const isSoft = clear.length === 0 || peaks.some(peak => peak > floored && peak < bar)
349 const advice = isSoft ? 'knock harder' : 'knock 3 separate times, a second apart'
350 return { reason: `heard ${clear.length} of 3 knocks reaching ${inG(bar)}; ${advice}`, typingMax, bar, peaks } as const
351 }
352 const threshold = Math.round(Math.min(1, Math.sqrt(floored * softest)) * 1000) / 1000
353 return { threshold, typingMax, softest, bar, peaks }
354}
355
356function inG(value: number) {
357 return `${value.toFixed(3)}g`
358}
359
360// An outcome told after the fact (a calibration's, a failed switch): a toast,
361// and a line in the transcript, which keeps the whole text when the toast
362// gets only one line.
363function report($: EngineInterface, text: string) {
364 $.ui.toast(text, { timeoutMs: 10000 })
365 $.ui.log(`spank: ${text}`)
366}
367
368// /slaps calibrate: a slapd of its own (--raw: the loudest shake every 0.1s)
369// listens to typing, then to knocks, and the sensitivity setting goes between
370// them. Typing is timed from the first key in the prompt box, and knocking
371// from the first moment loud enough to be a knock, so time spent reading the
372// instructions counts for neither. Slaps are ignored meanwhile, and one runs
373// at a time. Steps follow the clock as readings arrive, and leaving the loop
374// stops that slapd.
375async function calibrate($: EngineInterface) {
376 // Set before any await, so a /slaps calibrate right behind this one sees it.
377 const run: Calibration = { step: 'waiting' }
378 calibration = run
379 // reader.return() waits behind a pull still waiting for a line, so each
380 // pull races the backstop instead. Each step sets it anew.
381 let giveUp = () => {}
382 const quiet = new Promise<'quiet'>(resolve => (giveUp = () => resolve('quiet')))
383 let backstop = $.clock.after(CALIBRATE_WAIT_MS + CALIBRATE_SLACK_MS, () => giveUp())
384 const rearm = (stepMs: number) => {
385 backstop.cancel()
386 backstop = $.clock.after(stepMs + CALIBRATE_SLACK_MS, () => giveUp())
387 }
388 const heard = { typing: [] as number[], knocking: [] as number[] }
389 let failure: string | undefined
390 try {
391 // When the step began: the calibration, the first key, the end of the
392 // typing, the first knock.
393 let stepAt = await $.clock.now()
394 let bar = 0
395 $.ui.status(
396 `spank: calibrating 1/2: start typing, without pressing Enter (${CALIBRATE_TYPING_MS / 1000}s from the first key)`,
397 )
398 const reader = $.process.spawn({ argv: [`${$.plugin.root}/bin/slapd`, '--raw', '--threshold', '100'] })
399 const lines = lineSplitter()
400 let lastError = ''
401 try {
402 reading: for (;;) {
403 const pulled = await Promise.race([reader.next(), quiet])
404 if (pulled === 'quiet') {
405 failure = 'the sensor went quiet'
406 break
407 }
408 if (pulled.done === true) {
409 failure = `the sensor reader stopped (${lastError || 'slapd exited'})`
410 break
411 }
412 const { stream, text } = pulled.value
413 if (stream === 'stderr') {
414 lastError = text.trim().split('\n').pop() ?? lastError
415 continue
416 }
417 for (const line of lines(text)) {
418 const parsed = parseLine(line)
419 if (parsed?.type !== 'raw') continue
420 const now = await $.clock.now()
421 if (run.step === 'waiting') {
422 if (run.typedAt === undefined) {
423 if (now - stepAt < CALIBRATE_WAIT_MS) continue
424 failure = `nothing was typed in the prompt box within ${CALIBRATE_WAIT_MS / 1000}s`
425 break reading
426 }
427 run.step = 'typing'
428 stepAt = run.typedAt
429 rearm(CALIBRATE_TYPING_MS)
430 $.ui.status(`spank: calibrating 1/2: keep typing (${CALIBRATE_TYPING_MS / 1000}s)`)
431 }
432 if (run.step === 'typing') {
433 if (now - stepAt < CALIBRATE_TYPING_MS) {
434 heard.typing.push(parsed.peak)
435 continue
436 }
437 run.step = 'ready'
438 stepAt = now
439 bar = typingBar(heard.typing).bar
440 rearm(CALIBRATE_WAIT_MS)
441 $.ui.status(
442 `spank: calibrating 2/2: knock on the desk 3 times (${CALIBRATE_KNOCKING_MS / 1000}s from the first knock)`,
443 )
444 $.ui.toast('Now knock on the desk 3 times', { timeoutMs: CALIBRATE_KNOCKING_MS })
445 }
446 if (run.step === 'ready') {
447 // Typing on past the toast stays under the bar.
448 if (parsed.peak < bar) {
449 if (now - stepAt < CALIBRATE_WAIT_MS) continue
450 failure = `heard no knock reaching ${inG(bar)} within ${CALIBRATE_WAIT_MS / 1000}s; knock harder`
451 break reading
452 }
453 run.step = 'knocking'
454 stepAt = now
455 rearm(CALIBRATE_KNOCKING_MS)
456 $.ui.status(`spank: calibrating 2/2: keep knocking (${CALIBRATE_KNOCKING_MS / 1000}s)`)
457 }
458 if (now - stepAt >= CALIBRATE_KNOCKING_MS) break reading
459 heard.knocking.push(parsed.peak)
460 }
461 }
462 } finally {
463 // Stops slapd; a pull still waiting holds this until slapd writes.
464 reader.return({ code: null, signal: null }).catch(() => {})
465 }
466 } catch (error) {
467 failure = `the sensor could not be read (${String(error)})`
468 } finally {
469 backstop.cancel()
470 if (calibration === run) calibration = undefined
471 }
472
473 $.ui.status(sensorStatus)
474 if (failure !== undefined) {
475 report($, `Calibration failed: ${failure}.`)
476 return
477 }
478 const picked = pickThreshold(heard.typing, heard.knocking)
479 const peaks = picked.peaks.slice(0, 5).map(inG).join(', ')
480 $.ui.log(`spank: calibration: typing ${inG(picked.typingMax)}, bar ${inG(picked.bar)}, knock peaks [${peaks}]`, {
481 to: 'debug',
482 })
483 if (picked.threshold === undefined) {
484 report($, `Calibration failed: ${picked.reason}.`)
485 return
486 }
487 // Told before saving: saving reloads the plugin, which may drop anything
488 // this module says afterwards.
489 report($, `Sensitivity set to ${picked.threshold}g (typing ${inG(picked.typingMax)}, knocks ${inG(picked.softest)}).`)
490 const unsaved = await saveSetting($, 'threshold', picked.threshold, 'sensitivity').catch(error => String(error))
491 if (unsaved !== undefined) {
492 report($, `Could not save the sensitivity: ${unsaved}. Set "Slap sensitivity" in /config.`)
493 }
494}
495
496// Writes a userConfig option as the person would in /config; the module then
497// reloads with it. The row is looked up, not spelled, since its key depends
498// on how the plugin was loaded. Resolves undefined once saved, or why not,
499// calling the setting by its label.
500async function saveSetting(
501 $: EngineInterface,
502 option: string,
503 value: string | number,
504 label: string,
505): Promise<string | undefined> {
506 const rows = await $.config.list()
507 const row = rows.find(
508 r => r.key === `${$.plugin.name}.${option}` || (r.provider.plugin === $.plugin.name && r.key.endsWith(`.${option}`)),
509 )
510 if (row === undefined) return `no ${label} row in /config`
511 const set = await $.config.set({ key: row.key, value })
512 return set.deny
513}
514
515function titled(id: string) {
516 return id.charAt(0).toUpperCase() + id.slice(1)
517}
518
519// /slaps who [series]: lists the face series, or switches to one by saving
520// the face_series setting. Saving reloads the module, so the reply goes out
521// first and only a failure is told afterwards; until the reload the series is
522// switched here already, and switched back if saving fails. A calibration
523// under way would not survive the reload, so it holds the switch off.
524function who($: EngineInterface, wanted: string) {
525 const ids = Object.keys(SERIES)
526 if (wanted === '') return ids.map(id => (id === settings.series ? `${id} (current)` : id)).join(', ')
527 if (!isSeries(wanted)) return `No face series "${wanted}". Try: ${ids.join(', ')}.`
528 if (wanted === settings.series) return `${titled(wanted)} already. Slap away.`
529 if (calibration !== undefined) return 'Calibrating; switch after it finishes.'
530
531 const { series } = settings
532 settings = { ...settings, series: wanted }
533 void saveSetting($, 'face_series', wanted, 'face series')
534 .catch(error => String(error))
535 .then(unsaved => {
536 if (unsaved === undefined) return
537 settings = { ...settings, series }
538 report($, `Could not switch to ${titled(wanted)}: ${unsaved}. Set "Face series" in /config.`)
539 })
540 .catch(() => {})
541 return `${titled(wanted)} now. Slap away.`
542}
543
544async function onSlap($: EngineInterface, slap: Slap) {
545 if (calibration !== undefined) return
546 // Another session may have turned slaps off or on; follow it here too.
547 if (await isOff($)) {
548 if (sensorStatus !== OFF_STATUS) await goOff($)
549 return
550 }
551 goOn($)
552 if (!(await isActive($))) return
553
554 const now = await $.clock.now()
555 const gap = combo === undefined ? undefined : slap.ts - combo.at
556 const prior = gap !== undefined && gap >= 0 && gap <= COMBO_MS ? combo : undefined
557 // The slap's level in its combo, which never drops until the combo ends:
558 // what she shows and says, and what stops Claude. The score keeps what the
559 // sensor read.
560 const level = Math.min(Math.max(slap.level, (prior?.level ?? 0) + 1), 5)
561 combo = {
562 count: (prior?.count ?? 0) + 1,
563 since: prior?.since ?? slap.ts,
564 at: slap.ts,
565 weakest: Math.min(prior?.weakest ?? slap.level, slap.level),
566 level,
567 }
568
569 const n = await update($, count, c => c + 1)
570 await update($, last, () => slap)
571 await $.store.set('total', Number((await $.store.get('total')) ?? 0) + 1)
572
573 // Telling Claude and stopping its turn are off unless /slaps claude on.
574 const isClaudeOn = (await $.store.get('claude')) === true
575 const turnId = await read($, turn)
576 // A combo stops a turn only if none of its slaps barely registered (level
577 // 1), so steady shaking, a train or heavy typing, never does, and only once
578 // it has lasted COMBO_STOP_MS.
579 const isHard = slap.level >= settings.stopLevel
580 const isComboStop = combo.weakest >= 2 && slap.ts - combo.since >= COMBO_STOP_MS
581 const isStopping = isClaudeOn && turnId !== null && level >= settings.stopLevel && (isHard || isComboStop)
582
583 setSensorStatus($, `spank: ${n} this session, last L${slap.level} (${slap.peak.toFixed(2)}g)`)
584
585 const { captions } = voiceOf()
586 const line = captions[level - 1] ?? captions[0]
587 // A combo puts up a toast as it starts (unless one as hard is showing) and
588 // one when it ends, saying how far it got, not one per slap; a stop always
589 // says so.
590 // The end toast waits for a second with no slap; one still to come when a
591 // new combo starts is the last one's, shown then.
592 const inRow = combo.count
593 settleComboEnd(inRow === 1)
594 if (inRow > 1 && !isStopping) {
595 const text = `${line} L${level}, ${inRow} in a row`
596 const show = async () => {
597 comboEnd = undefined
598 if (calibration !== undefined || (await isOff($)) || !(await isActive($))) return
599 showToast($, await $.clock.now(), level, text)
600 }
601 comboEnd = { timer: $.clock.after(COMBO_MS, () => void show().catch(() => {})), show }
602 }
603 if (isStopping) {
604 showToast($, now, level, `Stopped Claude. L${level}`)
605 } else if (inRow === 1 && (toast === undefined || now - toast.at >= TOAST_MS || level > toast.level)) {
606 showToast($, now, level, `${line} L${level}`)
607 }
608 if ((await $.store.get('muted')) !== true) voice($, level, now)
609 await showFace($, { level, peak: slap.peak, line, combo: inRow })
610
611 if (!isClaudeOn) return
612 if (burst.length === 0) burstSince = now
613 burst.push(slap)
614 if (turnId === null) return // told as the next turn starts
615 if (isStopping) {
616 await update($, turn, () => null)
617 await $.turn.abort({ turnId }).catch(() => {})
618 await tellClaude($, isHard ? 'stopped' : 'combo')
619 return
620 }
621 cancelBurstTimer()
622 const wait = Math.max(0, Math.min(BURST_MS, burstSince + BURST_MAX_MS - now))
623 burstTimer = $.clock.after(wait, () => void tellClaude($, 'turn'))
624}
625
626// slapd ships as Swift source and is built on first run (and again when its
627// source is newer than the build), so installing needs only Xcode's command
628// line tools. Builds to a temporary name and renames, so two sessions starting
629// together never run a half-written binary. Resolves an error, or undefined.
630async function buildSlapd($: EngineInterface): Promise<string | undefined> {
631 const source = `${$.plugin.root}/slapd/main.swift`
632 const binary = `${$.plugin.root}/bin/slapd`
633 if ((await $.fs.exists(binary)) && (await $.fs.stat(binary)).mtimeMs >= (await $.fs.stat(source)).mtimeMs) {
634 return undefined
635 }
636
637 sensorSaid = 'spank: building the sensor reader (first run, about 20s)'
638 setSensorStatus($, sensorSaid)
639 const temporary = `${binary}.${await $.clock.now()}.tmp`
640 await $.process.run(['/bin/mkdir', '-p', `${$.plugin.root}/bin`])
641 const built = await $.process.run(['/usr/bin/swiftc', '-O', '-swift-version', '5', '-o', temporary, source], {
642 timeoutMs: 300_000,
643 })
644 if (built.exitCode !== 0) {
645 if (/xcode-select|developer path|CommandLineTools/i.test(built.stderr)) {
646 return 'needs Xcode command line tools: run xcode-select --install'
647 }
648 return `build failed: ${built.stderr.trim().split('\n').pop() ?? `swiftc exited ${built.exitCode}`}`
649 }
650 const moved = await $.process.run(['/bin/mv', '-f', temporary, binary])
651 return moved.exitCode === 0 ? undefined : `build failed: ${moved.stderr.trim()}`
652}
653
654// Runs slapd for the module's life: it prints one JSON line per hit, and
655// leaving this loop (a reload, the session ending) kills it.
656async function listen($: EngineInterface) {
657 const buildError = await buildSlapd($).catch(error => `build failed: ${String(error)}`)
658 if (buildError !== undefined) {
659 sensorSaid = `spank: sensor off (${buildError})`
660 setSensorStatus($, sensorSaid)
661 return
662 }
663
664 const slapd = $.process.spawn({ argv: [`${$.plugin.root}/bin/slapd`, '--threshold', String(settings.threshold)] })
665 const lines = lineSplitter()
666 let lastError = ''
667
668 try {
669 for await (const { stream, text } of slapd) {
670 if (stream === 'stderr') {
671 lastError = text.trim().split('\n').pop() ?? lastError
672 continue
673 }
674 for (const line of lines(text)) {
675 const parsed = parseLine(line)
676 if (parsed?.type === 'start') {
677 sensorSaid = `spank: armed (${settings.threshold}g)`
678 setSensorStatus($, (await isOff($)) ? OFF_STATUS : sensorSaid)
679 }
680 if (parsed?.type === 'slap') await onSlap($, { ts: parsed.ts, peak: parsed.peak, level: levelOf(parsed.peak) })
681 }
682 }
683 } catch (error) {
684 lastError = String(error)
685 }
686
687 sensorSaid = `spank: sensor off (${lastError || 'slapd exited'})`
688 setSensorStatus($, sensorSaid)
689}
690
691export const register: Register = (on, options) => {
692 settings = readSettings(options)
693 dropSlaps()
694 toast = undefined
695 calibration = undefined
696 sensorStatus = undefined
697 sensorSaid = undefined
698 probePng = undefined
699 bandRequestId = undefined
700
701 on('session.start', async ($, e, next) => {
702 const started = await next(e)
703 // A reload drops the timers that would hide a face or picture left showing.
704 await update($, face, () => null)
705 await update($, probe, () => false)
706 await markActive($).catch(() => {})
707 await $.command.register({
708 name: 'slaps',
709 description:
710 'How many times you hit the laptop; pick who gets hit, calibrate, turn off, mute, or let slaps reach Claude',
711 argumentHint: '[who [series]|calibrate|off|on|mute|unmute|claude on|claude off|image]',
712 immediate: true,
713 })
714 void listen($)
715 return started
716 })
717
718 on('prompt.submit', async ($, e, next) => {
719 await markActive($).catch(() => {})
720 return next(e)
721 })
722
723 // A calibration times its typing from the first key in the prompt box.
724 on('prompt.edit', async ($, e, next) => {
725 const run = calibration
726 if (run?.step === 'waiting' && run.typedAt === undefined) {
727 const now = await $.clock.now()
728 run.typedAt ??= now
729 }
730 return next(e)
731 })
732
733 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
734 // Read before any early return, so a later change redraws the band.
735 const shown = await read($, face)
736 const png = (await read($, probe)) ? probePng : undefined
737 if (e.props.hasSurvey || e.surface !== 'terminal') return next(e)
738 const art = shown === null ? undefined : faceArt(shown.level, e.props.maxRows, e.props.bodyColumns)
739 if (art === undefined && png === undefined) return next(e)
740
741 bandRequestId = e.requestId
742 const { Box, Image, Raster, Text } = $.ui.resolve(e)
743
744 return (
745 <Box flexDirection="row" alignItems="center" gap={2}>
746 {png !== undefined ? (
747 <Image key="probe" source={{ png }} columns={24} rows={12} alt="[spank: this terminal drew no picture]" />
748 ) : null}
749 {art !== undefined && shown !== null ? (
750 <Box flexDirection="row" alignItems="center" gap={2}>
751 <Raster key="face" columns={art.columns} rows={art.rows} cells={art.cells} />
752 <Box flexDirection="column">
753 <Text bold>{shown.line}</Text>
754 <Text dimColor>
755 level {shown.level} of 5, {shown.peak.toFixed(2)}g{shown.combo > 1 ? `, ${shown.combo} in a row` : ''}
756 </Text>
757 </Box>
758 </Box>
759 ) : null}
760 </Box>
761 )
762 })
763
764 on('turn.start', async ($, e, next) => {
765 await update($, turn, () => e.turnId)
766 // A combo begun before the turn does not carry into it, so it cannot stop
767 // the turn on its first slap.
768 combo = undefined
769 await tellClaude($, 'idle')
770 return next(e)
771 })
772
773 // A burst still waiting when the turn ends is told with the next turn.
774 on('turn.complete', async ($, e, next) => {
775 if ((await read($, turn)) === e.turnId) {
776 await update($, turn, () => null)
777 cancelBurstTimer()
778 }
779 return next(e)
780 })
781
782 on('command.run', { command: 'slaps' }, async ($, e) => {
783 await markActive($).catch(() => {})
784 const arg = e.args.trim()
785 const [subcommand, ...rest] = arg.split(/\s+/)
786 if (subcommand === 'who') return { text: who($, rest.join(' ').toLowerCase()) }
787 if (arg === 'off' || arg === 'on') {
788 const isTurningOff = arg === 'off'
789 await $.store.set('off', isTurningOff)
790 if (isTurningOff) {
791 await goOff($)
792 return { text: 'Slaps off: no faces, voice or notes to Claude until /slaps on.' }
793 }
794 goOn($)
795 return { text: 'Slaps on. Slap away.' }
796 }
797 if (arg === 'mute' || arg === 'unmute') {
798 await $.store.set('muted', arg === 'mute')
799 return { text: arg === 'mute' ? 'Laptop voice off.' : 'Laptop voice on.' }
800 }
801 if (arg === 'calibrate') {
802 if (calibration !== undefined) return { text: 'Already calibrating; wait for its result.' }
803 void calibrate($)
804 return {
805 text:
806 `Calibrating. Start typing in the prompt box, without pressing Enter: ` +
807 `${CALIBRATE_TYPING_MS / 1000} seconds from your first key. When the toast says so, knock on the desk ` +
808 `3 times: ${CALIBRATE_KNOCKING_MS / 1000} seconds from your first knock.`,
809 }
810 }
811 if (arg === 'image') {
812 // Draws a real picture above the prompt, then asks the terminal to take
813 // it again: a refusal says the terminal drew the alt text instead.
814 const picture = `${$.plugin.root}/assets/faces/${settings.series}/level_1.png`
815 const bytes = await $.fs.read(picture, { as: 'bytes' }).catch(() => undefined)
816 if (bytes === undefined) return { text: `Image probe: no picture to try (${picture} is missing).` }
817 const { base64 } = bytes
818 probePng = base64
819 await update($, probe, () => true)
820 await $.clock.sleep(1000)
821 const blitted =
822 bandRequestId === undefined
823 ? { deny: 'the band above the prompt was not drawn' }
824 : await $.ui.blit({ requestId: bandRequestId, key: 'probe', source: { png: base64 } })
825 $.clock.after(PROBE_MS, () => void update($, probe, () => false))
826
827 return {
828 text:
829 blitted.deny === undefined
830 ? 'Image probe: the terminal took the picture. You should see a face above the prompt for 10s.'
831 : `Image probe: no picture here (${blitted.deny}).`,
832 }
833 }
834 if (arg === 'claude on' || arg === 'claude off') {
835 const isOn = arg === 'claude on'
836 await $.store.set('claude', isOn)
837 if (!isOn) {
838 burst = []
839 cancelBurstTimer()
840 }
841 return {
842 text: isOn
843 ? 'Slaps now reach Claude, and a hard one stops its turn.'
844 : 'Slaps no longer reach Claude or stop its turn.',
845 }
846 }
847
848 const n = await read($, count)
849 const slap = await read($, last)
850 const total = Number((await $.store.get('total')) ?? 0)
851 const lastText = slap ? `last one level ${slap.level}, ${slap.peak.toFixed(2)}g` : 'none yet'
852 const offText = (await isOff($)) ? ' Off: /slaps on to turn them back on.' : ''
853
854 return { text: `${n} slaps this session, ${total} all time; ${lastText}.${offText}` }
855 })
856}
857hooks/series.ts 32 lines1import type { SeriesId } from './faces'
2
3// A voice: a clip per slap level, assets/voices/<voice>/level_<1-5>.mp3, and
4// what each one says, shown beside the face and in the toast.
5export type Voice = { captions: readonly [string, string, string, string, string] }
6
7export const VOICES = {
8 sakura: { captions: ['んっ!', 'あっ!', 'いたっ!', 'きゃっ!', 'あぁっ…!'] },
9 natsu: { captions: ['えっ!', 'うっ!', 'いてっ!', 'やっ!', 'うわぁっ!'] },
10 aki: { captions: ['ひゃっ!', 'あれっ!', 'いたぁ!', 'いやっ!', 'きゃあっ!'] },
11} as const satisfies Record<string, Voice>
12
13export type VoiceId = keyof typeof VOICES
14
15// A face series: its faces are assets/faces/<series>/level_<1-5>.png (drawn
16// into faces.ts by `make faces`), and it speaks with one of the voices; a
17// series with no voice of its own can borrow another's. The face_series
18// setting picks one, so its options in plugin.json list every series.
19export type Series = { voice: VoiceId }
20
21export const SERIES: Record<SeriesId, Series> = {
22 sakura: { voice: 'sakura' },
23 natsu: { voice: 'natsu' },
24 aki: { voice: 'aki' },
25}
26
27export const DEFAULT_SERIES: SeriesId = 'sakura'
28
29export function isSeries(value: unknown): value is SeriesId {
30 return typeof value === 'string' && Object.hasOwn(SERIES, value)
31}
32types/index.d.ts 12 lines1export type Slap = { ts: number; peak: number; level: number }
2
3// The face drawn above the prompt for a moment after a slap: its level (a
4// combo's added), the sensor's reading, and how many slaps came in a row.
5export type FaceShown = { level: number; peak: number; line: string; combo: number }
6
7declare module 'claude-code' {
8 interface PluginState {
9 spank: { count: number; last: Slap | null; turn: string | null; face: FaceShown | null; probe: boolean }
10 }
11}
12