SLOPSHOPPER

say

Claude Code's voice, through murmur (Kokoro on the Apple Neural Engine): each session in its own voice (/say picks one), /say read and /say tldr, and…

panecommandtoastpromptmodelprocess
v0.4.0no licenseupdated 2026-10-21whilestevego/claude-mods/say
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · say
│ ┃ claude-say-picker ✕ › fix the failing auth test and add an audit log call │ ┃ ✓ installed · A–F: Kokoro's grade · Enter to │ ┃ speak with it · Esc to close ⏺ Read(src/auth.ts) │ ⎿ 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 │ │ › /say │ ⎿ say: Couldn't list murmur's voices. Is murmur installed? │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · claude-say-picker
✓ installed · A–F: Kokoro's grade · Enter to speak with it · Esc to close
README

claude-mods

Mods for Claude Code: small plugins that add to its screen and behavior. Each folder is one mod. Turn on the ones you want (see Setup) and change their settings in /config, under the mod's name.

Each mod works on its own, and a few work better together. notify tells you when something happens; with say it can tell you out loud, with tldr its turn summaries reuse tldr's line instead of writing their own, and with ghostty it stays quiet while you're looking at the session. In Ghostty, clicking its notification brings you back to the session's tab.

The mods

context-bar

Shows how full Claude's context window is, as a colored bar above the prompt.

  • Point at the bar to see what's using the space (system prompt, messages, tools…).
  • /context-bar hides or shows it for this session.

rate-limits

Shows how much of your 5-hour and weekly usage limits you've used, as two small meters under the context bar. They turn yellow at 70% and red at 90%, and you get a warning inside Claude once a limit passes 90%. (notify also warns, as a desktop notification or out loud, at a threshold you set.)

  • Nothing to do: it appears on its own when you're on a subscription plan.

session-id

Shows this session's ID in the bottom-right corner of the screen.

  • Click it to copy the ID.
  • Ctrl-click it to copy the full claude --resume <id> command.

turn-receipt

Adds a receipt to the line that closes each turn ("✻ Baked for 42s"): how many tools ran, which files were edited, the tokens used and what the turn cost.

  • Nothing to do: it appears after every turn.

tldr

Adds a one-sentence summary under Claude's longer replies, written by Claude Haiku.

  • Nothing to do. TL;DR: long reply in /config sets how long a reply must be (600 characters by default).
  • With notify on, the same line is its summary when a long turn finishes, at no extra cost.

notify

Tells you when something happens in a session: as a desktop notification, out loud through say, or both. With the ghostty mod on, it only tells you when you're away from the session (another app or tab in front), so it never interrupts you while you're watching. Without it, nothing can tell whether you're looking, so it always tells you.

  • What it tells you about: Claude needs your permission or has a question, or a turn stopped on an API error (like a lost connection); a long turn finished, with a one-line summary of what it did; you're close to a usage limit; a background task finished; and every few minutes, how a long turn is going.
  • Where each one goes: each event has its own setting in /config under notify: both, banner (the desktop notification), voice (spoken by say) or off. By default the first three are both, and background tasks and check-ins are voice.
  • Clicking a notification in Ghostty brings you to the tab of the session that sent it. Each one is titled with the session's folder, so you can tell sessions apart.
  • Without say, voice alerts are skipped and the banners still go out.
CommandWhat it does
/notify testSends a desktop notification right away. macOS can't tell a mod whether your terminal may show notifications, so this is how to check. The first time notify starts, it reminds you once.
/notify settingsOpens the switch in System Settings: Ghostty's own entry in Ghostty, the Notifications list elsewhere.

say

Gives Claude a voice, through murmur. The notify mod decides what gets said and when; say is the voice it speaks in.

  • A soft chime plays before it speaks, so a voice never starts out of nowhere. Turn it off with Chime in /config.
  • Each open session gets its own voice: the best one no other session has, by Kokoro's grades (Heart, then Bella, Nicole, Emma…). Pick one fixed voice, or your own list, in /config under say.

Everything else is one command, /say:

