@thothdev/pink 1.0.31 → 1.0.32

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -3,6 +3,15 @@
3
3
  O Pink é um fork do Pi (MIT, veja `LICENSE-PI.txt` e `NOTICE.md`). Aqui só entra o que mudou no Pink; a base de cada
4
4
  versão está no campo `upstream` do `rebrand.json` do repositório.
5
5
 
6
+ ## [1.0.32] - 2026-11-28
7
+
8
+ - Valem nos modelos logados e no `/agente`: rastro das etapas do trabalho com ícones animados, fechamento "Pronto · operações · tempo · tokens" e a barra da caixa pulsando enquanto o agente trabalha.
9
+ - O resultado de comando (e de ferramenta com erro) aparece preso ao comando com `⎿`, com as últimas linhas e "N linhas ocultas".
10
+ - Pedido de permissão vem numa caixa com moldura.
11
+ - ↑ e ↓ trazem as mensagens já enviadas, também depois de reabrir o Pink.
12
+ - Tela inicial: logo em degradê com uma faixa de luz ao abrir, caixa mais limpa; a barra de baixo mostra o modo e o modelo.
13
+ - Cores com recuo para terminais de 256 e 16 cores e versão legível em tema claro (`PINK_COLORS` força; `PINK_REDUCED_MOTION` para as animações).
14
+
6
15
  ## [1.0.29] - 2026-11-28
7
16
 
8
17
  - Nos modelos logados no Pink e no `/agente`: ao lançar subagentes, o chat mostra o bloco "N subagentes lançados" com o nome e a tarefa de cada um, sem ficar escondido no resumo.
@@ -224,6 +224,13 @@ export function applyClaudeEvent(event: any, result: any, emit: () => void): voi
224
224
  for (const part of event.message.content) {
225
225
  // "Async agent launched": só começou em segundo plano, segue rodando
226
226
  const text = String((Array.isArray(part?.content) ? part.content[0]?.text : part?.content) ?? "");
227
+ if (part?.type === "tool_result") {
228
+ const call = result.messages.flatMap((message: any) => message.content ?? []).find((item: any) => item.type === "toolCall" && item.id && item.id === String(part.tool_use_id ?? ""));
229
+ if (call) {
230
+ call.output = (typeof part.content === "string" ? part.content : (part.content ?? []).map((item: any) => item?.text ?? "").join("\n")).slice(-2000);
231
+ if (part.is_error === true) call.failed = true;
232
+ }
233
+ }
227
234
  if (part?.type === "tool_result" && !text.startsWith("Async agent launched")) changed = subagentEnd(result, String(part.tool_use_id ?? ""), part.is_error === true) || changed;
228
235
  }
229
236
  if (changed) emit();
@@ -293,6 +300,12 @@ function acpArgs(update: any, before: Record<string, unknown> = {}): Record<stri
293
300
  if (typeof input.code === "string") args.code = input.code; // opencode chama MCP por código: tools.pink.pink_tela({...})
294
301
  return args;
295
302
  }
303
+ // o texto que a ferramenta devolveu (content[].content.text ou rawOutput), para o ⎿ da tela
304
+ function acpOutput(update: any): string {
305
+ const blocks = Array.isArray(update.content) ? update.content.map((item: any) => item?.content?.text ?? "").filter(Boolean).join("\n") : "";
306
+ const raw = update.rawOutput;
307
+ return blocks || (typeof raw === "string" ? raw : String(raw?.output ?? raw?.stdout ?? ""));
308
+ }
296
309
  // subagente no ACP: ferramenta "task"/"agent"... ou entrada com subagent_type; status completed/failed fecha a linha
297
310
  function acpSubagent(update: any, result: any): boolean {
298
311
  const id = String(update.toolCallId ?? "");
@@ -340,6 +353,9 @@ export function applyAcpUpdate(update: any, result: any, state: { text: string;
340
353
  if (!part) continue;
341
354
  part.arguments = acpArgs(update, part.arguments);
342
355
  if (part.name === "bash" && !part.arguments.command && update.title) part.arguments.command = String(update.title);
356
+ const output = acpOutput(update);
357
+ if (output) part.output = output.slice(-2000);
358
+ if (update.status === "failed") part.failed = true;
343
359
  emit();
344
360
  return;
345
361
  }
@@ -11,7 +11,7 @@ import os from "node:os";
11
11
  import path from "node:path";
12
12
  import { fileURLToPath } from "node:url";
13
13
  import { closeKept, externalAgents, listModels, pinkExtras, runExternal, subagentEnd, warmKept } from "../examples/extensions/subagent/external.ts";
14
- import { bulleted, elapsedLabel, fit, runLabel, shortModel, stallNote, streamedTokens, thinkingLabel, cleanLine as clean, tailLine, thinkingNow, stripThothRules, thothConfigured, toolSummary, userLines, workingLabel } from "./pink-ui.ts";
14
+ import { bulleted, elapsedLabel, fit, runLabel, shortModel, stallNote, streamedTokens, thinkingLabel, cleanLine as clean, tailLine, thinkingNow, stripThothRules, thothConfigured, toolSummary, userLines, workingLabel, clearDone, showDone, stageLines, trailOf, framedAsk, outputTail, tailRows } from "./pink-ui.ts";
15
15
 
16
16
  // reabrir o Pink volta ao último usado, modelo logado ou agente (owner 2026-11-28). O agente fica neste arquivo; o modelo
17
17
  // logado o motor grava como padrão a cada troca (rebrand.json, remember-last-model-module)
@@ -301,7 +301,9 @@ export function steps(result: any, cwd = "") {
301
301
  else if (part.type === "thinking") out.push({ kind: "thinking", ms: part.ms >= 100 ? part.ms : 0, text: String(part.thinking ?? "").trim().slice(0, THOUGHT_MAX) });
302
302
  else if (part.type === "toolCall") {
303
303
  const child = result.subagents?.[part.id]; // lançamento de subagente: bloco próprio com nome e tarefa
304
- out.push(child ? { kind: "agents", list: [{ agent: child.agent, task: child.task }] } : { kind: "tool", line: pinkTool(part, cwd) });
304
+ // o fim da saída (⎿), como no modelo logado: só de comando ou de ferramenta que falhou
305
+ const tail = part.failed || ["bash", "powershell", "shell"].includes(String(part.name).toLowerCase()) ? outputTail(part.output) : undefined;
306
+ out.push(child ? { kind: "agents", list: [{ agent: child.agent, task: child.task }] } : { kind: "tool", line: pinkTool(part, cwd), ...(tail?.lines.length ? { tail, failed: Boolean(part.failed) } : {}) });
305
307
  }
306
308
  }
307
309
  }
@@ -336,7 +338,7 @@ export function compact(list: any[]) {
336
338
  const names = [...counts].map(([action, n]) => (n > 1 ? `${action} ×${n}` : action)).join(", ");
337
339
  return { kind: "tool", line: `tela · ${step.actions.length} ${t("ações", "acciones", "actions")}: ${names}` };
338
340
  }
339
- return step.kind === "tool" ? { kind: "tool", line: step.count > 1 ? `${step.base} ×${step.count}` : step.base } : step;
341
+ return step.kind === "tool" ? { kind: "tool", line: step.count > 1 ? `${step.base} ×${step.count}` : step.base, ...(step.tail ? { tail: step.tail, failed: step.failed } : {}) } : step;
340
342
  });
