@thothdev/pink 1.0.10 → 1.0.11

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,372 @@
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 { 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
+ export default function (pink: any) {
341
+ const microfone = createMicrofone();
342
+ Reflect.set(globalThis, "__pinkMicrofone", microfone);
343
+ pink.registerCommand("microfone", {
344
+ description: t("Microfone para ditar (opcional): instalar ou status", "Micrófono para dictar (opcional): instalar o status", "Microphone for dictation (optional): install or status"),
345
+ getArgumentCompletions: (prefix: string) => ["instalar", "status"].filter((item) => item.startsWith(prefix)).map((value) => ({ value, label: value })),
346
+ handler: async (args: string, ctx: any) => {
347
+ const verb = String(args ?? "").trim().split(/\s+/)[0];
348
+ if (verb === "instalar" || verb === "install") {
349
+ 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");
350
+ const ok = await ctx.ui.confirm(
351
+ t("Instalar o microfone do Pink?", "¿Instalar el micrófono de Pink?", "Install Pink's microphone?"),
352
+ t(
353
+ `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.`,
354
+ `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.`,
355
+ `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.`,
356
+ ),
357
+ );
358
+ if (!ok) return ctx.ui.notify(t("Instalação cancelada.", "Instalación cancelada.", "Installation cancelled."), "info");
359
+ const done = await install({ progress: (text) => ctx.ui.notify(text, "info") });
360
+ return ctx.ui.notify(done, installed() ? "info" : "error");
361
+ }
362
+ const view = microfone.view();
363
+ ctx.ui.notify(
364
+ view.installed
365
+ ? 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}` : ""}`)
366
+ : 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)."),
367
+ "info",
368
+ );
369
+ },
370
+ });
371
+ pink.on("session_shutdown", () => microfone.shutdown());
372
+ }
@@ -11,6 +11,7 @@
11
11
  // The layout functions are pure and exported for tests.
12
12
 
13
13
  import { t } from "./pink-i18n.ts";
