@hxnnxs/opencode-voice 0.1.9 → 0.2.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/lib/engine.js CHANGED
@@ -466,8 +466,8 @@ function platformKey(options = {}) {
466
466
  }
467
467
 
468
468
  export function getBundledEngineDir(command, options = {}) {
469
- if (command !== "whisper-cli") return "";
470
- return path.join(getEnginesDir(options, options), "whisper.cpp", platformKey(options));
469
+ const engineId = command === "whisper-cli" ? "whisper.cpp" : command === "opencode-voice-transcribe" ? "transcribe-cpp" : "";
470
+ return engineId ? path.join(getEnginesDir(options, options), engineId, platformKey(options)) : "";
471
471
  }
472
472
 
473
473
  function looksLikePath(value) {
@@ -482,6 +482,11 @@ function candidateCommands(command, options = {}) {
482
482
  if (process.env.OPENCODE_VOICE_WHISPER_CLI) candidates.push(process.env.OPENCODE_VOICE_WHISPER_CLI);
483
483
  }
484
484
 
485
+ if (command === "opencode-voice-transcribe") {
486
+ if (options.transcribeCpp) candidates.push(options.transcribeCpp);
487
+ if (process.env.OPENCODE_VOICE_TRANSCRIBE_CPP) candidates.push(process.env.OPENCODE_VOICE_TRANSCRIBE_CPP);
488
+ }
489
+
485
490
  if (command === "ffmpeg") {
486
491
  if (options.ffmpeg) candidates.push(options.ffmpeg);
487
492
  if (process.env.OPENCODE_VOICE_FFMPEG) candidates.push(process.env.OPENCODE_VOICE_FFMPEG);
@@ -562,8 +567,8 @@ export function commandExists(command, options = {}) {
562
567
  function childEnv(options = {}) {
563
568
  const localLib = path.join(os.homedir(), ".local", "lib");
564
569
  const localBin = path.join(os.homedir(), ".local", "bin");
565
- const bundledDir = getBundledEngineDir("whisper-cli", options);
566
- const pathEntries = [bundledDir, localBin, localLib, process.env.PATH].filter(Boolean);
570
+ const bundledDirs = [getBundledEngineDir("whisper-cli", options), getBundledEngineDir("opencode-voice-transcribe", options)];
571
+ const pathEntries = [...bundledDirs, localBin, localLib, process.env.PATH].filter(Boolean);
567
572
  return {
568
573
  ...process.env,
569
574
  PATH: pathEntries.join(path.delimiter),
@@ -579,6 +584,15 @@ function normalizeWindowsAudioInput(device = "") {
579
584
  return `audio=${value}`;
580
585
  }
581
586
 
587
+ function formatCommand(command, args) {
588
+ const quote = (value) => {
589
+ const text = String(value);
590
+ if (/^[^\s"\\]+$/.test(text)) return text;
591
+ return `"${text.replace(/(\\*)"/g, "$1$1\\\"").replace(/(\\*)$/g, "$1$1")}"`;
592
+ };
593
+ return [command, ...args].map(quote).join(" ");
594
+ }
595
+
582
596
  function parseWindowsMicrophones(stderr) {
583
597
  const devices = new Set();
584
598
  for (const line of stderr.split(/\r?\n/)) {
@@ -668,7 +682,13 @@ function buildRecorders(file, settings = {}) {
668
682
  if (process.platform === "win32" && ffmpegCommand) {
669
683
  const ffmpegCmd = ffmpegCommand;
670
684
  if (ffmpegCmd) {
671
- const inputs = [...new Set([normalizeWindowsAudioInput(mic), "audio=default"])];
685
+ const configuredInput = mic && mic !== "default" ? normalizeWindowsAudioInput(mic) : "";
686
+ // DirectShow does not provide a reliable "audio=default" alias. Try each
687
+ // enumerated device before retaining it as a final fallback for custom setups.
688
+ const detectedInputs = listMicrophones(settings)
689
+ .filter((device) => device !== "default")
690
+ .map(normalizeWindowsAudioInput);
691
+ const inputs = [...new Set([configuredInput, ...detectedInputs, "audio=default"].filter(Boolean))];
672
692
  for (const input of inputs) {
673
693
  recorders.push({
674
694
  label: `ffmpeg dshow (${input.replace(/^audio=/, "")})`,
@@ -734,14 +754,22 @@ function startRecorder(recorder, file) {
734
754
  let stderr = "";
735
755
  let exited = false;
736
756
  let exitCode = null;
757
+ const commandLine = formatCommand(recorder.command, recorder.args);
758
+ const failure = (detail) => new Error(`${recorder.label}: ${detail}\nCommand: ${commandLine}${stderr.trim() ? `\nffmpeg stderr:\n${stderr.trim()}` : ""}`);
737
759
 
738
- const proc = spawn(recorder.command, recorder.args, { stdio: ["ignore", "ignore", "pipe"] });
760
+ let proc;
761
+ try {
762
+ proc = spawn(recorder.command, recorder.args, { stdio: ["ignore", "ignore", "pipe"] });
763
+ } catch (error) {
764
+ reject(failure(error instanceof Error ? error.message : String(error)));
765
+ return;
766
+ }
739
767
  proc.stderr.on("data", (chunk) => {
740
768
  stderr += chunk.toString();
741
769
  });
742
770
  proc.once("error", (error) => {
743
771
  exited = true;
744
- reject(new Error(`${recorder.label}: ${error.message}`));
772
+ reject(failure(error.message));
745
773
  });
746
774
  proc.once("exit", (code) => {
747
775
  exited = true;
@@ -750,7 +778,7 @@ function startRecorder(recorder, file) {
750
778
 
751
779
  setTimeout(() => {
752
780
  if (exited) {
753
- reject(new Error(`${recorder.label}: ${lastLine(stderr) || `exited with code ${exitCode}`}`));
781
+ reject(failure(lastLine(stderr) || `exited with code ${exitCode}`));
754
782
  return;
755
783
  }
756
784
 
@@ -758,7 +786,7 @@ function startRecorder(recorder, file) {
758
786
  try {
759
787
  proc.kill("SIGKILL");
760
788
  } catch {}
761
- reject(new Error(`${recorder.label}: did not create an audio file`));
789
+ reject(failure("did not create an audio file"));
762
790
  return;
763
791
  }
764
792
 
@@ -859,23 +887,22 @@ export class VoiceRuntime {
859
887
 
860
888
  async transcribe(audioFile, model, settings = {}) {
861
889
  const commandOptions = { ...this.options, downloadDir: settings.downloadDir };
862
- const whisperCli = resolveCommand("whisper-cli", commandOptions);
863
- if (!whisperCli) {
864
- throw new Error("whisper-cli not found. Install whisper.cpp or set OPENCODE_VOICE_WHISPER_CLI to the binary path.");
865
- }
890
+ const command = model.engine === "transcribe-cpp" ? "opencode-voice-transcribe" : "whisper-cli";
891
+ const binary = resolveCommand(command, commandOptions);
892
+ if (!binary) throw new Error(`${command} not found. Install the managed ${model.engine} engine or set its OPENCODE_VOICE_* binary path.`);
866
893
 
867
894
  const modelFile = getModelPath(model, this.options, settings);
868
895
  if (!fs.existsSync(modelFile)) {
869
896
  throw new Error(`Model is not downloaded: ${model.name}`);
870
897
  }
871
898
 
872
- const args = ["-m", modelFile, "-f", audioFile, "-np", "-nt"];
873
- if (settings.language && settings.language !== "auto") args.push("-l", settings.language);
899
+ const args = model.engine === "transcribe-cpp" ? ["--model", modelFile, "--file", audioFile] : ["-m", modelFile, "-f", audioFile, "-np", "-nt"];
900
+ if (settings.language && settings.language !== "auto") args.push(model.engine === "transcribe-cpp" ? "--language" : "-l", settings.language);
874
901
 
875
902
  return new Promise((resolve, reject) => {
876
903
  let stdout = "";
877
904
  let stderr = "";
878
- const proc = spawn(whisperCli, args, { env: childEnv(commandOptions), stdio: ["ignore", "pipe", "pipe"] });
905
+ const proc = spawn(binary, args, { env: childEnv(commandOptions), stdio: ["ignore", "pipe", "pipe"] });
879
906
  this.transcription = proc;
880
907
 
881
908
  const timer = setTimeout(() => {
@@ -901,7 +928,7 @@ export class VoiceRuntime {
901
928
  clearTimeout(timer);
902
929
  this.transcription = null;
903
930
  if (code !== 0) {
904
- reject(new Error(stderr.trim().split("\n").pop() || `whisper-cli exited with code ${code}`));
931
+ reject(new Error(stderr.trim().split("\n").pop() || `${command} exited with code ${code}`));
905
932
  return;
906
933
  }
907
934
 
package/lib/engines.js CHANGED
@@ -9,13 +9,21 @@ import { sha256, ensureDir, replaceFile } from "./download.js";
9
9
  import { getCacheDir } from "./models.js";
10
10
  import { getBundledEngineDir, resolveCommand } from "./engine.js";
11
11
 
12
- export const DEFAULT_ENGINE_REGISTRY_URL = "https://github.com/ihxnnxs/opencode-voice/releases/download/v0.1.9/registry.json";
13
-
14
- const ENGINE = {
15
- id: "whisper.cpp",
16
- command: "whisper-cli",
17
- probeArgs: ["--help"],
18
- probeContains: ["--model", "--file"],
12
+ export const DEFAULT_ENGINE_REGISTRY_URL = "https://github.com/ihxnnxs/opencode-voice/releases/download/v0.2.0/registry.json";
13
+
14
+ export const ENGINES = {
15
+ "whisper.cpp": {
16
+ id: "whisper.cpp",
17
+ command: "whisper-cli",
18
+ probeArgs: ["--help"],
19
+ probeContains: ["--model", "--file"],
20
+ },
21
+ "transcribe-cpp": {
22
+ id: "transcribe-cpp",
23
+ command: "opencode-voice-transcribe",
24
+ probeArgs: ["--help"],
25
+ probeContains: ["--model", "--file"],
26
+ },
19
27
  };
20
28
 
21
29
  const DEFAULT_ENGINE_DOWNLOAD_RETRIES = 5;
@@ -25,8 +33,15 @@ function sleep(ms) {
25
33
  return new Promise((resolve) => setTimeout(resolve, ms));
26
34
  }
27
35
 
28
- function executableName(options = {}) {
29
- return (options.platform || process.platform) === "win32" ? "whisper-cli.exe" : "whisper-cli";
36
+ function getEngine(engineId) {
37
+ const engine = ENGINES[engineId];
38
+ if (!engine) throw new Error(`Unsupported engine: ${engineId}`);
39
+ return engine;
40
+ }
41
+
42
+ function executableName(engineId, options = {}) {
43
+ const command = getEngine(engineId).command;
44
+ return (options.platform || process.platform) === "win32" ? `${command}.exe` : command;
30
45
  }
31
46
 
32
47
  function temporaryBinaryPath(binaryPath) {
@@ -50,20 +65,19 @@ function withDownloadDir(options = {}, settings = {}) {
50
65
  return { ...options, downloadDir: settings.downloadDir || options.downloadDir };
51
66
  }
52
67
 
53
- export function getManagedEngineDir(engineId = ENGINE.id, options = {}, settings = {}) {
54
- if (engineId !== ENGINE.id) throw new Error(`Unsupported engine: ${engineId}`);
55
- return getBundledEngineDir(ENGINE.command, withDownloadDir(options, settings));
68
+ export function getManagedEngineDir(engineId = "whisper.cpp", options = {}, settings = {}) {
69
+ return getBundledEngineDir(getEngine(engineId).command, withDownloadDir(options, settings));
56
70
  }
57
71
 
58
- export function getManagedEngineBinary(engineId = ENGINE.id, options = {}, settings = {}) {
59
- return path.join(getManagedEngineDir(engineId, options, settings), executableName(options));
72
+ export function getManagedEngineBinary(engineId = "whisper.cpp", options = {}, settings = {}) {
73
+ return path.join(getManagedEngineDir(engineId, options, settings), executableName(engineId, options));
60
74
  }
61
75
 
62
- export function getEngineManifestPath(engineId = ENGINE.id, options = {}, settings = {}) {
76
+ export function getEngineManifestPath(engineId = "whisper.cpp", options = {}, settings = {}) {
63
77
  return path.join(getManagedEngineDir(engineId, options, settings), "manifest.json");
64
78
  }
65
79
 
66
- export function readEngineManifest(engineId = ENGINE.id, options = {}, settings = {}) {
80
+ export function readEngineManifest(engineId = "whisper.cpp", options = {}, settings = {}) {
67
81
  const file = getEngineManifestPath(engineId, options, settings);
68
82
  if (!fs.existsSync(file)) return null;
69
83
  try {
@@ -73,24 +87,27 @@ export function readEngineManifest(engineId = ENGINE.id, options = {}, settings
73
87
  }
74
88
  }
75
89
 
76
- function engineSource(resolved, managedBinary, options = {}) {
90
+ function engineSource(engine, resolved, managedBinary, options = {}) {
77
91
  if (!resolved) return "missing";
78
92
  if (path.resolve(resolved) === path.resolve(managedBinary)) return "managed";
79
- if (options.whisperCli && path.resolve(resolved) === path.resolve(options.whisperCli)) return "option";
80
- if (process.env.OPENCODE_VOICE_WHISPER_CLI && path.resolve(resolved) === path.resolve(process.env.OPENCODE_VOICE_WHISPER_CLI)) return "env";
93
+ const optionKey = engine.id === "whisper.cpp" ? "whisperCli" : "transcribeCpp";
94
+ const envKey = engine.id === "whisper.cpp" ? "OPENCODE_VOICE_WHISPER_CLI" : "OPENCODE_VOICE_TRANSCRIBE_CPP";
95
+ if (options[optionKey] && path.resolve(resolved) === path.resolve(options[optionKey])) return "option";
96
+ if (process.env[envKey] && path.resolve(resolved) === path.resolve(process.env[envKey])) return "env";
81
97
  return "system";
82
98
  }
83
99
 
84
- export function getEngineStatus(engineId = ENGINE.id, options = {}, settings = {}) {
100
+ export function getEngineStatus(engineId = "whisper.cpp", options = {}, settings = {}) {
101
+ const engine = getEngine(engineId);
85
102
  const commandOptions = withDownloadDir(options, settings);
86
103
  const managedDir = getManagedEngineDir(engineId, commandOptions);
87
104
  const managedBinary = getManagedEngineBinary(engineId, commandOptions);
88
105
  const manifest = readEngineManifest(engineId, commandOptions);
89
- const resolvedBinary = resolveCommand(ENGINE.command, commandOptions);
106
+ const resolvedBinary = resolveCommand(engine.command, commandOptions);
90
107
 
91
108
  return {
92
109
  id: engineId,
93
- command: ENGINE.command,
110
+ command: engine.command,
94
111
  platform: getEnginePlatformKey(commandOptions),
95
112
  cacheDir: getCacheDir(commandOptions),
96
113
  managedDir,
@@ -98,7 +115,7 @@ export function getEngineStatus(engineId = ENGINE.id, options = {}, settings = {
98
115
  managedInstalled: fs.existsSync(managedBinary),
99
116
  manifest,
100
117
  resolvedBinary,
101
- source: engineSource(resolvedBinary, managedBinary, commandOptions),
118
+ source: engineSource(engine, resolvedBinary, managedBinary, commandOptions),
102
119
  };
103
120
  }
104
121
 
@@ -114,8 +131,8 @@ function engineProbeMessage(message) {
114
131
  return text || "unknown probe failure";
115
132
  }
116
133
 
117
- export async function probeEngine(engineId = ENGINE.id, binaryPath, options = {}) {
118
- if (engineId !== ENGINE.id) throw new Error(`Unsupported engine: ${engineId}`);
134
+ export async function probeEngine(engineId = "whisper.cpp", binaryPath, options = {}) {
135
+ const engine = getEngine(engineId);
119
136
  if (!binaryPath) return { ok: false, message: "missing binary" };
120
137
 
121
138
  return new Promise((resolve) => {
@@ -136,7 +153,7 @@ export async function probeEngine(engineId = ENGINE.id, binaryPath, options = {}
136
153
  DYLD_LIBRARY_PATH: [localLib, process.env.DYLD_LIBRARY_PATH].filter(Boolean).join(path.delimiter),
137
154
  ...options.env,
138
155
  };
139
- const proc = spawn(binaryPath, ENGINE.probeArgs, { stdio: ["ignore", "pipe", "pipe"], env });
156
+ const proc = spawn(binaryPath, engine.probeArgs, { stdio: ["ignore", "pipe", "pipe"], env });
140
157
  timer = setTimeout(() => {
141
158
  try {
142
159
  proc.kill("SIGKILL");
@@ -154,9 +171,9 @@ export async function probeEngine(engineId = ENGINE.id, binaryPath, options = {}
154
171
  finish({ ok: false, message: engineProbeMessage(error.message) });
155
172
  });
156
173
  proc.on("exit", (code, signal) => {
157
- const ok = ENGINE.probeContains.every((item) => output.includes(item));
174
+ const ok = engine.probeContains.every((item) => output.includes(item));
158
175
  const detail = summarizeProbeOutput(output) || `exit ${code ?? signal ?? "unknown"}`;
159
- finish({ ok, message: ok ? "ok" : engineProbeMessage(`unexpected whisper-cli help output: ${detail}`) });
176
+ finish({ ok, message: ok ? "ok" : engineProbeMessage(`unexpected ${engine.command} help output: ${detail}`) });
160
177
  });
161
178
  });
162
179
  }
@@ -272,13 +289,14 @@ async function downloadAsset(asset, compressedFile, hooks = {}, attempt = 1, att
272
289
  }
273
290
 
274
291
  async function writeManifest(engineId, managedBinary, source, options = {}) {
292
+ const engine = getEngine(engineId);
275
293
  const hash = await sha256(managedBinary);
276
294
  const stat = await fs.promises.stat(managedBinary);
277
295
  const manifest = {
278
296
  schema: "opencode-voice.engine-install.v1",
279
297
  id: engineId,
280
298
  kind: "cli",
281
- command: ENGINE.command,
299
+ command: engine.command,
282
300
  platform: getEnginePlatformKey(options),
283
301
  version: source.version || "local-import",
284
302
  source,
@@ -290,8 +308,8 @@ async function writeManifest(engineId, managedBinary, source, options = {}) {
290
308
  return manifest;
291
309
  }
292
310
 
293
- export async function installManagedEngine(engineId = ENGINE.id, options = {}, settings = {}, hooks = {}) {
294
- if (engineId !== ENGINE.id) throw new Error(`Unsupported engine: ${engineId}`);
311
+ export async function installManagedEngine(engineId = "whisper.cpp", options = {}, settings = {}, hooks = {}) {
312
+ getEngine(engineId);
295
313
 
296
314
  const commandOptions = withDownloadDir(options, settings);
297
315
  const managedDir = getManagedEngineDir(engineId, commandOptions);
@@ -360,9 +378,9 @@ export async function installManagedEngine(engineId = ENGINE.id, options = {}, s
360
378
  throw lastError;
361
379
  }
362
380
 
363
- export async function importManagedEngine(engineId = ENGINE.id, sourcePath, options = {}, settings = {}) {
364
- if (!sourcePath) throw new Error("Pass a whisper-cli path to import");
365
- if (engineId !== ENGINE.id) throw new Error(`Unsupported engine: ${engineId}`);
381
+ export async function importManagedEngine(engineId = "whisper.cpp", sourcePath, options = {}, settings = {}) {
382
+ const engine = getEngine(engineId);
383
+ if (!sourcePath) throw new Error(`Pass an ${engine.command} path to import`);
366
384
 
367
385
  const source = path.resolve(sourcePath.replace(/^~(?=$|\/)/, os.homedir()));
368
386
  const stat = await fs.promises.stat(source).catch(() => null);
@@ -387,7 +405,8 @@ export async function importManagedEngine(engineId = ENGINE.id, sourcePath, opti
387
405
  return { manifest, managedBinary };
388
406
  }
389
407
 
390
- export async function removeManagedEngine(engineId = ENGINE.id, options = {}, settings = {}) {
408
+ export async function removeManagedEngine(engineId = "whisper.cpp", options = {}, settings = {}) {
409
+ getEngine(engineId);
391
410
  const dir = getManagedEngineDir(engineId, options, settings);
392
411
  await fs.promises.rm(dir, { recursive: true, force: true });
393
412
  return dir;