341
343
  }
342
344
 
@@ -361,6 +363,7 @@ export function liveLines(result: any, width: number, cwd = ""): string[] {
361
363
  const block = agentLines(step.list);
362
364
  return [`● ${block.head}`, ...block.items.map((item) => ` ${item.branch} ${head(`${item.agent}${item.task ? ` (${item.task})` : ""}`)}`)];
363
365
  }
366
+ if (step.kind === "tool" && step.tail) return [`→ ${head(step.line)}`, ...tailRows({ fg: (_name: string, text: string) => text }, step.tail, { width: room, hint: "" })];
364
367
  return [step.kind === "tool" ? `→ ${head(step.line)}` : step.kind === "thinking" ? thinkingLabel(step.ms) : `● ${head(step.text)}`];
365
368
  });
366
369
  const part = result.partial;
@@ -442,7 +445,7 @@ export default function (pink: any, list: typeof externalAgents = externalAgents
442
445
  };
443
446
  // a fila em cinza fica em cima do "Trabalhando" e uma linha vazia o separa da caixa (owner 2026-11-25, como o Claude Code)
444
447
  const around = (lines: string[], width: number, theme: any) => [...queueLines(active?.queue ?? [], width).map((line) => theme.fg("dim", line)), ...lines, ""];
445
- const busy = (ui: any, output: () => number, doing: (width: number) => string[] = () => []) => {
448
+ const busy = (ui: any, output: () => number, doing: (width: number, theme?: any) => string[] = () => []) => {
446
449
  idle();
447
450
  lastUi = ui;
448
451
  if (!ui?.setWidget) return;
@@ -463,12 +466,12 @@ export default function (pink: any, list: typeof externalAgents = externalAgents
463
466
  loader?.stop?.(); // a fábrica pode ser chamada de novo: o Loader anterior para de girar
464
467
  loader = new tui.Loader(screen, (s: string) => theme.fg("accent", s), (s: string) => theme.fg("muted", s), message());
465
468
  const own = loader;
466
- return { render: (width: number) => around([...doing(width).map((line) => theme.fg("muted", tui.truncateToWidth?.(line, width) ?? line)), ...own.render(width).slice(1)], width, theme), invalidate: () => own.invalidate?.() };
469
+ return { render: (width: number) => around([...doing(width, theme).map((line) => theme.fg("muted", tui.truncateToWidth?.(line, width) ?? line)), ...own.render(width).slice(1)], width, theme), invalidate: () => own.invalidate?.() };
467
470
  }, { placement: "aboveEditor" });
468
471
  ticker = setInterval(() => loader?.setMessage?.(message()), 1000);
469
472
  } else {
470
473
  let frame = 0;
471
- const draw = () => ui.setWidget(WIDGET, (screen: any, theme: any) => ((screenRef = screen), { render: (width: number) => around([...doing(width).map((line) => tui?.truncateToWidth?.(line, width) ?? line), ` ${FRAMES[frame % FRAMES.length]} ${message()}`], width, theme), invalidate() {} }), { placement: "aboveEditor" });
474
+ const draw = () => ui.setWidget(WIDGET, (screen: any, theme: any) => ((screenRef = screen), { render: (width: number) => around([...doing(width, theme).map((line) => tui?.truncateToWidth?.(line, width) ?? line), ` ${FRAMES[frame % FRAMES.length]} ${message()}`], width, theme), invalidate() {} }), { placement: "aboveEditor" });
472
475
  draw();
473
476
  ticker = setInterval(() => (frame++, draw()), 120);
474
477
  }
@@ -598,7 +601,7 @@ export default function (pink: any, list: typeof externalAgents = externalAgents
598
601
  if (index && !(step.kind === "tool" && steps[index - 1]?.kind === "tool")) box.addChild(new tui.Spacer(1));
599
602
  if (step.kind === "thinking") thought(box, step, offset + index);
600
603
  else if (step.kind === "agents") drawAgents(box, step);
601
- else if (step.kind === "tool") box.addChild(new tui.Text(theme.fg("muted", `→ ${step.line}`), pad, 0));
604
+ else if (step.kind === "tool") box.addChild(new tui.Text([theme.fg("muted", `→ ${step.line}`), ...tailRows(theme, step.tail, { width: 120, error: step.failed, hint: "" })].join("\n"), pad, 0));
602
605
  else box.addChild(bulleted(new tui.Markdown(String(step.text).trim(), pad, 0, coding.getMarkdownTheme())));
603
606
  }
604
607
  };
@@ -663,10 +666,11 @@ export default function (pink: any, list: typeof externalAgents = externalAgents
663
666
  ctx.ui?.setStatus?.(STATUS, `${name} ${t("trabalhando", "trabajando", "working")}${last ? `: ${last}` : "…"}`);
664
667
  };
665
668
  status();
666
- if (ctx.hasUI) busy(ctx.ui, () => outputOf(result), (width) => liveLines(result, width, ctx.cwd));
669
+ // o rastro de etapas do modelo logado, em cima dos passos do agente; o fechamento do pedido anterior sai
670
+ if (ctx.hasUI) clearDone(ctx.ui), busy(ctx.ui, () => outputOf(result), (width, theme) => [...stageLines(theme ?? { fg: (_name: string, text: string) => text }, trailOf(result), { width }), ...liveLines(result, width, ctx.cwd)]);
667
671
  if (ctx.hasUI) watchChildren(ctx.ui);
668
672
  // "permitir tudo" (/permissoes): o que o agente pede é aceito sem perguntar
