SLOPSHOPPER

sfx-gen

Generate sound effects from text prompts with a local Stable Audio model (sa3.cpp), no API, no Python

panebandguardcommandtoaststatus
★ 2v0.3.0MITupdated 2026-10-11nkapila6/sfx-gen
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · sfx-gen
│ ┃ Sound effects ✕ › fix the failing auth test and add an audit log call │ ┃ ╭──────────────────────────────────────────╮ │ ┃ │ ~/sfx 0 clips · small-sfx │ ⏺ Read(src/auth.ts) │ ┃ │ $ /sfx a whoosh across the screen │ ⎿ Read 6 lines │ ┃ ╰──────────────────────────────────────────╯ ⏺ Update(src/auth.ts) │ ⎿ Added 2 lines, removed 1 line │ ⏺ Bash(bun test) │ ⎿ 3 pass, 1 fail │ │ ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ › /sfx │ ⎿ sfx-gen: usage /sfx <description> [--duration N] [--seed N] │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · Sound effects
╭──────────────────────────────────────────────────────────╮ │ ~/sfx 0 clips · small-sfx │ │ $ /sfx a whoosh across the screen │ ╰──────────────────────────────────────────────────────────╯
README

sfx-gen

License: MIT Version Platforms Stars

Sound effects from a text prompt, inside Claude Code, OpenCode, or omp. Runs a small Stable Audio model locally through sa3.cpp: no API key, no Python, about 1.5s for an 8s clip on Apple Silicon. macOS, Linux, Windows.

https://github.com/user-attachments/assets/2987d1f3-53e9-4546-b5a7-2018d2dbacfc

Demo

SoundPromptPlay
whoosha whoosh across the screenhttps://github.com/user-attachments/files/33307790/whoosh.mp3
impactdeep cinematic impact boom with a short metallic tailhttps://github.com/user-attachments/files/33307815/impact.mp3
screamscreamhttps://github.com/user-attachments/files/33307819/scream.mp3

| whistle | whistle | https://github.com/user-attachments/files/33307822/whistle.mp3 |\ | crowd | whistle and clap like a crowd | https://github.com/user-attachments/files/33307829/crowd.mp3 | | clap-repeatedly | clap repeatedly | https://github.com/user-attachments/files/33307833/clap-repeatedly.mp3 | | alarm | short sharp electronic alarm beep, two quick urgent tones | https://github.com/user-attachments/files/33307836/alarm.mp3 | chime | a soft rising two-note chime | https://github.com/user-attachments/files/33307844/chime.mp3 |

Install

macOS / Linux:

curl -fsSL https://raw.githubusercontent.com/nkapila6/sfx-gen/main/install.sh | bash

No terminal handy? Ask your agent to install it for you: "install github.com/nkapila6/sfx-gen". The installer also detects OpenCode and omp (oh-my-pi) and wires the sfx tool into whichever it finds.

Windows (PowerShell):

irm https://raw.githubusercontent.com/nkapila6/sfx-gen/main/install.ps1 | iex

Nothing gets compiled. It downloads a prebuilt sa3.cpp (checksum verified), fetches the weights from HuggingFace (~1 GB, into ~/.claude/sa3), and installs the plugin. Safe to re-run. macOS and Windows use sa3.cpp's own releases; Linux (arm64, or x86_64 with AVX2, meaning 2013+ Intel or any Ryzen, glibc 2.35+) uses a CPU build hosted on this repo's releases, so expect ~5-10s per clip there instead of ~1.5s on Apple Silicon.

Use

/sfx a whoosh across the screen
/sfx footsteps on gravel --duration 6 --seed 42
/sfx-pane                                   this session's clips, play, mp3
/sfx-pane history                           toggle older clips
/sfx-notify error a blood-curdling scream   sound for failed tool calls

Or just ask Claude ("make me a door creak", "use a doorbell when you need me"). It calls the sfx tool, and notify_on assigns the clip to an event.

/sfx-notify events: error (a tool call failed), permission (Claude is waiting on you), done (reply finished), abort (you interrupted), compact. /sfx-notify alone lists them, <event> test plays one, <event> off clears it, off/on mutes everything. The sounds live in ~/.claude/sfx-gen and play instantly since they're generated once.

The mp3 button needs ffmpeg. It copies the file to the clipboard on macOS, Windows, and Linux with wl-copy or xclip.

Config

Change with claude plugin configure sfx-gen@sfx-gen.

OptionDefault
sa3_dir~/.claude/sa3 via the installerfolder with build/bin/sa3-generate and models/
modelsmall-sfxsmall-sfx, small-music, medium
deviceautoauto, cpu, metal
encodingq5_k_mmust match the downloaded weights
duration8default clip length in seconds

