SLOPSHOPPER

voice-replies

Reads the main agent's replies aloud, rewritten for speech, with Kokoro on the GPU (or CPU). Sessions take turns instead of cutting each other off, each…

bandcommandtoaststatuspromptmodel
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · voice-replies
› fix the failing auth test and add an audit log call ⏺ 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 › /voice ⎿ voice-replies: Voice replies are off in this session. ⟨Claude Code's own drawing⟩ ╭──────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮ │ Voice replies starting │ │ │ │ Voice: Off ▾ │ ╰──────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
⟨Claude Code's own drawing⟩ ╭──────────────────────────────────────────────────────────────────────────────────────────────────╮ │ Voice replies starting │ │ │ │ Voice: Off ▾ │ ╰──────────────────────────────────────────────────────────────────────────────────────────────────╯
README

voice-replies

Reads Claude Code's replies aloud. When the main agent finishes a turn, the plugin asks Haiku to rewrite the reply as a short spoken script (outcome first, no code, paths or markdown), then speaks it with Kokoro-82M on your GPU, or on your CPU when the GPU cannot run it. If Kokoro is not running it falls back to the built-in Windows voice (or the system voice on macOS).

It speaks only the main agent's final answer in a session someone is watching. Subagent turns, stopped turns, claude -p runs and SDK sessions with no app attached stay silent.

Install

  1. Install the plugin:
   /plugin install voice-replies@personal-plugins
  1. Install the Kokoro voice server (Windows only):
   /voice install

It takes 5 to 15 minutes. The voice panel shows each step, and the Windows voice speaks until it is done. A toast says when it is done and whether Kokoro runs on the GPU or the CPU.

Until step 2 is done, replies use the Windows voice.

How the installer picks GPU or CPU

/voice install runs server/setup.ps1. It checks the machine first:

The machine hasKokoro runs onPyTorch build
An NVIDIA card with 2 GB or more of video memory, compute capability 5.0 to 9.x, and driver 528.33 or newerGPUCUDA 12.6
An NVIDIA RTX 50 series (Blackwell) card and driver 570.65 or newerGPUCUDA 12.8
An older, smaller or out-of-date NVIDIA card, AMD or Intel graphics, or Windows on ARMCPUCPU

After installing, it speaks a test phrase into memory on the chosen device. If the GPU fails that test, it switches to the CPU by itself. The choice is saved in config.json, and the server reads it each time it starts. Kokoro is small (82 million parameters), so a modern CPU still speaks faster than real time.

To force a choice, use /voice install gpu or /voice install cpu. To see what it would pick without installing anything:

powershell -ExecutionPolicy Bypass -File server\setup.ps1 -CheckOnly

You do not need Python. The installer gets uv (a small Python installer), and uv puts Python 3.12 in the same folder. It needs no admin rights. Downloads are about 3 GB for the GPU and about 700 MB for the CPU. Everything goes into %USERPROFILE%\.claude\voice-replies; delete that folder to remove it. Run /voice install again after a plugin update or a new GPU. It keeps what is already in place.

The plugin starts the server hidden in the background when it first needs it. One server is shared by every session, and it exits after two idle hours. The plugin starts the server from its own copy of server.py, so a plugin update reaches the server without a new install. A server from before 1.3.0 is stopped and started again once.

Use

A small Voice replies panel sits just above the prompt, under any other mod's panel (such as session-brief). It has three dropdowns, Voice, Speed and Length, and a Call me field. Pick Off in the Voice dropdown to turn voice replies off; pick any voice to turn them back on. Next to the panel's title, a short note says when it is preparing, in line or speaking, or when the Windows voice stands in for Kokoro. A Stop button shows while it speaks.

The panel fits its width. In a wide window everything sits on one line. In a narrower one the title and buttons go on top and the settings go below, and a setting that does not fit moves to the next line instead of drawing over its neighbour.

Length sets how much is read. Short reads a summary of about 80 words. Full reads every point of the reply. A script that is too long (1,500 characters for Short, 12,000 for Full) ends at the last full sentence.

How it sounds

Haiku writes the script the way a colleague talks: contractions, short sentences, and a new line between topics. The voice server pauses briefly at each new line.

Before the voice gets the script, the plugin rewrites what voices read badly:

WrittenSaid
8:00 AM, 8:05, 17:30, 12:00 PMeight in the morning, eight oh five, five thirty in the afternoon, noon
9:00 (no AM or PM)nine o'clock
2026-10-16October sixteenth, 2026
5-10, 95%, 1.2x, ~55 to 10, 95 percent, 1.2 times, about 5
v1.5.0version 1 point 5 point 0
&, e.g., i.e., vs, ->and, for example, that is, versus, to

Several sessions

Each session keeps its own voice, speed, length, name for you and on or off setting. A session you open again keeps what you picked there. A new session starts with the default; /voice default makes the current session's choices the default.

Sessions take turns. A reply never stops another session's speech:

  1. If no session is speaking, the reply plays at once.
  2. If another session is speaking, the reply waits. You get a Windows notification that names the session, and that session's panel shows 1 reply waiting with Play and Dismiss.
  3. Play puts the reply in line. It plays when the current speech ends.
  4. The voice does not say which session is speaking. To have it say a name when it moves to this session from another one, use /voice name <words>. The notification for a waiting reply always names the session (by its folder when no name is set).

Sending a new prompt stops that session's speech and drops its waiting replies. Other sessions keep speaking.

What the voice calls you

Type a name in the Call me field in the panel and press Enter, or use /voice call <name>. Each reply in that session then starts with it and a short pause, such as "Jay... the tests pass." A comma or full stop typed after the name is dropped, so it is not said twice. Clear the field, or use /voice call with no name, to stop. /voice default makes it the name for new sessions too.

Missed a reply because you were in another session? The panel shows Replay once a reply has played. It plays that session's last reply again, after any speech already in line. The last reply is saved with the session's settings, so Replay still works after the session restarts.

CommandDoes
/voiceToggles voice replies on or off in this session
/voice on, /voice offTurns them on or off in this session
/voice stopStops this session's speech
/voice stop allStops speech in every session
/voice playPlays this session's waiting replies
/voice clearDrops this session's waiting replies
/voice replayPlays this session's last reply again (same as Replay in the panel)
/voice voice bm_georgePicks a voice for this session
/voice speed 1.2Picks a speed for this session: 0.8, 0.9, 1.0, 1.1, 1.2, 1.3 or 1.5
/voice length fullReads replies in full (short reads a summary)
/voice call JayStarts each reply in this session with that name (no name: stops)
/voice name Voice fixesSays that name when the voice moves to this session from another one (no words: says nothing)
/voice defaultMakes this session's voice, speed, length and on or off the default for new sessions
/voice voicesLists the 28 English voices
/voice testPlays a sample with the current voice and speed
/voice installInstalls Kokoro on the GPU, or on the CPU if the GPU cannot run it
/voice install gpu, /voice install cpuInstalls Kokoro on the device you name

The Windows voice (used when Kokoro is not set up) does not take turns between sessions.

Cost

