@thothdev/pink 1.0.16 → 1.0.23

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/dist/mux/pink.mjs CHANGED
@@ -3,7 +3,7 @@
3
3
  // resto da tela é a sessão ativa. O modo interativo do Pink segura uma sessão por vez, então cada sessão é um Pink filho num
4
4
  // terminal virtual (node-pty + @xterm/headless) e este processo só desenha a lateral, a tela do filho ativo e repassa o teclado.
5
5
  // Sem terminal interativo, com comando de uma vez (-p, --help, install...) ou sem node-pty, roda o Pink normal, sem lateral.
6
- import { execFile } from "node:child_process";
6
+ import { execFile, spawnSync } from "node:child_process";
7
7
  import { appendFileSync, closeSync, existsSync, mkdirSync, openSync, readdirSync, readFileSync, readSync, realpathSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
8
8
  import { homedir, tmpdir } from "node:os";
9
9
  import path from "node:path";
@@ -32,6 +32,28 @@ const SPIN = ["◜", "◠", "◝", "◞", "◡", "◟"]; // arco girando, como u
32
32
  const CARD_BG = "48;2;32;30;38"; // fundo do card das outras sessões (a ativa usa ACTIVE_BG)
33
33
  const PINK = "38;2;255;110;180";
34
34
 
35
+ // idioma da lateral: a mesma escolha de extensions/pink-i18n.ts (PINK_LANG, idioma de exibição do Windows, LANG, locale)
36
+ // shortcut: cópia curta do detect(): este arquivo roda antes do Pink e não importa .ts; mudou lá, mude aqui
37
+ function detectLang(vars = process.env) {
38
+ const pick = (tag) => { const base = String(tag ?? "").trim().toLowerCase().split(/[-_.]/)[0]; return base === "pt" || base === "es" ? base : "en"; };
39
+ if (vars.PINK_LANG) return pick(vars.PINK_LANG);
40
+ if (process.platform === "win32") {
41
+ try {
42
+ const out = String(spawnSync(`${vars.SystemRoot || "C:\\Windows"}\\System32\\reg.exe`, ["query", "HKCU\\Control Panel\\International\\User Profile", "/v", "Languages"], { windowsHide: true, timeout: 3000, encoding: "utf8" }).stdout ?? "");
43
+ const first = out.match(/REG_MULTI_SZ\s+([A-Za-z]{2,3}(?:-[A-Za-z0-9]+)*)/)?.[1];
44
+ if (first) return pick(first);
45
+ } catch { /* sem registro: segue */ }
46
+ }
47
+ const posix = vars.LC_ALL || vars.LC_MESSAGES || vars.LANG;
48
+ if (posix && !/^(C|POSIX)(\.|$)/.test(posix)) return pick(posix);
49
+ return pick(Intl.DateTimeFormat().resolvedOptions().locale);
50
+ }
51
+ const LANG = detectLang();
52
+ const t = (pt, es, en) => (LANG === "pt" ? pt : LANG === "es" ? es : en);
53
+ const sessionName = (index) => `${t("Sessão", "Sesión", "Session")} ${index + 1}`;
54
+ const YES = t("[ sim ]", "[ sí ]", "[ yes ]");
55
+ const NO = t("[ não ]", "[ no ]", "[ no ]");
56
+
35
57
  // o lançador põe "--provider thoth --model thoth" antes de tudo; o Pink só reconhece subcomando como 1º argumento
36
58
  export function subcommandFirst(argv) {
37
59
  let i = 0;
@@ -109,7 +131,7 @@ export function shortTitle(title, index) {
109
131
  // o título vem do processo da sessão: sem caracteres de controle ele não consegue mexer no terminal ao ser desenhado
110
132
  const clean = (title ?? "").replace(/[\u0000-\u001f\u007f-\u009f]|\p{Cf}/gu, "").replace(/^\s*p(?:i|ink)\s*-\s*/i, "").replace(/^#+\s+/, "").trim(); // "# Missão" do markdown vira "Missão"
111
133
  // só o nome do programa (antes da pasta ser confiável o Pink ainda não pôs a pasta no título) conta como vazio
112
- return clean && !/^p(?:i|ink)$/i.test(clean) ? clean : `Sessão ${index + 1}`;
134
+ return clean && !/^p(?:i|ink)$/i.test(clean) ? clean : sessionName(index);
113
135
  }
114
136
 
115
137
  // estado de uma sessão a partir dos sinais do Pink filho: progresso (OSC 9;4) = trabalhando; fim do progresso ou sino numa
@@ -118,7 +140,17 @@ export function shortTitle(title, index) {
118
140
  // 0xC0000005/0xC0000409 = queda do processo, 1 = erro tratado), e é ele que diz a causa
119
141
  export function exitCodeText(code) {
120
142
  const n = Number(code);
121
- return Number.isFinite(n) && n > 255 ? `0x${(n >>> 0).toString(16).toUpperCase()}` : String(code);
143
+ return Number.isFinite(n) && (n > 255 || n < -255) ? `0x${(n >>> 0).toString(16).toUpperCase()}` : String(code);
144
+ }
145
+
146
+ // queda do processo (não é saída pedida nem erro tratado): código NTSTATUS de erro no Windows, ou sinal de falha fora dele.
147
+ // A sessão é reaberta sozinha, no máximo 3 vezes em 10 minutos, para uma falha que se repete não virar um laço
148
+ const CRASH_SIGNALS = new Set([4, 6, 7, 8, 11]); // ILL, ABRT, BUS, FPE, SEGV
149
+ export function crashRestarts(code, signal, previous = [], now = Date.now()) {
150
+ const status = Number(code) >>> 0;
151
+ if (!(CRASH_SIGNALS.has(signal) || (status >= 0xc0000000 && status !== 0xc000013a))) return undefined; // 0xC000013A = Ctrl+C
152
+ const recent = previous.filter((at) => now - at < 600_000);
153
+ return recent.length < 3 ? [...recent, now] : undefined;
122
154
  }
123
155
  export function logChildExit(session, exitCode, signal, env = process.env, write = appendFileSync) {
124
156
  try {
@@ -222,11 +254,11 @@ export function sidebarWidth(columns) {
222
254
  // o Pink põe no título "pink - nome - pasta" ou "pink - pasta"; a pasta conhecida vem antes, porque pode ter " - " no nome
223
255
  export function sessionLabel(title, index, folder = "") {
224
256
  const text = shortTitle(title, index);
225
- if (folder && text === folder) return { name: `Sessão ${index + 1}`, folder };
257
+ if (folder && text === folder) return { name: sessionName(index), folder };
226
258
  if (folder && text.endsWith(` - ${folder}`)) return { name: text.slice(0, -folder.length - 3), folder };
227
259
  const parts = text.split(" - ");
228
260
  if (parts.length > 1) return { name: parts.slice(0, -1).join(" - "), folder: parts.at(-1) };
229
- return { name: `Sessão ${index + 1}`, folder: text === `Sessão ${index + 1}` ? folder : text };
261
+ return { name: sessionName(index), folder: text === sessionName(index) ? folder : text };
230
262
  }
231
263
 
232
264
  // o que roda em segundo plano na sessão: subagentes (OSC 9;pink-subagents=N) e comandos (OSC 9;pink-jobs=N)
@@ -238,16 +270,17 @@ export function backgroundSignal(data) {
238
270
  function status(session, folder) {
239
271
  const text = baseStatus(session, folder);
240
272
  const count = (session.subagents ?? 0) + (session.jobs ?? 0);
241
- return count && !session.exited ? `${text} · ${count} em 2º plano` : text;
273
+ return count && !session.exited ? `${text} · ${count} ${t("em 2º plano", "en 2º plano", "in background")}` : text;
242
274
  }
243
275
 
244
276
  function baseStatus(session, folder) {
245
- if (session.exited) return "encerrada";
246
- if (session.program?.state === "blocked") return session.program.kind === "permission" ? "pede permissão · espera você" : "pergunta · espera você";
247
- if (session.program?.state === "error") return "parou com erro";
248
- if (session.attention) return "terminou · espera você";
249
- if (isWorking(session)) return "trabalhando…";
250
- return folder || "pronta";
277
+ if (session.exited) return t("encerrada", "cerrada", "closed");
278
+ if (session.program?.state === "blocked") return session.program.kind === "permission" ? t("pede permissão · espera você", "pide permiso · te espera", "needs permission · your turn") : t("pergunta · espera você", "pregunta · te espera", "question · your turn");
279
+ if (session.program?.state === "error") return t("parou com erro", "se detuvo con error", "stopped with error");
280
+ if (isWorking(session)) return t("trabalhando…", "trabajando…", "working…");
281
+ if (session.crashes?.length && session.attention) return t("caiu e foi reaberta", "cayó y se reabrió", "crashed, reopened");
282
+ if (session.attention) return t("terminou · espera você", "terminó · te espera", "done · your turn");
283
+ return folder || t("pronta", "lista", "ready");
251
284
  }
252
285
 
253
286
  export function hitAt(hits, x, y) {
@@ -260,7 +293,7 @@ export function sidebar({ sessions, active, width, rows, frame = 0, confirm, fol
260
293
  const plain = (text) => fit(text, width);
261
294
  const paint = (code, text) => `\x1b[${code}m${plain(text)}\x1b[0m`;
262
295
  const compact = width < SIDEBAR;
263
- const lines = [paint(`1;${PINK}`, compact ? " Pk" : " SESSÕES"), plain("")];
296
+ const lines = [paint(`1;${PINK}`, compact ? " Pk" : t(" SESSÕES", " SESIONES", " SESSIONS")), plain("")];
264
297
  const hits = [];
265
298
  const hit = (action, from = 0, to = width) => hits.push({ y: lines.length, from, to, action });
266
299
  const asking = confirm && !compact ? wrap(confirm, width - 1) : [];
@@ -306,17 +339,17 @@ export function sidebar({ sessions, active, width, rows, frame = 0, confirm, fol
306
339
  hits.splice(0, hits.length, ...hits.filter((item) => item.y < lines.length));
307
340
  }
308
341
  hit("new");
309
- lines.push(paint(`1;${PINK}`, compact ? " +" : " + nova sessão"));
342
+ lines.push(paint(`1;${PINK}`, compact ? " +" : t(" + nova sessão", " + nueva sesión", " + new session")));
310
343
  while (lines.length < top) lines.push(plain(""));
311
344
  const out = lines.slice(0, top);
312
345
  const kept = hits.filter((item) => item.y < top);
313
346
  if (asking.length) {
314
347
  for (const line of asking) out.push(paint(`1;${PINK}`, ` ${line}`));
315
- kept.push({ y: out.length, from: 2, to: 9, action: "yes" }, { y: out.length, from: 11, to: 18, action: "no" });
316
- out.push(paint("1", " [ sim ] [ não ]"));
348
+ kept.push({ y: out.length, from: 2, to: 2 + YES.length, action: "yes" }, { y: out.length, from: 4 + YES.length, to: 4 + YES.length + NO.length, action: "no" });
349
+ out.push(paint("1", ` ${YES} ${NO}`));
317
350
  } else if (!compact) {
318
351
  kept.push({ y: out.length, from: 0, to: width, action: "quit" });
319
- out.push(paint("2", " sair do Pink"));
352
+ out.push(paint("2", t(" sair do Pink", " salir de Pink", " quit Pink")));
320
353
  }
321
354
  return { lines: out.slice(0, rows), hits: kept.filter((item) => item.y < rows) };
322
355
  }
@@ -337,34 +370,52 @@ export function sessionsDir(env = process.env, home = homedir()) {
337
370
  return path.join(env.PINK_CODING_AGENT_DIR || path.join(home, ".pink", "agent"), "sessions");
338
371
  }
339
372
 
340
- // cabeçalho (cwd), nome (/name) e primeira mensagem de uma sessão
341
- // shortcut: lê só os primeiros 32 KB (o cabeçalho é a 1ª linha); um /name gravado depois disso não aparece, fica a 1ª mensagem
342
- const HEAD = Buffer.alloc(32768);
373
+ // cabeçalho (cwd), nome (/name) e primeira mensagem de uma sessão. A 1ª mensagem vem depois do contexto do sistema, que
374
+ // passa de centenas de KB: lê em blocos até achá-la (no máximo 4 MB) e procura o nome também no fim do arquivo
375
+ // shortcut: um /name gravado no meio de um arquivo grande não aparece, fica a 1ª mensagem
376
+ const BLOCK = Buffer.alloc(262144);
343
377
  function readHead(file) {
344
- let text = "";
345
- try {
346
- const fd = openSync(file, "r");
347
- try {
348
- text = HEAD.toString("utf8", 0, readSync(fd, HEAD, 0, HEAD.length, 0));
349
- } finally {
350
- closeSync(fd);
351
- }
352
- } catch {
353
- return {};
354
- }
355
378
  let cwd;
356
379
  let name = "";
357
380
  let first = "";
358
- for (const line of text.split("\n")) {
381
+ const take = (line) => {
359
382
  let entry;
360
383
  try {
361
384
  entry = JSON.parse(line);
362
385
  } catch {
363
- continue; // a última linha lida pode vir cortada
386
+ return; // linha cortada pelo começo ou fim do bloco
364
387
  }
365
388
  if (entry?.type === "session" && !cwd && typeof entry.cwd === "string" && entry.cwd) cwd = entry.cwd;
366
389
  else if (entry?.type === "session_info" && entry.name) name = oneLine(entry.name);
367
390
  else if (!first && entry?.type === "message" && entry.message?.role === "user") first = oneLine(textOf(entry.message.content));
391
+ };
392
+ try {
393
+ const fd = openSync(file, "r");
394
+ try {
395
+ const size = statSync(file).size;
396
+ let at = 0;
397
+ let rest = Buffer.alloc(0);
398
+ while (at < size && at < 4 << 20 && !(cwd && first)) {
399
+ const read = readSync(fd, BLOCK, 0, BLOCK.length, at);
400
+ if (!read) break;
401
+ at += read;
402
+ let data = Buffer.concat([rest, BLOCK.subarray(0, read)]);
403
+ for (let end = data.indexOf(10); end >= 0; end = data.indexOf(10)) {
404
+ take(data.toString("utf8", 0, end));
405
+ data = data.subarray(end + 1);
406
+ }
407
+ rest = Buffer.from(data);
408
+ }
409
+ if (at >= size && rest.length) take(rest.toString("utf8"));
410
+ if (at < size) {
411
+ const read = readSync(fd, BLOCK, 0, BLOCK.length, Math.max(at, size - BLOCK.length));
412
+ for (const line of BLOCK.toString("utf8", 0, read).split("\n")) if (line.includes("session_info")) take(line);
413
+ }
414
+ } finally {
415
+ closeSync(fd);
416
+ }
417
+ } catch {
418
+ return {};
368
419
  }
369
420
  return { cwd, name: name || first };
370
421
  }
@@ -454,44 +505,51 @@ const when = (ms) => {
454
505
 
455
506
  // o seletor na área da sessão: linhas com `width` colunas e onde cada clique cai (base 0): cancel, folder:N, input,
456
507
  // resume:N, delete:N. `saved[i].open` = a sessão está aberta agora (não exclui; clicar mostra ela)
457
- export function pickerView({ folders, saved, input = "", width, rows, scroll = 0, error = "", current = "" }) {
508
+ export function pickerView({ folders, saved, input = "", width, rows, scroll = 0, error = "", current = "", asking }) {
458
509
  const plain = (text) => fit(text, width);
459
510
  const paint = (code, text) => `\x1b[${code}m${plain(text)}\x1b[0m`;
460
511
  const lines = [];
461
512
  const hits = [];
462
513
  const hit = (action, from = 0, to = width) => hits.push({ y: lines.length, from, to, action });
463
- const cancel = "[ cancelar ]";
514
+ const cancel = t("[ cancelar ]", "[ cancelar ]", "[ cancel ]");
464
515
  hit("cancel", Math.max(0, width - cancel.length - 1), width);
465
- lines.push(`\x1b[1;${PINK}m${fit(" Nova sessão", width - cancel.length - 1)}\x1b[0m\x1b[2m${cancel} \x1b[0m`);
466
- lines.push(plain(""), paint("1", " Abrir numa pasta"));
516
+ lines.push(`\x1b[1;${PINK}m${fit(t(" Nova sessão", " Nueva sesión", " New session"), width - cancel.length - 1)}\x1b[0m\x1b[2m${cancel} \x1b[0m`);
517
+ lines.push(plain(""), paint("1", t(" Abrir numa pasta", " Abrir en una carpeta", " Open in a folder")));
467
518
  folders.forEach((folder, index) => {
468
519
  hit(`folder:${index}`);
469
- const tag = samePath(folder, current) ? "(atual)" : "";
520
+ const tag = samePath(folder, current) ? t("(atual)", "(actual)", "(current)") : "";
470
521
  // o cwd vem do arquivo da sessão: sem códigos de controle na tela
471
522
  lines.push(plain(` ▸ ${fit(oneLine(path.basename(folder) || folder), 20)} ${fit(tag, 8)}${oneLine(folder)}`));
472
523
  });
473
- const label = " Outra pasta: ";
524
+ const label = t(" Outra pasta: ", " Otra carpeta: ", " Other folder: ");
474
525
  hit("input");
475
526
  const caret = { y: lines.length, x: Math.min(width - 1, charsWidth(label) + charsWidth(input)) };
476
527
  const field = Math.max(1, width - charsWidth(label) - 1);
477
528
  lines.push(`${label}\x1b[48;2;60;60;70m${fit(input.length > field ? input.slice(-field) : input, field)}\x1b[0m `);
478
- lines.push(error ? paint("38;2;255;120;120", ` ${error}`) : paint("2", " digite o caminho e Enter · Esc fecha"));
479
- lines.push(plain(""), paint("1", ` Sessões anteriores, de todas as pastas (${saved.length})`));
529
+ lines.push(error ? paint("38;2;255;120;120", ` ${error}`) : paint("2", t(" digite o caminho e Enter · Esc fecha", " escribe la ruta y Enter · Esc cierra", " type the path and Enter · Esc closes")));
530
+ lines.push(plain(""), paint("1", t(` Sessões anteriores, de todas as pastas (${saved.length})`, ` Sesiones anteriores, de todas las carpetas (${saved.length})`, ` Previous sessions, from all folders (${saved.length})`)));
480
531
  const top = lines.length;
481
532
  const room = Math.max(0, rows - top - 1);
482
533
  const start = Math.max(0, Math.min(scroll, saved.length - Math.max(1, room)));
483
- const del = " excluir ";
534
+ const del = t(" excluir ", " borrar ", " delete ");
535
+ const ASK = `${t(" excluir?", " ¿borrar?", " delete?")} ${YES} ${NO} `;
484
536
  saved.slice(start, start + room).forEach((item, offset) => {
485
537
  const index = start + offset;
486
- const tail = item.open ? " aberta " : del;
487
- hit(`resume:${index}`, 0, width - del.length);
488
- if (!item.open) hit(`delete:${index}`, width - del.length);
489
- const text = ` ${when(item.mtime)} ${fit(oneLine(path.basename(item.cwd) || item.cwd), 18)} ${item.name || "(sem mensagens)"}`;
490
- lines.push(`${fit(text, width - del.length)}\x1b[${item.open ? "2" : "38;2;255;140;140"}m${tail}\x1b[0m`);
538
+ const confirming = asking === item.file && !item.open;
539
+ const tail = confirming ? ASK : item.open ? t(" aberta ", " abierta ", " open ") : del;
540
+ hit(`resume:${index}`, 0, width - tail.length);
541
+ if (confirming) {
542
+ const yes = width - tail.length + tail.indexOf(YES);
543
+ const no = width - tail.length + tail.indexOf(NO);
544
+ hit(`yes:${index}`, yes, yes + YES.length);
545
+ hit(`no:${index}`, no, no + NO.length);
546
+ } else if (!item.open) hit(`delete:${index}`, width - del.length);
547
+ const text = ` ${when(item.mtime)} ${fit(oneLine(path.basename(item.cwd) || item.cwd), 18)} ${item.name || t("(sem mensagens)", "(sin mensajes)", "(no messages)")}`;
548
+ lines.push(`${fit(text, width - tail.length)}\x1b[${confirming ? `1;${PINK}` : item.open ? "2" : "38;2;255;140;140"}m${tail}\x1b[0m`);
491
549
  });
492
- if (!saved.length) lines.push(paint("2", " nenhuma sessão salva ainda"));
550
+ if (!saved.length) lines.push(paint("2", t(" nenhuma sessão salva ainda", " ninguna sesión guardada todavía", " no saved sessions yet")));
493
551
  while (lines.length < rows - 1) lines.push(plain(""));
494
- const more = room && saved.length > room ? ` ${start + 1}-${Math.min(saved.length, start + room)} de ${saved.length} · role com a roda do mouse` : "";
552
+ const more = room && saved.length > room ? ` ${start + 1}-${Math.min(saved.length, start + room)} ${t("de", "de", "of")} ${saved.length} · ${t("role com a roda do mouse", "desplaza con la rueda", "scroll with the mouse wheel")}` : "";
495
553
  lines.push(paint("2", more));
496
554
  return { lines: lines.slice(0, rows), hits: hits.filter((item) => item.y < rows), caret, scroll: start, room };
497
555
  }
@@ -662,7 +720,7 @@ async function main() {
662
720
  const right = view ? view.lines[y] ?? " ".repeat(inner) : buffer ? serializeLine(buffer.getLine(buffer.viewportY + y), inner, current.scratch) : " ".repeat(inner);
663
721
  const full = `${lines[y] ?? " ".repeat(side)}\x1b[2;${PINK}m│\x1b[0m${right}`;
664
722
  // lateral estreita não cabe a pergunta: ela ocupa a última linha da tela inteira
665
- const shown = confirm && side < SIDEBAR && y === rows - 1 ? `\x1b[1;${PINK}m${fit(` ${confirm.text} s = sim · n = não`, side + 1 + inner)}\x1b[0m` : full;
723
+ const shown = confirm && side < SIDEBAR && y === rows - 1 ? `\x1b[1;${PINK}m${fit(` ${confirm.text} ${t("s = sim · n = não", "s = sí · n = no", "y = yes · n = no")}`, side + 1 + inner)}\x1b[0m` : full;
666
724
  if (cache[y] !== shown) text += `\x1b[${y + 1};1H${shown}`;
667
725
  cache[y] = shown;
668
726
  }
@@ -739,6 +797,19 @@ async function main() {
739
797
  if (!session.closing && exitCode !== 0) logChildExit(session, exitCode, signal);
740
798
  const index = sessions.indexOf(session);
741
799
  if (index < 0) return;
800
+ const crashes = !session.closing && !quittingAll && !finished && session.file && existsSync(session.file) ? crashRestarts(exitCode, signal, session.crashes) : undefined;
801
+ if (crashes) {
802
+ const was = active;
803
+ try {
804
+ open([...laterArgs(argv), "--session", session.file], session.cwd, session.file);
805
+ const fresh = sessions.pop();
806
+ Object.assign(fresh, { crashes, title: session.title, attention: true });
807
+ sessions.splice(index, 1, fresh); // no lugar da que caiu
808
+ term.dispose();
809
+ cache = [];
810
+ return select(was); // ver a sessão tira o aviso
811
+ } catch { /* não reabriu: segue como queda sem volta */ }
812
+ }
742
813
  sessions.splice(index, 1);
743
814
  // só fechar de propósito (×, /quit: código 0) tira da lista; erro ou morte (rede, janela fechada) mantém
744
815
  if (session.closing || exitCode === 0) saveOpen();
@@ -806,15 +877,15 @@ async function main() {
806
877
  if (action.startsWith("close:") && sessions[index]) {
807
878
  const target = sessions[index];
808
879
  const close = () => quitGently(target);
809
- return target.working ? ask(`Encerrar "${sessionLabel(target.title, index, folder).name}"? Ela está trabalhando.`, close) : close();
880
+ return target.working ? ask(t(`Encerrar "${sessionLabel(target.title, index, folder).name}"? Ela está trabalhando.`, `¿Cerrar "${sessionLabel(target.title, index, folder).name}"? Está trabajando.`, `Close "${sessionLabel(target.title, index, folder).name}"? It is working.`), close) : close();
810
881
  }
811
882
  if (action === "quit") {
812
883
  const all = () => {
813
884
  quittingAll = true;
814
885
  [...sessions].forEach(quitGently);
815
886
  };
816
- if (sessions.length > 1) return ask(`Sair do Pink com ${sessions.length} sessões abertas?`, all);
817
- return current?.working ? ask("Sair do Pink? A sessão está trabalhando.", all) : all();
887
+ if (sessions.length > 1) return ask(t(`Sair do Pink com ${sessions.length} sessões abertas?`, `¿Salir de Pink con ${sessions.length} sesiones abiertas?`, `Quit Pink with ${sessions.length} sessions open?`), all);
888
+ return current?.working ? ask(t("Sair do Pink? A sessão está trabalhando.", "¿Salir de Pink? La sesión está trabajando.", "Quit Pink? The session is working."), all) : all();
818
889
  }
819
890
  };
820
891
 
@@ -836,7 +907,7 @@ async function main() {
836
907
  try {
837
908
  open([...laterArgs(argv), ...extra], cwd, file);
838
909
  } catch {
839
- picker = { ...back, error: "A sessão não abriu nesta pasta." }; // as abertas seguem
910
+ picker = { ...back, error: t("A sessão não abriu nesta pasta.", "La sesión no se abrió en esta carpeta.", "The session did not open in this folder.") }; // as abertas seguem
840
911
  }
841
912
  schedule();
842
913
  };
@@ -844,6 +915,10 @@ async function main() {
844
915
  const index = Number(action.split(":")[1]);
845
916
  const item = picker.saved[index];
846
917
  if (action === "cancel") return closePicker();
918
+ const asked = picker.asking;
919
+ picker.asking = undefined; // qualquer outro clique desiste da exclusão
920
+ if (action.startsWith("no:")) return schedule();
921
+ if (action.startsWith("yes:") && item && item.file === asked && !isOpen(item)) return removeSaved(item);
847
922
  if (action.startsWith("folder:")) return startIn(picker.folders[index]);
848
923
  if (action.startsWith("resume:") && item) {
849
924
  if (isOpen(item)) {
@@ -853,27 +928,27 @@ async function main() {
853
928
  return select(shown);
854
929
  }
855
930
  if (!existsSync(item.cwd)) {
856
- picker.error = `A pasta desta sessão não existe mais: ${oneLine(item.cwd)}`;
931
+ picker.error = t(`A pasta desta sessão não existe mais: ${oneLine(item.cwd)}`, `La carpeta de esta sesión ya no existe: ${oneLine(item.cwd)}`, `The folder of this session no longer exists: ${oneLine(item.cwd)}`);
857
932
  return schedule();
858
933
  }
859
934
  return startIn(item.cwd, ["--session", item.file], item.file);
860
935
  }
861
- if (action.startsWith("delete:") && item && !isOpen(item)) {
862
- const name = item.name.length > 40 ? `${item.name.slice(0, 39)}…` : item.name || "sem mensagens";
863
- return ask(`Excluir a sessão "${name}"? Ela vai para a lixeira.`, () => {
864
- if (!picker) return;
865
- const shown = picker;
866
- shown.saved = shown.saved.filter((other) => other !== item); // some da lista já; volta se a lixeira falhar
867
- shown.hits = []; // os cliques antigos apontariam para o item seguinte até o próximo desenho
868
- trashFile(item.file, sessionsDir()).then((ok) => {
869
- if (ok) return;
870
- shown.saved = [item, ...shown.saved].sort((a, b) => b.mtime - a.mtime);
871
- shown.error = "Não deu para mandar a sessão para a lixeira.";
872
- cache = [];
873
- schedule();
874
- });
875
- });
876
- }
936
+ if (action.startsWith("delete:") && item && !isOpen(item)) picker.asking = item.file;
937
+ schedule();
938
+ };
939
+ const removeSaved = (item) => {
940
+ const shown = picker;
941
+ shown.saved = shown.saved.filter((other) => other !== item); // some da lista já; volta se a lixeira falhar
942
+ shown.hits = []; // os cliques antigos apontariam para o item seguinte até o próximo desenho
943
+ shown.error = "";
944
+ schedule();
945
+ trashFile(item.file, sessionsDir()).then((ok) => {
946
+ if (ok) return;
947
+ shown.saved = [item, ...shown.saved].sort((a, b) => b.mtime - a.mtime);
948
+ shown.error = t("Não deu para mandar a sessão para a lixeira.", "No se pudo enviar la sesión a la papelera.", "Could not move the session to the trash.");
949
+ cache = [];
950
+ schedule();
951
+ });
877
952
  };
878
953
  const submitPicker = () => {
879
954
  // pasta arrastada para o terminal: aspas duplas (Windows), simples (Linux) ou espaços com \ (Mac)
@@ -886,12 +961,18 @@ async function main() {
886
961
  folderOk = statSync(target).isDirectory();
887
962
  } catch { /* não existe */ }
888
963
  if (!folderOk) {
889
- picker.error = `Pasta não encontrada: ${oneLine(target)}`;
964
+ picker.error = t(`Pasta não encontrada: ${oneLine(target)}`, `Carpeta no encontrada: ${oneLine(target)}`, `Folder not found: ${oneLine(target)}`);
890
965
  return schedule();
891
966
  }
892
967
  return startIn(target);
893
968
  };
894
969
  const typeIntoPicker = (text) => {
970
+ if (picker.asking) {
971
+ const item = picker.saved.find((other) => other.file === picker.asking);
972
+ picker.asking = undefined;
973
+ if (/^[sSyY]$/.test(text) && item && !isOpen(item)) return removeSaved(item);
974
+ return schedule();
975
+ }
895
976
  if (text === "\x1b") return closePicker();
896
977
  const clean = text.replace(/\x1b\[20[01]~/g, "").replace(/\x1b(?:\[[0-9;?]*[A-Za-z~]|O.)/g, "");
897
978
  picker.error = "";
@@ -147,7 +147,7 @@ export function discoverAgents(cwd: string, scope: AgentScope): AgentDiscoveryRe
147
147
  // Pink: personas do Thoth (o thoth-client grava ~/.claude/agents/thoth-*.md) pelo nome curto: "tifa", "cloud"... Um
148
148
  // agents/tifa.md vence. O model de lá (haiku, sonnet) é apelido do Claude: aqui vale o da sessão (owner 2026-11-25)
149
149
  const home = process.env.USERPROFILE || process.env.HOME;
150
- if (home && scope !== "project") for (const persona of loadAgentsFromDir(path.join(home, ".claude", "agents"), "user")) {
150
+ if (home && scope !== "project" && Reflect.get(globalThis, "__pinkThothConfigured")?.()) for (const persona of loadAgentsFromDir(path.join(home, ".claude", "agents"), "user")) {
151
151
  const name = persona.name.startsWith("thoth-") ? persona.name.slice(6) : "";
152
152
  if (name && !agentMap.has(name)) agentMap.set(name, { ...persona, name, model: undefined, description: `Persona ${name} do Thoth: ${persona.description}` });
153
153
  }
@@ -4,7 +4,7 @@
4
4
  // a sessão (session_shutdown) os filhos são abortados e nada é entregue: o resultado nunca cai em outra conversa.
5
5
  // Copiado para examples/extensions/subagent/background.ts pelo build (rebrand.json); o index.ts do subagente o importa.
6
6
 
7
- import { choose, t } from "./pink-i18n.ts";
7
+ import { type Choice, choose, completeFrom, t, unknown } from "./pink-i18n.ts";
8
8
  export const MAX_BACKGROUND = 4;
9
9
  const OUTPUT_CAP = 50 * 1024;
10
10
  const WIDGET = "pink-subagents";
@@ -117,26 +117,31 @@ export function createBackground(pink: any, { now = Date.now, write = muxWrite }
117
117
  return targets.length;
118
118
  }
119
119
 
120
+ const none = () => t("Nenhum subagente em segundo plano. Peça ao agente para rodar um subagente em segundo plano.", "No hay subagentes en segundo plano. Pide al agente que ejecute un subagente en segundo plano.", "No background subagents. Ask the agent to run a background subagent.");
121
+ const options = (): Choice[] => [
122
+ { value: "listar", description: jobs.size ? t("mostra os que estão rodando", "muestra los que están corriendo", "shows the running ones") : t("nada rodando agora", "nada corriendo ahora", "nothing running now") },
123
+ ...(jobs.size ? [{ value: "cancelar todos", description: t("cancela todos", "cancela todos", "cancels all") }] : []),
124
+ ...[...jobs.keys()].map((id) => ({ value: `cancelar ${id}` })),
125
+ ];
120
126
  pink.registerCommand("subagentes", {
121
127
  description: t("Subagentes em segundo plano: lista; 'cancelar <n>' ou 'cancelar todos'", "Subagentes en segundo plano: lista; 'cancelar <n>' o 'cancelar todos'", "Background subagents: list; 'cancel <n>' or 'cancel all'"),
122
- getArgumentCompletions: (prefix: string) =>
123
- ["cancelar todos", ...[...jobs.keys()].map((id) => `cancelar ${id}`)].filter((item) => item.startsWith(prefix)).map((value) => ({ value, label: value })),
128
+ getArgumentCompletions: completeFrom(options),
124
129
  handler: async (args: string, ctx: any) => {
125
130
  if (!args.trim() && jobs.size) {
126
- const choice = await choose(ctx, "/subagentes", [
127
- { value: "listar", description: t("mostra os que estão rodando", "muestra los que están corriendo", "shows the running ones") },
128
- ...["cancelar todos", ...[...jobs.keys()].map((id) => `cancelar ${id}`)].map((value) => ({ value })),
129
- ]);
131
+ const choice = await choose(ctx, "/subagentes", options());
130
132
  if (choice === undefined) return;
131
- args = choice === "listar" ? "" : choice;
133
+ args = choice;
132
134
  }
133
135
  const [verb, target] = args.trim().split(/\s+/);
136
+ if (verb && !["listar", "list", "cancelar", "cancel"].includes(verb)) return unknown(ctx, "/subagentes", args.trim(), options());
137
+ if ((verb === "cancelar" || verb === "cancel") && !jobs.size) return void ctx.ui.notify(none(), "warning");
134
138
  if (verb === "cancelar" || verb === "cancel") {
135
139
  const count = target ? cancel(target) : 0;
136
- ctx.ui.notify(count ? t(`Cancelando ${count} subagente(s).`, `Cancelando ${count} subagente(s).`, `Cancelling ${count} subagent(s).`) : t("Use /subagentes cancelar <n> ou /subagentes cancelar todos.", "Usa /subagentes cancelar <n> o /subagentes cancelar todos.", "Use /subagentes cancel <n> or /subagentes cancel all."), count ? "info" : "warning");
140
+ if (!count) return unknown(ctx, "/subagentes", args.trim(), options());
141
+ ctx.ui.notify(t(`Cancelando ${count} subagente(s).`, `Cancelando ${count} subagente(s).`, `Cancelling ${count} subagent(s).`), "info");
137
142
  return;
138
143
  }
139
- ctx.ui.notify(jobs.size ? lines().slice(0, -1).join("\n") : t("Nenhum subagente em segundo plano.", "No hay subagentes en segundo plano.", "No background subagents."), "info");
144
+ ctx.ui.notify(jobs.size ? lines().slice(0, -1).join("\n") : none(), "info");
140
145
  },
141
146
  });
142
147
 
@@ -163,23 +163,49 @@ function codexCollab(item: any, result: any): boolean {
163
163
  if (/spawn/i.test(String(item.tool ?? ""))) for (const thread of item.receiverThreadIds ?? []) changed = subagentStart(result, String(thread), item.agentType ?? item.model ?? "codex", item.prompt) || changed;
164
164
  for (const [thread, value] of Object.entries(item.agentsStates ?? {})) {
165
165
  const status = String((value as any)?.status ?? value ?? "");
166
- if (/err|fail/i.test(status)) changed = subagentEnd(result, thread, true) || changed;
166
+ if (/err|fail|interrupt|notfound/i.test(status)) changed = subagentEnd(result, thread, true) || changed;
167
167
  else if (/complet|done|shutdown|closed|finished/i.test(status)) changed = subagentEnd(result, thread) || changed;
168
168
  }
169
169
  if (/close/i.test(String(item.tool ?? ""))) for (const thread of item.receiverThreadIds ?? []) changed = subagentEnd(result, String(thread)) || changed;
170
170
  return changed;
171
171
  }
172
172
 
173
+ // pedaço do que está chegando (texto ou pensamento), para a tela ao vivo; some quando o bloco inteiro chega
174
+ const partial = (result: any, kind: "text" | "thinking", delta: unknown) => {
175
+ if (typeof delta !== "string" || !delta) return;
176
+ const before = result.partial?.kind === kind ? result.partial.text : "";
177
+ result.partial = { kind, text: `${before}${delta}`.slice(-2000) };
178
+ };
179
+
173
180
  // ---------- Claude Code: stream-json ----------
174
181
  export function applyClaudeEvent(event: any, result: any, emit: () => void): void {
175
182
  if (event?.type === "system" && event.subtype === "init") {
176
183
  if (typeof event.model === "string") result.model = event.model;
177
184
  return;
178
185
  }
186
+ // --include-partial-messages: o texto e o pensamento enquanto chegam (os dos subagentes ficam de fora)
187
+ if (event?.type === "stream_event") {
188
+ if (event.parent_tool_use_id) return;
189
+ const inner = event.event ?? {};
190
+ if (inner.type === "content_block_start") result.partial = undefined;
191
+ else if (inner.type === "content_block_delta") {
192
+ if (inner.delta?.type === "text_delta") partial(result, "text", inner.delta.text);
193
+ else if (inner.delta?.type === "thinking_delta") partial(result, "thinking", inner.delta.thinking);
194
+ }
195
+ return;
196
+ }
197
+ // subagente em segundo plano do Claude Code: o fim chega neste aviso, não no resultado da ferramenta
198
+ if (event?.type === "system" && event.subtype === "task_notification") {
199
+ if (subagentEnd(result, String(event.tool_use_id ?? ""), event.status !== "completed")) emit();
200
+ return;
201
+ }
179
202
  if (event?.type === "assistant" && Array.isArray(event.message?.content)) {
203
+ result.partial = undefined;
180
204
  const content = event.message.content
181
205
  .map((part: any) =>
182
- part?.type === "text" && typeof part.text === "string"
206
+ part?.type === "thinking" && typeof part.thinking === "string" && part.thinking.trim()
207
+ ? { type: "thinking", thinking: part.thinking, ms: 0 }
208
+ : part?.type === "text" && typeof part.text === "string"
183
209
  ? { type: "text", text: part.text }
184
210
  : part?.type === "tool_use"
185
211
  ? tool(String(part.name ?? "tool"), part.input && typeof part.input === "object" ? part.input : {}, String(part.id ?? ""))
@@ -195,7 +221,11 @@ export function applyClaudeEvent(event: any, result: any, emit: () => void): voi
195
221
  // o resultado da ferramenta volta numa mensagem "user": fecha o subagente daquela chamada
196
222
  if (event?.type === "user" && Array.isArray(event.message?.content)) {
197
223
  let changed = false;
198
- for (const part of event.message.content) if (part?.type === "tool_result") changed = subagentEnd(result, String(part.tool_use_id ?? ""), part.is_error === true) || changed;
224
+ for (const part of event.message.content) {
225
+ // "Async agent launched": só começou em segundo plano, segue rodando
226
+ const text = String((Array.isArray(part?.content) ? part.content[0]?.text : part?.content) ?? "");
227
+ if (part?.type === "tool_result" && !text.startsWith("Async agent launched")) changed = subagentEnd(result, String(part.tool_use_id ?? ""), part.is_error === true) || changed;
228
+ }
199
229
  if (changed) emit();
200
230
  return;
201
231
  }
@@ -220,13 +250,21 @@ export function applyClaudeEvent(event: any, result: any, emit: () => void): voi
220
250
  // ---------- Codex: itens do app-server ----------
221
251
  export function applyCodexItem(item: any, result: any, emit: () => void): void {
222
252
  if (!item || typeof item !== "object") return;
223
- if (item.type === "agentMessage" && typeof item.text === "string" && item.text) push(result, [{ type: "text", text: item.text }]);
253
+ // o comando aparece ao começar (item/started): ao terminar, não entra de novo
254
+ if (item.id && result.messages.some((message: any) => message.content?.some((part: any) => part.type === "toolCall" && part.id === item.id))) return;
255
+ const thought = item.type === "reasoning" ? [...(item.summary ?? []), ...(item.content ?? [])].join("\n").trim() : "";
256
+ if (thought) push(result, [{ type: "thinking", thinking: thought, ms: 0 }]);
257
+ else if (item.type === "agentMessage" && typeof item.text === "string" && item.text) push(result, [{ type: "text", text: item.text }]);
224
258
  else if (item.type === "commandExecution") push(result, [tool("bash", { command: String(item.command ?? "") }, item.id)]);
225
- else if (item.type === "fileChange") push(result, (item.changes ?? []).map((change: any) => tool(change?.kind?.type === "add" || change?.kind === "add" ? "write" : "edit", { path: String(change?.path ?? "") }, item.id)));
259
+ else if (item.type === "fileChange") push(result, (item.changes ?? []).map((change: any) => change?.kind?.type === "add" || change?.kind === "add" ? tool("write", { path: String(change?.path ?? ""), created: true }, item.id) : tool("edit", { path: String(change?.path ?? "") }, item.id)));
226
260
  else if (item.type === "mcpToolCall") push(result, [tool(`mcp__${item.server}__${item.tool}`, item.arguments && typeof item.arguments === "object" ? item.arguments : {}, item.id)]);
227
261
  else if (item.type === "webSearch") push(result, [tool("web_search", { query: String(item.query ?? "") }, item.id)]);
228
262
  else if (item.type === "collabAgentToolCall") {
229
263
  if (!codexCollab(item, result)) return;
264
+ } else if (item.type === "subAgentActivity") {
265
+ const id = String(item.agentThreadId ?? "");
266
+ const name = String(item.agentPath ?? "").split("/").filter(Boolean).at(-1) ?? "codex";
267
+ if (!(item.kind === "completed" || item.kind === "interrupted" ? subagentEnd(result, id, item.kind === "interrupted") : subagentStart(result, id, name, ""))) return;
230
268
  } else return;
231
269
  emit();
232
270
  }
@@ -269,17 +307,20 @@ const flushThinking = (result: any, state: any) => {
269
307
  if (state.thinking) push(result, [{ type: "thinking", thinking: state.thinking, ms: Date.now() - state.thoughtAt }]);
270
308
  state.thinking = "";
271
309
  state.thoughtAt = undefined;
310
+ result.partial = undefined;
272
311
  };
273
312
  export function applyAcpUpdate(update: any, result: any, state: { text: string; thinking?: string; thoughtAt?: number }, emit: () => void): void {
274
313
  if (!update || typeof update !== "object") return;
275
314
  if (update.sessionUpdate === "agent_thought_chunk" && update.content?.type === "text") {
276
315
  state.thoughtAt ??= Date.now();
277
316
  state.thinking = (state.thinking ?? "") + String(update.content.text ?? "");
317
+ result.partial = { kind: "thinking", text: state.thinking.slice(-2000) };
278
318
  return;
279
319
  }
280
320
  if (update.sessionUpdate === "agent_message_chunk" && update.content?.type === "text") {
281
321
  flushThinking(result, state);
282
322
  state.text += String(update.content.text ?? "");
323
+ result.partial = { kind: "text", text: state.text.slice(-2000) };
283
324
  return;
284
325
  }
285
326
  if (update.sessionUpdate === "tool_call") {
@@ -524,7 +565,7 @@ export async function runExternal(agent: ExternalAgent, task: string, cwd: strin
524
565
  if (agent.extras.mcp.pink) extra.push("--allowedTools", "mcp__pink__pink_tarefa,mcp__pink__pink_tela"); // a tela confirma cada ação no Pink
525
566
  extra.push("--append-system-prompt-file", rulesFile);
526
567
  }
527
- const args = agent.external === "claude" ? [...agent.args, ...(agent.model ? ["--model", agent.model] : []), ...(agent.effort ? ["--effort", agent.effort] : []), ...extra, ...(resume?.id ? ["--resume", resume.id] : [])] : agent.args;
568
+ const args = agent.external === "claude" ? [...agent.args, "--include-partial-messages", ...(agent.model ? ["--model", agent.model] : []), ...(agent.effort ? ["--effort", agent.effort] : []), ...extra, ...(resume?.id ? ["--resume", resume.id] : [])] : agent.args;
528
569
  const child = spawnAgent(agent, args, cwd, start);
529
570
  if (scratch) {
530
571
  const dir = scratch;
@@ -594,15 +635,23 @@ const failed = (result: any, name: string, message: string) => {
594
635
  async function runCodex(child: any, task: string, cwd: string, result: any, emit: () => void, ask: () => Ask | undefined, exited: Promise<number>, resume?: { id?: string }, model?: string, extras?: Extras, effort?: string): Promise<number> {
595
636
  let done: (code: number) => void = () => {};
596
637
  const finished = new Promise<number>((resolve) => (done = resolve));
638
+ let main: string | undefined; // a conversa pedida; os subagentes do Codex rodam em outras
597
639
  const client = rpc(
598
640
  child,
599
641
  "codex",
600
642
  (method, params) => {
601
- if (method === "item/completed") applyCodexItem(params?.item, result, emit);
602
- else if (method === "item/started" && params?.item?.type === "collabAgentToolCall") applyCodexItem(params.item, result, emit); // o subagente aparece ao nascer
643
+ const mine = !main || !params?.threadId || params.threadId === main; // o que chega dos subagentes não vira "ao vivo"
644
+ if (method === "item/completed") {
645
+ if (mine) result.partial = undefined;
646
+ applyCodexItem(params?.item, result, emit);
647
+ } else if (method === "item/started" && ["collabAgentToolCall", "commandExecution", "mcpToolCall", "webSearch"].includes(params?.item?.type)) applyCodexItem(params.item, result, emit); // o subagente e o comando aparecem ao começar
648
+ else if (method === "item/agentMessage/delta") mine && partial(result, "text", params?.delta);
649
+ else if (method === "item/reasoning/summaryTextDelta" || method === "item/reasoning/textDelta") mine && partial(result, "thinking", params?.delta);
603
650
  else if (method === "thread/tokenUsage/updated") codexUsage(params?.tokenUsage, result);
604
651
  else if (method === "error" && params?.error?.message) result.errorMessage = String(params.error.message);
605
652
  else if (method === "turn/completed") {
653
+ // o fim de um subagente fecha a linha dele, não o pedido
654
+ if (main && params?.threadId && params.threadId !== main) return void (subagentEnd(result, String(params.threadId), params.turn?.status === "failed") && emit());
606
655
  const turn = params?.turn ?? {};
607
656
  if (turn.status === "failed" || turn.status === "interrupted") done(failed(result, "codex", String(turn.error?.message ?? result.errorMessage ?? turn.status)));
608
657
  else {
@@ -643,6 +692,7 @@ async function runCodex(child: any, task: string, cwd: string, result: any, emit
643
692
  if (thread.error) return failed(result, "codex", String(thread.error.message ?? "thread/start falhou"));
644
693
  if (typeof thread.result?.model === "string") result.model = thread.result.model;
645
694
  if (resume && thread.result?.thread?.id) resume.id = thread.result.thread.id;
695
+ main = thread.result?.thread?.id;
646
696
  const turn = await client.request("turn/start", { threadId: thread.result?.thread?.id, input: [{ type: "text", text: task, text_elements: [] }], ...(effort ? { effort } : {}) });
647
697
  if (turn.error) return failed(result, "codex", String(turn.error.message ?? "turn/start falhou"));
648
698
  return Promise.race([finished, exited.then((code) => (result.stopReason ? code : failed(result, "codex", result.errorMessage || `o codex saiu (código ${code}) antes de terminar.${result.stderr ? `\n${result.stderr.slice(-400)}` : ""}`)))]);