669
- (globalThis as any).__pinkExternalAsk = ctx.hasUI ? (title: string, body: string) => ((globalThis as any).__pinkPermissionMode === "all" ? Promise.resolve(true) : ctx.ui.confirm(title, body)) : undefined;
673
+ (globalThis as any).__pinkExternalAsk = ctx.hasUI ? (title: string, body: string) => ((globalThis as any).__pinkPermissionMode === "all" ? Promise.resolve(true) : ctx.ui.confirm(title, ctx.mode === "tui" ? framedAsk(title, body) : body)) : undefined;
670
674
  try {
671
675
  await run(current.agent, before ? `${before}\n${text}` : text, ctx.cwd, controller.signal, result, status, undefined, undefined, current.resume);
672
676
  } catch (error: any) {
@@ -677,6 +681,12 @@ export default function (pink: any, list: typeof externalAgents = externalAgents
677
681
  for (const id of Object.keys(result.subagents ?? {})) subagentEnd(result, id, result.stopReason === "error");
678
682
  if (current.controller === controller) current.controller = undefined;
679
683
  if (active === current || !active) idle();
684
+ // o mesmo fechamento do modelo logado: os ✓ acendem e "Pronto · tempo · tokens"; com erro, a última etapa leva ✗
685
+ if (ctx.hasUI && (active === current || !active)) {
686
+ const trail = trailOf(result);
687
+ if (result.stopReason === "error") trail[trail.length - 1] = { ...trail.at(-1)!, failed: true } as any;
688
+ showDone(ctx.ui, trail, runLabel({ ms: Date.now() - started, output: outputOf(result) }));
689
+ }
680
690
  Reflect.get(globalThis, "__pinkTela")?.hide?.(); // o agente terminou: apaga o contorno da tela
681
691
  if (active === current) {
682
692
  ctx.ui?.setStatus?.(STATUS, `${t("agente", "agente", "agent")}: ${label(current.agent)}`);
@@ -12,6 +12,7 @@
12
12
  // ofuscação ($(echo rm), eval) escapa do padrão. Isolamento de verdade é o sandbox do sistema, não isto.
13
13
  // - /permissoes mostra as regras em uso.
14
14
  import { noArgs, t } from "./pink-i18n.ts";
15
+ import { framedAsk } from "./pink-ui.ts";
15
16
  import fs from "node:fs";
16
17
  import os from "node:os";
17
18
  import path from "node:path";
@@ -230,7 +231,9 @@ export function permissions(pink, deps = {}) {
230
231
  if (sessionAllowed.has(key)) return undefined;
231
232
  if (!ctx?.hasUI) return { block: true, reason: t(`Precisa de confirmação e não há tela para pedir (${why}): ${shown}`, `Necesita confirmación y no hay pantalla para pedirla (${why}): ${shown}`, `Needs confirmation and there is no screen to ask (${why}): ${shown}`) };
232
233
  const [once, session, deny] = [t("Permitir uma vez", "Permitir una vez", "Allow once"), t("Permitir nesta sessão", "Permitir en esta sesión", "Allow this session"), t("Negar", "Denegar", "Deny")];
233
- const choice = await ctx.ui.select(t(`Confirmar ${toolName}: ${why}\n\n ${shown}\n`, `Confirmar ${toolName}: ${why}\n\n ${shown}\n`, `Confirm ${toolName}: ${why}\n\n ${shown}\n`), [once, session, deny]);
234
+ // a moldura só na tela: em RPC o título vai como texto puro para quem desenha
235
+ const plain = t(`Confirmar ${toolName}: ${why}\n\n ${shown}\n`, `Confirmar ${toolName}: ${why}\n\n ${shown}\n`, `Confirm ${toolName}: ${why}\n\n ${shown}\n`);
236
+ const choice = await ctx.ui.select(ctx.mode === "tui" ? framedAsk(t(`Confirmar ${toolName}`, `Confirmar ${toolName}`, `Confirm ${toolName}`), `${why}\n\n${shown}`) : plain, [once, session, deny]);
234
237
  if (choice === once) return undefined;
235
238
  if (choice === session) { sessionAllowed.add(key); return undefined; }
236
239
  return { block: true, reason: t("A pessoa negou esta ação", "La persona denegó esta acción", "The person denied this action") };
@@ -10,8 +10,30 @@
10
10
  // assistant-footer, user-bar) that only call globalThis.__pinkFrame, __pinkAssistantFooter and __pinkUserBar.
11
11
  // The layout functions are pure and exported for tests.
12
12
 
13
+ import fs from "node:fs";
14
+ import os from "node:os";
15
+ import path from "node:path";
13
16
  import { builtinWithArgs, completeFrom, noArgs, t, unknown } from "./pink-i18n.ts";
14
17
  import { micBar } from "./pink-microfone.ts";
18
+
19
+ // ↑/↓ na caixa trazem as mensagens já enviadas (owner 2026-11-28): o editor do motor já navega, mas o histórico morria com
20
+ // a sessão; agora fica em disco, as 100 últimas, mais nova primeiro
21
+ export const HISTORY_MAX = 100;
22
+ export const historyFile = (env = process.env) => path.join(env.PINK_CODING_AGENT_DIR || path.join(os.homedir(), ".pink", "agent"), "historico.json");
23
+ export function loadHistory(file = historyFile()) {
24
+ try {
25
+ const items = JSON.parse(fs.readFileSync(file, "utf8"));
26
+ return Array.isArray(items) ? items.filter((item) => typeof item === "string" && item.trim()).slice(0, HISTORY_MAX) : [];
27
+ } catch {
28
+ return [];
29
+ }
30
+ }
31
+ export function saveHistory(items, file = historyFile()) {
32
+ try {
33
+ fs.mkdirSync(path.dirname(file), { recursive: true });
34
+ fs.writeFileSync(file, JSON.stringify(items.slice(0, HISTORY_MAX)));
35
+ } catch {} // sem disco o histórico fica só nesta sessão, como antes
36
+ }
15
37
  export const LOGO = [
16
38
  "██████╗ ██╗███╗ ██╗██╗ ██╗",
17
39
  "██╔══██╗██║████╗ ██║██║ ██╔╝",
@@ -58,11 +80,24 @@ export function center(text, width) {
58
80
  return " ".repeat(Math.max(0, Math.floor((width - visible(text)) / 2))) + text;
59
81
  }
60
82
 
61
- export function logoLines(theme, width) {
83
+ // degradê do logo (Renoir): rosa da marca → orquídea, da esquerda para a direita; `sweep` = progresso 0..1 da faixa de luz
84
+ // que passa uma vez ao abrir (null = sem varredura). NO_COLOR: sem degradê, a cor do tema
85
+ export const ORCHID_RGB = [208, 140, 255];
86
+ export const SWEEP_MS = 800;
87
+ export function logoLines(theme, width, sweep = null) {
62
88
  if (width < LOGO[0].length + 2) return [theme.fg("accent", "PINK")].map((line) => center(line, width));
89
+ const cols = LOGO[0].length;
90
+ setAppearance(theme);
91
+ const front = sweep == null ? -99 : sweep * (cols + 12) - 6;
63
92
  return LOGO.map((row) => {
64
93
  let out = "";
65
- for (const ch of row) out += ch === "█" ? theme.fg("accent", ch) : ch === " " ? ch : theme.fg("dim", ch);
94
+ [...row].forEach((ch, x) => {
95
+ if (ch === " ") return void (out += ch);
96
+ if (ch !== "█" || process.env.NO_COLOR) return void (out += ch === "█" ? theme.fg("accent", ch) : theme.fg("dim", ch));
97
+ const base = mix(PINK_RGB, ORCHID_RGB, x / Math.max(1, cols - 1));
98
+ const glow = Math.max(0, 1 - Math.abs(x - front) / 5);
99
+ out += paint(...mix(base, [255, 255, 255], glow * 0.7), ch);
100
+ });
66
101
  return center(out, width);
67
102
  });
68
103
  }
@@ -75,8 +110,8 @@ export function homeTop(rows, bodyHeight = HEADER_BODY, editorHeight = EDITOR_BO
75
110
  return Math.max(1, Math.floor((rows - 1 - bodyHeight - editorHeight) / 2));
76
111
  }
77
112
 
78
- export function homeHeader({ theme, width, rows, subtitle }) {
79
- const body = [...logoLines(theme, width), "", center(theme.fg("muted", subtitle), width), ""];
113
+ export function homeHeader({ theme, width, rows, subtitle, sweep = null }) {
114
+ const body = [...logoLines(theme, width, sweep), "", center(theme.fg("muted", subtitle), width), ""];
80
115
  return [...Array(homeTop(rows, body.length)).fill(""), ...body];
81
116
  }
82
117
 
@@ -85,7 +120,7 @@ export function homeBottomPad(rows, headerHeight, editorHeight) {
85
120
  return Math.max(0, rows - 1 - headerHeight - editorHeight);
86
121
  }
87
122
 
88
- export function inputBox({ theme, content, width, label, inline = false, hints = BOX_HINTS, mic = "" }) {
123
+ export function inputBox({ theme, content, width, label, inline = false, hints = BOX_HINTS, mic = "", barRgb = undefined }) {
89
124
  // `content` are the lines of the built-in editor without its top and bottom borders; the box is exactly `width` wide.
90
125
  // Barra rosa cheia à esquerda + fundo, como a barra do OpenCode (owner 2026-10-29, pink.3; antes era a borda inteira);
91
126
  // `inline`: o rótulo "Build · modelo" fica à direita da primeira linha (o editor foi desenhado mais estreito para caber);
@@ -96,13 +131,15 @@ export function inputBox({ theme, content, width, label, inline = false, hints =
96
131
  // a faixa do texto ficava preta e só o rodapé da caixa ficava rosado
97
132
  const open = theme.bg ? theme.bg("userMessageBg", "\u0000").split("\u0000")[0] : "";
98
133
  const keep = (value) => (open ? value.replace(/\x1b\[(?:0|49)?m/g, (reset) => reset + open) : value);
99
- const row = (value) => `${theme.fg("accent", BAR)}${panel(keep(` ${pad(fit(value, text), text)} `))}`;
100
- const hint = theme.fg("dim", hints);
134
+ setAppearance(theme);
135
+ const bar = barRgb && !process.env.NO_COLOR ? paint(...barRgb, BAR) : theme.fg("accent", BAR);
136
+ const row = (value) => `${bar}${panel(keep(` ${pad(fit(value, text), text)} `))}`;
137
+ const hint = hints ? theme.fg("dim", hints) : "";
101
138
  const lines = inline && label ? [footerLine({ theme, width: text, left: content[0] ?? "", right: label }), ...content.slice(1)] : content;
102
139
  const own = !inline && label && visible(label) + 1 + visible(hint) > text;
103
140
  const left = inline || !label || own ? "" : theme.fg("muted", label);
104
141
  // 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;
142
+ const tip = mic ? (hint && visible(left) + 1 + visible(mic) + 3 + visible(hint) <= text ? `${mic} ${hint}` : mic) : hint;
106
143
  // a coluna onde os botões começam dentro da caixa (a barra e um espaço vêm antes), para o clique
107
144
  const at = (rowIndex) => Object.assign(out, mic ? { micAt: { y: rowIndex, x: own ? 2 : 2 + Math.max(visible(left) + 1, text - visible(tip)) } } : {});
108
145
  let out;
@@ -138,7 +175,7 @@ export function modelLabel({ theme, model, thinking, agent, permission = "edits"
138
175
  }
139
176
 
140
177
  export function hintsLine({ theme, width }) {
141
- return center(theme.fg("dim", t("ctrl+p comandos tab agente alt+m modo @ arquivo ! bash ctrl+t pensamento ctrl+c sair", "ctrl+p comandos tab agente alt+m modo @ archivo ! bash ctrl+t razonamiento ctrl+c salir", "ctrl+p commands tab agent alt+m mode @ file ! bash ctrl+t thinking ctrl+c quit")), width);
178
+ return center(theme.fg("dim", t("ctrl+p comandos tab agente alt+m modo @ arquivo ! bash ↑ anteriores shift+tab pensar ctrl+t pensamento ctrl+c sair", "ctrl+p comandos tab agente alt+m modo @ archivo ! bash ↑ anteriores shift+tab pensar ctrl+t razonamiento ctrl+c salir", "ctrl+p commands tab agent alt+m mode @ file ! bash ↑ previous shift+tab think ctrl+t thinking ctrl+c quit")), width);
142
179
  }
143
180
 
144
181
  // -- funções do OpenCode (owner 2026-10-28: "gosto muito do opencode, poderia replicar as funções dele")
@@ -294,6 +331,142 @@ export async function savedSnapshot(entries, entryId, cwd, run = runGit) {
294
331
  export const LEFT_WIDTH = 32; // com a borda (pink.3: +2 para o horário de cada sessão)
295
332
  export const RIGHT_WIDTH = 36; // com a borda
296
333
  const ABOVE_BOX = "pink-acima-da-caixa";
334
+
335
+ // etapas do trabalho acima da caixa (owner 2026-11-28): a atual anima com ícone e cor próprios, as que passaram ficam com ✓;
336
+ // vêm dos eventos reais (ferramenta chamada, texto da resposta), nunca de um texto inventado
337
+ // cores do Renoir (2026-11-28): leitura numa rampa fria derivada do rosa, só o build no rosa da marca, pêssego nas validações;
338
+ // amarelo fica para "esperando você"; todas ≥ 7:1 no fundo escuro do Pink
339
+ // recuo de cores (owner 2026-11-28): terminal sem truecolor recebe a cor mais próxima das 256 ou das 16
340
+ export function colorDepth(env = process.env, platform = process.platform) {
341
+ if (["truecolor", "256", "16"].includes(env.PINK_COLORS)) return env.PINK_COLORS;
342
+ if (/truecolor|24bit/i.test(env.COLORTERM ?? "") || env.WT_SESSION) return "truecolor";
343
+ if (/256/.test(env.TERM ?? "")) return "256";
344
+ return platform === "win32" ? "truecolor" : "16"; // o console do Windows 10+ desenha 24 bits
345
+ }
346
+ const CUBE = [0, 95, 135, 175, 215, 255];
347
+ const ANSI16 = [[30, 0, 0, 0], [31, 205, 49, 49], [32, 13, 188, 121], [33, 229, 229, 16], [34, 36, 114, 200], [35, 188, 63, 188], [36, 17, 168, 205], [37, 229, 229, 229], [90, 102, 102, 102], [91, 241, 76, 76], [92, 35, 209, 139], [93, 245, 245, 67], [94, 59, 142, 234], [95, 214, 112, 214], [96, 41, 184, 219], [97, 255, 255, 255]];
348
+ const distance = (a, b) => (a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2 + (a[2] - b[2]) ** 2;
349
+ const nearest = (list, rgbValue, pick) => list.reduce((best, item) => (distance(pick(item), rgbValue) < distance(pick(best), rgbValue) ? item : best));
350
+ export function sgr(rgbValue, depth = colorDepth()) {
351
+ if (depth === "truecolor") return `38;2;${rgbValue.join(";")}`;
352
+ if (depth === "256") {
353
+ const [r, g, b] = rgbValue.map((v) => CUBE.indexOf(nearest(CUBE, [v, 0, 0], (c) => [c, 0, 0])));
354
+ return `38;5;${16 + 36 * r + 6 * g + b}`;
355
+ }
356
+ return String(nearest(ANSI16, rgbValue, (item) => item.slice(1))[0]);
357
+ }
358
+ // tema claro: escurece a cor até 4,5:1 sobre branco (as cores da marca foram escolhidas para fundo escuro)
359
+ let lightTheme = false;
360
+ export const setAppearance = (theme) => { if (theme?.appearance) lightTheme = theme.appearance === "light"; };
361
+ const luminance = (rgbValue) => rgbValue.map((v) => v / 255).map((v) => (v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4)).reduce((sum, v, i) => sum + v * [0.2126, 0.7152, 0.0722][i], 0);
362
+ export function readable(rgbValue, light = lightTheme) {
363
+ let out = rgbValue;
364
+ while (light && 1.05 / (luminance(out) + 0.05) < 4.5) out = out.map((v) => Math.floor(v * 0.9));
365
+ return out;
366
+ }
367
+ const paint = (r, g, b, text) => (process.env.NO_COLOR ? text : `\x1b[${sgr(readable([r, g, b]))}m${text}\x1b[39m`);
368
+ const rgb = (r, g, b) => Object.assign((text) => paint(r, g, b, text), { rgb: [r, g, b] });
369
+ export const PINK_RGB = [255, 110, 180];
370
+ const GREEN = rgb(74, 222, 128);
371
+ export const STAGES = {
372
+ interpret: { frames: ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"], color: rgb(216, 180, 255), label: t("Interpretando solicitação", "Interpretando la solicitud", "Reading the request") },
373
+ map: { frames: ["◇", "◈", "◆", "◈"], color: rgb(190, 150, 255), label: t("Mapeando o projeto", "Mapeando el proyecto", "Mapping the project") },
374
+ investigate: { frames: ["○", "◎", "◉", "◎"], color: rgb(160, 160, 255), label: t("Investigando", "Investigando", "Investigating") },
375
+ build: { frames: ["⠿", "⠾", "⠽", "⠻", "⠟", "⠯", "⠷"], color: rgb(...PINK_RGB), label: t("Elaborando a implementação", "Elaborando la implementación", "Writing the change") },
376
+ validate: { frames: ["◐", "◓", "◑", "◒"], color: rgb(255, 170, 140), label: t("Executando validações", "Ejecutando validaciones", "Running checks") },
377
+ command: { frames: ["◐", "◓", "◑", "◒"], color: rgb(255, 170, 140), label: t("Executando comando", "Ejecutando comando", "Running a command") },
378
+ answer: { frames: ["✓"], color: GREEN, label: t("Escrevendo a resposta", "Escribiendo la respuesta", "Writing the answer") },
379
+ };
380
+ // todo efeito anda a no máximo 12 quadros/s: o tempo vira passos de 83 ms (o redesenho vem do spinner do motor)
381
+ const FRAME_MS = 83;
382
+ const still = () => !!process.env.PINK_REDUCED_MOTION; // NO_COLOR tira só a cor (o padrão no-color.org), não o movimento
383
+ const mix = (a, b, k) => a.map((v, i) => Math.round(v + (b[i] - v) * k));
384
+
385
+ // barra que respira (Renoir): enquanto o agente trabalha, a ▌ vai do rosa da marca ao rosa escuro em ciclos de 1,6 s
386
+ export function breathe(now = Date.now(), period = 1600) {
387
+ const step = Math.floor(now / FRAME_MS) * FRAME_MS;
388
+ return mix(PINK_RGB, [194, 69, 127], (1 - Math.cos((2 * Math.PI * (step % period)) / period)) / 2);
389
+ }
390
+
391
+ // brilho (shimmer): uma faixa de 3 letras, a cor da etapa com 35% de branco, percorre o rótulo da etapa atual
392
+ export function shimmer(text, color, now = Date.now()) {
393
+ const chars = [...text];
394
+ const at = (Math.floor(now / FRAME_MS) % (chars.length + 6)) - 3;
395
+ const light = mix(color, [255, 255, 255], 0.35);
396
+ return chars.map((char, i) => (Math.abs(i - at) <= 1 ? paint(...light, char) : paint(...color, char))).join("");
397
+ }
398
+ const TEST_COMMAND = /\b(test|tests|pytest|jest|vitest|mocha|playwright|maestro|go test|cargo test|npm (run )?test|ruff|eslint|tsc|lint|check|verify)\b/i;
399
+ const base = (value) => String(value ?? "").split(/[\\/]/).filter(Boolean).pop() ?? "";
400
+
401
+ export function stageOf(toolName, input = {}) {
402
+ const tool = String(toolName ?? "").toLowerCase();
403
+ const file = base(input.path ?? input.file_path ?? input.filePath);
404
+ if (["grep", "find", "ls", "glob", "tool_search"].includes(tool)) return { key: "map", detail: String(input.pattern ?? input.path ?? "").slice(0, 40) };
405
+ if (["read", "web_fetch", "web_search"].includes(tool)) return { key: "investigate", detail: tool === "read" ? file : String(input.query ?? input.url ?? input.pattern ?? "").slice(0, 40) };
406
+ if (["edit", "write", "multiedit", "apply_patch", "delete", "move"].includes(tool)) return { key: "build", detail: file };
407
+ if (["bash", "powershell", "shell"].includes(tool)) {
408
+ const command = String(input.command ?? "").replace(/\s+/g, " ").trim();
409
+ return { key: TEST_COMMAND.test(command) ? "validate" : "command", detail: command.slice(0, 40) };
410
+ }
411
+ return { key: "investigate", detail: tool };
412
+ }
413
+
414
+ // a mesma etapa seguida não repete a linha: troca o detalhe; só as 6 últimas ficam na tela
415
+ export function pushStage(trail, stage) {
416
+ const last = trail.at(-1);
417
+ if (last?.key === stage.key) return [...trail.slice(0, -1), { ...last, detail: stage.detail || last.detail, count: (last.count ?? 1) + 1 }];
418
+ return [...trail, { ...stage, count: 1 }].slice(-6);
419
+ }
420
+
421
+ // /agente (owner 2026-11-28: os mesmos efeitos do modelo logado): o rastro sai das ferramentas que o agente externo chamou
422
+ export function trailOf(result) {
423
+ let trail = [{ key: "interpret", count: 1 }];
424
+ for (const message of result?.messages ?? []) {
425
+ for (const part of message.content ?? []) if (part.type === "toolCall") trail = pushStage(trail, stageOf(part.name, part.arguments ?? {}));
426
+ }
427
+ if (result?.partial?.kind === "text") trail = pushStage(trail, { key: "answer" });
428
+ return trail;
429
+ }
430
+
431
+ // fechamento comum aos dois: o rastro fica, os ✓ acendem em sequência e "Pronto" fica verde 2 s, depois cinza até o próximo
432
+ // pedido; sem spinner ninguém redesenha, então só estes poucos temporizadores pedem a tela (nenhum em loop)
433
+ let doneTimers = [];
434
+ export function clearDone(ui) {
435
+ for (const timer of doneTimers) clearTimeout(timer);
436
+ doneTimers = [];
437
+ ui?.setWidget?.(ABOVE_BOX, undefined);
438
+ }
439
+ export function showDone(ui, trail, summary = "") {
440
+ clearDone(ui);
441
+ if (!trail?.length) return;
442
+ const done = { at: Date.now(), summary };
443
+ const calls = trail.reduce((sum, stage) => sum + (["interpret", "answer"].includes(stage.key) ? 0 : stage.count ?? 1), 0);
444
+ if (calls) done.summary = `${calls} ${t("operações", "operaciones", "operations")}${summary ? ` · ${summary}` : ""}`;
445
+ ui?.setWidget?.(ABOVE_BOX, (_tui, theme) => ({ render: (width) => [...stageLines(theme, trail, { width, done }), ""], invalidate() {} }), { placement: "aboveEditor" });
446
+ const redraw = () => { try { globalThis.__pinkMicTarget?.redraw?.(); } catch {} }; // o editor publica o redesenho da tela
447
+ doneTimers = [...Array.from({ length: 8 }, (_, i) => setTimeout(redraw, 40 * (i + 1))), setTimeout(redraw, DONE_GREEN_MS + 20)];
448
+ for (const timer of doneTimers) timer.unref?.();
449
+ }
450
+
451
+ // done: { at, summary } — fechamento (Renoir): os ✓ acendem em sequência (40 ms cada, até 300 ms) e "✓ Pronto · tempo ·
452
+ // tokens" fica verde 2 s; depois só a linha de resumo, em cinza, até o próximo pedido
453
+ export const DONE_GREEN_MS = 2000;
454
+ export function stageLines(theme, trail, { now = Date.now(), still: stopped = still(), width = 80, done = undefined } = {}) {
455
+ setAppearance(theme);
456
+ const ready = done ? `${t("Pronto", "Listo", "Done")}${done.summary ? ` · ${done.summary}` : ""}` : "";
457
+ if (done && now - done.at >= DONE_GREEN_MS) return [fit(` ${theme.fg("muted", `✓ ${ready}`)}`, width)];
458
+ const lit = done ? (stopped ? trail.length : Math.floor((now - done.at) / Math.min(40, 300 / Math.max(1, trail.length)))) : trail.length - 1;
459
+ const lines = trail.map((stage, index) => {
460
+ const spec = STAGES[stage.key] ?? STAGES.investigate;
461
+ const detail = stage.detail ? theme.fg("dim", ` · ${stage.detail}${stage.count > 1 ? ` (+${stage.count - 1})` : ""}`) : "";
462
+ if (done) return fit(` ${index < lit ? (stage.failed ? rgb(248, 113, 113)("✗") : GREEN("✓")) : theme.fg("dim", "·")} ${theme.fg("muted", spec.label)}${detail}`, width);
463
+ if (index < lit) return fit(` ${stage.failed ? rgb(248, 113, 113)("✗") : GREEN("✓")} ${theme.fg("muted", spec.label)}${detail}`, width);
464
+ const icon = spec.frames[stopped ? 0 : Math.floor(now / FRAME_MS) % spec.frames.length];
465
+ const label = stopped ? spec.color(`${spec.label}...`) : `${shimmer(spec.label, spec.color.rgb, now)}${spec.color("...")}`;
466
+ return fit(` ${spec.color(icon)} ${label}${detail}`, width);
467
+ });
468
+ return done ? [...lines, fit(` ${GREEN(`✓ ${ready}`)}`, width)] : lines;
469
+ }
297
470
  const BELOW_BOX = "pink-subagentes-embaixo";
298
471
  export const THREE_COLUMNS = 150; // >= 150: sessões, conversa e contexto
299
472
  export const TWO_COLUMNS = 115; // 115-149: some a coluna de sessões; < 115: só a conversa
@@ -340,9 +513,16 @@ export function topBar({ theme, width, rows, data }) {
340
513
 
341
514
  export const SHORTCUTS = [["ctrl+p", t("comandos", "comandos", "commands")], ["ctrl+c", t("limpar", "limpiar", "clear")], ["/hotkeys", t("ajuda", "ayuda", "help")]]; // os atalhos reais do Pink
342
515
 
516
+ // com o /agente ligado, a barra mostra o agente e o modelo dele, não o modelo do Pink
517
+ export function externalModel(external = Reflect.get(globalThis, "__pinkExternalAgent")) {
518
+ return external?.name ? [external.name, external.model && shortModel(external.model)].filter(Boolean).join(" · ") : undefined;
519
+ }
520
+
343
521
  export function bottomBar({ theme, width, rows, data }) {
344
522
  const sep = theme.fg("dim", " │ ");
345
- const left = ` ${theme.fg("muted", data.folder || "")}${data.branch && width >= 80 ? `${sep}${theme.fg("accent", `⎇ ${data.branch}`)}` : ""}`;
523
+ // modo e modelo à esquerda, como o BUILD MODE · ● modelo do mockup do guia (owner 2026-11-28)
524
+ const mode = width >= 90 ? `${theme.fg("accent", `${(AGENTS[data.agent]?.label ?? "Build").toUpperCase()}`)}${data.model ? ` ${theme.fg("dim", "·")} ${theme.fg("success", "●")} ${theme.fg("muted", shortModel(data.model))}` : ""}${sep}` : "";
525
+ const left = ` ${mode}${theme.fg("muted", data.folder || "")}${data.branch && width >= 80 ? `${sep}${theme.fg("accent", `⎇ ${data.branch}`)}` : ""}`;
346
526
  let keys = SHORTCUTS;
347
527
  const render = (list) => `${list.map(([key, what]) => `${theme.fg("muted", key)} ${theme.fg("dim", what)}`).join(sep)} `;
348
528
  while (keys.length > 1 && visible(left) + visible(render(keys)) + 2 > width) keys = keys.slice(0, -1);
@@ -917,10 +1097,19 @@ export function install(pink, ctx, { CustomEditor, SessionManager, version = "",
917
1097
  const rows = () => state.tui?.terminal?.rows ?? 24;
918
1098
  const homeRows = () => (framed() ? rows() - 2 * barRows(rows()) + 1 : rows()); // homeTop/homeBottomPad já descontam uma linha de rodapé
919
1099
 
1100
+ // varredura de luz no logo: uma vez por abertura, só na tela inicial, a 12 quadros/s por 0,8 s; qualquer tecla encerra
1101
+ state.sweepAt = state.home && !process.env.PINK_REDUCED_MOTION && !process.env.NO_COLOR && ctx.mode === "tui" ? Date.now() : 0;
1102
+ const sweepProgress = () => {
1103
+ if (!state.sweepAt) return null;
1104
+ const progress = (Date.now() - state.sweepAt) / SWEEP_MS;
1105
+ if (progress >= 1) return void (state.sweepAt = 0) ?? null;
1106
+ return progress;
1107
+ };
1108
+ if (state.sweepAt) for (let i = 1; i <= 11; i++) setTimeout(() => state.sweepAt && state.tui?.requestRender?.(), i * 75).unref?.();
920
1109
  ctx.ui.setHeader((tui, theme) => {
921
1110
  state.tui = tui;
922
1111
  return {
923
- render: live((width) => (state.home ? homeHeader({ theme, width, rows: homeRows(), subtitle: `coding agent · ${t("modelo", "modelo", "model")} ${ctx.model?.id ?? t("nenhum", "ninguno", "none")}` }) : []), []),
1112
+ render: live((width) => (state.home ? homeHeader({ theme, width, rows: homeRows(), sweep: sweepProgress(), subtitle: `coding agent · ${t("modelo", "modelo", "model")} ${ctx.model?.id ?? t("nenhum", "ninguno", "none")}` }) : []), []),
924
1113
  invalidate() {},
925
1114
  };
926
1115
  });
@@ -931,10 +1120,17 @@ export function install(pink, ctx, { CustomEditor, SessionManager, version = "",
931
1120
  state.tui = tui;
932
1121
  state.editor = this;
933
1122
  this.pinkKeys = keybindings;
1123
+ if (Array.isArray(this.history) && !this.history.length) this.history.push(...loadHistory());
1124
+ }
1125
+
1126
+ addToHistory(text) {
1127
+ super.addToHistory?.(text);
1128
+ if (Array.isArray(this.history)) saveHistory(this.history);
934
1129
  }
935
1130
 
936
1131
  // ctrl+p abre a paleta e tab com a caixa vazia troca o agente (OpenCode); o resto segue para o editor do Pink
937
1132
  handleInput(data) {
1133
+ state.sweepAt = 0; // qualquer tecla pula a varredura do logo
938
1134
  if (matchesKey?.(data, "ctrl+p") && onPalette) return void onPalette();
939
1135
  if (matchesKey?.(data, "tab") && onAgent && !String(this.getText?.() ?? "").trim()) return void onAgent();
940
1136
  // ctrl+n nova sessão; alt+↑/alt+↓ a sessão anterior/seguinte da coluna, salvo onde o Pink já usa a tecla (dequeue fora do Windows)
@@ -999,7 +1195,9 @@ export function install(pink, ctx, { CustomEditor, SessionManager, version = "",
999
1195
  const mic = globalThis.__pinkMicrofone;
1000
1196
  const bar = framed() && mic ? micBar(theme, mic.view()) : undefined;
1001
1197
  const working = globalThis.__pinkAgentBusy === true || (typeof ctx.isIdle === "function" && !ctx.isIdle());
1002
- const box = inputBox({ theme, content, width: outer, label, inline, mic: bar?.text, ...(working ? { hints: WORK_HINTS } : {}) });
1198
+ // tela inicial: a linha de atalhos embaixo já tem as dicas; na caixa ficam só o modelo e o microfone (owner 2026-11-28)
1199
+ const box = inputBox({ theme, content, width: outer, label, inline, mic: bar?.text, ...(working ? { hints: WORK_HINTS } : state.home ? { hints: "" } : {}),
1200
+ ...(working && !still() ? { barRgb: breathe() } : {}) }); // a barra respira só com o agente trabalhando
1003
1201
  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;
1004
1202
  const lines = box.map((line) => " ".repeat(margin) + line);
1005
1203
  if (!state.home) return lines;
@@ -1107,7 +1305,7 @@ export function install(pink, ctx, { CustomEditor, SessionManager, version = "",
1107
1305
  const columns = (width) => frameColumns(width, { home: state.home, on: globalThis.__pinkSidebarOn ?? true, sessions: process.env.PINK_MUX_CHILD !== "1" });
1108
1306
  const bars = () => {
1109
1307
  const usage = ctx.getContextUsage?.();
1110
- return { version, folder: tilde(ctx.cwd), branch: state.branch, agent: PINK.agent, context: usage ? { tokens: usage.tokens, percent: usage.percent, window: usage.contextWindow } : undefined };
1308
+ return { version, folder: tilde(ctx.cwd), branch: state.branch, agent: PINK.agent, model: externalModel() ?? ctx.model?.id, context: usage ? { tokens: usage.tokens, percent: usage.percent, window: usage.contextWindow } : undefined };
1111
1309
  };
1112
1310
  globalThis.__pinkFrame = {
1113
1311
  // clique na coluna SESSÕES: linha 0 título, 1 em branco, depois as sessões e "+ Nova sessão"
@@ -1377,6 +1575,30 @@ export function subagentLaunch(args, theme, pad, width) {
1377
1575
  return [`${margin}${theme.fg("success", "●")} ${theme.fg("text", head)}${args.background ? theme.fg("dim", t(" em segundo plano", " en segundo plano", " in the background")) : ""}`, ...list.map((item, index) => `${margin} ${theme.fg("muted", index === list.length - 1 ? "└" : "├")} ${theme.fg("text", flat(item.agent))}${flat(item.task) ? theme.fg("muted", ` (${flat(item.task)})`) : ""}`)].map((row) => fit(row, width));
1378
1576
  }
1379
1577
 
1578
+ // o resultado fica preso ao comando com ⎿ (owner 2026-11-28): as últimas linhas; o resto vira "… N linhas ocultas (ctrl+o)"
1579
+ export const TAIL_LINES = 3;
1580
+ export function outputTail(text, max = TAIL_LINES) {
1581
+ const all = String(text ?? "").split("\n").map((row) => cleanLine(row)).filter(Boolean);
1582
+ return { lines: all.slice(-max), hidden: Math.max(0, all.length - max) };
1583
+ }
1584
+ export function tailRows(theme, tail, { width, pad = 0, error = false, hint = " (ctrl+o)" }) {
1585
+ if (!tail?.lines?.length) return [];
1586
+ const margin = " ".repeat(pad + 2);
1587
+ const rows = [...(tail.hidden ? [theme.fg("dim", `… ${tail.hidden} ${tail.hidden === 1 ? t("linha oculta", "línea oculta", "hidden line") : t("linhas ocultas", "líneas ocultas", "hidden lines")}${hint}`)] : []), ...tail.lines.map((row) => theme.fg(error ? "error" : "dim", row))];
1588
+ return rows.map((row, i) => fit(`${margin}${i ? " " : theme.fg("dim", "⎿ ")}${row}`, width));
1589
+ }
1590
+
1591
+ // pedido de permissão com moldura (só ele: a conversa segue sem caixas); amarelo é "esperando você"
1592
+ export function framedAsk(title, body, width = Math.min(90, (process.stdout.columns || 80) - 6)) {
1593
+ const inner = Math.max(20, width - 4);
1594
+ const wrap = (text) => String(text).split("\n").flatMap((row) => row.replace(/\s+$/, "").match(new RegExp(`.{1,${inner}}`, "g")) ?? [""]);
1595
+ const edge = (text) => paint(250, 204, 21, text);
1596
+ const head = `─ ${String(title).slice(0, inner - 2)} `;
1597
+ return [edge(`╭${head}${"─".repeat(Math.max(0, inner + 2 - head.length))}╮`),
1598
+ ...wrap(body).map((row) => `${edge("│")} ${row}${" ".repeat(Math.max(0, inner - [...row].length))} ${edge("│")}`),
1599
+ edge(`╰${"─".repeat(inner + 2)}╯`)].join("\n");
1600
+ }
1601
+
1380
1602
  export function compactToolRenderer(toolName, next) {
1381
1603
  const base = next?.();
1382
1604
  const empty = { render: () => [], invalidate() {} };
@@ -1416,12 +1638,21 @@ export function compactToolRenderer(toolName, next) {
1416
1638
  const summary = line(theme, context.outputPad, toolSummary(toolName, context.args ?? {}, result), `${time}${context.isError ? theme.fg("error", t(" · erro", " · error", " · error")) : ""}`);
1417
1639
  // edit e write: o diff fica aberto sob a linha (como no Claude Code); o write mostra as primeiras 40 linhas
1418
1640
  const diff = context.isError ? "" : toolName === "edit" ? result?.details?.diff : toolName === "write" ? writeDiff(context.args?.content) : "";
1419
- if (!diff) return grouped(theme, context.outputPad, context.toolCallId, summary);
1641
+ if (!diff) {
1642
+ // comando e ferramenta com erro mostram o fim da saída; em grupo segue uma linha só
1643
+ const shell = toolName === "bash" || toolName === "powershell";
1644
+ const text = shell || context.isError ? (result?.content ?? []).filter((part) => part?.type === "text").map((part) => part.text).join("\n") : "";
1645
+ const tail = outputTail(text);
1646
+ return grouped(theme, context.outputPad, context.toolCallId, !tail.lines.length ? summary : {
1647
+ render: (width) => [...summary.render(width), ...tailRows(theme, tail, { width, pad: context.outputPad, error: context.isError })],
1648
+ invalidate() {},
1649
+ });
1650
+ }
1420
1651
  const cache = new Map();
1421
1652
  const pad2 = context.outputPad + 2;
1422
1653
  return {
1423
1654
  render: (width) => {
1424
- if (!cache.has(width)) cache.set(width, [...summary.render(width), ...diffBlock({ theme, diff, width: Math.max(8, width - pad2), max: 200 }).map((row) => " ".repeat(pad2) + row)]);
1655
+ if (!cache.has(width)) cache.set(width, [...summary.render(width), ...diffBlock({ theme, diff, width: Math.max(8, width - pad2), max: 200 }).map((row, i) => (i ? " ".repeat(pad2) : `${" ".repeat(context.outputPad)}${theme.fg("dim", "⎿ ")}`) + row)]);
1425
1656
  return cache.get(width);
1426
1657
  },
1427
1658
  invalidate: () => cache.clear(),
@@ -1693,7 +1924,10 @@ function registerOpenCodeFunctions(pink) {
1693
1924
  PINK.runTimer.unref?.();
1694
1925
  // uma linha vazia entre o "Trabalhando" e a caixa; o relógio de cima (1 s) redesenha a tela e a lista de baixo junto
1695
1926
  // fábrica, não [""]: a lista vira Text(""), que não desenha nada, e o "Trabalhando" ficava colado (owner 2026-11-25)
1696
- ctx.ui.setWidget?.(ABOVE_BOX, () => ({ render: () => [""], invalidate() {} }), { placement: "aboveEditor" });
1927
+ // as etapas (interpretar, mapear, investigar...) vão aqui, embaixo do "Trabalhando"; o spinner do motor já redesenha a tela
1928
+ PINK.stages = [{ key: "interpret", count: 1 }];
1929
+ clearDone();
1930
+ ctx.ui.setWidget?.(ABOVE_BOX, (_tui, theme) => ({ render: (width) => [...stageLines(theme, PINK.stages ?? [], { width }), ""], invalidate() {} }), { placement: "aboveEditor" });
1697
1931
  ctx.ui.setWidget?.(BELOW_BOX, (_tui, theme) => ({
1698
1932
  render: (width) => belowBox(theme, width, { agents: [...runningSubagents(PINK.subagents), ...dagAgentsCached(ctx.cwd)], side: globalThis.__pinkRightOn === true }),
1699
1933
  invalidate() {},
@@ -1703,8 +1937,11 @@ function registerOpenCodeFunctions(pink) {
1703
1937
  clearInterval(PINK.runTimer);
1704
1938
  PINK.subagents.clear(); // ferramenta bloqueada ou interrompida não manda tool_result
1705
1939
  ctx.ui.setWorkingMessage?.();
1706
- ctx.ui.setWidget?.(ABOVE_BOX, undefined);
1707
1940
  ctx.ui.setWidget?.(BELOW_BOX, undefined);
1941
+ let summary = "";
1942
+ try { summary = PINK.run ? runLabel(PINK.run.summary()) : ""; } catch {}
1943
+ if (PINK.stages?.length) showDone(ctx.ui, PINK.stages, summary);
1944
+ else clearDone(ctx.ui);
1708
1945
  if (PINK.run?.last !== undefined) PINK.runOf.set(PINK.run.last, PINK.run.summary());
1709
1946
  [PINK.lastRun, PINK.lastRunEnd, PINK.run, PINK.runShow] = [PINK.run, Date.now(), undefined, undefined];
1710
1947
  });
@@ -1732,6 +1969,7 @@ function registerOpenCodeFunctions(pink) {
1732
1969
  PINK.runShow?.();
1733
1970
  }
1734
1971
  const kind = event?.assistantMessageEvent?.type;
1972
+ if (kind === "text_delta" && PINK.stages && PINK.stages.at(-1)?.key !== "answer") PINK.stages = pushStage(PINK.stages, { key: "answer" });
1735
1973
  if (kind !== "thinking_start" && kind !== "thinking_end") return;
1736
1974
  const key = event.message?.timestamp;
1737
1975
  const runs = PINK.thinking.get(key) ?? [];
@@ -1752,6 +1990,7 @@ function registerOpenCodeFunctions(pink) {
1752
1990
  });
1753
1991
  pink.on("tool_result", async (event) => {
1754
1992
  trackSubagent(PINK.subagents, event);
1993
+ if (event?.isError && PINK.stages?.length && PINK.stages.at(-1).key !== "answer") PINK.stages = [...PINK.stages.slice(0, -1), { ...PINK.stages.at(-1), failed: true }]; // ferramenta com erro: ✗ vermelho
1755
1994
  // Git Bash, docker e cia. mexem no modo do console do Windows: o teclado parava de chegar ao Pink ("trava")
1756
1995
  if (process.platform === "win32" && (event?.toolName === "bash" || event?.toolName === "powershell")) {
1757
1996
  try {
@@ -1761,6 +2000,7 @@ function registerOpenCodeFunctions(pink) {
1761
2000
  });
1762
2001
  pink.on("tool_call", async (event, ctx) => {
1763
2002
  trackSubagent(PINK.subagents, event);
2003
+ if (PINK.stages) PINK.stages = pushStage(PINK.stages, stageOf(event?.toolName, event?.input ?? {}));
1764
2004
  const target = event.toolName === "write" ? event.input?.path : undefined;
1765
2005
  if (typeof target === "string" && target) {
1766
2006
  try {
@@ -1772,7 +2012,7 @@ function registerOpenCodeFunctions(pink) {
1772
2012
  if (PINK.agent !== "plan") return;
1773
2013
  const decision = planDecision(event.toolName, pink.getAllTools?.().find((tool) => tool.name === event.toolName)?.annotations);
1774
2014
  if (decision === "allow") return;
1775
- if (decision === "ask" && ctx.hasUI && (await ctx.ui.confirm?.(t("Agente Plano: rodar este comando?", "Agente Plan: ¿ejecutar este comando?", "Plan agent: run this command?"), String(event.input?.command ?? event.toolName)))) return;
2015
+ if (decision === "ask" && ctx.hasUI && (await ctx.ui.confirm?.(t("Agente Plano: rodar este comando?", "Agente Plan: ¿ejecutar este comando?", "Plan agent: run this command?"), (ctx.mode === "tui" ? framedAsk(event.toolName, String(event.input?.command ?? event.toolName)) : String(event.input?.command ?? event.toolName))))) return;
1776
2016
  return { block: true, reason: t(`Agente Plano (só leitura): ${event.toolName} não é permitido. Peça ao usuário para trocar para o Build (tab).`, `Agente Plan (solo lectura): ${event.toolName} no está permitido. Pide al usuario que cambie a Build (tab).`, `Plan agent (read-only): ${event.toolName} is not allowed. Ask the user to switch to Build (tab).`) };
1777
2017
  });
1778
2018
  // seções do prompt, não o prompt inteiro: devolver systemPrompt forçava o texto e apagava as seções das outras extensões (Ponytail)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@thothdev/pink",
3
- "version": "1.0.31",
3
+ "version": "1.0.32",
4
4
  "description": "Open-source AI coding agent for the terminal that also drives Claude Code, Codex, OpenCode and other agents, with parallel sessions, visible plan and changes, and real undo.",
5
5
  "type": "module",
6
6
  "piConfig": {