Each spoken reply makes one Haiku call: about 200 tokens of rules plus the reply in, and 60 to 150 tokens out (up to 4,000 with Length set to Full). Nothing is added to the main conversation's context. Kokoro runs locally and uses no tokens. With voice replies off there is no extra call.

How it works

PieceJob
hooks/register.tsxThe hooks module: listens for the end of each turn, writes the speech script, draws the voice panel above the prompt, holds replies for Play, and handles /voice. Settings are saved per session under session:<id> in the plugin's store
server/server.pyA local HTTP server on 127.0.0.1:47861 that keeps Kokoro loaded on the device in config.json. It plays jobs one at a time, in order. POST /speak returns at once with a job id, or busy when asked to play only while nothing else plays. GET /status?id=N reports progress. POST /stop stops one session's jobs, or every job with no session. POST /shutdown ends the server
server/setup.ps1Run by /voice install. Checks the GPU, installs Python, PyTorch and Kokoro, copies server.py into place, tests Kokoro, and writes config.json

The server log is at %USERPROFILE%\.claude\voice-replies\logs\server.log. The install log is install.log in the same folder.

Develop

claude plugin validate plugins/voice-replies
claude plugin test plugins/voice-replies
python -m unittest discover -s plugins/voice-replies/tests -p "test_server.py"

The server tests replace Kokoro, PyTorch and the sound card with fakes, so they run on any machine with Python 3.10 or later.

