@thothdev/pink 1.0.10 → 1.0.12

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.
@@ -0,0 +1,221 @@
1
+ {
2
+ "why": "motor do /microfone: o npm ci instala só estas versões, conferidas pelo sha512 de cada pacote",
3
+ "package": {
4
+ "name": "pink-microfone",
5
+ "private": true,
6
+ "dependencies": {
7
+ "sherpa-onnx-node": "2.0.1",
8
+ "decibri": "5.8.0"
9
+ }
10
+ },
11
+ "lock": {
12
+ "name": "pink-microfone",
13
+ "lockfileVersion": 3,
14
+ "requires": true,
15
+ "packages": {
16
+ "": {
17
+ "name": "pink-microfone",
18
+ "dependencies": {
19
+ "decibri": "5.8.0",
20
+ "sherpa-onnx-node": "2.0.1"
21
+ }
22
+ },
23
+ "node_modules/@decibri/decibri-darwin-arm64": {
24
+ "version": "5.8.0",
25
+ "resolved": "https://registry.npmjs.org/@decibri/decibri-darwin-arm64/-/decibri-darwin-arm64-5.8.0.tgz",
26
+ "integrity": "sha512-dv86BvRoP+IlS/ucJ73vGP/mzGgRcLvyoS0MxoCAkSnrlWKFhKzW6fbm7rqberIkODsiJPHjUfXuSIAd06KC+g==",
27
+ "cpu": [
28
+ "arm64"
29
+ ],
30
+ "license": "Apache-2.0",
31
+ "optional": true,
32
+ "os": [
33
+ "darwin"
34
+ ]
35
+ },
36
+ "node_modules/@decibri/decibri-linux-arm64-gnu": {
37
+ "version": "5.8.0",
38
+ "resolved": "https://registry.npmjs.org/@decibri/decibri-linux-arm64-gnu/-/decibri-linux-arm64-gnu-5.8.0.tgz",
39
+ "integrity": "sha512-wlzVMVh5aWzVyZgaSNJ0ZfpUfyGsb+plNGdlEcg5bLZ5KFhnT5D/y9YBA+Q+NKLdyzO/mgrsuZpf9VS6ZDJHbw==",
40
+ "cpu": [
41
+ "arm64"
42
+ ],
43
+ "license": "Apache-2.0",
44
+ "optional": true,
45
+ "os": [
46
+ "linux"
47
+ ]
48
+ },
49
+ "node_modules/@decibri/decibri-linux-x64-gnu": {
50
+ "version": "5.8.0",
51
+ "resolved": "https://registry.npmjs.org/@decibri/decibri-linux-x64-gnu/-/decibri-linux-x64-gnu-5.8.0.tgz",
52
+ "integrity": "sha512-+43s3AzpktZiDy2ws47v59TzUivhFo8TQYUKU/EcDdRRebYCnlEHGSeoSDkjI30lW4m85nURETfxEWsGbKtcGg==",
53
+ "cpu": [
54
+ "x64"
55
+ ],
56
+ "license": "Apache-2.0",
57
+ "optional": true,
58
+ "os": [
59
+ "linux"
60
+ ]
61
+ },
62
+ "node_modules/@decibri/decibri-win32-arm64-msvc": {
63
+ "version": "5.8.0",
64
+ "resolved": "https://registry.npmjs.org/@decibri/decibri-win32-arm64-msvc/-/decibri-win32-arm64-msvc-5.8.0.tgz",
65
+ "integrity": "sha512-FS1yvuj0UpG9WDTG3JIcDR1UyGDBNKw+Ht7LVhqJDs4uoJmSnrMTTuHzqyY5QuznVE6jyFkTCIl+/XKku48GoA==",
66
+ "cpu": [
67
+ "arm64"
68
+ ],
69
+ "license": "Apache-2.0",
70
+ "optional": true,
71
+ "os": [
72
+ "win32"
73
+ ]
74
+ },
75
+ "node_modules/@decibri/decibri-win32-x64-msvc": {
76
+ "version": "5.8.0",
77
+ "resolved": "https://registry.npmjs.org/@decibri/decibri-win32-x64-msvc/-/decibri-win32-x64-msvc-5.8.0.tgz",
78
+ "integrity": "sha512-pAmKh6fp3VLaOVD6bChCZFLqThM+pzohb/2BYDN99+3thrb9/cZYgfTocXZ/WjRuHHvR6ErjgQ1wed63unQKYQ==",
79
+ "cpu": [
80
+ "x64"
81
+ ],
82
+ "license": "Apache-2.0",
83
+ "optional": true,
84
+ "os": [
85
+ "win32"
86
+ ]
87
+ },
88
+ "node_modules/decibri": {
89
+ "version": "5.8.0",
90
+ "resolved": "https://registry.npmjs.org/decibri/-/decibri-5.8.0.tgz",
91
+ "integrity": "sha512-mAIFQ0jMmGj4UqF56UDHtX53PvUMpEE4odTUfhvR8ejG2VvohiSPc4hSk83IUNRxj1unrEuSeF0G6RPtaegR6Q==",
92
+ "cpu": [
93
+ "x64",
94
+ "arm64"
95
+ ],
96
+ "license": "Apache-2.0",
97
+ "os": [
98
+ "win32",
99
+ "darwin",
100
+ "linux"
101
+ ],
102
+ "engines": {
103
+ "node": ">=18.0.0"
104
+ },
105
+ "optionalDependencies": {
106
+ "@decibri/decibri-darwin-arm64": "5.8.0",
107
+ "@decibri/decibri-linux-arm64-gnu": "5.8.0",
108
+ "@decibri/decibri-linux-x64-gnu": "5.8.0",
109
+ "@decibri/decibri-win32-arm64-msvc": "5.8.0",
110
+ "@decibri/decibri-win32-x64-msvc": "5.8.0"
111
+ }
112
+ },
113
+ "node_modules/sherpa-onnx-darwin-arm64": {
114
+ "version": "2.0.1",
115
+ "resolved": "https://registry.npmjs.org/sherpa-onnx-darwin-arm64/-/sherpa-onnx-darwin-arm64-2.0.1.tgz",
116
+ "integrity": "sha512-agXmbbwiVPUSMViMhWhYAt59iG21ui7x6HxQFU35XzHOfQe9x6Pg9V160Pzak/66x0ePMjixsLUtMaaUrLfCwQ==",
117
+ "cpu": [
118
+ "arm64"
119
+ ],
120
+ "license": "Apache-2.0",
121
+ "optional": true,
122
+ "os": [
123
+ "darwin"
124
+ ]
125
+ },
126
+ "node_modules/sherpa-onnx-darwin-x64": {
127
+ "version": "2.0.1",
128
+ "resolved": "https://registry.npmjs.org/sherpa-onnx-darwin-x64/-/sherpa-onnx-darwin-x64-2.0.1.tgz",
129
+ "integrity": "sha512-SBnHa3LDOSI/5/rpBHGxKQDFq+yIdxowYY0InLzfojTUx+yGgqu7cYBrRxjzvHOiOKi0O4rmlFVZboyhIqpDgA==",
130
+ "cpu": [
131
+ "x64"
132
+ ],
133
+ "license": "Apache-2.0",
134
+ "optional": true,
135
+ "os": [
136
+ "darwin"
137
+ ]
138
+ },
139
+ "node_modules/sherpa-onnx-linux-arm64": {
140
+ "version": "2.0.1",
141
+ "resolved": "https://registry.npmjs.org/sherpa-onnx-linux-arm64/-/sherpa-onnx-linux-arm64-2.0.1.tgz",
142
+ "integrity": "sha512-5CJvLjFYIg23oELCsT7l07fMLT3PdquZ3tqh7KZK3Pzi+c2YiPKRe1DDUxoNdtCaw3ZiS4aQSQPBblB9JStuDA==",
143
+ "cpu": [
144
+ "arm64"
145
+ ],
146
+ "license": "Apache-2.0",
147
+ "optional": true,
148
+ "os": [
149
+ "linux"
150
+ ]
151
+ },
152
+ "node_modules/sherpa-onnx-linux-x64": {
153
+ "version": "2.0.1",
154
+ "resolved": "https://registry.npmjs.org/sherpa-onnx-linux-x64/-/sherpa-onnx-linux-x64-2.0.1.tgz",
155
+ "integrity": "sha512-w5mRRrIvPvcNWac7rQ8AN/t/cwElPGoRpH+ceCRBV7XfjCIQ9Rcr3Ig/kXcJLNOxgK4bGmef+Y47lIWiesDODw==",
156
+ "cpu": [
157
+ "x64"
158
+ ],
159
+ "license": "Apache-2.0",
160
+ "optional": true,
161
+ "os": [
162
+ "linux"
163
+ ]
164
+ },
165
+ "node_modules/sherpa-onnx-node": {
166
+ "version": "2.0.1",
167
+ "resolved": "https://registry.npmjs.org/sherpa-onnx-node/-/sherpa-onnx-node-2.0.1.tgz",
168
+ "integrity": "sha512-1PSACfQgPXAD7ExwCv1QW09EXTjcNlpZKBqDY+jxSdIzlyOSq0M13SILBoUQUfeJqiTTXnqp6Ha9jjMUQ6efXg==",
169
+ "license": "Apache-2.0",
170
+ "optionalDependencies": {
171
+ "sherpa-onnx-darwin-arm64": "2.0.1",
172
+ "sherpa-onnx-darwin-x64": "2.0.1",
173
+ "sherpa-onnx-linux-arm64": "2.0.1",
174
+ "sherpa-onnx-linux-x64": "2.0.1",
175
+ "sherpa-onnx-win-arm64": "2.0.1",
176
+ "sherpa-onnx-win-ia32": "2.0.1",
177
+ "sherpa-onnx-win-x64": "2.0.1"
178
+ }
179
+ },
180
+ "node_modules/sherpa-onnx-win-arm64": {
181
+ "version": "2.0.1",
182
+ "resolved": "https://registry.npmjs.org/sherpa-onnx-win-arm64/-/sherpa-onnx-win-arm64-2.0.1.tgz",
183
+ "integrity": "sha512-Mb9iqy2Zp7GC5a99dk5E8EQJsEBnapf+IcwHLVCgtIf5mxYHO9Q8YptnAoOHZOD0Zi+R+MblFyG9qv0Q6tin4Q==",
184
+ "cpu": [
185
+ "arm64"
186
+ ],
187
+ "license": "Apache-2.0",
188
+ "optional": true,
189
+ "os": [
190
+ "win32"
191
+ ]
192
+ },
193
+ "node_modules/sherpa-onnx-win-ia32": {
194
+ "version": "2.0.1",
195
+ "resolved": "https://registry.npmjs.org/sherpa-onnx-win-ia32/-/sherpa-onnx-win-ia32-2.0.1.tgz",
196
+ "integrity": "sha512-q7qFCA3FK+tYc8pexC9Kzu9WGGoZ9X//UkpxVp6iT4E4W5tPhOEirPyvawS6zgfEW6K/GOISMcYe996Yc7d6iw==",
197
+ "cpu": [
198
+ "ia32"
199
+ ],
200
+ "license": "Apache-2.0",
201
+ "optional": true,
202
+ "os": [
203
+ "win32"
204
+ ]
205
+ },
206
+ "node_modules/sherpa-onnx-win-x64": {
207
+ "version": "2.0.1",
208
+ "resolved": "https://registry.npmjs.org/sherpa-onnx-win-x64/-/sherpa-onnx-win-x64-2.0.1.tgz",
209
+ "integrity": "sha512-7vwdAw9PGEb0JLSpK7UFxAdp1vabBHK9Nhw2jFRBWSFgtslUPHIB0T6syJfRgiUGyCeNW9fJvcFAk2F2u7hBEw==",
210
+ "cpu": [
211
+ "x64"
212
+ ],
213
+ "license": "Apache-2.0",
214
+ "optional": true,
215
+ "os": [
216
+ "win32"
217
+ ]
218
+ }
219
+ }
220
+ }
221
+ }
@@ -0,0 +1,393 @@
1
+ // Microfone opcional (owner 2026-11-25): o botão "◉ falar" na caixa de digitar grava, a fala vira texto ao vivo na caixa,
2
+ // e "‖ pausar", "■ parar" (o texto fica na caixa) e "➤ enviar" (manda ao agente). Mesmo modelo do OpenBot: NVIDIA Parakeet
3
+ // TDT 0.6B v3 int8 (CC-BY-4.0), rodando local com o sherpa-onnx; o áudio nunca sai da máquina.
4
+ // Nada vem instalado: /microfone instalar (com o ok da pessoa) põe em ~/.pink/agent/microfone o motor (sherpa-onnx-node e
5
+ // decibri, pelo npm ci do lock que vem com o Pink, conferido pelo sha512 de cada pacote) e o modelo (GitHub oficial do
6
+ // sherpa-onnx, conferido pelo SHA-256). O VAD (Silero) é o que vem dentro do decibri.
7
+ import { spawnSync } from "node:child_process";
8
+ import crypto from "node:crypto";
9
+ import fs from "node:fs";
10
+ import { createRequire } from "node:module";
11
+ import os from "node:os";
12
+ import path from "node:path";
13
+ import { fileURLToPath } from "node:url";
14
+ import { type Choice, choose, completeFrom, t } from "./pink-i18n.ts";
15
+
16
+ export const MODEL = {
17
+ name: "sherpa-onnx-nemo-parakeet-tdt-0.6b-v3-int8",
18
+ url: "https://github.com/k2-fsa/sherpa-onnx/releases/download/asr-models/sherpa-onnx-nemo-parakeet-tdt-0.6b-v3-int8.tar.bz2",
19
+ sha256: "1495e91b59d7fc53ddca91f3431758ec99f8fa253fdb0e1e851be0f72b14b0f9",
20
+ bytes: 487211443,
21
+ };
22
+ export const MODEL_FILES = ["encoder.int8.onnx", "decoder.int8.onnx", "joiner.int8.onnx", "tokens.txt"];
23
+ export const ENGINE = ["sherpa-onnx-node", "decibri"];
24
+ export const SAMPLE_RATE = 16000;
25
+ const WINDOW = 512; // o Silero VAD lê janelas de 512 amostras a 16 kHz
26
+ const PARTIAL_MS = 1200; // de quanto em quanto tempo a fala em curso é transcrita de novo (o texto "ao vivo")
27
+ export const SIZE_MB = 530; // motor (~42 MB) + modelo (~465 MB), para a pergunta de instalar
28
+
29
+ export const micDir = (env = process.env) => path.join(env.PINK_CODING_AGENT_DIR || path.join(os.homedir(), ".pink", "agent"), "microfone");
30
+ const modelDir = (env = process.env) => path.join(micDir(env), "model");
31
+ const vadModel = (env = process.env) => path.join(micDir(env), "node_modules", "decibri", "models", "silero_vad.onnx");
32
+
33
+ export function installed(env = process.env, exists = fs.existsSync): boolean {
34
+ const dir = micDir(env);
35
+ return ENGINE.every((name) => exists(path.join(dir, "node_modules", name, "package.json"))) && MODEL_FILES.every((name) => exists(path.join(modelDir(env), name))) && exists(vadModel(env));
36
+ }
37
+
38
+ const lockFile = () => path.join(path.dirname(fileURLToPath(import.meta.url)), "pink-microfone-lock.json");
39
+
40
+ type Fetch = (url: string, init?: any) => Promise<any>;
41
+ type Sync = typeof spawnSync;
42
+
43
+ // o modelo baixado vai para o disco enquanto o hash é calculado (são ~465 MB: nada de guardar tudo na memória)
44
+ async function download(url: string, file: string, fetcher: Fetch, progress?: (percent: number) => void): Promise<string> {
45
+ const response = await fetcher(url, { redirect: "follow", signal: AbortSignal.timeout(30 * 60_000) });
46
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
47
+ const hash = crypto.createHash("sha256");
48
+ const out = fs.createWriteStream(file);
49
+ let got = 0;
50
+ let shown = -1;
51
+ try {
52
+ for await (const chunk of response.body as AsyncIterable<Uint8Array>) {
53
+ got += chunk.length;
54
+ if (got > MODEL.bytes * 1.05) throw new Error(t("o download é maior que o esperado", "la descarga es más grande de lo esperado", "the download is larger than expected"));
55
+ hash.update(chunk);
56
+ if (!out.write(chunk)) await new Promise((done) => out.once("drain", done));
57
+ const percent = Math.floor((got / MODEL.bytes) * 10) * 10;
58
+ if (percent !== shown) progress?.((shown = percent));
59
+ }
60
+ } finally {
61
+ await new Promise((done) => out.end(done));
62
+ }
63
+ return hash.digest("hex");
64
+ }
65
+
66
+ export async function install({ env = process.env, fetcher = globalThis.fetch as unknown as Fetch, sync = spawnSync as Sync, progress = undefined as ((text: string) => void) | undefined } = {}): Promise<string> {
67
+ const dir = micDir(env);
68
+ const fail = (why: string) => t(`Microfone: ${why}; não instalei nada.`, `Micrófono: ${why}; no instalé nada.`, `Microphone: ${why}; nothing was installed.`);
69
+ fs.mkdirSync(dir, { recursive: true });
70
+ for (const old of fs.readdirSync(dir)) if (old.startsWith("baixando-")) fs.rmSync(path.join(dir, old), { recursive: true, force: true });
71
+ const work = fs.mkdtempSync(path.join(dir, "baixando-"));
72
+ try {
73
+ // 1) o motor: package.json + package-lock.json do Pink e npm ci (sem scripts de instalação)
74
+ const { package: pkg, lock } = JSON.parse(fs.readFileSync(lockFile(), "utf8"));
75
+ fs.writeFileSync(path.join(dir, "package.json"), JSON.stringify(pkg, null, 2));
76
+ fs.writeFileSync(path.join(dir, "package-lock.json"), JSON.stringify(lock, null, 2));
77
+ progress?.(t("Microfone: instalando o motor (sherpa-onnx e decibri)…", "Micrófono: instalando el motor (sherpa-onnx y decibri)…", "Microphone: installing the engine (sherpa-onnx and decibri)…"));
78
+ // argumentos fixos; no Windows o npm é um .cmd, que só roda pelo shell
79
+ const npm = sync("npm", ["ci", "--ignore-scripts", "--omit=dev", "--no-audit", "--no-fund"], { cwd: dir, shell: process.platform === "win32", windowsHide: true, timeout: 10 * 60_000, encoding: "utf8" });
80
+ if (npm.status !== 0) return fail(t(`o npm ci falhou (${String(npm.stderr || npm.error?.message || "").trim().slice(-200)})`, `npm ci falló (${String(npm.stderr || npm.error?.message || "").trim().slice(-200)})`, `npm ci failed (${String(npm.stderr || npm.error?.message || "").trim().slice(-200)})`));
81
+ // 2) o modelo: baixado uma vez; reinstalar só o motor não baixa de novo
82
+ const marker = path.join(modelDir(env), ".sha256");
83
+ const have = fs.existsSync(marker) && fs.readFileSync(marker, "utf8").trim() === MODEL.sha256 && MODEL_FILES.every((name) => fs.existsSync(path.join(modelDir(env), name)));
84
+ if (!have) {
85
+ const archive = path.join(work, "model.tar.bz2");
86
+ const sum = await download(MODEL.url, archive, fetcher, (percent) => progress?.(t(`Microfone: baixando o modelo Parakeet… ${percent}%`, `Micrófono: descargando el modelo Parakeet… ${percent}%`, `Microphone: downloading the Parakeet model… ${percent}%`)));
87
+ if (sum !== MODEL.sha256) return fail(t("o modelo baixado não bate com o SHA-256 conferido", "el modelo descargado no coincide con el SHA-256 verificado", "the downloaded model does not match the verified SHA-256"));
88
+ progress?.(t("Microfone: extraindo o modelo…", "Micrófono: extrayendo el modelo…", "Microphone: extracting the model…"));
89
+ const tar = sync("tar", ["-xjf", archive, "-C", work], { windowsHide: true, timeout: 10 * 60_000 });
90
+ const extracted = path.join(work, MODEL.name);
91
+ if (tar.status !== 0 || !MODEL_FILES.every((name) => fs.existsSync(path.join(extracted, name)))) return fail(t("não consegui extrair o modelo", "no pude extraer el modelo", "could not extract the model"));
92
+ fs.rmSync(modelDir(env), { recursive: true, force: true });
93
+ fs.renameSync(extracted, modelDir(env));
94
+ fs.writeFileSync(marker, MODEL.sha256);
95
+ }
96
+ if (!installed(env)) return fail(t("a pasta ficou incompleta", "la carpeta quedó incompleta", "the folder is incomplete"));
97
+ return t(`Microfone instalado em ${dir}. O botão "◉ falar" aparece na caixa de digitar (tela cheia).`, `Micrófono instalado en ${dir}. El botón "◉ hablar" aparece en la caja de texto (pantalla completa).`, `Microphone installed in ${dir}. The "◉ talk" button shows in the input box (fullscreen).`);
98
+ } catch (error: any) {
99
+ return fail(String(error?.message ?? error).slice(0, 200));
100
+ } finally {
101
+ fs.rmSync(work, { recursive: true, force: true });
102
+ }
103
+ }
104
+
105
+ // PCM Int16 little-endian (o que o decibri entrega) para Float32 entre -1 e 1 (o que o sherpa-onnx lê)
106
+ export function toFloat(chunk: Uint8Array): Float32Array {
107
+ const view = new DataView(chunk.buffer, chunk.byteOffset, chunk.byteLength);
108
+ const out = new Float32Array(Math.floor(chunk.byteLength / 2));
109
+ for (let i = 0; i < out.length; i++) out[i] = view.getInt16(i * 2, true) / 32768;
110
+ return out;
111
+ }
112
+
113
+ export const joinText = (...parts: string[]) => parts.map((part) => part.trim()).filter(Boolean).join(" ");
114
+
115
+ type Engine = { sherpa: any; decibri: any };
116
+ export const loadEngine = (env = process.env): Engine => {
117
+ const req = createRequire(path.join(micDir(env), "package.json"));
118
+ return { sherpa: req("sherpa-onnx-node"), decibri: req("decibri") };
119
+ };
120
+
121
+ export type Editor = { getText(): string; setText(text: string): void; handleInput(data: string): void };
122
+ export type MicState = "off" | "loading" | "rec" | "paused" | "finishing";
123
+
124
+ export function createMicrofone({ env = process.env, load = loadEngine, now = Date.now, every = setInterval as (fn: () => void, ms: number) => any, stopEvery = clearInterval as (id: any) => void } = {}) {
125
+ let state: MicState = "off";
126
+ let error = "";
127
+ let recognizer: Promise<any> | undefined;
128
+ let engine: Engine | undefined;
129
+ let mic: any, vad: any, timer: any;
130
+ let editor: Editor | undefined;
131
+ let redraw = () => {};
132
+ let base = "", committed = "", partial = "";
133
+ let pending = new Float32Array(0);
134
+ let speech: Float32Array[] = [];
135
+ let queue: Promise<void> = Promise.resolve();
136
+ let decoding = false;
137
+ let startedAt = 0, elapsed = 0, lastPartial = 0;
138
+
139
+ const show = () => {
140
+ editor?.setText(joinText(base, committed, partial));
141
+ redraw();
142
+ };
143
+ const recognizerFor = (e: Engine) =>
144
+ (recognizer ??= e.sherpa.OfflineRecognizer.createAsync({
145
+ featConfig: { sampleRate: SAMPLE_RATE, featureDim: 80 },
146
+ modelConfig: {
147
+ transducer: { encoder: path.join(modelDir(env), "encoder.int8.onnx"), decoder: path.join(modelDir(env), "decoder.int8.onnx"), joiner: path.join(modelDir(env), "joiner.int8.onnx") },
148
+ tokens: path.join(modelDir(env), "tokens.txt"),
149
+ numThreads: Math.max(1, Math.min(4, (os.cpus?.().length ?? 2) - 1)),
150
+ provider: "cpu",
151
+ modelType: "nemo_transducer",
152
+ debug: 0,
153
+ },
154
+ }));
155
+ const decode = async (samples: Float32Array) => {
156
+ const rec = await recognizerFor(engine!);
157
+ const stream = rec.createStream();
158
+ stream.acceptWaveform({ sampleRate: SAMPLE_RATE, samples });
159
+ await rec.decodeAsync(stream);
160
+ return String(rec.getResult(stream)?.text ?? "").trim();
161
+ };
162
+ // trechos fechados pelo VAD viram texto definitivo, um de cada vez e na ordem da fala
163
+ const drain = () => {
164
+ while (vad && !vad.isEmpty()) {
165
+ const samples = Float32Array.from(vad.front(false).samples);
166
+ vad.pop();
167
+ speech = [];
168
+ queue = queue.then(async () => {
169
+ const text = await decode(samples);
170
+ committed = joinText(committed, text);
171
+ partial = "";
172
+ show();
173
+ });
174
+ }
175
+ };
176
+ // a fala em curso, transcrita de novo a cada PARTIAL_MS: é o texto que aparece enquanto a pessoa ainda fala
177
+ const livePreview = () => {
178
+ if (decoding || state !== "rec" || !vad?.isDetected?.() || now() - lastPartial < PARTIAL_MS) return;
179
+ const total = speech.reduce((sum, part) => sum + part.length, 0);
180
+ if (total < SAMPLE_RATE / 2) return;
181
+ lastPartial = now();
182
+ const joined = new Float32Array(total);
183
+ let at = 0;
184
+ for (const part of speech) joined.set(part, (at += part.length) - part.length);
185
+ decoding = true;
186
+ decode(joined)
187
+ .then((text) => {
188
+ if (state === "rec" || state === "paused") (partial = text), show();
189
+ })
190
+ .catch(() => {})
191
+ .finally(() => (decoding = false));
192
+ };
193
+ const feed = (chunk: Uint8Array) => {
194
+ if (state !== "rec") return;
195
+ const samples = toFloat(chunk);
196
+ const all = new Float32Array(pending.length + samples.length);
197
+ all.set(pending);
198
+ all.set(samples, pending.length);
199
+ let at = 0;
200
+ for (; at + WINDOW <= all.length; at += WINDOW) {
201
+ const window = all.subarray(at, at + WINDOW);
202
+ vad.acceptWaveform(window);
203
+ if (vad.isDetected()) speech.push(Float32Array.from(window));
204
+ }
205
+ pending = all.slice(at);
206
+ drain();
207
+ livePreview();
208
+ };
209
+ const fault = (why: string) => {
210
+ error = why;
211
+ close();
212
+ state = "off";
213
+ redraw();
214
+ };
215
+ const openMic = () => {
216
+ mic = new engine!.decibri.Microphone({ sampleRate: SAMPLE_RATE, channels: 1 });
217
+ mic.on("data", feed);
218
+ mic.on("error", (e: any) => fault(t(`o microfone falhou (${e?.message ?? e})`, `el micrófono falló (${e?.message ?? e})`, `the microphone failed (${e?.message ?? e})`)));
219
+ };
220
+ const close = () => {
221
+ try {
222
+ mic?.stop?.();
223
+ } catch {}
224
+ mic = undefined;
225
+ if (timer) stopEvery(timer), (timer = undefined);
226
+ };
227
+ const seconds = () => Math.floor((elapsed + (state === "rec" ? now() - startedAt : 0)) / 1000);
228
+
229
+ async function start(target: Editor, draw: () => void) {
230
+ if (state !== "off") return;
231
+ if (!installed(env)) return void (error = t("o microfone não está instalado (/microfone instalar)", "el micrófono no está instalado (/microfone instalar)", "the microphone is not installed (/microfone instalar)"));
232
+ editor = target;
233
+ redraw = draw;
234
+ error = "";
235
+ state = "loading";
236
+ redraw();
237
+ try {
238
+ engine ??= load(env);
239
+ await recognizerFor(engine);
240
+ vad = new engine.sherpa.Vad({ sileroVad: { model: vadModel(env), threshold: 0.5, minSilenceDuration: 0.5, minSpeechDuration: 0.25, windowSize: WINDOW, maxSpeechDuration: 20 }, sampleRate: SAMPLE_RATE, numThreads: 1, debug: 0 }, 60);
241
+ } catch (e: any) {
242
+ recognizer = undefined;
243
+ return fault(t(`não consegui carregar o modelo (${String(e?.message ?? e).slice(0, 160)})`, `no pude cargar el modelo (${String(e?.message ?? e).slice(0, 160)})`, `could not load the model (${String(e?.message ?? e).slice(0, 160)})`));
244
+ }
245
+ base = editor.getText();
246
+ committed = partial = "";
247
+ pending = new Float32Array(0);
248
+ speech = [];
249
+ elapsed = 0;
250
+ startedAt = now();
251
+ state = "rec";
252
+ try {
253
+ openMic();
254
+ } catch (e: any) {
255
+ return fault(t(`não consegui abrir o microfone (${e?.message ?? e})`, `no pude abrir el micrófono (${e?.message ?? e})`, `could not open the microphone (${e?.message ?? e})`));
256
+ }
257
+ timer = every(() => redraw(), 1000);
258
+ timer?.unref?.();
259
+ redraw();
260
+ }
261
+ function pause() {
262
+ if (state !== "rec") return;
263
+ elapsed += now() - startedAt;
264
+ state = "paused";
265
+ close();
266
+ redraw();
267
+ }
268
+ function resume() {
269
+ if (state !== "paused" || !engine) return;
270
+ startedAt = now();
271
+ state = "rec";
272
+ openMic();
273
+ timer = every(() => redraw(), 1000);
274
+ timer?.unref?.();
275
+ redraw();
276
+ }
277
+ // para de gravar e espera o último trecho virar texto; o texto fica na caixa
278
+ async function stop() {
279
+ if (state !== "rec" && state !== "paused") return;
280
+ if (state === "rec") elapsed += now() - startedAt;
281
+ state = "finishing";
282
+ close();
283
+ redraw();
284
+ if (vad) {
285
+ if (pending.length) vad.acceptWaveform(pending), (pending = new Float32Array(0));
286
+ vad.flush();
287
+ drain();
288
+ }
289
+ await queue.catch(() => {});
290
+ partial = "";
291
+ show();
292
+ vad = undefined;
293
+ state = "off";
294
+ redraw();
295
+ }
296
+ async function send() {
297
+ await stop();
298
+ if (editor && editor.getText().trim()) editor.handleInput("\r");
299
+ }
300
+ async function act(action: string, target: Editor, draw: () => void) {
301
+ if (action === "start") return start(target, draw);
302
+ if (action === "pause") return pause();
303
+ if (action === "resume") return resume();
304
+ if (action === "stop") return stop();
305
+ if (action === "send") return send();
306
+ }
307
+ const view = () => ({ installed: installed(env), state, seconds: seconds(), error });
308
+ return { act, view, start, pause, resume, stop, send, shutdown: () => (close(), (state = "off")) };
309
+ }
310
+
311
+ // os botões da caixa de digitar: texto já colorido e, para o clique, a coluna de cada um (de `from` até antes de `to`)
312
+ export function micBar(theme: any, view: { installed: boolean; state: MicState; seconds: number }) {
313
+ if (!view.installed) return undefined;
314
+ const clock = `${Math.floor(view.seconds / 60)}:${String(view.seconds % 60).padStart(2, "0")}`;
315
+ const items: [string, string, string | undefined][] =
316
+ view.state === "off"
317
+ ? [["accent", t("◉ falar", "◉ hablar", "◉ talk"), "start"]]
318
+ : view.state === "loading"
319
+ ? [["dim", t("◌ carregando…", "◌ cargando…", "◌ loading…"), undefined]]
320
+ : view.state === "finishing"
321
+ ? [["dim", t("◌ transcrevendo…", "◌ transcribiendo…", "◌ transcribing…"), undefined]]
322
+ : [
323
+ view.state === "rec" ? ["error", `● ${clock}`, undefined] : ["muted", `◌ ${clock}`, undefined],
324
+ view.state === "rec" ? ["text", t("‖ pausar", "‖ pausar", "‖ pause"), "pause"] : ["text", t("▶ continuar", "▶ seguir", "▶ resume"), "resume"],
325
+ ["text", t("■ parar", "■ parar", "■ stop"), "stop"],
326
+ ["accent", t("➤ enviar", "➤ enviar", "➤ send"), "send"],
327
+ ];
328
+ let text = "";
329
+ let col = 0;
330
+ const spans: { from: number; to: number; action: string }[] = [];
331
+ for (const [color, label, action] of items) {
332
+ if (text) (text += " "), (col += 2);
333
+ text += theme.fg(color, label);
334
+ if (action) spans.push({ from: col, to: col + [...label].length, action });
335
+ col += [...label].length;
336
+ }
337
+ return { text, spans };
338
+ }
339
+
340
+ const MIC_CHOICES = (): Choice[] => [
341
+ { value: "status", description: t("está instalado? onde?", "¿está instalado? ¿dónde?", "is it installed? where?") },
342
+ { value: "falar", description: t("começa a gravar; o texto vai para a caixa", "empieza a grabar; el texto va a la caja", "starts recording; the text goes to the box") },
343
+ { value: "parar", description: t("para de gravar e deixa o texto na caixa", "deja de grabar y deja el texto en la caja", "stops recording and leaves the text in the box") },
344
+ { value: "instalar", description: t(`baixa ~${SIZE_MB} MB, uma vez`, `descarga ~${SIZE_MB} MB, una vez`, `downloads ~${SIZE_MB} MB, once`) },
345
+ ];
346
+
347
+ export default function (pink: any) {
348
+ const microfone = createMicrofone();
349
+ Reflect.set(globalThis, "__pinkMicrofone", microfone);
350
+ pink.registerCommand("microfone", {
351
+ description: t("Microfone para ditar (opcional): falar, parar, instalar ou status", "Micrófono para dictar (opcional): falar, parar, instalar o status", "Microphone for dictation (optional): falar (talk), parar (stop), instalar (install) or status"),
352
+ getArgumentCompletions: completeFrom(MIC_CHOICES),
353
+ handler: async (args: string, ctx: any) => {
354
+ let verb: string | undefined = String(args ?? "").trim().split(/\s+/)[0];
355
+ if (!verb && (verb = await choose(ctx, "/microfone", MIC_CHOICES())) === undefined) return;
356
+ if (verb === "falar" || verb === "talk") {
357
+ // pelo comando também (o botão "◉ falar" só aparece na tela cheia); a caixa de digitar se registra ao desenhar
358
+ const target = (globalThis as any).__pinkMicTarget;
359
+ if (!target?.editor) return ctx.ui.notify(t("A caixa de digitar do Pink não está aberta.", "La caja de texto de Pink no está abierta.", "Pink's input box is not open."), "warning");
360
+ await microfone.act("start", target.editor, target.redraw);
361
+ const why = microfone.view().error;
362
+ return ctx.ui.notify(why ? t(`Microfone: ${why}`, `Micrófono: ${why}`, `Microphone: ${why}`) : t("Gravando: fale. /microfone parar deixa o texto na caixa.", "Grabando: habla. /microfone parar deja el texto en la caja.", "Recording: speak. /microfone parar leaves the text in the box."), why ? "error" : "info");
363
+ }
364
+ if (verb === "parar" || verb === "stop") {
365
+ if (microfone.view().state === "off") return ctx.ui.notify(t("O microfone não está gravando.", "El micrófono no está grabando.", "The microphone is not recording."), "info");
366
+ await microfone.stop();
367
+ return ctx.ui.notify(t("Gravação parada; o texto ficou na caixa.", "Grabación detenida; el texto quedó en la caja.", "Recording stopped; the text stayed in the box."), "info");
368
+ }
369
+ if (verb === "instalar" || verb === "install") {
370
+ if (microfone.view().state !== "off") return ctx.ui.notify(t("Pare a gravação antes de reinstalar.", "Detén la grabación antes de reinstalar.", "Stop recording before reinstalling."), "warning");
371
+ const ok = await ctx.ui.confirm(
372
+ t("Instalar o microfone do Pink?", "¿Instalar el micrófono de Pink?", "Install Pink's microphone?"),
373
+ t(
374
+ `Baixa ~${SIZE_MB} MB, uma vez, para ${micDir()}:\n• motor: sherpa-onnx-node 2.0.1 e decibri 5.8.0 (Apache-2.0), pelo npm, conferidos pelo sha512\n• modelo: NVIDIA Parakeet TDT 0.6B v3 int8 (CC-BY-4.0), do GitHub do sherpa-onnx, conferido pelo SHA-256 ${MODEL.sha256.slice(0, 16)}…\nA transcrição roda nesta máquina; o áudio não sai dela.`,
375
+ `Descarga ~${SIZE_MB} MB, una vez, en ${micDir()}:\n• motor: sherpa-onnx-node 2.0.1 y decibri 5.8.0 (Apache-2.0), por npm, verificados por sha512\n• modelo: NVIDIA Parakeet TDT 0.6B v3 int8 (CC-BY-4.0), del GitHub de sherpa-onnx, verificado por el SHA-256 ${MODEL.sha256.slice(0, 16)}…\nLa transcripción corre en esta máquina; el audio no sale de ella.`,
376
+ `Downloads ~${SIZE_MB} MB, once, to ${micDir()}:\n• engine: sherpa-onnx-node 2.0.1 and decibri 5.8.0 (Apache-2.0), via npm, verified by sha512\n• model: NVIDIA Parakeet TDT 0.6B v3 int8 (CC-BY-4.0), from sherpa-onnx's GitHub, verified by SHA-256 ${MODEL.sha256.slice(0, 16)}…\nTranscription runs on this machine; the audio never leaves it.`,
377
+ ),
378
+ );
379
+ if (!ok) return ctx.ui.notify(t("Instalação cancelada.", "Instalación cancelada.", "Installation cancelled."), "info");
380
+ const done = await install({ progress: (text) => ctx.ui.notify(text, "info") });
381
+ return ctx.ui.notify(done, installed() ? "info" : "error");
382
+ }
383
+ const view = microfone.view();
384
+ ctx.ui.notify(
385
+ view.installed
386
+ ? t(`Microfone instalado em ${micDir()}. Clique em "◉ falar" na caixa de digitar (tela cheia).${view.error ? ` Último erro: ${view.error}` : ""}`, `Micrófono instalado en ${micDir()}. Haz clic en "◉ hablar" en la caja de texto (pantalla completa).${view.error ? ` Último error: ${view.error}` : ""}`, `Microphone installed in ${micDir()}. Click "◉ talk" in the input box (fullscreen).${view.error ? ` Last error: ${view.error}` : ""}`)
387
+ : t("Microfone não instalado. Rode /microfone instalar (~530 MB, uma vez).", "Micrófono no instalado. Ejecuta /microfone instalar (~530 MB, una vez).", "Microphone not installed. Run /microfone instalar (~530 MB, once)."),
388
+ "info",
389
+ );
390
+ },
391
+ });
392
+ pink.on("session_shutdown", () => microfone.shutdown());
393
+ }
@@ -4,7 +4,14 @@
4
4
  // processo só grava onde o SID do Pink tem permissão (a pasta do projeto e um temporário próprio) ou onde Todos já gravam
