@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.
- package/.env.example +75 -0
- package/CHANGELOG.md +18 -0
- package/LICENSE +21 -0
- package/README.md +259 -0
- package/SECURITY.md +78 -0
- package/img/micme_logo.png +0 -0
- package/package.json +68 -0
- package/scripts/check-package-contents.mjs +50 -0
- package/scripts/doctor.mjs +162 -0
- package/src/audio-level.ts +51 -0
- package/src/audio.ts +199 -0
- package/src/config.ts +256 -0
- package/src/constants.ts +43 -0
- package/src/editor.ts +122 -0
- package/src/extension.ts +351 -0
- package/src/models.ts +236 -0
- package/src/processes.ts +231 -0
- package/src/recording-widget.ts +61 -0
- package/src/settings.ts +948 -0
- package/src/streaming.ts +237 -0
- package/src/transcript-delivery.ts +24 -0
- package/src/transcription.ts +131 -0
- package/src/types.ts +80 -0
- package/tsconfig.json +15 -0
package/src/models.ts
ADDED
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { once } from "node:events";
|
|
3
|
+
import { createWriteStream, existsSync, readdirSync, statSync } from "node:fs";
|
|
4
|
+
import { mkdir, rename, unlink } from "node:fs/promises";
|
|
5
|
+
import { homedir } from "node:os";
|
|
6
|
+
import { basename, dirname, join } from "node:path";
|
|
7
|
+
import { finished } from "node:stream/promises";
|
|
8
|
+
import {
|
|
9
|
+
DEFAULT_WHISPER_CPP_MODEL_NAME,
|
|
10
|
+
STATUS_KEY,
|
|
11
|
+
WHISPER_CPP_MODEL_BASE_URL,
|
|
12
|
+
WHISPER_CPP_MODEL_NAMES,
|
|
13
|
+
} from "./constants.ts";
|
|
14
|
+
import { env, expandConfigPath } from "./config.ts";
|
|
15
|
+
import type { ModelCandidate } from "./types.ts";
|
|
16
|
+
|
|
17
|
+
const modelDownloads = new Map<string, Promise<void>>();
|
|
18
|
+
|
|
19
|
+
export function discoverWhisperCppModels(cwd: string): ModelCandidate[] {
|
|
20
|
+
const candidates: ModelCandidate[] = [];
|
|
21
|
+
const seen = new Set<string>();
|
|
22
|
+
const add = (candidate: ModelCandidate) => {
|
|
23
|
+
const key = candidate.value;
|
|
24
|
+
if (!key || seen.has(key)) return;
|
|
25
|
+
seen.add(key);
|
|
26
|
+
candidates.push(candidate);
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
const current = env("MICME_WHISPER_CPP_MODEL");
|
|
30
|
+
if (current) {
|
|
31
|
+
const expanded = expandConfigPath(current);
|
|
32
|
+
add({
|
|
33
|
+
label: basename(expanded),
|
|
34
|
+
value: expanded,
|
|
35
|
+
description: existsSync(expanded) ? `current model: ${expanded}` : `current model path is missing: ${expanded}`,
|
|
36
|
+
installed: existsSync(expanded),
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
for (const file of scanModelFiles(cwd)) {
|
|
41
|
+
add({ label: basename(file), value: file, description: file, installed: true });
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const cacheDir = getWhisperCppModelCacheDir();
|
|
45
|
+
for (const modelName of WHISPER_CPP_MODEL_NAMES) {
|
|
46
|
+
const path = join(cacheDir, `ggml-${modelName}.bin`);
|
|
47
|
+
add({
|
|
48
|
+
label: `ggml-${modelName}.bin`,
|
|
49
|
+
value: path,
|
|
50
|
+
description: `${describeWhisperModel(modelName)}${existsSync(path) ? "" : " (expected path; download model first)"}`,
|
|
51
|
+
installed: existsSync(path),
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
return candidates.sort((a, b) => Number(b.installed) - Number(a.installed) || a.label.localeCompare(b.label));
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export function scanModelFiles(cwd: string) {
|
|
59
|
+
const directories = new Set<string>();
|
|
60
|
+
const addDir = (path: string | undefined) => {
|
|
61
|
+
if (path) directories.add(expandConfigPath(path));
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
addDir(env("MICME_MODEL_DIR"));
|
|
65
|
+
const currentModel = env("MICME_WHISPER_CPP_MODEL");
|
|
66
|
+
if (currentModel) addDir(dirname(expandConfigPath(currentModel)));
|
|
67
|
+
addDir(join(cwd, "models"));
|
|
68
|
+
addDir(join(cwd, ".micme", "models"));
|
|
69
|
+
addDir(join(homedir(), ".cache", "whisper.cpp"));
|
|
70
|
+
addDir(join(homedir(), ".cache", "whisper"));
|
|
71
|
+
|
|
72
|
+
const files: string[] = [];
|
|
73
|
+
for (const directory of directories) {
|
|
74
|
+
scanModelDirectory(directory, files, 0);
|
|
75
|
+
}
|
|
76
|
+
return files;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export function scanModelDirectory(directory: string, files: string[], depth: number) {
|
|
80
|
+
if (depth > 3 || !existsSync(directory)) return;
|
|
81
|
+
let entries: string[];
|
|
82
|
+
try {
|
|
83
|
+
entries = readdirSync(directory);
|
|
84
|
+
} catch {
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
for (const entry of entries) {
|
|
89
|
+
const path = join(directory, entry);
|
|
90
|
+
let stats;
|
|
91
|
+
try {
|
|
92
|
+
stats = statSync(path);
|
|
93
|
+
} catch {
|
|
94
|
+
continue;
|
|
95
|
+
}
|
|
96
|
+
if (stats.isDirectory()) {
|
|
97
|
+
scanModelDirectory(path, files, depth + 1);
|
|
98
|
+
continue;
|
|
99
|
+
}
|
|
100
|
+
if (/^ggml-.+\.(bin|gguf)$/i.test(entry)) files.push(path);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export function describeWhisperModel(name: string) {
|
|
105
|
+
if (name.startsWith("tiny")) return "fastest, lowest accuracy";
|
|
106
|
+
if (name.startsWith("base")) return "fast baseline";
|
|
107
|
+
if (name.startsWith("small")) return "recommended stronger local model";
|
|
108
|
+
if (name.startsWith("medium")) return "stronger, slower";
|
|
109
|
+
if (name.includes("turbo")) return "large-v3 turbo, strong but larger";
|
|
110
|
+
if (name.startsWith("large")) return "highest accuracy, slowest/largest";
|
|
111
|
+
return "Whisper model";
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export async function ensureWhisperCppModel(modelPath: string, ctx?: ExtensionContext) {
|
|
115
|
+
if (existsSync(modelPath)) return;
|
|
116
|
+
if (env("MICME_AUTO_DOWNLOAD_MODEL") === "0") {
|
|
117
|
+
throw new Error(`Micme model is missing and auto-download is disabled: ${modelPath}`);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
const existingDownload = modelDownloads.get(modelPath);
|
|
121
|
+
if (existingDownload) {
|
|
122
|
+
ctx?.ui.setStatus(STATUS_KEY, `waiting for ${basename(modelPath)} download…`);
|
|
123
|
+
try {
|
|
124
|
+
await existingDownload;
|
|
125
|
+
} finally {
|
|
126
|
+
ctx?.ui.setStatus(STATUS_KEY, undefined);
|
|
127
|
+
}
|
|
128
|
+
return;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
const modelName = getWhisperCppModelNameFromPath(modelPath);
|
|
132
|
+
if (!modelName) {
|
|
133
|
+
throw new Error(`Micme model is missing and cannot infer download URL: ${modelPath}`);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
const download = downloadWhisperCppModel(modelName, modelPath, ctx);
|
|
137
|
+
modelDownloads.set(modelPath, download);
|
|
138
|
+
try {
|
|
139
|
+
await download;
|
|
140
|
+
} finally {
|
|
141
|
+
modelDownloads.delete(modelPath);
|
|
142
|
+
ctx?.ui.setStatus(STATUS_KEY, undefined);
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
export async function downloadWhisperCppModel(modelName: string, modelPath: string, ctx?: ExtensionContext) {
|
|
147
|
+
if (existsSync(modelPath)) return;
|
|
148
|
+
const url = getWhisperCppModelUrl(modelName);
|
|
149
|
+
ctx?.ui.setStatus(STATUS_KEY, `downloading ${basename(modelPath)}…`);
|
|
150
|
+
ctx?.ui.notify(`Downloading ${basename(modelPath)}. This can take a while the first time.`, "info");
|
|
151
|
+
await downloadFile(url, modelPath, ctx);
|
|
152
|
+
ctx?.ui.notify(`Downloaded ${basename(modelPath)}.`, "info");
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
export async function downloadFile(url: string, targetPath: string, ctx?: ExtensionContext) {
|
|
156
|
+
if (existsSync(targetPath)) return;
|
|
157
|
+
await mkdir(dirname(targetPath), { recursive: true });
|
|
158
|
+
const tempPath = `${targetPath}.download-${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}`;
|
|
159
|
+
|
|
160
|
+
const response = await fetch(url);
|
|
161
|
+
if (!response.ok || !response.body) {
|
|
162
|
+
throw new Error(`Failed to download ${url}: HTTP ${response.status} ${response.statusText}`);
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
const totalBytes = Number(response.headers.get("content-length") || "0");
|
|
166
|
+
const reader = response.body.getReader();
|
|
167
|
+
const output = createWriteStream(tempPath, { flags: "wx" });
|
|
168
|
+
let downloadedBytes = 0;
|
|
169
|
+
let lastUpdate = 0;
|
|
170
|
+
|
|
171
|
+
try {
|
|
172
|
+
while (true) {
|
|
173
|
+
const { done, value } = await reader.read();
|
|
174
|
+
if (done) break;
|
|
175
|
+
if (!value) continue;
|
|
176
|
+
downloadedBytes += value.byteLength;
|
|
177
|
+
if (!output.write(Buffer.from(value))) {
|
|
178
|
+
await once(output, "drain");
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
const now = Date.now();
|
|
182
|
+
if (ctx && now - lastUpdate > 1_000) {
|
|
183
|
+
ctx.ui.setStatus(STATUS_KEY, `downloading ${basename(targetPath)} ${formatDownloadProgress(downloadedBytes, totalBytes)}`);
|
|
184
|
+
lastUpdate = now;
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
output.end();
|
|
189
|
+
await finished(output);
|
|
190
|
+
if (existsSync(targetPath)) {
|
|
191
|
+
await unlink(tempPath).catch(() => undefined);
|
|
192
|
+
return;
|
|
193
|
+
}
|
|
194
|
+
await rename(tempPath, targetPath);
|
|
195
|
+
} catch (error) {
|
|
196
|
+
output.destroy();
|
|
197
|
+
await unlink(tempPath).catch(() => undefined);
|
|
198
|
+
throw error;
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
export function getWhisperCppModelNameFromPath(modelPath: string) {
|
|
203
|
+
const match = basename(modelPath).match(/^ggml-(.+)\.(?:bin|gguf)$/i);
|
|
204
|
+
return match?.[1];
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
export function getWhisperCppModelUrl(modelName: string) {
|
|
208
|
+
return `${WHISPER_CPP_MODEL_BASE_URL}/ggml-${modelName}.bin`;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
export function getWhisperCppModelCacheDir() {
|
|
212
|
+
return expandConfigPath(env("MICME_MODEL_DIR") || join(homedir(), ".cache", "whisper.cpp"));
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
export function getDefaultWhisperCppModelPath() {
|
|
216
|
+
const modelName = env("MICME_DEFAULT_WHISPER_CPP_MODEL") || DEFAULT_WHISPER_CPP_MODEL_NAME;
|
|
217
|
+
return join(getWhisperCppModelCacheDir(), `ggml-${modelName}.bin`);
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
export function formatDownloadProgress(downloadedBytes: number, totalBytes: number) {
|
|
221
|
+
if (!totalBytes) return formatBytes(downloadedBytes);
|
|
222
|
+
const percent = Math.max(0, Math.min(100, (downloadedBytes / totalBytes) * 100));
|
|
223
|
+
return `${percent.toFixed(0)}% (${formatBytes(downloadedBytes)}/${formatBytes(totalBytes)})`;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
export function formatBytes(bytes: number) {
|
|
227
|
+
if (bytes < 1024) return `${bytes} B`;
|
|
228
|
+
const units = ["KB", "MB", "GB"];
|
|
229
|
+
let value = bytes / 1024;
|
|
230
|
+
let unit = units[0];
|
|
231
|
+
for (let index = 1; value >= 1024 && index < units.length; index++) {
|
|
232
|
+
value /= 1024;
|
|
233
|
+
unit = units[index];
|
|
234
|
+
}
|
|
235
|
+
return `${value.toFixed(value >= 10 ? 0 : 1)} ${unit}`;
|
|
236
|
+
}
|
package/src/processes.ts
ADDED
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { existsSync } from "node:fs";
|
|
3
|
+
import { rm, stat } from "node:fs/promises";
|
|
4
|
+
import { delimiter, join } from "node:path";
|
|
5
|
+
import { MAX_CAPTURED_OUTPUT_CHARS, MIN_AUDIO_BYTES, RECORDER_STOP_GRACE_MS } from "./constants.ts";
|
|
6
|
+
import { pcm16BufferLevel } from "./audio-level.ts";
|
|
7
|
+
import type { CommandSpec, ExitResult, Recording, RunResult } from "./types.ts";
|
|
8
|
+
|
|
9
|
+
export function spawnRecording(command: CommandSpec, audioPath: string, tempDir: string): Recording {
|
|
10
|
+
const child = spawn(command.command, command.args, {
|
|
11
|
+
stdio: [command.stopInput ? "pipe" : "ignore", "pipe", "pipe"],
|
|
12
|
+
windowsHide: true,
|
|
13
|
+
});
|
|
14
|
+
|
|
15
|
+
let stdout = "";
|
|
16
|
+
let stderr = "";
|
|
17
|
+
let settled = false;
|
|
18
|
+
let audioLevel = 0;
|
|
19
|
+
|
|
20
|
+
if (command.meterFromStdout) {
|
|
21
|
+
child.stdout?.on("data", (chunk: Buffer) => {
|
|
22
|
+
audioLevel = audioLevel * 0.35 + pcm16BufferLevel(chunk) * 0.65;
|
|
23
|
+
});
|
|
24
|
+
} else {
|
|
25
|
+
child.stdout?.setEncoding("utf8");
|
|
26
|
+
child.stdout?.on("data", (chunk: string) => {
|
|
27
|
+
stdout = appendCapped(stdout, chunk);
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
child.stderr?.setEncoding("utf8");
|
|
31
|
+
child.stderr?.on("data", (chunk: string) => {
|
|
32
|
+
stderr = appendCapped(stderr, chunk);
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
const exitPromise = new Promise<ExitResult>((resolve) => {
|
|
36
|
+
child.once("error", (error) => {
|
|
37
|
+
settled = true;
|
|
38
|
+
resolve({ code: null, signal: null, error });
|
|
39
|
+
});
|
|
40
|
+
child.once("close", (code, signal) => {
|
|
41
|
+
settled = true;
|
|
42
|
+
resolve({ code, signal });
|
|
43
|
+
});
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
return {
|
|
47
|
+
process: child,
|
|
48
|
+
audioPath,
|
|
49
|
+
tempDir,
|
|
50
|
+
startedAt: Date.now(),
|
|
51
|
+
command,
|
|
52
|
+
audioLevel: () => audioLevel,
|
|
53
|
+
exitPromise,
|
|
54
|
+
isSettled: () => settled,
|
|
55
|
+
stdout: () => stdout,
|
|
56
|
+
stderr: () => stderr,
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export async function stopProcess(active: Recording) {
|
|
61
|
+
if (!active.isSettled()) {
|
|
62
|
+
active.stopRequested = true;
|
|
63
|
+
let exit: ExitResult | undefined;
|
|
64
|
+
if (sendStopInput(active)) {
|
|
65
|
+
exit = await raceWithTimeout(active.exitPromise, RECORDER_STOP_GRACE_MS);
|
|
66
|
+
}
|
|
67
|
+
if (!exit) {
|
|
68
|
+
active.process.kill("SIGINT");
|
|
69
|
+
exit = await raceWithTimeout(active.exitPromise, RECORDER_STOP_GRACE_MS);
|
|
70
|
+
}
|
|
71
|
+
if (!exit) {
|
|
72
|
+
active.process.kill("SIGTERM");
|
|
73
|
+
exit = await raceWithTimeout(active.exitPromise, 1_000);
|
|
74
|
+
}
|
|
75
|
+
if (!exit) {
|
|
76
|
+
active.process.kill("SIGKILL");
|
|
77
|
+
await active.exitPromise;
|
|
78
|
+
}
|
|
79
|
+
} else {
|
|
80
|
+
await active.exitPromise;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export function sendStopInput(active: Recording) {
|
|
85
|
+
if (!active.command.stopInput || !active.process.stdin || active.process.stdin.destroyed || !active.process.stdin.writable) return false;
|
|
86
|
+
try {
|
|
87
|
+
active.process.stdin.write(active.command.stopInput);
|
|
88
|
+
active.process.stdin.end();
|
|
89
|
+
return true;
|
|
90
|
+
} catch {
|
|
91
|
+
return false;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export async function stopRecorder(active: Recording) {
|
|
96
|
+
await stopProcess(active);
|
|
97
|
+
|
|
98
|
+
const audioStats = await stat(active.audioPath).catch(() => undefined);
|
|
99
|
+
if (!audioStats || audioStats.size < MIN_AUDIO_BYTES) {
|
|
100
|
+
const stderr = active.stderr().trim();
|
|
101
|
+
const suffix = stderr ? `\nRecorder output:\n${stderr}` : "";
|
|
102
|
+
throw new Error(`Micme recorder did not produce usable audio.${suffix}`);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export function runShell(command: string, timeoutMs: number) {
|
|
107
|
+
const spec = shellCommand(command);
|
|
108
|
+
return runProcess(spec.command, spec.args, timeoutMs);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export function shellCommand(command: string): CommandSpec {
|
|
112
|
+
if (process.platform === "win32") {
|
|
113
|
+
return { command: "cmd.exe", args: ["/d", "/s", "/c", command], display: command };
|
|
114
|
+
}
|
|
115
|
+
return { command: "sh", args: ["-lc", command], display: command };
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
export function runProcess(command: string, args: string[], timeoutMs: number): Promise<RunResult> {
|
|
119
|
+
return new Promise((resolve, reject) => {
|
|
120
|
+
const child = spawn(command, args, { stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
|
|
121
|
+
let stdout = "";
|
|
122
|
+
let stderr = "";
|
|
123
|
+
let timedOut = false;
|
|
124
|
+
let settled = false;
|
|
125
|
+
|
|
126
|
+
const timer = setTimeout(() => {
|
|
127
|
+
timedOut = true;
|
|
128
|
+
child.kill("SIGKILL");
|
|
129
|
+
}, timeoutMs);
|
|
130
|
+
|
|
131
|
+
child.stdout?.setEncoding("utf8");
|
|
132
|
+
child.stderr?.setEncoding("utf8");
|
|
133
|
+
child.stdout?.on("data", (chunk: string) => {
|
|
134
|
+
stdout = appendCapped(stdout, chunk);
|
|
135
|
+
});
|
|
136
|
+
child.stderr?.on("data", (chunk: string) => {
|
|
137
|
+
stderr = appendCapped(stderr, chunk);
|
|
138
|
+
});
|
|
139
|
+
child.once("error", (error) => {
|
|
140
|
+
if (settled) return;
|
|
141
|
+
settled = true;
|
|
142
|
+
clearTimeout(timer);
|
|
143
|
+
reject(error);
|
|
144
|
+
});
|
|
145
|
+
child.once("close", (code, signal) => {
|
|
146
|
+
if (settled) return;
|
|
147
|
+
settled = true;
|
|
148
|
+
clearTimeout(timer);
|
|
149
|
+
resolve({ code, signal, stdout, stderr, timedOut });
|
|
150
|
+
});
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
export function normalizeTranscript(text: string) {
|
|
155
|
+
return text
|
|
156
|
+
.replace(/\r\n/g, "\n")
|
|
157
|
+
.split("\n")
|
|
158
|
+
.map((line) => line.trim())
|
|
159
|
+
.filter(Boolean)
|
|
160
|
+
.join(" ")
|
|
161
|
+
.replace(/\s+/g, " ")
|
|
162
|
+
.trim();
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
export function replacePlaceholders(template: string, values: Record<string, string>) {
|
|
166
|
+
let output = template;
|
|
167
|
+
for (const [key, value] of Object.entries(values)) {
|
|
168
|
+
output = output.replaceAll(`{${key}}`, shellQuote(value));
|
|
169
|
+
output = output.replaceAll(`{${key}Raw}`, value);
|
|
170
|
+
}
|
|
171
|
+
return output;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
export function findExecutable(names: string[]) {
|
|
175
|
+
const dirs = (process.env.PATH || "").split(delimiter).filter(Boolean);
|
|
176
|
+
const extensions = process.platform === "win32" ? (process.env.PATHEXT || ".EXE;.CMD;.BAT;.COM").split(";") : [""];
|
|
177
|
+
|
|
178
|
+
for (const name of names) {
|
|
179
|
+
for (const dir of dirs) {
|
|
180
|
+
for (const extension of extensions) {
|
|
181
|
+
const candidate = join(dir, process.platform === "win32" && !/\.[^.]+$/.test(name) ? `${name}${extension}` : name);
|
|
182
|
+
if (existsSync(candidate)) return candidate;
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
return undefined;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
export function appendCapped(current: string, chunk: string) {
|
|
190
|
+
const next = current + chunk;
|
|
191
|
+
return next.length > MAX_CAPTURED_OUTPUT_CHARS ? next.slice(-MAX_CAPTURED_OUTPUT_CHARS) : next;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
export function raceWithTimeout<T>(promise: Promise<T>, timeoutMs: number): Promise<T | undefined> {
|
|
195
|
+
return new Promise((resolve) => {
|
|
196
|
+
const timer = setTimeout(() => resolve(undefined), timeoutMs);
|
|
197
|
+
promise.then(
|
|
198
|
+
(value) => {
|
|
199
|
+
clearTimeout(timer);
|
|
200
|
+
resolve(value);
|
|
201
|
+
},
|
|
202
|
+
() => {
|
|
203
|
+
clearTimeout(timer);
|
|
204
|
+
resolve(undefined);
|
|
205
|
+
},
|
|
206
|
+
);
|
|
207
|
+
});
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
export async function cleanup(tempDir: string) {
|
|
211
|
+
await rm(tempDir, { recursive: true, force: true });
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
export function formatExit(exit: ExitResult) {
|
|
215
|
+
if (exit.error) return exit.error.message;
|
|
216
|
+
if (exit.signal) return `signal ${exit.signal}`;
|
|
217
|
+
return `code ${exit.code}`;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
export function formatRunExit(result: RunResult) {
|
|
221
|
+
if (result.timedOut) return "timeout";
|
|
222
|
+
if (result.signal) return `signal ${result.signal}`;
|
|
223
|
+
return `code ${result.code}`;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
export function shellQuote(value: string) {
|
|
227
|
+
if (process.platform === "win32") {
|
|
228
|
+
return `"${value.replace(/"/g, '\\"')}"`;
|
|
229
|
+
}
|
|
230
|
+
return `'${value.replace(/'/g, `'\\''`)}'`;
|
|
231
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { RECORDING_WIDGET_KEY } from "./constants.ts";
|
|
3
|
+
import { readPcm16WaveLevel } from "./audio-level.ts";
|
|
4
|
+
import type { Recording } from "./types.ts";
|
|
5
|
+
|
|
6
|
+
let recordingWidgetTimer: ReturnType<typeof setInterval> | undefined;
|
|
7
|
+
|
|
8
|
+
export function startRecordingWidget(ctx: ExtensionContext, active: Recording) {
|
|
9
|
+
clearRecordingWidget(ctx);
|
|
10
|
+
let displayLevel = 0;
|
|
11
|
+
const update = () => {
|
|
12
|
+
const elapsedSeconds = Math.max(0, Math.floor((Date.now() - active.startedAt) / 1000));
|
|
13
|
+
const liveLevel = active.audioLevel();
|
|
14
|
+
const measuredLevel = liveLevel > 0 ? liveLevel : readPcm16WaveLevel(active.audioPath);
|
|
15
|
+
displayLevel = displayLevel * 0.55 + measuredLevel * 0.45;
|
|
16
|
+
const line = formatRecordingWidgetLine(ctx, elapsedSeconds, displayLevel);
|
|
17
|
+
ctx.ui.setWidget(RECORDING_WIDGET_KEY, [line]);
|
|
18
|
+
};
|
|
19
|
+
update();
|
|
20
|
+
recordingWidgetTimer = setInterval(update, 120);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function clearRecordingWidget(ctx?: ExtensionContext) {
|
|
24
|
+
if (recordingWidgetTimer) {
|
|
25
|
+
clearInterval(recordingWidgetTimer);
|
|
26
|
+
recordingWidgetTimer = undefined;
|
|
27
|
+
}
|
|
28
|
+
ctx?.ui.setWidget(RECORDING_WIDGET_KEY, undefined);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function formatRecordingWidgetLine(ctx: ExtensionContext, elapsedSeconds: number, audioLevel: number) {
|
|
32
|
+
const dot = ctx.ui.theme.fg("error", "●");
|
|
33
|
+
const time = ctx.ui.theme.fg("accent", formatElapsedTime(elapsedSeconds));
|
|
34
|
+
const wave = ctx.ui.theme.fg("muted", recordingWaveformFrame(audioLevel));
|
|
35
|
+
return `${dot} ${time} ${wave}`;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function recordingWaveformFrame(audioLevel: number) {
|
|
39
|
+
const bars = ["▁", "▂", "▃", "▄", "▅", "▆", "▇", "█"];
|
|
40
|
+
const width = 13;
|
|
41
|
+
const phase = Math.floor(Date.now() / 250) % width;
|
|
42
|
+
const level = Math.max(0, Math.min(1, audioLevel));
|
|
43
|
+
if (level < 0.02) return bars[0].repeat(width);
|
|
44
|
+
|
|
45
|
+
let output = "";
|
|
46
|
+
for (let index = 0; index < width; index++) {
|
|
47
|
+
const x = ((index + phase) % width) / (width - 1);
|
|
48
|
+
const envelope = Math.sin(Math.PI * x);
|
|
49
|
+
const shaped = Math.max(0.06, envelope) * level;
|
|
50
|
+
const barIndex = Math.max(0, Math.min(bars.length - 1, Math.round(shaped * (bars.length - 1))));
|
|
51
|
+
output += bars[barIndex];
|
|
52
|
+
}
|
|
53
|
+
return output;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function formatElapsedTime(totalSeconds: number) {
|
|
57
|
+
const hours = Math.floor(totalSeconds / 3600);
|
|
58
|
+
const minutes = Math.floor((totalSeconds % 3600) / 60);
|
|
59
|
+
const seconds = totalSeconds % 60;
|
|
60
|
+
return [hours, minutes, seconds].map((value) => String(value).padStart(2, "0")).join(":");
|
|
61
|
+
}
|