@senad-d/micme 0.3.7 → 0.3.9

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/CHANGELOG.md CHANGED
@@ -25,6 +25,11 @@ All notable changes to Micme will be documented in this file.
25
25
  - Align `micme-doctor` executable/model checks with runtime validation and translation-capable model fallback behavior.
26
26
  - Let `MICME_RECORD_COMMAND` use the same `{audio}`, `{tempDir}`, and `{transcript}` placeholders as custom transcription commands.
27
27
 
28
+ ## [0.3.9] - 2026-11-24
29
+
30
+ - Windows recording and transcription hooks now launch the system command interpreter rather than a same-named executable in the project directory.
31
+ - Micme reports failed signal escalation instead of treating a still-running recorder as stopped or letting a second signal error go unhandled.
32
+
28
33
  ## 0.1.0 - 2026-06-18
29
34
 
30
35
  Initial publication-readiness candidate.
package/README.md CHANGED
@@ -118,7 +118,9 @@ pi install /absolute/path/to/micme
118
118
 
119
119
  ## Pi Compatibility
120
120
 
121
- Micme supports `@earendil-works/pi-coding-agent` and `@earendil-works/pi-tui` versions `>=0.80.7 <0.81.0`. CI installs and tests both packages at `0.80.7`, typechecks every production TypeScript file against their real declarations, and loads the default extension through Pi's jiti-based loader. Supporting a new Pi minor release requires intentionally updating the peer ranges, pinned development versions, and contract gate together.
121
+ Micme declares `*` as the peer dependency range for both `@earendil-works/pi-coding-agent` and `@earendil-works/pi-tui`. These published ranges are not a compatibility guarantee. CI pins both packages to `1.6.0` and tests only that version: it typechecks every production TypeScript file against their declarations and loads the default extension through Pi's jiti-based loader.
122
+
123
+ Before adopting another Pi release, review both published peer ranges and update the development pins and the contract test together.
122
124
 
123
125
  ---
124
126
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@senad-d/micme",
3
- "version": "0.3.7",
3
+ "version": "0.3.9",
4
4
  "type": "module",
5
5
  "description": "Local voice dictation for Pi coding prompts. Press Alt+M, speak, review, send.",
6
6
  "license": "MIT",
@@ -77,17 +77,17 @@
77
77
  "image": "https://raw.githubusercontent.com/senad-d/micme/main/img/demo.gif"
78
78
  },
79
79
  "peerDependencies": {
80
- "@earendil-works/pi-coding-agent": ">=0.80.7 <0.81.0",
81
- "@earendil-works/pi-tui": ">=0.80.7 <0.81.0"
80
+ "@earendil-works/pi-coding-agent": "*",
81
+ "@earendil-works/pi-tui": "*"
82
82
  },
83
83
  "devDependencies": {
84
- "@earendil-works/pi-coding-agent": "0.80.7",
85
- "@earendil-works/pi-tui": "0.80.7",
84
+ "@earendil-works/pi-coding-agent": "1.6.0",
85
+ "@earendil-works/pi-tui": "1.6.0",
86
86
  "@eslint/js": "^10.0.1",
87
87
  "@types/node": "^26.0.0",
88
88
  "eslint": "^10.6.0",
89
89
  "globals": "^17.7.0",
90
- "typescript": "~6.0.3",
90
+ "typescript": "6.0.3",
91
91
  "typescript-eslint": "^8.62.1"
92
92
  }
93
93
  }
package/src/audio.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
2
  import { sliceByColumn, visibleWidth, type Component } from "@earendil-works/pi-tui";
3
+ import { spawnSync } from "node:child_process";
3
4
  import { dirname, join } from "node:path";
4
5
  import { AUDIO_VALIDATION_TIMEOUT_MS, MAX_CAPTURED_OUTPUT_CHARS } from "./constants.ts";
5
6
  import { env, envFlag, getAudioFilter, getAvfoundationDropLateFrames, getAvfoundationInputSampleRate, getMinMaxVolumeDb, getRecordMeter, getRecordSampleRate, getRecordSync, getTranscribeSampleRate } from "./config.ts";
@@ -63,6 +64,7 @@ const RECORD_TIMING_SYNC_FILTER = "aresample=async=1:first_pts=0";
63
64
  const AVFOUNDATION_DEVICE_PREFIX_PATTERN = /^\[(\d+)]\s+/;
