@senad-d/micme 0.2.0 → 0.3.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/CHANGELOG.md CHANGED
@@ -9,6 +9,9 @@ All notable changes to Micme will be documented in this file.
9
9
  - Document the scoped npm package name, `@senad-d/micme`, in install, diagnostics, update, and uninstall commands.
10
10
  - Add an interactive npm publishing script that prompts for a version, validates the package, creates the release commit/tag, and publishes with public scoped-package access.
11
11
  - Keep publication on hold until package name, metadata, security review, validation, and smoke tests are complete.
12
+ - Add explicit transcription backend selection with backend-specific `/micme conf` model rows, doctor diagnostics, schema, and docs.
13
+ - Store kept audio in sequential project directories under `./micme-rec/rec-###/` instead of the system temp directory.
14
+ - Make the recorder quality-safe by default: preserve recorder timing from ffmpeg timestamps, disable the stdout meter branch, and ask macOS AVFoundation not to drop late frames.
12
15
 
13
16
  ## 0.1.0 - 2026-06-18
14
17
 
package/README.md CHANGED
@@ -15,7 +15,18 @@
15
15
 
16
16
  ---
17
17
 
18
- Micme is a pi extension for short coding prompts. It records your microphone with `ffmpeg`, transcribes locally with `whisper.cpp` or another local backend, and inserts the transcript into pi.
18
+ MicMe is a pi extension for short coding prompts. It records your microphone with `ffmpeg`, transcribes locally with `whisper.cpp` or another local backend, and inserts the transcript into pi.
19
+
20
+ <table align="center">
21
+ <tr>
22
+ <th>MicMe demo</th>
23
+ </tr>
24
+ <tr>
25
+ <td align="center">
26
+ <img src="img/demo.gif" alt="MicMe demo: record voice and paste the transcript into pi" title="MicMe demo" width="760">
27
+ </td>
28
+ </tr>
29
+ </table>
19
30
 
20
31
  - **Local-first:** no telemetry and no cloud STT service by default.
21
32
  - **Review-first:** transcripts paste into the editor unless you enable auto-submit.
@@ -109,7 +120,7 @@ Micme does not bundle recorder, transcriber, or model binaries.
109
120
 
110
121
  | OS | Install | Device setting |
111
122
  | --- | --- | --- |
112
- | macOS | `brew install ffmpeg whisper-cpp` | `MICME_AUDIO_DEVICE=0` or `MICME_AVFOUNDATION_INPUT=:0` |
123
+ | macOS | `brew install ffmpeg whisper-cpp` | Run `/micme devices`, then set `MICME_AUDIO_DEVICE=<audio id>` or `MICME_AVFOUNDATION_INPUT=:<audio id>`. |
113
124
  | Linux | Install `ffmpeg` and `whisper.cpp` with your package manager, Nix, Homebrew, or source build. | `MICME_PULSE_SOURCE=default` |
114
125
  | Windows | `winget install Gyan.FFmpeg`, then install/build `whisper.cpp`. | `MICME_DSHOW_AUDIO_DEVICE=Microphone Name` |
115
126
 
