@senad-d/micme 0.3.2 → 0.3.4

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.
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { readFileSync } from "node:fs";
2
+ import { existsSync, readFileSync } from "node:fs";
3
3
  import { execFileSync, spawnSync } from "node:child_process";
4
4
  import { createInterface } from "node:readline/promises";
5
5
  import { stdin as input, stdout as output } from "node:process";
@@ -9,11 +9,66 @@ const rootUrl = new URL("../", import.meta.url);
9
9
  const root = fileURLToPath(rootUrl);
10
10
  const packageJsonUrl = new URL("package.json", rootUrl);
11
11
  const pkg = JSON.parse(readFileSync(packageJsonUrl, "utf8"));
12
- const semverPattern = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;
12
+
13
+ const SAFE_PATH = "/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/opt/homebrew/bin";
14
+ const SAFE_ENV = { ...process.env, PATH: SAFE_PATH };
15
+ const COMMAND_PATHS = {
16
+ git: ["/usr/bin/git", "/usr/local/bin/git", "/opt/homebrew/bin/git"],
17
+ npm: ["/usr/bin/npm", "/usr/local/bin/npm", "/opt/homebrew/bin/npm"],
18
+ };
19
+ const PACKAGE_NAME_RE = /^(?:@[a-z0-9][a-z0-9._~-]*\/[a-z0-9][a-z0-9._~-]*|[a-z0-9][a-z0-9._~-]*)$/;
20
+ const SEMVER_IDENTIFIER_RE = "(?:0|[1-9][0-9]*|[0-9A-Za-z-]*[A-Za-z-][0-9A-Za-z-]*)";
21
+ const SEMVER_RE = new RegExp(
22
+ `^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)(?:-(${SEMVER_IDENTIFIER_RE}(?:\\.${SEMVER_IDENTIFIER_RE})*))?(?:\\+([0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*))?$`,
23
+ );
24
+ const GIT_REF_FORBIDDEN_RE = /[\x00-\x20\x7f~^:?*[\\]/;
25
+ const CONTROL_OR_WHITESPACE_RE = /[\x00-\x20\x7f]/;
26
+
27
+ function fail(message) {
28
+ console.error(`\n${message}`);
29
+ process.exit(1);
30
+ }
31
+
32
+ function firstExistingPath(paths) {
33
+ return paths.find((path) => existsSync(path));
34
+ }
35
+
36
+ function commandPath(command) {
37
+ const candidates = COMMAND_PATHS[command];
38
+ if (!candidates) fail(`Unsupported command: ${command}`);
39
+
40
+ const resolved = firstExistingPath(candidates);
41
+ if (!resolved) fail(`Required command ${command} was not found in trusted locations.`);
42
+ return resolved;
43
+ }
44
+
45
+ function commandDisplayName(command) {
46
+ if (!COMMAND_PATHS[command]) fail(`Unsupported command: ${command}`);
47
+ return command;
48
+ }
49
+
50
+ function assertSafeCommandArgs(args) {
51
+ for (const arg of args) {
52
+ if (typeof arg !== "string" || arg.includes("\0")) {
53
+ fail("Refusing to execute a command with an invalid argument.");
54
+ }
55
+ }
56
+ }
57
+
58
+ function spawnKnownCommand(command, args, options = {}) {
59
+ assertSafeCommandArgs(args);
60
+ return spawnSync(commandPath(command), args, {
61
+ cwd: root,
62
+ env: SAFE_ENV,
63
+ ...options,
64
+ });
65
+ }
13
66
 
14
67
  function capture(command, args, options = {}) {
15
- return execFileSync(command, args, {
68
+ assertSafeCommandArgs(args);
69
+ return execFileSync(commandPath(command), args, {
16
70
  cwd: root,
71
+ env: SAFE_ENV,
17
72
  encoding: "utf8",
18
73
  stdio: ["ignore", "pipe", "pipe"],
19
74
  ...options,
@@ -21,30 +76,68 @@ function capture(command, args, options = {}) {
21
76
  }
22
77
 
23
78
  function run(command, args) {
24
- console.log(`\n$ ${command} ${args.join(" ")}`);
25
- const result = spawnSync(command, args, {
26
- cwd: root,
27
- stdio: "inherit",
28
- });
79
+ console.log(`\n$ ${commandDisplayName(command)} ${args.join(" ")}`);
80
+ const result = spawnKnownCommand(command, args, { stdio: "inherit" });
29
81
 
30
82
  if (result.status !== 0) {
31
83
  process.exit(result.status ?? 1);
32
84
  }
33
85
  }
34
86
 
35
- function fail(message) {
36
- console.error(`\n${message}`);
37
- process.exit(1);
38
- }
39
-
40
87
  function commandSucceeds(command, args) {
41
- const result = spawnSync(command, args, {
42
- cwd: root,
43
- stdio: "ignore",
44
- });
88
+ const result = spawnKnownCommand(command, args, { stdio: "ignore" });
45
89
  return result.status === 0;
46
90
  }
47
91
 
92
+ function assertNonEmptySafeValue(label, value) {
93
+ if (typeof value !== "string" || value.length === 0) fail(`${label} must not be empty.`);
94
+ if (value.startsWith("-")) fail(`${label} must not start with a dash.`);
95
+ if (CONTROL_OR_WHITESPACE_RE.test(value)) fail(`${label} must not contain whitespace or control characters.`);
96
+ }
97
+
98
+ function assertPackageName(value) {
99
+ assertNonEmptySafeValue("Package name", value);
100
+ if (!PACKAGE_NAME_RE.test(value)) fail(`Package name ${value} is not safe for publishing.`);
101
+ }
102
+
103
+ function assertVersion(value) {
104
+ assertNonEmptySafeValue("Version", value);
105
+ if (!SEMVER_RE.test(value)) {
106
+ fail("Enter a valid semver version, for example 0.1.1 or 1.0.0-beta.1.");
107
+ }
108
+ }
109
+
110
+ function assertSafeGitRefSegment(label, value) {
111
+ assertNonEmptySafeValue(label, value);
112
+ if (GIT_REF_FORBIDDEN_RE.test(value)) fail(`${label} contains characters that are not safe in git refs.`);
113
+ if (value.includes("..") || value.includes("@{") || value.includes("//")) fail(`${label} is not a safe git ref.`);
114
+ if (value.endsWith(".") || value.endsWith("/") || value.endsWith(".lock")) fail(`${label} is not a safe git ref.`);
115
+ if (value.split("/").some((segment) => segment === "" || segment === "." || segment === "..")) {
116
+ fail(`${label} is not a safe git ref.`);
117
+ }
118
+ }
119
+
120
+ function gitTagForVersion(version) {
121
+ assertVersion(version);
122
+ const tag = `v${version}`;
123
+ assertSafeGitRefSegment("Git tag", tag);
124
+ return tag;
125
+ }
126
+
127
+ function npmPackageSpec(packageName, version) {
128
+ assertPackageName(packageName);
129
+ assertVersion(version);
130
+ const spec = `${packageName}@${version}`;
131
+ assertNonEmptySafeValue("npm package spec", spec);
132
+ return spec;
133
+ }
134
+
135
+ function validateCurrentBranch(branch) {
136
+ assertSafeGitRefSegment("Current branch", branch);
137
+ if (branch === "HEAD" || branch.startsWith("HEAD:")) fail("Git is in detached HEAD.");
138
+ return branch;
139
+ }
140
+
48
141
  function ensureCleanGitTree() {
49
142
  const status = capture("git", ["status", "--porcelain"]);
50
143
  if (status) {
@@ -53,8 +146,7 @@ function ensureCleanGitTree() {
53
146
  }
54
147
 
55
148
  function ensureNpmLogin() {
56
- const result = spawnSync("npm", ["whoami"], {
57
- cwd: root,
149
+ const result = spawnKnownCommand("npm", ["whoami"], {
58
150
  encoding: "utf8",
59
151
  stdio: ["ignore", "pipe", "pipe"],
60
152
  });
@@ -63,86 +155,99 @@ function ensureNpmLogin() {
63
155
  fail("npm login is required before publishing. Run `npm login`, then retry.");
64
156
  }
65
157
 
66
- console.log(`npm user: ${result.stdout.trim()}`);
158
+ const npmUser = String(result.stdout).trim();
159
+ assertNonEmptySafeValue("npm username", npmUser);
160
+ console.log(`npm user: ${npmUser}`);
67
161
  }
68
162
 
69
- async function main() {
70
- console.log(`Publishing ${pkg.name}`);
71
- console.log(`Current version: ${pkg.version}`);
72
-
73
- ensureCleanGitTree();
74
- ensureNpmLogin();
75
-
76
- const rl = createInterface({ input, output });
77
- const version = (await rl.question("Version to publish (for example 0.1.1): ")).trim();
78
-
79
- if (!semverPattern.test(version)) {
80
- rl.close();
81
- fail("Enter a valid semver version, for example 0.1.1 or 1.0.0-beta.1.");
82
- }
83
-
84
- if (version === pkg.version) {
85
- rl.close();
86
- fail(`package.json is already at version ${version}. Choose a new version.`);
87
- }
163
+ function packageIsScoped(packageName) {
164
+ assertPackageName(packageName);
165
+ return packageName.startsWith("@");
166
+ }
88
167
 
89
- const gitTag = `v${version}`;
90
- if (commandSucceeds("git", ["rev-parse", "--verify", `refs/tags/${gitTag}`])) {
91
- rl.close();
92
- fail(`Git tag ${gitTag} already exists.`);
93
- }
168
+ function publishArgsForPackage(packageName) {
169
+ const publishArgs = ["publish"];
170
+ if (packageIsScoped(packageName)) publishArgs.push("--access", "public");
171
+ return publishArgs;
172
+ }
94
173
 
95
- const publishedVersion = spawnSync("npm", ["view", `${pkg.name}@${version}`, "version"], {
96
- cwd: root,
174
+ function packageVersionExists(packageName, version) {
175
+ const spec = npmPackageSpec(packageName, version);
176
+ const publishedVersion = spawnKnownCommand("npm", ["view", spec, "version"], {
97
177
  encoding: "utf8",
98
178
  stdio: ["ignore", "pipe", "ignore"],
99
179
  });
180
+ return publishedVersion.status === 0 && String(publishedVersion.stdout).trim().length > 0;
181
+ }
100
182
 
101
- if (publishedVersion.status === 0 && publishedVersion.stdout.trim()) {
183
+ async function askQuestion(question) {
184
+ const rl = createInterface({ input, output });
185
+ try {
186
+ return (await rl.question(question)).trim();
187
+ } finally {
102
188
  rl.close();
103
- fail(`${pkg.name}@${version} already exists on npm.`);
104
189
  }
190
+ }
105
191
 
106
- const publishArgs = ["publish"];
107
- if (pkg.name.startsWith("@")) {
108
- publishArgs.push("--access", "public");
109
- }
192
+ async function readVersionFromUser() {
193
+ const version = await askQuestion("Version to publish (for example 0.1.1): ");
194
+ assertVersion(version);
195
+ return version;
196
+ }
110
197
 
198
+ async function confirmPublishPlan(version, gitTag, publishArgs) {
111
199
  console.log("\nThis will:");
112
- console.log(`- run npm validation`);
200
+ console.log("- run npm validation");
113
201
  console.log(`- run npm version ${version} to update package.json/package-lock.json`);
114
202
  console.log(`- create a release commit and git tag ${gitTag}`);
115
203
  console.log(`- run npm ${publishArgs.join(" ")}`);
116
204
 
117
- const confirm = (await rl.question("Continue? [y/N] ")).trim().toLowerCase();
118
- if (confirm !== "y" && confirm !== "yes") {
119
- rl.close();
120
- fail("Publish cancelled.");
121
- }
205
+ const confirm = (await askQuestion("Continue? [y/N] ")).toLowerCase();
206
+ if (confirm !== "y" && confirm !== "yes") fail("Publish cancelled.");
207
+ }
122
208
 
123
- rl.close();
209
+ async function pushReleaseRefs(gitTag) {
210
+ const push = (await askQuestion(`Push current branch and ${gitTag} to origin? [y/N] `)).toLowerCase();
211
+ if (push !== "y" && push !== "yes") return;
124
212
 
125
- run("npm", ["run", "validate"]);
126
- run("npm", ["version", version, "-m", "chore(release): v%s"]);
127
- run("npm", publishArgs);
213
+ const branch = validateCurrentBranch(capture("git", ["branch", "--show-current"]));
214
+ run("git", ["push", "origin", `refs/heads/${branch}:refs/heads/${branch}`]);
215
+ run("git", ["push", "origin", `refs/tags/${gitTag}:refs/tags/${gitTag}`]);
216
+ }
128
217
 
129
- const pushRl = createInterface({ input, output });
130
- const push = (await pushRl.question(`Push current branch and ${gitTag} to origin? [y/N] `)).trim().toLowerCase();
131
- pushRl.close();
218
+ async function main() {
219
+ assertPackageName(pkg.name);
220
+ assertVersion(pkg.version);
132
221
 
133
- if (push === "y" || push === "yes") {
134
- const branch = capture("git", ["branch", "--show-current"]);
135
- if (!branch) {
136
- fail(`Release was published, but git is in detached HEAD. Push ${gitTag} manually.`);
137
- }
222
+ console.log(`Publishing ${pkg.name}`);
223
+ console.log(`Current version: ${pkg.version}`);
138
224
 
139
- run("git", ["push", "origin", branch]);
140
- run("git", ["push", "origin", gitTag]);
225
+ ensureCleanGitTree();
226
+ ensureNpmLogin();
227
+
228
+ const version = await readVersionFromUser();
229
+ if (version === pkg.version) fail(`package.json is already at version ${version}. Choose a new version.`);
230
+
231
+ const gitTag = gitTagForVersion(version);
232
+ if (commandSucceeds("git", ["rev-parse", "--verify", "--quiet", `refs/tags/${gitTag}`])) {
233
+ fail(`Git tag ${gitTag} already exists.`);
141
234
  }
142
235
 
236
+ if (packageVersionExists(pkg.name, version)) fail(`${pkg.name}@${version} already exists on npm.`);
237
+
238
+ const publishArgs = publishArgsForPackage(pkg.name);
239
+ await confirmPublishPlan(version, gitTag, publishArgs);
240
+
241
+ run("npm", ["run", "validate"]);
242
+ run("npm", ["version", version, "-m", "chore(release): v%s"]);
243
+ run("npm", publishArgs);
244
+ await pushReleaseRefs(gitTag);
245
+
143
246
  console.log(`\nPublished ${pkg.name}@${version}.`);
144
247
  }
145
248
 
146
- main().catch((error) => {
249
+ try {
250
+ await main();
251
+ } catch (error) {
147
252
  fail(error instanceof Error ? error.message : String(error));
148
- });
253
+ }
package/src/audio.ts CHANGED
@@ -1,9 +1,9 @@
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 { join } from "node:path";
3
+ import { dirname, join } from "node:path";
4
4
  import { AUDIO_VALIDATION_TIMEOUT_MS } from "./constants.ts";
5
5
  import { env, envFlag, getAudioFilter, getAvfoundationDropLateFrames, getAvfoundationInputSampleRate, getMinMaxVolumeDb, getRecordMeter, getRecordSampleRate, getRecordSync, getTranscribeSampleRate } from "./config.ts";
6
- import { findExecutable, formatRunExit, replacePlaceholders, runProcess, shellCommand, shellQuote } from "./processes.ts";
6
+ import { findExecutable, formatProcessOutput, formatRunExit, replacePlaceholders, runProcess, shellCommand, shellQuote } from "./processes.ts";
7
7
  import { sanitizeTerminalText } from "./terminal-text.ts";
8
8
  import type { AudioDeviceCandidate, AudioDiagnostics, CommandSpec, RunResult } from "./types.ts";
9
9
 
@@ -60,6 +60,11 @@ const DEVICE_PANEL_DEFAULT_WIDTH = 92;
60
60
  const DEVICE_PANEL_MAX_WIDTH = 100;
61
61
  const DEVICE_PANEL_MIN_WIDTH = 36;
62
62
  const RECORD_TIMING_SYNC_FILTER = "aresample=async=1:first_pts=0";
63
+ const AVFOUNDATION_DEVICE_PREFIX_PATTERN = /^\[(\d+)]\s+/;
64
+ const DIRECT_SHOW_FULL_DEVICE_NAME_PATTERN = /^"(.+)"$/;
65
+ const DIRECT_SHOW_DEVICE_NAME_PATTERN = /"([^"]+)"/;
66
+ const FFMPEG_WARNING_WORDS = new Set(["warning", "error", "failed", "cannot", "unable"]);
67
+ const PULSE_SOURCE_LINE_PATTERN = /^([^\s[]+)(?:\s+\[(.+)\])?$/;
63
68
 
64
69
  let deviceMessageRendererRegistered = false;
65
70
 
@@ -225,10 +230,10 @@ export function parseAvfoundationDevices(output: string): ParsedDeviceInventory
225
230
  }
226
231
  if (!section) continue;
227
232
 
228
- const match = line.match(/\[(\d+)\]\s+(.+)$/);
233
+ const match = AVFOUNDATION_DEVICE_PREFIX_PATTERN.exec(line);
229
234
  if (!match) continue;
230
235
  const id = sanitizeDeviceField(match[1] ?? "");
231
- const name = sanitizeDeviceField(match[2] ?? "");
236
+ const name = sanitizeDeviceField(line.slice(match[0].length));
232
237
  if (!name) continue;
233
238
  inventory[section].push({ id, name });
234
239
  }
@@ -250,7 +255,7 @@ function parsePulseAudioDevices(output: string): ParsedDeviceInventory {
250
255
  if (!inSources || !line || /^(Cannot|Error|Failed|Unknown)\b/i.test(line)) continue;
251
256
 
252
257
  const sourceLine = line.replace(/^\*\s*/, "");
253
- const match = sourceLine.match(/^([^\s\[]+)(?:\s+\[(.+)\])?$/);
258
+ const match = PULSE_SOURCE_LINE_PATTERN.exec(sourceLine);
254
259
  if (!match) continue;
255
260
  const id = sanitizeDeviceField(match[1] ?? "");
256
261
  if (!id || id.includes(":")) continue;
@@ -262,7 +267,7 @@ function parsePulseAudioDevices(output: string): ParsedDeviceInventory {
262
267
  return inventory;
263
268
  }
264
269
 
265
- function parseDirectShowDevices(output: string): ParsedDeviceInventory {
270
+ export function parseDirectShowDevices(output: string): ParsedDeviceInventory {
266
271
  const inventory: ParsedDeviceInventory = { audio: [], video: [], sawDeviceSection: false };
267
272
  let section: DeviceKind | undefined;
268
273
 
@@ -280,7 +285,7 @@ function parseDirectShowDevices(output: string): ParsedDeviceInventory {
280
285
  }
281
286
  if (!section || /Alternative name/i.test(line)) continue;
282
287
 
283
- const match = line.match(/^"(.+)"$/) ?? line.match(/"([^"]+)"/);
288
+ const match = DIRECT_SHOW_FULL_DEVICE_NAME_PATTERN.exec(line) ?? DIRECT_SHOW_DEVICE_NAME_PATTERN.exec(line);
284
289
  const name = sanitizeDeviceField(match?.[1] ?? "");
285
290
  if (!name) continue;
286
291
  inventory[section].push({ name });
@@ -315,7 +320,10 @@ function hasAvfoundationIoWarning(output: string) {
315
320
  }
316
321
 
317
322
  function hasFfmpegWarningAfterScan(output: string) {
318
- return /\b(?:warning|error|failed|cannot|unable)\b/i.test(output);
323
+ return output
324
+ .toLowerCase()
325
+ .split(/\W+/)
326
+ .some((word) => FFMPEG_WARNING_WORDS.has(word));
319
327
  }
320
328
 
321
329
  function getNoParseableDeviceMessage(backend: Exclude<DeviceBackend, "unsupported">) {
@@ -353,7 +361,9 @@ class DevicePanelMessageComponent implements Component {
353
361
  return renderDevicePanel(this.options, Math.min(width, DEVICE_PANEL_MAX_WIDTH)).split("\n");
354
362
  }
355
363
 
356
- invalidate(): void {}
364
+ invalidate(): void {
365
+ // Device panel messages render immutable options directly, so there is no cached state to invalidate.
366
+ }
357
367
  }
358
368
 
359
369
  function readDevicePanelOptions(value: unknown): DevicePanelOptions {
@@ -378,18 +388,19 @@ function isDeviceBackend(value: unknown): value is DeviceBackend {
378
388
  }
379
389
 
380
390
  export function renderDevicePanel(options: DevicePanelOptions, width = getDevicePanelWidth()) {
391
+ const safeOptions = sanitizeDevicePanelOptions(options);
381
392
  const style = getDevicePanelStyle();
382
393
  const panelWidth = Math.max(2, Math.floor(width));
383
- const lines = [buildDevicePanelHeader(panelWidth, options.sourceLabel, style)];
384
- const hasInventory = options.audio !== undefined || options.video !== undefined || !options.errorLines?.length;
394
+ const lines = [buildDevicePanelHeader(panelWidth, safeOptions.sourceLabel, style)];
395
+ const hasInventory = safeOptions.audio !== undefined || safeOptions.video !== undefined || !safeOptions.errorLines?.length;
385
396
 
386
397
  if (hasInventory) {
387
- lines.push(buildDeviceRow("audio", options.audio ?? [], style, panelWidth));
388
- if (options.includeVideo) lines.push(buildDeviceRow("video", options.video ?? [], style, panelWidth));
398
+ lines.push(buildDeviceRow("audio", safeOptions.audio ?? [], style, panelWidth));
399
+ if (safeOptions.includeVideo) lines.push(buildDeviceRow("video", safeOptions.video ?? [], style, panelWidth));
389
400
  }
390
401
 
391
- if (options.warning) lines.push(buildStatusRow("warning", options.warning, style, panelWidth));
392
- for (const [index, line] of (options.errorLines ?? []).entries()) {
402
+ if (safeOptions.warning) lines.push(buildStatusRow("warning", safeOptions.warning, style, panelWidth));
403
+ for (const [index, line] of (safeOptions.errorLines ?? []).entries()) {
393
404
  lines.push(buildErrorRow(line, index === 0, style, panelWidth));
394
405
  }
395
406
  lines.push(buildDevicePanelFooter(panelWidth, style));
@@ -397,6 +408,25 @@ export function renderDevicePanel(options: DevicePanelOptions, width = getDevice
397
408
  return lines.filter(Boolean).join("\n");
398
409
  }
399
410
 
411
+ function sanitizeDevicePanelOptions(options: DevicePanelOptions): DevicePanelOptions {
412
+ const errorLines = Array.isArray(options.errorLines) ? options.errorLines.map((line) => sanitizeTerminalText(String(line))).filter(Boolean) : undefined;
413
+ return {
414
+ ...options,
415
+ sourceLabel: sanitizeTerminalText(options.sourceLabel) || "unknown",
416
+ warning: typeof options.warning === "string" ? sanitizeTerminalText(options.warning) : undefined,
417
+ errorLines,
418
+ audio: sanitizeListedDevices(options.audio),
419
+ video: sanitizeListedDevices(options.video),
420
+ };
421
+ }
422
+
423
+ function sanitizeListedDevices(devices: ListedDevice[] | undefined) {
424
+ if (!Array.isArray(devices)) return undefined;
425
+ return devices
426
+ .map((device) => ({ id: device.id ? sanitizeDeviceField(String(device.id)) : undefined, name: sanitizeDeviceField(String(device.name ?? "")) }))
427
+ .filter((device) => device.id || device.name);
428
+ }
429
+
400
430
  function getDevicePanelWidth() {
401
431
  const columns = process.stdout.columns;
402
432
  if (Number.isFinite(columns) && columns > 0) {
@@ -425,7 +455,27 @@ function shouldUsePlainDevicePanel() {
425
455
  }
426
456
 
427
457
  function formatSourceLabel(sourceLabel: string, style: DevicePanelStyle) {
428
- return style.plain ? sourceLabel.replace(/\s*·\s*/g, " - ") : sourceLabel;
458
+ return style.plain ? replaceMiddleDotSeparators(sourceLabel) : sourceLabel;
459
+ }
460
+
461
+ function replaceMiddleDotSeparators(text: string) {
462
+ let formatted = "";
463
+ let index = 0;
464
+
465
+ while (index < text.length) {
466
+ const middleDotIndex = text.indexOf("·", index);
467
+ if (middleDotIndex === -1) return `${formatted}${text.slice(index)}`;
468
+
469
+ formatted = `${formatted}${text.slice(index, middleDotIndex).trimEnd()} - `;
470
+ index = middleDotIndex + 1;
471
+ while (index < text.length && isLabelWhitespace(text[index] ?? "")) index++;
472
+ }
473
+
474
+ return formatted;
475
+ }
476
+
477
+ function isLabelWhitespace(character: string) {
478
+ return character.trim() === "";
429
479
  }
430
480
 
431
481
  function buildDevicePanelHeader(width: number, sourceLabel: string, style: DevicePanelStyle) {
@@ -436,7 +486,7 @@ function buildDevicePanelHeader(width: number, sourceLabel: string, style: Devic
436
486
  const availableTextWidth = Math.max(1, width - overhead - 1);
437
487
  const sourceBudget = Math.max(4, Math.min(visibleWidth(sourceLabel), Math.floor(availableTextWidth * 0.45)));
438
488
  let source = ellipsize(formatSourceLabel(sourceLabel, style), sourceBudget, style);
439
- let titleText = ellipsize(title, Math.max(4, availableTextWidth - visibleWidth(source)), style);
489
+ const titleText = ellipsize(title, Math.max(4, availableTextWidth - visibleWidth(source)), style);
440
490
  if (visibleWidth(titleText) + visibleWidth(source) > availableTextWidth) {
441
491
  source = ellipsize(source, Math.max(1, availableTextWidth - visibleWidth(titleText)), style);
442
492
  }
@@ -453,7 +503,8 @@ function buildDevicePanelFooter(width: number, style: DevicePanelStyle) {
453
503
  }
454
504
 
455
505
  function buildDeviceRow(kind: DeviceKind, devices: ListedDevice[], style: DevicePanelStyle, width: number) {
456
- const prefix = style.plain ? ` ${kind.padEnd(5)} ${devices.length}` : ` ${kind === "audio" ? style.audioLabel : style.videoLabel} ${devices.length}`;
506
+ const deviceLabel = kind === "audio" ? style.audioLabel : style.videoLabel;
507
+ const prefix = style.plain ? ` ${kind.padEnd(5)} ${devices.length}` : ` ${deviceLabel} ${devices.length}`;
457
508
  if (devices.length === 0) return fitLine(`${prefix}${style.separator}no ${kind} devices found`, width, style);
458
509
 
459
510
  const displayNames = compactDeviceNames(devices);
@@ -600,7 +651,7 @@ export async function prepareAudioForTranscription(inputPath: string, tempDir: s
600
651
 
601
652
  const result = await runProcess(ffmpeg, args, AUDIO_VALIDATION_TIMEOUT_MS);
602
653
  if (result.code !== 0) {
603
- throw new Error(`Micme audio preprocessing failed (${formatRunExit(result)}):\n${result.stderr || result.stdout}`);
654
+ throw new Error(`Micme audio preprocessing failed (${formatRunExit(result)}):\n${formatProcessOutput(result.stderr, result.stdout)}`);
604
655
  }
605
656
 
606
657
  return outputPath;
@@ -613,7 +664,7 @@ export async function validateRecordedAudio(audioPath: string): Promise<AudioDia
613
664
  if (!ffmpeg) return undefined;
614
665
 
615
666
  const result = await runProcess(ffmpeg, ["-hide_banner", "-nostats", "-i", audioPath, "-af", "volumedetect", "-f", "null", "-"], AUDIO_VALIDATION_TIMEOUT_MS);
616
- const raw = `${result.stdout}\n${result.stderr}`.trim();
667
+ const raw = formatProcessOutput(`${result.stdout}\n${result.stderr}`);
617
668
  if (result.code !== 0) {
618
669
  throw new Error(`Micme could not inspect recorded audio (${formatRunExit(result)}):\n${raw}`);
619
670
  }
@@ -637,15 +688,16 @@ export async function validateRecordedAudio(audioPath: string): Promise<AudioDia
637
688
  }
638
689
 
639
690
  export function parseVolumeDb(output: string, label: "mean_volume" | "max_volume") {
640
- const match = output.match(new RegExp(`${label}:\\s*(-?(?:\\d+(?:\\.\\d+)?|inf))\\s*dB`, "i"));
691
+ const pattern = new RegExp(String.raw`${label}:\s*(-?(?:\d+(?:\.\d+)?|inf))\s*dB`, "i");
692
+ const match = pattern.exec(output);
641
693
  if (!match) return undefined;
642
694
  return match[1]?.toLowerCase() === "-inf" ? Number.NEGATIVE_INFINITY : Number(match[1]);
643
695
  }
644
696
 
645
- export function buildRecorderCommand(audioPath: string): CommandSpec {
697
+ export function buildRecorderCommand(audioPath: string, tempDir = dirname(audioPath)): CommandSpec {
646
698
  const custom = env("MICME_RECORD_COMMAND");
647
699
  if (custom?.trim()) {
648
- const expanded = replacePlaceholders(custom, { audio: audioPath });
700
+ const expanded = replacePlaceholders(custom, { audio: audioPath, tempDir, transcript: join(tempDir, "transcript.txt") });
649
701
  return shellCommand(expanded);
650
702
  }
651
703
 
@@ -665,7 +717,7 @@ export function buildRecorderCommand(audioPath: string): CommandSpec {
665
717
  const args = buildFfmpegRecorderArgs("avfoundation", input, audioPath, recordSampleRate, {
666
718
  meter: recordMeter,
667
719
  inputOptions: ["-drop_late_frames", getAvfoundationDropLateFrames() ? "true" : "false"],
668
- audioFilters: recordSync ? timingFilters : avfoundationInputSampleRate ? [`asetrate=${avfoundationInputSampleRate}`] : [],
720
+ audioFilters: getAvfoundationAudioFilters(recordSync, avfoundationInputSampleRate),
669
721
  });
670
722
  return { command: ffmpeg, args, display: `${ffmpeg} ${args.map(shellQuote).join(" ")}`, meterFromStdout: recordMeter, stopInput: "q\n" };
671
723
  }
@@ -691,6 +743,12 @@ type FfmpegRecorderOptions = {
691
743
  audioFilters?: string[];
692
744
  };
693
745
 
746
+ function getAvfoundationAudioFilters(recordSync: boolean, avfoundationInputSampleRate: number | undefined) {
747
+ if (recordSync) return [RECORD_TIMING_SYNC_FILTER];
748
+ if (avfoundationInputSampleRate) return [`asetrate=${avfoundationInputSampleRate}`];
749
+ return [];
750
+ }
751
+
694
752
  export function buildFfmpegRecorderArgs(inputFormat: string, input: string, audioPath: string, recordSampleRate: string | undefined, options: FfmpegRecorderOptions = {}) {
695
753
  const inputArgs = [
696
754
  "-hide_banner",