64
65
  const DIRECT_SHOW_FULL_DEVICE_NAME_PATTERN = /^"(.+)"$/;
65
66
  const DIRECT_SHOW_DEVICE_NAME_PATTERN = /"([^"]+)"/;
67
+ const DIRECT_SHOW_DEVICE_KIND_PATTERN = /^"([^"]+)"\s*\((audio|video)\)$/i;
66
68
  const FFMPEG_WARNING_WORDS = new Set(["warning", "error", "failed", "cannot", "unable"]);
67
69
  const PULSE_SOURCE_LINE_PATTERN = /^([^\s[]+)(?:\s+\[(.+)\])?$/;
68
70
 
@@ -273,27 +275,60 @@ export function parseDirectShowDevices(output: string): ParsedDeviceInventory {
273
275
 
274
276
  for (const rawLine of output.split(/\r?\n/)) {
275
277
  const line = stripFfmpegLogPrefix(rawLine).trim();
276
- if (/DirectShow video devices/i.test(line)) {
277
- section = "video";
278
- inventory.sawDeviceSection = true;
279
- continue;
280
- }
281
- if (/DirectShow audio devices/i.test(line)) {
282
- section = "audio";
278
+ const nextSection = parseDirectShowSection(line);
279
+ if (nextSection) {
280
+ section = nextSection;
283
281
  inventory.sawDeviceSection = true;
284
282
  continue;
285
283
  }
286
- if (!section || /Alternative name/i.test(line)) continue;
287
284
 
288
- const match = DIRECT_SHOW_FULL_DEVICE_NAME_PATTERN.exec(line) ?? DIRECT_SHOW_DEVICE_NAME_PATTERN.exec(line);
289
- const name = sanitizeDeviceField(match?.[1] ?? "");
290
- if (!name) continue;
291
- inventory[section].push({ name });
285
+ const device = parseDirectShowDevice(line, section);
286
+ if (device) inventory[device.kind].push({ name: device.name });
292
287
  }
293
288
 
294
289
  return inventory;
295
290
  }
296
291
 
292
+ function parseDirectShowSection(line: string): DeviceKind | undefined {
293
+ if (/DirectShow video devices/i.test(line)) return "video";
294
+ if (/DirectShow audio devices/i.test(line)) return "audio";
295
+ return undefined;
296
+ }
297
+
298
+ function parseDirectShowDevice(line: string, section: DeviceKind | undefined): { kind: DeviceKind; name: string } | undefined {
299
+ if (/Alternative name/i.test(line)) return undefined;
300
+
301
+ const kindMatch = DIRECT_SHOW_DEVICE_KIND_PATTERN.exec(line);
302
+ if (kindMatch) {
303
+ const name = sanitizeDeviceField(kindMatch[1] ?? "");
304
+ const kind = (kindMatch[2] ?? "").toLowerCase() === "video" ? "video" : "audio";
305
+ return name ? { kind, name } : undefined;
306
+ }
307
+
308
+ if (!section) return undefined;
309
+ const match = DIRECT_SHOW_FULL_DEVICE_NAME_PATTERN.exec(line) ?? DIRECT_SHOW_DEVICE_NAME_PATTERN.exec(line);
310
+ const name = sanitizeDeviceField(match?.[1] ?? "");
311
+ return name ? { kind: section, name } : undefined;
312
+ }
313
+
314
+ function findDefaultDshowAudioDevice(): string | undefined {
315
+ if (process.platform !== "win32") return undefined;
316
+ const ffmpeg = findExecutable(["ffmpeg"]);
317
+ if (!ffmpeg) return undefined;
318
+ try {
319
+ const result = spawnSync(ffmpeg, ["-hide_banner", "-list_devices", "true", "-f", "dshow", "-i", "dummy"], {
320
+ encoding: "utf8",
321
+ timeout: DEVICE_SCAN_TIMEOUT_MS,
322
+ windowsHide: true,
323
+ });
324
+ if (result.error || result.signal) return undefined;
325
+ const inventory = parseDirectShowDevices(`${result.stdout ?? ""}\n${result.stderr ?? ""}`);
326
+ return inventory.audio[0]?.name;
327
+ } catch {
328
+ return undefined;
329
+ }
330
+ }
331
+
297
332
  function stripFfmpegLogPrefix(line: string) {
298
333
  return line.replace(/^(?:\[[^\]]+\]\s*)+/, "");
299
334
  }
@@ -623,6 +658,11 @@ export async function discoverAudioDevices(): Promise<AudioDeviceCandidate[]> {
623
658
  }
624
659
 
625
660
  if (process.platform === "win32") {
661
+ const result = await runProcess(ffmpeg, ["-hide_banner", "-list_devices", "true", "-f", "dshow", "-i", "dummy"], DEVICE_SCAN_TIMEOUT_MS);
662
+ const parsed = parseDirectShowDevices(`${result.stdout ?? ""}\n${result.stderr ?? ""}`);
663
+ if (parsed.audio.length > 0) {
664
+ return parsed.audio.map((device) => ({ label: device.name, value: device.name, description: "DirectShow audio input" }));
665
+ }
626
666
  return [{ label: "default", value: "default", description: "DirectShow default audio input" }];
627
667
  }
628
668
 
@@ -700,7 +740,7 @@ export async function validateRecordedAudio(audioPath: string, signal?: AbortSig
700
740
  throw new Error(
701
741
  `Micme recorded almost-silent audio (max ${formatVolumeDb(diagnostics.maxVolumeDb)} dB; threshold ${minimumMaxVolumeDb.toFixed(1)} dB). ` +
702
742
  "Whisper often hallucinates phrases like 'Thank you very much' from silence. " +
703
- "Run /micme devices and set MICME_AUDIO_DEVICE to the real microphone, or set MICME_VALIDATE_AUDIO=0 to bypass this check.",
743
+ `Run /micme devices and set ${process.platform === "win32" ? "MICME_DSHOW_AUDIO_DEVICE" : "MICME_AUDIO_DEVICE"} to the real microphone, or set MICME_VALIDATE_AUDIO=0 to bypass this check.`,
704
744
  );
705
745
  }
706
746
 
@@ -765,7 +805,8 @@ export function buildRecorderCommand(audioPath: string, tempDir = dirname(audioP
765
805
  }
766
806
 
767
807
  if (process.platform === "win32") {
768
- const input = `audio=${env("MICME_DSHOW_AUDIO_DEVICE") || "default"}`;
808
+ const deviceName = env("MICME_DSHOW_AUDIO_DEVICE") || findDefaultDshowAudioDevice() || "default";
809
+ const input = `audio=${deviceName}`;
769
810
  const args = buildFfmpegRecorderArgs("dshow", input, audioPath, recordSampleRate, { meter: recordMeter, audioFilters: timingFilters });
770
811
  return { command: ffmpeg, args, display: `${ffmpeg} ${args.map(shellQuote).join(" ")}`, meterFromStdout: recordMeter, stopInput: "q\n", signalStopExitCodes: [255] };
771
812
  }
package/src/editor.ts CHANGED
@@ -63,7 +63,8 @@ class WrappedMicmeEditor extends CustomEditor {
63
63
 
64
64
  override render(width: number): string[] {
65
65
  this.syncBaseEditor();
66
- return this.base.render(width);
66
+ // Pi components may reuse readonly render output; CustomEditor promises a mutable array.
67
+ return [...this.base.render(width)];
67
68
  }
68
69
 
69
70
  override invalidate(): void {
package/src/processes.ts CHANGED
@@ -1,12 +1,15 @@
1
- import { spawn } from "node:child_process";
1
+ import { spawn, type ChildProcess } from "node:child_process";
2
2
  import { accessSync, constants as fsConstants, statSync } from "node:fs";
3
3
  import { rm, stat } from "node:fs/promises";
4
- import { delimiter, join } from "node:path";
4
+ import { delimiter, join, win32 } from "node:path";
5
5
  import { MAX_CAPTURED_OUTPUT_CHARS, MIN_AUDIO_BYTES, RECORDER_STOP_GRACE_MS } from "./constants.ts";
6
6
  import { pcm16BufferLevel } from "./audio-level.ts";
7
7
  import { sanitizeTerminalOutput, stripTerminalControlSequences } from "./terminal-text.ts";
8
8
  import type { CommandSpec, ExitResult, Recording, RunResult } from "./types.ts";
9
9
 
10
+ const TERMINATE_GRACE_MS = 1_000;
11
+ const FAILED_KILL_CLOSE_GRACE_MS = 1_000;
12
+
10
13
  export function spawnRecording(command: CommandSpec, audioPath: string, tempDir: string): Recording {
11
14
  const child = spawn(command.command, command.args, {
12
15
  stdio: [command.stopInput ? "pipe" : "ignore", "pipe", "pipe"],
@@ -36,13 +39,9 @@ export function spawnRecording(command: CommandSpec, audioPath: string, tempDir:
36
39
  });
37
40
 
38
41
  const exitPromise = new Promise<ExitResult>((resolve) => {
39
- child.once("error", (error) => {
40
- settled = true;
41
- resolve({ code: null, signal: null, error });
42
- });
43
- child.once("close", (code, signal) => {
42
+ observeProcessExit(child, (exit) => {
44
43
  settled = true;
45
- resolve({ code, signal });
44
+ resolve(exit);
46
45
  });
47
46
  });
48
47
 
@@ -80,23 +79,56 @@ async function stopProcessOnce(active: Recording) {
80
79
  }
81
80
  if (!exit) {
82
81
  sendStopSignal(active, "SIGTERM");
83
- exit = await raceWithTimeout(active.exitPromise, 1_000);
84
- }
85
- if (!exit) {
86
- sendStopSignal(active, "SIGKILL");
87
- exit = await active.exitPromise;
82
+ exit = await raceWithTimeout(active.exitPromise, TERMINATE_GRACE_MS);
88
83
  }
89
- return exit;
84
+ if (exit) return exit;
85
+
86
+ const failure = sendStopSignal(active, "SIGKILL");
87
+ if (!failure) return active.exitPromise;
88
+ // A failed kill can race with a real exit. Bound the stop attempt, not the exit promise.
89
+ exit = await raceWithTimeout(active.exitPromise, FAILED_KILL_CLOSE_GRACE_MS);
90
+ if (exit) return exit;
91
+ throw failure;
90
92
  }
91
93
 
92
94
  function sendStopSignal(active: Recording, signal: NodeJS.Signals) {
95
+ const failure = sendProcessSignal(active.process, signal);
96
+ if (failure) return failure;
97
+ active.stopSignals ??= new Set();
98
+ active.stopSignals.add(signal);
99
+ }
100
+
101
+ function observeProcessExit(child: ChildProcess, settle: (exit: ExitResult) => void) {
102
+ let launchFailed = false;
103
+ const onError = (error: Error) => {
104
+ // Node assigns the PID before emitting 'spawn', so even an immediate signal can fail after launch.
105
+ if (child.pid !== undefined || launchFailed) return;
106
+ launchFailed = true;
107
+ settle({ code: null, signal: null, error });
108
+ };
109
+ child.on("error", onError);
110
+ child.once("close", (code, signal) => {
111
+ child.off("error", onError);
112
+ if (!launchFailed) settle({ code, signal });
113
+ });
114
+ }
115
+
116
+ function sendProcessSignal(child: ChildProcess, signal: NodeJS.Signals) {
117
+ let cause: unknown;
118
+ const captureError = (error: Error) => {
119
+ cause = error;
120
+ };
121
+ // ChildProcess.kill() can emit an error synchronously or throw instead.
122
+ child.on("error", captureError);
93
123
  try {
94
- if (!active.process.kill(signal)) return;
95
- active.stopSignals ??= new Set();
96
- active.stopSignals.add(signal);
97
- } catch {
98
- // The exit promise remains authoritative when the process settles during escalation.
124
+ if (child.kill(signal) && cause === undefined) return;
125
+ } catch (error) {
126
+ cause = error;
127
+ } finally {
128
+ child.off("error", captureError);
99
129
  }
130
+ const reason = cause instanceof Error ? formatProcessOutput(appendCapped("", cause.message)) : "";
131
+ return new Error(`Micme could not send ${signal}${reason ? ` (${reason})` : ""}; the child process may still be running.`, { cause });
100
132
  }
101
133
 
102
134
  export function sendStopInput(active: Recording) {
@@ -129,7 +161,12 @@ export function runShell(command: string, timeoutMs: number, options: RunProcess
129
161
 
130
162
  export function shellCommand(command: string): CommandSpec {
131
163
  if (process.platform === "win32") {
132
- return { command: "cmd.exe", args: ["/d", "/s", "/c", command], display: command };
164
+ // Use the host's Windows installation directory, not ComSpec or executable lookup.
165
+ const systemRoot = process.env.SystemRoot;
166
+ if (!systemRoot || !/^[a-z]:[\\/]/i.test(systemRoot)) {
167
+ throw new Error("Micme cannot locate the Windows system shell: SystemRoot must be a drive-qualified absolute path.");
168
+ }
169
+ return { command: win32.join(systemRoot, "System32", "cmd.exe"), args: ["/d", "/s", "/c", command], display: command };
133
170
  }
134
171
  return { command: "sh", args: ["-lc", command], display: command };
135
172
  }
@@ -150,24 +187,40 @@ export function runProcess(command: string, args: string[], timeoutMs: number, o
150
187
  let stderr = "";
151
188
  let timedOut = false;
152
189
  let cancelled = false;
153
- let settled = false;
190
+ let finished = false;
191
+ let killAttempted = false;
154
192
  let abortTimer: ReturnType<typeof setTimeout> | undefined;
193
+ let failedKillTimer: ReturnType<typeof setTimeout> | undefined;
155
194
 
156
195
  const timer = setTimeout(() => {
157
196
  timedOut = true;
158
- child.kill("SIGKILL");
197
+ forceStop();
159
198
  }, timeoutMs);
160
199
  const abort = () => {
161
- if (settled) return;
200
+ if (finished || cancelled) return;
162
201
  cancelled = true;
163
- child.kill("SIGTERM");
164
- abortTimer = setTimeout(() => child.kill("SIGKILL"), 1_000);
202
+ if (killAttempted) return;
203
+ abortTimer = setTimeout(forceStop, TERMINATE_GRACE_MS);
204
+ sendProcessSignal(child, "SIGTERM");
165
205
  };
166
206
  const finish = () => {
207
+ finished = true;
167
208
  clearTimeout(timer);
168
- if (abortTimer) clearTimeout(abortTimer);
209
+ clearTimeout(abortTimer);
210
+ clearTimeout(failedKillTimer);
169
211
  options.signal?.removeEventListener("abort", abort);
170
212
  };
213
+ const forceStop = () => {
214
+ if (finished || killAttempted) return;
215
+ killAttempted = true;
216
+ clearTimeout(abortTimer);
217
+ const failure = sendProcessSignal(child, "SIGKILL");
218
+ if (!failure || finished) return;
219
+ failedKillTimer = setTimeout(() => {
220
+ finish();
221
+ reject(failure);
222
+ }, FAILED_KILL_CLOSE_GRACE_MS);
223
+ };
171
224
  options.signal?.addEventListener("abort", abort, { once: true });
172
225
 
173
226
  child.stdout?.setEncoding("utf8");
@@ -178,17 +231,11 @@ export function runProcess(command: string, args: string[], timeoutMs: number, o
178
231
  child.stderr?.on("data", (chunk: string) => {
179
232
  stderr = appendCapped(stderr, chunk);
180
233
  });
181
- child.once("error", (error) => {
182
- if (settled) return;
183
- settled = true;
184
- finish();
185
- reject(error);
186
- });
187
- child.once("close", (code, signal) => {
188
- if (settled) return;
189
- settled = true;
234
+ observeProcessExit(child, ({ code, signal, error }) => {
235
+ if (finished) return;
190
236
  finish();
191
- resolve({ code, signal, stdout, stderr, timedOut, ...(cancelled ? { cancelled: true } : {}) });
237
+ if (error) reject(error);
238
+ else resolve({ code, signal, stdout, stderr, timedOut, ...(cancelled ? { cancelled: true } : {}) });
192
239
  });
193
240
  if (options.signal?.aborted) abort();
194
241
  });
package/src/settings.ts CHANGED
@@ -269,7 +269,7 @@ class ConfigurationScreen implements Component {
269
269
  this.requestRender();
270
270
  }
271
271
 
272
- render(width: number): string[] {
272
+ render(width: number): readonly string[] {
273
273
  this.refreshDerivedItems();
274
274
  if (this.submenuComponent) return this.submenuComponent.render(width);
275
275
  if (width < TWO_PANE_MIN_WIDTH) return this.renderNarrow(width);