@@ -150,6 +161,7 @@ You can also edit the JSON manually. Minimal `~/.pi/agent/micme.json`:
150
161
  {
151
162
  "$schema": "https://raw.githubusercontent.com/senad-d/micme/main/micme.schema.json",
152
163
  "MICME_LANGUAGE": "en",
164
+ "MICME_TRANSCRIBE_BACKEND": "auto",
153
165
  "MICME_AUTO_DOWNLOAD_MODEL": "1",
154
166
  "MICME_DEFAULT_WHISPER_CPP_MODEL": "small.en",
155
167
  "MICME_AUTO_SUBMIT": "0",
@@ -163,16 +175,20 @@ Common settings:
163
175
 
164
176
  | Variable | Meaning |
165
177
  | --- | --- |
178
+ | `MICME_TRANSCRIBE_BACKEND=auto` | Backend selector. `auto` preserves priority: custom command, whisper.cpp, then Python Whisper. |
166
179
  | `MICME_TRANSCRIPTION_MODE=clip` | Stable default: transcribe after recording stops. |
167
- | `MICME_TRANSCRIPTION_MODE=stream` | Experimental append-only live dictation with `whisper-stream`. |
180
+ | `MICME_TRANSCRIPTION_MODE=stream` | Experimental append-only live dictation with `whisper-stream`; requires whisper.cpp. |
168
181
  | `MICME_STREAM_KEEP_CONTEXT=0` | Stream default: avoid Whisper prompt carry-over so live chunks are less likely to rewrite each other. |
169
182
  | `MICME_STREAM_FLUSH_MS=650` | Stream profile quiet interval before tentative words are committed append-only. |
170
183
  | `MICME_STREAM_FINALIZE_WITH_CLIP=0` | Keep the append-only live transcript on stop. Set `1` to opt in to final clip replacement. |
171
184
  | `MICME_AUTO_SUBMIT=0` | Paste for review. Set `1` to send automatically. |
172
- | `MICME_SHORTCUT=alt+m` | Toggle shortcut. Restart or `/reload` after changing. |
173
- | `MICME_PRINTABLE_SHORTCUTS=§` | macOS Option-key fallback. |
185
+ | `MICME_SHORTCUT=alt+m` | Toggle shortcut. Use terminal syntax (`alt+m`, `ctrl+space`, `f8`) or a printable character such as `§`. Restart or `/reload` after changing. |
174
186
  | `MICME_VALIDATE_AUDIO=1` | Reject near-silent recordings. |
175
- | `MICME_KEEP_AUDIO=0` | Delete successful temp audio. Set `1` for debugging. |
187
+ | `MICME_RECORD_SAMPLE_RATE=auto` | Raw recording sample-rate override. Leave `auto` so ffmpeg uses the selected input's native rate. |
188
+ | `MICME_RECORD_SYNC=1` | Automatically preserve wall-clock recording duration from ffmpeg timestamps. |
189
+ | `MICME_RECORD_METER=0` | Quality-safe default: meter from `raw.wav` instead of a second ffmpeg stdout branch. Set `1` to restore the legacy live meter pipe. |
190
+ | `MICME_AVFOUNDATION_DROP_LATE_FRAMES=0` | macOS only: ask AVFoundation not to drop late frames when capture lags. |
191
+ | `MICME_KEEP_AUDIO=0` | Delete successful recording audio. Set `1` to keep each recording under `./micme-rec/rec-###/` for debugging. |
176
192
  | `MICME_MODEL_DIR=~/.cache/whisper.cpp` | Model cache/discovery directory. |
177
193
 
178
194
  See [`micme.example.json`](micme.example.json) for the full JSON template.
@@ -196,9 +212,14 @@ Streaming mode treats `whisper-stream` output as repeated, overlapping hypothese
196
212
 
197
213
  ## Models and Backends
198
214
 
199
- Default backend: `whisper.cpp` via `whisper-cli`.
215
+ Micme supports these backend values in JSON/env config:
200
216
 
201
- With `MICME_AUTO_DOWNLOAD_MODEL=1`, Micme downloads missing standard models into `MICME_MODEL_DIR`. Disable downloads with:
217
+ - `whisper.cpp`: uses `whisper-cli`/`whisper-cpp` and a ggml/gguf model path.
218
+ - `python`: uses the OpenAI Whisper `whisper` CLI and a Python model name.
219
+
220
+ `/micme conf` keeps the interactive backend picker focused on `whisper.cpp` and `Python Whisper`, then shows only the model/binary fields for the selected backend. For whisper.cpp, `MICME_WHISPER_CPP_MODEL` is the selected ggml/gguf model path; if it is unset, Micme falls back to `${MICME_MODEL_DIR}/ggml-${MICME_DEFAULT_WHISPER_CPP_MODEL}.bin`. For Python Whisper, `MICME_WHISPER_MODEL` is passed as the CLI model name.
221
+
222
+ With `MICME_AUTO_DOWNLOAD_MODEL=1`, Micme downloads missing standard whisper.cpp models into `MICME_MODEL_DIR`. Disable downloads with:
202
223
 
203
224
  ```env
204
225
  MICME_AUTO_DOWNLOAD_MODEL=0
@@ -209,7 +230,7 @@ Recommended model progression: `base.en` for speed, `small.en` for a stronger de
209
230
  Advanced users can replace the recorder or transcriber:
210
231
 
211
232
  ```env
212
- MICME_RECORD_COMMAND=ffmpeg -hide_banner -loglevel error -f avfoundation -i :0 -ac 1 -ar 16000 -y {audio}
233
+ MICME_RECORD_COMMAND=ffmpeg -hide_banner -loglevel error -f avfoundation -i :0 -af aresample=async=1:first_pts=0 -ac 1 -y {audio}
213
234
  MICME_TRANSCRIBE_COMMAND=whisper-cli -m /path/to/model.bin -f {audio} -otxt -of {tempDirRaw}/out -nt -np && cat {tempDirRaw}/out.txt
214
235
  ```
215
236
 
@@ -221,8 +242,9 @@ MICME_TRANSCRIBE_COMMAND=whisper-cli -m /path/to/model.bin -f {audio} -otxt -of
221
242
 
222
243
  | Problem | Try |
223
244
  | --- | --- |
224
- | No backend found | Install `whisper.cpp`, put `whisper-cli` on `PATH`, or set `MICME_WHISPER_CPP_BIN`. |
245
+ | No backend found | Use `/micme conf` to choose `whisper.cpp` or Python Whisper, install the selected backend, or configure a trusted custom command manually. |
225
246
  | Wrong microphone | Run `/micme devices`, then set the OS-specific device variable. |
247
+ | Crackling or shortened audio | Keep `MICME_RECORD_SYNC=1` and `MICME_RECORD_METER=0`; on macOS keep `MICME_AVFOUNDATION_DROP_LATE_FRAMES=0`, and avoid Aggregate/BlackHole devices unless intentionally routing audio. |
226
248
  | Unrelated transcript | You probably recorded silence. Set `MICME_KEEP_AUDIO=1` and check `/micme audio`. |
227
249
  | Slow transcription | Use `whisper.cpp`, a smaller model, and shorter recordings. |
228
250
  | Option/Alt inserts `§` or `µ` | Set `MICME_PRINTABLE_SHORTCUTS=§` or change `MICME_SHORTCUT`, then `/reload`. |
@@ -242,7 +264,7 @@ From a source checkout:
242
264
  npm run doctor
243
265
  ```
244
266
 
245
- The doctor checks Node, pi, `ffmpeg`, whisper.cpp, optional `whisper-stream`, model paths, and macOS devices when available. Custom command values are redacted.
267
+ The doctor checks Node, pi, `ffmpeg`, requested/effective backend, effective model, whisper.cpp, optional `whisper-stream`, model paths, and macOS devices when available. Custom command values are redacted.
246
268
 
247
269
  For stream state investigation, start pi with `MICME_STREAM_DIAGNOSTICS=1`. Diagnostics are opt-in and include sanitized frames, extraction mode, committed words, and tentative candidate words.
248
270
 
package/SECURITY.md CHANGED
@@ -23,7 +23,7 @@ The default recorder uses `ffmpeg` and your operating system's microphone APIs:
23
23
  - Linux: PulseAudio through `ffmpeg -f pulse`
24
24
  - Windows: DirectShow through `ffmpeg -f dshow`
25
25
 
26
- Micme writes temporary audio files under the operating system temp directory while a recording is being processed. After successful transcription, those files are removed by default. Set `MICME_KEEP_AUDIO=1` only when you intentionally want to keep the last raw/preprocessed audio for debugging.
26
+ Micme writes temporary audio files under the operating system temp directory by default. After successful transcription, those files are removed. Set `MICME_KEEP_AUDIO=1` only when you intentionally want to keep raw/preprocessed audio for debugging; kept recordings are written to per-recording project directories such as `./micme-rec/rec-001/`.
27
27
 
28
28
  ## Local process execution
29
29
 
@@ -39,7 +39,7 @@ The default process output is capped before it is shown to users or errors. Diag
39
39
 
40
40
  ## Custom command risks
41
41
 
42
- `MICME_RECORD_COMMAND` and `MICME_TRANSCRIBE_COMMAND` are advanced escape hatches. They run through the local shell (`sh -lc` on Unix-like systems and `cmd.exe` on Windows). Only use commands you wrote or fully trust.
42
+ `MICME_RECORD_COMMAND` and `MICME_TRANSCRIBE_COMMAND` are advanced escape hatches. They run through the local shell (`sh -lc` on Unix-like systems and `cmd.exe` on Windows). Only use commands you wrote or fully trust. When `MICME_TRANSCRIBE_BACKEND=custom`, Micme does not try to inspect, parse, or rewrite the command to infer which model it uses.
43
43
 
44
44
  Micme replaces these placeholders in custom commands:
45
45
 
@@ -59,7 +59,7 @@ Disable model downloads with:
59
59
  MICME_AUTO_DOWNLOAD_MODEL=0
60
60
  ```
61
61
 
62
- You can also download models manually and set `MICME_WHISPER_CPP_MODEL=/path/to/model.bin`.
62
+ You can also download models manually and set `MICME_WHISPER_CPP_MODEL=/path/to/model.bin`. Micme only auto-downloads standard, inferable whisper.cpp model files and does not treat arbitrary custom-command model references as downloadable assets.
63
63
 
64
64
  ## Micme config handling
65
65
 
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "$schema": "https://raw.githubusercontent.com/senad-d/micme/main/micme.schema.json",
3
3
  "MICME_SHORTCUT": "alt+m",
4
- "MICME_PRINTABLE_SHORTCUTS": "§",
5
4
  "MICME_TRANSCRIPTION_MODE": "clip",
5
+ "MICME_TRANSCRIBE_BACKEND": "auto",
6
6
  "MICME_AUTO_SUBMIT": "0",
7
7
  "MICME_LANGUAGE": "en",
8
8
  "MICME_TRANSCRIBE_TIMEOUT_MS": "120000",
@@ -10,8 +10,11 @@
10
10
  "MICME_DEFAULT_WHISPER_CPP_MODEL": "small.en",
11
11
  "MICME_MODEL_DIR": "${HOME}/.cache/whisper.cpp",
12
12
  "MICME_AUDIO_DEVICE": "0",
13
- "MICME_RECORD_SAMPLE_RATE": "48000",
13
+ "MICME_RECORD_SAMPLE_RATE": "auto",
14
14
  "MICME_TRANSCRIBE_SAMPLE_RATE": "16000",
15
+ "MICME_RECORD_SYNC": "1",
16
+ "MICME_RECORD_METER": "0",
17
+ "MICME_AVFOUNDATION_DROP_LATE_FRAMES": "0",
15
18
  "MICME_PROCESS_AUDIO": "1",
16
19
  "MICME_AUDIO_FILTER": "highpass=f=80,lowpass=f=7600",
17
20
  "MICME_VALIDATE_AUDIO": "1",
package/micme.schema.json CHANGED
@@ -10,17 +10,25 @@
10
10
  },
11
11
  "MICME_SHORTCUT": {
12
12
  "type": "string",
13
- "default": "alt+m"
13
+ "default": "alt+m",
14
+ "description": "Unified toggle shortcut. Use terminal syntax such as alt+m/ctrl+space/f8, or a printable character such as §."
14
15
  },
15
16
  "MICME_PRINTABLE_SHORTCUTS": {
16
17
  "type": "string",
17
- "default": "§"
18
+ "default": "§",
19
+ "description": "Legacy printable-character fallback. Prefer MICME_SHORTCUT with a printable character."
18
20
  },
19
21
  "MICME_TRANSCRIPTION_MODE": {
20
22
  "type": "string",
21
23
  "enum": ["clip", "stream"],
22
24
  "default": "clip"
23
25
  },
26
+ "MICME_TRANSCRIBE_BACKEND": {
27
+ "type": "string",
28
+ "enum": ["auto", "whisper.cpp", "python", "custom"],
29
+ "default": "auto",
30
+ "description": "Select transcription backend. auto preserves priority: custom command, whisper.cpp, then Python Whisper."
31
+ },
24
32
  "MICME_AUTO_SUBMIT": {
25
33
  "$ref": "#/$defs/stringFlag"
26
34
  },
@@ -33,7 +41,21 @@
33
41
  },
34
42
  "MICME_DEFAULT_WHISPER_CPP_MODEL": {
35
43
  "type": "string",
36
- "default": "small.en"
44
+ "default": "small.en",
45
+ "description": "whisper.cpp model name mapped to MICME_MODEL_DIR/ggml-<name>.bin unless MICME_WHISPER_CPP_MODEL is set."
46
+ },
47
+ "MICME_WHISPER_CPP_MODEL": {
48
+ "type": "string",
49
+ "description": "Advanced whisper.cpp exact ggml/gguf model path override. When set, it wins over MICME_DEFAULT_WHISPER_CPP_MODEL."
50
+ },
51
+ "MICME_WHISPER_CPP_BIN": {
52
+ "type": "string",
53
+ "description": "Command or path for whisper.cpp clip transcription. Leave unset to find whisper-cli/whisper-cpp on PATH."
54
+ },
55
+ "MICME_WHISPER_MODEL": {
56
+ "type": "string",
57
+ "default": "base.en",
58
+ "description": "Model name passed to the OpenAI Whisper Python CLI when the Python backend is used."
37
59
  },
38
60
  "MICME_MODEL_DIR": {
39
61
  "type": "string",
@@ -43,6 +65,28 @@
43
65
  "type": "string",
44
66
  "default": "0"
45
67
  },
68
+ "MICME_RECORD_SAMPLE_RATE": {
69
+ "type": ["string", "number"],
70
+ "default": "auto",
71
+ "description": "Raw recording sample-rate override. Leave auto/unset so ffmpeg uses the selected input's native sample rate."
72
+ },
73
+ "MICME_RECORD_SYNC": {
74
+ "$ref": "#/$defs/stringFlag",
75
+ "default": "1",
76
+ "description": "Preserve wall-clock recording duration from ffmpeg timestamps with aresample async correction. Defaults on."
77
+ },
78
+ "MICME_RECORD_METER": {
79
+ "$ref": "#/$defs/stringFlag",
80
+ "description": "Enable the legacy ffmpeg stdout PCM branch for live metering. Defaults off to avoid recorder backpressure; the UI can still meter by polling raw.wav."
81
+ },
82
+ "MICME_AVFOUNDATION_DROP_LATE_FRAMES": {
83
+ "$ref": "#/$defs/stringFlag",
84
+ "description": "macOS AVFoundation only. Defaults off so ffmpeg is asked not to drop late frames when capture lags."
85
+ },
86
+ "MICME_AVFOUNDATION_INPUT_SAMPLE_RATE": {
87
+ "type": ["string", "number"],
88
+ "description": "Advanced macOS fallback used only when MICME_RECORD_SYNC=0. Reinterpret input samples with this source rate before resampling."
89
+ },
46
90
  "MICME_KEEP_AUDIO": {
47
91
  "$ref": "#/$defs/stringFlag"
48
92
  },
@@ -65,7 +109,7 @@
65
109
  },
66
110
  "MICME_TRANSCRIBE_COMMAND": {
67
111
  "type": "string",
68
- "description": "Advanced shell command hook. Use only trusted commands."
112
+ "description": "Advanced custom transcription shell command. Use only trusted commands; Micme cannot inspect which model it uses."
69
113
  }
70
114
  },
71
115
  "patternProperties": {
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "@senad-d/micme",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "type": "module",
5
- "description": "Local voice-to-text for pi, optimized for fast Whisper-style backends.",
5
+ "description": "Local voice dictation for Pi coding prompts. Press Alt+M, speak, review, send.",
6
6
  "license": "MIT",
7
7
  "author": "Senad Dizdarević <112484166+senad-d@users.noreply.github.com>",
8
8
  "repository": {
@@ -16,12 +16,22 @@
16
16
  "keywords": [
17
17
  "pi-package",
18
18
  "pi-extension",
19
+ "pi-agent",
20
+ "pi-coding-agent",
19
21
  "voice-to-text",
20
22
  "speech-to-text",
23
+ "voice-input",
21
24
  "dictation",
22
25
  "whisper",
23
- "whisper.cpp",
24
- "local-first"
26
+ "whisper-cpp",
27
+ "local-first",
28
+ "offline",
29
+ "privacy",
30
+ "developer-tools",
31
+ "cli",
32
+ "terminal",
33
+ "typescript",
34
+ "coding-agent"
25
35
  ],
26
36
  "engines": {
27
37
  "node": ">=22.19.0"
@@ -45,7 +55,7 @@
45
55
  "scripts": {
46
56
  "doctor": "node scripts/doctor.mjs",
47
57
  "check": "node --check scripts/doctor.mjs && node --check scripts/check-package-contents.mjs && node --check scripts/publish-npm.mjs",
48
- "test": "node --test test/streaming.test.mjs",
58
+ "test": "node --test test/*.test.mjs",
49
59
  "typecheck": "tsc --noEmit",
50
60
  "pack:dry-run": "npm pack --dry-run --json",
51
61
  "check:pack": "node scripts/check-package-contents.mjs",
@@ -56,7 +66,8 @@
56
66
  "pi": {
57
67
  "extensions": [
58
68
  "./src/extension.ts"
59
- ]
69
+ ],
70
+ "image": "https://raw.githubusercontent.com/senad-d/micme/main/img/demo.gif"
60
71
  },
61
72
  "peerDependencies": {
62
73
  "@earendil-works/pi-coding-agent": "*",
@@ -13,6 +13,7 @@ const forbiddenChecks = [
13
13
  { label: "node_modules", test: (path) => path.startsWith("node_modules/") || path.includes("/node_modules/") },
14
14
  { label: "planning specs", test: (path) => path.startsWith("specs/") },
15
15
  { label: "Micme cache", test: (path) => path.startsWith(".micme/") || path.includes("/.micme/") },
16
+ { label: "Micme recordings", test: (path) => path.startsWith("micme-rec/") || path.includes("/micme-rec/") },
16
17
  { label: "token insight files", test: (path) => path.includes("token-insights") },
17
18
  { label: "npm tarballs", test: (path) => /(^|\/)micme-[^/]+\.tgz$/i.test(path) || path.endsWith(".tgz") },
18
19
  { label: "audio artifacts", test: (path) => /\.(wav|mp3|m4a|flac|ogg|opus|aiff?|pcm)$/i.test(path) },
@@ -7,6 +7,8 @@ import { execFileSync, spawnSync } from "node:child_process";
7
7
 
8
8
  const isWin = process.platform === "win32";
9
9
  const micmeConfig = loadMicmeConfig();
10
+ const DEFAULT_TRANSCRIBE_BACKEND = "auto";
11
+ const TRANSCRIBE_BACKENDS = new Set(["auto", "whisper.cpp", "python", "custom"]);
10
12
 
11
13
  function getMicmeConfigPath() {
12
14
  const agentDir = process.env.PI_CODING_AGENT_DIR ? resolve(process.env.PI_CODING_AGENT_DIR) : join(homedir(), ".pi", "agent");
@@ -91,6 +93,94 @@ function summarizeConfiguredCommand(value) {
91
93
  return `configured (${trimmed.length} chars${placeholderText}; full value redacted)`;
92
94
  }
93
95
 
96
+ function getTranscribeBackend() {
97
+ const raw = env("MICME_TRANSCRIBE_BACKEND")?.trim();
98
+ return TRANSCRIBE_BACKENDS.has(raw) ? raw : DEFAULT_TRANSCRIBE_BACKEND;
99
+ }
100
+
101
+ function getTranscriptionMode() {
102
+ return env("MICME_TRANSCRIPTION_MODE") === "stream" ? "stream" : "clip";
103
+ }
104
+
105
+ function resolveWhisperCppModelSummary() {
106
+ const explicit = envPath("MICME_WHISPER_CPP_MODEL");
107
+ if (explicit) {
108
+ return {
109
+ path: explicit,
110
+ source: "MICME_WHISPER_CPP_MODEL explicit path",
111
+ exists: existsSync(explicit),
112
+ };
113
+ }
114
+ const defaultModel = env("MICME_DEFAULT_WHISPER_CPP_MODEL") || "small.en";
115
+ const modelDir = expandConfigValue(env("MICME_MODEL_DIR") || join(homedir(), ".cache", "whisper.cpp"));
116
+ const path = join(modelDir, `ggml-${defaultModel}.bin`);
117
+ return {
118
+ path,
119
+ modelName: defaultModel,
120
+ source: env("MICME_DEFAULT_WHISPER_CPP_MODEL") ? "MICME_DEFAULT_WHISPER_CPP_MODEL" : "default whisper.cpp model name",
121
+ exists: existsSync(path),
122
+ };
123
+ }
124
+
125
+ function resolveBackendPlan({ whisperCpp, whisperStream, whisper, transcribeCommand }) {
126
+ const requestedBackend = getTranscribeBackend();
127
+ const mode = getTranscriptionMode();
128
+ const whisperCppAvailable = Boolean(whisperCpp && existsSync(whisperCpp));
129
+ const whisperStreamAvailable = Boolean(whisperStream && existsSync(whisperStream));
130
+ const pythonAvailable = Boolean(whisper && existsSync(whisper));
131
+ const model = resolveWhisperCppModelSummary();
132
+ const warnings = [];
133
+
134
+ const invalidBackend = env("MICME_TRANSCRIBE_BACKEND")?.trim();
135
+ if (invalidBackend && !TRANSCRIBE_BACKENDS.has(invalidBackend)) warnings.push(`Invalid MICME_TRANSCRIBE_BACKEND=${invalidBackend}; using auto.`);
136
+
137
+ if (mode === "stream") {
138
+ if (requestedBackend === "python") {
139
+ return { requestedBackend, effectiveBackend: "none", effectiveModel: "unavailable", reason: "Streaming mode requires whisper.cpp; Python Whisper only supports clip transcription.", warnings };
140
+ }
141
+ if (requestedBackend === "custom") {
142
+ return { requestedBackend, effectiveBackend: "none", effectiveModel: "unavailable", reason: "Streaming mode requires whisper.cpp; custom transcribe commands only support clip transcription.", warnings };
143
+ }
144
+ if (whisperStreamAvailable) {
145
+ return { requestedBackend, effectiveBackend: "whisper.cpp", binary: whisperStream, model, effectiveModel: model.path, reason: "streaming uses whisper-stream", warnings };
146
+ }
147
+ return { requestedBackend, effectiveBackend: "none", effectiveModel: "unavailable", reason: "MICME_TRANSCRIPTION_MODE=stream but whisper-stream was not found.", warnings };
148
+ }
149
+
150
+ if (requestedBackend === "custom") {
151
+ if (transcribeCommand?.trim()) return { requestedBackend, effectiveBackend: "custom", effectiveModel: "unknown", reason: "MICME_TRANSCRIBE_BACKEND=custom", warnings };
152
+ return { requestedBackend, effectiveBackend: "none", effectiveModel: "unavailable", reason: "MICME_TRANSCRIBE_BACKEND=custom but MICME_TRANSCRIBE_COMMAND is not set.", warnings };
153
+ }
154
+ if (requestedBackend === "whisper.cpp") {
155
+ if (whisperCppAvailable) return { requestedBackend, effectiveBackend: "whisper.cpp", binary: whisperCpp, model, effectiveModel: model.path, reason: "MICME_TRANSCRIBE_BACKEND=whisper.cpp", warnings };
156
+ return { requestedBackend, effectiveBackend: "none", effectiveModel: "unavailable", reason: "MICME_TRANSCRIBE_BACKEND=whisper.cpp but whisper.cpp was not found.", warnings };
157
+ }
158
+ if (requestedBackend === "python") {
159
+ if (pythonAvailable) return { requestedBackend, effectiveBackend: "python", binary: whisper, effectiveModel: env("MICME_WHISPER_MODEL") || "base.en", reason: "MICME_TRANSCRIBE_BACKEND=python", warnings };
160
+ return { requestedBackend, effectiveBackend: "none", effectiveModel: "unavailable", reason: "MICME_TRANSCRIBE_BACKEND=python but the `whisper` CLI was not found.", warnings };
161
+ }
162
+
163
+ if (transcribeCommand?.trim()) return { requestedBackend, effectiveBackend: "custom", effectiveModel: "unknown", reason: "auto selected custom command because MICME_TRANSCRIBE_COMMAND is configured", warnings };
164
+ if (whisperCppAvailable) return { requestedBackend, effectiveBackend: "whisper.cpp", binary: whisperCpp, model, effectiveModel: model.path, reason: "auto selected whisper.cpp because a whisper.cpp binary is available", warnings };
165
+ if (pythonAvailable) return { requestedBackend, effectiveBackend: "python", binary: whisper, effectiveModel: env("MICME_WHISPER_MODEL") || "base.en", reason: "auto selected Python Whisper because whisper.cpp is unavailable", warnings };
166
+ return { requestedBackend, effectiveBackend: "none", effectiveModel: "unavailable", reason: "No Micme transcription backend found.", warnings };
167
+ }
168
+
169
+ function printBackendPlanDiagnostics(plan) {
170
+ info("requested backend", plan.requestedBackend);
171
+ if (plan.effectiveBackend === "none") warn("effective backend", plan.reason);
172
+ else ok("effective backend", `${plan.effectiveBackend} (${plan.reason})`);
173
+
174
+ if (plan.effectiveBackend === "custom") info("effective model", "unknown; controlled by MICME_TRANSCRIBE_COMMAND");
175
+ else if (plan.effectiveBackend === "whisper.cpp") {
176
+ info("effective model", `${plan.effectiveModel} (${plan.model?.source || "whisper.cpp model"})`);
177
+ if (plan.model && !plan.model.exists) warn("effective whisper.cpp model is missing", plan.effectiveModel);
178
+ } else if (plan.effectiveBackend === "python") info("effective model", plan.effectiveModel);
179
+ else info("effective model", "unavailable");
180
+
181
+ for (const warning of plan.warnings) warn("backend warning", warning);
182
+ }
183
+
94
184
  function printConfigDiagnostics() {
95
185
  if (micmeConfig.error) warn("micme.json invalid", `${micmeConfig.path}: ${micmeConfig.error}`);
96
186
  else if (micmeConfig.found) ok("micme.json loaded", `${micmeConfig.path} (${Object.keys(micmeConfig.values).length} MICME_* key(s))`);
@@ -152,6 +242,8 @@ async function main() {
152
242
  if (transcribeCommand) ok("custom transcribe command", summarizeConfiguredCommand(transcribeCommand));
153
243
  else info("custom transcribe command", "not set");
154
244
 
245
+ printBackendPlanDiagnostics(resolveBackendPlan({ whisperCpp, whisperStream, whisper, transcribeCommand }));
246
+
155
247
  const recordCommand = env("MICME_RECORD_COMMAND");
156
248
  if (recordCommand) ok("custom record command", summarizeConfiguredCommand(recordCommand));
157
249
  else info("custom record command", "not set");
package/src/audio.ts CHANGED
@@ -2,7 +2,7 @@ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-a
2
2
  import { sliceByColumn, visibleWidth, type Component } from "@earendil-works/pi-tui";
3
3
  import { join } from "node:path";
4
4
  import { AUDIO_VALIDATION_TIMEOUT_MS } from "./constants.ts";
5
- import { env, envFlag, getAudioFilter, getMinMaxVolumeDb, getRecordSampleRate, getTranscribeSampleRate } from "./config.ts";
5
+ import { env, envFlag, getAudioFilter, getAvfoundationDropLateFrames, getAvfoundationInputSampleRate, getMinMaxVolumeDb, getRecordMeter, getRecordSampleRate, getRecordSync, getTranscribeSampleRate } from "./config.ts";
6
6
  import { findExecutable, formatRunExit, replacePlaceholders, runProcess, shellCommand, shellQuote } from "./processes.ts";
7
7
  import type { AudioDeviceCandidate, AudioDiagnostics, CommandSpec, RunResult } from "./types.ts";
8
8
 
@@ -58,6 +58,7 @@ const DEVICE_PANEL_MESSAGE_TYPE = "micme-devices";
58
58
  const DEVICE_PANEL_DEFAULT_WIDTH = 92;
59
59
  const DEVICE_PANEL_MAX_WIDTH = 100;
60
60
  const DEVICE_PANEL_MIN_WIDTH = 36;
61
+ const RECORD_TIMING_SYNC_FILTER = "aresample=async=1:first_pts=0";
61
62
 
62
63
  let deviceMessageRendererRegistered = false;
63
64
 
@@ -337,7 +338,11 @@ function sendDevicePanelMessage(pi: ExtensionAPI | undefined, options: DevicePan
337
338
  }
338
339
 
339
340
  class DevicePanelMessageComponent implements Component {
340
- constructor(private readonly options: DevicePanelOptions) {}
341
+ private readonly options: DevicePanelOptions;
342
+
343
+ constructor(options: DevicePanelOptions) {
344
+ this.options = options;
345
+ }
341
346
 
342
347
  render(width: number): string[] {
343
348
  return renderDevicePanel(this.options, Math.min(width, DEVICE_PANEL_MAX_WIDTH)).split("\n");
@@ -644,31 +649,45 @@ export function buildRecorderCommand(audioPath: string): CommandSpec {
644
649
  throw new Error("Micme needs ffmpeg for recording, or set MICME_RECORD_COMMAND.");
645
650
  }
646
651
 
647
- const recordSampleRate = String(getRecordSampleRate());
652
+ const recordSampleRate = getRecordSampleRate()?.toString();
653
+ const recordMeter = getRecordMeter();
654
+ const recordSync = getRecordSync();
655
+ const timingFilters = recordSync ? [RECORD_TIMING_SYNC_FILTER] : [];
648
656
 
649
657
  if (process.platform === "darwin") {
650
658
  const input = env("MICME_AVFOUNDATION_INPUT") || `:${env("MICME_AUDIO_DEVICE") || "0"}`;
651
- const args = buildMeteredFfmpegRecorderArgs("avfoundation", input, audioPath, recordSampleRate);
652
- return { command: ffmpeg, args, display: `${ffmpeg} ${args.map(shellQuote).join(" ")}`, meterFromStdout: true, stopInput: "q\n" };
659
+ const avfoundationInputSampleRate = getAvfoundationInputSampleRate();
660
+ const args = buildFfmpegRecorderArgs("avfoundation", input, audioPath, recordSampleRate, {
661
+ meter: recordMeter,
662
+ inputOptions: ["-drop_late_frames", getAvfoundationDropLateFrames() ? "true" : "false"],
663
+ audioFilters: recordSync ? timingFilters : avfoundationInputSampleRate ? [`asetrate=${avfoundationInputSampleRate}`] : [],
664
+ });
665
+ return { command: ffmpeg, args, display: `${ffmpeg} ${args.map(shellQuote).join(" ")}`, meterFromStdout: recordMeter, stopInput: "q\n" };
653
666
  }
654
667
 
655
668
  if (process.platform === "linux") {
656
669
  const input = env("MICME_PULSE_SOURCE") || "default";
657
- const args = buildMeteredFfmpegRecorderArgs("pulse", input, audioPath, recordSampleRate);
658
- return { command: ffmpeg, args, display: `${ffmpeg} ${args.map(shellQuote).join(" ")}`, meterFromStdout: true, stopInput: "q\n" };
670
+ const args = buildFfmpegRecorderArgs("pulse", input, audioPath, recordSampleRate, { meter: recordMeter, audioFilters: timingFilters });
671
+ return { command: ffmpeg, args, display: `${ffmpeg} ${args.map(shellQuote).join(" ")}`, meterFromStdout: recordMeter, stopInput: "q\n" };
659
672
  }
660
673
 
661
674
  if (process.platform === "win32") {
662
675
  const input = `audio=${env("MICME_DSHOW_AUDIO_DEVICE") || "default"}`;
663
- const args = buildMeteredFfmpegRecorderArgs("dshow", input, audioPath, recordSampleRate);
664
- return { command: ffmpeg, args, display: `${ffmpeg} ${args.map(shellQuote).join(" ")}`, meterFromStdout: true, stopInput: "q\n" };
676
+ const args = buildFfmpegRecorderArgs("dshow", input, audioPath, recordSampleRate, { meter: recordMeter, audioFilters: timingFilters });
677
+ return { command: ffmpeg, args, display: `${ffmpeg} ${args.map(shellQuote).join(" ")}`, meterFromStdout: recordMeter, stopInput: "q\n" };
665
678
  }
666
679
 
667
680
  throw new Error(`Micme has no default recorder for ${process.platform}. Set MICME_RECORD_COMMAND.`);
668
681
  }
669
682
 
670
- export function buildMeteredFfmpegRecorderArgs(inputFormat: string, input: string, audioPath: string, recordSampleRate: string) {
671
- return [
683
+ type FfmpegRecorderOptions = {
684
+ meter?: boolean;
685
+ inputOptions?: string[];
686
+ audioFilters?: string[];
687
+ };
688
+
689
+ export function buildFfmpegRecorderArgs(inputFormat: string, input: string, audioPath: string, recordSampleRate: string | undefined, options: FfmpegRecorderOptions = {}) {
690
+ const inputArgs = [
672
691
  "-hide_banner",
673
692
  "-loglevel",
674
693
  "error",
@@ -676,21 +695,28 @@ export function buildMeteredFfmpegRecorderArgs(inputFormat: string, input: strin
676
695
  "4096",
677
696
  "-f",
678
697
  inputFormat,
698
+ ...(options.inputOptions ?? []),
679
699
  "-i",
680
700
  input,
701
+ ];
702
+ const fileOutputArgs = ["-ac", "1", ...formatOptionalSampleRateArgs(recordSampleRate), "-c:a", "pcm_s16le", "-vn", "-y", audioPath];
703
+ const audioFilters = (options.audioFilters ?? []).filter(Boolean);
704
+
705
+ if (options.meter === false && audioFilters.length === 0) {
706
+ return [...inputArgs, "-map", "0:a:0", ...fileOutputArgs];
707
+ }
708
+
709
+ if (options.meter === false) {
710
+ return [...inputArgs, "-filter_complex", buildFileOnlyAudioFilterGraph(audioFilters), "-map", "[micme_file]", ...fileOutputArgs];
711
+ }
712
+
713
+ return [
714
+ ...inputArgs,
681
715
  "-filter_complex",
682
- "[0:a]asplit=2[micme_file][micme_meter]",
716
+ buildMeteredAudioFilterGraph(audioFilters),
683
717
  "-map",
684
718
  "[micme_file]",
685
- "-ac",
686
- "1",
687
- "-ar",
688
- recordSampleRate,
689
- "-c:a",
690
- "pcm_s16le",
691
- "-vn",
692
- "-y",
693
- audioPath,
719
+ ...fileOutputArgs,
694
720
  "-map",
695
721
  "[micme_meter]",
696
722
  "-ac",
@@ -702,3 +728,20 @@ export function buildMeteredFfmpegRecorderArgs(inputFormat: string, input: strin
702
728
  "pipe:1",
703
729
  ];
704
730
  }
731
+
732
+ export function buildMeteredFfmpegRecorderArgs(inputFormat: string, input: string, audioPath: string, recordSampleRate: string | undefined) {
733
+ return buildFfmpegRecorderArgs(inputFormat, input, audioPath, recordSampleRate, { meter: true });
734
+ }
735
+
736
+ function formatOptionalSampleRateArgs(recordSampleRate: string | undefined) {
737
+ return recordSampleRate ? ["-ar", recordSampleRate] : [];
738
+ }
739
+
740
+ function buildFileOnlyAudioFilterGraph(audioFilters: string[]) {
741
+ return audioFilters.length > 0 ? `[0:a]${audioFilters.join(",")}[micme_file]` : "[0:a]anull[micme_file]";
742
+ }
743
+
744
+ function buildMeteredAudioFilterGraph(audioFilters: string[]) {
745
+ const prefix = audioFilters.length > 0 ? `${audioFilters.join(",")},` : "";
746
+ return `[0:a]${prefix}asplit=2[micme_file][micme_meter]`;
747
+ }