@senad-d/micme 0.3.3 → 0.3.5

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/src/editor.ts CHANGED
@@ -30,7 +30,12 @@ class MicmeEditor extends CustomEditor {
30
30
 
31
31
  function handleMicmeEditorInput(data: string, handlers: MicmeEditorInputHandlers) {
32
32
  const printable = decodeKittyPrintable(data);
33
- const printableShortcut = matchesPrintableMicmeShortcut(data) ? data : printable !== undefined && matchesPrintableMicmeShortcut(printable) ? printable : undefined;
33
+ let printableShortcut: string | undefined;
34
+ if (matchesPrintableMicmeShortcut(data)) {
35
+ printableShortcut = data;
36
+ } else if (printable !== undefined && matchesPrintableMicmeShortcut(printable)) {
37
+ printableShortcut = printable;
38
+ }
34
39
  if (printableShortcut !== undefined) {
35
40
  if (!isPrintableShortcutAutoRepeat(printableShortcut)) void handlers.toggle();
36
41
  return true;
package/src/extension.ts CHANGED
@@ -40,12 +40,14 @@ import {
40
40
  import { pasteOrSubmitTranscript } from "./transcript-delivery.ts";
41
41
  import { sanitizeTerminalOutput } from "./terminal-text.ts";
42
42
  import { transcribe } from "./transcription.ts";
43
- import type { Recording } from "./types.ts";
43
+ import type { Recording, ResolvedTranscriptionPlan } from "./types.ts";
44
44
 
45
45
  const MICME_ACTIONS = ["devices", "conf", "last", "audio", "help"] as const;
46
46
 
47
47
  const SHORTCUT_REPEAT_GUARD_MS = 1_000;
48
48
 
49
+ type StreamingTranscriptionPlan = ResolvedTranscriptionPlan & { effectiveBackend: "whisper.cpp"; binary: string; modelPath: string };
50
+
49
51
  let recording: Recording | undefined;
50
52
  let lastTranscript = "";
51
53
  let lastAudioDir = "";
@@ -251,7 +253,7 @@ async function stopAndTranscribe(ctx: ExtensionContext, pi: ExtensionAPI) {
251
253
  ctx.ui.setStatus(STATUS_KEY, undefined);
252
254
  lastAudioDir = active.tempDir;
253
255
  const message = sanitizeTerminalOutput(error instanceof Error ? error.message : String(error));
254
- throw new Error(`${message}\nAudio kept for debugging: ${sanitizeTerminalOutput(active.tempDir)}`);
256
+ throw new Error(`${message}\nAudio kept for debugging: ${sanitizeTerminalOutput(active.tempDir)}`, { cause: error });
255
257
  } finally {
256
258
  if (completed && !envFlag("MICME_KEEP_AUDIO")) {
257
259
  await cleanup(active.tempDir).catch(() => undefined);
@@ -260,55 +262,20 @@ async function stopAndTranscribe(ctx: ExtensionContext, pi: ExtensionAPI) {
260
262
  }
261
263
 
262
264
  async function startStreamingTranscription(ctx: ExtensionContext, stopHint = getShortcut()) {
263
- const plan = resolveTranscriptionPlan({ transcriptionMode: "stream" });
264
- if (plan.effectiveBackend !== "whisper.cpp" || !plan.binary || !plan.modelPath) {
265
- throw new Error(formatTranscriptionPlan(plan));
266
- }
267
-
265
+ const plan = resolveStreamingTranscriptionPlan();
268
266
  await ensureWhisperCppModel(plan.modelPath, ctx, { allowDownload: plan.modelDownloadable !== false });
269
267
 
270
268
  const tempDir = await createRecordingDirectory(ctx.cwd, envFlag("MICME_KEEP_AUDIO"), "micme-stream-");
271
269
  let active: Recording | undefined;
272
270
 
273
271
  try {
274
- const command = buildWhisperStreamCommand(plan.binary, plan.modelPath, tempDir);
275
- const clipAudioPath = getStreamFinalizeWithClip() ? join(tempDir, "raw.wav") : undefined;
276
- const clipCommand = clipAudioPath ? buildRecorderCommand(clipAudioPath) : undefined;
277
- active = spawnRecording(command, "", tempDir);
278
- const streamRecording = active;
279
- const baseText = ctx.ui.getEditorText();
280
- streamRecording.streaming = {
281
- baseText,
282
- previewText: baseText,
283
- outputBuffer: "",
284
- lastText: "",
285
- emittedWords: [],
286
- candidateWords: [],
287
- lastHypothesisWords: [],
288
- startedAt: Date.now(),
289
- };
290
- if (clipCommand && clipAudioPath) {
291
- streamRecording.clipRecording = spawnRecording(clipCommand, clipAudioPath, tempDir);
292
- }
272
+ const streamRecording = spawnWhisperStreamingRecording(plan, tempDir);
273
+ active = streamRecording;
274
+ initializeStreamingRecording(ctx, streamRecording);
275
+ startOptionalClipRecording(streamRecording, tempDir);
293
276
  recording = streamRecording;
294
277
 
295
- streamRecording.process.stdout?.on("data", (chunk: Buffer | string) => {
296
- const text = typeof chunk === "string" ? chunk : chunk.toString("utf8");
297
- handleStreamingOutput(ctx, streamRecording, text);
298
- });
299
-
300
- const [earlyExit, recorderEarlyExit] = await Promise.all([
301
- raceWithTimeout(streamRecording.exitPromise, RECORDER_STARTUP_GRACE_MS),
302
- streamRecording.clipRecording ? raceWithTimeout(streamRecording.clipRecording.exitPromise, RECORDER_STARTUP_GRACE_MS) : Promise.resolve(undefined),
303
- ]);
304
- if (earlyExit || recorderEarlyExit) {
305
- if (streamRecording.stopRequested || streamRecording.clipRecording?.stopRequested) return;
306
- const failed = earlyExit ? streamRecording : streamRecording.clipRecording;
307
- const stderr = failed ? formatProcessOutput(failed.stderr()) : "";
308
- const suffix = stderr ? `\n${stderr}` : "";
309
- throw new Error(`Micme streaming exited early (${formatExit(earlyExit ?? recorderEarlyExit!)}).${suffix}`);
310
- }
311
-
278
+ await ensureStreamingRecorderStarted(streamRecording);
312
279
  ctx.ui.setStatus(STATUS_KEY, `● streaming (${sanitizeTerminalOutput(stopHint) || "shortcut"} or /micme)`);
313
280
  startRecordingWidget(ctx, streamRecording);
314
281
  } catch (error) {
@@ -317,68 +284,163 @@ async function startStreamingTranscription(ctx: ExtensionContext, stopHint = get
317
284
  }
318
285
  }
319
286
 
287
+ function resolveStreamingTranscriptionPlan(): StreamingTranscriptionPlan {
288
+ const plan = resolveTranscriptionPlan({ transcriptionMode: "stream" });
289
+ if (plan.effectiveBackend !== "whisper.cpp" || !plan.binary || !plan.modelPath) {
290
+ throw new Error(formatTranscriptionPlan(plan));
291
+ }
292
+ return plan as StreamingTranscriptionPlan;
293
+ }
294
+
295
+ function spawnWhisperStreamingRecording(plan: StreamingTranscriptionPlan, tempDir: string) {
296
+ const command = buildWhisperStreamCommand(plan.binary, plan.modelPath, tempDir);
297
+ return spawnRecording(command, "", tempDir);
298
+ }
299
+
300
+ function initializeStreamingRecording(ctx: ExtensionContext, streamRecording: Recording) {
301
+ const baseText = ctx.ui.getEditorText();
302
+ streamRecording.streaming = {
303
+ baseText,
304
+ previewText: baseText,
305
+ outputBuffer: "",
306
+ lastText: "",
307
+ emittedWords: [],
308
+ candidateWords: [],
309
+ lastHypothesisWords: [],
310
+ startedAt: Date.now(),
311
+ };
312
+ streamRecording.process.stdout?.on("data", (chunk: Buffer | string) => {
313
+ const text = typeof chunk === "string" ? chunk : chunk.toString("utf8");
314
+ handleStreamingOutput(ctx, streamRecording, text);
315
+ });
316
+ }
317
+
318
+ function startOptionalClipRecording(streamRecording: Recording, tempDir: string) {
319
+ const clipAudioPath = getStreamFinalizeWithClip() ? join(tempDir, "raw.wav") : undefined;
320
+ if (!clipAudioPath) return;
321
+ streamRecording.clipRecording = spawnRecording(buildRecorderCommand(clipAudioPath), clipAudioPath, tempDir);
322
+ }
323
+
324
+ async function ensureStreamingRecorderStarted(streamRecording: Recording) {
325
+ const [earlyExit, recorderEarlyExit] = await Promise.all([
326
+ raceWithTimeout(streamRecording.exitPromise, RECORDER_STARTUP_GRACE_MS),
327
+ streamRecording.clipRecording ? raceWithTimeout(streamRecording.clipRecording.exitPromise, RECORDER_STARTUP_GRACE_MS) : Promise.resolve(undefined),
328
+ ]);
329
+ const failedExit = earlyExit ?? recorderEarlyExit;
330
+ if (!failedExit) return;
331
+ if (streamRecording.stopRequested || streamRecording.clipRecording?.stopRequested) return;
332
+ const failed = earlyExit ? streamRecording : streamRecording.clipRecording;
333
+ const stderr = failed ? formatProcessOutput(failed.stderr()) : "";
334
+ const suffix = stderr ? `\n${stderr}` : "";
335
+ throw new Error(`Micme streaming exited early (${formatExit(failedExit)}).${suffix}`);
336
+ }
337
+
320
338
  async function stopStreamingTranscription(ctx: ExtensionContext, pi: ExtensionAPI, active: Recording) {
321
339
  const state = active.streaming;
322
- let keepTempDir = false;
323
- const clipStopPromise = active.clipRecording ? stopRecorder(active.clipRecording).then(() => undefined, (error: unknown) => error) : undefined;
324
-
325
- if (state) {
326
- drainStreamingOutput(ctx, active, false);
327
- renderStreamingPreview(ctx, state, false);
328
- clearStreamingFlush(state);
329
- }
340
+ const clipStopPromise = stopClipRecording(active);
330
341
 
342
+ prepareStreamingStop(ctx, active, state);
331
343
  await stopProcess(active);
332
344
 
333
- if (state) {
334
- drainStreamingOutput(ctx, active, true);
335
- showStreamingDiagnostics(ctx, state);
336
- if (!active.clipRecording) {
337
- flushPendingStreamingWords(ctx, state);
338
- const liveTranscript = normalizeTranscript(getStreamingTranscript(state));
339
- if (liveTranscript) {
340
- lastTranscript = liveTranscript;
341
- if (envFlag("MICME_AUTO_SUBMIT")) {
342
- ctx.ui.setEditorText(state.baseText);
343
- await pasteOrSubmitTranscript(ctx, pi, liveTranscript);
344
- }
345
- }
346
- } else {
347
- renderStreamingPreview(ctx, state, false);
348
- }
345
+ const keepTempDir = state ? await completeStreamingStop(ctx, pi, active, state, clipStopPromise) : false;
346
+ if (!keepTempDir) await cleanup(active.tempDir).catch(() => undefined);
347
+ ctx.ui.setStatus(STATUS_KEY, undefined);
348
+ }
349
+
350
+ function stopClipRecording(active: Recording) {
351
+ return active.clipRecording ? stopRecorder(active.clipRecording).then(() => undefined, (error: unknown) => error) : undefined;
352
+ }
353
+
354
+ function prepareStreamingStop(ctx: ExtensionContext, active: Recording, state: Recording["streaming"]) {
355
+ if (!state) return;
356
+ drainStreamingOutput(ctx, active, false);
357
+ renderStreamingPreview(ctx, state, false);
358
+ clearStreamingFlush(state);
359
+ }
360
+
361
+ async function completeStreamingStop(
362
+ ctx: ExtensionContext,
363
+ pi: ExtensionAPI,
364
+ active: Recording,
365
+ state: NonNullable<Recording["streaming"]>,
366
+ clipStopPromise: ReturnType<typeof stopClipRecording>,
367
+ ) {
368
+ drainStreamingOutput(ctx, active, true);
369
+ showStreamingDiagnostics(ctx, state);
370
+ const clipRecording = active.clipRecording;
371
+ if (!clipRecording) {
372
+ await useLiveStreamingTranscript(ctx, pi, state);
349
373
  clearStreamingFlush(state);
374
+ return false;
350
375
  }
351
376
 
352
- if (active.clipRecording && state) {
353
- ctx.ui.setStatus(STATUS_KEY, "finalizing stream…");
354
- try {
355
- const clipStopError = await clipStopPromise;
356
- if (clipStopError) throw clipStopError;
357
- const preparedAudioPath = await prepareAudioForTranscription(active.clipRecording.audioPath, active.tempDir);
358
- await validateRecordedAudio(preparedAudioPath);
359
- const transcript = await transcribe(preparedAudioPath, active.tempDir, ctx);
360
- const normalized = normalizeTranscript(transcript);
361
- if (!normalized) throw new Error("Micme did not receive any final transcript text.");
362
-
363
- lastTranscript = normalized;
364
- await pasteOrSubmitFinalStreamingTranscript(ctx, pi, state, normalized);
365
- if (envFlag("MICME_KEEP_AUDIO")) {
366
- lastAudioDir = active.tempDir;
367
- keepTempDir = true;
368
- }
369
- } catch (error) {
370
- flushPendingStreamingWords(ctx, state);
371
- const liveTranscript = normalizeTranscript(getStreamingTranscript(state));
372
- if (liveTranscript) lastTranscript = liveTranscript;
373
- lastAudioDir = active.tempDir;
374
- keepTempDir = true;
375
- const message = sanitizeTerminalOutput(error instanceof Error ? error.message : String(error));
376
- ctx.ui.notify(`Micme kept the live append-only stream transcript because final clip transcription failed: ${message}\nAudio kept for debugging: ${sanitizeTerminalOutput(active.tempDir)}`, "warning");
377
- }
377
+ renderStreamingPreview(ctx, state, false);
378
+ clearStreamingFlush(state);
379
+ return finalizeStreamingClip(ctx, pi, active, clipRecording, state, clipStopPromise);
380
+ }
381
+
382
+ async function useLiveStreamingTranscript(ctx: ExtensionContext, pi: ExtensionAPI, state: NonNullable<Recording["streaming"]>) {
383
+ flushPendingStreamingWords(ctx, state);
384
+ const liveTranscript = normalizeTranscript(getStreamingTranscript(state));
385
+ if (!liveTranscript) return;
386
+
387
+ lastTranscript = liveTranscript;
388
+ if (!envFlag("MICME_AUTO_SUBMIT")) return;
389
+ ctx.ui.setEditorText(state.baseText);
390
+ await pasteOrSubmitTranscript(ctx, pi, liveTranscript);
391
+ }
392
+
393
+ async function finalizeStreamingClip(
394
+ ctx: ExtensionContext,
395
+ pi: ExtensionAPI,
396
+ active: Recording,
397
+ clipRecording: Recording,
398
+ state: NonNullable<Recording["streaming"]>,
399
+ clipStopPromise: ReturnType<typeof stopClipRecording>,
400
+ ) {
401
+ ctx.ui.setStatus(STATUS_KEY, "finalizing stream…");
402
+ try {
403
+ await transcribeFinalStreamingClip(ctx, pi, active, clipRecording, state, clipStopPromise);
404
+ return keepCompletedStreamingClipAudio(active);
405
+ } catch (error) {
406
+ handleFinalStreamingClipError(ctx, active, state, error);
407
+ return true;
378
408
  }
409
+ }
379
410
 
380
- if (!keepTempDir) await cleanup(active.tempDir).catch(() => undefined);
381
- ctx.ui.setStatus(STATUS_KEY, undefined);
411
+ async function transcribeFinalStreamingClip(
412
+ ctx: ExtensionContext,
413
+ pi: ExtensionAPI,
414
+ active: Recording,
415
+ clipRecording: Recording,
416
+ state: NonNullable<Recording["streaming"]>,
417
+ clipStopPromise: ReturnType<typeof stopClipRecording>,
418
+ ) {
419
+ const clipStopError = clipStopPromise ? await clipStopPromise : undefined;
420
+ if (clipStopError) throw clipStopError;
421
+ const preparedAudioPath = await prepareAudioForTranscription(clipRecording.audioPath, active.tempDir);
422
+ await validateRecordedAudio(preparedAudioPath);
423
+ const transcript = await transcribe(preparedAudioPath, active.tempDir, ctx);
424
+ const normalized = normalizeTranscript(transcript);
425
+ if (!normalized) throw new Error("Micme did not receive any final transcript text.");
426
+
427
+ lastTranscript = normalized;
428
+ await pasteOrSubmitFinalStreamingTranscript(ctx, pi, state, normalized);
429
+ }
430
+
431
+ function keepCompletedStreamingClipAudio(active: Recording) {
432
+ if (!envFlag("MICME_KEEP_AUDIO")) return false;
433
+ lastAudioDir = active.tempDir;
434
+ return true;
435
+ }
436
+
437
+ function handleFinalStreamingClipError(ctx: ExtensionContext, active: Recording, state: NonNullable<Recording["streaming"]>, error: unknown) {
438
+ flushPendingStreamingWords(ctx, state);
439
+ const liveTranscript = normalizeTranscript(getStreamingTranscript(state));
440
+ if (liveTranscript) lastTranscript = liveTranscript;
441
+ lastAudioDir = active.tempDir;
442
+ const message = sanitizeTerminalOutput(error instanceof Error ? error.message : String(error));
443
+ ctx.ui.notify(`Micme kept the live append-only stream transcript because final clip transcription failed: ${message}\nAudio kept for debugging: ${sanitizeTerminalOutput(active.tempDir)}`, "warning");
382
444
  }
383
445
 
384
446
 
package/src/models.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import { randomUUID } from "node:crypto";
2
3
  import { once } from "node:events";
3
4
  import { createWriteStream, existsSync, readdirSync, statSync, type WriteStream } from "node:fs";
4
5
  import { mkdir, rename, unlink } from "node:fs/promises";
@@ -19,7 +20,7 @@ import { sanitizeTerminalText } from "./terminal-text.ts";
19
20
  import type { ModelCandidate, ResolvedWhisperCppModel } from "./types.ts";
20
21
 
21
22
  const modelDownloads = new Map<string, Promise<void>>();
22
- const PYTHON_WHISPER_MODELS_SCRIPT = "import whisper; print('\\n'.join(whisper.available_models()))";
23
+ const PYTHON_WHISPER_MODELS_SCRIPT = String.raw`import whisper; print('\n'.join(whisper.available_models()))`;
23
24
 
24
25
  export function discoverWhisperCppModels(cwd: string): ModelCandidate[] {
25
26
  const candidates: ModelCandidate[] = [];
@@ -177,7 +178,7 @@ function getSiblingWhisperCppModelPath(modelPath: string, modelName: string) {
177
178
  }
178
179
 
179
180
  function getTranslationFallbackSource(rawModelName: string, modelName: string) {
180
- return rawModelName !== modelName ? rawModelName : undefined;
181
+ return rawModelName === modelName ? undefined : rawModelName;
181
182
  }
182
183
 
183
184
  export function getPythonWhisperModelName() {
@@ -203,9 +204,11 @@ export function isEnglishOnlyWhisperModelName(modelName: string | undefined) {
203
204
  }
204
205
 
205
206
  export function isTranslationUnsupportedWhisperModelName(modelName: string | undefined) {
206
- if (!modelName) return false;
207
- const normalized = modelName.toLowerCase();
208
- return normalized === "turbo" || normalized === "large-v3-turbo" || normalized.startsWith("large-v3-turbo-");
207
+ if (modelName) {
208
+ const normalized = modelName.toLowerCase();
209
+ return normalized === "turbo" || normalized === "large-v3-turbo" || normalized.startsWith("large-v3-turbo-");
210
+ }
211
+ return false;
209
212
  }
210
213
 
211
214
  export async function discoverPythonWhisperModels(): Promise<ModelCandidate[]> {
@@ -302,7 +305,7 @@ export async function downloadFile(url: string, targetPath: string, ctx?: Extens
302
305
  assertDownloadTargetIsUsable(targetPath, "Download target");
303
306
  if (isRegularFile(targetPath)) return;
304
307
  await mkdir(dirname(targetPath), { recursive: true });
305
- const tempPath = `${targetPath}.download-${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}`;
308
+ const tempPath = `${targetPath}.download-${process.pid}-${Date.now()}-${randomUUID()}`;
306
309
 
307
310
  const response = await fetch(url);
308
311
  if (!response.ok || !response.body) {
@@ -356,12 +359,12 @@ async function writeDownloadChunk(output: WriteStream, chunk: Buffer, outputFini
356
359
  }
357
360
 
358
361
  export function getWhisperCppModelNameFromPath(modelPath: string) {
359
- const match = basename(modelPath).match(/^ggml-(.+)\.(?:bin|gguf)$/i);
362
+ const match = /^ggml-(.+)\.(?:bin|gguf)$/i.exec(basename(modelPath));
360
363
  return match?.[1];
361
364
  }
362
365
 
363
366
  export function getDownloadableWhisperCppModelName(modelPath: string) {
364
- const match = basename(modelPath).match(/^ggml-(.+)\.bin$/i);
367
+ const match = /^ggml-(.+)\.bin$/i.exec(basename(modelPath));
365
368
  const modelName = match?.[1];
366
369
  return modelName && isKnownWhisperCppModelName(modelName) ? modelName : undefined;
367
370
  }
package/src/processes.ts CHANGED
@@ -61,7 +61,9 @@ export function spawnRecording(command: CommandSpec, audioPath: string, tempDir:
61
61
  }
62
62
 
63
63
  export async function stopProcess(active: Recording) {
64
- if (!active.isSettled()) {
64
+ if (active.isSettled()) {
65
+ await active.exitPromise;
66
+ } else {
65
67
  active.stopRequested = true;
66
68
  let exit: ExitResult | undefined;
67
69
  if (sendStopInput(active)) {
@@ -79,8 +81,6 @@ export async function stopProcess(active: Recording) {
79
81
  active.process.kill("SIGKILL");
80
82
  await active.exitPromise;
81
83
  }
82
- } else {
83
- await active.exitPromise;
84
84
  }
85
85
  }
86
86
 
@@ -156,7 +156,7 @@ export function runProcess(command: string, args: string[], timeoutMs: number):
156
156
 
157
157
  export function normalizeTranscript(text: string) {
158
158
  return stripTerminalControlSequences(text)
159
- .replace(/\r\n/g, "\n")
159
+ .replaceAll("\r\n", "\n")
160
160
  .split("\n")
161
161
  .map((line) => line.trim())
162
162
  .filter(Boolean)
@@ -167,27 +167,51 @@ export function normalizeTranscript(text: string) {
167
167
 
168
168
  export function replacePlaceholders(template: string, values: Record<string, string>) {
169
169
  return template.replace(/\{([A-Za-z][A-Za-z0-9]*?)(Raw)?\}/g, (placeholder, key: string, rawSuffix: string | undefined) => {
170
- if (!Object.prototype.hasOwnProperty.call(values, key)) return placeholder;
170
+ if (!Object.hasOwn(values, key)) return placeholder;
171
171
  const value = values[key] ?? "";
172
172
  return rawSuffix ? value : shellQuote(value);
173
173
  });
174
174
  }
175
175
 
176
176
  export function findExecutable(names: string[]) {
177
- const dirs = (process.env.PATH || "").split(delimiter).filter(Boolean);
178
- const extensions = process.platform === "win32" ? (process.env.PATHEXT || ".EXE;.CMD;.BAT;.COM").split(";") : [""];
177
+ const dirs = getPathDirectories();
178
+ const extensions = getExecutableExtensions();
179
179
 
180
180
  for (const name of names) {
181
- for (const dir of dirs) {
182
- for (const extension of extensions) {
183
- const candidate = join(dir, process.platform === "win32" && !/\.[^.]+$/.test(name) ? `${name}${extension}` : name);
184
- if (isExecutableFile(candidate)) return candidate;
185
- }
186
- }
181
+ const executable = findExecutableByName(name, dirs, extensions);
182
+ if (executable) return executable;
187
183
  }
188
184
  return undefined;
189
185
  }
190
186
 
187
+ function getPathDirectories() {
188
+ return (process.env.PATH || "").split(delimiter).filter(Boolean);
189
+ }
190
+
191
+ function getExecutableExtensions() {
192
+ return process.platform === "win32" ? (process.env.PATHEXT || ".EXE;.CMD;.BAT;.COM").split(";") : [""];
193
+ }
194
+
195
+ function findExecutableByName(name: string, dirs: string[], extensions: string[]) {
196
+ for (const dir of dirs) {
197
+ const executable = findExecutableInDirectory(name, dir, extensions);
198
+ if (executable) return executable;
199
+ }
200
+ return undefined;
201
+ }
202
+
203
+ function findExecutableInDirectory(name: string, dir: string, extensions: string[]) {
204
+ for (const extension of extensions) {
205
+ const candidate = join(dir, getExecutableFileName(name, extension));
206
+ if (isExecutableFile(candidate)) return candidate;
207
+ }
208
+ return undefined;
209
+ }
210
+
211
+ function getExecutableFileName(name: string, extension: string) {
212
+ return process.platform === "win32" && !/\.[^.]+$/.test(name) ? `${name}${extension}` : name;
213
+ }
214
+
191
215
  export function isExecutableFile(path: string) {
192
216
  try {
193
217
  const stats = statSync(path);
@@ -247,7 +271,9 @@ export function formatRunExit(result: RunResult) {
247
271
 
248
272
  export function shellQuote(value: string) {
249
273
  if (process.platform === "win32") {
250
- return `"${value.replace(/"/g, '\\"')}"`;
274
+ const escapedValue = value.replaceAll('"', String.raw`\"`);
275
+ return `"${escapedValue}"`;
251
276
  }
252
- return `'${value.replace(/'/g, `'\\''`)}'`;
277
+ const escapedValue = value.replaceAll("'", String.raw`'\''`);
278
+ return `'${escapedValue}'`;
253
279
  }