5
5
  // (limite conhecido). Leitura e rede não mudam. O Job Object do helper mata a árvore inteira junto com ele.
6
6
  // Os comandos que a pessoa roda com ! não passam pelo sandbox: são dela. Linux e macOS ficam para depois.
7
- import { t } from "./pink-i18n.ts";
7
+ import { type Choice, choose, completeFrom, t } from "./pink-i18n.ts";
8
+
9
+ const SANDBOX_CHOICES = (): Choice[] => [
10
+ { value: "status", description: t("ligado ou desligado?", "¿activado o desactivado?", "on or off?") },
11
+ { value: "ligar", description: t("os comandos só gravam na pasta do projeto", "los comandos solo escriben en la carpeta del proyecto", "commands only write to the project folder") },
12
+ { value: "desligar", description: t("volta a rodar os comandos fora do isolamento", "vuelve a ejecutar los comandos sin aislamiento", "runs commands without isolation again") },
13
+ { value: "remover", description: t("apaga o isolamento desta pasta", "borra el aislamiento de esta carpeta", "removes this folder's isolation") },
14
+ ];
8
15
  import { spawn, spawnSync } from "node:child_process";
9
16
  import crypto from "node:crypto";
10
17
  import fs from "node:fs";
@@ -281,8 +288,10 @@ export default function (pink: any) {
281
288
  const label = (ctx: any) => ctx?.ui?.setStatus?.("pink-sandbox", sandbox.active() ? "sandbox" : undefined);
282
289
  pink.registerCommand("sandbox", {
283
290
  description: t("Isola os comandos do agente (só gravam na pasta do projeto): /sandbox ligar | desligar | status | remover", "Aísla los comandos del agente (solo escriben en la carpeta del proyecto): /sandbox activar | desactivar | status | quitar", "Isolates the agent's commands (they only write to the project folder): /sandbox on | off | status | remove"),
291
+ getArgumentCompletions: completeFrom(SANDBOX_CHOICES),
284
292
  handler: async (args: string, ctx: any) => {
285
- const verb = String(args ?? "").trim().toLowerCase();
293
+ let verb: string | undefined = String(args ?? "").trim().toLowerCase();
294
+ if (!verb && (verb = await choose(ctx, "/sandbox", SANDBOX_CHOICES())) === undefined) return;
286
295
  const root = path.resolve(ctx?.cwd ?? process.cwd());
287
296
  let text: string;
288
297
  if (["ligar", "on", "activar"].includes(verb)) text = await sandbox.on(root, (note) => ctx.ui.notify(note, "info"));