Source 2 files
hooks/register.tsx 1045 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { VoiceEngine, VoiceLength, VoiceStatus } from '../types'
5
6const isOn = atom({ plugin: 'voice-replies', key: 'isOn' } as const, true)
7const status = atom({ plugin: 'voice-replies', key: 'status' } as const, 'idle' as VoiceStatus)
8const voice = atom({ plugin: 'voice-replies', key: 'voice' } as const, 'af_heart')
9const speed = atom({ plugin: 'voice-replies', key: 'speed' } as const, '1.0')
10const length = atom({ plugin: 'voice-replies', key: 'length' } as const, 'short' as VoiceLength)
11const engine = atom({ plugin: 'voice-replies', key: 'engine' } as const, 'starting' as VoiceEngine)
12// The step `/voice install` is on, or '' when no install runs.
13const installing = atom({ plugin: 'voice-replies', key: 'install' } as const, '')
14const waiting = atom({ plugin: 'voice-replies', key: 'waiting' } as const, [] as string[])
15// Said before the session's speech when the voice moves to it; '' (the default) says nothing.
16const label = atom({ plugin: 'voice-replies', key: 'label' } as const, '')
17// What the voice calls the person at the start of each reply; '' says no name.
18const callMe = atom({ plugin: 'voice-replies', key: 'callMe' } as const, '')
19// Also saved in this session's store record, so Replay works after a reload or a restart.
20const last = atom({ plugin: 'voice-replies', key: 'last' } as const, '')
21
22const SERVER = 'http://127.0.0.1:47861'
23// The server API this module needs. An older server is restarted from the plugin's copy.
24// 3: each line of a script is spoken on its own, with a pause between lines.
25const API = 3
26// Replies kept for Play while another session speaks; older ones drop off.
27const MAX_WAITING = 3
28// Per-session settings kept in the store; the oldest drop off past this.
29const MAX_SAVED_SESSIONS = 200
30// How long to follow one job, queue time included: 3600 polls of 500 ms.
31const MAX_POLLS = 3600
32
33// Kokoro-82M English voices. First letter: a = American, b = British. Second: f/m.
34const VOICES = [
35  'af_heart', 'af_alloy', 'af_aoede', 'af_bella', 'af_jessica', 'af_kore', 'af_nicole',
36  'af_nova', 'af_river', 'af_sarah', 'af_sky',
37  'am_adam', 'am_echo', 'am_eric', 'am_fenrir', 'am_liam', 'am_michael', 'am_onyx',
38  'am_puck', 'am_santa',
39  'bf_alice', 'bf_emma', 'bf_isabella', 'bf_lily',
40  'bm_daniel', 'bm_fable', 'bm_george', 'bm_lewis',
41] as const
42const SPEEDS = ['0.8', '0.9', '1.0', '1.1', '1.2', '1.3', '1.5'] as const
43const LENGTHS = ['short', 'full'] as const
44
45// How a person talks, shared by both lengths. The voice reads exactly what it gets, so the
46// script must already be written the way it is said.
47const SPOKEN_STYLE = `How it must sound:
48- Talk like a colleague giving a quick update out loud: warm, direct and plain. Use contractions (it's, I've, you'll, didn't).
49- Use short sentences and vary their length. Put commas where a speaker takes a breath.
50- Start a new line between separate topics, so the voice pauses there.
51- Do not open with filler such as "Sure", "Okay so" or "Great news". Do not use the person's name; the voice adds it.
52- Write times, dates and numbers the way people say them: "8:00 AM" is "eight in the morning", "8:30" is "eight thirty", "17:00" is "five in the afternoon", "2026-10-16" is "October sixteenth", "95%" is "ninety-five percent", "v1.5.0" is "version one point five", "3-5 min" is "three to five minutes".
53- Say symbols and abbreviations as words: "&" is "and", "e.g." is "for example", "i.e." is "that is", "~" is "about", "->" is "to", "vs" is "versus".
54- Never read code, commands, file paths, IDs or hashes character by character. Say what they are ("the config file", "a git command") instead.`
55
56const SHORT_RULES = `You turn a coding assistant's chat reply into a short script that a text-to-speech voice reads aloud to the person who asked.
57
58Rules:
59- Output plain spoken sentences only. No markdown, bullets, headings, tables, code, emojis or URLs.
60- Lead with the outcome: what was done, whether it worked, what the person needs to do next.
61- Keep it under 80 words. A short, plain reply can stay almost word for word.
62- If the reply asks the person a question, end with that question.
63- Output only the script, nothing before or after it.
64
65${SPOKEN_STYLE}`
66
67const FULL_RULES = `You turn a coding assistant's chat reply into a script that a text-to-speech voice reads aloud, in full, to the person who asked.
68
69Rules:
70- Output plain spoken sentences only. No markdown, bullets, headings, tables, code, emojis or URLs.
71- Keep every point of the reply, in the same order. Do not summarize and do not leave points out.
72- Turn lists and tables into sentences, one item or row at a time.
73- If the reply asks the person a question, end with that question.
74- Output only the script, nothing before or after it.
75
76${SPOKEN_STYLE}`
77
78// Per length: the rules, the longest script spoken, and the Haiku call's limits.
79const LIMITS = {
80  short: { rules: SHORT_RULES, chars: 1500, maxTokens: 400, timeoutMs: 15000 },
81  full: { rules: FULL_RULES, chars: 12000, maxTokens: 4000, timeoutMs: 60000 },
82} as const
83
84type Settings = {
85  isOn: boolean
86  voice: string
87  speed: string
88  length: VoiceLength
89  callMe: string
90  label?: string
91  last?: string
92}
93
94// The longest name the voice says, for the session or for the person.
95const MAX_NAME = 40
96// The panel's width, in cells, with every control on one line: the title and its state,
97// four labelled controls and the gaps between them. Narrower bands get two rows.
98const ONE_LINE_COLUMNS = 150
99// Room for the Call me label, a short name and its save button.
100const CALL_ME_COLUMNS = 30
101
102// A speech run in flight. `runId` drops stale work; `speakerPid` lets Stop kill the Windows voice.
103let runId = 0
104let speakerPid: number | undefined
105let hasWarnedSetup = false
106let hasTriedUpgrade = false
107// `session:<id>`: this session's settings key in the store, and its name on the voice server.
108let sessionKey = ''
109
110function voiceLabel(name: string): string {
111  const accent = name.startsWith('b') ? 'UK' : 'US'
112  const gender = name[1] === 'm' ? 'male' : 'female'
113  const first = name.slice(3)
114  return `${first.charAt(0).toUpperCase()}${first.slice(1)} (${accent} ${gender})`
115}
116
117function isOneOf<T extends string>(list: readonly T[], value: unknown): value is T {
118  return typeof value === 'string' && (list as readonly string[]).includes(value)
119}
120
121function asRecord(value: unknown): Record<string, unknown> {
122  return typeof value === 'object' && value !== null && !Array.isArray(value)
123    ? (value as Record<string, unknown>)
124    : {}
125}
126
127export const register: Register = on => {
128  on('session.start', async ($, e, next) => {
129    sessionKey = `session:${await $.session.id()}`
130    const settings = await loadSettings($)
131    await update($, isOn, () => settings.isOn)
132    await update($, voice, () => settings.voice)
133    await update($, speed, () => settings.speed)
134    await update($, length, () => settings.length)
135    await update($, callMe, () => settings.callMe)
136    await update($, label, () => settings.label ?? '')
137    await update($, last, () => settings.last ?? '')
138    await update($, status, () => 'idle')
139    await $.command.register({
140      name: 'voice',
141      description:
142        'Voice replies for this session: on, off, stop [all], play, clear, replay, voice <name>, ' +
143        'speed <0.8-1.5>, length short|full, call <your name>, name <words>, default, voices, test, install [gpu|cpu]',
144      argumentHint:
145        '[on|off|stop [all]|play|clear|replay|voice <name>|speed <n>|length short|full|call <your name>|name <words>|default|voices|test|install [gpu|cpu]]',
146    })
147    $.clock.after(0, () => void forgetOldSessions($))
148    // Warm the server up only where someone is watching; elsewhere it starts on first use.
149    if ((await $.session.surfaces()).length > 0) $.clock.after(0, () => void ensureServer($))
150
151    return next(e)
152  })
153
154  on('command.run', { command: 'voice' }, async ($, e) => {
155    const [first = '', ...rest] = e.args.trim().split(/\s+/)
156    const word = first.toLowerCase()
157    const value = rest.join(' ').toLowerCase()
158    if (word === 'stop') {
159      const isAll = value === 'all'
160      await stopSpeaking($, isAll ? 'all' : 'session')
161      return { text: isAll ? 'Stopped speaking in every session.' : 'Stopped speaking.' }
162    }
163    if (word === 'play') {
164      if ((await read($, waiting)).length === 0) return { text: 'No reply is waiting.' }
165      $.clock.after(0, () => void playWaiting($))
166      return { text: 'Playing the waiting reply.' }
167    }
168    if (word === 'clear') {
169      await update($, waiting, () => [])
170      return { text: 'Cleared the waiting replies.' }
171    }
172    if (word === 'replay') {
173      if ((await read($, last)) === '') return { text: 'Nothing to replay yet.' }
174      $.clock.after(0, () => void replayLast($))
175      return { text: 'Replaying the last reply.' }
176    }
177    if (word === 'voices') {
178      return { text: `Voices: ${VOICES.map(v => `${v} = ${voiceLabel(v)}`).join(', ')}` }
179    }
180    if (word === 'voice') {
181      if (!isOneOf(VOICES, value)) {
182        return { text: `Unknown voice "${value}". Type /voice voices to list them.` }
183      }
184      await setVoice($, value)
185      return { text: `Voice set to ${voiceLabel(value)} for this session.` }
186    }
187    if (word === 'speed') {
188      if (!isOneOf(SPEEDS, value)) {
189        return { text: `Speed must be one of ${SPEEDS.join(', ')}.` }
190      }
191      await setSpeed($, value)
192      return { text: `Speed set to ${value} for this session.` }
193    }
194    if (word === 'length') {
195      if (!isOneOf(LENGTHS, value)) return { text: 'Use /voice length short or /voice length full.' }
196      await setLength($, value)
197      return {
198        text: value === 'full'
199          ? 'Replies are read in full in this session.'
200          : 'Replies are read as a short summary in this session.',
201      }
202    }
203    if (word === 'call') {
204      // Keep the person's own capitals; '' stops saying a name.
205      const name = cleanName(rest.join(' '))
206      await setCallMe($, name)
207      return {
208        text: name === ''
209          ? 'Replies in this session no longer start with your name.'
210          : `Replies in this session start with "${name}".`,
211      }
212    }
213    if (word === 'name') {
214      // Keep the person's own capitals; '' stops saying the session's name.
215      const name = rest.join(' ').trim().slice(0, MAX_NAME)
216      await update($, label, () => name)
217      await saveSettings($, { label: name === '' ? undefined : name })
218      return {
219        text: name === ''
220          ? "The voice no longer says this session's name when it moves to it."
221          : `The voice says "${name}" when it moves to this session.`,
222      }
223    }
224    if (word === 'default') {
225      await $.store.set('isOn', await read($, isOn))
226      await $.store.set('voice', await read($, voice))
227      await $.store.set('speed', await read($, speed))
228      await $.store.set('length', await read($, length))
229      await $.store.set('callMe', await read($, callMe))
230      return { text: "New sessions now start with this session's voice, speed, length and name for you." }
231    }
232    if (word === 'install') {
233      const mode = value === '' ? 'auto' : value
234      if (mode !== 'auto' && mode !== 'gpu' && mode !== 'cpu') {
235        return { text: 'Use /voice install, /voice install gpu or /voice install cpu.' }
236      }
237      if ((await read($, installing)) !== '') return { text: 'Kokoro is already installing.' }
238      if ((await $.env.get('OS')) !== 'Windows_NT') {
239        return { text: 'The Kokoro installer runs on Windows only. Replies use the system voice here.' }
240      }
241      await update($, installing, () => 'starting')
242      // The install takes minutes, far past a hook's budget, so it runs on a timer of its own.
243      $.clock.after(0, () => void installKokoro($, mode))
244      return {
245        text:
246          'Installing Kokoro. It checks your GPU first and uses the CPU if the GPU cannot run it. ' +
247          'This takes 5 to 15 minutes; the Windows voice speaks until it is done.',
248      }
249    }
250    if (word === 'test') {
251      $.clock.after(0, () => void speakScript($, 'This is how voice replies will sound.'))
252      return { text: 'Playing a test phrase.' }
253    }
254    const want = word === 'on' ? true : word === 'off' ? false : !(await read($, isOn))
255    await setOn($, want)
256
257    return { text: want ? 'Voice replies are on in this session.' : 'Voice replies are off in this session.' }
258  })
259
260  // A new prompt means the person moved on: stop this session's voice and drop what waits.
261  // Other sessions keep speaking.
262  on('prompt.submit', ($, e, next) => {
263    // Never let the voice block a prompt: errors here are logged, not thrown.
264    const quiet = (err: unknown) => $.ui.log(`voice-replies: ${String(err)}`, { to: 'debug' })
265    stopSpeaking($).catch(quiet)
266    update($, waiting, () => []).catch(quiet)
267
268    return next(e)
269  })
270
271  on('turn.complete', async ($, e, next) => {
272    const result = await next(e)
273    const isMainAnswer = e.agentId === undefined && e.reason === 'answer' && !e.isAborted
274    if (!isMainAnswer || e.answer.trim() === '' || !(await read($, isOn))) return result
275    // Stay silent where nobody is watching: `claude -p` runs, scheduled tasks, agents
276    // driven over the SDK with no app attached.
277    if ((await $.session.surfaces()).length === 0) return result
278    // The Chief of Staff's own session speaks through its own voice daemon.
279    if (await isChiefSession($)) return result
280
281    // Speaking outlasts the hook's 10 s budget, so it runs on a timer of its own.
282    const answer = e.answer
283    $.clock.after(0, () => void speakReply($, answer))
284
285    return result
286  })
287
288  // The voice controls are a small panel of their own at the foot of the band above the
289  // prompt, under anything other mods draw there (session-brief). The desktop app does not
290  // draw a mod's tree in the prompt footer, so the band is the one place that works on both.
291  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
292    const above = await next(e)
293    if (e.props.hasSurvey) return above
294    const ui = $.ui.resolve(e)
295    const { Box, Button, Text } = ui
296    const Select = 'Select' in ui ? ui.Select : undefined
297    const Input = 'Input' in ui ? ui.Input : undefined
298    if (Select === undefined || Input === undefined) return above
299
300    const enabled = await read($, isOn)
301    const now = await read($, status)
302    const chosen = await read($, voice)
303    const pace = await read($, speed)
304    const size = await read($, length)
305    const via = await read($, engine)
306    const step = await read($, installing)
307    const held = await read($, waiting)
308    const you = await read($, callMe)
309    // Replay is for a reply that already played, maybe while the person was away. A waiting
310    // reply has Play instead, and Stop takes the place while the voice is busy.
311    const canReplay = enabled && now === 'idle' && held.length === 0 && (await read($, last)) !== ''
312    // Say the engine only when it is not the normal one (Kokoro).
313    const note =
314      now === 'writing' ? 'preparing'
315      : now === 'queued' ? 'in line'
316      : now === 'speaking' ? 'speaking'
317      : step !== '' ? `installing Kokoro: ${step}`
318      : via === 'windows' ? 'Windows voice'
319      : via === 'starting' ? 'starting'
320      : ''
321
322    // Wide enough for everything on one line: one row. Narrower: the title, state and
323    // buttons on top, the settings below. Every item keeps its own width (flexShrink 0) and
324    // moves to the next line when it does not fit, so labels never draw over each other.
325    const isOneLine = e.props.bodyColumns >= ONE_LINE_COLUMNS
326
327    return (
328      <Box flexDirection="column" rowGap={1}>
329        {above}
330        <Box
331          flexDirection={isOneLine ? 'row' : 'column'}
332          alignItems={isOneLine ? 'center' : 'stretch'}
333          justifyContent="space-between"
334          columnGap={3}
335          rowGap={1}
336          borderStyle="round"
337          borderDimColor
338          paddingX={1}
339        >
340          <Box flexDirection="row" flexWrap="wrap" alignItems="center" columnGap={2} rowGap={1} flexShrink={0}>
341            <Box flexShrink={0}>
342              <Text dimColor wrap="truncate">Voice replies</Text>
343            </Box>
344            {note !== '' && (
345              <Box flexShrink={0}>
346                <Text key="note" dimColor wrap="truncate">{note}</Text>
347              </Box>
348            )}
349            {held.length > 0 && (
350              <Box flexShrink={0}>
351                <Text key="waiting" wrap="truncate">
352                  {held.length === 1 ? '1 reply waiting' : `${held.length} replies waiting`}
353                </Text>
354              </Box>
355            )}
356            {held.length > 0 && (
357              <Button key="play" label="Play" onPress={() => void $.clock.after(0, () => void playWaiting($))} />
358            )}
359            {held.length > 0 && (
360              <Button key="dismiss" label="Dismiss" dimColor onPress={() => update($, waiting, () => [])} />
361            )}
362            {canReplay && (
363              <Button key="replay" label="Replay" onPress={() => void $.clock.after(0, () => void replayLast($))} />
364            )}
365            {now !== 'idle' && <Button key="stop" label="Stop" dimColor onPress={() => stopSpeaking($)} />}
366          </Box>
367          <Box flexDirection="row" flexWrap="wrap" alignItems="center" columnGap={3} rowGap={1}>
368            <Box flexShrink={0}>
369              <Select
370                key="voice"
371                label="Voice"
372                value={enabled ? chosen : OFF}
373                options={[
374                  { value: OFF, label: 'Off' },
375                  ...VOICES.map(v => ({ value: v, label: voiceLabel(v) })),
376                ]}
377                onSelect={(value: string) => void pickVoice($, value)}
378              />
379            </Box>
380            {enabled && (
381              <Box flexShrink={0}>
382                <Select
383                  key="speed"
384                  label="Speed"
385                  value={pace}
386                  options={SPEEDS.map(s => ({ value: s, label: `${s}x` }))}
387                  onSelect={(value: string) => void setSpeed($, value)}
388                />
389              </Box>
390            )}
391            {enabled && (
392              <Box flexShrink={0}>
393                <Select
394                  key="length"
395                  label="Length"
396                  value={size}
397                  options={[
398                    { value: 'short', label: 'Short' },
399                    { value: 'full', label: 'Full' },
400                  ]}
401                  onSelect={(value: string) => void (isOneOf(LENGTHS, value) && setLength($, value))}
402                />
403              </Box>
404            )}
405            {enabled && (
406              <Box flexShrink={0} minWidth={CALL_ME_COLUMNS}>
407                <Input
408                  key="call"
409                  label="Call me"
410                  placeholder="your name"
411                  value={you}
412                  submitLabel="save"
413                  onSubmit={(value: string) => void setCallMe($, cleanName(value))}
414                />
415              </Box>
416            )}
417          </Box>
418        </Box>
419      </Box>
420    )
421  })
422}
423
424// True when this session is the chief-of-staff plugin's Chief: its server.json names this
425// session's CLI id as chiefCliId and that server still answers, so a server that crashed
426// and left server.json behind never silences the session. Any failure means no.
427async function isChiefSession($: EngineInterface): Promise<boolean> {
428  try {
429    const home = await $.env.get('USERPROFILE')
430    if (home === undefined) return false
431    const raw = await $.fs.read(`${home}\\.claude\\chief-of-staff\\run\\server.json`)
432    const info = JSON.parse(typeof raw === 'string' ? raw : '{}') as { chiefCliId?: unknown; port?: unknown }
433    if (typeof info.chiefCliId !== 'string' || info.chiefCliId !== (await $.session.id())) return false
434    if (typeof info.port !== 'number') return false
435    const res = await $.http.fetch(`http://127.0.0.1:${info.port}/api/health`)
436    const health = JSON.parse(res.text) as { app?: unknown }
437    return res.ok && health.app === 'chief-of-staff'
438  } catch {
439    return false
440  }
441}
442
443// Settings: the store's top-level keys are the defaults for new sessions (and what 1.2 saved);
444// `session:<id>` holds what this session changed.
445async function loadSettings($: EngineInterface): Promise<Settings> {
446  const [savedOn, savedVoice, savedSpeed, savedLength, savedCallMe, own] = await Promise.all([
447    $.store.get('isOn'),
448    $.store.get('voice'),
449    $.store.get('speed'),
450    $.store.get('length'),
451    $.store.get('callMe'),
452    $.store.get(sessionKey),
453  ])
454  const mine = asRecord(own)
455  const pick = <T,>(ok: (v: unknown) => v is T, fallback: T, ...values: unknown[]): T =>
456    (values.find(ok) as T | undefined) ?? fallback
457  const isBool = (v: unknown): v is boolean => typeof v === 'boolean'
458
459  return {
460    isOn: pick(isBool, true, mine.isOn, savedOn),
461    voice: pick((v): v is string => isOneOf(VOICES, v), 'af_heart', mine.voice, savedVoice),
462    speed: pick((v): v is string => isOneOf(SPEEDS, v), '1.0', mine.speed, savedSpeed),
463    length: pick((v): v is VoiceLength => isOneOf(LENGTHS, v), 'short', mine.length, savedLength),
464    // '' saved for this session means "no name here", over the default.
465    callMe: pick((v): v is string => typeof v === 'string', '', mine.callMe, savedCallMe).slice(0, MAX_NAME),
466    label: typeof mine.label === 'string' && mine.label !== '' ? mine.label : undefined,
467    last: typeof mine.last === 'string' ? mine.last : undefined,
468  }
469}
470
471async function saveSettings($: EngineInterface, patch: Partial<Settings>): Promise<void> {
472  if (sessionKey === '') return
473  const own = asRecord(await $.store.get(sessionKey))
474  await $.store.set(sessionKey, { ...own, ...patch, at: await now($) })
475}
476
477// Keeps the store small: drops the settings of the sessions used longest ago.
478async function forgetOldSessions($: EngineInterface): Promise<void> {
479  const keys = (await $.store.keys()).filter(k => k.startsWith('session:'))
480  if (keys.length <= MAX_SAVED_SESSIONS) return
481  const dated = await Promise.all(
482    keys.map(async k => ({ k, at: Number(asRecord(await $.store.get(k)).at ?? 0) })),
483  )
484  dated.sort((a, b) => a.at - b.at)
485  for (const { k } of dated.slice(0, dated.length - MAX_SAVED_SESSIONS)) {
486    if (k !== sessionKey) await $.store.delete(k)
487  }
488}
489
490async function now($: EngineInterface): Promise<number> {
491  try {
492    return await $.clock.now()
493  } catch {
494    return 0
495  }
496}
497
498// The repository's folder name (the main one, for a worktree), else the session's folder.
499async function defaultLabel($: EngineInterface): Promise<string> {
500  const baseName = (path: string) => path.split(/[\\/]/).filter(Boolean).at(-1) ?? ''
501  try {
502    const repo = await $.session.repo()
503    if (repo !== null) return baseName(repo.root)
504  } catch {
505    // Not a git repository, or git is missing: use the folder.
506  }
507  try {
508    return baseName(await $.session.root())
509  } catch {
510    return ''
511  }
512}
513
514async function setOn($: EngineInterface, value: boolean): Promise<void> {
515  await update($, isOn, () => value)
516  await saveSettings($, { isOn: value })
517  if (!value) {
518    await stopSpeaking($)
519    await update($, waiting, () => [])
520  }
521}
522
523// The voice dropdown's first option turns voice replies off; any voice turns them on.
524const OFF = 'off'
525
526async function pickVoice($: EngineInterface, value: string): Promise<void> {
527  if (value === OFF) {
528    await setOn($, false)
529    return
530  }
531  await setVoice($, value)
532  if (!(await read($, isOn))) await setOn($, true)
533}
534
535async function setVoice($: EngineInterface, value: string): Promise<void> {
536  await update($, voice, () => value)
537  await saveSettings($, { voice: value })
538}
539
540async function setSpeed($: EngineInterface, value: string): Promise<void> {
541  await update($, speed, () => value)
542  await saveSettings($, { speed: value })
543}
544
545async function setLength($: EngineInterface, value: VoiceLength): Promise<void> {
546  await update($, length, () => value)
547  await saveSettings($, { length: value })
548}
549
550async function setCallMe($: EngineInterface, value: string): Promise<void> {
551  await update($, callMe, () => value)
552  await saveSettings($, { callMe: value })
553}
554
555async function setStatus($: EngineInterface, value: VoiceStatus): Promise<void> {
556  if ((await read($, status)) !== value) await update($, status, () => value)
557}
558
559// The server's API version: 0 when it is not running, 1 for a server from before 1.3.0.
560async function serverApi($: EngineInterface): Promise<number> {
561  try {
562    const res = await $.http.fetch(`${SERVER}/health`)
563    if (!res.ok) return 0
564    const { api } = JSON.parse(res.text) as { api?: unknown }
565    return typeof api === 'number' ? api : 1
566  } catch {
567    return 0
568  }
569}
570
571// PowerShell single-quoted string.
572function psQuote(text: string): string {
573  return `'${text.replace(/'/g, "''")}'`
574}
575
576// Starts the shared Kokoro server if it is not running, from the plugin's own server.py, so a
577// plugin update reaches the server. A server older than API is stopped and started again, once.
578// It runs hidden, outlives this session, and exits by itself after two idle hours.
579async function ensureServer($: EngineInterface): Promise<boolean> {
580  const api = await serverApi($)
581  if (api >= API) {
582    await update($, engine, () => 'kokoro')
583    return true
584  }
585  // An old server still speaks; it only lacks the queue. Use it rather than restart again.
586  if (api > 0 && hasTriedUpgrade) return true
587  // The installer stops the server and rewrites its files: do not start it under it.
588  if ((await read($, installing)) !== '') {
589    await update($, engine, () => 'windows')
590    return false
591  }
592  const home = await $.env.get('USERPROFILE')
593  if (home === undefined) {
594    await update($, engine, () => 'windows')
595    return false
596  }
597  const dir = `${home}\\.claude\\voice-replies`
598  const isSetUp = await $.fs.stat(`${dir}\\venv\\Scripts\\pythonw.exe`).then(
599    () => true,
600    () => false,
601  )
602  if (!isSetUp) {
603    await update($, engine, () => 'windows')
604    if (!hasWarnedSetup) {
605      hasWarnedSetup = true
606      $.ui.toast('Kokoro is not set up, so replies use the Windows voice. Type /voice install to set it up.')
607    }
608    return false
609  }
610  await update($, engine, () => 'starting')
611  const commands = [`$d = ${psQuote(dir)}`]
612  if (api > 0) {
613    hasTriedUpgrade = true
614    $.ui.log('voice-replies: restarting an older voice server', { to: 'debug' })
615    // Servers before API 2 have no /shutdown, so stop the process itself.
616    commands.push(
617      "Get-CimInstance Win32_Process -Filter \"Name='pythonw.exe'\" | " +
618        "Where-Object { $_.CommandLine -like '*voice-replies*server.py*' -and $_.CommandLine -notlike '*--check*' } | " +
619        'ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }',
620      'Start-Sleep -Milliseconds 500',
621    )
622  }
623  commands.push(
624    `Copy-Item -LiteralPath ${psQuote(`${$.plugin.root}\\server\\server.py`)} -Destination (Join-Path $d 'server.py') -Force -ErrorAction SilentlyContinue`,
625    "Start-Process -WindowStyle Hidden -FilePath (Join-Path $d 'venv\\Scripts\\pythonw.exe') " +
626      "-ArgumentList ('\"' + (Join-Path $d 'server.py') + '\"') -WorkingDirectory $d",
627  )
628  try {
629    await $.process.run(
630      ['powershell.exe', '-NoProfile', '-NonInteractive', '-Command', commands.join('; ')],
631      { timeoutMs: 30000 },
632    )
633  } catch {
634    await update($, engine, () => 'windows')
635    return false
636  }
637  // The model takes a few seconds to load onto the GPU.
638  for (let i = 0; i < 60; i += 1) {
639    await wait($, 1000)
640    const up = await serverApi($)
641    if (up >= API) {
642      await update($, engine, () => 'kokoro')
643      return true
644    }
645  }
646  await update($, engine, () => 'windows')
647  return false
648}
649
650// Runs server\setup.ps1, which checks the GPU, picks GPU or CPU, installs Kokoro and tests it.
651// Each "==> step" line shows in the panel and the status line; the last lines explain a failure.
652async function installKokoro($: EngineInterface, mode: 'auto' | 'gpu' | 'cpu'): Promise<void> {
653  const tail: string[] = []
654  let partial = ''
655  let done = ''
656  let choice = ''
657  const onLine = async (raw: string) => {
658    const line = raw.trim()
659    if (line === '') return
660    tail.push(line)
661    if (tail.length > 8) tail.shift()
662    if (line.startsWith('==> ')) {
663      const step = line.slice(4)
664      await update($, installing, () => step)
665      $.ui.status(`Kokoro install: ${step}`)
666    } else if (line.startsWith('Kokoro will run on the ')) {
667      choice = line
668    } else if (line.startsWith('DONE: ')) {
669      done = line.slice(6)
670    }
671  }
672
673  let code: number | null = null
674  try {
675    const child = $.process.spawn({
676      argv: [
677        'powershell.exe', '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass',
678        '-File', `${$.plugin.root}\\server\\setup.ps1`, '-Device', mode,
679      ],
680    })
681    for await (const { text } of child) {
682      const lines = (partial + text).split(/\r?\n/)
683      partial = lines.pop() ?? ''
684      for (const line of lines) await onLine(line)
685    }
686    await onLine(partial)
687    code = (await child.result).code
688  } catch (err) {
689    tail.push(String(err))
690  }
691
692  await update($, installing, () => '')
693  $.ui.status(undefined)
694  if (code === 0 && done !== '') {
695    hasWarnedSetup = false
696    $.ui.toast(done)
697    $.ui.log(`voice-replies: ${choice} ${done}`, { to: 'debug' })
698    await ensureServer($)
699    return
700  }
701  const why = tail.filter(l => !l.startsWith('At ') && !l.startsWith('+ ')).slice(-2).join(' ')
702  $.ui.toast(`Kokoro install failed: ${why} Full log: %USERPROFILE%\\.claude\\voice-replies\\logs\\install.log`)
703  await update($, engine, () => 'windows')
704}
705
706// A pause built on $.clock.after, which runs outside any hook's time budget.
707function wait($: EngineInterface, ms: number): Promise<void> {
708  return new Promise(resolve => void $.clock.after(ms, resolve))
709}
710
711// Stops this session's voice, or with 'all' every session's. Other sessions keep their place.
712async function stopSpeaking($: EngineInterface, scope: 'session' | 'all' = 'session'): Promise<void> {
713  runId += 1
714  const pid = speakerPid
715  speakerPid = undefined
716  await update($, status, () => 'idle')
717  try {
718    await $.http.fetch(`${SERVER}/stop`, {
719      method: 'POST',
720      headers: { 'Content-Type': 'application/json' },
721      body: JSON.stringify(scope === 'all' ? {} : { session: sessionKey }),
722    })
723  } catch {
724    // Server not running: nothing to stop there.
725  }
726  if (pid === undefined) return
727  try {
728    await $.process.run(['taskkill', '/PID', String(pid), '/T', '/F'], { timeoutMs: 5000 })
729  } catch {
730    // Already gone, or not Windows: nothing to stop.
731  }
732}
733
734async function speakReply($: EngineInterface, answer: string): Promise<void> {
735  await stopSpeaking($)
736  const id = runId
737  await update($, status, () => 'writing')
738
739  const script = await toSpeech($, answer)
740  if (id !== runId) return
741  if (script !== '') {
742    await update($, last, () => script)
743    await saveSettings($, { last: script })
744  }
745  await playScript($, script, id, 'idle')
746}
747
748async function replayLast($: EngineInterface): Promise<void> {
749  const script = await read($, last)
750  if (script !== '') await speakScript($, script)
751}
752
753// Plays at once, or after what other sessions have queued: /voice test, replay and Play.
754async function speakScript($: EngineInterface, script: string): Promise<void> {
755  await stopSpeaking($)
756  await playScript($, script, runId, 'queue')
757}
758
759async function playWaiting($: EngineInterface): Promise<void> {
760  const held = await read($, waiting)
761  if (held.length === 0) return
762  await update($, waiting, () => [])
763  await speakScript($, held.join('\n\n'))
764}
765
766// 'idle': speak only if no session is speaking, else hold the reply for Play.
767// 'queue': speak after what is already queued.
768async function playScript($: EngineInterface, script: string, id: number, when: 'idle' | 'queue'): Promise<void> {
769  if (script === '') {
770    await update($, status, () => 'idle')
771    return
772  }
773  // The person's name goes on at play time, so a held or replayed script never says it twice.
774  // It is a line of its own: the voice server pauses between lines, as a person does after
775  // saying someone's name.
776  const you = cleanName(await read($, callMe))
777  const spoken = you === '' ? script : `${you},\n${script}`
778  try {
779    const outcome = await speakKokoro($, spoken, id, when)
780    if (outcome === 'busy') {
781      await holdReply($, script)
782    } else if (outcome === 'failed' && id === runId) {
783      await setStatus($, 'speaking')
784      await speakWindows($, spoken, id)
785    }
786  } catch (err) {
787    $.ui.log(`voice-replies: could not speak: ${String(err)}`, { to: 'debug' })
788  } finally {
789    if (id === runId) await update($, status, () => 'idle')
790  }
791}
792
793// Another session is speaking: keep the reply for Play and tell the person where it is.
794async function holdReply($: EngineInterface, script: string): Promise<void> {
795  const held = [...(await read($, waiting)), script].slice(-MAX_WAITING)
796  await update($, waiting, () => held)
797  $.ui.toast('Another session is speaking. This reply waits: press Play to hear it.')
798  // The notification names the session even when the voice does not say its name.
799  const name = (await read($, label)) || (await defaultLabel($))
800  try {
801    await $.ui.notify(
802      `${name === '' ? 'A session' : name} has a reply waiting. Press Play in that session to hear it.`,
803      { title: 'Voice replies' },
804    )
805  } catch (err) {
806    $.ui.log(`voice-replies: could not notify: ${String(err)}`, { to: 'debug' })
807  }
808}
809
810async function toSpeech($: EngineInterface, answer: string): Promise<string> {
811  const limit = LIMITS[await read($, length)]
812  const reply = await $.model.complete({
813    model: 'haiku',
814    system: [{ text: limit.rules, cache: true }],
815    prompt: `Reply to convert:\n\n${answer.slice(0, 20000)}`,
816    maxTokens: limit.maxTokens,
817    effort: 'low',
818    timeoutMs: limit.timeoutMs,
819  })
820  const text = reply.isAnswered ? reply.text : stripMarkdown(answer)
821
822  return clipAtSentence(speakable(text.trim()), limit.chars)
823}
824
825// Cuts a script that is too long at the end of a sentence, never in the middle of a word.
826function clipAtSentence(text: string, max: number): string {
827  if (text.length <= max) return text
828  const head = text.slice(0, max)
829  const end = Math.max(...['. ', '! ', '? ', '.\n', '!\n', '?\n'].map(mark => head.lastIndexOf(mark)))
830  if (end >= max / 2) return head.slice(0, end + 1)
831  const space = head.lastIndexOf(' ')
832  return `${space > 0 ? head.slice(0, space) : head}.`
833}
834
835// Kokoro on the GPU. 'failed' only when the server did not take the text, so the caller
836// falls back to the Windows voice; 'busy' when `when` is 'idle' and another session speaks.
837// Once Kokoro has taken the text it never falls back: the server answers /speak at once and
838// this polls /status until the voice ends.
839async function speakKokoro(
840  $: EngineInterface,
841  text: string,
842  id: number,
843  when: 'idle' | 'queue',
844): Promise<'spoken' | 'busy' | 'failed'> {
845  if (!(await ensureServer($))) return 'failed'
846  let job: number
847  try {
848    const name = await read($, label)
849    const res = await $.http.fetch(`${SERVER}/speak`, {
850      method: 'POST',
851      headers: { 'Content-Type': 'application/json' },
852      body: JSON.stringify({
853        text,
854        voice: await read($, voice),
855        speed: Number(await read($, speed)),
856        session: sessionKey,
857        tag: name.replace(/[-_.]+/g, ' ').trim(),
858        when,
859      }),
860    })
861    const body = res.ok ? (JSON.parse(res.text) as { id?: unknown; state?: unknown }) : {}
862    if (body.state === 'busy') return 'busy'
863    if (typeof body.id !== 'number') {
864      $.ui.log(`voice-replies: Kokoro said ${res.status}: ${res.text}`, { to: 'debug' })
865      await update($, engine, () => 'windows')
866      return 'failed'
867    }
868    job = body.id
869  } catch {
870    await update($, engine, () => 'windows')
871    return 'failed'
872  }
873  await update($, engine, () => 'kokoro')
874
875  // Kokoro has it now. Wait until it ends, is stopped, or the server goes quiet.
876  let misses = 0
877  for (let i = 0; i < MAX_POLLS && id === runId; i += 1) {
878    await wait($, 500)
879    try {
880      const res = await $.http.fetch(`${SERVER}/status?id=${job}`)
881      const { state } = JSON.parse(res.text) as { state?: string }
882      misses = 0
883      if (state !== 'queued' && state !== 'speaking') break
884      if (id === runId) await setStatus($, state)
885    } catch {
886      misses += 1
887      if (misses >= 6) break
888    }
889  }
890  return 'spoken'
891}
892
893// Windows: the built-in SAPI voice through PowerShell, which prints its PID so Stop can kill it.
894// Elsewhere (no powershell.exe): the platform voice through $.audio.speak.
895const PS_SPEAK = [
896  '[Console]::InputEncoding = [Text.Encoding]::UTF8',
897  '[Console]::Out.WriteLine($PID); [Console]::Out.Flush()',
898  '$t = [Console]::In.ReadToEnd()',
899  'Add-Type -AssemblyName System.Speech',
900  '$s = New-Object System.Speech.Synthesis.SpeechSynthesizer',
901  '$s.Speak($t)',
902].join('; ')
903
904async function speakWindows($: EngineInterface, text: string, id: number): Promise<void> {
905  let started = false
906  try {
907    const child = $.process.spawn({
908      argv: ['powershell.exe', '-NoProfile', '-NonInteractive', '-Command', PS_SPEAK],
909      input: text,
910    })
911    for await (const { stream, text: out } of child) {
912      started = true
913      if (stream !== 'stdout' || speakerPid !== undefined) continue
914      const pid = Number.parseInt(out.trim(), 10)
915      if (Number.isFinite(pid)) speakerPid = pid
916      if (id !== runId) await stopSpeaking($)
917    }
918    if (id === runId) speakerPid = undefined
919    return
920  } catch (err) {
921    if (started) throw err
922  }
923  await $.audio.speak(text)
924}
925
926const SMALL = [
927  'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten',
928  'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen',
929]
930const TENS = ['', '', 'twenty', 'thirty', 'forty', 'fifty']
931const ORDINAL: Record<string, string> = {
932  one: 'first', two: 'second', three: 'third', five: 'fifth', eight: 'eighth', nine: 'ninth', twelve: 'twelfth',
933}
934const MONTHS = [
935  'January', 'February', 'March', 'April', 'May', 'June',
936  'July', 'August', 'September', 'October', 'November', 'December',
937]
938
939// 0 to 59 in words: "seven", "forty-five".
940function numberWords(n: number): string {
941  if (n < 20) return SMALL[n] ?? String(n)
942  const ones = n % 10
943  const tens = TENS[Math.floor(n / 10)] ?? String(n)
944  return ones === 0 ? tens : `${tens}-${SMALL[ones]}`
945}
946
947// 1 to 31 as a spoken ordinal: "first", "sixteenth", "twenty-second".
948function ordinalWords(n: number): string {
949  const words = numberWords(n)
950  const parts = words.split('-')
951  const tail = parts.pop() ?? ''
952  const said = ORDINAL[tail] ?? (tail.endsWith('y') ? `${tail.slice(0, -1)}ieth` : `${tail}th`)
953  return [...parts, said].join('-')
954}
955
956// A clock time as a person says it: "eight o'clock", "eight thirty", "eight oh five in the
957// morning", "noon". `meridiem` is 'a' or 'p' when the text gave AM or PM.
958function sayTime(hour: number, minute: number, meridiem: string | undefined): string {
959  const isPm = meridiem === 'p' || (meridiem === undefined && hour > 12)
960  const isAm = meridiem === 'a' || (meridiem === undefined && hour === 0)
961  let h = hour % 12
962  if (h === 0 && (isAm || isPm || hour === 12)) h = 12
963  if (minute === 0 && h === 12 && isPm) return 'noon'
964  if (minute === 0 && h === 12 && isAm) return 'midnight'
965  const mins = minute === 0 ? '' : minute < 10 ? ` oh ${numberWords(minute)}` : ` ${numberWords(minute)}`
966  const clock = `${numberWords(h)}${mins}`
967  if (!isAm && !isPm) return minute === 0 ? `${clock} o'clock` : clock
968  const base = h === 12 ? 0 : h
969  const part = isAm
970    ? base === 0 ? 'at night' : 'in the morning'
971    : base < 6 ? 'in the afternoon' : base < 9 ? 'in the evening' : 'at night'
972  return `${clock} ${part}`
973}
974
975// Keeps a sentence's full stop when "a.m." or "p.m." ended the sentence.
976function keepStop(match: string, rest: string): string {
977  return match.endsWith('.') && (rest === '' || /^\s+[A-Z]/.test(rest)) ? '.' : ''
978}
979
980// The last pass over every script before the voice gets it: rewrites what text-to-speech
981// voices read badly ("8:00" as "eight zero zero") into the words a person would say.
982// Haiku is asked to do this too; this catches what it leaves, and the plain-text fallback.
983function speakable(text: string): string {
984  return text
985    .replace(/\p{Extended_Pictographic}️?/gu, '')
986    .replace(/[*`#]+/g, '')
987    // ISO dates: 2026-10-16 -> October sixteenth, 2026
988    .replace(/\b(\d{4})-(\d{2})-(\d{2})\b/g, (m, y: string, mo: string, d: string) => {
989      const month = MONTHS[Number(mo) - 1]
990      const day = Number(d)
991      return month === undefined || day < 1 || day > 31 ? m : `${month} ${ordinalWords(day)}, ${y}`
992    })
993    // Clock times, with or without AM / PM: 8:00 AM, 8:30, 17:45, 9:05 p.m.
994    .replace(
995      /\b([01]?\d|2[0-3]):([0-5]\d)(?![\d:])(?:\s?([AaPp])\.?\s?[Mm]\b\.?)?/g,
996      (m: string, h: string, min: string, ap: string | undefined, at: number, all: string) =>
997        sayTime(Number(h), Number(min), ap?.toLowerCase()) + keepStop(m, all.slice(at + m.length)),
998    )
999    // Whole hours with AM / PM: 8am, 8 PM, 11 p.m.
1000    .replace(
1001      /\b(1[0-2]|0?[1-9])\s?([AaPp])\.?\s?[Mm]\b\.?/g,
1002      (m: string, h: string, ap: string, at: number, all: string) =>
1003        sayTime(Number(h), 0, ap.toLowerCase()) + keepStop(m, all.slice(at + m.length)),
1004    )
1005    // Versions: v1.5.0 -> version 1 point 5 point 0
1006    .replace(/\bv(\d+(?:\.\d+)+)\b/g, (_m, v: string) => `version ${v.split('.').join(' point ')}`)
1007    .replace(/\b(\d+)\.(\d+)\.(\d+)\b/g, '$1 point $2 point $3')
1008    // Ranges and amounts: 5-15 -> 5 to 15, 95% -> 95 percent, 1.2x -> 1.2 times
1009    .replace(/(\d)\s?[-–]\s?(\d)/g, '$1 to $2')
1010    .replace(/(\d)\s?%/g, '$1 percent')
1011    .replace(/\b(\d+(?:\.\d+)?)x\b/g, '$1 times')
1012    .replace(/~\s?(?=\d)/g, 'about ')
1013    // Symbols and abbreviations said as words.
1014    .replace(/\s&\s/g, ' and ')
1015    .replace(/\s?(?:->|→|=>)\s?/g, ' to ')
1016    .replace(/\be\.g\.,?/gi, 'for example,')
1017    .replace(/\bi\.e\.,?/gi, 'that is,')
1018    .replace(/\betc\./gi, 'and so on.')
1019    .replace(/\bvs\.?(?=\s)/gi, 'versus')
1020    .replace(/\bw\/(?=\s)/gi, 'with')
1021    .replace(/[ \t]{2,}/g, ' ')
1022    .trim()
1023}
1024
1025// The name the voice calls the person, without the punctuation the voice adds itself.
1026function cleanName(name: string): string {
1027  return name.trim().replace(/[\s,.;:!?\-–—]+$/, '').slice(0, MAX_NAME)
1028}
1029
1030function stripMarkdown(md: string): string {
1031  return md
1032    .replace(/```[\s\S]*?```/g, ' (code omitted) ')
1033    .replace(/`([^`]*)`/g, '$1')
1034    .replace(/!\[[^\]]*\]\([^)]*\)/g, '')
1035    .replace(/\[([^\]]+)\]\([^)]*\)/g, '$1')
1036    .replace(/^\s{0,3}#{1,6}\s+/gm, '')
1037    .replace(/^\s*[-*+]\s+/gm, '')
1038    .replace(/^\s*\|.*\|\s*$/gm, '')
1039    .replace(/[*_~>]+/g, '')
1040    .replace(/https?:\/\/\S+/g, 'a link')
1041    .replace(/\n{2,}/g, '. ')
1042    .replace(/\s+/g, ' ')
1043    .trim()
1044}
1045
types/index.d.ts 26 lines
1export type VoiceStatus = 'idle' | 'writing' | 'queued' | 'speaking'
2export type VoiceEngine = 'kokoro' | 'windows' | 'starting'
3export type VoiceLength = 'short' | 'full'
4
5declare module 'claude-code' {
6  interface PluginState {
7    'voice-replies': {
8      isOn: boolean
9      status: VoiceStatus
10      voice: string
11      speed: string
12      length: VoiceLength
13      engine: VoiceEngine
14      install: string
15      // Speech scripts of this session's replies that wait for Play, oldest first.
16      waiting: string[]
17      // The last speech script this session spoke or held, for Replay. '' when none yet.
18      last: string
19      // What the voice says first when it moves to this session from another one. '' says nothing.
20      label: string
21      // What the voice calls the person at the start of each reply. '' says no name.
22      callMe: string
23    }
24  }
25}
26