CommandWhat it does
/sayNames this session's voice and plays a short sample of it.
/say pickLists every voice with its grade and switches this session to the one you pick, with a sample in it. The choice sticks to the conversation, so resuming it keeps the voice.
/say pick <name>Switches directly, like /say pick emma. Part of the name is enough.
/say pick randomSwitches to a random voice, other than the current one. Better-graded voices come up more often.
/say readReads Claude's last reply aloud.
/say tldrA spoken 2–3 sentence summary of the session so far.
/say hushMutes this session; run it again to unmute.
/say helpLists these.

ghostty

Ties Claude into the Ghostty terminal. All its settings start with "Ghostty" in /config.

  • Tab title: a 4-word summary of what the session is about, from your last 10 messages and Claude's latest reply, updated every few minutes as it goes. /title gets a new one right away. A resumed session gets its old title back.
  • Tab progress bar: shows while Claude works, and turns red when a command fails.
  • ❓ waiting on you: a ❓ in the tab title when Claude needs a permission or an answer. The notify mod sends the notification.
  • /workspace saves and reopens whole windows of sessions: see Workspaces.
  • /goto lists your open Claude sessions, the ones waiting on you first, and jumps to the one you pick. /goto next jumps straight to the one waiting longest; /goto <words> jumps to the one whose title matches.
  • /keybind add <keys> <text> makes a Ghostty key type something into Claude, like /keybind add super+ctrl+h /say hush for ⌘⌃H. /keybind lists them, and /keybind remove <keys> removes one. For ⌘⌃G to open /goto, run /keybind add super+ctrl+g /goto, or turn on Ghostty: install Claude keybinds in /config. The mod changes your Ghostty config only when you do one of these: it adds one line that loads its own claude-keybinds file.
Workspaces

A workspace is a Ghostty window of Claude sessions you can put away and bring back later. It remembers every tab and split: each Claude session with its conversation, and each shell with its folder. Reopening it brings back the whole window, with every conversation picking up where it left off.

CommandWhat it does
/workspace save [name]Saves this window. With no name, it keeps the name the window already had, or Claude Haiku picks one from the tabs.
/workspace close [name]Saves this window, then exits every Claude session in it and closes their tabs. Your current tab stays open at the shell, and shell tabs stay open. If another session is still working or waiting on you, it closes nothing and names them; /workspace close --force closes them anyway.
/workspace listShows your saved workspaces, newest first. Press a number or Enter to reopen one, or Tab to ✕ delete to remove it.
/workspace open <name>Reopens a saved workspace in a new window. Part of the name is enough.
  • Reopening puts each tab back in its folder. Claude tabs run claude --resume, so they continue their own conversation, with the tab title they had when you saved. A tab saved without a title gets a new one from its conversation. Shell tabs open at the prompt.
  • Put away a project for the day: /workspace close. Pick it up tomorrow: /workspace list, then press its number.
  • What doesn't come back: programs that were running (a dev server, a test watcher), and the exact split layout. Splits reopen side by side.
  • Where they're kept: ~/.claude/workspaces/, one JSON file per workspace. Saving never overwrites a different workspace that happens to have the same name: the new one gets a file of its own.

Setup

Install the mods you want, one line each, at the prompt of a Claude Code session:

/plugin install context-bar --marketplace whilestevego/claude-mods

Answer y to add the marketplace, then pick a scope. The mods are context-bar, rate-limits, session-id, turn-receipt, tldr, notify, say and ghostty.

From a clone, while working on them

  1. Clone this repo.
  2. List the mods you want in CLAUDE_CODE_PLUGIN_DIRS, separated by :, in the env block of ~/.claude/settings.json:
   "env": {
     "CLAUDE_CODE_PLUGIN_DIRS": "/path/to/claude-mods/context-bar:/path/to/claude-mods/say"
   }
  1. Start a new Claude session.

To try one mod for a single session: claude --plugin-dir /path/to/claude-mods/tldr.

Requirements

  • ghostty needs Ghostty 1.3 or newer on macOS. Set CLAUDE_CODE_DISABLE_TERMINAL_TITLE=1 in the same env block, so Claude Code doesn't overwrite the tab title.
  • say needs murmur installed, which runs on Apple Silicon Macs.
  • notify's desktop notifications need notifications allowed for your terminal, in System Settings → Notifications (Ghostty, say). /notify test checks; /notify settings opens the page.
  • session-id's pointing-hand cursor works in Ghostty, Kitty and foot.

