@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,162 @@
1
+ #!/usr/bin/env node
2
+ import { existsSync, readFileSync } from "node:fs";
3
+ import { access } from "node:fs/promises";
4
+ import { delimiter, join } from "node:path";
5
+ import { execFileSync, spawnSync } from "node:child_process";
6
+
7
+ const isWin = process.platform === "win32";
8
+ const dotEnv = loadDotEnv(process.cwd());
9
+
10
+ function loadDotEnv(cwd) {
11
+ const path = join(cwd, ".env");
12
+ if (!existsSync(path)) return { path: "", values: {} };
13
+ const values = {};
14
+ for (const rawLine of readFileSync(path, "utf8").replace(/^\uFEFF/, "").split(/\r?\n/)) {
15
+ const line = rawLine.trim();
16
+ if (!line || line.startsWith("#")) continue;
17
+ const match = line.match(/^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/);
18
+ if (!match || !match[1].startsWith("MICME_")) continue;
19
+ let value = match[2] || "";
20
+ if (value.startsWith('"') && value.endsWith('"')) value = value.slice(1, -1);
21
+ else if (value.startsWith("'") && value.endsWith("'")) value = value.slice(1, -1);
22
+ else value = value.replace(/\s+#.*$/, "").trim();
23
+ value = value.replace(/^~\//, `${process.env.HOME || ""}/`);
24
+ value = value.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)/g, (_m, braced, bare) => values[braced || bare] ?? process.env[braced || bare] ?? "");
25
+ values[match[1]] = value;
26
+ }
27
+ return { path, values };
28
+ }
29
+
30
+ function env(name) {
31
+ return process.env[name] ?? dotEnv.values[name];
32
+ }
33
+
34
+ function which(names) {
35
+ const pathDirs = (process.env.PATH || "").split(delimiter).filter(Boolean);
36
+ const exts = isWin ? (process.env.PATHEXT || ".EXE;.CMD;.BAT;.COM").split(";") : [""];
37
+ for (const name of names) {
38
+ for (const dir of pathDirs) {
39
+ for (const ext of exts) {
40
+ const candidate = join(dir, isWin && !/\.[^.]+$/.test(name) ? `${name}${ext}` : name);
41
+ if (existsSync(candidate)) return candidate;
42
+ }
43
+ }
44
+ }
45
+ return undefined;
46
+ }
47
+
48
+ function resolveExecutable(value) {
49
+ const expanded = value.replace(/^~\//, `${process.env.HOME || ""}/`);
50
+ if (/[\\/]/.test(expanded)) return expanded;
51
+ return which([expanded]) || expanded;
52
+ }
53
+
54
+ function ok(label, detail = "") {
55
+ console.log(`✓ ${label}${detail ? `: ${detail}` : ""}`);
56
+ }
57
+
58
+ function warn(label, detail = "") {
59
+ console.log(`! ${label}${detail ? `: ${detail}` : ""}`);
60
+ }
61
+
62
+ function info(label, detail = "") {
63
+ console.log(`- ${label}${detail ? `: ${detail}` : ""}`);
64
+ }
65
+
66
+ function summarizeConfiguredCommand(value) {
67
+ const trimmed = value.trim();
68
+ const placeholders = [...new Set([...trimmed.matchAll(/\{([A-Za-z]+?)(Raw)?\}/g)].map((match) => match[0]))];
69
+ const placeholderText = placeholders.length ? `; placeholders: ${placeholders.join(", ")}` : "";
70
+ return `configured (${trimmed.length} chars${placeholderText}; full value redacted)`;
71
+ }
72
+
73
+ async function main() {
74
+ console.log("Micme doctor\n");
75
+ info("platform", `${process.platform} ${process.arch}`);
76
+ info("node", process.version);
77
+ if (dotEnv.path) ok(".env loaded", dotEnv.path);
78
+ else info(".env", "not found");
79
+
80
+ const pi = which(["pi"]);
81
+ if (pi) ok("pi CLI", pi);
82
+ else warn("pi CLI not found", "install @earendil-works/pi-coding-agent or use this as a package from pi");
83
+
84
+ const ffmpeg = which(["ffmpeg"]);
85
+ if (ffmpeg) ok("ffmpeg recorder", ffmpeg);
86
+ else warn("ffmpeg recorder missing", "install ffmpeg or set MICME_RECORD_COMMAND");
87
+
88
+ const configuredWhisperCpp = env("MICME_WHISPER_CPP_BIN");
89
+ const whisperCpp = configuredWhisperCpp ? resolveExecutable(configuredWhisperCpp) : which(["whisper-cli", "whisper-cpp"]);
90
+ const whisperCppModel = env("MICME_WHISPER_CPP_MODEL");
91
+ if (whisperCpp && existsSync(whisperCpp)) ok("whisper.cpp binary", whisperCpp);
92
+ else if (configuredWhisperCpp) warn("MICME_WHISPER_CPP_BIN is set but not found", configuredWhisperCpp);
93
+ else warn("whisper.cpp binary missing", "recommended backend for portable local transcription");
94
+
95
+ const configuredWhisperStream = env("MICME_WHISPER_STREAM_BIN");
96
+ const whisperStream = configuredWhisperStream ? resolveExecutable(configuredWhisperStream) : which(["whisper-stream"]);
97
+ if (whisperStream && existsSync(whisperStream)) ok("whisper-stream binary", whisperStream);
98
+ else if (configuredWhisperStream) warn("MICME_WHISPER_STREAM_BIN is set but not found", configuredWhisperStream);
99
+ else info("whisper-stream binary", "not installed; only needed for MICME_TRANSCRIPTION_MODE=stream");
100
+
101
+ if (whisperCppModel) {
102
+ try {
103
+ await access(whisperCppModel);
104
+ ok("MICME_WHISPER_CPP_MODEL", whisperCppModel);
105
+ } catch {
106
+ const auto = env("MICME_AUTO_DOWNLOAD_MODEL") !== "0";
107
+ warn("MICME_WHISPER_CPP_MODEL is set but not readable", auto ? `${whisperCppModel} (Micme will try to download if it is a standard ggml model path)` : whisperCppModel);
108
+ }
109
+ } else {
110
+ const defaultModel = env("MICME_DEFAULT_WHISPER_CPP_MODEL") || "small.en";
111
+ const modelDir = env("MICME_MODEL_DIR") || `${process.env.HOME}/.cache/whisper.cpp`;
112
+ info("MICME_WHISPER_CPP_MODEL", `not set; Micme defaults to ${modelDir}/ggml-${defaultModel}.bin and auto-downloads when needed`);
113
+ }
114
+
115
+ const whisper = which(["whisper"]);
116
+ if (whisper) ok("openai-whisper fallback", whisper);
117
+ else info("openai-whisper fallback", "not installed");
118
+
119
+ const transcribeCommand = env("MICME_TRANSCRIBE_COMMAND");
120
+ if (transcribeCommand) ok("custom transcribe command", summarizeConfiguredCommand(transcribeCommand));
121
+ else info("custom transcribe command", "not set");
122
+
123
+ const recordCommand = env("MICME_RECORD_COMMAND");
124
+ if (recordCommand) ok("custom record command", summarizeConfiguredCommand(recordCommand));
125
+ else info("custom record command", "not set");
126
+
127
+ console.log("\nRecommended macOS setup:");
128
+ console.log(" brew install ffmpeg whisper-cpp");
129
+ console.log(" # Then use /micme conf, or let Micme auto-download ggml-small.en.bin on first use.");
130
+
131
+ if (process.platform === "darwin" && ffmpeg) {
132
+ console.log("\nmacOS microphone devices:");
133
+ const listed = spawnSync(ffmpeg, ["-hide_banner", "-f", "avfoundation", "-list_devices", "true", "-i", ""], {
134
+ encoding: "utf8",
135
+ timeout: 8000,
136
+ });
137
+ const deviceOutput = `${listed.stdout || ""}\n${listed.stderr || ""}`.trim();
138
+ if (deviceOutput) console.log(deviceOutput);
139
+ const macbookMic = deviceOutput.match(/\[(\d+)\]\s+MacBook Pro Microphone/i);
140
+ if (macbookMic) {
141
+ const current = env("MICME_AUDIO_DEVICE") || "0";
142
+ if (current !== macbookMic[1]) {
143
+ warn("MacBook Pro microphone is not the configured default", `try: export MICME_AUDIO_DEVICE=${macbookMic[1]}`);
144
+ }
145
+ }
146
+ console.log("\nSet MICME_AUDIO_DEVICE to the numeric audio device id if device 0 is wrong.");
147
+ }
148
+
149
+ if (ffmpeg) {
150
+ try {
151
+ const version = execFileSync(ffmpeg, ["-version"], { encoding: "utf8", timeout: 3000 }).split("\n")[0];
152
+ info("ffmpeg version", version);
153
+ } catch {
154
+ warn("could not read ffmpeg version");
155
+ }
156
+ }
157
+ }
158
+
159
+ main().catch((error) => {
160
+ console.error(error instanceof Error ? error.message : String(error));
161
+ process.exitCode = 1;
162
+ });
@@ -0,0 +1,51 @@
1
+ import { closeSync, openSync, readSync, statSync } from "node:fs";
2
+ import { getMeterFloorDb, getMeterGain, getMeterPeakFloorDb, getMeterRangeDb } from "./config.ts";
3
+
4
+ export function readPcm16WaveLevel(path: string) {
5
+ try {
6
+ const stats = statSync(path);
7
+ if (stats.size <= 44) return 0;
8
+
9
+ const maxBytes = 48_000;
10
+ const start = Math.max(44, stats.size - maxBytes);
11
+ const length = Math.max(0, stats.size - start);
12
+ if (length < 2) return 0;
13
+
14
+ const buffer = Buffer.alloc(length - (length % 2));
15
+ const fd = openSync(path, "r");
16
+ try {
17
+ readSync(fd, buffer, 0, buffer.length, start);
18
+ } finally {
19
+ closeSync(fd);
20
+ }
21
+
22
+ return pcm16BufferLevel(buffer);
23
+ } catch {
24
+ return 0;
25
+ }
26
+ }
27
+
28
+ export function pcm16BufferLevel(buffer: Buffer) {
29
+ let sumSquares = 0;
30
+ let peak = 0;
31
+ const samples = Math.floor(buffer.length / 2);
32
+ if (samples <= 0) return 0;
33
+
34
+ for (let offset = 0; offset + 1 < buffer.length; offset += 2) {
35
+ const sample = buffer.readInt16LE(offset) / 32768;
36
+ const abs = Math.abs(sample);
37
+ if (abs > peak) peak = abs;
38
+ sumSquares += sample * sample;
39
+ }
40
+
41
+ const rms = Math.sqrt(sumSquares / samples);
42
+ if (!Number.isFinite(rms) || rms <= 0) return 0;
43
+
44
+ const rmsDb = 20 * Math.log10(rms);
45
+ const peakDb = peak > 0 ? 20 * Math.log10(peak) : Number.NEGATIVE_INFINITY;
46
+ const rmsLevel = (rmsDb + getMeterFloorDb()) / getMeterRangeDb();
47
+ const peakLevel = (peakDb + getMeterPeakFloorDb()) / getMeterRangeDb();
48
+ const level = Math.max(rmsLevel, peakLevel * 0.8) * getMeterGain();
49
+ return Math.max(0, Math.min(1, level));
50
+ }
51
+
package/src/audio.ts ADDED
@@ -0,0 +1,199 @@
1
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import { join } from "node:path";
3
+ import { AUDIO_VALIDATION_TIMEOUT_MS } from "./constants.ts";
4
+ import { env, envFlag, getAudioFilter, getMinMaxVolumeDb, getRecordSampleRate, getTranscribeSampleRate } from "./config.ts";
5
+ import { findExecutable, formatRunExit, replacePlaceholders, runProcess, shellCommand, shellQuote } from "./processes.ts";
6
+ import type { AudioDeviceCandidate, AudioDiagnostics, CommandSpec, RunResult } from "./types.ts";
7
+
8
+ export async function listAudioDevices(ctx: ExtensionContext) {
9
+ const ffmpeg = findExecutable(["ffmpeg"]);
10
+ if (!ffmpeg) {
11
+ ctx.ui.notify("ffmpeg is not installed, so Micme cannot list audio devices.", "warning");
12
+ return;
13
+ }
14
+
15
+ let title = "Micme audio devices";
16
+ let result: RunResult;
17
+ if (process.platform === "darwin") {
18
+ result = await runProcess(ffmpeg, ["-hide_banner", "-f", "avfoundation", "-list_devices", "true", "-i", ""], 8_000);
19
+ title = "Micme macOS avfoundation devices";
20
+ } else if (process.platform === "linux") {
21
+ result = await runProcess(ffmpeg, ["-hide_banner", "-sources", "pulse"], 8_000);
22
+ title = "Micme Linux PulseAudio sources";
23
+ } else if (process.platform === "win32") {
24
+ result = await runProcess(ffmpeg, ["-hide_banner", "-list_devices", "true", "-f", "dshow", "-i", "dummy"], 8_000);
25
+ title = "Micme Windows DirectShow devices";
26
+ } else {
27
+ ctx.ui.notify(`Device listing is not implemented for ${process.platform}.`, "warning");
28
+ return;
29
+ }
30
+
31
+ const output = `${result.stdout}\n${result.stderr}`.trim() || "No device output.";
32
+ await ctx.ui.editor(title, output);
33
+ }
34
+
35
+ export async function discoverAudioDevices(): Promise<AudioDeviceCandidate[]> {
36
+ const ffmpeg = findExecutable(["ffmpeg"]);
37
+ if (!ffmpeg) return [];
38
+
39
+ if (process.platform === "darwin") {
40
+ const result = await runProcess(ffmpeg, ["-hide_banner", "-f", "avfoundation", "-list_devices", "true", "-i", ""], 8_000);
41
+ return parseAvfoundationAudioDevices(`${result.stdout}\n${result.stderr}`);
42
+ }
43
+
44
+ if (process.platform === "linux") {
45
+ return [{ label: "default", value: "default", description: "PulseAudio default source" }];
46
+ }
47
+
48
+ if (process.platform === "win32") {
49
+ return [{ label: "default", value: "default", description: "DirectShow default audio input" }];
50
+ }
51
+
52
+ return [];
53
+ }
54
+
55
+ export function parseAvfoundationAudioDevices(output: string): AudioDeviceCandidate[] {
56
+ const devices: AudioDeviceCandidate[] = [];
57
+ let inAudioDevices = false;
58
+ for (const line of output.split(/\r?\n/)) {
59
+ if (line.includes("AVFoundation audio devices:")) {
60
+ inAudioDevices = true;
61
+ continue;
62
+ }
63
+ if (inAudioDevices && line.includes("Error opening input")) break;
64
+ if (!inAudioDevices) continue;
65
+ const match = line.match(/\[(\d+)\]\s+(.+)$/);
66
+ if (!match) continue;
67
+ const value = match[1] ?? "";
68
+ const name = (match[2] ?? "").trim();
69
+ devices.push({ label: `${value}: ${name}`, value, description: name });
70
+ }
71
+ return devices;
72
+ }
73
+
74
+ export async function prepareAudioForTranscription(inputPath: string, tempDir: string) {
75
+ if (env("MICME_PROCESS_AUDIO") === "0") return inputPath;
76
+
77
+ const ffmpeg = findExecutable(["ffmpeg"]);
78
+ if (!ffmpeg) return inputPath;
79
+
80
+ const outputPath = join(tempDir, "clip.wav");
81
+ const filter = getAudioFilter();
82
+ const args = ["-hide_banner", "-loglevel", "error", "-y", "-i", inputPath];
83
+ if (filter) args.push("-af", filter);
84
+ args.push("-ac", "1", "-ar", String(getTranscribeSampleRate()), "-c:a", "pcm_s16le", outputPath);
85
+
86
+ const result = await runProcess(ffmpeg, args, AUDIO_VALIDATION_TIMEOUT_MS);
87
+ if (result.code !== 0) {
88
+ throw new Error(`Micme audio preprocessing failed (${formatRunExit(result)}):\n${result.stderr || result.stdout}`);
89
+ }
90
+
91
+ return outputPath;
92
+ }
93
+
94
+ export async function validateRecordedAudio(audioPath: string): Promise<AudioDiagnostics | undefined> {
95
+ if (env("MICME_VALIDATE_AUDIO") === "0" || envFlag("MICME_SKIP_AUDIO_VALIDATION")) return undefined;
96
+
97
+ const ffmpeg = findExecutable(["ffmpeg"]);
98
+ if (!ffmpeg) return undefined;
99
+
100
+ const result = await runProcess(ffmpeg, ["-hide_banner", "-nostats", "-i", audioPath, "-af", "volumedetect", "-f", "null", "-"], AUDIO_VALIDATION_TIMEOUT_MS);
101
+ const raw = `${result.stdout}\n${result.stderr}`.trim();
102
+ if (result.code !== 0) {
103
+ throw new Error(`Micme could not inspect recorded audio (${formatRunExit(result)}):\n${raw}`);
104
+ }
105
+
106
+ const diagnostics: AudioDiagnostics = {
107
+ meanVolumeDb: parseVolumeDb(raw, "mean_volume"),
108
+ maxVolumeDb: parseVolumeDb(raw, "max_volume"),
109
+ raw,
110
+ };
111
+
112
+ const minimumMaxVolumeDb = getMinMaxVolumeDb();
113
+ if (diagnostics.maxVolumeDb !== undefined && diagnostics.maxVolumeDb < minimumMaxVolumeDb) {
114
+ throw new Error(
115
+ `Micme recorded almost-silent audio (max ${diagnostics.maxVolumeDb.toFixed(1)} dB; threshold ${minimumMaxVolumeDb.toFixed(1)} dB). ` +
116
+ "Whisper often hallucinates phrases like 'Thank you very much' from silence. " +
117
+ "Run /micme devices and set MICME_AUDIO_DEVICE to the real microphone, or set MICME_VALIDATE_AUDIO=0 to bypass this check.",
118
+ );
119
+ }
120
+
121
+ return diagnostics;
122
+ }
123
+
124
+ export function parseVolumeDb(output: string, label: "mean_volume" | "max_volume") {
125
+ const match = output.match(new RegExp(`${label}:\\s*(-?(?:\\d+(?:\\.\\d+)?|inf))\\s*dB`, "i"));
126
+ if (!match) return undefined;
127
+ return match[1]?.toLowerCase() === "-inf" ? Number.NEGATIVE_INFINITY : Number(match[1]);
128
+ }
129
+
130
+ export function buildRecorderCommand(audioPath: string): CommandSpec {
131
+ const custom = env("MICME_RECORD_COMMAND");
132
+ if (custom?.trim()) {
133
+ const expanded = replacePlaceholders(custom, { audio: audioPath });
134
+ return shellCommand(expanded);
135
+ }
136
+
137
+ const ffmpeg = findExecutable(["ffmpeg"]);
138
+ if (!ffmpeg) {
139
+ throw new Error("Micme needs ffmpeg for recording, or set MICME_RECORD_COMMAND.");
140
+ }
141
+
142
+ const recordSampleRate = String(getRecordSampleRate());
143
+
144
+ if (process.platform === "darwin") {
145
+ const input = env("MICME_AVFOUNDATION_INPUT") || `:${env("MICME_AUDIO_DEVICE") || "0"}`;
146
+ const args = buildMeteredFfmpegRecorderArgs("avfoundation", input, audioPath, recordSampleRate);
147
+ return { command: ffmpeg, args, display: `${ffmpeg} ${args.map(shellQuote).join(" ")}`, meterFromStdout: true, stopInput: "q\n" };
148
+ }
149
+
150
+ if (process.platform === "linux") {
151
+ const input = env("MICME_PULSE_SOURCE") || "default";
152
+ const args = buildMeteredFfmpegRecorderArgs("pulse", input, audioPath, recordSampleRate);
153
+ return { command: ffmpeg, args, display: `${ffmpeg} ${args.map(shellQuote).join(" ")}`, meterFromStdout: true, stopInput: "q\n" };
154
+ }
155
+
156
+ if (process.platform === "win32") {
157
+ const input = `audio=${env("MICME_DSHOW_AUDIO_DEVICE") || "default"}`;
158
+ const args = buildMeteredFfmpegRecorderArgs("dshow", input, audioPath, recordSampleRate);
159
+ return { command: ffmpeg, args, display: `${ffmpeg} ${args.map(shellQuote).join(" ")}`, meterFromStdout: true, stopInput: "q\n" };
160
+ }
161
+
162
+ throw new Error(`Micme has no default recorder for ${process.platform}. Set MICME_RECORD_COMMAND.`);
163
+ }
164
+
165
+ export function buildMeteredFfmpegRecorderArgs(inputFormat: string, input: string, audioPath: string, recordSampleRate: string) {
166
+ return [
167
+ "-hide_banner",
168
+ "-loglevel",
169
+ "error",
170
+ "-thread_queue_size",
171
+ "4096",
172
+ "-f",
173
+ inputFormat,
174
+ "-i",
175
+ input,
176
+ "-filter_complex",
177
+ "[0:a]asplit=2[micme_file][micme_meter]",
178
+ "-map",
179
+ "[micme_file]",
180
+ "-ac",
181
+ "1",
182
+ "-ar",
183
+ recordSampleRate,
184
+ "-c:a",
185
+ "pcm_s16le",
186
+ "-vn",
187
+ "-y",
188
+ audioPath,
189
+ "-map",
190
+ "[micme_meter]",
191
+ "-ac",
192
+ "1",
193
+ "-ar",
194
+ "16000",
195
+ "-f",
196
+ "s16le",
197
+ "pipe:1",
198
+ ];
199
+ }
package/src/config.ts ADDED
@@ -0,0 +1,256 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { writeFile } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+ import type { DotEnvState, TranscriptionMode } from "./types.ts";
5
+ import {
6
+ DEFAULT_MACOS_PRINTABLE_SHORTCUT,
7
+ DEFAULT_RECORD_SAMPLE_RATE,
8
+ DEFAULT_SHORTCUT,
9
+ DEFAULT_STREAM_KEEP_MS,
10
+ DEFAULT_STREAM_LENGTH_MS,
11
+ DEFAULT_STREAM_MAX_TOKENS,
12
+ DEFAULT_STREAM_STEP_MS,
13
+ DEFAULT_STREAM_VAD_THRESHOLD,
14
+ DEFAULT_TRANSCRIBE_SAMPLE_RATE,
15
+ DEFAULT_TRANSCRIBE_TIMEOUT_MS,
16
+ DEFAULT_MIN_MAX_VOLUME_DB,
17
+ STREAM_PROFILE_KEEP_MS,
18
+ STREAM_PROFILE_LENGTH_MS,
19
+ STREAM_PROFILE_MAX_TOKENS,
20
+ STREAM_PROFILE_STEP_MS,
21
+ STREAM_PROFILE_VAD_THRESHOLD,
22
+ STREAM_PROFILE_WORDS_PER_CHUNK,
23
+ } from "./constants.ts";
24
+
25
+ let dotEnvState: DotEnvState = { path: "", values: {} };
26
+
27
+ export function reloadDotEnv(cwd: string) {
28
+ dotEnvState = loadDotEnv(cwd);
29
+ return dotEnvState;
30
+ }
31
+
32
+ export function getTranscriptionModeProfile(mode: TranscriptionMode): Record<string, string> {
33
+ if (mode === "stream") {
34
+ return {
35
+ MICME_TRANSCRIPTION_MODE: "stream",
36
+ MICME_STREAM_STEP_MS: String(STREAM_PROFILE_STEP_MS),
37
+ MICME_STREAM_LENGTH_MS: String(STREAM_PROFILE_LENGTH_MS),
38
+ MICME_STREAM_KEEP_MS: String(STREAM_PROFILE_KEEP_MS),
39
+ MICME_STREAM_MAX_TOKENS: String(STREAM_PROFILE_MAX_TOKENS),
40
+ MICME_STREAM_WORDS_PER_CHUNK: String(STREAM_PROFILE_WORDS_PER_CHUNK),
41
+ MICME_STREAM_KEEP_CONTEXT: "1",
42
+ MICME_STREAM_FINALIZE_WITH_CLIP: "0",
43
+ MICME_STREAM_VAD_THRESHOLD: String(STREAM_PROFILE_VAD_THRESHOLD),
44
+ };
45
+ }
46
+
47
+ return {
48
+ MICME_TRANSCRIPTION_MODE: "clip",
49
+ MICME_STREAM_STEP_MS: String(DEFAULT_STREAM_STEP_MS),
50
+ MICME_STREAM_LENGTH_MS: String(DEFAULT_STREAM_LENGTH_MS),
51
+ MICME_STREAM_KEEP_MS: String(DEFAULT_STREAM_KEEP_MS),
52
+ MICME_STREAM_MAX_TOKENS: String(DEFAULT_STREAM_MAX_TOKENS),
53
+ MICME_STREAM_WORDS_PER_CHUNK: "10",
54
+ MICME_STREAM_KEEP_CONTEXT: "1",
55
+ MICME_STREAM_FINALIZE_WITH_CLIP: "1",
56
+ MICME_STREAM_VAD_THRESHOLD: String(DEFAULT_STREAM_VAD_THRESHOLD),
57
+ };
58
+ }
59
+
60
+ export async function writeDotEnvValue(cwd: string, key: string, value: string) {
61
+ const path = join(cwd, ".env");
62
+ const lines = existsSync(path) ? readFileSync(path, "utf8").split(/\r?\n/) : [];
63
+ const matcher = new RegExp(`^\\s*(?:export\\s+)?${escapeRegExp(key)}\\s*=`);
64
+ let found = false;
65
+ const nextLines = lines.map((line) => {
66
+ if (!matcher.test(line)) return line;
67
+ found = true;
68
+ return `${key}=${formatDotEnvValue(value)}`;
69
+ });
70
+
71
+ if (!found) {
72
+ if (nextLines.length > 0 && nextLines[nextLines.length - 1] !== "") nextLines.push("");
73
+ nextLines.push(`${key}=${formatDotEnvValue(value)}`);
74
+ }
75
+
76
+ await writeFile(path, `${nextLines.join("\n").replace(/\n*$/, "")}\n`, "utf8");
77
+ }
78
+
79
+ export function formatDotEnvValue(value: string) {
80
+ if (value === "") return "";
81
+ if (/^[A-Za-z0-9_./:@%+=,-]+$/.test(value)) return value;
82
+ return JSON.stringify(value);
83
+ }
84
+
85
+ export function escapeRegExp(value: string) {
86
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
87
+ }
88
+
89
+ export function expandConfigPath(value: string) {
90
+ return expandEnvReferences(value, dotEnvState.values);
91
+ }
92
+
93
+ export function loadDotEnv(cwd: string): DotEnvState {
94
+ const path = join(cwd, ".env");
95
+ if (!existsSync(path)) return { path: "", values: {} };
96
+
97
+ try {
98
+ const values: Record<string, string> = {};
99
+ const content = readFileSync(path, "utf8").replace(/^\uFEFF/, "");
100
+ for (const line of content.split(/\r?\n/)) {
101
+ const parsed = parseDotEnvLine(line, values);
102
+ if (!parsed) continue;
103
+ values[parsed.key] = parsed.value;
104
+ }
105
+ return { path, values };
106
+ } catch (error) {
107
+ return { path, values: {}, error: error instanceof Error ? error.message : String(error) };
108
+ }
109
+ }
110
+
111
+ export function parseDotEnvLine(line: string, previousValues: Record<string, string>) {
112
+ const trimmed = line.trim();
113
+ if (!trimmed || trimmed.startsWith("#")) return undefined;
114
+
115
+ const match = trimmed.match(/^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/);
116
+ if (!match) return undefined;
117
+
118
+ const key = match[1] ?? "";
119
+ if (!key.startsWith("MICME_")) return undefined;
120
+
121
+ let value = match[2] ?? "";
122
+ if (value.startsWith('"') && value.endsWith('"')) {
123
+ value = value.slice(1, -1).replace(/\\n/g, "\n").replace(/\\r/g, "\r").replace(/\\t/g, "\t").replace(/\\"/g, '"').replace(/\\\\/g, "\\");
124
+ } else if (value.startsWith("'") && value.endsWith("'")) {
125
+ value = value.slice(1, -1);
126
+ } else {
127
+ value = value.replace(/\s+#.*$/, "").trim();
128
+ }
129
+
130
+ value = expandEnvReferences(value, previousValues);
131
+ return { key, value };
132
+ }
133
+
134
+ export function expandEnvReferences(value: string, previousValues: Record<string, string>) {
135
+ const withHome = value.startsWith("~/") && process.env.HOME ? `${process.env.HOME}${value.slice(1)}` : value;
136
+ return withHome.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)/g, (_match, braced: string | undefined, bare: string | undefined) => {
137
+ const key = braced ?? bare ?? "";
138
+ return previousValues[key] ?? process.env[key] ?? "";
139
+ });
140
+ }
141
+
142
+ export function env(name: string) {
143
+ return process.env[name] ?? dotEnvState.values[name];
144
+ }
145
+
146
+ export function getShortcut() {
147
+ return env("MICME_SHORTCUT") || DEFAULT_SHORTCUT;
148
+ }
149
+
150
+ export function getTranscriptionMode() {
151
+ return env("MICME_TRANSCRIPTION_MODE") === "stream" ? "stream" : "clip";
152
+ }
153
+
154
+ export function getPrintableShortcuts() {
155
+ const configured = env("MICME_PRINTABLE_SHORTCUTS");
156
+ if (configured !== undefined) {
157
+ return configured
158
+ .split(",")
159
+ .map((value) => value.trim())
160
+ .filter(Boolean);
161
+ }
162
+ return process.platform === "darwin" ? [DEFAULT_MACOS_PRINTABLE_SHORTCUT] : [];
163
+ }
164
+
165
+ export function matchesPrintableMicmeShortcut(data: string) {
166
+ return getPrintableShortcuts().includes(data);
167
+ }
168
+
169
+ export function getTranscribeTimeoutMs() {
170
+ const value = Number(env("MICME_TRANSCRIBE_TIMEOUT_MS"));
171
+ return Number.isFinite(value) && value > 0 ? value : DEFAULT_TRANSCRIBE_TIMEOUT_MS;
172
+ }
173
+
174
+ export function getStreamStepMs() {
175
+ const value = Number(env("MICME_STREAM_STEP_MS"));
176
+ return Number.isFinite(value) && value > 0 ? Math.round(value) : DEFAULT_STREAM_STEP_MS;
177
+ }
178
+
179
+ export function getStreamLengthMs() {
180
+ const value = Number(env("MICME_STREAM_LENGTH_MS"));
181
+ return Number.isFinite(value) && value > 0 ? Math.round(value) : DEFAULT_STREAM_LENGTH_MS;
182
+ }
183
+
184
+ export function getStreamKeepMs() {
185
+ const value = Number(env("MICME_STREAM_KEEP_MS"));
186
+ return Number.isFinite(value) && value >= 0 ? Math.round(value) : DEFAULT_STREAM_KEEP_MS;
187
+ }
188
+
189
+ export function getStreamMaxTokens() {
190
+ const value = Number(env("MICME_STREAM_MAX_TOKENS"));
191
+ return Number.isFinite(value) && value > 0 ? Math.round(value) : DEFAULT_STREAM_MAX_TOKENS;
192
+ }
193
+
194
+ export function getStreamVadThreshold() {
195
+ const value = Number(env("MICME_STREAM_VAD_THRESHOLD"));
196
+ return Number.isFinite(value) && value > 0 && value < 1 ? value : DEFAULT_STREAM_VAD_THRESHOLD;
197
+ }
198
+
199
+ export function getStreamKeepContext() {
200
+ const value = env("MICME_STREAM_KEEP_CONTEXT");
201
+ return value === undefined ? true : /^(1|true|yes|on)$/i.test(value);
202
+ }
203
+
204
+ export function getStreamFinalizeWithClip() {
205
+ const value = env("MICME_STREAM_FINALIZE_WITH_CLIP");
206
+ return value === undefined ? true : /^(1|true|yes|on)$/i.test(value);
207
+ }
208
+
209
+ export function getStreamWordsPerChunk() {
210
+ const value = Number(env("MICME_STREAM_WORDS_PER_CHUNK"));
211
+ return Number.isFinite(value) && value > 0 ? Math.min(10, Math.round(value)) : 10;
212
+ }
213
+
214
+ export function getRecordSampleRate() {
215
+ const value = Number(env("MICME_RECORD_SAMPLE_RATE"));
216
+ return Number.isFinite(value) && value > 0 ? Math.round(value) : DEFAULT_RECORD_SAMPLE_RATE;
217
+ }
218
+
219
+ export function getTranscribeSampleRate() {
220
+ const value = Number(env("MICME_TRANSCRIBE_SAMPLE_RATE"));
221
+ return Number.isFinite(value) && value > 0 ? Math.round(value) : DEFAULT_TRANSCRIBE_SAMPLE_RATE;
222
+ }
223
+
224
+ export function getAudioFilter() {
225
+ if (env("MICME_AUDIO_FILTER") !== undefined) return env("MICME_AUDIO_FILTER")!.trim();
226
+ return "highpass=f=80,lowpass=f=7600";
227
+ }
228
+
229
+ export function getMinMaxVolumeDb() {
230
+ const value = Number(env("MICME_MIN_MAX_VOLUME_DB"));
231
+ return Number.isFinite(value) ? value : DEFAULT_MIN_MAX_VOLUME_DB;
232
+ }
233
+
234
+ export function getMeterFloorDb() {
235
+ const value = Number(env("MICME_METER_FLOOR_DB"));
236
+ return Number.isFinite(value) ? value : 55;
237
+ }
238
+
239
+ export function getMeterPeakFloorDb() {
240
+ const value = Number(env("MICME_METER_PEAK_FLOOR_DB"));
241
+ return Number.isFinite(value) ? value : 45;
242
+ }
243
+
244
+ export function getMeterRangeDb() {
245
+ const value = Number(env("MICME_METER_RANGE_DB"));
246
+ return Number.isFinite(value) && value > 0 ? value : 35;
247
+ }
248
+
249
+ export function getMeterGain() {
250
+ const value = Number(env("MICME_METER_GAIN"));
251
+ return Number.isFinite(value) && value > 0 ? value : 1;
252
+ }
253
+
254
+ export function envFlag(name: string) {
255
+ return /^(1|true|yes|on)$/i.test(env(name) || "");
256
+ }