@senad-d/micme 0.1.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.
@@ -0,0 +1,43 @@
1
+ export const STATUS_KEY = "micme";
2
+ export const RECORDING_WIDGET_KEY = "micme-recording";
3
+ export const DEFAULT_SHORTCUT = "alt+m";
4
+ export const DEFAULT_MACOS_PRINTABLE_SHORTCUT = "§";
5
+ export const DEFAULT_TRANSCRIBE_TIMEOUT_MS = 120_000;
6
+ export const DEFAULT_RECORD_SAMPLE_RATE = 48_000;
7
+ export const DEFAULT_TRANSCRIBE_SAMPLE_RATE = 16_000;
8
+ export const RECORDER_STARTUP_GRACE_MS = 700;
9
+ export const RECORDER_STOP_GRACE_MS = 3_000;
10
+ export const MIN_AUDIO_BYTES = 512;
11
+ export const MAX_CAPTURED_OUTPUT_CHARS = 100_000;
12
+ export const STREAM_MIN_INITIAL_WORDS = 2;
13
+ export const DEFAULT_STREAM_STEP_MS = 1_000;
14
+ export const DEFAULT_STREAM_LENGTH_MS = 5_000;
15
+ export const DEFAULT_STREAM_KEEP_MS = 500;
16
+ export const DEFAULT_STREAM_MAX_TOKENS = 64;
17
+ export const DEFAULT_STREAM_VAD_THRESHOLD = 0.45;
18
+ export const STREAM_PROFILE_STEP_MS = 500;
19
+ export const STREAM_PROFILE_LENGTH_MS = 3_000;
20
+ export const STREAM_PROFILE_KEEP_MS = 300;
21
+ export const STREAM_PROFILE_MAX_TOKENS = 32;
22
+ export const STREAM_PROFILE_WORDS_PER_CHUNK = 5;
23
+ export const STREAM_PROFILE_VAD_THRESHOLD = 0.35;
24
+ export const DEFAULT_MIN_MAX_VOLUME_DB = -50;
25
+ export const AUDIO_VALIDATION_TIMEOUT_MS = 30_000;
26
+ export const DEFAULT_WHISPER_CPP_MODEL_NAME = "small.en";
27
+ export const WHISPER_CPP_MODEL_BASE_URL = "https://huggingface.co/ggerganov/whisper.cpp/resolve/main";
28
+ export const WHISPER_CPP_MODEL_NAMES = [
29
+ "tiny.en",
30
+ "tiny",
31
+ "base.en",
32
+ "base",
33
+ "small.en",
34
+ "small",
35
+ "medium.en",
36
+ "medium",
37
+ "large-v1",
38
+ "large-v2",
39
+ "large-v3",
40
+ "large-v3-turbo",
41
+ ] as const;
42
+ export const PYTHON_WHISPER_MODEL_NAMES = ["tiny.en", "tiny", "base.en", "base", "small.en", "small", "medium.en", "medium", "large-v1", "large-v2", "large-v3", "large"] as const;
43
+
package/src/editor.ts ADDED
@@ -0,0 +1,122 @@
1
+ import { CustomEditor, type ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import { type AutocompleteProvider, decodeKittyPrintable } from "@earendil-works/pi-tui";
3
+ import { matchesPrintableMicmeShortcut } from "./config.ts";
4
+
5
+ type CustomEditorArgs = ConstructorParameters<typeof CustomEditor>;
6
+ // Printable Option-key fallbacks auto-repeat while held; debounce them so one hold is one toggle.
7
+ const PRINTABLE_SHORTCUT_REPEAT_GUARD_MS = 1_000;
8
+ let lastPrintableShortcut = "";
9
+ let lastPrintableShortcutAt = 0;
10
+
11
+ export type MicmeEditorInputHandlers = {
12
+ toggle: () => Promise<void> | void;
13
+ };
14
+
15
+ class MicmeEditor extends CustomEditor {
16
+ constructor(
17
+ tui: CustomEditorArgs[0],
18
+ theme: CustomEditorArgs[1],
19
+ keybindings: CustomEditorArgs[2],
20
+ private readonly micmeHandlers: MicmeEditorInputHandlers,
21
+ ) {
22
+ super(tui, theme, keybindings);
23
+ }
24
+
25
+ override handleInput(data: string): void {
26
+ if (handleMicmeEditorInput(data, this.micmeHandlers)) return;
27
+ super.handleInput(data);
28
+ }
29
+ }
30
+
31
+ function handleMicmeEditorInput(data: string, handlers: MicmeEditorInputHandlers) {
32
+ const printable = decodeKittyPrintable(data);
33
+ const printableShortcut = matchesPrintableMicmeShortcut(data) ? data : printable !== undefined && matchesPrintableMicmeShortcut(printable) ? printable : undefined;
34
+ if (printableShortcut !== undefined) {
35
+ if (!isPrintableShortcutAutoRepeat(printableShortcut)) void handlers.toggle();
36
+ return true;
37
+ }
38
+
39
+ return false;
40
+ }
41
+
42
+ function isPrintableShortcutAutoRepeat(printableShortcut: string) {
43
+ const now = Date.now();
44
+ const repeated = printableShortcut === lastPrintableShortcut && now - lastPrintableShortcutAt < PRINTABLE_SHORTCUT_REPEAT_GUARD_MS;
45
+ lastPrintableShortcut = printableShortcut;
46
+ lastPrintableShortcutAt = now;
47
+ return repeated;
48
+ }
49
+
50
+ export function installMicmeEditorFallback(ctx: ExtensionContext, micmeHandlers: MicmeEditorInputHandlers) {
51
+ if (ctx.mode !== "tui") return;
52
+
53
+ const previousEditor = ctx.ui.getEditorComponent();
54
+ if (previousEditor) {
55
+ ctx.ui.setEditorComponent((tui, theme, keybindings) => {
56
+ const base = previousEditor(tui, theme, keybindings);
57
+ return {
58
+ get focused(): boolean {
59
+ return Boolean((base as { focused?: boolean }).focused);
60
+ },
61
+ set focused(value: boolean) {
62
+ if ("focused" in base) (base as { focused?: boolean }).focused = value;
63
+ },
64
+ get onSubmit(): ((text: string) => void) | undefined {
65
+ return base.onSubmit;
66
+ },
67
+ set onSubmit(handler: ((text: string) => void) | undefined) {
68
+ base.onSubmit = handler;
69
+ },
70
+ get onChange(): ((text: string) => void) | undefined {
71
+ return base.onChange;
72
+ },
73
+ set onChange(handler: ((text: string) => void) | undefined) {
74
+ base.onChange = handler;
75
+ },
76
+ get borderColor(): ((str: string) => string) | undefined {
77
+ return base.borderColor;
78
+ },
79
+ set borderColor(handler: ((str: string) => string) | undefined) {
80
+ base.borderColor = handler;
81
+ },
82
+ render(width: number) {
83
+ return base.render(width);
84
+ },
85
+ invalidate() {
86
+ base.invalidate();
87
+ },
88
+ getText() {
89
+ return base.getText();
90
+ },
91
+ setText(text: string) {
92
+ base.setText(text);
93
+ },
94
+ getExpandedText() {
95
+ return base.getExpandedText?.() ?? base.getText();
96
+ },
97
+ addToHistory(text: string) {
98
+ base.addToHistory?.(text);
99
+ },
100
+ insertTextAtCursor(text: string) {
101
+ base.insertTextAtCursor?.(text);
102
+ },
103
+ setAutocompleteProvider(provider: AutocompleteProvider) {
104
+ base.setAutocompleteProvider?.(provider);
105
+ },
106
+ setPaddingX(padding: number) {
107
+ base.setPaddingX?.(padding);
108
+ },
109
+ setAutocompleteMaxVisible(maxVisible: number) {
110
+ base.setAutocompleteMaxVisible?.(maxVisible);
111
+ },
112
+ handleInput(data: string) {
113
+ if (handleMicmeEditorInput(data, micmeHandlers)) return;
114
+ base.handleInput(data);
115
+ },
116
+ };
117
+ });
118
+ return;
119
+ }
120
+
121
+ ctx.ui.setEditorComponent((tui, theme, keybindings) => new MicmeEditor(tui, theme, keybindings, micmeHandlers));
122
+ }
@@ -0,0 +1,351 @@
1
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import { mkdtemp } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { RECORDER_STARTUP_GRACE_MS, STATUS_KEY } from "./constants.ts";
6
+ import {
7
+ env,
8
+ envFlag,
9
+ expandConfigPath,
10
+ getShortcut,
11
+ getStreamFinalizeWithClip,
12
+ getTranscriptionMode,
13
+ reloadDotEnv,
14
+ } from "./config.ts";
15
+ import { buildRecorderCommand, listAudioDevices, prepareAudioForTranscription, validateRecordedAudio } from "./audio.ts";
16
+ import { installMicmeEditorFallback, type MicmeEditorInputHandlers } from "./editor.ts";
17
+ import { getDefaultWhisperCppModelPath, ensureWhisperCppModel } from "./models.ts";
18
+ import {
19
+ cleanup,
20
+ formatExit,
21
+ normalizeTranscript,
22
+ raceWithTimeout,
23
+ spawnRecording,
24
+ stopProcess,
25
+ stopRecorder,
26
+ } from "./processes.ts";
27
+ import { clearRecordingWidget, startRecordingWidget } from "./recording-widget.ts";
28
+ import { showConfiguration } from "./settings.ts";
29
+ import {
30
+ buildWhisperStreamCommand,
31
+ clearStreamingFlush,
32
+ drainStreamingOutput,
33
+ flushPendingStreamingWords,
34
+ getStreamingTranscript,
35
+ handleStreamingOutput,
36
+ pasteOrSubmitFinalStreamingTranscript,
37
+ renderStreamingPreview,
38
+ showStreamingDiagnostics,
39
+ } from "./streaming.ts";
40
+ import { pasteOrSubmitTranscript } from "./transcript-delivery.ts";
41
+ import { getWhisperStreamBinary, transcribe } from "./transcription.ts";
42
+ import type { Recording } from "./types.ts";
43
+
44
+ const MICME_ACTIONS = ["devices", "conf", "last", "audio", "help"] as const;
45
+
46
+ const SHORTCUT_REPEAT_GUARD_MS = 1_000;
47
+
48
+ let recording: Recording | undefined;
49
+ let lastTranscript = "";
50
+ let lastAudioDir = "";
51
+ let lastShortcutInputAt = 0;
52
+
53
+ export default function micmeExtension(pi: ExtensionAPI) {
54
+ reloadDotEnv(process.cwd());
55
+
56
+ async function toggle(ctx: ExtensionContext) {
57
+ if (recording) {
58
+ if (isStillStarting(recording)) return;
59
+ await stopAndTranscribe(ctx, pi);
60
+ return;
61
+ }
62
+ await startRecording(ctx);
63
+ }
64
+
65
+ pi.registerCommand("micme", {
66
+ description: "Toggle local voice recording and paste the transcript into the editor",
67
+ getArgumentCompletions: (prefix) => {
68
+ const matches = MICME_ACTIONS.filter((action) => action.startsWith(prefix.trim().toLowerCase()));
69
+ return matches.length ? matches.map((value) => ({ value, label: value })) : null;
70
+ },
71
+ handler: async (args, ctx) => {
72
+ const action = args.trim().split(/\s+/, 1)[0]?.toLowerCase() ?? "";
73
+
74
+ try {
75
+ switch (action) {
76
+ case "":
77
+ await toggle(ctx);
78
+ return;
79
+ case "devices":
80
+ await listAudioDevices(ctx);
81
+ return;
82
+ case "conf":
83
+ await showConfiguration(ctx);
84
+ return;
85
+ case "last":
86
+ await pasteOrSubmitTranscript(ctx, pi, lastTranscript);
87
+ return;
88
+ case "audio":
89
+ ctx.ui.notify(lastAudioDir ? `Last Micme audio directory: ${lastAudioDir}` : "No kept Micme audio yet. Set MICME_KEEP_AUDIO=1.", "info");
90
+ return;
91
+ case "help":
92
+ ctx.ui.notify(getHelpText(), "info");
93
+ return;
94
+ default:
95
+ ctx.ui.notify(`Unknown micme action: ${action}. Try /micme help`, "warning");
96
+ }
97
+ } catch (error) {
98
+ handleExtensionError(ctx, error);
99
+ }
100
+ },
101
+ });
102
+
103
+ pi.registerShortcut(getShortcut() as Parameters<ExtensionAPI["registerShortcut"]>[0], {
104
+ description: "Micme: toggle local voice recording",
105
+ handler: async (ctx) => {
106
+ try {
107
+ if (isShortcutAutoRepeat()) return;
108
+ await toggle(ctx);
109
+ } catch (error) {
110
+ handleExtensionError(ctx, error);
111
+ }
112
+ },
113
+ });
114
+
115
+ pi.on("session_start", async (_event, ctx) => {
116
+ reloadDotEnv(ctx.cwd);
117
+ installMicmeEditorFallback(ctx, createMicmeEditorHandlers(ctx, toggle));
118
+ });
119
+
120
+ pi.on("session_shutdown", async (_event, ctx) => {
121
+ clearRecordingWidget(ctx);
122
+ if (!recording) return;
123
+ const active = recording;
124
+ recording = undefined;
125
+ if (active.streaming) {
126
+ clearStreamingFlush(active.streaming);
127
+ await Promise.all([stopProcess(active).catch(() => undefined), active.clipRecording ? stopProcess(active.clipRecording).catch(() => undefined) : Promise.resolve()]);
128
+ } else {
129
+ await stopRecorder(active).catch(() => undefined);
130
+ }
131
+ await cleanup(active.tempDir).catch(() => undefined);
132
+ });
133
+ }
134
+
135
+ function createMicmeEditorHandlers(ctx: ExtensionContext, toggle: (ctx: ExtensionContext) => Promise<void>): MicmeEditorInputHandlers {
136
+ return {
137
+ toggle: () => toggle(ctx).catch((error) => handleExtensionError(ctx, error)),
138
+ };
139
+ }
140
+
141
+ function handleExtensionError(ctx: ExtensionContext, error: unknown) {
142
+ ctx.ui.setStatus(STATUS_KEY, undefined);
143
+ ctx.ui.notify(error instanceof Error ? error.message : String(error), "error");
144
+ }
145
+
146
+ function isStillStarting(active: Recording) {
147
+ return Date.now() - active.startedAt < RECORDER_STARTUP_GRACE_MS;
148
+ }
149
+
150
+ function isShortcutAutoRepeat() {
151
+ const now = Date.now();
152
+ const repeated = now - lastShortcutInputAt < SHORTCUT_REPEAT_GUARD_MS;
153
+ lastShortcutInputAt = now;
154
+ return repeated;
155
+ }
156
+
157
+ function getHelpText() {
158
+ const shortcut = getShortcut();
159
+ const actions = MICME_ACTIONS.filter((action) => action !== "help").join("|");
160
+ return `Usage: /micme [${actions}]. Shortcut: ${shortcut} toggles recording; tap once to start, tap again to stop/transcribe.`;
161
+ }
162
+
163
+ async function startRecording(ctx: ExtensionContext, stopHint = getShortcut()) {
164
+ if (recording) return;
165
+
166
+ if (getTranscriptionMode() === "stream") {
167
+ await startStreamingTranscription(ctx, stopHint);
168
+ return;
169
+ }
170
+
171
+ const tempDir = await mkdtemp(join(tmpdir(), "micme-"));
172
+ const audioPath = join(tempDir, "raw.wav");
173
+ const command = buildRecorderCommand(audioPath);
174
+ const active = spawnRecording(command, audioPath, tempDir);
175
+ recording = active;
176
+
177
+ const earlyExit = await raceWithTimeout(active.exitPromise, RECORDER_STARTUP_GRACE_MS);
178
+ if (earlyExit) {
179
+ if (active.stopRequested) return;
180
+ recording = undefined;
181
+ clearRecordingWidget(ctx);
182
+ await cleanup(tempDir).catch(() => undefined);
183
+ const stderr = active.stderr().trim();
184
+ const suffix = stderr ? `\n${stderr}` : "";
185
+ throw new Error(`Micme recorder exited early (${formatExit(earlyExit)}).${suffix}`);
186
+ }
187
+
188
+ ctx.ui.setStatus(STATUS_KEY, `● recording (${stopHint} or /micme)`);
189
+ startRecordingWidget(ctx, active);
190
+ }
191
+
192
+ async function stopAndTranscribe(ctx: ExtensionContext, pi: ExtensionAPI) {
193
+ const active = recording;
194
+ if (!active) {
195
+ ctx.ui.notify("Micme is not recording. Use /micme to start recording.", "warning");
196
+ return;
197
+ }
198
+
199
+ if (active.streaming) {
200
+ recording = undefined;
201
+ clearRecordingWidget(ctx);
202
+ await stopStreamingTranscription(ctx, pi, active);
203
+ return;
204
+ }
205
+
206
+ recording = undefined;
207
+ clearRecordingWidget(ctx);
208
+ ctx.ui.setStatus(STATUS_KEY, "transcribing…");
209
+
210
+ let completed = false;
211
+ try {
212
+ await stopRecorder(active);
213
+ const preparedAudioPath = await prepareAudioForTranscription(active.audioPath, active.tempDir);
214
+ await validateRecordedAudio(preparedAudioPath);
215
+ const transcript = await transcribe(preparedAudioPath, active.tempDir, ctx);
216
+ const normalized = normalizeTranscript(transcript);
217
+
218
+ if (!normalized) {
219
+ throw new Error("Micme did not receive any transcript text.");
220
+ }
221
+
222
+ lastTranscript = normalized;
223
+ await pasteOrSubmitTranscript(ctx, pi, normalized);
224
+ completed = true;
225
+ ctx.ui.setStatus(STATUS_KEY, undefined);
226
+ if (envFlag("MICME_KEEP_AUDIO")) {
227
+ lastAudioDir = active.tempDir;
228
+ }
229
+ } catch (error) {
230
+ ctx.ui.setStatus(STATUS_KEY, undefined);
231
+ lastAudioDir = active.tempDir;
232
+ const message = error instanceof Error ? error.message : String(error);
233
+ throw new Error(`${message}\nAudio kept for debugging: ${active.tempDir}`);
234
+ } finally {
235
+ if (completed && !envFlag("MICME_KEEP_AUDIO")) {
236
+ await cleanup(active.tempDir).catch(() => undefined);
237
+ }
238
+ }
239
+ }
240
+
241
+ async function startStreamingTranscription(ctx: ExtensionContext, stopHint = getShortcut()) {
242
+ const whisperStream = getWhisperStreamBinary();
243
+ if (!whisperStream) {
244
+ throw new Error("Streaming mode needs whisper-stream. Install whisper-cpp or switch /micme conf back to clip mode.");
245
+ }
246
+
247
+ const whisperCppModel = expandConfigPath(getConfiguredWhisperCppModel());
248
+ await ensureWhisperCppModel(whisperCppModel, ctx);
249
+
250
+ const tempDir = await mkdtemp(join(tmpdir(), "micme-stream-"));
251
+ const command = buildWhisperStreamCommand(whisperStream, whisperCppModel, tempDir);
252
+ const active = spawnRecording(command, "", tempDir);
253
+ const baseText = ctx.ui.getEditorText();
254
+ active.streaming = { baseText, previewText: baseText, outputBuffer: "", lastText: "", pendingWords: [], emittedWords: [], startedAt: Date.now() };
255
+ if (getStreamFinalizeWithClip()) {
256
+ const audioPath = join(tempDir, "raw.wav");
257
+ active.clipRecording = spawnRecording(buildRecorderCommand(audioPath), audioPath, tempDir);
258
+ }
259
+ recording = active;
260
+
261
+ active.process.stdout?.on("data", (chunk: Buffer | string) => {
262
+ const text = typeof chunk === "string" ? chunk : chunk.toString("utf8");
263
+ handleStreamingOutput(ctx, active, text);
264
+ });
265
+
266
+ const [earlyExit, recorderEarlyExit] = await Promise.all([
267
+ raceWithTimeout(active.exitPromise, RECORDER_STARTUP_GRACE_MS),
268
+ active.clipRecording ? raceWithTimeout(active.clipRecording.exitPromise, RECORDER_STARTUP_GRACE_MS) : Promise.resolve(undefined),
269
+ ]);
270
+ if (earlyExit || recorderEarlyExit) {
271
+ if (active.stopRequested || active.clipRecording?.stopRequested) return;
272
+ recording = undefined;
273
+ clearRecordingWidget(ctx);
274
+ await stopProcess(active).catch(() => undefined);
275
+ if (active.clipRecording) await stopProcess(active.clipRecording).catch(() => undefined);
276
+ await cleanup(tempDir).catch(() => undefined);
277
+ const failed = earlyExit ? active : active.clipRecording;
278
+ const stderr = failed?.stderr().trim();
279
+ const suffix = stderr ? `\n${stderr}` : "";
280
+ throw new Error(`Micme streaming exited early (${formatExit(earlyExit ?? recorderEarlyExit!)}).${suffix}`);
281
+ }
282
+
283
+ ctx.ui.setStatus(STATUS_KEY, `● streaming (${stopHint} or /micme)`);
284
+ startRecordingWidget(ctx, active);
285
+ }
286
+
287
+ async function stopStreamingTranscription(ctx: ExtensionContext, pi: ExtensionAPI, active: Recording) {
288
+ const state = active.streaming;
289
+ let keepTempDir = false;
290
+ const clipStopPromise = active.clipRecording ? stopRecorder(active.clipRecording).then(() => undefined, (error: unknown) => error) : undefined;
291
+
292
+ if (state) {
293
+ drainStreamingOutput(ctx, active, false);
294
+ renderStreamingPreview(ctx, state, false);
295
+ clearStreamingFlush(state);
296
+ }
297
+
298
+ await stopProcess(active);
299
+
300
+ if (state) {
301
+ drainStreamingOutput(ctx, active, true);
302
+ showStreamingDiagnostics(ctx, state);
303
+ if (!active.clipRecording) {
304
+ flushPendingStreamingWords(ctx, state);
305
+ const liveTranscript = normalizeTranscript(getStreamingTranscript(state));
306
+ if (liveTranscript) {
307
+ lastTranscript = liveTranscript;
308
+ if (envFlag("MICME_AUTO_SUBMIT")) {
309
+ ctx.ui.setEditorText(state.baseText);
310
+ await pasteOrSubmitTranscript(ctx, pi, liveTranscript);
311
+ }
312
+ }
313
+ } else {
314
+ renderStreamingPreview(ctx, state, false);
315
+ }
316
+ clearStreamingFlush(state);
317
+ }
318
+
319
+ if (active.clipRecording && state) {
320
+ ctx.ui.setStatus(STATUS_KEY, "finalizing stream…");
321
+ try {
322
+ const clipStopError = await clipStopPromise;
323
+ if (clipStopError) throw clipStopError;
324
+ const preparedAudioPath = await prepareAudioForTranscription(active.clipRecording.audioPath, active.tempDir);
325
+ await validateRecordedAudio(preparedAudioPath);
326
+ const transcript = await transcribe(preparedAudioPath, active.tempDir, ctx);
327
+ const normalized = normalizeTranscript(transcript);
328
+ if (!normalized) throw new Error("Micme did not receive any final transcript text.");
329
+
330
+ lastTranscript = normalized;
331
+ await pasteOrSubmitFinalStreamingTranscript(ctx, pi, state, normalized);
332
+ if (envFlag("MICME_KEEP_AUDIO")) {
333
+ lastAudioDir = active.tempDir;
334
+ keepTempDir = true;
335
+ }
336
+ } catch (error) {
337
+ lastAudioDir = active.tempDir;
338
+ keepTempDir = true;
339
+ const message = error instanceof Error ? error.message : String(error);
340
+ ctx.ui.notify(`Micme kept the live stream preview because final clip transcription failed: ${message}\nAudio kept for debugging: ${active.tempDir}`, "warning");
341
+ }
342
+ }
343
+
344
+ if (!keepTempDir) await cleanup(active.tempDir).catch(() => undefined);
345
+ ctx.ui.setStatus(STATUS_KEY, undefined);
346
+ }
347
+
348
+ function getConfiguredWhisperCppModel() {
349
+ return env("MICME_WHISPER_CPP_MODEL") || getDefaultWhisperCppModelPath();
350
+ }
351
+