@thegitai/cli 1.7.0 → 1.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -29,7 +29,8 @@ This package is the CLI. The same agent is also available as a
29
29
  - **Beyond source code** - reads PDF, Word and Excel files, edits Word
30
30
  documents, looks at screenshots, generates images, and searches and fetches
31
31
  the web.
32
- - **Keyboard shortcuts** - open `/keybindings` to edit the keys for mode switching, image paste, background jobs, and notifications. Saved changes apply in the current session.
32
+ - **Voice dictation** - run `/voice`, then hold Space and talk. Your words appear in the prompt as you speak, and nothing is sent until you press Enter.
33
+ - **Keyboard shortcuts** - open `/keybindings` to edit the keys for mode switching, image paste, background jobs, notifications, and dictation. Saved changes apply in the current session.
33
34
  - **Steering and recovery** - send corrections while it works, switch between
34
35
  Default, Bypass all permissions and Plan modes, and undo an edit, a turn or a
35
36
  file, or restore a checkpoint.
@@ -0,0 +1,96 @@
1
+ import { createTraceContext, failureCode, failureDetails, failureMessage, normalizeServerUrl, readJsonResponse, ServerApiError, } from './http.js';
2
+ const TRANSCRIBE_TIMEOUT_MS = 90_000;
3
+ export async function transcribeRecording({ config, audio, hints = [], signal, fetchImpl = globalThis.fetch, }) {
4
+ const trace = createTraceContext();
5
+ const timeout = AbortSignal.timeout(TRANSCRIBE_TIMEOUT_MS);
6
+ const response = await fetchImpl(`${normalizeServerUrl(config.serverUrl)}/v1/voice/transcribe`, {
7
+ method: 'POST',
8
+ headers: {
9
+ authorization: `Bearer ${config.token}`,
10
+ ...trace.headers,
11
+ 'content-type': 'audio/wav',
12
+ ...(hints.length ? { 'x-thegitai-voice-hints': encodeURIComponent(JSON.stringify(hints)) } : {}),
13
+ },
14
+ body: new Uint8Array(audio),
15
+ signal: signal ? AbortSignal.any([signal, timeout]) : timeout,
16
+ });
17
+ const data = await readJsonResponse(response);
18
+ if (!response.ok) {
19
+ throw new ServerApiError(failureMessage(data, response.status), response.status, trace.traceId, failureCode(data), failureDetails(data));
20
+ }
21
+ return typeof data?.text === 'string' ? data.text : '';
22
+ }
23
+ export function openVoiceStream({ config, onText, WebSocketImpl = globalThis.WebSocket, }) {
24
+ if (typeof WebSocketImpl !== 'function')
25
+ return null;
26
+ let socket;
27
+ try {
28
+ socket = new WebSocketImpl(`${normalizeServerUrl(config.serverUrl).replace(/^http/i, 'ws')}/v1/voice/stream`);
29
+ }
30
+ catch {
31
+ return null;
32
+ }
33
+ socket.binaryType = 'arraybuffer';
34
+ const queued = [];
35
+ let open = false;
36
+ let ready = false;
37
+ let closed = false;
38
+ socket.addEventListener('open', () => {
39
+ if (closed) {
40
+ socket.close();
41
+ return;
42
+ }
43
+ open = true;
44
+ socket.send(JSON.stringify({ type: 'start', token: config.token }));
45
+ });
46
+ socket.addEventListener('message', (event) => {
47
+ if (closed || typeof event.data !== 'string')
48
+ return;
49
+ let message = null;
50
+ try {
51
+ message = JSON.parse(event.data);
52
+ }
53
+ catch {
54
+ return;
55
+ }
56
+ if (message?.type === 'ready' && !ready) {
57
+ ready = true;
58
+ for (const chunk of queued.splice(0))
59
+ socket.send(chunk);
60
+ }
61
+ else if (message?.type === 'text' && typeof message.text === 'string') {
62
+ onText(message.text);
63
+ }
64
+ });
65
+ socket.addEventListener('error', () => {
66
+ closed = true;
67
+ });
68
+ socket.addEventListener('close', () => {
69
+ closed = true;
70
+ });
71
+ return {
72
+ send(chunk) {
73
+ if (closed)
74
+ return;
75
+ const copy = new Uint8Array(chunk);
76
+ if (ready)
77
+ socket.send(copy);
78
+ else
79
+ queued.push(copy);
80
+ },
81
+ close() {
82
+ if (closed)
83
+ return;
84
+ closed = true;
85
+ if (open) {
86
+ try {
87
+ socket.send(JSON.stringify({ type: 'stop' }));
88
+ }
89
+ catch {
90
+ return;
91
+ }
92
+ }
93
+ socket.close();
94
+ },
95
+ };
96
+ }
@@ -109,6 +109,12 @@ function helpMarkdown(shortcuts = {}) {
109
109
  ' back for editing and **Esc**/**Ctrl+C** discards it; both unlock the',
110
110
  ` composer for the next message. **${key('pasteImage')}** pastes a screenshot onto the`,
111
111
  ' queued message, and it is delivered into the running turn with the text.',
112
+ `- **/voice** turns voice dictation on, and it stays on between sessions. Then hold **${key('pushToTalk')}**`,
113
+ ' to talk and let go to stop: your words land in the composer at the cursor and',
114
+ ' are never sent on their own. **Esc** or **Ctrl+C** cancels a recording.',
115
+ ' `/voice tap` switches to tap to start and tap again to stop, `/voice hold`',
116
+ ' switches back, and `/voice off` turns it off. The microphone is used only',
117
+ ' while you record.',
112
118
  `- **${key('notifications')}** turns desktop notifications on or off. One is raised when a turn`,
113
119
  ' ends and when a permission prompt or a question is waiting for you, but',
114
120
  ' only while the terminal is in the background - if you are looking at the',
@@ -165,8 +171,9 @@ function helpMarkdown(shortcuts = {}) {
165
171
  '- `/jobs output <id>` - print one job\'s full captured output',
166
172
  '- `/jobs kill <id>` - stop one background job',
167
173
  `- \`/notify\` - turn desktop notifications on or off (same as ${key('notifications')})`,
174
+ '- `/voice` - turn voice dictation on or off; `/voice hold` or `/voice tap` picks how you record',
168
175
  '- `/keybindings` - change the keys for the agent mode, image paste, background',
169
- ' jobs and notifications',
176
+ ' jobs, notifications and dictation',
170
177
  '- `/new` - start a new conversation; this session remains saved',
171
178
  '- `/logout` - sign out and quit',
172
179
  '- `/exit` - quit the session',
@@ -5,6 +5,7 @@ export function defaultShortcuts(platform = process.platform) {
5
5
  pasteImage: platform === 'win32' ? ['Alt+V', 'Ctrl+V'] : ['Ctrl+V'],
6
6
  backgroundJobs: ['Ctrl+B'],
7
7
  notifications: ['Ctrl+G'],
8
+ pushToTalk: ['Space'],
8
9
  };
9
10
  }
10
11
  export function shortcutLabel(id, overrides = {}, platform = process.platform) {
@@ -13,9 +14,11 @@ export function shortcutLabel(id, overrides = {}, platform = process.platform) {
13
14
  export function matchesShortcut(id, key, overrides = {}) {
14
15
  const chord = key.tab
15
16
  ? key.shift && !key.ctrl && !key.meta ? 'Shift+Tab' : ''
16
- : key.ctrl !== key.meta && !key.shift && /^[a-z]$/i.test(key.input)
17
- ? `${key.ctrl ? 'Ctrl' : 'Alt'}+${key.input.toUpperCase()}`
18
- : '';
17
+ : key.input === ' ' && !key.ctrl && !key.meta
18
+ ? 'Space'
19
+ : key.ctrl !== key.meta && !key.shift && /^[a-z]$/i.test(key.input)
20
+ ? `${key.ctrl ? 'Ctrl' : 'Alt'}+${key.input.toUpperCase()}`
21
+ : '';
19
22
  return chord !== '' && (overrides[id] ?? defaultShortcuts()[id]).includes(chord);
20
23
  }
21
24
  export function parseShortcutFile(value, platform = process.platform) {
@@ -44,6 +47,8 @@ export function parseShortcutFile(value, platform = process.platform) {
44
47
  }))];
45
48
  if (overrides[id].length === 0)
46
49
  throw new Error(`Give ${id} a key, like "Ctrl+T".`);
50
+ if (id === 'pushToTalk' && overrides[id].length > 1)
51
+ throw new Error('Give pushToTalk one key, like "Space" or "Ctrl+K".');
47
52
  }
