@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.
- package/CHANGELOG.md +9 -0
- package/README.md +5 -2
- package/SECURITY.md +1 -1
- package/img/demo.gif +0 -0
- package/img/micme_logo.svg +3 -0
- package/package.json +16 -6
- package/scripts/check-format.mjs +89 -0
- package/scripts/doctor.mjs +75 -18
- package/scripts/publish-npm.mjs +179 -74
- package/src/audio.ts +82 -24
- package/src/backends.ts +28 -21
- package/src/config.ts +51 -10
- package/src/editor.ts +6 -1
- package/src/extension.ts +168 -103
- package/src/models.ts +72 -27
- package/src/processes.ts +52 -17
- package/src/settings.ts +116 -65
- package/src/streaming.ts +151 -32
- package/src/terminal-text.ts +42 -4
- package/src/transcription.ts +4 -4
package/src/models.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
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
|
-
import { createWriteStream, existsSync, readdirSync, statSync } from "node:fs";
|
|
4
|
+
import { createWriteStream, existsSync, readdirSync, statSync, type WriteStream } from "node:fs";
|
|
4
5
|
import { mkdir, rename, unlink } from "node:fs/promises";
|
|
5
6
|
import { homedir } from "node:os";
|
|
6
7
|
import { basename, dirname, extname, join } from "node:path";
|
|
@@ -15,10 +16,11 @@ import {
|
|
|
15
16
|
} from "./constants.ts";
|
|
16
17
|
import { env, expandConfigPath, getTranslateToEnglishLanguage } from "./config.ts";
|
|
17
18
|
import { findExecutable, runProcess } from "./processes.ts";
|
|
19
|
+
import { sanitizeTerminalText } from "./terminal-text.ts";
|
|
18
20
|
import type { ModelCandidate, ResolvedWhisperCppModel } from "./types.ts";
|
|
19
21
|
|
|
20
22
|
const modelDownloads = new Map<string, Promise<void>>();
|
|
21
|
-
const PYTHON_WHISPER_MODELS_SCRIPT =
|
|
23
|
+
const PYTHON_WHISPER_MODELS_SCRIPT = String.raw`import whisper; print('\n'.join(whisper.available_models()))`;
|
|
22
24
|
|
|
23
25
|
export function discoverWhisperCppModels(cwd: string): ModelCandidate[] {
|
|
24
26
|
const candidates: ModelCandidate[] = [];
|
|
@@ -33,11 +35,12 @@ export function discoverWhisperCppModels(cwd: string): ModelCandidate[] {
|
|
|
33
35
|
const current = env("MICME_WHISPER_CPP_MODEL");
|
|
34
36
|
if (current) {
|
|
35
37
|
const expanded = expandConfigPath(current);
|
|
38
|
+
const installed = isRegularFile(expanded);
|
|
36
39
|
add({
|
|
37
40
|
label: basename(expanded),
|
|
38
41
|
value: expanded,
|
|
39
|
-
description:
|
|
40
|
-
installed
|
|
42
|
+
description: installed ? `current explicit path: ${expanded}` : `current explicit path is missing or not a file: ${expanded}`,
|
|
43
|
+
installed,
|
|
41
44
|
kind: "path",
|
|
42
45
|
});
|
|
43
46
|
}
|
|
@@ -49,11 +52,12 @@ export function discoverWhisperCppModels(cwd: string): ModelCandidate[] {
|
|
|
49
52
|
const cacheDir = getWhisperCppModelCacheDir();
|
|
50
53
|
for (const modelName of WHISPER_CPP_MODEL_NAMES) {
|
|
51
54
|
const path = join(cacheDir, `ggml-${modelName}.bin`);
|
|
55
|
+
const installed = isRegularFile(path);
|
|
52
56
|
add({
|
|
53
57
|
label: modelName,
|
|
54
58
|
value: path,
|
|
55
|
-
description: `${describeWhisperModel(modelName)} • ${basename(path)}${
|
|
56
|
-
installed
|
|
59
|
+
description: `${describeWhisperModel(modelName)} • ${basename(path)}${installed ? "" : " (expected path; download model first)"}`,
|
|
60
|
+
installed,
|
|
57
61
|
kind: "model-name",
|
|
58
62
|
});
|
|
59
63
|
}
|
|
@@ -162,7 +166,7 @@ function buildResolvedWhisperCppModel(
|
|
|
162
166
|
modelName: metadata.modelName,
|
|
163
167
|
source: metadata.source,
|
|
164
168
|
configuredValue: metadata.configuredValue,
|
|
165
|
-
exists:
|
|
169
|
+
exists: isRegularFile(path),
|
|
166
170
|
downloadable: isDownloadableWhisperCppModelPath(path),
|
|
167
171
|
translationFallbackFrom: metadata.translationFallbackFrom,
|
|
168
172
|
};
|
|
@@ -174,7 +178,7 @@ function getSiblingWhisperCppModelPath(modelPath: string, modelName: string) {
|
|
|
174
178
|
}
|
|
175
179
|
|
|
176
180
|
function getTranslationFallbackSource(rawModelName: string, modelName: string) {
|
|
177
|
-
return rawModelName
|
|
181
|
+
return rawModelName === modelName ? undefined : rawModelName;
|
|
178
182
|
}
|
|
179
183
|
|
|
180
184
|
export function getPythonWhisperModelName() {
|
|
@@ -200,9 +204,11 @@ export function isEnglishOnlyWhisperModelName(modelName: string | undefined) {
|
|
|
200
204
|
}
|
|
201
205
|
|
|
202
206
|
export function isTranslationUnsupportedWhisperModelName(modelName: string | undefined) {
|
|
203
|
-
if (
|
|
204
|
-
|
|
205
|
-
|
|
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;
|
|
206
212
|
}
|
|
207
213
|
|
|
208
214
|
export async function discoverPythonWhisperModels(): Promise<ModelCandidate[]> {
|
|
@@ -249,7 +255,8 @@ export function uniqueModelNames(names: string[]) {
|
|
|
249
255
|
}
|
|
250
256
|
|
|
251
257
|
export async function ensureWhisperCppModel(modelPath: string, ctx?: ExtensionContext, options: { allowDownload?: boolean } = {}) {
|
|
252
|
-
|
|
258
|
+
assertDownloadTargetIsUsable(modelPath, "Micme model path");
|
|
259
|
+
if (isRegularFile(modelPath)) return;
|
|
253
260
|
if (options.allowDownload === false) {
|
|
254
261
|
throw new Error(`Micme model is missing: ${modelPath}`);
|
|
255
262
|
}
|
|
@@ -259,7 +266,7 @@ export async function ensureWhisperCppModel(modelPath: string, ctx?: ExtensionCo
|
|
|
259
266
|
|
|
260
267
|
const existingDownload = modelDownloads.get(modelPath);
|
|
261
268
|
if (existingDownload) {
|
|
262
|
-
ctx?.ui.setStatus(STATUS_KEY, `waiting for ${
|
|
269
|
+
ctx?.ui.setStatus(STATUS_KEY, `waiting for ${safeBasename(modelPath)} download…`);
|
|
263
270
|
try {
|
|
264
271
|
await existingDownload;
|
|
265
272
|
} finally {
|
|
@@ -284,18 +291,21 @@ export async function ensureWhisperCppModel(modelPath: string, ctx?: ExtensionCo
|
|
|
284
291
|
}
|
|
285
292
|
|
|
286
293
|
export async function downloadWhisperCppModel(modelName: string, modelPath: string, ctx?: ExtensionContext) {
|
|
287
|
-
|
|
294
|
+
assertDownloadTargetIsUsable(modelPath, "Micme model path");
|
|
295
|
+
if (isRegularFile(modelPath)) return;
|
|
288
296
|
const url = getWhisperCppModelUrl(modelName);
|
|
289
|
-
|
|
290
|
-
ctx?.ui.
|
|
297
|
+
const displayName = safeBasename(modelPath);
|
|
298
|
+
ctx?.ui.setStatus(STATUS_KEY, `downloading ${displayName}…`);
|
|
299
|
+
ctx?.ui.notify(`Downloading ${displayName}. This can take a while the first time.`, "info");
|
|
291
300
|
await downloadFile(url, modelPath, ctx);
|
|
292
|
-
ctx?.ui.notify(`Downloaded ${
|
|
301
|
+
ctx?.ui.notify(`Downloaded ${displayName}.`, "info");
|
|
293
302
|
}
|
|
294
303
|
|
|
295
304
|
export async function downloadFile(url: string, targetPath: string, ctx?: ExtensionContext) {
|
|
296
|
-
|
|
305
|
+
assertDownloadTargetIsUsable(targetPath, "Download target");
|
|
306
|
+
if (isRegularFile(targetPath)) return;
|
|
297
307
|
await mkdir(dirname(targetPath), { recursive: true });
|
|
298
|
-
const tempPath = `${targetPath}.download-${process.pid}-${Date.now()}-${
|
|
308
|
+
const tempPath = `${targetPath}.download-${process.pid}-${Date.now()}-${randomUUID()}`;
|
|
299
309
|
|
|
300
310
|
const response = await fetch(url);
|
|
301
311
|
if (!response.ok || !response.body) {
|
|
@@ -305,6 +315,8 @@ export async function downloadFile(url: string, targetPath: string, ctx?: Extens
|
|
|
305
315
|
const totalBytes = Number(response.headers.get("content-length") || "0");
|
|
306
316
|
const reader = response.body.getReader();
|
|
307
317
|
const output = createWriteStream(tempPath, { flags: "wx" });
|
|
318
|
+
const outputFinished = finished(output);
|
|
319
|
+
outputFinished.catch(() => undefined);
|
|
308
320
|
let downloadedBytes = 0;
|
|
309
321
|
let lastUpdate = 0;
|
|
310
322
|
|
|
@@ -314,38 +326,45 @@ export async function downloadFile(url: string, targetPath: string, ctx?: Extens
|
|
|
314
326
|
if (done) break;
|
|
315
327
|
if (!value) continue;
|
|
316
328
|
downloadedBytes += value.byteLength;
|
|
317
|
-
|
|
318
|
-
await once(output, "drain");
|
|
319
|
-
}
|
|
329
|
+
await writeDownloadChunk(output, Buffer.from(value), outputFinished);
|
|
320
330
|
|
|
321
331
|
const now = Date.now();
|
|
322
332
|
if (ctx && now - lastUpdate > 1_000) {
|
|
323
|
-
ctx.ui.setStatus(STATUS_KEY, `downloading ${
|
|
333
|
+
ctx.ui.setStatus(STATUS_KEY, `downloading ${safeBasename(targetPath)} ${formatDownloadProgress(downloadedBytes, totalBytes)}`);
|
|
324
334
|
lastUpdate = now;
|
|
325
335
|
}
|
|
326
336
|
}
|
|
327
337
|
|
|
328
338
|
output.end();
|
|
329
|
-
await
|
|
330
|
-
if (
|
|
339
|
+
await outputFinished;
|
|
340
|
+
if (isRegularFile(targetPath)) {
|
|
331
341
|
await unlink(tempPath).catch(() => undefined);
|
|
332
342
|
return;
|
|
333
343
|
}
|
|
344
|
+
assertDownloadTargetIsUsable(targetPath, "Download target");
|
|
334
345
|
await rename(tempPath, targetPath);
|
|
335
346
|
} catch (error) {
|
|
347
|
+
await reader.cancel().catch(() => undefined);
|
|
336
348
|
output.destroy();
|
|
349
|
+
await outputFinished.catch(() => undefined);
|
|
337
350
|
await unlink(tempPath).catch(() => undefined);
|
|
338
351
|
throw error;
|
|
339
352
|
}
|
|
340
353
|
}
|
|
341
354
|
|
|
355
|
+
async function writeDownloadChunk(output: WriteStream, chunk: Buffer, outputFinished: Promise<void>) {
|
|
356
|
+
if (output.destroyed) await outputFinished;
|
|
357
|
+
if (output.write(chunk)) return;
|
|
358
|
+
await Promise.race([once(output, "drain"), outputFinished]);
|
|
359
|
+
}
|
|
360
|
+
|
|
342
361
|
export function getWhisperCppModelNameFromPath(modelPath: string) {
|
|
343
|
-
const match =
|
|
362
|
+
const match = /^ggml-(.+)\.(?:bin|gguf)$/i.exec(basename(modelPath));
|
|
344
363
|
return match?.[1];
|
|
345
364
|
}
|
|
346
365
|
|
|
347
366
|
export function getDownloadableWhisperCppModelName(modelPath: string) {
|
|
348
|
-
const match =
|
|
367
|
+
const match = /^ggml-(.+)\.bin$/i.exec(basename(modelPath));
|
|
349
368
|
const modelName = match?.[1];
|
|
350
369
|
return modelName && isKnownWhisperCppModelName(modelName) ? modelName : undefined;
|
|
351
370
|
}
|
|
@@ -389,3 +408,29 @@ export function formatBytes(bytes: number) {
|
|
|
389
408
|
}
|
|
390
409
|
return `${value.toFixed(value >= 10 ? 0 : 1)} ${unit}`;
|
|
391
410
|
}
|
|
411
|
+
|
|
412
|
+
function safeBasename(path: string) {
|
|
413
|
+
return sanitizeTerminalText(basename(path)) || "model";
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
function isRegularFile(path: string) {
|
|
417
|
+
try {
|
|
418
|
+
return statSync(path).isFile();
|
|
419
|
+
} catch {
|
|
420
|
+
return false;
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
function assertDownloadTargetIsUsable(path: string, label: string) {
|
|
425
|
+
try {
|
|
426
|
+
if (statSync(path).isFile()) return;
|
|
427
|
+
} catch (error) {
|
|
428
|
+
if (isNotFoundError(error)) return;
|
|
429
|
+
throw error;
|
|
430
|
+
}
|
|
431
|
+
throw new Error(`${label} exists but is not a file: ${path}`);
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
function isNotFoundError(error: unknown) {
|
|
435
|
+
return typeof error === "object" && error !== null && "code" in error && (error as NodeJS.ErrnoException).code === "ENOENT";
|
|
436
|
+
}
|
package/src/processes.ts
CHANGED
|
@@ -4,6 +4,7 @@ import { rm, stat } from "node:fs/promises";
|
|
|
4
4
|
import { delimiter, join } from "node:path";
|
|
5
5
|
import { MAX_CAPTURED_OUTPUT_CHARS, MIN_AUDIO_BYTES, RECORDER_STOP_GRACE_MS } from "./constants.ts";
|
|
6
6
|
import { pcm16BufferLevel } from "./audio-level.ts";
|
|
7
|
+
import { sanitizeTerminalOutput, stripTerminalControlSequences } from "./terminal-text.ts";
|
|
7
8
|
import type { CommandSpec, ExitResult, Recording, RunResult } from "./types.ts";
|
|
8
9
|
|
|
9
10
|
export function spawnRecording(command: CommandSpec, audioPath: string, tempDir: string): Recording {
|
|
@@ -60,7 +61,9 @@ export function spawnRecording(command: CommandSpec, audioPath: string, tempDir:
|
|
|
60
61
|
}
|
|
61
62
|
|
|
62
63
|
export async function stopProcess(active: Recording) {
|
|
63
|
-
if (
|
|
64
|
+
if (active.isSettled()) {
|
|
65
|
+
await active.exitPromise;
|
|
66
|
+
} else {
|
|
64
67
|
active.stopRequested = true;
|
|
65
68
|
let exit: ExitResult | undefined;
|
|
66
69
|
if (sendStopInput(active)) {
|
|
@@ -78,8 +81,6 @@ export async function stopProcess(active: Recording) {
|
|
|
78
81
|
active.process.kill("SIGKILL");
|
|
79
82
|
await active.exitPromise;
|
|
80
83
|
}
|
|
81
|
-
} else {
|
|
82
|
-
await active.exitPromise;
|
|
83
84
|
}
|
|
84
85
|
}
|
|
85
86
|
|
|
@@ -99,7 +100,7 @@ export async function stopRecorder(active: Recording) {
|
|
|
99
100
|
|
|
100
101
|
const audioStats = await stat(active.audioPath).catch(() => undefined);
|
|
101
102
|
if (!audioStats || audioStats.size < MIN_AUDIO_BYTES) {
|
|
102
|
-
const stderr = active.stderr()
|
|
103
|
+
const stderr = formatProcessOutput(active.stderr());
|
|
103
104
|
const suffix = stderr ? `\nRecorder output:\n${stderr}` : "";
|
|
104
105
|
throw new Error(`Micme recorder did not produce usable audio.${suffix}`);
|
|
105
106
|
}
|
|
@@ -154,8 +155,8 @@ export function runProcess(command: string, args: string[], timeoutMs: number):
|
|
|
154
155
|
}
|
|
155
156
|
|
|
156
157
|
export function normalizeTranscript(text: string) {
|
|
157
|
-
return text
|
|
158
|
-
.
|
|
158
|
+
return stripTerminalControlSequences(text)
|
|
159
|
+
.replaceAll("\r\n", "\n")
|
|
159
160
|
.split("\n")
|
|
160
161
|
.map((line) => line.trim())
|
|
161
162
|
.filter(Boolean)
|
|
@@ -166,27 +167,51 @@ export function normalizeTranscript(text: string) {
|
|
|
166
167
|
|
|
167
168
|
export function replacePlaceholders(template: string, values: Record<string, string>) {
|
|
168
169
|
return template.replace(/\{([A-Za-z][A-Za-z0-9]*?)(Raw)?\}/g, (placeholder, key: string, rawSuffix: string | undefined) => {
|
|
169
|
-
if (!Object.
|
|
170
|
+
if (!Object.hasOwn(values, key)) return placeholder;
|
|
170
171
|
const value = values[key] ?? "";
|
|
171
172
|
return rawSuffix ? value : shellQuote(value);
|
|
172
173
|
});
|
|
173
174
|
}
|
|
174
175
|
|
|
175
176
|
export function findExecutable(names: string[]) {
|
|
176
|
-
const dirs = (
|
|
177
|
-
const extensions =
|
|
177
|
+
const dirs = getPathDirectories();
|
|
178
|
+
const extensions = getExecutableExtensions();
|
|
178
179
|
|
|
179
180
|
for (const name of names) {
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
181
|
+
const executable = findExecutableByName(name, dirs, extensions);
|
|
182
|
+
if (executable) return executable;
|
|
183
|
+
}
|
|
184
|
+
return undefined;
|
|
185
|
+
}
|
|
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;
|
|
186
207
|
}
|
|
187
208
|
return undefined;
|
|
188
209
|
}
|
|
189
210
|
|
|
211
|
+
function getExecutableFileName(name: string, extension: string) {
|
|
212
|
+
return process.platform === "win32" && !/\.[^.]+$/.test(name) ? `${name}${extension}` : name;
|
|
213
|
+
}
|
|
214
|
+
|
|
190
215
|
export function isExecutableFile(path: string) {
|
|
191
216
|
try {
|
|
192
217
|
const stats = statSync(path);
|
|
@@ -204,6 +229,14 @@ export function appendCapped(current: string, chunk: string) {
|
|
|
204
229
|
return next.length > MAX_CAPTURED_OUTPUT_CHARS ? next.slice(-MAX_CAPTURED_OUTPUT_CHARS) : next;
|
|
205
230
|
}
|
|
206
231
|
|
|
232
|
+
export function formatProcessOutput(...outputs: string[]) {
|
|
233
|
+
for (const output of outputs) {
|
|
234
|
+
const sanitized = sanitizeTerminalOutput(output);
|
|
235
|
+
if (sanitized) return sanitized;
|
|
236
|
+
}
|
|
237
|
+
return "";
|
|
238
|
+
}
|
|
239
|
+
|
|
207
240
|
export function raceWithTimeout<T>(promise: Promise<T>, timeoutMs: number): Promise<T | undefined> {
|
|
208
241
|
return new Promise((resolve) => {
|
|
209
242
|
const timer = setTimeout(() => resolve(undefined), timeoutMs);
|
|
@@ -238,7 +271,9 @@ export function formatRunExit(result: RunResult) {
|
|
|
238
271
|
|
|
239
272
|
export function shellQuote(value: string) {
|
|
240
273
|
if (process.platform === "win32") {
|
|
241
|
-
|
|
274
|
+
const escapedValue = value.replaceAll('"', String.raw`\"`);
|
|
275
|
+
return `"${escapedValue}"`;
|
|
242
276
|
}
|
|
243
|
-
|
|
277
|
+
const escapedValue = value.replaceAll("'", String.raw`'\''`);
|
|
278
|
+
return `'${escapedValue}'`;
|
|
244
279
|
}
|