The first time a mod controls Ghostty, macOS asks for permission. Allow it.

Development

Editing a mod's files reloads it in running sessions. A mod newly added to CLAUDE_CODE_PLUGIN_DIRS loads only in sessions started after that.

claude plugin validate context-bar   # check a mod the way Claude Code will load it
claude plugin test context-bar       # run its tests

Mods can call each other through nouns on $: say adds $.voice.say({ text }), which notify speaks through, and ghostty adds $.ghostty.isFocused(), which notify asks before alerting. Their types are in each mod's types/index.d.ts.

IDEAS.md has ideas for more mods.

Source 4 files
hooks/register.tsx 276 lines
1import type { EngineInterface, PluginOptions, Register, RenderNode } from 'claude-code'
2
3import type { VoiceSaid } from '../types'
4
5import { prose, voiceList } from './speech'
6import { byGrade, claimVoice, matchVoice, parseCatalog, parseTable, weightedPick } from './voices'
7import type { VoiceInfo } from './voices'
8
9type Config = {
10  speed: number
11  chime: boolean
12  voice: string
13  voices: string[]
14}
15
16function config(o: PluginOptions): Config {
17  const num = (v: unknown, d: number) => (typeof v === 'number' && v > 0 ? v : d)
18  return {
19    speed: num(o.speed, 1),
20    chime: o.chime !== false,
21    voice: typeof o.voice === 'string' ? o.voice.trim() : '',
22    voices: typeof o.voices === 'string' ? voiceList(o.voices) : [],
23  }
24}
25
26/** /say hush, for this session: in $.state so a hot reload of the mod keeps it. */
27const MUTED = { plugin: 'say', key: 'muted' } as const
28const isMuted = async ($: EngineInterface) => (await $.state.get(MUTED)).value === true
29
30// The module's own session state; a reload starts it over.
31let cfg: Config
32let claude: { tty: string; pid: string } | null = null
33let home = ''
34/** This mod's folder, for its chime. */
35let root = ''
36/** This session's own voice, claimed at start (unused when a fixed voice is set). */
37let sessionVoice = ''
38/** The voice you picked with /say for this conversation: wins over the session's own and the fixed one. */
39let chosen = ''
40/** After /clear: the chosen voice is saved again under the new conversation at the next prompt. */
41let isChosenStale = false
42/** What the /say picker lists: murmur's voices, and the ones other sessions hold. */
43const PICKER = 'claude-say-picker'
44const currentVoice = () => chosen || cfg.voice || sessionVoice || 'af_heart'
45let picker: { voices: VoiceInfo[]; others: Set<string> } = { voices: [], others: new Set() }
46let lastAnswer = ''
47
48// "<tty> <pid>" of Claude itself: the nearest ancestor named claude (the mods' own host process, between it and
49// this shell, owns the tty too, and changes when mods reload). Its pid keys the session's voice. No API names either.
50const FIND_CLAUDE = `p=$$
51first=
52while [ "$p" -gt 1 ]; do
53  t=$(ps -o tty= -p "$p" | tr -d ' ')
54  case "$t" in ''|'?'|'??') ;; *) [ -z "$first" ] && first="$t $p"
55    c=$(ps -o comm= -p "$p"); [ "\${c##*/}" = claude ] && { echo "$t $p"; exit; } ;;
56  esac
57  p=$(ps -o ppid= -p "$p" | tr -d ' ')
58done
59echo "$first"`
60
61async function locate($: EngineInterface) {
62  home = (await $.env.get('HOME')) ?? ''
63  const [tty, pid] = (await $.process.run(['sh', '-c', FIND_CLAUDE])).stdout.trim().split(' ')
64  claude = tty && pid ? { tty, pid } : null
65}
66
67// /say's choice, kept per conversation so resuming it (or reopening its workspace) keeps the voice.
68async function chosenFile($: EngineInterface): Promise<string | undefined> {
69  const id = await $.session.id()
70  return home && /^[0-9a-f-]{8,64}$/i.test(id) ? `${home}/Library/Caches/claude-say/chosen/${id}` : undefined
71}
72
73async function saveChosen($: EngineInterface) {
74  const file = await chosenFile($)
75  if (!file) return
76  await $.process.run(['mkdir', '-p', file.replace(/\/[^/]*$/, '')])
77  await $.fs.write(file, chosen)
78}
79
80async function choose($: EngineInterface, v: VoiceInfo): Promise<string> {
81  chosen = v.id
82  await saveChosen($)
83  await claimSessionVoice($).catch(() => {})
84  void say($, sample(v.name))
85  return `🔊 This session now speaks as ${v.name} (${v.id}).` + (v.isInstalled ? '' : ' It installs on first use, so the first line may take a moment.')
86}
87
88/** The voices to pick from, and which ones other running sessions hold. */
89async function loadPicker($: EngineInterface) {
90  const r = await $.process.run(['murmur', 'voices']).catch(() => ({ stdout: '' }))
91  const table = parseTable(await $.fs.read(`${home}/Library/Caches/claude-say/voices.json`).catch(() => ''))
92  const others = new Set(Object.entries(table).filter(([pid]) => pid !== claude?.pid).map(([, v]) => v))
93  picker = { voices: parseCatalog(r.stdout), others }
94  return picker.voices
95}
96
97// Every running session shares one small table of who speaks with which voice.
98async function claimSessionVoice($: EngineInterface) {
99  if (!claude || !home) return
100  const dir = `${home}/Library/Caches/claude-say`
101  const file = `${dir}/voices.json`
102  const table = parseTable(await $.fs.read(file).catch(() => ''))
103  const pids = Object.keys(table)
104  const alive = pids.length
105    ? (await $.process.run(['sh', '-c', 'for p; do kill -0 "$p" 2>/dev/null && echo "$p"; done', 'sh', ...pids])).stdout.split('\n')
106    : []
107  // Unless you listed voices yourself, sessions take the best-graded voice no other session holds.
108  const pool = cfg.voices.length ? cfg.voices : byGrade(await loadPicker($))
109  const claimed = claimVoice(table, claude.pid, new Set(alive), pool)
110  sessionVoice = claimed.voice
111  if (chosen) claimed.table[claude.pid] = chosen
112  // ponytail: last writer wins; two sessions starting in the same instant can share a voice until one restarts.
113  await $.process.run(['mkdir', '-p', dir])
114  await $.fs.write(file, JSON.stringify(claimed.table))
115}
116
117// Interrupt, don't stack: each new line cuts off whatever is still playing. Whether a line is worth saying at all
118// (is anyone away from this terminal?) is the caller's call: the notify mod's, or yours with /say.
119async function say($: EngineInterface, text: string): Promise<VoiceSaid> {
120  if (!text.trim() || (await isMuted($))) return { isSpoken: false }
121  // A soft bell first (the mod's chime.wav), so speech never starts out of nowhere. Not awaited: murmur takes
122  // about as long to get ready as the bell rings.
123  if (cfg.chime && root) void $.process.run(['afplay', `${root}/chime.wav`]).catch(() => null)
124  const argv = ['murmur', '--interrupt', '--speed', String(cfg.speed)]
125  const voice = chosen || cfg.voice || sessionVoice
126  if (voice) argv.push('--voice', voice)
127  const r = await $.process.run([...argv, '--', text]).catch(() => null)
128  if (r && r.exitCode !== 0) $.ui.toast(`murmur: ${r.stderr.trim().slice(0, 120) || 'failed'}`)
129  return { isSpoken: r?.exitCode === 0 }
130}
131
132/** What a voice says to show how it sounds. */
133const sample = (name: string) => `Hi, I'm ${name}. This is how I sound.`
134
135/** /say alone: this session's voice and a sample of it. /say pick: the picker, a random voice, or the one named. */
136async function pickVoice($: EngineInterface, query: string): Promise<{ text: string }> {
137  const voices = await loadPicker($)
138  if (voices.length === 0) return { text: "Couldn't list murmur's voices. Is murmur installed?" }
139  if (!query) {
140    const name = voices.find(v => v.id === currentVoice())?.name ?? currentVoice()
141    if (await isMuted($)) return { text: `🔊 This session speaks as ${name} (${currentVoice()}), muted. /say pick for another.` }
142    void say($, sample(name))
143    return { text: `🔊 This session speaks as ${name} (${currentVoice()}). /say pick for another.` }
144  }
145  const [word = '', ...rest] = query.split(/\s+/)
146  if (word.toLowerCase() !== 'pick') return { text: `No /say command called "${word}". /say help lists them.` }
147  const name = rest.join(' ')
148  if (name.toLowerCase() === 'random') {
149    const others = voices.filter(v => v.id !== currentVoice())
150    return { text: await choose($, weightedPick(others) ?? voices[0]!) }
151  }
152  if (!name) {
153    await $.ui.open({ id: PICKER, title: 'Voices', focus: true, closeOnEscape: true, rows: voices.length + new Set(voices.map(v => v.group)).size + 1 })
154    return { text: `Speaking as ${voices.find(v => v.id === currentVoice())?.name ?? currentVoice()}: pick another above.` }
155  }
156  const hits = matchVoice(name, voices)
157  if (hits.length === 1) return { text: await choose($, hits[0]!) }
158  if (hits.length === 0) return { text: `No voice called "${name}". /say pick lists them.` }
159  return { text: `"${name}" could be ${hits.map(v => `${v.name} (${v.id})`).join(', ')}.` }
160}
161
162const HELP = [
163  "/say              hear this session's voice",
164  '/say pick         pick another voice from a list',
165  '/say pick <name>  switch to that voice (/say pick emma)',
166  '/say pick random  switch to a random voice',
167  "/say read         read Claude's last answer aloud",
168  '/say tldr         hear a 2–3 sentence summary of this session',
169  '/say hush         mute or unmute spoken updates for this session',
170].join('\n')
171
172async function hush($: EngineInterface): Promise<{ text: string }> {
173  const muted = !(await isMuted($))
174  await $.state.set(MUTED, muted)
175  if (muted) await $.process.run(['murmur', 'stop']).catch(() => null)
176  return { text: muted ? '🔇 Spoken updates muted for this session. /say hush again to unmute.' : '🔊 Spoken updates back on.' }
177}
178
179async function readAloud($: EngineInterface): Promise<{ text: string }> {
180  if (!lastAnswer) return { text: 'Nothing to read yet.' }
181  if (await isMuted($)) return { text: 'Muted: /say hush to unmute first.' }
182  void say($, prose(lastAnswer, 'Code omitted.'))
183  return { text: '🔊 Reading the last answer aloud. /say hush stops it.' }
184}
185
186async function tldrAloud($: EngineInterface): Promise<{ text: string }> {
187  if (await isMuted($)) return { text: 'Muted: /say hush to unmute first.' }
188  const r = await $.model.fork({
189    prompt: 'In 2 or 3 short sentences meant to be spoken aloud, summarize this session so far: the goal, what is done, and what is next. Plain words only, no markdown or code.',
190  })
191  if (!r.isAnswered) return { text: `Couldn't summarize: ${r.reason}` }
192  const line = prose(r.text).replace(/\s+/g, ' ').trim()
193  void say($, line)
194  return { text: `🔊 ${line}` }
195}
196
197export const register: Register = (on, options) => {
198  cfg = config(options)
199
200  // $.voice.say: other mods (notify) speak through this session's voice. The noun's own method holds no `$`, so
201  // it only answers when nothing else does; the voice.say hook below, which has one, does the speaking.
202  on('engine.create', async (_$, e, next) => ({ ...(await next(e)), voice: { say: async () => ({ isSpoken: false }) } }))
203
204  on('voice.say', async ($, e) => ({ value: await say($, e.text) }))
205
206  on('session.start', async ($, e, next) => {
207    root = $.plugin.root
208    await locate($)
209    const file = await chosenFile($).catch(() => undefined)
210    chosen = file ? (await $.fs.read(file).catch(() => '')).trim() : ''
211    if (!cfg.voice || chosen) await claimSessionVoice($).catch(() => {})
212    await $.command.register({ name: 'say', description: "Spoken updates: /say to hear this session's voice, /say pick [<name>|random], /say read, /say tldr, /say hush, /say help" })
213    return next(e)
214  })
215
216  on('prompt.submit', ($, e, next) => {
217    if (isChosenStale && chosen) void saveChosen($).catch(() => {})
218    isChosenStale = false
219    return next(e)
220  }).catch(($, e, next) => next(e))
221
222  // For /say read.
223  on('turn.complete', ($, e, next) => {
224    if (!e.agentId) lastAnswer = e.answer
225    return next(e)
226  })
227
228  // /clear starts a new conversation in this same session (no session.start follows): it keeps the voice.
229  on('session.end', ($, e, next) => {
230    if (e.reason === 'clear') isChosenStale = true
231    return next(e)
232  })
233
234  on('command.run', { command: 'say' }, async ($, e) => {
235    switch (e.args.trim().toLowerCase()) {
236      case 'help': return { text: HELP }
237      case 'hush': return hush($)
238      case 'read': return readAloud($)
239      case 'tldr': return tldrAloud($)
240      default: return pickVoice($, e.args.trim())
241    }
242  })
243
244  on('ui.render', { component: 'Pane', requestId: PICKER }, async ($, e) => {
245    const { Box, Button, Text } = $.ui.resolve(e)
246    const mine = currentVoice()
247    const rows: RenderNode[] = []
248    let group = ''
249    picker.voices.forEach((v, i) => {
250      if (v.group !== group) {
251        group = v.group
252        rows.push(<Text bold>{group}</Text>)
253      }
254      const note = v.id === mine ? ' · this session' : picker.others.has(v.id) ? ' · in use' : ''
255      rows.push(
256        <Button
257          key={`voice-${i}`}
258          plain
259          label={`${v.isInstalled ? '✓' : '·'} ${v.name.padEnd(9)} ${v.id.padEnd(12)} ${v.grade.padEnd(2)}${note}`}
260          autoFocus={v.id === mine ? true : undefined}
261          onPress={async () => {
262            await $.ui.close({ id: PICKER })
263            $.ui.toast(await choose($, v))
264          }}
265        />,
266      )
267    })
268    return (
269      <Box flexDirection="column">
270        {rows}
271        <Text dimColor>✓ installed · A–F: Kokoro's grade · Enter to speak with it · Esc to close</Text>
272      </Box>
273    )
274  })
275}
276
hooks/speech.ts 21 lines
1// Turning Claude's markdown into something worth hearing.
2
3/** Markdown → plain spoken prose. Code blocks become `codeAs` (dropped when empty). */
4export function prose(markdown: string, codeAs = ''): string {
5  return markdown
6    .replace(/```[\s\S]*?```/g, codeAs ? ` ${codeAs} ` : ' ')
7    .replace(/`([^`\n]*)`/g, '$1')
8    .replace(/!?\[([^\]]*)\]\([^)]*\)/g, '$1')
9    .replace(/^\s*[-*+]\s+/gm, '')
10    .replace(/^\s*\|.*\|\s*$/gm, '')
11    .replace(/[*_#>|~]/g, '')
12    .replace(/[ \t]+/g, ' ')
13    .replace(/\n{2,}/g, '\n')
14    .trim()
15}
16
17/** "af_heart, bm_george" → ["af_heart", "bm_george"]; empty → []. */
18export function voiceList(option: string): string[] {
19  return option.split(',').map(v => v.trim()).filter(Boolean)
20}
21
hooks/voices.ts 73 lines
1// One voice per running Claude session, claimed from a small table every session shares.
2
3/** Session (process id) → voice. */
4export type VoiceTable = Record<string, string>
5
6/**
7 * This session's voice: the one it already holds, else the first in `pool` no other live session holds
8 * (cycling once every voice is taken). Sessions not in `alive` are dropped, freeing their voices.
9 */
10export function claimVoice(table: VoiceTable, me: string, alive: ReadonlySet<string>, pool: readonly string[]) {
11  const live: VoiceTable = Object.fromEntries(Object.entries(table).filter(([pid]) => pid === me || alive.has(pid)))
12  const held = live[me]
13  if (held) return { voice: held, table: live }
14  const choices = pool.length ? pool : ['af_heart']
15  const taken = new Set(Object.values(live))
16  const voice = choices.find(v => !taken.has(v)) ?? choices[Object.keys(live).length % choices.length]!
17  return { voice, table: { ...live, [me]: voice } }
18}
19
20/** The shared table file's text → a table; anything unreadable is an empty table. */
21export function parseTable(text: string): VoiceTable {
22  try {
23    const data: unknown = JSON.parse(text)
24    if (!data || typeof data !== 'object' || Array.isArray(data)) return {}
25    return Object.fromEntries(Object.entries(data).filter((kv): kv is [string, string] => typeof kv[1] === 'string'))
26  } catch {
27    return {}
28  }
29}
30
31/** One of murmur's voices, as `murmur voices` lists it; `grade` is Kokoro's (A to F), '' from a murmur without grades. */
32export type VoiceInfo = { id: string; name: string; group: string; isInstalled: boolean; grade: string }
33
34/** `murmur voices` output → its voices, in its order ("AMERICAN FEMALE" headers, "  ✓ af_bella  Bella  A-" rows). */
35export function parseCatalog(text: string): VoiceInfo[] {
36  let group = ''
37  const voices: VoiceInfo[] = []
38  for (const line of text.split('\n')) {
39    const header = line.match(/^([A-Z][A-Z ]+)$/)
40    if (header) group = header[1]!.trim()
41    const row = line.match(/^\s+([✓·])\s+([a-z]{2}_[a-z]+)\s+(\S+)(?:\s+([A-F][+-]?)(?=\s|$))?/)
42    if (row) voices.push({ id: row[2]!, name: row[3]!, group, isInstalled: row[1] === '✓', grade: row[4] ?? '' })
43  }
44  return voices
45}
46
47/** "emma", "bf_emma", "isa" → the voices it could mean: an exact id or name wins, else every partial match. */
48export function matchVoice(query: string, voices: readonly VoiceInfo[]): VoiceInfo[] {
49  const q = query.trim().toLowerCase()
50  if (!q) return []
51  const exact = voices.filter(v => v.id === q || v.name.toLowerCase() === q)
52  return exact.length ? exact : voices.filter(v => v.id.includes(q) || v.name.toLowerCase().includes(q))
53}
54
55/** A grade as a number: A 4, B 3, C 2, D 1, F 0, a + or − worth 0.3; no grade counts as a C. */
56export function gradePoints(grade: string): number {
57  const m = grade.match(/^([A-DF])([+-]?)$/)
58  if (!m) return 2
59  return 'FDCBA'.indexOf(m[1]!) + (m[2] === '+' ? 0.3 : m[2] === '-' ? -0.3 : 0)
60}
61
62/** Voice ids, best grade first; equal grades keep murmur's order. */
63export function byGrade(voices: readonly VoiceInfo[]): string[] {
64  return [...voices].sort((a, b) => gradePoints(b.grade) - gradePoints(a.grade)).map(v => v.id)
65}
66
67/** A random voice, weighted by the square of its grade: an A comes up 16 times as often as a D. */
68export function weightedPick(voices: readonly VoiceInfo[], random = Math.random): VoiceInfo | undefined {
69  const weights = voices.map(v => Math.max(gradePoints(v.grade), 0.1) ** 2)
70  let r = random() * weights.reduce((a, b) => a + b, 0)
71  return voices.find((_, i) => (r -= weights[i]!) < 0) ?? voices.at(-1)
72}
73
types/index.d.ts 21 lines
1/** /say hush, for this session. */
2export type VoiceMuted = boolean
3
4/** `$.voice.say`'s argument: one line to speak in this session's voice. */
5export type VoiceSay = { text: string }
6
7/** Whether it reached the speakers: false while /say hush mutes this session, or when murmur failed. */
8export type VoiceSaid = { isSpoken: boolean }
9
10/** The say mod's voice, for other mods (notify) to speak through. */
11export type Voice = { say: (input: VoiceSay) => Promise<VoiceSaid> }
12
13declare module 'claude-code' {
14  interface EngineInterface {
15    voice: Voice
16  }
17  interface PluginState {
18    say: { muted: VoiceMuted }
19  }
20}
21