48
53
  const owners = new Map();
49
54
  for (const [id, keys] of Object.entries({ ...defaults, ...overrides })) {
@@ -3,6 +3,7 @@ import path from 'node:path';
3
3
  import { getClientStateDir } from './client-state.js';
4
4
  export const DEFAULT_PREFERENCES = {
5
5
  notifications: true,
6
+ voice: { enabled: false, mode: 'hold', hints: 0 },
6
7
  };
7
8
  export function getPreferencesPath(env = process.env) {
8
9
  return path.join(getClientStateDir(env), 'prefs.json');
@@ -10,15 +11,20 @@ export function getPreferencesPath(env = process.env) {
10
11
  export function readPreferences(env = process.env) {
11
12
  const filePath = getPreferencesPath(env);
12
13
  if (!existsSync(filePath))
13
- return { ...DEFAULT_PREFERENCES };
14
+ return { ...DEFAULT_PREFERENCES, voice: { ...DEFAULT_PREFERENCES.voice } };
14
15
  try {
15
16
  const parsed = JSON.parse(readFileSync(filePath, 'utf8'));
16
17
  return {
17
18
  notifications: parsed.notifications === false ? false : DEFAULT_PREFERENCES.notifications,
19
+ voice: {
20
+ enabled: parsed.voice?.enabled === true,
21
+ mode: parsed.voice?.mode === 'tap' ? 'tap' : 'hold',
22
+ hints: Number.isInteger(parsed.voice?.hints) ? Math.max(0, parsed.voice.hints) : 0,
23
+ },
18
24
  };
19
25
  }
20
26
  catch {
21
- return { ...DEFAULT_PREFERENCES };
27
+ return { ...DEFAULT_PREFERENCES, voice: { ...DEFAULT_PREFERENCES.voice } };
22
28
  }
23
29
  }
24
30
  export function writePreferences(preferences, env = process.env) {
@@ -9,6 +9,8 @@ import { AGENT_MODE_LOCKED_STATUS, approvalScrollLimit, buildTuiFrame, modelPick
9
9
  import { createAttentionController, INITIAL_TERMINAL_FOCUS, } from './tui/attention.js';
10
10
  import { backendFor, createNotificationQueue, } from './tui/desktop-notification.js';
11
11
  import { readPreferences, writePreferences } from '../preferences.js';
12
+ import { createVoiceDictation, isRemoteSession, voiceErrorMessage, voiceKeyLabel, } from './tui/voice-dictation.js';
13
+ import { openVoiceStream, transcribeRecording } from '../api/voice.js';
12
14
  import { createTerminalTitleController } from './tui/terminal-title.js';
13
15
  import { captureTerminalWrites, releaseTerminalWrites, } from './tui/terminal-writes.js';
14
16
  import { getInputCommandToken, getSlashCommandSuggestions, isSkillSlashCommand, setSkillSlashCommands, SLASH_COMMANDS, slashCommandMatchesToken, } from './slash-commands.js';
@@ -25,20 +27,20 @@ import { formatTurnRecoveryStatus } from '../api/turn-recovery.js';
25
27
  import { createJobWaitTracker } from '../job-follow-up.js';
26
28
  import { getJobBufferedOutput, getJobOutputPreview, hasRunningBackgroundJobs, killAllBackgroundJobs, killBackgroundJob, listBackgroundJobs, setBackgroundJobSession, setBackgroundJobUpdateHook, } from '../background-jobs.js';
27
29
  import { clearTodos, listTodos, setTodoSession } from '../todo-list.js';
28
- import { setScratchSession } from '../scratch-dir.js';
30
+ import { ensureSessionScratchDir, setScratchSession } from '../scratch-dir.js';
29
31
  import { setImageStoreSession } from '../core/session-image-store.js';
30
32
  import { runMemoryCommand } from '../memory/command.js';
31
33
  import { cancelActiveCommand } from '../executor.js';
32
34
  import { isTurnFailureMarker } from '../turn-failure-marker.js';
33
35
  import { clearCliAuthConfig, logoutFromServer, } from '../api/auth.js';
34
- import { authenticationErrorMessage, isAuthenticationError, } from '../api/http.js';
36
+ import { authenticationErrorMessage, isAuthenticationError, ServerApiError, } from '../api/http.js';
35
37
  import { buildRefusalNotice } from '../quota-notice.js';
36
38
  import { createUsageNoticeTracker } from '../usage-notice.js';
37
39
  import { createUserInputPromptState, formatUserInputTranscript, } from './tui/user-input.js';
38
40
  import { setCommandOutputHook, withTuiMode } from '../runtime-mode.js';
39
41
  import { collectBackgroundJobUiKillMutations, collectBackgroundJobUiOutputMutations, } from '../tool-executor.js';
40
42
  import { startNewConversation, } from '../session.js';
41
- import { applySessionSnapshot, listSessionMetadata, loadSessionSnapshot, saveSessionState, sessionHasUserMessage, } from '../session-store.js';
43
+ import { applySessionSnapshot, listSessionMetadata, loadSessionSnapshot, readGitBranch, saveSessionState, sessionHasUserMessage, } from '../session-store.js';
42
44
  import { truncate } from '../utils.js';
43
45
  import { TOOL_MAP } from '../tools/index.js';
44
46
  import { countStep, EMPTY_TURN_STEPS, turnStepFields, } from './turn-steps.js';
@@ -1200,6 +1202,10 @@ function createInitialShellState(session, serverModels, debugUi, serverUrl) {
1200
1202
  input: '',
1201
1203
  maxToolSteps: session.maxToolSteps,
1202
1204
  notificationsEnabled: readPreferences(session.env).notifications,
1205
+ voice: null,
1206
+ voiceEnabled: readPreferences(session.env).voice.enabled && !isRemoteSession(session.env),
1207
+ voiceHint: false,
1208
+ voiceMode: readPreferences(session.env).voice.mode,
1203
1209
  terminalFocused: INITIAL_TERMINAL_FOCUS,
1204
1210
  jobsPickerExpandedId: null,
1205
1211
  jobsPickerIndex: 0,
@@ -2398,6 +2404,122 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
2398
2404
  }
2399
2405
  showTransientStatus(enabled ? 'Notifications on' : 'Notifications off');
2400
2406
  };
2407
+ const voiceHints = () => [basename(session.rootDir), readGitBranch(session.rootDir) ?? '']
2408
+ .map((hint) => hint.trim())
2409
+ .filter((hint, index, all) => hint && all.indexOf(hint) === index);
2410
+ const transcribeDictation = async (audio, signal) => {
2411
+ try {
2412
+ return await transcribeRecording({ config: authConfig, audio, hints: voiceHints(), signal });
2413
+ }
2414
+ catch (error) {
2415
+ if (signal.aborted)
2416
+ throw error;
2417
+ const notice = buildRefusalNotice(error);
2418
+ if (notice)
2419
+ throw new Error(notice.body);
2420
+ if (isAuthenticationError(error))
2421
+ throw new Error(authenticationErrorMessage(error));
2422
+ if (error instanceof ServerApiError && error.status < 500 && error.message)
2423
+ throw new Error(error.message);
2424
+ throw new Error("Couldn't transcribe that, try again.");
2425
+ }
2426
+ };
2427
+ const voiceDictation = createVoiceDictation({
2428
+ getState: () => store.getState(),
2429
+ update: (change) => store.update(change),
2430
+ canDictate: (state) => !state.approvalPrompt &&
2431
+ !state.sudoPrompt &&
2432
+ !state.userInputPrompt &&
2433
+ !state.modelPickerOpen &&
2434
+ !state.resumePickerOpen &&
2435
+ !state.skillsPickerOpen &&
2436
+ !state.jobsPickerOpen &&
2437
+ !state.shortcutsOpen &&
2438
+ !state.exiting &&
2439
+ state.exitConfirmUntil == null &&
2440
+ !(state.busy && state.queuedMessage),
2441
+ start: (file, maxSeconds) => bridge.voiceStart(file, maxSeconds),
2442
+ stop: () => bridge.voiceStop(),
2443
+ cancel: () => bridge.voiceCancel(),
2444
+ probe: () => bridge.voiceProbe(),
2445
+ scratchDir: () => ensureSessionScratchDir(),
2446
+ transcribe: transcribeDictation,
2447
+ openStream: (onText) => openVoiceStream({ config: authConfig, onText }),
2448
+ report: (body) => appendStaticEntry({ kind: 'error', title: 'Voice', body }),
2449
+ notice: (body) => appendStaticEntry({ kind: 'system', title: 'Voice', body }),
2450
+ status: (text) => showTransientStatus(text),
2451
+ });
2452
+ const countVoiceHint = () => {
2453
+ const prefs = readPreferences(session.env);
2454
+ if (!prefs.voice.enabled || prefs.voice.hints >= 3 || isRemoteSession(session.env))
2455
+ return;
2456
+ store.update((current) => ({ ...current, voiceHint: true }));
2457
+ try {
2458
+ writePreferences({ ...prefs, voice: { ...prefs.voice, hints: prefs.voice.hints + 1 } }, session.env);
2459
+ }
2460
+ catch {
2461
+ }
2462
+ };
2463
+ countVoiceHint();
2464
+ const voiceOnMessage = (mode) => {
2465
+ const key = voiceKeyLabel(store.getState().shortcuts);
2466
+ const how = mode === 'hold'
2467
+ ? `Hold ${key} to talk and let go to stop.`
2468
+ : key === 'Space'
2469
+ ? 'Tap Space in an empty message box to start, and tap it again to stop.'
2470
+ : `Tap ${key} to start, and tap it again to stop.`;
2471
+ return `Dictation on (${mode}). ${how} Your words go into the message box, and nothing is sent until you press Enter. Esc cancels a recording.`;
2472
+ };
2473
+ const handleVoiceCommand = async (arg) => {
2474
+ const state = store.getState();
2475
+ const choice = arg.toLowerCase();
2476
+ let next;
2477
+ if (!choice)
2478
+ next = { enabled: !state.voiceEnabled, mode: state.voiceMode };
2479
+ else if (choice === 'on')
2480
+ next = { enabled: true, mode: state.voiceMode };
2481
+ else if (choice === 'off')
2482
+ next = { enabled: false, mode: state.voiceMode };
2483
+ else if (choice === 'hold' || choice === 'tap')
2484
+ next = { enabled: true, mode: choice };
2485
+ else {
2486
+ appendStaticEntry({ kind: 'error', title: 'Voice', body: 'Use /voice, /voice hold, /voice tap or /voice off.' });
2487
+ return;
2488
+ }
2489
+ if (next.enabled && !state.voiceEnabled) {
2490
+ if (isRemoteSession(session.env)) {
2491
+ appendStaticEntry({
2492
+ kind: 'error',
2493
+ title: 'Voice',
2494
+ body: "Voice dictation needs a microphone on this computer, so it doesn't work over SSH.",
2495
+ });
2496
+ return;
2497
+ }
2498
+ const probe = await voiceDictation.probe();
2499
+ if (!probe.ok) {
2500
+ appendStaticEntry({ kind: 'error', title: 'Voice', body: voiceErrorMessage(probe.code, probe.detail) });
2501
+ return;
2502
+ }
2503
+ }
2504
+ else if (!next.enabled) {
2505
+ voiceDictation.cancel();
2506
+ }
2507
+ const wasEnabled = state.voiceEnabled;
2508
+ store.update((current) => ({ ...current, voiceEnabled: next.enabled, voiceMode: next.mode }));
2509
+ try {
2510
+ const prefs = readPreferences(session.env);
2511
+ writePreferences({ ...prefs, voice: { ...prefs.voice, ...next } }, session.env);
2512
+ }
2513
+ catch {
2514
+ }
2515
+ if (next.enabled && !wasEnabled && !store.getState().voiceHint)
2516
+ countVoiceHint();
2517
+ appendStaticEntry({
2518
+ kind: 'system',
2519
+ title: 'Voice',
2520
+ body: next.enabled ? voiceOnMessage(next.mode) : 'Dictation off.',
2521
+ });
2522
+ };
2401
2523
  const openJobsPicker = () => {
2402
2524
  if (store.getState().jobsPickerOpen)
2403
2525
  return;
@@ -2926,6 +3048,16 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
2926
3048
  toggleNotifications();
2927
3049
  return;
2928
3050
  }
3051
+ if (input === '/voice' || input.startsWith('/voice ')) {
3052
+ store.update((current) => ({
3053
+ ...current,
3054
+ cursor: 0,
3055
+ input: '',
3056
+ pastedChunks: [],
3057
+ }));
3058
+ await handleVoiceCommand(input.slice('/voice'.length).trim());
3059
+ return;
3060
+ }
2929
3061
  appendTurnAwareEntry({
2930
3062
  body: "Slash commands can't be queued while a turn is running. " +
2931
3063
  'Use /jobs for background jobs or /notify to toggle notifications.',
@@ -3063,6 +3195,10 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
3063
3195
  toggleNotifications();
3064
3196
  return;
3065
3197
  }
3198
+ if (input === '/voice' || input.startsWith('/voice ')) {
3199
+ await handleVoiceCommand(input.slice('/voice'.length).trim());
3200
+ return;
3201
+ }
3066
3202
  if (input === '/jobs' || input.startsWith('/jobs ')) {
3067
3203
  const jobsArgs = input.slice('/jobs'.length).trim();
3068
3204
  if (!jobsArgs) {
@@ -3712,6 +3848,7 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
3712
3848
  onSelectModel: handleInlineModelSelection,
3713
3849
  onOpenJobsPicker: openJobsPicker,
3714
3850
  onToggleNotifications: toggleNotifications,
3851
+ onVoiceKey: (key) => voiceDictation.handleKey(key),
3715
3852
  onJobsPickerOutput: handleJobsPickerOutput,
3716
3853
  onJobsPickerKill: handleJobsPickerKill,
3717
3854
  onSudoPasswordInput: handleSudoPasswordInput,
@@ -3770,6 +3907,10 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
3770
3907
  void remountTui();
3771
3908
  return;
3772
3909
  }
3910
+ if (message.kind.startsWith('voice')) {
3911
+ voiceDictation.handleEvent(message);
3912
+ return;
3913
+ }
3773
3914
  handleShellKeyEvent(store, shellInputHandlers, message);
3774
3915
  renderCurrentFrame();
3775
3916
  }
@@ -3782,6 +3923,7 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
3782
3923
  await done;
3783
3924
  }
3784
3925
  finally {
3926
+ voiceDictation.dispose();
3785
3927
  stopWatchingKeys();
3786
3928
  clearInterval(spinnerTimer);
3787
3929
  clearInterval(clockTimer);
@@ -15,6 +15,7 @@ export const SLASH_COMMANDS = [
15
15
  command: '/notify',
16
16
  description: 'Toggle desktop notifications when a turn ends',
17
17
  },
18
+ { command: '/voice', description: 'Voice dictation on or off; /voice hold or /voice tap picks how' },
18
19
  { command: '/keybindings', description: 'Change your keyboard shortcuts' },
19
20
  { command: '/report', description: 'Report a bug or request a feature privately on the TheGitAI website' },
20
21
  { command: '/about', description: 'Show version and platform info' },
@@ -71,6 +71,44 @@ function normalizeChildMessage(raw) {
71
71
  offset: Number(raw.offset ?? 0),
72
72
  };
73
73
  }
74
+ if (raw.kind === 'voiceStarted') {
75
+ return {
76
+ op: 'event',
77
+ kind: 'voiceStarted',
78
+ recorder: String(raw.recorder ?? ''),
79
+ ...(typeof raw.path === 'string' ? { path: raw.path } : {}),
80
+ };
81
+ }
82
+ if (raw.kind === 'voiceLevel') {
83
+ return {
84
+ op: 'event',
85
+ kind: 'voiceLevel',
86
+ level: Number(raw.level ?? 0),
87
+ ...(typeof raw.audio === 'string' ? { audio: raw.audio } : {}),
88
+ ...(typeof raw.path === 'string' ? { path: raw.path } : {}),
89
+ };
90
+ }
91
+ if (raw.kind === 'voiceDone') {
92
+ return { op: 'event', kind: 'voiceDone', path: String(raw.path ?? ''), seconds: Number(raw.seconds ?? 0) };
93
+ }
94
+ if (raw.kind === 'voiceError') {
95
+ return {
96
+ op: 'event',
97
+ kind: 'voiceError',
98
+ code: String(raw.code ?? 'failed'),
99
+ detail: String(raw.detail ?? ''),
100
+ ...(typeof raw.path === 'string' ? { path: raw.path } : {}),
101
+ };
102
+ }
103
+ if (raw.kind === 'voiceProbe') {
104
+ return {
105
+ op: 'event',
106
+ kind: 'voiceProbe',
107
+ ok: raw.ok === true,
108
+ code: String(raw.code ?? ''),
109
+ detail: String(raw.detail ?? ''),
110
+ };
111
+ }
74
112
  if (raw.kind !== 'key') {
75
113
  return null;
76
114
  }
@@ -191,6 +229,18 @@ export function createRatatuiBridge() {
191
229
  setTitle(title) {
192
230
  writeParent({ op: 'title', text: title });
193
231
  },
232
+ voiceStart(path, maxSeconds) {
233
+ writeParent({ op: 'voiceStart', path, maxSeconds });
234
+ },
235
+ voiceStop() {
236
+ writeParent({ op: 'voiceStop' });
237
+ },
238
+ voiceCancel() {
239
+ writeParent({ op: 'voiceCancel' });
240
+ },
241
+ voiceProbe() {
242
+ writeParent({ op: 'voiceProbe' });
243
+ },
194
244
  async close() {
195
245
  if (closed)
196
246
  return;
@@ -1,4 +1,5 @@
1
1
  import { shortcutLabel } from '../../keyboard-shortcuts.js';
2
+ import { joinDictatedText, VOICE_GRADIENT, voiceClock, voiceHint, voiceLevelGlyph, voiceSpinner, voiceWave, } from './voice-dictation.js';
2
3
  import { modelPickerWindow, modelPickerScrollLabel } from './model-picker-window.js';
3
4
  import { fitModelLabel } from './model-label.js';
4
5
  import { projectModelEffort } from '../../project-model-preferences.js';
@@ -50,6 +51,28 @@ export function footerNotificationHint(status) {
50
51
  return '';
51
52
  }
52
53
  const OVERLAY_PANEL_MAX_WIDTH = 86;
54
+ function voiceTitle(state, at = Date.now()) {
55
+ const activity = state.voice;
56
+ if (!activity)
57
+ return null;
58
+ const muted = { color: mutedColor() };
59
+ if (activity.phase === 'warmup')
60
+ return line(span(' keep holding… ', muted));
61
+ if (activity.phase === 'starting')
62
+ return line(span(' ○ starting… ', muted));
63
+ if (activity.phase === 'transcribing') {
64
+ return line(span(` ${voiceSpinner(activity.tick)} `, { color: 'cyan' }), span('transcribing… ', muted));
65
+ }
66
+ const pulse = Math.floor(at / 500) % 2 === 0;
67
+ return line(span(' ● ', { color: 'red', bold: pulse, dim: !pulse }), span(`${voiceClock(activity, at)} `, muted), ...voiceWave(activity.levels).map((glyph, index) => span(glyph, { color: VOICE_GRADIENT[index] })), span(' listening… ', muted));
68
+ }
69
+ function voiceCursor(state, at = Date.now()) {
70
+ const activity = state.voice;
71
+ if (!activity || activity.phase !== 'recording')
72
+ return null;
73
+ const level = activity.levels[activity.levels.length - 1] ?? 0;
74
+ return span(voiceLevelGlyph(level), { color: VOICE_GRADIENT[Math.floor(at / 150) % VOICE_GRADIENT.length] });
75
+ }
53
76
  const USER_INPUT_PANEL_MAX_WIDTH = 120;
54
77
  const OVERLAY_PANEL_MARGIN_LINES = 2;
55
78
  const OVERLAY_PANEL_MARGIN_MIN_ROWS = 30;
@@ -73,13 +96,13 @@ function composerMarkerMask(text) {
73
96
  }
74
97
  return mask;
75
98
  }
76
- function composerRowSpans(text, mask, cursorCol) {
99
+ function composerRowSpans(text, mask, cursorCol, dim = [], cursorSpan = null) {
77
100
  const spans = [];
78
- const push = (value, marker, cursor) => {
101
+ const push = (value, marker, cursor, faded = false) => {
79
102
  if (!value)
80
103
  return;
81
104
  spans.push(span(value, {
82
- ...(marker ? { color: 'cyan' } : {}),
105
+ ...(marker ? { color: 'cyan' } : faded ? { color: mutedColor() } : {}),
83
106
  ...(cursor ? { inverse: true } : {}),
84
107
  }));
85
108
  };
@@ -87,10 +110,11 @@ function composerRowSpans(text, mask, cursorCol) {
87
110
  const flushTo = (end) => {
88
111
  while (cut < end) {
89
112
  const marker = mask[cut] ?? false;
113
+ const faded = dim[cut] ?? false;
90
114
  let runEnd = cut + 1;
91
- while (runEnd < end && (mask[runEnd] ?? false) === marker)
115
+ while (runEnd < end && (mask[runEnd] ?? false) === marker && (dim[runEnd] ?? false) === faded)
92
116
  runEnd += 1;
93
- push(text.slice(cut, runEnd), marker, false);
117
+ push(text.slice(cut, runEnd), marker, false, faded);
94
118
  cut = runEnd;
95
119
  }
96
120
  };
@@ -99,15 +123,18 @@ function composerRowSpans(text, mask, cursorCol) {
99
123
  return spans;
100
124
  }
101
125
  flushTo(Math.min(cursorCol, text.length));
102
- push(text[cursorCol] ?? ' ', mask[cursorCol] ?? false, true);
126
+ if (cursorSpan && cursorCol >= text.length)
127
+ spans.push(cursorSpan);
128
+ else
129
+ push(text[cursorCol] ?? ' ', mask[cursorCol] ?? false, true);
103
130
  cut = Math.min(cursorCol + 1, text.length);
104
131
  flushTo(text.length);
105
132
  return spans;
106
133
  }
107
- function buildComposerInputLines(input, cursor, promptLabel, placeholder, width) {
134
+ function buildComposerInputLines(input, cursor, promptLabel, placeholder, width, { dim, cursorSpan = null } = {}) {
108
135
  if (!input) {
109
136
  return [
110
- line(span(promptLabel, { color: 'cyan' }), span(' ', { inverse: true }), span(placeholder, { color: mutedColor() })),
137
+ line(span(promptLabel, { color: 'cyan' }), cursorSpan ?? span(' ', { inverse: true }), span(placeholder, { color: mutedColor() })),
111
138
  ];
112
139
  }
113
140
  const labelWidth = promptLabel.length;
@@ -121,6 +148,11 @@ function buildComposerInputLines(input, cursor, promptLabel, placeholder, width)
121
148
  consumed += row.length;
122
149
  }
123
150
  const mask = composerMarkerMask(rows.join(''));
151
+ const rowsOffset = (offset) => offset - (input.slice(0, offset).match(/[\r\n]/g)?.length ?? 0);
152
+ const [dimStart, dimEnd] = dim ? [rowsOffset(dim[0]), rowsOffset(dim[1])] : [0, 0];
153
+ const dimMask = dim
154
+ ? Array.from({ length: consumed }, (_, index) => index >= dimStart && index < dimEnd)
155
+ : [];
124
156
  return rows
125
157
  .slice(firstRow, firstRow + COMPOSER_INPUT_MAX_ROWS)
126
158
  .map((text, index) => {
@@ -129,7 +161,7 @@ function buildComposerInputLines(input, cursor, promptLabel, placeholder, width)
129
161
  const label = index === 0
130
162
  ? span(promptLabel, { color: 'cyan' })
131
163
  : span(' '.repeat(labelWidth));
132
- return line(label, ...composerRowSpans(text, mask.slice(rowStart, rowStart + text.length), absoluteRow === cursorRow ? cursorCol : null));
164
+ return line(label, ...composerRowSpans(text, mask.slice(rowStart, rowStart + text.length), absoluteRow === cursorRow ? cursorCol : null, dimMask.slice(rowStart, rowStart + text.length), cursorSpan));
133
165
  });
134
166
  }
135
167
  function getEntryColor(kind) {
@@ -1649,14 +1681,27 @@ export function buildTuiFrame(state, cols, rows, spinnerFrame, elapsedSeconds, n
1649
1681
  }
1650
1682
  else {
1651
1683
  const promptLabel = composerPromptLabel(state);
1652
- const placeholder = state.busy
1684
+ const basePlaceholder = state.busy
1653
1685
  ? 'Type to queue the next message'
1654
1686
  : 'Type a request or /help';
1655
- composerLines.push(...buildComposerInputLines(state.input, state.cursor, promptLabel, placeholder, contentWidth));
1687
+ const placeholder = state.voice
1688
+ ? ''
1689
+ : state.voiceEnabled && state.voiceHint
1690
+ ? `${basePlaceholder} · ${voiceHint({ shortcuts: state.shortcuts ?? {}, voiceMode: state.voiceMode ?? 'hold' })}`
1691
+ : basePlaceholder;
1692
+ const interim = state.voice?.interim.trim() ?? '';
1693
+ const shown = interim
1694
+ ? joinDictatedText(state.input, state.cursor, interim)
1695
+ : { input: state.input, cursor: state.cursor };
1696
+ composerLines.push(...buildComposerInputLines(shown.input, shown.cursor, promptLabel, placeholder, contentWidth, {
1697
+ ...(interim ? { dim: [shown.cursor - interim.length, shown.cursor] } : {}),
1698
+ cursorSpan: voiceCursor(state),
1699
+ }));
1656
1700
  }
1657
1701
  sections.push({
1658
1702
  kind: 'composer',
1659
1703
  lines: [...composerLines, plainLine(''), ...composerFooterLines(state, contentWidth)],
1704
+ ...(voiceTitle(state) ? { title: voiceTitle(state) } : {}),
1660
1705
  });
1661
1706
  }
1662
1707
  if (state.userInputPrompt) {
@@ -228,6 +228,8 @@ export function handleShellKeyEvent(store, handlers, event) {
228
228
  if (event.kind !== 'key')
229
229
  return;
230
230
  const key = event;
231
+ if (handlers.onVoiceKey?.(key))
232
+ return;
231
233
  const state = store.getState();
232
234
  const commandPaletteActive = shouldShowCommandPalette(state);
233
235
  const commandSuggestions = commandPaletteActive
@@ -6,6 +6,7 @@ export function shortcutsPanelAvailable(state) {
6
6
  !state.sudoPrompt &&
7
7
  !state.userInputPrompt &&
8
8
  !state.queuedMessage &&
9
+ !state.voice &&
9
10
  !state.input &&
10
11
  (state.cursor ?? 0) === 0 &&
11
12
  (state.pastedChunks?.length ?? 0) === 0 &&
@@ -29,6 +30,7 @@ export function buildShortcutGroups(platform = process.platform, shortcuts = {})
29
30
  { keys: 'Esc', description: 'Clear the composer' },
30
31
  { keys: 'Ctrl+C', description: 'Clear the composer, or quit when empty' },
31
32
  { keys: key('notifications'), description: 'Desktop notifications - toggle on or off' },
33
+ { keys: `Hold ${key('pushToTalk')}`, description: 'Dictate into the message, once /voice is on' },
32
34
  { keys: '/keybindings', description: 'Change these shortcuts' },
33
35
  ],
34
36
  },
@@ -0,0 +1,438 @@
1
+ import { existsSync, readFileSync, rmSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { matchesShortcut, shortcutLabel } from '../../keyboard-shortcuts.js';
5
+ export const VOICE_MAX_SECONDS = 120;
6
+ const REPEAT_GAP_MS = 150;
7
+ const RUN_RESET_MS = 1000;
8
+ const FIRST_RELEASE_MS = 750;
9
+ const MIN_RELEASE_MS = 260;
10
+ const TAP_DEBOUNCE_MS = 180;
11
+ const MIN_SECONDS = 0.4;
12
+ const SPEECH_LEVEL = 12;
13
+ const LOUD_LEVEL = 30;
14
+ const SILENCE_STOP_MS = 15_000;
15
+ const LEVEL_HISTORY = 8;
16
+ const PROBE_TIMEOUT_MS = 5000;
17
+ const UNHEARD_BEFORE_HINT = 3;
18
+ export function voiceKeyLabel(shortcuts = {}) {
19
+ return shortcutLabel('pushToTalk', shortcuts);
20
+ }
21
+ export function voiceHint(state) {
22
+ return `${state.voiceMode === 'tap' ? 'tap' : 'hold'} ${voiceKeyLabel(state.shortcuts).toLowerCase()} to speak`;
23
+ }
24
+ function isPlainSpace(key) {
25
+ return key.input === ' ' && !key.ctrl && !key.meta;
26
+ }
27
+ function isCancelKey(key) {
28
+ return key.escape || (key.ctrl && !key.meta && key.input.toLowerCase() === 'c');
29
+ }
30
+ export function joinDictatedText(input, cursor, text) {
31
+ const clean = text.trim();
32
+ if (!clean)
33
+ return { input, cursor };
34
+ const before = input.slice(0, cursor);
35
+ const after = input.slice(cursor);
36
+ const lead = before && !/\s$/.test(before) ? ' ' : '';
37
+ const trail = after && !/^\s/.test(after) ? ' ' : '';
38
+ const inserted = `${lead}${clean}${trail}`;
39
+ return { input: `${before}${inserted}${after}`, cursor: before.length + lead.length + clean.length };
40
+ }
41
+ export function createVoiceDictation(deps) {
42
+ const now = deps.now ?? (() => Date.now());
43
+ let run = null;
44
+ let lastPush = 0;
45
+ let pushes = 0;
46
+ let releaseAfter = FIRST_RELEASE_MS;
47
+ let started = false;
48
+ let stopRequested = false;
49
+ let maxLevel = 0;
50
+ let lastLoud = 0;
51
+ let file = null;
52
+ let timer = null;
53
+ let upload = null;
54
+ let probeWaiter = null;
55
+ let stream = null;
56
+ let spinner = null;
57
+ let warmupTimer = null;
58
+ let unheard = 0;
59
+ const heardNothing = () => {
60
+ unheard += 1;
61
+ if (unheard < UNHEARD_BEFORE_HINT)
62
+ return;
63
+ unheard = 0;
64
+ deps.notice(`Nothing was heard in the last ${UNHEARD_BEFORE_HINT} recordings. ${voiceErrorMessage('silent')}`);
65
+ };
66
+ const activityOf = (phase, mode, startedAt = null) => ({
67
+ phase,
68
+ mode,
69
+ startedAt,
70
+ levels: [],
71
+ interim: '',
72
+ tick: 0,
73
+ });
74
+ const setActivity = (activity) => deps.update((state) => ({ ...state, voice: activity }));
75
+ const patchActivity = (patch) => deps.update((state) => (state.voice ? { ...state, voice: { ...state.voice, ...patch } } : state));
76
+ const closeStream = () => {
77
+ stream?.close();
78
+ stream = null;
79
+ };
80
+ const removeFile = () => {
81
+ if (file)
82
+ rmSync(file, { force: true });
83
+ file = null;
84
+ };
85
+ const clearTimer = () => {
86
+ if (timer)
87
+ clearInterval(timer);
88
+ timer = null;
89
+ };
90
+ const endWarmup = () => {
91
+ if (warmupTimer)
92
+ clearTimeout(warmupTimer);
93
+ warmupTimer = null;
94
+ if (deps.getState().voice?.phase === 'warmup')
95
+ setActivity(null);
96
+ };
97
+ const reset = () => {
98
+ clearTimer();
99
+ closeStream();
100
+ if (spinner)
101
+ clearInterval(spinner);
102
+ spinner = null;
103
+ removeFile();
104
+ run = null;
105
+ started = false;
106
+ stopRequested = false;
107
+ setActivity(null);
108
+ };
109
+ const pushKey = (key, shortcuts) => matchesShortcut('pushToTalk', key, shortcuts);
110
+ const begin = (mode) => {
111
+ const at = now();
112
+ file = path.join(deps.scratchDir(), `voice-${randomUUID()}.wav`);
113
+ started = false;
114
+ stopRequested = false;
115
+ maxLevel = 0;
116
+ lastLoud = at;
117
+ lastPush = at;
118
+ pushes = 0;
119
+ if (warmupTimer)
120
+ clearTimeout(warmupTimer);
121
+ warmupTimer = null;
122
+ setActivity(activityOf('starting', mode));
123
+ closeStream();
124
+ stream = deps.openStream?.((text) => {
125
+ const phase = deps.getState().voice?.phase;
126
+ if (phase === 'starting' || phase === 'recording' || phase === 'transcribing')
127
+ patchActivity({ interim: text });
128
+ }) ?? null;
129
+ deps.start(file, VOICE_MAX_SECONDS);
130
+ clearTimer();
131
+ timer = setInterval(tick, 50);
132
+ };
133
+ const finish = () => {
134
+ if (stopRequested)
135
+ return;
136
+ stopRequested = true;
137
+ clearTimer();
138
+ if (!started) {
139
+ deps.cancel();
140
+ reset();
141
+ return;
142
+ }
143
+ closeStream();
144
+ deps.stop();
145
+ };
146
+ const tick = () => {
147
+ const state = deps.getState();
148
+ const activity = state.voice;
149
+ if (!activity || activity.phase === 'transcribing')
150
+ return;
151
+ if (!deps.canDictate(state)) {
152
+ finish();
153
+ return;
154
+ }
155
+ const at = now();
156
+ if (activity.mode === 'hold' && at - lastPush > releaseAfter) {
157
+ finish();
158
+ return;
159
+ }
160
+ if (activity.mode === 'tap' && started && at - lastLoud > SILENCE_STOP_MS) {
161
+ deps.status('Stopped after 15 seconds of silence');
162
+ finish();
163
+ }
164
+ };
165
+ const cancel = () => {
166
+ const activity = deps.getState().voice;
167
+ if (!activity)
168
+ return;
169
+ upload?.abort();
170
+ upload = null;
171
+ if (activity.phase !== 'transcribing')
172
+ deps.cancel();
173
+ reset();
174
+ };
175
+ const handleKey = (key) => {
176
+ const state = deps.getState();
177
+ const activity = state.voice;
178
+ const at = now();
179
+ if (activity && activity.phase !== 'warmup') {
180
+ if (!deps.canDictate(state)) {
181
+ if (activity.phase !== 'transcribing')
182
+ finish();
183
+ if (activity.mode !== 'hold' || !pushKey(key, state.shortcuts))
184
+ return false;
185
+ const held = at - lastPush < releaseAfter;
186
+ if (held)
187
+ lastPush = at;
188
+ return held;
189
+ }
190
+ if (isCancelKey(key)) {
191
+ cancel();
192
+ return true;
193
+ }
194
+ if (key.returnKey) {
195
+ if (activity.phase !== 'transcribing')
196
+ finish();
197
+ return true;
198
+ }
199
+ if (!pushKey(key, state.shortcuts))
200
+ return false;
201
+ if (activity.phase === 'transcribing')
202
+ return true;
203
+ if (activity.mode === 'hold') {
204
+ const gap = at - lastPush;
205
+ lastPush = at;
206
+ pushes += 1;
207
+ if (pushes > 1 || gap < REPEAT_GAP_MS) {
208
+ releaseAfter = Math.min(FIRST_RELEASE_MS, Math.max(MIN_RELEASE_MS, gap * 3));
209
+ }
210
+ return true;
211
+ }
212
+ const gap = at - lastPush;
213
+ lastPush = at;
214
+ if (gap > TAP_DEBOUNCE_MS)
215
+ finish();
216
+ return true;
217
+ }
218
+ if (!state.voiceEnabled || !pushKey(key, state.shortcuts) || !deps.canDictate(state)) {
219
+ endWarmup();
220
+ run = null;
221
+ return false;
222
+ }
223
+ const space = isPlainSpace(key);
224
+ if (state.voiceMode === 'tap') {
225
+ if (space && (state.input || state.cursor))
226
+ return false;
227
+ begin('tap');
228
+ return true;
229
+ }
230
+ if (!space) {
231
+ releaseAfter = FIRST_RELEASE_MS;
232
+ begin('hold');
233
+ return true;
234
+ }
235
+ if (!run || at - run.times[run.times.length - 1] > RUN_RESET_MS) {
236
+ endWarmup();
237
+ run = { times: [at], input: state.input, cursor: state.cursor };
238
+ return false;
239
+ }
240
+ run.times.push(at);
241
+ const gaps = run.times.slice(1).map((time, index) => time - run.times[index]);
242
+ const fast = gaps.slice(-2).filter((gap) => gap < REPEAT_GAP_MS).length;
243
+ if (fast < 2) {
244
+ if (fast === 1) {
245
+ setActivity(activityOf('warmup', 'hold'));
246
+ if (warmupTimer)
247
+ clearTimeout(warmupTimer);
248
+ warmupTimer = setTimeout(endWarmup, REPEAT_GAP_MS * 2);
249
+ }
250
+ else
251
+ endWarmup();
252
+ return false;
253
+ }
254
+ const snapshot = run;
255
+ run = null;
256
+ releaseAfter = Math.max(MIN_RELEASE_MS, gaps[gaps.length - 1] * 3);
257
+ deps.update((current) => ({ ...current, input: snapshot.input, cursor: snapshot.cursor }));
258
+ begin('hold');
259
+ return true;
260
+ };
261
+ const transcribe = async (recording, seconds) => {
262
+ if (seconds < MIN_SECONDS) {
263
+ reset();
264
+ return;
265
+ }
266
+ if (maxLevel < SPEECH_LEVEL) {
267
+ reset();
268
+ heardNothing();
269
+ return;
270
+ }
271
+ patchActivity({ phase: 'transcribing', levels: [] });
272
+ if (spinner)
273
+ clearInterval(spinner);
274
+ spinner = setInterval(() => patchActivity({ tick: (deps.getState().voice?.tick ?? 0) + 1 }), 120);
275
+ const controller = new AbortController();
276
+ upload = controller;
277
+ try {
278
+ const audio = readFileSync(recording);
279
+ removeFile();
280
+ const text = await deps.transcribe(audio, controller.signal);
281
+ if (controller.signal.aborted)
282
+ return;
283
+ upload = null;
284
+ reset();
285
+ if (!text.trim()) {
286
+ heardNothing();
287
+ return;
288
+ }
289
+ unheard = 0;
290
+ deps.update((state) => ({ ...state, ...joinDictatedText(state.input, state.cursor, text) }));
291
+ }
292
+ catch (error) {
293
+ if (controller.signal.aborted)
294
+ return;
295
+ upload = null;
296
+ reset();
297
+ deps.report(error.message || "Couldn't transcribe that, try again.");
298
+ }
299
+ };
300
+ const handleEvent = (event) => {
301
+ if (event.kind === 'voiceProbe') {
302
+ probeWaiter?.({ ok: event.ok, code: event.code, detail: event.detail });
303
+ probeWaiter = null;
304
+ return;
305
+ }
306
+ const activity = deps.getState().voice;
307
+ if (event.kind !== 'voiceDone' && event.path !== undefined && event.path !== file)
308
+ return;
309
+ if (event.kind === 'voiceStarted') {
310
+ if (!activity || activity.phase !== 'starting')
311
+ return;
312
+ started = true;
313
+ lastLoud = now();
314
+ patchActivity({ phase: 'recording', startedAt: now() });
315
+ return;
316
+ }
317
+ if (event.kind === 'voiceLevel') {
318
+ if (!activity || activity.phase !== 'recording')
319
+ return;
320
+ maxLevel = Math.max(maxLevel, event.level);
321
+ if (event.level >= LOUD_LEVEL)
322
+ lastLoud = now();
323
+ if (event.audio && stream)
324
+ stream.send(Buffer.from(event.audio, 'base64'));
325
+ patchActivity({ levels: [...activity.levels, event.level].slice(-LEVEL_HISTORY) });
326
+ return;
327
+ }
328
+ if (event.kind === 'voiceDone') {
329
+ if (!activity || activity.phase === 'transcribing' || event.path !== file) {
330
+ rmSync(event.path, { force: true });
331
+ return;
332
+ }
333
+ clearTimer();
334
+ closeStream();
335
+ if (!stopRequested && activity.startedAt && now() - activity.startedAt >= VOICE_MAX_SECONDS * 1000 - 500) {
336
+ deps.status('Stopped at the 2-minute limit');
337
+ }
338
+ void transcribe(event.path, event.seconds);
339
+ return;
340
+ }
341
+ if (event.kind === 'voiceError') {
342
+ if (!activity)
343
+ return;
344
+ const quiet = stopRequested && !started;
345
+ reset();
346
+ if (event.code === 'silent')
347
+ heardNothing();
348
+ else if (!quiet)
349
+ deps.report(voiceErrorMessage(event.code, event.detail));
350
+ }
351
+ };
352
+ const probe = () => new Promise((resolve) => {
353
+ probeWaiter?.({ ok: false, code: 'failed', detail: '' });
354
+ const timeout = setTimeout(() => {
355
+ if (probeWaiter === done)
356
+ probeWaiter = null;
357
+ resolve({ ok: true, code: '', detail: '' });
358
+ }, PROBE_TIMEOUT_MS);
359
+ const done = (result) => {
360
+ clearTimeout(timeout);
361
+ resolve(result);
362
+ };
363
+ probeWaiter = done;
364
+ deps.probe();
365
+ });
366
+ const dispose = () => {
367
+ upload?.abort();
368
+ upload = null;
369
+ closeStream();
370
+ if (spinner)
371
+ clearInterval(spinner);
372
+ if (warmupTimer)
373
+ clearTimeout(warmupTimer);
374
+ warmupTimer = null;
375
+ if (deps.getState().voice && deps.getState().voice?.phase !== 'transcribing')
376
+ deps.cancel();
377
+ clearTimer();
378
+ removeFile();
379
+ };
380
+ return { handleKey, handleEvent, cancel, probe, dispose };
381
+ }
382
+ function linuxInstallHint() {
383
+ const has = (program) => (process.env.PATH ?? '').split(':').some((entry) => entry && existsSync(path.join(entry, program)));
384
+ if (has('apt'))
385
+ return 'sudo apt install alsa-utils';
386
+ if (has('dnf'))
387
+ return 'sudo dnf install alsa-utils';
388
+ if (has('pacman'))
389
+ return 'sudo pacman -S alsa-utils';
390
+ if (has('zypper'))
391
+ return 'sudo zypper install alsa-utils';
392
+ if (has('apk'))
393
+ return 'sudo apk add alsa-utils';
394
+ return 'install alsa-utils, pulseaudio-utils or pipewire';
395
+ }
396
+ export function voiceErrorMessage(code, detail = '', platform = process.platform) {
397
+ if (code === 'noRecorder') {
398
+ return `Voice dictation needs an audio recorder (pw-record, parecord or arecord). Install one, then try again: ${linuxInstallHint()}`;
399
+ }
400
+ if (code === 'noMicrophone')
401
+ return 'No microphone found. Connect one or check your sound input settings, then try again.';
402
+ if (code === 'denied' || code === 'silent') {
403
+ if (platform === 'darwin') {
404
+ return code === 'denied'
405
+ ? 'Microphone access is off for your terminal. Open System Settings > Privacy & Security > Microphone, allow your terminal app, then restart it.'
406
+ : 'No sound from the microphone. If your terminal is not allowed yet, open System Settings > Privacy & Security > Microphone, allow it, then restart it.';
407
+ }
408
+ if (platform === 'win32') {
409
+ return code === 'denied'
410
+ ? 'Microphone access is blocked. Open Settings > Privacy & security > Microphone and turn on "Let desktop apps access your microphone".'
411
+ : 'No sound from the microphone. Check Settings > System > Sound > Input, and that desktop apps may use the microphone.';
412
+ }
413
+ return code === 'denied'
414
+ ? `Microphone access was denied${detail ? `: ${detail}` : '.'}`
415
+ : 'No sound from the microphone. Check your input device and its level in your sound settings.';
416
+ }
417
+ return `Couldn't start recording${detail ? `: ${detail}` : '.'}`;
418
+ }
419
+ export function isRemoteSession(env = process.env) {
420
+ return Boolean(env.SSH_CONNECTION || env.SSH_CLIENT || env.SSH_TTY);
421
+ }
422
+ export const VOICE_GRADIENT = [51, 45, 39, 33, 69, 105, 141, 177].map((index) => `ansi256(${index})`);
423
+ const LEVEL_GLYPHS = '▁▂▃▄▅▆▇█';
424
+ const SPINNER = '⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏';
425
+ export function voiceClock(activity, at = Date.now()) {
426
+ const elapsed = Math.max(0, Math.floor((at - (activity.startedAt ?? at)) / 1000));
427
+ return `${Math.floor(elapsed / 60)}:${String(elapsed % 60).padStart(2, '0')}`;
428
+ }
429
+ export function voiceLevelGlyph(level) {
430
+ return LEVEL_GLYPHS[Math.min(LEVEL_GLYPHS.length - 1, Math.max(0, Math.floor((level / 100) * LEVEL_GLYPHS.length)))];
431
+ }
432
+ export function voiceSpinner(tick) {
433
+ return SPINNER[tick % SPINNER.length];
434
+ }
435
+ export function voiceWave(levels) {
436
+ const recent = levels.slice(-LEVEL_HISTORY);
437
+ return [...Array(Math.max(0, LEVEL_HISTORY - recent.length)).fill(0), ...recent].map(voiceLevelGlyph);
438
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@thegitai/cli",
3
- "version": "1.7.0",
4
- "description": "TheGitAI is an AI coding agent. It reads and searches your repository, writes and edits files, runs your tests, verifies the change before handing it back, uses the apps on your computer, and remembers your corrections between sessions. Customize its keyboard shortcuts in your editor.",
3
+ "version": "1.8.0",
4
+ "description": "TheGitAI is an AI coding agent. It reads and searches your repository, writes and edits files, runs your tests, verifies the change before handing it back, uses the apps on your computer, and remembers your corrections between sessions. Talk to it with voice dictation, and customize its keyboard shortcuts in your editor.",
5
5
  "keywords": [
6
6
  "agentic-ai",
7
7
  "ai-coding-agent",
@@ -13,6 +13,8 @@
13
13
  "coding-assistant",
14
14
  "ai-memory",
15
15
  "keyboard-shortcuts",
16
+ "voice-dictation",
17
+ "speech-to-text",
16
18
  "computer-use",
17
19
  "code-assistant",
18
20
  "ai",
@@ -48,11 +50,11 @@
48
50
  "@lydell/node-pty-linux-x64": "1.1.0",
49
51
  "@lydell/node-pty-win32-arm64": "1.1.0",
50
52
  "@lydell/node-pty-win32-x64": "1.1.0",
51
- "@thegitai/tui-darwin-arm64": "1.7.0",
52
- "@thegitai/tui-darwin-x64": "1.7.0",
53
- "@thegitai/tui-linux-arm64": "1.7.0",
54
- "@thegitai/tui-linux-x64": "1.7.0",
55
- "@thegitai/tui-win32-x64": "1.7.0",
53
+ "@thegitai/tui-darwin-arm64": "1.8.0",
54
+ "@thegitai/tui-darwin-x64": "1.8.0",
55
+ "@thegitai/tui-linux-arm64": "1.8.0",
56
+ "@thegitai/tui-linux-x64": "1.8.0",
57
+ "@thegitai/tui-win32-x64": "1.8.0",
56
58
  "@vscode/ripgrep": "1.18.0"
57
59
  },
58
60
  "repository": {