@senad-d/micme 0.3.6 → 0.3.8

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
@@ -4,7 +4,7 @@ All notable changes to Micme will be documented in this file.
4
4
 
5
5
  ## Unreleased
6
6
 
7
- - Preserve Pi's built-in keyboard shortcuts by installing Micme's editor fallback only when a printable-character shortcut is configured.
7
+ - Preserve Pi's built-in keyboard shortcuts by installing Micme's editor fallback only for printable-character shortcuts and retaining the `CustomEditor` app-handler contract when wrapping another extension's editor.
8
8
  - Move normal Micme persistence to the global `~/.pi/agent/micme.json` store; shell environment variables still override saved settings.
9
9
  - Update `/micme conf`, `micme-doctor`, docs, and package examples for the new global JSON config path.
10
10
  - Document the scoped npm package name, `@senad-d/micme`, in install, diagnostics, update, and uninstall commands.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@senad-d/micme",
3
- "version": "0.3.6",
3
+ "version": "0.3.8",
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,8 +77,8 @@
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
84
  "@earendil-works/pi-coding-agent": "0.80.7",
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
@@ -1,5 +1,5 @@
1
- import { CustomEditor, type ExtensionContext } from "@earendil-works/pi-coding-agent";
2
- import { type AutocompleteProvider, decodeKittyPrintable } from "@earendil-works/pi-tui";
1
+ import { type AppKeybinding, CustomEditor, type ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import { type AutocompleteProvider, decodeKittyPrintable, type EditorComponent } from "@earendil-works/pi-tui";
3
3
  import { getPrintableShortcuts, matchesPrintableMicmeShortcut } from "./config.ts";
4
4
 
5
5
  type CustomEditorArgs = ConstructorParameters<typeof CustomEditor>;
@@ -12,6 +12,14 @@ export type MicmeEditorInputHandlers = {
12
12
  toggle: () => Promise<void> | void;
13
13
  };
14
14
 
15
+ type AppAwareEditor = EditorComponent & {
16
+ actionHandlers: Map<AppKeybinding, () => void>;
17
+ onEscape?: () => void;
18
+ onCtrlD?: () => void;
19
+ onPasteImage?: () => void;
20
+ onExtensionShortcut?: (data: string) => boolean;
21
+ };
22
+
15
23
  class MicmeEditor extends CustomEditor {
16
24
  private readonly micmeHandlers: MicmeEditorInputHandlers;
17
25
 
@@ -26,6 +34,110 @@ class MicmeEditor extends CustomEditor {
26
34
  }
27
35
  }
28
36
 
37
+ // Pi wires app handlers only onto the outer editor returned by the active factory.
38
+ // Keep that identity while delegating editing behavior to the previously installed editor.
39
+ class WrappedMicmeEditor extends CustomEditor {
40
+ readonly wantsKeyRelease?: boolean;
41
+ private readonly base: EditorComponent;
42
+ private readonly baseAppEditor: AppAwareEditor | undefined;
43
+ private readonly micmeHandlers: MicmeEditorInputHandlers;
44
+
45
+ constructor(
46
+ tui: CustomEditorArgs[0],
47
+ theme: CustomEditorArgs[1],
48
+ keybindings: CustomEditorArgs[2],
49
+ base: EditorComponent,
50
+ micmeHandlers: MicmeEditorInputHandlers,
51
+ ) {
52
+ super(tui, theme, keybindings);
53
+ this.base = base;
54
+ this.baseAppEditor = getAppAwareEditor(base);
55
+ this.micmeHandlers = micmeHandlers;
56
+ this.wantsKeyRelease = base.wantsKeyRelease;
57
+ this.focused = "focused" in base && Boolean(base.focused);
58
+ this.onSubmit = base.onSubmit;
59
+ this.onChange = base.onChange;
60
+ if (base.borderColor !== undefined) this.borderColor = base.borderColor;
61
+ if (this.baseAppEditor) this.adoptBaseAppHandlers(this.baseAppEditor);
62
+ }
63
+
64
+ override render(width: number): string[] {
65
+ this.syncBaseEditor();
66
+ return this.base.render(width);
67
+ }
68
+
69
+ override invalidate(): void {
70
+ this.syncBaseEditor();
71
+ this.base.invalidate();
72
+ }
73
+
74
+ override getText(): string {
75
+ return this.base.getText();
76
+ }
77
+
78
+ override setText(text: string): void {
79
+ this.syncBaseEditor();
80
+ this.base.setText(text);
81
+ }
82
+
83
+ override getExpandedText(): string {
84
+ return this.base.getExpandedText?.() ?? this.base.getText();
85
+ }
86
+
87
+ override addToHistory(text: string): void {
88
+ this.base.addToHistory?.(text);
89
+ }
90
+
91
+ override insertTextAtCursor(text: string): void {
92
+ this.syncBaseEditor();
93
+ this.base.insertTextAtCursor?.(text);
94
+ }
95
+
96
+ override setAutocompleteProvider(provider: AutocompleteProvider): void {
97
+ this.base.setAutocompleteProvider?.(provider);
98
+ }
99
+
100
+ override setPaddingX(padding: number): void {
101
+ this.base.setPaddingX?.(padding);
102
+ }
103
+
104
+ override setAutocompleteMaxVisible(maxVisible: number): void {
105
+ this.base.setAutocompleteMaxVisible?.(maxVisible);
106
+ }
107
+
108
+ override handleInput(data: string): void {
109
+ if (handleMicmeEditorInput(data, this.micmeHandlers)) return;
110
+ this.syncBaseEditor();
111
+ this.base.handleInput(data);
112
+ }
113
+
114
+ private adoptBaseAppHandlers(base: AppAwareEditor): void {
115
+ // Sharing the map makes Pi's later handler copy immediately visible to the wrapped CustomEditor.
116
+ this.actionHandlers = base.actionHandlers;
117
+ this.onEscape = base.onEscape;
118
+ this.onCtrlD = base.onCtrlD;
119
+ this.onPasteImage = base.onPasteImage;
120
+ this.onExtensionShortcut = base.onExtensionShortcut;
121
+ }
122
+
123
+ private syncBaseEditor(): void {
124
+ if ("focused" in this.base) this.base.focused = this.focused;
125
+ this.base.onSubmit = this.onSubmit;
126
+ this.base.onChange = this.onChange;
127
+ this.base.borderColor = this.borderColor;
128
+ if (!this.baseAppEditor) return;
129
+ this.baseAppEditor.onEscape = this.onEscape;
130
+ this.baseAppEditor.onCtrlD = this.onCtrlD;
131
+ this.baseAppEditor.onPasteImage = this.onPasteImage;
132
+ this.baseAppEditor.onExtensionShortcut = this.onExtensionShortcut;
133
+ }
134
+ }
135
+
136
+ function getAppAwareEditor(editor: EditorComponent): AppAwareEditor | undefined {
137
+ if (!("actionHandlers" in editor) || !(editor.actionHandlers instanceof Map)) return undefined;
138
+ return editor as AppAwareEditor;
139
+ }
140
+
29
141
  function handleMicmeEditorInput(data: string, handlers: MicmeEditorInputHandlers) {
30
142
  const printable = decodeKittyPrintable(data);
31
143
  let printableShortcut: string | undefined;
@@ -57,66 +169,7 @@ export function installMicmeEditorFallback(ctx: ExtensionContext, micmeHandlers:
57
169
  if (previousEditor) {
58
170
  ctx.ui.setEditorComponent((tui, theme, keybindings) => {
59
171
  const base = previousEditor(tui, theme, keybindings);
60
- return {
61
- get focused(): boolean {
62
- return Boolean((base as { focused?: boolean }).focused);
63
- },
64
- set focused(value: boolean) {
65
- if ("focused" in base) (base as { focused?: boolean }).focused = value;
66
- },
67
- get onSubmit(): ((text: string) => void) | undefined {
68
- return base.onSubmit;
69
- },
70
- set onSubmit(handler: ((text: string) => void) | undefined) {
71
- base.onSubmit = handler;
72
- },
73
- get onChange(): ((text: string) => void) | undefined {
74
- return base.onChange;
75
- },
76
- set onChange(handler: ((text: string) => void) | undefined) {
77
- base.onChange = handler;
78
- },
79
- get borderColor(): ((str: string) => string) | undefined {
80
- return base.borderColor;
81
- },
82
- set borderColor(handler: ((str: string) => string) | undefined) {
83
- base.borderColor = handler;
84
- },
85
- render(width: number) {
86
- return base.render(width);
87
- },
88
- invalidate() {
89
- base.invalidate();
90
- },
91
- getText() {
92
- return base.getText();
93
- },
94
- setText(text: string) {
95
- base.setText(text);
96
- },
97
- getExpandedText() {
98
- return base.getExpandedText?.() ?? base.getText();
99
- },
100
- addToHistory(text: string) {
101
- base.addToHistory?.(text);
102
- },
103
- insertTextAtCursor(text: string) {
104
- base.insertTextAtCursor?.(text);
105
- },
106
- setAutocompleteProvider(provider: AutocompleteProvider) {
107
- base.setAutocompleteProvider?.(provider);
108
- },
109
- setPaddingX(padding: number) {
110
- base.setPaddingX?.(padding);
111
- },
112
- setAutocompleteMaxVisible(maxVisible: number) {
113
- base.setAutocompleteMaxVisible?.(maxVisible);
114
- },
115
- handleInput(data: string) {
116
- if (handleMicmeEditorInput(data, micmeHandlers)) return;
117
- base.handleInput(data);
118
- },
119
- };
172
+ return new WrappedMicmeEditor(tui, theme, keybindings, base, micmeHandlers);
120
173
  });
121
174
  return;
122
175
  }