14
+ import { micBar } from "./pink-microfone.ts";
14
15
  export const LOGO = [
15
16
  "██████╗ ██╗███╗ ██╗██╗ ██╗",
16
17
  "██╔══██╗██║████╗ ██║██║ ██╔╝",
@@ -84,7 +85,7 @@ export function homeBottomPad(rows, headerHeight, editorHeight) {
84
85
  return Math.max(0, rows - 1 - headerHeight - editorHeight);
85
86
  }
86
87
 
87
- export function inputBox({ theme, content, width, label, inline = false, hints = BOX_HINTS }) {
88
+ export function inputBox({ theme, content, width, label, inline = false, hints = BOX_HINTS, mic = "" }) {
88
89
  // `content` are the lines of the built-in editor without its top and bottom borders; the box is exactly `width` wide.
89
90
  // Barra rosa cheia à esquerda + fundo, como a barra do OpenCode (owner 2026-10-29, pink.3; antes era a borda inteira);
90
91
  // `inline`: o rótulo "Build · modelo" fica à direita da primeira linha (o editor foi desenhado mais estreito para caber);
@@ -96,15 +97,23 @@ export function inputBox({ theme, content, width, label, inline = false, hints =
96
97
  const open = theme.bg ? theme.bg("userMessageBg", "\u0000").split("\u0000")[0] : "";
97
98
  const keep = (value) => (open ? value.replace(/\x1b\[(?:0|49)?m/g, (reset) => reset + open) : value);
98
99
  const row = (value) => `${theme.fg("accent", BAR)}${panel(keep(` ${pad(fit(value, text), text)} `))}`;
99
- const tip = theme.fg("dim", hints);
100
+ const hint = theme.fg("dim", hints);
100
101
  const lines = inline && label ? [footerLine({ theme, width: text, left: content[0] ?? "", right: label }), ...content.slice(1)] : content;
101
- if (!inline && label && visible(label) + 1 + visible(tip) > text) {
102
+ const own = !inline && label && visible(label) + 1 + visible(hint) > text;
103
+ const left = inline || !label || own ? "" : theme.fg("muted", label);
104
+ // os botões do microfone (opcional) vão antes das dicas; sem lugar para os dois, as dicas saem
105
+ const tip = mic ? (visible(left) + 1 + visible(mic) + 3 + visible(hint) <= text ? `${mic} ${hint}` : mic) : hint;
106
+ // a coluna onde os botões começam dentro da caixa (a barra e um espaço vêm antes), para o clique
107
+ const at = (rowIndex) => Object.assign(out, mic ? { micAt: { y: rowIndex, x: 2 + Math.max(visible(left) + 1, text - visible(tip)) } } : {});
108
+ let out;
109
+ if (own) {
102
110
  // rótulo e dicas não cabem juntos: o rótulo ganha a linha dele, em vez de cortar as dicas
103
- return [row(""), ...lines.map(row), row(""), row(theme.fg("muted", label)), row(footerLine({ theme, width: text, left: "", right: tip })), row("")];
111
+ out = [row(""), ...lines.map(row), row(""), row(theme.fg("muted", label)), row(footerLine({ theme, width: text, left: "", right: tip })), row("")];
112
+ return at(out.length - 2);
104
113
  }
105
- const last = inline || !label ? footerLine({ theme, width: text, left: "", right: tip }) : footerLine({ theme, width: text, left: theme.fg("muted", label), right: tip });
106
114
  // linha vazia também embaixo do rótulo, como a caixa do OpenCode (owner 2026-11-24)
107
- return [row(""), ...lines.map(row), row(""), row(last), row("")];
115
+ out = [row(""), ...lines.map(row), row(""), row(footerLine({ theme, width: text, left, right: tip })), row("")];
116
+ return at(out.length - 2);
108
117
  }
109
118
 
110
119
  export function footerLine({ theme, width, left, right }) {
@@ -285,6 +294,8 @@ export const RIGHT_WIDTH = 36; // com a borda
285
294
  export const THREE_COLUMNS = 150; // >= 150: sessões, conversa e contexto
286
295
  export const TWO_COLUMNS = 115; // 115-149: some a coluna de sessões; < 115: só a conversa
287
296
  export const PLACEHOLDER = t("Peça a próxima etapa...", "Pide el siguiente paso...", "Ask for the next step...");
297
+ // enquanto o agente trabalha, como o "esc interrupt" do OpenCode (owner 2026-11-25)
298
+ export const WORK_HINTS = t("esc interromper · ctrl+enter enviar agora", "esc interrumpir · ctrl+enter enviar ya", "esc interrupt · ctrl+enter send now");
288
299
  export const BOX_HINTS = t("Enter enviar · shift+tab pensar · ctrl+t ver pensamento", "Enter enviar · shift+tab pensar · ctrl+t ver razonamiento", "Enter send · shift+tab think · ctrl+t show thinking");
289
300
 
290
301
  export function frameColumns(width, { home = false, on = true, sessions = true } = {}) {
@@ -371,15 +382,6 @@ export function rightColumn({ theme, width, height, data }) {
371
382
  } else {
372
383
  out.push(theme.fg("dim", t("ainda sem medida", "todavía sin medir", "not measured yet")));
373
384
  }
374
- const agents = data.agents ?? [];
375
- if (agents.length) {
376
- out.push("", rule(theme, inner), heading(theme, t("SUBAGENTES", "SUBAGENTES", "SUBAGENTS"), theme.fg("muted", ` ${agents.length}`)));
377
- for (const item of agents) {
378
- const clock = theme.fg("dim", elapsedLabel((data.now ?? Date.now()) - item.started));
379
- const text = `${theme.fg("accent", "●")} ${theme.fg("text", String(item.agent ?? "?"))} ${theme.fg("muted", String(item.task ?? "").replace(/\s+/g, " ").trim())}`;
380
- out.push(footerLine({ theme, width: inner, left: fit(text, Math.max(1, inner - visible(clock) - 1)), right: clock }));
381
- }
382
- }
383
385
  if (data.thoth) out.push("", rule(theme, inner), heading(theme, "THOTH"), ...thothLines({ theme, thoth: data.thoth, width: inner }));
384
386
  if (data.plan) out.push("", rule(theme, inner), heading(theme, t("COTA", "CUOTA", "QUOTA")), ...planLines({ theme, plan: data.plan, width: inner }));
385
387
  if (data.mcp) {
@@ -411,6 +413,16 @@ export function rightColumn({ theme, width, height, data }) {
411
413
  if (data.models?.length) out.push(theme.fg("muted", `${t("modelo", "modelo", "model")} ${data.models.map(shortModel).join(", ")}`));
412
414
  if (data.cost > 0) out.push(theme.fg("muted", `$${data.cost.toFixed(2)} ${t("gasto", "gastado", "spent")}`));
413
415
  if (data.project) out.push(theme.fg("muted", `${t("projeto", "proyecto", "project")} ${data.project}`));
416
+ // SUBAGENTES por último, abaixo da SESSÃO (owner 2026-11-25): a lista cresce no espaço livre do fim da coluna
417
+ const agents = data.agents ?? [];
418
+ if (agents.length) {
419
+ out.push("", rule(theme, inner), heading(theme, t("SUBAGENTES", "SUBAGENTES", "SUBAGENTS"), theme.fg("muted", ` ${agents.length}`)));
420
+ for (const item of agents) {
421
+ const clock = theme.fg("dim", item.clock ?? elapsedLabel((data.now ?? Date.now()) - item.started));
422
+ const text = `${theme.fg(item.mark === "✗" ? "error" : item.mark === "✓" ? "success" : "accent", item.mark ?? "●")} ${theme.fg("text", String(item.agent ?? "?"))} ${theme.fg("muted", String(item.task ?? "").replace(/\s+/g, " ").trim())}`;
423
+ out.push(footerLine({ theme, width: inner, left: fit(text, Math.max(1, inner - visible(clock) - 1)), right: clock }));
424
+ }
425
+ }
414
426
  const lines = out.slice(0, height).map((line) => pad(fit(line, inner), inner));
415
427
  return [...lines, ...Array(Math.max(0, height - lines.length)).fill(" ".repeat(inner))].map((line) => `${theme.fg("borderMuted", "│")} ${line} `);
416
428
  }
@@ -426,6 +438,36 @@ export function trackSubagent(map, event) {
426
438
  const items = Array.isArray(input.tasks) ? input.tasks : Array.isArray(input.chain) ? input.chain : [{ agent: input.agent, task: input.task }];
427
439
  map.set(event.toolCallId, items.map((item) => ({ agent: item?.agent, task: item?.task, started: Date.now() })));
428
440
  }
441
+ // DAG do Thoth (thoth-client dag run) grava .thoth/dag/live.json enquanto roda: cada persona aparece em SUBAGENTES, como os
442
+ // subagentes do Pink (owner 2026-11-25). Some 15 s depois do fim, ou quando o processo do DAG morre sem terminar.
443
+ const DAG_STATE = { waiting: ["·", "esperando"], running: ["●", "rodando"], ok: ["✓", "pronto"], failed: ["✗", "falhou"], skipped: ["−", "pulou"] };
444
+ export function dagAgents(cwd, now = Date.now(), read = (file) => process.getBuiltinModule?.("node:fs")?.readFileSync(file, "utf8"), alive = (pid) => {
445
+ try {
446
+ process.kill(pid, 0);
447
+ return true;
448
+ } catch (error) {
449
+ return error?.code === "EPERM";
450
+ }
451
+ }) {
452
+ let live;
453
+ try {
454
+ live = JSON.parse(read(`${cwd}/.thoth/dag/live.json`));
455
+ } catch {
456
+ return [];
457
+ }
458
+ if (!live || !Array.isArray(live.nodes)) return [];
459
+ if (live.finished ? now - live.finished * 1000 > 15000 : !alive(Number(live.pid))) return [];
460
+ return live.nodes.map((node) => {
461
+ const [mark, label] = DAG_STATE[node.state] ?? DAG_STATE.waiting;
462
+ const running = node.state === "running" && node.started;
463
+ return { agent: node.persona || node.id, task: t(label, label, node.state), mark, started: running ? node.started * 1000 : now, clock: running ? undefined : node.seconds ? `${node.seconds}s` : "" };
464
+ });
465
+ }
466
+ let dagCache = { at: 0, cwd: "", items: [] };
467
+ function dagAgentsCached(cwd, now = Date.now()) {
468
+ if (cwd && (now - dagCache.at > 1000 || dagCache.cwd !== cwd)) dagCache = { at: now, cwd, items: dagAgents(cwd, now) }; // um arquivo lido por segundo, não por quadro
469
+ return cwd ? dagCache.items : [];
470
+ }
429
471
  export function runningSubagents(waiting, background) {
430
472
  return [...[...(background?.values?.() ?? [])].map((job) => ({ agent: job.agent, task: job.task, started: job.started })), ...[...(waiting?.values?.() ?? [])].flat()];
431
473
  }
@@ -822,9 +864,31 @@ export function install(pink, ctx, { CustomEditor, SessionManager, version = "",
822
864
  if (matchesKey?.(data, "ctrl+n")) return void runCommand("/new");
823
865
  const step = matchesKey?.(data, "alt+up") ? -1 : matchesKey?.(data, "alt+down") ? 1 : 0;
824
866
  if (step && !this.pinkKeys?.matches?.(data, "app.message.dequeue")) return void openNeighbour(step);
867
+ // ctrl+enter: com o /agente trabalhando, interrompe e manda já (com a fila); no Pink, é o Enter, que já entra no meio
868
+ if (matchesKey?.(data, "ctrl+enter")) {
869
+ const text = String(this.getText?.() ?? "");
870
+ if (globalThis.__pinkAgentSendNow?.(text)) return void this.setText("");
871
+ return void super.handleInput("\r");
872
+ }
825
873
  super.handleInput(data);
826
874
  }
827
875
 
876
+ // clique nos botões do microfone (◉ falar, ‖ pausar, ■ parar, ➤ enviar); o resto segue para o editor
877
+ handleMouse(event) {
878
+ const hits = state.micHits;
879
+ const span = event?.type === "click" && event.button === "left" && hits && event.y === hits.y ? hits.spans.find((item) => event.x >= item.from && event.x < item.to) : undefined;
880
+ if (!span) return super.handleMouse?.(event);
881
+ const mic = globalThis.__pinkMicrofone;
882
+ void mic
883
+ ?.act(span.action, this, redraw)
884
+ .then(() => {
885
+ const why = mic.view().error;
886
+ if (why) ctx.ui.notify?.(t(`Microfone: ${why}`, `Micrófono: ${why}`, `Microphone: ${why}`), "error");
887
+ })
888
+ .catch((error) => ctx.ui.notify?.(String(error?.message ?? error), "error"));
889
+ return { handled: true };
890
+ }
891
+
828
892
  render(width) {
829
893
  try {
830
894
  return this.pinkRender(width);
@@ -843,9 +907,18 @@ export function install(pink, ctx, { CustomEditor, SessionManager, version = "",
843
907
  // ~35 colunas na tela inicial (owner 2026-11-15)
844
908
  const inline = false;
845
909
  const raw = super.render(Math.max(1, text));
846
- let content = raw.length >= 3 ? raw.slice(1, -1) : raw; // the built-in editor draws its own top and bottom borders
910
+ // the built-in editor draws its own top and bottom borders; the autocomplete list comes AFTER the bottom border, so
911
+ // cutting the last line ate the last suggestion (with one match, "/resu", the whole list vanished; owner 2026-11-25)
912
+ const below = Math.max(0, Math.min(raw.length - 2, Number(this.renderedAutocompleteHeight) || 0));
913
+ let content = raw.length >= 3 ? [...raw.slice(1, raw.length - 1 - below), ...raw.slice(raw.length - below)] : raw;
847
914
  if (typeof this.getText === "function" && this.getText() === "" && content.length) content = [`${content[0].replace(/\s+$/, "")}${theme.fg("dim", PLACEHOLDER)}`, ...content.slice(1)];
848
- const lines = inputBox({ theme, content, width: outer, label, inline }).map((line) => " ".repeat(margin) + line);
915
+ // o botão do microfone só aparece instalado e na tela cheia (fora dela o terminal não entrega o clique)
916
+ const mic = globalThis.__pinkMicrofone;
917
+ const bar = framed() && mic ? micBar(theme, mic.view()) : undefined;
918
+ const working = globalThis.__pinkAgentBusy === true || (typeof ctx.isIdle === "function" && !ctx.isIdle());
919
+ const box = inputBox({ theme, content, width: outer, label, inline, mic: bar?.text, ...(working ? { hints: WORK_HINTS } : {}) });
920
+ state.micHits = bar && box.micAt ? { y: box.micAt.y, spans: bar.spans.map((span) => ({ ...span, from: margin + box.micAt.x + span.from, to: margin + box.micAt.x + span.to })) } : undefined;
921
+ const lines = box.map((line) => " ".repeat(margin) + line);
849
922
  if (!state.home) return lines;
850
923
  const body = [...lines, "", hintsLine({ theme, width })];
851
924
  return [...body, ...Array(homeBottomPad(homeRows(), homeTop(homeRows()) + HEADER_BODY, body.length)).fill("")];
@@ -988,7 +1061,8 @@ export function install(pink, ctx, { CustomEditor, SessionManager, version = "",
988
1061
  if (PINK.thothOn) startThoth();
989
1062
  const stats = sessionStats(ctx.sessionManager?.getEntries?.());
990
1063
  const total = stats.models.reduce((sum, item) => ({ input: sum.input + item.input, output: sum.output + item.output }), { input: 0, output: 0 });
991
- return rightColumn({ theme, width: RIGHT_WIDTH, height, data: { ...total, cost: stats.cost, models: stats.models.map((item) => item.model).filter((model) => model && model !== "?"), project, context: bars().context, todos: PINK.todos, thoth: PINK.thothOn ? PINK.thoth.data : { ad: true }, plan: PINK.thothOn ? PINK.plan.data : undefined, mcp: globalThis.__pinkMcp?.(), mcpOpen: PINK.mcpOpen, hits: (PINK.rightHits = {}), changes: changesFromBranch(ctx.sessionManager?.getBranch?.(), PINK.created), agents: runningSubagents(PINK.subagents, globalThis.__pinkSubagentJobs) } });
1064
+ globalThis.__pinkSideAt = Date.now(); // pink-agente: com a lateral na tela, os subagentes ficam só nela
1065
+ return rightColumn({ theme, width: RIGHT_WIDTH, height, data: { ...total, cost: stats.cost, models: stats.models.map((item) => item.model).filter((model) => model && model !== "?"), project, context: bars().context, todos: PINK.todos, thoth: PINK.thothOn ? PINK.thoth.data : { ad: true }, plan: PINK.thothOn ? PINK.plan.data : undefined, mcp: globalThis.__pinkMcp?.(), mcpOpen: PINK.mcpOpen, hits: (PINK.rightHits = {}), changes: changesFromBranch(ctx.sessionManager?.getBranch?.(), PINK.created), agents: [...runningSubagents(PINK.subagents, globalThis.__pinkSubagentJobs), ...dagAgentsCached(ctx.cwd), ...(globalThis.__pinkAgentChildren ?? [])] } });
992
1066
  }, []),
993
1067
  };
994
1068
  // tarefas sobre a caixa de digitar quando a coluna da direita não cabe (com ela, as tarefas aparecem no PLANO)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@thothdev/pink",
3
- "version": "1.0.10",
3
+ "version": "1.0.11",
4
4
  "description": "Pink: coding agent of the Thoth project, with a pink theme",
5
5
  "type": "module",
6
6
  "piConfig": {