Hacking on it: claude --plugin-dir /path/to/sfx-gen with your own sa3.cpp build, or set SA3_CPP_DIR.

MIT. Model weights are under the Stability AI Community License.

Source 2 files
hooks/register.tsx 729 lines
1// sfx-gen: generate sound effects from text with a local Stable Audio model.
2// Shells out to sa3.cpp's sa3-generate binary. No Python, no API key.
3
4import { atom, read, update } from 'claude-code'
5import type { EngineInterface, Register } from 'claude-code'
6
7import type { Clip } from '../types'
8
9type Engine = EngineInterface
10
11const PANE = 'sfx'
12const PANE_TITLE = 'Sound effects'
13const STORE_KEY = 'clips'
14const MAX_CLIPS = 50
15
16const clipsRef = { plugin: 'sfx-gen', key: 'clips' } as const
17const clips = atom(clipsRef, [])
18const pending = atom({ plugin: 'sfx-gen', key: 'pending' } as const, null)
19const dismissed = atom({ plugin: 'sfx-gen', key: 'dismissed' } as const, null)
20const showHistory = atom({ plugin: 'sfx-gen', key: 'showHistory' } as const, false)
21const since = atom({ plugin: 'sfx-gen', key: 'since' } as const, 0)
22
23const DEFAULTS = {
24  model: 'small-sfx',
25  device: 'auto',
26  encoding: 'q5_k_m',
27  duration: 8,
28}
29
30type Config = typeof DEFAULTS & { sa3Dir?: string }
31let config: Config = { ...DEFAULTS }
32
33type GenOpts = {
34  prompt: string
35  duration?: number | string | null
36  seed?: number | string | null
37  steps?: number | string | null
38  // write here instead of the session cwd (notify sounds live outside any project)
39  outPath?: string
40}
41
42type GenResult =
43  | { ok: true; clip: Clip; base64: string }
44  | { ok: false; error: string }
45
46const ACCENT = 'green'
47const WAVE_WIDTH = 32
48const FLAT = '·'.repeat(WAVE_WIDTH)
49
50// Moments the mod can ring for, each mapped to a pre-generated clip.
51const NOTIFY_EVENTS = ['error', 'permission', 'done', 'abort', 'compact'] as const
52type NotifyEvent = (typeof NOTIFY_EVENTS)[number]
53type NotifySound = { prompt: string; path: string; wave?: string }
54type NotifyConfig = { on: boolean; sounds: Partial<Record<NotifyEvent, NotifySound>> }
55
56const NOTIFY_KEY = 'notify'
57const NOTIFY_DURATION = 2
58// a burst of failing calls should scream once, not ten times
59const NOTIFY_GAP_MS = 2000
60const NOTIFY_HINT: Record<NotifyEvent, string> = {
61  error: 'a tool call or test run fails',
62  permission: 'Claude is waiting on you',
63  done: 'a reply finished',
64  abort: 'you interrupted a reply',
65  compact: 'the conversation was compacted',
66}
67
68let notify: NotifyConfig = { on: true, sounds: {} }
69const notifyAudio = new Map<NotifyEvent, string>()
70const lastRing = new Map<NotifyEvent, number>()
71
72function isNotifyEvent(v: unknown): v is NotifyEvent {
73  return typeof v === 'string' && (NOTIFY_EVENTS as readonly string[]).includes(v)
74}
75
76function boxed(lines: string[]) {
77  const w = Math.max(...lines.map(l => l.length))
78  return ['', `╭${'─'.repeat(w + 2)}╮`, ...lines.map(l => `│ ${l.padEnd(w)} │`), `╰${'─'.repeat(w + 2)}╯`].join('\n')
79}
80
81const POWERSHELL = 'C:/Windows/System32/WindowsPowerShell/v1.0/powershell.exe'
82
83type OS = 'mac' | 'linux' | 'windows'
84let osCache: OS | null = null
85
86// The module sandbox has no process.platform, so sniff it.
87async function detectOS($: Engine): Promise<OS> {
88  if (osCache) return osCache
89  if ((await $.env.get('OS')) === 'Windows_NT') osCache = 'windows'
90  else if (await $.fs.exists('/System/Library/CoreServices')) osCache = 'mac'
91  else osCache = 'linux'
92  return osCache
93}
94
95async function homeDir($: Engine) {
96  return ((await $.env.get('HOME')) || (await $.env.get('USERPROFILE')) || '').replace(/\\/g, '/')
97}
98
99function binaryCandidates(root: string, os: OS) {
100  const exe = os === 'windows' ? 'sa3-generate.exe' : 'sa3-generate'
101  return [`${root}/build-metal/bin/${exe}`, `${root}/build/bin/${exe}`, `${root}/build/bin/Release/${exe}`]
102}
103
104// Absolute paths first, then a PATH lookup through which/where.
105async function findTool($: Engine, name: string, known: string[] = []) {
106  const os = await detectOS($)
107  const hit = await firstExisting($, known)
108  if (hit) return hit
109  const lookup = os === 'windows' ? ['C:/Windows/System32/where.exe', name] : ['/usr/bin/which', name]
110  try {
111    const r = await $.process.run(lookup)
112    const first = r.stdout.split(/\r?\n/)[0]?.trim()
113    if (r.exitCode === 0 && first) return first
114  } catch {}
115  return null
116}
117
118// Parse a prompt string, pulling out --duration/--dur, --seed, --steps flags.
119function parseArgs(raw: string | undefined) {
120  let text = (raw || '').trim()
121  const grab = (re: RegExp) => {
122    const m = text.match(re)
123    if (!m) return null
124    text = text.replace(re, ' ').trim()
125    return m[1] ?? null
126  }
127  const duration = grab(/(?:^|\s)--(?:duration|dur)[ =](-?\d+(?:\.\d+)?)/i) ?? grab(/(?:^|\s)-d[ =](\d+(?:\.\d+)?)/i)
128  const seed = grab(/(?:^|\s)--seed[ =](\d+)/i)
129  const steps = grab(/(?:^|\s)--steps[ =](\d+)/i)
130  return { prompt: text, duration, seed, steps }
131}
132
133function errText(err: unknown) {
134  return err instanceof Error ? err.message : String(err)
135}
136
137function slug(text: string) {
138  return text.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '').slice(0, 40) || 'sfx'
139}
140
141function basename(path: string) {
142  return path.split('/').pop() ?? path
143}
144
145const B64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
146const BARS = '▁▂▃▄▅▆▇█'
147
148// No atob or Buffer in the module sandbox, so decode by hand.
149function fromBase64(b64: string) {
150  const clean = b64.replace(/[^A-Za-z0-9+/]/g, '')
151  const out = new Uint8Array(Math.floor((clean.length * 3) / 4))
152  let o = 0
153  for (let i = 0; i < clean.length; i += 4) {
154    const n =
155      (B64.indexOf(clean.charAt(i)) << 18) |
156      (B64.indexOf(clean.charAt(i + 1)) << 12) |
157      ((B64.indexOf(clean[i + 2] ?? 'A') & 63) << 6) |
158      (B64.indexOf(clean[i + 3] ?? 'A') & 63)
159    if (o < out.length) out[o++] = (n >> 16) & 255
160    if (o < out.length) out[o++] = (n >> 8) & 255
161    if (o < out.length) out[o++] = n & 255
162  }
163  return out
164}
165
166// Peak per bucket from a PCM16 or float32 wav, drawn as block characters.
167function waveform(b64: string, width = WAVE_WIDTH) {
168  try {
169    const buf = fromBase64(b64)
170    const dv = new DataView(buf.buffer)
171    let fmt = 1
172    let bits = 16
173    let pos = 12
174    let data = -1
175    let size = 0
176    while (pos + 8 <= buf.length) {
177      const id = String.fromCharCode(dv.getUint8(pos), dv.getUint8(pos + 1), dv.getUint8(pos + 2), dv.getUint8(pos + 3))
178      const len = dv.getUint32(pos + 4, true)
179      if (id === 'fmt ') {
180        fmt = dv.getUint16(pos + 8, true)
181        bits = dv.getUint16(pos + 22, true)
182      } else if (id === 'data') {
183        data = pos + 8
184        size = Math.min(len, buf.length - data)
185        break
186      }
187      pos += 8 + len + (len & 1)
188    }
189    if (data < 0 || (bits !== 16 && !(fmt === 3 && bits === 32))) return ''
190    const step = bits / 8
191    const count = Math.floor(size / step)
192    const per = Math.max(1, Math.floor(count / width))
193    const peaks: number[] = []
194    for (let b = 0; b < width; b++) {
195      let peak = 0
196      // stride through the bucket, a sparkline doesn't need every sample
197      for (let i = b * per; i < (b + 1) * per && i < count; i += 16) {
198        const at = data + i * step
199        const v = bits === 16 ? dv.getInt16(at, true) / 32768 : dv.getFloat32(at, true)
200        peak = Math.max(peak, Math.abs(v))
201      }
202      peaks.push(peak)
203    }
204    const max = Math.max(...peaks) || 1
205    return peaks.map(p => BARS[Math.min(7, Math.floor((p / max) * 7.99))]).join('')
206  } catch {
207    return ''
208  }
209}
210
211async function firstExisting($: Engine, paths: string[]) {
212  for (const p of paths) if (await $.fs.exists(p)) return p
213  return null
214}
215
216async function saveClips($: Engine, list: Clip[]) {
217  try {
218    await $.store.set(STORE_KEY, list)
219  } catch (err) {
220    $.ui.toast('sfx-gen: could not persist clips: ' + errText(err))
221  }
222}
223
224async function addClip($: Engine, clip: Clip) {
225  await update($, clips, list => [...(list ?? []), clip].slice(-MAX_CLIPS))
226  await saveClips($, await read($, clips))
227}
228
229async function generate($: Engine, opts: GenOpts): Promise<GenResult> {
230  const envDir = await $.env.get('SA3_CPP_DIR')
231  const sa3Dir = (config.sa3Dir || envDir || '').trim()
232  const { model, encoding, device } = config
233  const duration = Number(opts.duration ?? config.duration)
234  const prompt = (opts.prompt || '').trim()
235
236  if (!prompt) return { ok: false, error: 'empty prompt' }
237
238  const candidates = binaryCandidates(sa3Dir.replace(/\\/g, '/'), await detectOS($))
239  const bin = await firstExisting($, candidates)
240  const modelsDir = sa3Dir + '/models'
241
242  if (!bin) {
243    return { ok: false, error: `sa3-generate not found under ${sa3Dir || '(sa3_dir unset)'}. Set the sa3_dir config or run the installer.` }
244  }
245  if (!(await $.fs.exists(modelsDir))) {
246    return { ok: false, error: `models dir not found: ${modelsDir}. Run sa3.cpp's ./models.sh first.` }
247  }
248
249  const id = String(Date.now())
250  const outPath = opts.outPath ?? `${await $.session.cwd()}/.sfx-${id}.wav`
251
252  const argv = [
253    bin,
254    '--model', model,
255    '--encoding', encoding,
256    '--models-dir', modelsDir,
257    '--prompt', prompt,
258    '--duration', String(duration),
259    '--out', outPath,
260  ]
261  if (opts.seed != null) argv.push('--seed', String(opts.seed))
262  if (opts.steps != null) argv.push('--steps', String(opts.steps))
263
264  const init: { timeoutMs: number; env?: Record<string, string> } = { timeoutMs: 180000 }
265  if (device === 'cpu') init.env = { SA3_DEVICE: 'cpu' }
266
267  const started = Date.now()
268  $.ui.status(`generating ${duration}s sfx with ${model} (${device})...`)
269  await update($, pending, () => ({ prompt, duration, model, device }))
270
271  try {
272    let run
273    try {
274      run = await $.process.run(argv, init)
275    } catch (err) {
276      return { ok: false, error: `sa3-generate failed to start: ${errText(err)}` }
277    }
278    if (run.exitCode !== 0) {
279      return { ok: false, error: `sa3-generate exited ${run.exitCode}: ${run.stderr || run.stdout}` }
280    }
281
282    let bytes
283    try {
284      bytes = await $.fs.read(outPath, { as: 'bytes' })
285    } catch (err) {
286      return { ok: false, error: `wrote ${outPath} but could not read it back: ${errText(err)}` }
287    }
288
289    const elapsed = ((Date.now() - started) / 1000).toFixed(1)
290    const clip: Clip = { id, prompt, path: outPath, duration, elapsed, model, at: started, wave: waveform(bytes.base64) }
291    await addClip($, clip)
292    return { ok: true, clip, base64: bytes.base64 }
293  } finally {
294    $.ui.status(undefined)
295    await update($, pending, () => null)
296  }
297}
298
299async function saveNotify($: Engine) {
300  try {
301    await $.store.set(NOTIFY_KEY, notify)
302  } catch (err) {
303    $.ui.toast('sfx-gen: could not save notify sounds: ' + errText(err))
304  }
305}
306
307async function notifyDir($: Engine) {
308  const dir = `${await homeDir($)}/.claude/sfx-gen`
309  if (await $.fs.exists(dir)) return dir
310  // $.fs has no mkdir
311  const argv =
312    (await detectOS($)) === 'windows'
313      ? [POWERSHELL, '-NoProfile', '-Command', 'New-Item -ItemType Directory -Force -Path $args[0] | Out-Null', dir]
314      : ['/bin/mkdir', '-p', dir]
315  await $.process.run(argv)
316  return dir
317}
318
319// Generate a short clip and make it the sound for one event.
320async function assignNotify($: Engine, event: NotifyEvent, opts: GenOpts): Promise<GenResult> {
321  const outPath = `${await notifyDir($)}/notify-${event}.wav`
322  const r = await generate($, { ...opts, duration: opts.duration ?? NOTIFY_DURATION, outPath })
323  if (!r.ok) return r
324  notify.sounds[event] = { prompt: r.clip.prompt, path: outPath, wave: r.clip.wave }
325  notify.on = true
326  notifyAudio.set(event, r.base64)
327  await saveNotify($)
328  return r
329}
330
331// Play an event's sound from memory; read the wav once on first use.
332async function ring($: Engine, event: NotifyEvent) {
333  const sound = notify.sounds[event]
334  if (!notify.on || !sound) return
335  const now = Date.now()
336  if (now - (lastRing.get(event) ?? 0) < NOTIFY_GAP_MS) return
337  lastRing.set(event, now)
338  try {
339    let base64 = notifyAudio.get(event)
340    if (!base64) {
341      base64 = (await $.fs.read(sound.path, { as: 'bytes' })).base64
342      notifyAudio.set(event, base64)
343    }
344    // say why a sound just went off
345    $.ui.toast(`♪ ${event}: "${sound.prompt}"`)
346    await $.audio.play({ base64, mime: 'audio/wav' })
347  } catch (err) {
348    $.ui.toast(`sfx-gen: cannot play the ${event} sound: ${errText(err)}`)
349  }
350}
351
352// Claude usually runs `npm test | tail`, which exits 0 and never counts as an error,
353// so also catch the summary lines common test runners print.
354const TEST_FAIL = [
355  /^\s*(ℹ|#)\s*fail\s+[1-9]/m, // node --test, tap
356  /\b[1-9]\d*\s+(failed|failing)\b/i, // jest, vitest, pytest, mocha
357  /^FAIL\b/m, // jest file header
358  /^--- FAIL:/m, // go test
359  /^FAILED\b/m, // pytest short summary, cargo
360]
361
362function looksLikeTestFailure(r: { text?: string; result?: unknown }) {
363  const res = r.result as { stdout?: unknown; stderr?: unknown } | undefined
364  const out =
365    typeof r.text === 'string' ? r.text : [res?.stdout, res?.stderr].filter(v => typeof v === 'string').join('\n')
366  return TEST_FAIL.some(re => re.test(out))
367}
368
369function notifyList() {
370  const lines = [`❯ sfx-notify  ${notify.on ? 'on' : 'off (muted)'}`]
371  for (const ev of NOTIFY_EVENTS) {
372    const s = notify.sounds[ev]
373    lines.push(`${ev.padEnd(10)} ${s ? `"${s.prompt}"` : '·  ' + NOTIFY_HINT[ev]}`)
374  }
375  lines.push('', 'set   /sfx-notify <event> <description>', 'test  /sfx-notify <event> test', 'clear /sfx-notify <event> off', 'mute  /sfx-notify off | on')
376  return boxed(lines)
377}
378
379async function runNotify($: Engine, raw: string | undefined) {
380  const args = (raw || '').trim()
381  if (!args) return notifyList()
382
383  if (args === 'on' || args === 'off') {
384    notify.on = args === 'on'
385    await saveNotify($)
386    return notifyList()
387  }
388
389  const [head = '', ...rest] = args.split(/\s+/)
390  const event = head.toLowerCase()
391  if (!isNotifyEvent(event)) return `✗ unknown event "${head}". Pick one of: ${NOTIFY_EVENTS.join(', ')}`
392  const tail = rest.join(' ').trim()
393
394  if (tail === 'off') {
395    delete notify.sounds[event]
396    notifyAudio.delete(event)
397    await saveNotify($)
398    return notifyList()
399  }
400  if (tail === 'test' || !tail) {
401    if (!notify.sounds[event]) return `✗ no ${event} sound yet. Try /sfx-notify ${event} a short alarm beep`
402    lastRing.delete(event)
403    await ring($, event)
404    return `❯ played the ${event} sound: "${notify.sounds[event]?.prompt}"`
405  }
406
407  const r = await assignNotify($, event, parseArgs(tail))
408  if (!r.ok) return `✗ ${r.error}`
409  // don't hold the output until the clip finishes playing
410  void $.audio.play({ base64: r.base64, mime: 'audio/wav' }).catch(() => {})
411  return boxed([
412    `❯ ${event} → "${r.clip.prompt}"`,
413    r.clip.wave || FLAT,
414    `${r.clip.duration}s · plays when ${NOTIFY_HINT[event]}`,
415  ])
416}
417
418// Shared tail of /sfx and the tool: toast, play, show the pane.
419async function announce($: Engine, r: GenResult, play: boolean) {
420  if (!r.ok) {
421    $.ui.toast('sfx-gen: ' + r.error)
422    return
423  }
424  $.ui.toast(`sfx ready: ${r.clip.prompt} (${r.clip.elapsed}s)`)
425  void $.ui.open({ id: PANE, title: PANE_TITLE })
426  // fire and forget: awaiting would block /sfx output and the tool result for the clip's length
427  if (play) void $.audio.play({ base64: r.base64, mime: 'audio/wav' }).catch(() => {})
428}
429
430async function playClip($: Engine, clip: Clip) {
431  try {
432    const bytes = await $.fs.read(clip.path, { as: 'bytes' })
433    await $.audio.play({ base64: bytes.base64, mime: 'audio/wav' })
434  } catch (err) {
435    $.ui.toast(`sfx-gen: cannot play ${clip.path}: ${errText(err)}`)
436  }
437}
438
439// A file reference on the clipboard pastes as an attachment in chat apps.
440async function copyFileRef($: Engine, path: string) {
441  const os = await detectOS($)
442  try {
443    if (os === 'mac') {
444      const cp = await $.process.run([
445        '/usr/bin/osascript',
446        '-e', 'on run argv',
447        '-e', 'set the clipboard to (POSIX file (item 1 of argv))',
448        '-e', 'end run',
449        path,
450      ])
451      return cp.exitCode === 0
452    }
453    if (os === 'windows') {
454      const cp = await $.process.run([POWERSHELL, '-NoProfile', '-Command', 'Set-Clipboard -Path $args[0]', path])
455      return cp.exitCode === 0
456    }
457    // file managers and chat apps read a uri-list as "these files"
458    const uri = { stdin: `file://${path}\n` }
459    const wl = await findTool($, 'wl-copy')
460    if (wl) return (await $.process.run([wl, '--type', 'text/uri-list'], uri)).exitCode === 0
461    const xclip = await findTool($, 'xclip')
462    if (xclip) return (await $.process.run([xclip, '-selection', 'clipboard', '-t', 'text/uri-list'], uri)).exitCode === 0
463  } catch {}
464  return false
465}
466
467async function shareClip($: Engine, clip: Clip) {
468  const os = await detectOS($)
469  const ffmpeg = await findTool($, os === 'windows' ? 'ffmpeg.exe' : 'ffmpeg', [
470    '/opt/homebrew/bin/ffmpeg',
471    '/usr/local/bin/ffmpeg',
472    '/usr/bin/ffmpeg',
473  ])
474  if (!ffmpeg) {
475    const how = os === 'mac' ? 'brew install ffmpeg' : os === 'windows' ? 'winget install ffmpeg' : 'your package manager'
476    $.ui.toast(`sfx-gen: ffmpeg not found, install it with ${how}`)
477    return
478  }
479  if (!(await $.fs.exists(clip.path))) {
480    $.ui.toast(`sfx-gen: clip is gone: ${clip.path}`)
481    return
482  }
483
484  const out = `${await homeDir($)}/Downloads/sfx-${slug(clip.prompt)}-${clip.id}.mp3`
485  $.ui.toast('sfx-gen: converting to mp3...')
486
487  try {
488    const run = await $.process.run(
489      [ffmpeg, '-y', '-loglevel', 'error', '-i', clip.path, '-codec:a', 'libmp3lame', '-q:a', '2', out],
490      { timeoutMs: 120000 },
491    )
492    if (run.exitCode !== 0) {
493      $.ui.toast(`sfx-gen: ffmpeg exited ${run.exitCode}: ${run.stderr}`)
494      return
495    }
496  } catch (err) {
497    $.ui.toast('sfx-gen: ffmpeg failed: ' + errText(err))
498    return
499  }
500
501  const copied = await copyFileRef($, out)
502  const where = '~/Downloads/' + basename(out)
503  $.ui.toast(copied ? `mp3 saved to ${where} and copied to the clipboard` : `mp3 saved to ${where}`)
504}
505
506export const register: Register = (on, options) => {
507  if (options.sa3_dir) config.sa3Dir = String(options.sa3_dir)
508  if (options.model) config.model = String(options.model)
509  if (options.device) config.device = String(options.device)
510  if (options.encoding) config.encoding = String(options.encoding)
511  if (options.duration != null) config.duration = Number(options.duration)
512
513  on('session.start', async ($, e, next) => {
514    // Seed session state from the store once; a hot reload keeps state as is.
515    if ((await $.state.get(clipsRef)).version === 0) {
516      const saved = await $.store.get(STORE_KEY)
517      const list = Array.isArray(saved) ? (saved as Clip[]).slice(-MAX_CLIPS) : []
518      await update($, clips, () => list)
519      // old clips stay in the pane but don't take over the band
520      const last = list[list.length - 1]
521      if (last) await update($, dismissed, () => last.id)
522      // clips older than this are history, hidden in the pane until toggled
523      await update($, since, () => Date.now())
524    }
525
526    // module vars reset on reload, so reread notify sounds every start
527    const savedNotify = (await $.store.get(NOTIFY_KEY)) as NotifyConfig | undefined
528    if (savedNotify && typeof savedNotify === 'object') notify = { on: savedNotify.on !== false, sounds: savedNotify.sounds ?? {} }
529
530    await $.command.register({
531      name: 'sfx',
532      description: 'Generate a sound effect from a text prompt with a local Stable Audio model',
533      argumentHint: '[description] [--duration N] [--seed N]',
534    })
535    await $.command.register({
536      name: 'sfx-pane',
537      description: 'Show generated sound effects in a pane',
538      argumentHint: '[history]',
539    })
540    await $.command.register({
541      name: 'sfx-notify',
542      description: 'Play custom sounds on errors, permission prompts and finished replies',
543      argumentHint: '[event] [description | test | off] or on | off',
544    })
545    await $.tool.register({
546      name: 'sfx',
547      description:
548        'Generate a sound effect from a text prompt using a local Stable Audio model (sa3.cpp). ' +
549        'No API key, no Python. Returns the path to a WAV file. Use for foley and SFX: ' +
550        '"metal impact with a deep sub boom", "whoosh across the screen", "footsteps on gravel". ' +
551        'Keep prompts to one sound each and layer clips for complex scenes. ' +
552        'Set notify_on to make the clip the sound played when that event happens ' +
553        '(error: a tool call or test run failed, permission: waiting on the user, done: reply finished, ' +
554        'abort: user interrupted, compact: context compacted); notify clips default to 2s.',
555      inputSchema: {
556        type: 'object',
557        properties: {
558          prompt: { type: 'string', description: 'Text description of the sound effect to generate' },
559          duration: { type: 'number', description: 'Clip length in seconds (1-30), default from config' },
560          seed: { type: 'number', description: 'Random seed for reproducibility' },
561          steps: { type: 'number', description: 'Diffusion steps, default 8' },
562          play: { type: 'boolean', description: 'Play the generated clip after writing (default true)' },
563          notify_on: {
564            type: 'string',
565            enum: [...NOTIFY_EVENTS],
566            description: 'Assign the clip as the notification sound for this event',
567          },
568        },
569        required: ['prompt'],
570      },
571    })
572    return next(e)
573  })
574
575  on('command.run', { command: 'sfx' }, async ($, e) => {
576    const a = parseArgs(e.args)
577    if (!a.prompt) return { text: 'usage  /sfx <description> [--duration N] [--seed N]' }
578    const r = await generate($, a)
579    await announce($, r, true)
580    if (!r.ok) return { text: `✗ ${r.error}` }
581    const c = r.clip
582    // command output is plain text, so draw the box with characters
583    return {
584      text: boxed([`❯ "${c.prompt}"`, c.wave || FLAT, `${c.duration}s · ${c.model} · ${c.elapsed}s · ${basename(c.path)}`]),
585    }
586  })
587
588  on('command.run', { command: 'sfx-notify' }, async ($, e) => ({ text: await runNotify($, e.args) }))
589
590  on('command.run', { command: 'sfx-pane' }, async ($, e) => {
591    if ((e.args || '').trim() === 'history') {
592      await update($, showHistory, v => !v)
593      return { text: (await read($, showHistory)) ? 'Showing clip history.' : 'Hiding clip history.' }
594    }
595    const opened = await $.ui.open({ id: PANE, title: PANE_TITLE })
596    return { text: opened.isPlaced ? 'Sound effects pane opened.' : 'Sound effects pane is waiting for room.' }
597  })
598
599  on('tool.call', { tool: 'mcp__sfx-gen__sfx' }, async ($, e) => {
600    const input = e as unknown as GenOpts & { play?: boolean; notify_on?: string }
601    const event = isNotifyEvent(input.notify_on) ? input.notify_on : null
602    const r = event ? await assignNotify($, event, input) : await generate($, input)
603    await announce($, r, input.play !== false)
604    if (!r.ok) return { result: r.error }
605    const made = `Generated ${r.clip.duration}s sound effect "${r.clip.prompt}" in ${r.clip.elapsed}s -> ${r.clip.path}`
606    return { result: event ? `${made}. It now plays when ${NOTIFY_HINT[event]}.` : made }
607  })
608
609  // Notification sounds. Each hook lets the engine run first and only listens.
610  on('tool.call', async ($, e, next) => {
611    const r = await next(e)
612    if (r.isError || (e.tool === 'Bash' && looksLikeTestFailure(r))) void ring($, 'error')
613    return r
614  })
615
616  on('tool.check', async ($, e, next) => {
617    const r = await next(e)
618    if (r.decision === 'ask') void ring($, 'permission')
619    return r
620  })
621
622  on('turn.complete', async ($, e, next) => {
623    // subagent turns end all the time; only the main loop counts
624    if (!e.agentId) void ring($, e.isAborted ? 'abort' : 'done')
625    return next(e)
626  })
627
628  on('session.compact', async ($, e, next) => {
629    void ring($, 'compact')
630    return next(e)
631  })
632
633  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
634    const { Box, Text, Button } = $.ui.resolve(e)
635    const all = (await read($, clips)) ?? []
636    const now = await read($, pending)
637    const history = await read($, showHistory)
638    const start = await read($, since)
639    const older = all.filter(c => c.at < start).length
640    const list = history ? all : all.filter(c => c.at >= start)
641    // each clip card is 5 rows tall with its border
642    const room = Math.max(1, Math.floor(((e.viewport?.rows ?? 24) - 6) / 5))
643    const recent = list.slice(-room).reverse()
644
645    return (
646      <Box flexDirection="column" borderStyle="round" borderColor={ACCENT} paddingX={1}>
647        <Box justifyContent="space-between">
648          <Text color={ACCENT} bold>~/sfx</Text>
649          <Box>
650            <Text dimColor>
651              {list.length} {list.length === 1 ? 'clip' : 'clips'} · {config.model}
652              {older > 0 ? '  ' : ''}
653            </Text>
654            {older > 0 && (
655              <Button
656                key="history"
657                label={history ? `history ▾ ${older}` : `history ▸ ${older}`}
658                onPress={() => void update($, showHistory, v => !v)}
659              />
660            )}
661          </Box>
662        </Box>
663        {now && (
664          <Box borderStyle="single" borderColor="yellow" paddingX={1}>
665            <Text color="yellow" wrap="truncate-end">
666              [gen] {now.duration}s "{now.prompt}"...
667            </Text>
668          </Box>
669        )}
670        {list.length === 0 && !now && (
671          <Text dimColor>
672            <Text color={ACCENT}>$ </Text>/sfx a whoosh across the screen
673          </Text>
674        )}
675        {recent.map(clip => (
676          <Box key={'row-' + clip.id} flexDirection="column" borderStyle="round" borderColor="gray" paddingX={1}>
677            <Text wrap="truncate-end">
678              <Text color={ACCENT}>❯ </Text>
679              <Text bold>{clip.prompt}</Text>
680            </Text>
681            <Text color={ACCENT}>{clip.wave || FLAT}</Text>
682            <Box>
683              <Text dimColor>
684                {clip.duration}s · {clip.elapsed}s{'  '}
685              </Text>
686              <Button key={'play-' + clip.id} label="▶ play" onPress={() => void playClip($, clip)} />
687              <Text> </Text>
688              <Button key={'share-' + clip.id} label="⇪ mp3" onPress={() => void shareClip($, clip)} />
689            </Box>
690          </Box>
691        ))}
692      </Box>
693    )
694  })
695
696  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
697    if (e.props.hasSurvey) return next(e)
698
699    const { Box, Text, Button } = $.ui.resolve(e)
700    const now = await read($, pending)
701    if (now) {
702      return (
703        <Box borderStyle="round" borderColor="yellow" paddingX={1}>
704          <Text color="yellow" wrap="truncate-end">
705            [gen] {now.duration}s "{now.prompt}" · {now.model} ({now.device})...
706          </Text>
707        </Box>
708      )
709    }
710
711    const list = (await read($, clips)) ?? []
712    const last = list[list.length - 1]
713    if (!last || (await read($, dismissed)) === last.id) return next(e)
714
715    return (
716      <Box borderStyle="round" borderColor={ACCENT} paddingX={1}>
717        <Text wrap="truncate-end">
718          <Text color={ACCENT}>❯ </Text>"{last.prompt}" <Text color={ACCENT}>{last.wave || FLAT}</Text>{' '}
719        </Text>
720        <Button key="play" label="▶ play" onPress={() => void playClip($, last)} />
721        <Text> </Text>
722        <Button key="share" label="⇪ mp3" onPress={() => void shareClip($, last)} />
723        <Text> </Text>
724        <Button key="dismiss" label="✕" role="dismiss" onPress={() => void update($, dismissed, () => last.id)} />
725      </Box>
726    )
727  })
728}
729
types/index.d.ts 29 lines
1export type Clip = {
2  id: string
3  prompt: string
4  path: string
5  duration: number
6  elapsed: string
7  model: string
8  at: number
9  // unicode sparkline of the clip's loudness, cached so the pane needn't reread the wav
10  wave?: string
11}
12
13export type Pending = { prompt: string; duration: number; model: string; device: string }
14
15declare module 'claude-code' {
16  interface PluginState {
17    'sfx-gen': {
18      clips: Clip[]
19      pending: Pending | null
20      // id of the last clip the band was dismissed for
21      dismissed: string | null
22      // pane shows clips from before this session only when toggled on
23      showHistory: boolean
24      // when this session started; older clips count as history
25      since: number
26    }
27  }
28}
29