SLOPSHOPPER

Better Call GPT

Voice-call this Claude Code session on macOS: Call, Mute, Steer and Hang up above the prompt. During a call, your speech, what you type, Claude's replies and…

bandcommandtoastpromptprocesstimer
★ 8v0.2.2MITupdated 2026-10-09insta-fusion/bettercallgpt/plugin
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · bettercallgpt
› 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 › /call-icons ⎿ bettercallgpt: icons: keys (choose keys, nerd, emoji or none) ⟨Claude Code's own drawing⟩ ◌ HANGING UP saying goodbye… ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
⟨Claude Code's own drawing⟩ ◌ HANGING UP saying goodbye…
README

Better Call GPT

Put this Claude Code session on a full-duplex voice call. You talk while it codes, interrupt it at any time, and hear results read back. A spoken "yes" never approves anything: permission prompts stay on your keyboard. macOS only.

Open source (MIT). We run no server and collect nothing: the call runs on your own key, with the voice provider you choose.

Commands

  • /bettercallgpt:on starts a voice call bound to this session. Claude Code asks you to approve the start.
  • /bettercallgpt:status shows whether the call is live.
  • /bettercallgpt:off ends the call.

On Claude Code 2.1.287+ (CLI and the desktop Code tab) a row above the prompt does the same with one press: Call, Mute (the voice service hears silence until you press Unmute; the band shows MUTED while it lasts), Steer (send what you just said now; Claude's running turn makes way; unsent words exist only on the GPT-Live voice, on Voice Live Steer brings a waiting message forward) and Hang up (/clear and closing the session end the call too). /call, /mute, /steer and /hangup are the same actions; /call-icons picks the symbols.

Get started

  1. Install uv (the voice process runs through it).
  2. Copy .env.example to ~/.config/bettercallgpt/.env and paste your voice key into that file, not into the chat. Keys come from Azure (Voice Live or GPT-Live) or OpenAI (Realtime).
  3. Press Call above the prompt, or type /bettercallgpt:on. A rising tone means you are live.

What it runs, sends and fetches

Everything below is the whole list. The plugin is one hooks module (the Mod, hooks/register.tsx) and three commands; the voice itself is a separate program, bettercallgpt, from this repository.

The Mod runs one program

  • Which: bettercallgpt, the voice process. Nothing else.
  • How, exactly: when you press Call, the Mod starts it as a child of your Claude Code process with one of these two commands, no shell and no inline script:
  • an installed command, if one is found as a file at ~/.local/bin/bettercallgpt, /opt/homebrew/bin/bettercallgpt or /usr/local/bin/bettercallgpt (checked as files, in that order; the first one found is run once with the single fixed argument --help, and if it does not know the console the pinned release below is used instead): bettercallgpt --session <session id> --nonce <nonce> --mod start
  • otherwise the pinned release through uv: uvx --from git+https://github.com/insta-fusion/bettercallgpt@v0.2.2 bettercallgpt --session <session id> --nonce <nonce> --mod start
  • <session id> is this Claude Code session's id; <nonce> is a fresh single-use token the Mod makes for that start. No other value is read into the command.
  • Hang up, Steer and Mute run the same program, written out the same two ways, with the fixed arguments --session <session id> stop, --session <session id> steer and --session <session id> mute (or unmute).
  • Your press is the consent: no model turn runs and no permission prompt is shown. The voice process (not the Mod) refuses this kind of start unless Claude Code itself spawned it.

What leaves your machine, and where

  • The Mod itself sends nothing. It makes no network request and opens no socket.
  • The voice process sends your microphone audio and the text of the call to the one realtime voice service you configured, with your own key: Azure Voice Live (*.cognitiveservices.azure.com, the default), the Azure GPT-Live API (*.openai.azure.com), or the OpenAI Realtime API (api.openai.com). When Claude makes a permission request during a call, a one-line summary of it (the tool's name and the Bash command, file path or MCP tool name) is spoken, so it goes to that service too. Nothing goes anywhere else, and nothing is sent when no call is running.
  • Fetches: the tagged release from GitHub, on first use, through uv.

Your conversation and privacy

  • What is read: at Call, the voice process reads this session's transcript once, on your machine, only to learn where the session stands (whether Claude is working, whether a message is waiting). None of that earlier history is sent. After that it follows only what is written in this session during the call, and this session's terminal pane, to notice permission prompts.
  • What is sent: Claude's reply text, anything you type during the call, your speech, and the one-line permission summaries above. Tool output and files are not forwarded.
  • Where and on whose account: only to the voice service you configured, with your own key and under your own account with that provider. Its retention is set by your agreement with that provider.
  • What we collect: nothing. There is no server of ours, no analytics and no telemetry.
  • What stays on your machine: the voice process's call files (the ledger and status files described below) and the Mod's permission.json (the last permission summary, which can be a full command), in a directory only you can open. They are not deleted automatically; delete ~/.local/state/bettercallgpt to remove them.
  • When it stops: at Hang up or /bettercallgpt:off; with the Mod enabled, also at /clear or when the session closes.

What the Mod reads

  • The environment variables HOME, XDG_STATE_HOME and VOICE_LISTEN_STATE_DIR, to find the state directory: ~/.local/state/bettercallgpt unless one of the last two is set.
  • status.json in <state directory>/<session id>/, every 2 seconds (twice a second during a call). During a call that file holds the last 60 characters you said that are not sent yet (the voice process masks credentials before writing it), which the call row shows.
  • This session's id, to name that directory.
  • During a call, each permission request's tool name and input (the Bash command, file path or MCP tool name), to write the one-line summary below.
  • Whether bettercallgpt exists at the three install paths above, and the first one's --help output; and the end of the voice process's error output, to show why a call failed to start.
  • Nothing else: no transcript and no other file.
  • Prompts: only while a Steer waits during a live call is each prompt Claude takes checked for the call's voice tag, so the row knows your spoken message arrived. With no call, or no Steer waiting, the prompt hook returns at once without reading the prompt. Nothing from a prompt is stored or sent.
  • Its own symbol choice (/call-icons), from the plugin's store.

The voice process reads your key from ~/.config/bettercallgpt/.env (you fill it yourself; setup never asks for it), and this session's own transcript and terminal pane, to relay results and to notice permission prompts.

The permission hook: what it decides and when

  • When: on every permission request Claude Code makes (classic.PermissionRequest), only while a call is live in this session. With no call it does nothing.
  • What it decides: nothing. It returns the request unchanged (next(e)), so the outcome is whatever your permission settings and your own hooks decide. It never allows, denies or rewords a request, and never changes what a dialog shows. Approvals stay on your keyboard; a spoken "yes" never approves anything.
  • What it does instead: writes the one file below, so the voice can say what Claude is asking for. That can include a request another hook or Claude Code then decides without asking you; sandbox network prompts are not covered.

The one file the Mod writes

  • Path: <state directory>/<session id>/permission.json, that is ~/.local/state/bettercallgpt/<session id>/permission.json by default.
  • Content: the time, the tool's name, a one-line summary and the call's instance id.
  • Who reads it: the voice process of this call, to speak it once. No other tool runs or obeys it.
  • The voice process writes its own files in that directory (a conversation ledger and status files); it is per-user and only you can open it (0700). They stay on your machine.

Off switch

"disableAllHooks": true in your settings turns the Mod off (with all your hooks), or disable the plugin in /plugin. The three commands keep working without it.

Where it works

Claude Code on macOS: the CLI in any terminal, and the Code tab of the Claude desktop app. It needs a Mac microphone, so it does nothing in Claude chat, Cowork, or Claude Code on the web.

Why the key stays in a file

The voice service key lives in ~/.config/bettercallgpt/.env rather than in plugin settings so that it never enters a prompt, a command line or the model's context; only the local voice process reads it.

"GPT" names the voice model the call runs on. This project is not affiliated with OpenAI, Microsoft or Anthropic.

Full guide, security notes and source: https://github.com/insta-fusion/bettercallgpt

Source 2 files
hooks/register.tsx 641 lines
1// Better Call GPT's hooks module: the call console.
2//
3// - ui.render AbovePrompt: one band. No call: [ Call ]. On a call: what the voice heard and has
4//   not handed over, how many spoken messages wait in Claude's queue, and [ Steer ] [ Hang up ].
5// - Call: starts the voice process as this session's child ($.process.spawn), on the operator's
6//   own press. No model turn runs and no permission prompt is involved: the press is the
7//   consent to open the microphone and the paid voice connection.
8// - Hang up: the voice process's own `stop` (goodbye, falling tone, device released).
9// - Steer: "take what I said now". The voice process is asked to hand over what it heard; and
10//   when a spoken message waits behind Claude's running turn, that turn is ended so the message
11//   is read next. Nothing is ever sent twice.
12// - /call, /hangup, /steer do the same as the buttons.
13// - classic.PermissionRequest: while on a call, write permission.json so the voice can say
14//   Claude is asking for a permission. Observed only: the hook returns what next(e) returns.
15//   Approvals stay on the keyboard.
16//
17// It reads status.json (written by the voice process) and writes only permission.json, both in
18// <state root>/<session id>/, the directory the voice process created (0700).
19import { atom, read, update } from 'claude-code'
20import type { EngineInterface, Register } from 'claude-code'
21
22import type { CallView } from '../types'
23
24const APP = 'bettercallgpt'
25// The release this plugin starts when no `bettercallgpt` is installed on PATH.
26const RELEASE = 'git+https://github.com/insta-fusion/bettercallgpt@v0.2.2'
27const TICK_MS = 500
28// With no call, status.json is read every IDLE_TICKS ticks (a call started with
29// /bettercallgpt:on shows up within two seconds).
30const IDLE_TICKS = 4
31// A Hang up the voice process has not answered after this long ends the child directly.
32const HANGUP_BOUND_MS = 8000
33// An installed command that does not answer `--help` in this long is passed over.
34const PROBE_BOUND_MS = 5000
35// Longer than this after flattening, no summary is written at all (the tool's name still is):
36// a cut command could split a credential the voice process would then fail to mask.
37const SUMMARY_MAX = 2000
38// The voice process refreshes `at` in status.json every 10 s while the call runs; older than
39// this, the status is one a killed process left behind. A little ahead is clock skew.
40const STALE_AFTER_S = 30
41const AHEAD_S = 5
42// The session ids the launcher accepts (bettercallgpt/cli.py SESSION_ID): a name, never a path.
43const SESSION_ID = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/
44const FILE_TOOLS = new Set(['Read', 'Edit', 'MultiEdit', 'Write', 'NotebookEdit'])
45// A spoken message as it arrives in the session: its text ends with the voice tag.
46const VOICE_TAG = /⟨v#[^⟩]*⟩\s*$/
47
48// The band's colors are the terminal's own named colors, so they follow the person's theme:
49// green is live and "call", red is "hang up" and failure, yellow is waiting, cyan is the queue.
50const LIVE = 'green'
51const WARN = 'yellow'
52const QUEUE = 'cyan'
53const END = 'red'
54const INK = 'black'
55// Below this many columns the words heard and not sent get a row of their own.
56const NARROW = 80
57// The engine draws the band's own collapse control (`[-]`) over its right end: each row of
58// controls stops this many columns short of it.
59const COLLAPSE_COLUMNS = 4
60
61// The symbols on the controls, chosen with /call-icons and kept in this plugin's store.
62// `keys` (the default) and `nerd` draw each symbol as a small colored key before its button:
63// green to call, red to hang up, as on a phone. `keys` uses characters every font has; `nerd`
64// needs a Nerd Font and has a real hung-up handset and a steering wheel. `emoji` puts emoji in
65// the labels; `none` is words only.
66export const ICON_SETS = {
67  // Steer keeps the wheel emoji in its label: no plain character reads as a steering wheel.
68  // Mute and Unmute carry their symbol in the label, as Steer does; `muted` heads the pill.
69  keys: { call: '☎', steer: '🛞 ', hangup: '☎', live: '● ', mute: '🔇 ', unmute: '🎙 ', muted: '○ ' },
70  nerd: {
71    call: '\uf095',
72    steer: '\u{f04d4}',
73    hangup: '\u{f03fa}',
74    live: '\u{f036c} ',
75    mute: '\u{f036d} ',
76    unmute: '\u{f036c} ',
77    muted: '\u{f036d} ',
78  },
79  emoji: { call: '📞 ', steer: '🛞 ', hangup: '📴 ', live: '🎙 ', mute: '🔇 ', unmute: '🎙 ', muted: '🔇 ' },
80  none: { call: '', steer: '', hangup: '', live: '● ', mute: '', unmute: '', muted: '○ ' },
81} as const
82export type IconSet = keyof typeof ICON_SETS
83const ICONS_KEY = 'icons'
84
85export const IDLE: CallView = { phase: 'idle', unsent: '', queued: 0, working: false, note: '', muted: false }
86
87const call = atom({ plugin: 'bettercallgpt', key: 'call' } as const, IDLE)
88
89type Child = AsyncGenerator<unknown, unknown, unknown>
90type Status = Record<string, unknown>
91type LiveCall = { dir: string; instance: string; status: Status }
92
93// This module's own memory. A reload starts it over, and a reload also ends the child.
94let child: Child | undefined
95let command: string | undefined // an installed bettercallgpt that fits, once probed
96let probed = false
97let mainTurn = ''
98let steerWaits = false
99let isStarting = false
100let steerShown = ''
101let icons: IconSet = 'keys'
102let ticks = 0
103let isPolling = false
104
105function set($: EngineInterface, patch: Partial<CallView>) {
106  return update($, call, view => ({ ...view, ...patch }))
107}
108
109/** Where the voice process keeps its state. The order mirrors bettercallgpt/cli.py
110 * user_state_dir + apply_defaults, which main() applies before daemon.main in the same process. */
111async function stateRoot($: EngineInterface): Promise<string | undefined> {
112  const absolute = (path: string | undefined) =>
113    path?.startsWith('/') ? path.replace(/\/+$/, '') : undefined
114  const explicit = absolute(await $.env.get('VOICE_LISTEN_STATE_DIR'))
115  if (explicit !== undefined) return explicit
116  const xdg = absolute(await $.env.get('XDG_STATE_HOME'))
117  if (xdg !== undefined) return `${xdg}/${APP}`
118  const home = absolute(await $.env.get('HOME'))
119  return home === undefined ? undefined : `${home}/.local/state/${APP}`
120}
121
122/** The rule of `bettercallgpt statusline` with a fresh heartbeat in place of its pid probe:
123 * running, relay qualified, not ended (an empty `ended` object is "not ended", as in Python),
124 * and a finite `at` (epoch seconds) between AHEAD_S ahead and STALE_AFTER_S behind now. */
125export function isLive(status: unknown, nowSeconds: number): boolean {
126  if (typeof status !== 'object' || status === null) return false
127  const { phase, relay, ended, at } = status as Status
128  const hasEnded =
129    typeof ended === 'object' && ended !== null ? Object.keys(ended).length > 0 : Boolean(ended)
130  const age = typeof at === 'number' && Number.isFinite(at) ? nowSeconds - at : NaN
131  const isFresh = age >= -AHEAD_S && age <= STALE_AFTER_S
132  return phase === 'running' && relay === 'qualified' && !hasEnded && isFresh
133}
134
135/** This session's live call (its state directory, the voice process's instance id and its
136 * status), or undefined. Rejects when status.json cannot be read or parsed. */
137async function liveCall($: EngineInterface, sessionId: string): Promise<LiveCall | undefined> {
138  if (!SESSION_ID.test(sessionId)) return undefined
139  const root = await stateRoot($)
140  if (root === undefined) return undefined
141  const dir = `${root}/${sessionId}`
142  const statusPath = `${dir}/status.json`
143  if (!(await $.fs.exists(statusPath))) return undefined
144  const status: unknown = JSON.parse(await $.fs.read(statusPath))
145  if (!isLive(status, (await $.clock.now()) / 1000)) return undefined
146  const { instance } = status as Status
147  return { dir, instance: typeof instance === 'string' ? instance : '', status: status as Status }
148}
149
150/** One line naming what the request is about: the Bash command, the file, or the MCP tool;
151 * empty when that line is longer than SUMMARY_MAX (never a partial command). */
152export function summarize(tool: string, input: unknown): string {
153  const fields = typeof input === 'object' && input !== null ? (input as Record<string, unknown>) : {}
154  const text = (value: unknown) => (typeof value === 'string' ? value : '')
155  let summary = ''
156  if (tool === 'Bash') summary = text(fields.command)
157  else if (FILE_TOOLS.has(tool)) summary = text(fields.file_path) || text(fields.notebook_path)
158  else if (tool.startsWith('mcp__')) summary = tool
159  const line = summary.replace(/\s+/g, ' ').trim()
160  return line.length <= SUMMARY_MAX ? line : ''
161}
162
163/** What status.json says the band should show. */
164export function liveFields(status: Status): Pick<CallView, 'unsent' | 'queued' | 'muted'> {
165  const unsent = status.unsent
166  const preview =
167    typeof unsent === 'object' && unsent !== null ? (unsent as Status).preview : undefined
168  const queued = Array.isArray(status.queued) ? status.queued.length : 0
169  // Muted only on the voice process's word: the band never says muted while the mic is heard.
170  return { unsent: typeof preview === 'string' ? preview : '', queued, muted: status.muted === true }
171}
172
173/** The last line of what a failed start wrote, as one short note. */
174export function failure(stderr: string, code: unknown): string {
175  const lines = stderr.split('\n').map(line => line.trim()).filter(line => line !== '')
176  const last = (lines.pop() ?? '').replace(/^voice:\s*/, '')
177  if (last.includes('bind_no_transcript')) return 'send Claude one message first, then call again'
178  if (last.includes('missing ')) return `${last.split(' — ')[0]} — add your key, see the README`
179  if (last === '') return `the voice process ended (exit ${String(code)})`
180  return last.length <= 160 ? last : `${last.slice(0, 159)}…`
181}
182
183/** Where `uv tool install` and Homebrew put an installed `bettercallgpt`. Checked as files, in
184 * this order; no shell and no PATH search is run to find the command. */
185const INSTALLED_AT = ['.local/bin/bettercallgpt', '/opt/homebrew/bin/bettercallgpt', '/usr/local/bin/bettercallgpt']
186
187/** An installed `bettercallgpt` that knows the console's commands (a checkout installed for
188 * development), or undefined: then the pinned release runs through `uvx`. */
189async function installed($: EngineInterface): Promise<string | undefined> {
190  if (probed) return command
191  probed = true
192  const home = await $.env.get('HOME')
193  for (const at of INSTALLED_AT) {
194    const path = at.startsWith('/') ? at : `${home ?? ''}/${at}`
195    if (!path.startsWith('/') || !(await $.fs.exists(path).catch(() => false))) continue
196    // One program, by name, with one fixed argument: an installed command from before the call
197    // console knows neither `--mod` nor `steer`, and is passed over for the release.
198    const fits = await $.process
199      .run([path, '--help'], { timeoutMs: PROBE_BOUND_MS })
200      .then(result => result.exitCode === 0 && result.stdout.includes('--mod'), () => false)
201    if (fits) command = path
202    break
203  }
204  return command
205}
206
207/** Read the child's output until it ends; then the call is over, whatever ended it. */
208async function follow($: EngineInterface, stream: Child) {
209  let stderr = ''
210  let code: unknown
211  try {
212    for (;;) {
213      const piece = await stream.next()
214      if (piece.done) {
215        code = (piece.value as { code?: unknown } | undefined)?.code
216        break
217      }
218      const { stream: pipe, text } = piece.value as { stream: string; text: string }
219      if (pipe === 'stderr') stderr = (stderr + text).slice(-4000)
220    }
221  } catch (error) {
222    stderr = String(error)
223  }
224  if (child !== stream) return // a newer call owns the band
225  child = undefined
226  steerWaits = false
227  try {
228    const { phase } = await read($, call)
229    const note = phase === 'starting' ? failure(stderr, code) : ''
230    await set($, { ...IDLE, working: mainTurn !== '', note })
231  } catch {
232    // The module was unloaded while the child was ending: there is no band left to update.
233  }
234}
235
236async function startCall($: EngineInterface): Promise<string> {
237  // Two presses in a row: the flag is taken before anything is awaited, so one call starts.
238  if (isStarting || child !== undefined) return 'a call is already on'
239  isStarting = true
240  try {
241    const view = await read($, call)
242    if (view.phase !== 'idle') return 'a call is already on'
243    const sessionId = await $.session.id()
244    if (!SESSION_ID.test(sessionId)) return 'this session has no usable id'
245    const nonce = `mod-${(await $.clock.now()).toString(36)}-${Math.random().toString(36).slice(2, 10)}`
246    // The whole command, as text: the installed command, or the pinned release through uvx.
247    // `sessionId` and `nonce` are the only values; nothing else is read from the environment.
248    const bin = await installed($)
249    const argv =
250      bin !== undefined
251        ? [bin, '--session', sessionId, '--nonce', nonce, '--mod', 'start']
252        : ['uvx', '--from', RELEASE, 'bettercallgpt', '--session', sessionId, '--nonce', nonce, '--mod', 'start']
253    const stream = $.process.spawn({ argv, env: { NONCE: nonce } }) as unknown as Child
254    child = stream
255    await set($, { ...IDLE, phase: 'starting', working: mainTurn !== '', note: '' })
256    void follow($, stream)
257    return 'calling'
258  } finally {
259    isStarting = false
260  }
261}
262
263async function hangUp($: EngineInterface): Promise<string> {
264  const view = await read($, call)
265  if (view.phase === 'idle') return 'no call to hang up'
266  const sessionId = await $.session.id()
267  await set($, { phase: 'ending', note: '' })
268  steerWaits = false
269  const ending = child
270  if (ending !== undefined) {
271    // The voice process says goodbye and exits by itself; one that does not is ended here.
272    // Armed before the stop is sent: a stop that hangs must not leave the call running.
273    $.clock.after(HANGUP_BOUND_MS, () => {
274      if (child === ending) void ending.return(undefined)
275    })
276  }
277  // The whole command, as text, like Call's: the installed command or the pinned release.
278  const bin = await installed($)
279  const argv =
280    bin !== undefined
281      ? [bin, '--session', sessionId, 'stop']
282      : ['uvx', '--from', RELEASE, 'bettercallgpt', '--session', sessionId, 'stop']
283  await $.process.run(argv).catch(() => undefined)
284  return 'hanging up'
285}
286
287/** End Claude's running turn when a Steer is waiting and a spoken message sits behind it.
288 * The status is read again right here: a message Claude took in the meantime (it is no longer
289 * queued) must not cost the turn that is now working on it. */
290async function bringForward($: EngineInterface) {
291  if (!steerWaits) return
292  const turnId = mainTurn
293  if (turnId === '') {
294    steerWaits = false // idle: a message starts its own turn
295    return
296  }
297  const sessionId = await $.session.id()
298  const live = await liveCall($, sessionId).catch(() => undefined)
299  if (live === undefined || liveFields(live.status).queued === 0) return
300  if (!steerWaits || turnId !== mainTurn) return // answered while reading
301  steerWaits = false
302  try {
303    await $.turn.abort({ turnId })
304    $.ui.toast('Steer: Claude takes your message now')
305  } catch {
306    // That turn ended by itself in the meantime: the message is read next anyway.
307  }
308}
309
310async function chooseIcons($: EngineInterface, wanted: string): Promise<string> {
311  const name = wanted.trim()
312  if (!Object.hasOwn(ICON_SETS, name)) return `icons: ${icons} (choose keys, nerd, emoji or none)`
313  icons = name as IconSet
314  await $.store.set(ICONS_KEY, icons)
315  await update($, call, view => ({ ...view })) // draw the band again
316  return `icons: ${icons}`
317}
318
319/** What the voice process answered to the last Steer, as the band's note. */
320export function steerNote(result: unknown): string {
321  if (typeof result !== 'string' || result === '') return ''
322  if (result === 'sent') return ''
323  if (result === 'nothing_unsent') return ''
324  if (result === 'uncertain') return 'steer: not confirmed (it is not sent again)'
325  return `steer did not send (${result.slice(0, 60)})`
326}
327
328async function steer($: EngineInterface): Promise<string> {
329  const view = await read($, call)
330  if (view.phase !== 'live') return 'no call to steer'
331  const sessionId = await $.session.id()
332  // A Steer waits only for the turn it was pressed in (turn.complete clears it).
333  steerWaits = mainTurn !== ''
334  // The voice process sends what it heard and has not handed over, itself, as a message that
335  // ends Claude's running turn. Its answer comes back in status.json (`steer`).
336  const bin = await installed($)
337  const argv =
338    bin !== undefined
339      ? [bin, '--session', sessionId, 'steer']
340      : ['uvx', '--from', RELEASE, 'bettercallgpt', '--session', sessionId, 'steer']
341  await $.process.run(argv).catch(() => undefined)
342  await bringForward($)
343  return 'steering'
344}
345
346async function toggleMute($: EngineInterface): Promise<string> {
347  const view = await read($, call)
348  if (view.phase !== 'live') return 'no call to mute'
349  const sessionId = await $.session.id()
350  // The band changes when the voice process says so in status.json, not on the press.
351  const bin = await installed($)
352  let argv: string[]
353  if (view.muted) {
354    argv =
355      bin !== undefined
356        ? [bin, '--session', sessionId, 'unmute']
357        : ['uvx', '--from', RELEASE, 'bettercallgpt', '--session', sessionId, 'unmute']
358  } else {
359    argv =
360      bin !== undefined
361        ? [bin, '--session', sessionId, 'mute']
362        : ['uvx', '--from', RELEASE, 'bettercallgpt', '--session', sessionId, 'mute']
363  }
364  await $.process.run(argv).catch(() => undefined)
365  return view.muted ? 'unmuting' : 'muting'
366}
367
368async function poll($: EngineInterface, isFirst = false) {
369  if (isPolling) return // one read at a time: a slow one never lands after a newer one
370  isPolling = true
371  try {
372    const view = await read($, call)
373    ticks += 1
374    if (!isFirst && view.phase === 'idle' && ticks % IDLE_TICKS !== 0) return
375    const sessionId = await $.session.id()
376    // A status that cannot be read or parsed is no call.
377    const live = await liveCall($, sessionId).catch(() => undefined)
378    // A /clear while reading moved to another session: this answer is for the old one.
379    if (sessionId !== (await $.session.id())) return
380    if (live === undefined) {
381      // No child and no live status: the call (one started by /bettercallgpt:on) is over.
382      if (child === undefined) steerWaits = false // a Steer belongs to a live call
383      if (child === undefined && view.phase !== 'idle') await set($, { ...IDLE, working: view.working })
384      return
385    }
386    const fields = liveFields(live.status)
387    // The voice process's answer to a Steer, shown once per press.
388    const answer = (live.status.steer ?? {}) as Status
389    const answerId = typeof answer.id === 'string' ? answer.id : ''
390    let note: string | undefined
391    if (answerId !== '' && answerId !== steerShown) {
392      // What happened is said once, in passing; only a failure stays in the band.
393      note = steerNote(answer.result)
394      if (answer.result === 'sent') $.ui.toast('Steer: sent what you said')
395      if (answer.result === 'nothing_unsent' && fields.queued === 0) $.ui.toast('Nothing to steer')
396      steerShown = answerId
397    }
398    const isSame =
399      view.phase === 'live' &&
400      view.unsent === fields.unsent &&
401      view.queued === fields.queued &&
402      view.muted === fields.muted
403    if (!isSame || note !== undefined) {
404      // The phase is decided on the view as it is when written: a Hang up pressed while this
405      // read was out stays "ending".
406      await update($, call, (now): CallView => ({
407        ...now,
408        ...fields,
409        phase: now.phase === 'ending' ? 'ending' : 'live',
410        note: note ?? now.note,
411      }))
412    }
413    await bringForward($)
414  } catch {
415    // The session itself could not be asked: try again on the next tick.
416  } finally {
417    isPolling = false
418  }
419}
420
421export const register: Register = on => {
422  on('classic.PermissionRequest', async ($, e, next) => {
423    try {
424      const live = await liveCall($, e.session_id)
425      if (live !== undefined) {
426        const at = (await $.clock.now()) / 1000
427        const summary = summarize(e.tool_name, e.tool_input)
428        // `instance` ties the notice to this call: a later call in the same session ignores it.
429        const event = { at, tool: e.tool_name, summary, instance: live.instance }
430        // The one file this module writes: <state root>/<session id>/permission.json, read by the
431        // voice process of this call only. The state root is ~/.local/state/bettercallgpt unless
432        // VOICE_LISTEN_STATE_DIR or XDG_STATE_HOME is set (see stateRoot).
433        await $.fs.write(`${live.dir}/permission.json`, JSON.stringify(event))
434      }
435    } catch {
436      // Observing failed. The prompt is the same either way.
437    }
438    return next(e)
439  })
440
441  on('session.start', async ($, e, next) => {
442    const kept = await $.store.get(ICONS_KEY).catch(() => undefined)
443    if (typeof kept === 'string' && Object.hasOwn(ICON_SETS, kept)) icons = kept as IconSet
444    try {
445      await $.command.register({
446        name: 'call-icons',
447        description: 'Symbols on the call controls: keys, nerd (Nerd Font), emoji or none',
448        argumentHint: '[keys|nerd|emoji|none]',
449        immediate: true,
450      })
451      await $.command.register({
452        name: 'call',
453        description: 'Start a voice call in this session',
454        immediate: true,
455      })
456      await $.command.register({ name: 'hangup', description: 'End the voice call', immediate: true })
457      await $.command.register({
458        name: 'mute',
459        description: 'Mute or unmute your microphone on the voice call',
460        immediate: true,
461      })
462      await $.command.register({
463        name: 'steer',
464        description: 'Have Claude take what you just said now',
465        immediate: true,
466      })
467    } catch {
468      // A host that takes no commands still gets the band and its buttons.
469    }
470    await poll($, true)
471    $.clock.every(TICK_MS, () => void poll($))
472    return next(e)
473  })
474
475  on('session.end', async ($, e, next) => {
476    // The call belongs to the session that started it: a /clear or an exit ends it.
477    await hangUp($) // also a call /bettercallgpt:on started; with no call it does nothing
478    return next(e)
479  })
480
481  on('command.run', { command: 'call' }, async $ => ({ text: await startCall($) }))
482  on('command.run', { command: 'call-icons' }, async ($, e) => ({ text: await chooseIcons($, e.args) }))
483  on('command.run', { command: 'hangup' }, async $ => ({ text: await hangUp($) }))
484  on('command.run', { command: 'steer' }, async $ => ({ text: await steer($) }))
485  on('command.run', { command: 'mute' }, async $ => ({ text: await toggleMute($) }))
486
487  on('turn.start', async ($, e, next) => {
488    mainTurn = e.turnId
489    await set($, { working: true })
490    return next(e)
491  })
492
493  on('turn.complete', async ($, e, next) => {
494    // A subagent's turn completes here too; only the main turn's own end clears it.
495    if (e.agentId === undefined && e.turnId === mainTurn) {
496      mainTurn = ''
497      steerWaits = false // a Steer is about the turn it was pressed in
498      await set($, { working: false })
499    }
500    return next(e)
501  })
502
503  on('prompt.submit', async ($, e, next) => {
504    // Only while a Steer waits on a live call: otherwise the prompt passes untouched and unread.
505    if (!steerWaits) return next(e)
506    // A spoken message was just read by Claude: the Steer that was waiting for it is done.
507    if (e.origin.kind === 'peer' && VOICE_TAG.test(e.text)) steerWaits = false
508    return next(e)
509  })
510
511  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
512    const isDrawn = e.surface === 'terminal' || e.surface === 'desktop'
513    if (!isDrawn || e.props.hasSurvey) return next(e)
514    const view = await read($, call)
515    // The band is shared: keep what the mods after this one draw (mods_interface.md, "Pick
516    // where to draw"), and add one line under it.
517    const below = await next(e)
518    const { Box, Button, Text } = $.ui.resolve(e)
519    const icon = ICON_SETS[icons]
520    // Emoji carry their own colors, inside the label. The other symbols are one-color
521    // characters: each is drawn before its button as a key in the control's color.
522    const isKeyed = icons === 'keys' || icons === 'nerd'
523    const inLabel = (symbol: string) => (isKeyed ? '' : symbol)
524    const tint = (symbol: string, color: string) =>
525      isKeyed ? (
526        <Box flexShrink={0}>
527          <Text backgroundColor={color} color={INK} bold>
528            {` ${symbol} `}
529          </Text>
530        </Box>
531      ) : null
532    // A state pill keeps its width: when the row is tight the words beside it are cut, never it.
533    const pill = (words: string, color: string) => (
534      <Box flexShrink={0}>
535        <Text backgroundColor={color} color={INK} bold>
536          {words}
537        </Text>
538      </Box>
539    )
540    const isNarrow = e.props.bodyColumns < NARROW
541    if (view.phase === 'idle') {
542      const hasFailed = view.note !== ''
543      return (
544        <Box flexDirection="column">
545          {below}
546          <Box gap={1} paddingRight={COLLAPSE_COLUMNS}>
547            {hasFailed ? pill(' ✕ CALL FAILED ', END) : null}
548            {tint(icon.call, LIVE)}
549            <Button
550              key="call"
551              label={`${inLabel(icon.call)}${hasFailed ? 'Call again' : 'Call'}`}
552              hotkey="c"
553              variant="primary"
554              onPress={() => void startCall($)}
555            />
556            {hasFailed ? (
557              <Text wrap="truncate-end">{view.note}</Text>
558            ) : (
559              <Text wrap="truncate-end">
560                <Text bold>Better Call GPT</Text>
561                <Text dimColor>{isNarrow ? '' : ' · talk to this session by voice'}</Text>
562              </Text>
563            )}
564          </Box>
565        </Box>
566      )
567    }
568    if (view.phase === 'starting' || view.phase === 'ending') {
569      return (
570        <Box flexDirection="column">
571          {below}
572          <Box gap={1} paddingRight={COLLAPSE_COLUMNS}>
573            {pill(view.phase === 'starting' ? ' ◌ CONNECTING ' : ' ◌ HANGING UP ', WARN)}
574            <Text dimColor wrap="truncate-end">
575              {view.phase === 'starting' ? 'opening the microphone and the voice…' : 'saying goodbye…'}
576            </Text>
577            {view.phase === 'starting' ? tint(icon.hangup, END) : null}
578            {view.phase === 'starting' ? (
579              <Button key="hangup" label={`${inLabel(icon.hangup)}Hang up`} hotkey="h" onPress={() => void hangUp($)} />
580            ) : null}
581          </Box>
582        </Box>
583      )
584    }
585    const canSteer = view.unsent !== '' || view.queued > 0
586    const quote =
587      view.unsent === '' ? null : (
588        <Text color={WARN} italic wrap="truncate-start">
589          «{view.unsent}» not sent
590        </Text>
591      )
592    return (
593      <Box flexDirection="column">
594        {below}
595        <Box gap={1} paddingRight={COLLAPSE_COLUMNS}>
596          {view.muted ? pill(` ${icon.muted}MUTED `, WARN) : pill(` ${icon.live}LIVE `, LIVE)}
597          <Box flexGrow={1} flexShrink={1} gap={1} overflow="hidden">
598            {canSteer ? null : (
599              <Text dimColor>{view.note !== '' ? view.note : view.muted ? 'muted · Claude does not hear you' : 'listening'}</Text>
600            )}
601            {isNarrow ? null : quote}
602            {view.queued === 0 ? null : (
603              <Text color={QUEUE} bold>
604                {view.queued} queued
605              </Text>
606            )}
607            {canSteer && view.note !== '' ? <Text dimColor>{view.note}</Text> : null}
608          </Box>
609          <Box flexShrink={0} gap={1}>
610            <Button
611              key="mute"
612              label={view.muted ? `${icon.unmute}Unmute` : `${icon.mute}Mute`}
613              hotkey="m"
614              variant={view.muted ? 'primary' : 'secondary'}
615              onPress={() => void toggleMute($)}
616            />
617            {icons === 'nerd' ? tint(icon.steer, QUEUE) : null}
618            <Button
619              key="steer"
620              label={`${icons === 'nerd' ? '' : icon.steer}Steer`}
621              hotkey="s"
622              variant={canSteer ? 'primary' : 'secondary'}
623              dimColor={!canSteer}
624              onPress={() => void steer($)}
625            />
626            {tint(icon.hangup, END)}
627            <Button
628              key="hangup"
629              label={`${inLabel(icon.hangup)}Hang up`}
630              hotkey="h"
631              variant="secondary"
632              onPress={() => void hangUp($)}
633            />
634          </Box>
635        </Box>
636        {isNarrow ? quote : null}
637      </Box>
638    )
639  })
640}
641
types/index.d.ts 26 lines
1// The values this plugin keeps in $.state for the session.
2// `call`: what the band above the prompt draws.
3//   phase   idle (no call), starting (the voice process is coming up), live, ending
4//   unsent  the tail of what the voice heard and has not handed to Claude yet ('' when none)
5//   queued  how many spoken messages wait in Claude's queue behind the running turn
6//   working whether Claude is in a turn right now
7//   note    one line about the last thing that happened (a failed start, a Steer's result)
8//   muted   the voice process says the microphone is muted (the provider hears silence)
9
10export type CallPhase = 'idle' | 'starting' | 'live' | 'ending'
11
12export type CallView = {
13  phase: CallPhase
14  unsent: string
15  queued: number
16  working: boolean
17  note: string
18  muted: boolean
19}
20
21declare module 'claude-code' {
22  interface PluginState {
23    bettercallgpt: { call: CallView }
24  }
25}
26