@thothdev/pink 1.0.35 → 1.0.40

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,30 @@
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.40] - 2026-11-29
7
+
8
+ - O Pink registra em `~/.pink/agent/crash.log` quando abre e quando fecha (e o relatório do Node numa falha fatal). Se ele cair de novo sem deixar a linha de saída, sabemos que foi encerrado por fora.
9
+
10
+ ## [1.0.39] - 2026-11-29
11
+
12
+ - "Permite tudo" não volta mais sozinho ao modo padrão quando o Pink recarrega as extensões (troca de sessão, /reload); vale até fechar o Pink ou trocar o modo, como o aviso diz.
13
+
14
+ ## [1.0.38] - 2026-11-29
15
+
16
+ - `/agente`: quando o Claude Code ou o Codex avisam que a cota acabou (como texto da resposta), o Pink trata como falha: ponto "sem cota" e aviso acima da caixa.
17
+ - Novo `/efeitos`: completo, reduzido (sem animação) ou simples (sem animação e sem cor); fica salvo.
18
+ - Revisão do Renoir: o ponto antes do modelo só aparece com problema e com texto curto; modo plano em lavanda e "permite tudo" em magenta; o subagente trabalhando gira um arco (não repete o giro da etapa) e voltou o espaço antes do nome; o anel gira também com o agente parado; o aviso do limite do ChatGPT usa o mesmo aviso acima da caixa; "ctrl+enter envia agora" igual na caixa e na fila.
19
+
20
+ ## [1.0.37] - 2026-11-29
21
+
22
+ - Ponto de conexão com o provedor antes do modelo (verde quando responde; com problema mostra a causa: cota ou limite esgotado, sem acesso, sem conexão, pedido recusado) e aviso curto acima da caixa quando a resposta falha, a conversa é compactada ou a compactação falha. Vale no Pink e no `/agente`.
23
+ - A barra da caixa muda de cor com o modo: âmbar (pergunta tudo), azul (plano), vermelho (permite tudo); no padrão continua rosa.
24
+ - Subagente trabalhando ganha um ícone girando no lugar da bolinha parada.
25
+
26
+ ## [1.0.36] - 2026-11-29
27
+
28
+ - Mensagem na fila, como no Claude Code: embaixo dela aparece "└ Na fila · ctrl+enter envia agora" no `/agente` (interrompe o agente e manda a fila) e "└ Na fila · entra no próximo passo" no modelo logado. O texto da fila do modelo logado saiu do inglês.
29
+
6
30
  ## [1.0.35] - 2026-11-29
7
31
 
8
32
  - As etapas ficam alinhadas com as linhas de ferramenta logo abaixo (um espaço a menos à esquerda).
@@ -3837,15 +3837,15 @@ export class InteractiveMode {
3837
3837
  if (steeringMessages.length > 0 || followUpMessages.length > 0) {
3838
3838
  this.pendingMessagesContainer.addChild(new Spacer(1));
3839
3839
  for (const message of steeringMessages) {
3840
- const text = theme.fg("dim", `Steering: ${message}`);
3840
+ const text = theme.fg("dim", globalThis.__pinkQueue ? `> ${message}` : `Steering: ${message}`);
3841
3841
  this.pendingMessagesContainer.addChild(new TruncatedText(text, 1, 0));
3842
3842
  }
3843
3843
  for (const message of followUpMessages) {
3844
- const text = theme.fg("dim", `Follow-up: ${message}`);
3844
+ const text = theme.fg("dim", globalThis.__pinkQueue ? `> ${message}${globalThis.__pinkQueue.followUp}` : `Follow-up: ${message}`);
3845
3845
  this.pendingMessagesContainer.addChild(new TruncatedText(text, 1, 0));
3846
3846
  }
3847
3847
  const dequeueHint = this.getAppKeyDisplay("app.message.dequeue");
3848
- const hintText = theme.fg("dim", `↳ ${dequeueHint} to edit all queued messages`);
3848
+ const hintText = theme.fg("dim", globalThis.__pinkQueue ? globalThis.__pinkQueue.hint(dequeueHint) : `↳ ${dequeueHint} to edit all queued messages`);
3849
3849
  this.pendingMessagesContainer.addChild(new TruncatedText(hintText, 1, 0));
3850
3850
  }
3851
3851
  }
package/dist/mux/pink.mjs CHANGED
@@ -160,6 +160,26 @@ export function logChildExit(session, exitCode, signal, env = process.env, write
160
160
  } catch { /* sem disco, sem registro */ }
161
161
  }
162
162
 
163
+ // o próprio mux morria sem rastro (owner 2026-11-29: tela congelada, mouse vazando no PowerShell, nada no crash.log nem no
164
+ // Windows). Agora ele registra quando abre e quando sai: abertura sem saída no log = processo encerrado por fora (ou queda
165
+ // nativa, que deixa o relatório do Node em ~/.pink/agent)
166
+ export function logMux(text, env = process.env, write = appendFileSync) {
167
+ try {
168
+ const dir = env.PINK_CODING_AGENT_DIR || path.join(homedir(), ".pink", "agent");
169
+ mkdirSync(dir, { recursive: true });
170
+ write(path.join(dir, "crash.log"), `${new Date().toISOString()} mux pid=${process.pid} ${text}\n`);
171
+ } catch { /* sem disco, sem registro */ }
172
+ }
173
+ export function watchMux(proc = process, env = process.env) {
174
+ logMux(`aberto · node ${proc.version}`, env);
175
+ proc.on("uncaughtExceptionMonitor", (err, origin) => logMux(`${origin}: ${err?.stack || err}`, env));
176
+ proc.on("exit", (code) => logMux(`saiu · código ${exitCodeText(code)}`, env));
177
+ try {
178
+ proc.report.reportOnFatalError = true;
179
+ proc.report.directory = env.PINK_CODING_AGENT_DIR || path.join(homedir(), ".pink", "agent");
180
+ } catch { /* Node sem relatório */ }
181
+ }
182
+
163
183
  export function onSignal(session, signal, isActive) {
164
184
  if (signal === "work") session.working = true;
165
185
  if (signal === "idle") {
@@ -1001,6 +1021,7 @@ async function main() {
1001
1021
  }
1002
1022
  }
1003
1023
  out.write(`\x1b[?1049h\x1b[2J\x1b[?25l${MOUSE_ON}`);
1024
+ watchMux();
1004
1025
  process.on("exit", () => finished || out.write(`${MOUSE_OFF}\x1b[?2004l\x1b[?1l\x1b[?25h\x1b[?1049l`)); // finish já restaurou e pode ter escrito o erro
1005
1026
  process.on("SIGTERM", () => { quittingAll = true; finish(143); });
1006
1027
  process.on("SIGHUP", () => { quittingAll = true; finish(129); }); // janela do terminal fechada: guarda as abertas como "sair do Pink"
@@ -28,6 +28,8 @@ const muxWrite = (text: string) => {
28
28
  if (process.env.PINK_MUX_CHILD === "1" && process.stdout.isTTY) process.stdout.write(text);
29
29
  };
30
30
 
31
+ const RING = ["◜", "◝", "◞", "◟"]; // o mesmo anel girando da lateral (pink-ui), no lugar do ⏳ parado
32
+
31
33
  export function createBackground(pink: any, { now = Date.now, write = muxWrite } = {}) {
32
34
  const jobs = new Map<number, Job>();
33
35
  let next = 1;
@@ -38,7 +40,7 @@ export function createBackground(pink: any, { now = Date.now, write = muxWrite }
38
40
  (globalThis as any).__pinkSubagentJobs = jobs; // a seção SUBAGENTES da lateral lê daqui
39
41
 
40
42
  const lines = () => [
41
- ...[...jobs.values()].map((job) => `⏳ #${job.id} ${job.agent} · ${oneLine(job.task, 60)} · ${clock(now() - job.started)} · ↓ ${tokens(job.tokens)} tokens`),
43
+ ...[...jobs.values()].map((job) => `${RING[Math.floor(now() / 125) % RING.length]} #${job.id} ${job.agent} · ${oneLine(job.task, 60)} · ${clock(now() - job.started)} · ↓ ${tokens(job.tokens)} tokens`),
42
44
  t(" /subagentes para listar ou cancelar", " /subagentes para listar o cancelar", " /subagentes to list or cancel"),
43
45
  ];
44
46
  const refresh = () => {
@@ -59,7 +61,7 @@ export function createBackground(pink: any, { now = Date.now, write = muxWrite }
59
61
  }
60
62
  }
61
63
  if (jobs.size && !closed && !timer) {
62
- timer = setInterval(refresh, 1000); // o relógio de cada linha
64
+ timer = setInterval(refresh, 125); // o relógio de cada linha e o anel girando
63
65
  timer.unref?.();
64
66
  } else if ((!jobs.size || closed) && timer) {
65
67
  clearInterval(timer);
@@ -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, clearDone, showDone, stageLines, trailOf, framedAsk, outputTail, tailRows, exitFailed } 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, exitFailed, QUEUE_HINT, agentMark } 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)
@@ -344,6 +344,13 @@ export function compact(list: any[]) {
344
344
  });
345
345
  }
346
346
 
347
+ // Claude Code e Codex avisam que a cota acabou como TEXTO da resposta, não como erro: sem isto o Pink mostrava a frase
348
+ // como se fosse uma resposta e nada avisava (owner 2026-11-29). Só vale para resposta curta que é a própria frase.
349
+ export const limitNotice = (answer: string) => {
350
+ const text = String(answer ?? "").replace(/\s+/g, " ").trim();
351
+ return text.length > 0 && text.length < 300 && /hit your (usage )?limit|usage limit (reached|exceeded)|limit reached|out of (extra )?usage|rate.?limit(ed)?\b|you'?ve reached your|resets? (at|in|on) \d|acabou a cota|limite de uso/i.test(text) ? text : "";
352
+ };
353
+
347
354
  export function render(result: any, cwd = ""): string {
348
355
  const all = compact(steps(result, cwd));
349
356
  const tools = all.filter((step) => step.kind === "tool" || step.kind === "agents").map((step) => (step.kind === "tool" ? `→ ${step.line}` : step.list.map((item: any) => `→ ${t("subagente", "subagente", "subagent")} ${item.agent}: ${item.task}`).join("\n")));
@@ -446,7 +453,11 @@ export default function (pink: any, list: typeof externalAgents = externalAgents
446
453
  (globalThis as any).__pinkAgentBusy = false; // a caixa volta às dicas de sempre (pink-ui)
447
454
  };
448
455
  // 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)
449
- const around = (lines: string[], width: number, theme: any) => [...queueLines(active?.queue ?? [], width).map((line) => theme.fg("dim", line)), ...lines, ""];
456
+ // embaixo da fila, como mandar já (owner 2026-11-29, como o Claude Code)
457
+ const around = (lines: string[], width: number, theme: any) => {
458
+ const queue = queueLines(active?.queue ?? [], width);
459
+ return [...[...queue, ...(queue.length ? [fit(QUEUE_HINT, width)] : [])].map((line) => theme.fg("dim", line)), ...lines, ""];
460
+ };
450
461
  // a etapa atual leva o tempo e os tokens e é a única linha animada (owner 2026-11-29): o Loader segue vivo só para
451
462
  // redesenhar a tela, sem a linha "Trabalhando" embaixo
452
463
  const busy = (ui: any, output: () => number, doing: (width: number, theme: any, status: string) => string[]) => {
@@ -512,7 +523,7 @@ export default function (pink: any, list: typeof externalAgents = externalAgents
512
523
  ui.setWidget(CHILDREN, items.length && !side ? (_screen: any, theme: any) => ({
513
524
  render: (width: number) => items.map((item: any) => {
514
525
  const clock = item.clock ?? elapsedLabel(Date.now() - item.started);
515
- const mark = theme.fg(item.mark === "✗" ? "error" : item.mark === "✓" ? "success" : "accent", item.mark ?? "●");
526
+ const mark = theme.fg(item.mark === "✗" ? "error" : item.mark === "✓" ? "success" : "accent", agentMark(item.mark));
516
527
  return fit(` ${mark} ${theme.fg("text", item.agent)} ${theme.fg("muted", item.task)} ${theme.fg("dim", clock)}`, width);
517
528
  }),
518
529
  invalidate() {},
@@ -521,6 +532,12 @@ export default function (pink: any, list: typeof externalAgents = externalAgents
521
532
  };
522
533
  tick();
523
534
  childTimer = setInterval(tick, 2000);
535
+ // o anel do subagente gira entre uma leitura e outra: só redesenha, sem reler o banco
536
+ const spin = setInterval(() => {
537
+ if (!childTimer) return clearInterval(spin);
538
+ if (((globalThis as any).__pinkAgentChildren ?? []).length) screenRef?.requestRender?.();
539
+ }, 125);
540
+ spin.unref?.();
524
541
  childTimer.unref?.();
525
542
  };
526
543
 
@@ -685,6 +702,10 @@ export default function (pink: any, list: typeof externalAgents = externalAgents
685
702
  result.stopReason = "error";
686
703
  result.errorMessage = controller.signal.aborted ? t("cancelado", "cancelado", "cancelled") : String(error?.message ?? error);
687
704
  }
705
+ if (result.stopReason !== "error" && !controller.signal.aborted) {
706
+ const limit = limitNotice(compact(steps(result, ctx.cwd)).filter((step: any) => step.kind === "text").at(-1)?.text ?? "");
707
+ if (limit) (result.stopReason = "error"), (result.errorMessage = limit);
708
+ }
688
709
  // acabou a mensagem: subagente sem aviso de fim não pode ficar "rodando" para sempre
689
710
  for (const id of Object.keys(result.subagents ?? {})) subagentEnd(result, id, result.stopReason === "error");
690
711
  if (current.controller === controller) current.controller = undefined;
@@ -702,6 +723,8 @@ export default function (pink: any, list: typeof externalAgents = externalAgents
702
723
  if (!current.agent.model && result.model && result.model !== name) (globalThis as any).__pinkExternalAgent = { name, model: result.model, effort: current.agent.effort };
703
724
  }
704
725
  const error = result.stopReason === "error" ? String(result.errorMessage ?? t("erro", "error", "error")) : undefined;
726
+ // o ponto de conexão e o aviso são os do Pink (pink-ui)
727
+ if (!controller.signal.aborted) (globalThis as any).__pinkReportLink?.(ctx.ui, error !== undefined ? { error } : { status: 200 });
705
728
  pink.sendMessage({ customType: "pink-agente", display: true, content: render(result, ctx.cwd), details: { agent: name, session: current.resume?.id, model: result.model, usage: result.usage, error, steps: steps(result, ctx.cwd), changes: fileChanges(result, ctx.cwd), ms: Date.now() - started, output: outputOf(result) } });
706
729
  pink.events?.emit?.("pink:agent_settled", { ctx, aborted: controller.signal.aborted });
707
730
  // trocaram o modelo do Pink no meio: o que o agente fez já está na sessão; o novo modelo continua o pedido
@@ -19,6 +19,38 @@ import { micBar } from "./pink-microfone.ts";
19
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
20
  // a sessão; agora fica em disco, as 100 últimas, mais nova primeiro
21
21
  export const HISTORY_MAX = 100;
22
+ // /efeitos (guia de design, seção 8 e 10): movimento e cor ligados ou não, salvo entre sessões. Usa as mesmas chaves que
23
+ // os efeitos já leem (PINK_REDUCED_MOTION e NO_COLOR); a variável que a pessoa definiu fora do Pink sempre vale.
24
+ export const effectsFile = (env = process.env) => path.join(env.PINK_CODING_AGENT_DIR || path.join(os.homedir(), ".pink", "agent"), "efeitos.json");
25
+ export const EFFECTS = {
26
+ completo: { motion: true, color: true, label: t("Completo: animações e cores", "Completo: animaciones y colores", "Full: animations and colors") },
27
+ reduzido: { motion: false, color: true, label: t("Reduzido: cores, sem animação", "Reducido: colores, sin animación", "Reduced: colors, no animation") },
28
+ simples: { motion: false, color: false, label: t("Simples: sem animação e sem cor", "Simple: sin animación ni color", "Plain: no animation, no color") },
29
+ };
30
+ const effectsOwn = { motion: process.env.PINK_REDUCED_MOTION !== undefined, color: process.env.NO_COLOR !== undefined };
31
+ export function applyEffects(name, env = process.env) {
32
+ const item = EFFECTS[name];
33
+ if (!item) return false;
34
+ const own = env === process.env ? effectsOwn : { motion: false, color: false };
35
+ if (!own.motion) item.motion ? delete env.PINK_REDUCED_MOTION : (env.PINK_REDUCED_MOTION = "1");
36
+ if (!own.color) item.color ? delete env.NO_COLOR : (env.NO_COLOR = "1");
37
+ return true;
38
+ }
39
+ export function saveEffects(name, env = process.env) {
40
+ if (!applyEffects(name, env)) return false;
41
+ try {
42
+ fs.mkdirSync(path.dirname(effectsFile(env)), { recursive: true });
43
+ fs.writeFileSync(effectsFile(env), JSON.stringify({ effects: name }));
44
+ return true;
45
+ } catch {
46
+ return false;
47
+ }
48
+ }
49
+ try {
50
+ applyEffects(JSON.parse(fs.readFileSync(effectsFile(), "utf8"))?.effects);
51
+ } catch {
52
+ /* sem escolha salva: completo */
53
+ }
22
54
  export const historyFile = (env = process.env) => path.join(env.PINK_CODING_AGENT_DIR || path.join(os.homedir(), ".pink", "agent"), "historico.json");
23
55
  export function loadHistory(file = historyFile()) {
24
56
  try {
@@ -162,8 +194,12 @@ export function footerLine({ theme, width, left, right }) {
162
194
  // "thoth thoth off" dizia modelo, provedor e nível sem explicar nada: agora o nome do modelo, o provedor só quando é
163
195
  // outro, e o nível só quando está ligado ("Sonnet 5.5 · medium", o nível sempre na palavra em inglês)
164
196
  // como no OpenCode, o agente (Build/Plano) vem antes do modelo, na cor da marca
165
- export function modelLabel({ theme, model, thinking, agent, permission = "edits", external = Reflect.get(globalThis, "__pinkExternalAgent") }) {
166
- const mode = agent !== "build" ? "" : permission === "ask" ? t(" (pergunta tudo)", " (pregunta todo)", " (ask everything)") : permission === "all" ? t(" (permite tudo)", " (permite todo)", " (allows everything)") : "";
197
+ export function modelLabel({ theme, model, thinking, agent, permission = "edits", external = Reflect.get(globalThis, "__pinkExternalAgent"), link = undefined }) {
198
+ const dot = linkLabel(theme, link);
199
+ return dot + modelName({ theme, model, thinking, agent, permission, external });
200
+ }
201
+ function modelName({ theme, model, thinking, agent, permission, external }) {
202
+ const mode =agent !== "build" ? "" : permission === "ask" ? t(" (pergunta tudo)", " (pregunta todo)", " (ask everything)") : permission === "all" ? t(" (permite tudo)", " (permite todo)", " (allows everything)") : "";
167
203
  const who = AGENTS[agent] ? `${theme.fg("accent", `${AGENTS[agent].label}${mode}`)}${theme.fg("muted", " · ")}` : "";
168
204
  // /agente ligado (card 1dfwh7kgfjr): o Build fica; no lugar do modelo do Pink, o agente instalado e o modelo dele
169
205
  if (external?.name) return `${who}${external.name}${theme.fg("muted", ` · ${external.model ?? t("modelo padrão", "modelo predeterminado", "default model")}${external.effort ? ` · ${external.effort}` : ""}`)}`;
@@ -383,10 +419,65 @@ const still = () => !!process.env.PINK_REDUCED_MOTION; // NO_COLOR tira só a c
383
419
  const mix = (a, b, k) => a.map((v, i) => Math.round(v + (b[i] - v) * k));
384
420
 
385
421
  // 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) {
422
+ export function breathe(now = Date.now(), period = 1600, base = PINK_RGB) {
387
423
  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);
424
+ const dark = base === PINK_RGB ? [194, 69, 127] : base.map((v) => Math.round(v * 0.76));
425
+ return mix(base, dark, (1 - Math.cos((2 * Math.PI * (step % period)) / period)) / 2);
426
+ }
427
+
428
+ // a cor da barra da caixa diz o modo de permissão (owner 2026-11-29); "aceita edições" é o padrão e fica rosa
429
+ // Renoir: plano em lavanda (a família das etapas de leitura) e "permite tudo" em magenta, porque vermelho é erro
430
+ export const MODE_RGB = { ask: [255, 179, 0], plan: [180, 160, 255], all: [236, 72, 153] };
431
+
432
+ // conexão com o provedor (Connection Pulse): o status da última resposta ou o erro da última mensagem
433
+ export function classifyLink({ status, error } = {}) {
434
+ if (error !== undefined) {
435
+ const text = String(error);
436
+ if (/429|quota|cota|rate.?limit|usage.?limit|limit.?exceeded|limit reached|hit your|out of (extra )?usage|resets? (at|in|on)|insufficient|exhaust|too many/i.test(text)) return "limit";
437
+ if (/401|403|unauthori[sz]ed|forbidden|api.?key|not.?logged|sign.?in|login/i.test(text)) return "auth";
438
+ if (/econn|enotfound|etimedout|fetch failed|network|socket|timed? ?out|offline/i.test(text)) return "net";
439
+ return "fail";
440
+ }
441
+ if (status >= 200 && status < 300) return "ok";
442
+ return status === 429 ? "limit" : status === 401 || status === 403 ? "auth" : "fail";
443
+ }
444
+ export const LINKS = {
445
+ ok: { tone: "success", text: "" },
446
+ limit: { tone: "warning", text: t("sem cota", "sin cuota", "out of quota"), long: t("Cota ou limite esgotado", "Cuota o límite agotado", "Quota or limit reached"), tip: t("Troque de modelo com /model ou espere a cota voltar.", "Cambia de modelo con /model o espera a que vuelva la cuota.", "Switch model with /model or wait for the quota to return.") },
447
+ auth: { tone: "error", text: t("sem acesso", "sin acceso", "no access"), long: t("Sem acesso ao provedor", "Sin acceso al proveedor", "No access to the provider"), tip: t("Refaça o /login desse provedor.", "Rehaz el /login de ese proveedor.", "Redo /login for that provider.") },
448
+ net: { tone: "warning", text: t("sem rede", "sin red", "offline"), long: t("Sem conexão com o provedor", "Sin conexión con el proveedor", "Cannot reach the provider"), tip: t("Confira a internet e envie de novo.", "Revisa internet y envía de nuevo.", "Check the network and send again.") },
449
+ fail: { tone: "error", text: t("recusado", "rechazado", "rejected"), long: t("O provedor recusou o pedido", "El proveedor rechazó el pedido", "The provider rejected the request"), tip: t("Envie de novo ou troque de modelo com /model.", "Envía de nuevo o cambia de modelo con /model.", "Send again or switch model with /model.") },
450
+ };
451
+ // o ponto antes do modelo só aparece com problema, com a causa curta (Renoir: ponto verde fixo é ruído)
452
+ export function linkLabel(theme, kind) {
453
+ const link = LINKS[kind];
454
+ return link?.text ? `${theme.fg(link.tone, `● ${link.text}`)}${theme.fg("muted", " · ")}` : "";
455
+ }
456
+
457
+ // aviso curto dentro do Pink (toast): uma linha acima da caixa que some sozinha
458
+ let toastTimer;
459
+ export function toast(ui, text, tone = "warning", ms = 7000) {
460
+ if (!ui?.setWidget) return;
461
+ clearTimeout(toastTimer);
462
+ ui.setWidget("pink-toast", (_screen, theme) => ({ render: (width) => [fit(` ${theme.fg(tone, "●")} ${theme.fg("text", text)}`, width)], invalidate() {} }), { placement: "aboveEditor" });
463
+ toastTimer = setTimeout(() => {
464
+ try {
465
+ ui.setWidget("pink-toast", undefined);
466
+ } catch {
467
+ /* tela já fechada */
468
+ }
469
+ }, ms);
470
+ toastTimer.unref?.();
389
471
  }
472
+ // o Pink e o /agente contam o resultado de cada resposta por aqui: o ponto e o aviso são os mesmos nos dois
473
+ export function reportLink(ui, input) {
474
+ const kind = classifyLink(input);
475
+ globalThis.__pinkLink = kind;
476
+ if (kind !== "ok" && input.error !== undefined) toast(ui, `${LINKS[kind].long}. ${LINKS[kind].tip}`, LINKS[kind].tone);
477
+ return kind;
478
+ }
479
+ globalThis.__pinkReportLink = reportLink;
480
+ globalThis.__pinkToast = toast;
390
481
 
391
482
  // brilho (shimmer): uma faixa de 3 letras, a cor da etapa com 35% de branco, percorre o rótulo da etapa atual
392
483
  export function shimmer(text, color, now = Date.now()) {
@@ -483,7 +574,14 @@ export const THREE_COLUMNS = 150; // >= 150: sessões, conversa e contexto
483
574
  export const TWO_COLUMNS = 115; // 115-149: some a coluna de sessões; < 115: só a conversa
484
575
  export const PLACEHOLDER = t("Peça a próxima etapa...", "Pide el siguiente paso...", "Ask for the next step...");
485
576
  // enquanto o agente trabalha, como o "esc interrupt" do OpenCode (owner 2026-11-25)
486
- export const WORK_HINTS = t("esc interromper · ctrl+enter enviar agora", "esc interrumpir · ctrl+enter enviar ya", "esc interrupt · ctrl+enter send now");
577
+ // mensagem na fila (owner 2026-11-29, como o Claude Code): logo abaixo dela, como mandar já. No modelo logado o Enter já
578
+ // entra no próximo passo do agente; o texto do Pi vem por patch (rebrand.json, queued-*-module) e lê isto
579
+ globalThis.__pinkQueue = {
580
+ followUp: t(" (no fim)", " (al final)", " (at the end)"),
581
+ hint: (key) => t(` └ Na fila · entra no próximo passo · ${key} edita`, ` └ En cola · entra en el próximo paso · ${key} edita`, ` └ Queued · goes in at the next step · ${key} edits`),
582
+ };
583
+ export const QUEUE_HINT = t(" └ Na fila · ctrl+enter envia agora", " └ En cola · ctrl+enter envía ya", " └ Queued · ctrl+enter to send now");
584
+ export const WORK_HINTS = t("esc interromper · ctrl+enter envia agora", "esc interrumpir · ctrl+enter envía ya", "esc interrupt · ctrl+enter send now");
487
585
  export const BOX_HINTS = t("Enter enviar · shift+tab pensar · ctrl+t ver pensamento", "Enter enviar · shift+tab pensar · ctrl+t ver razonamiento", "Enter send · shift+tab think · ctrl+t show thinking");
488
586
 
489
587
  export function frameColumns(width, { home = false, on = true, sessions = true } = {}) {
@@ -620,9 +718,13 @@ export function rightColumn({ theme, width, height, data }) {
620
718
  }
621
719
 
622
720
  // uma linha de SUBAGENTES: "● persona tarefa ........ 12s" (coluna da direita e a lista acima da caixa)
721
+ // arco girando: só o subagente trabalhando o usa (owner 2026-11-29); não é braille para não repetir o giro da etapa (Renoir)
722
+ export const AGENT_FRAMES = ["◜", "◝", "◞", "◟"];
723
+ export const agentMark = (mark, now = Date.now()) => mark ?? (still() ? "●" : AGENT_FRAMES[Math.floor(now / 125) % AGENT_FRAMES.length]);
623
724
  export function agentLine(theme, item, width, now = Date.now()) {
624
725
  const clock = theme.fg("dim", item.clock ?? elapsedLabel(now - item.started));
625
- const text = `${theme.fg(item.mark === "✗" ? "error" : item.mark === "✓" ? "success" : "accent", item.mark ?? "●")} ${theme.fg("text", String(item.agent ?? "?"))} ${theme.fg("muted", String(item.task ?? "").replace(/\s+/g, " ").trim())}`;
726
+ const mark = agentMark(item.mark, now);
727
+ const text = `${theme.fg(item.mark === "✗" ? "error" : item.mark === "✓" ? "success" : "accent", mark)} ${theme.fg("text", String(item.agent ?? "?"))} ${theme.fg("muted", String(item.task ?? "").replace(/\s+/g, " ").trim())}`;
626
728
  return footerLine({ theme, width, left: fit(text, Math.max(1, width - visible(clock) - 1)), right: clock });
627
729
  }
628
730
 
@@ -1192,7 +1294,7 @@ export function install(pink, ctx, { CustomEditor, SessionManager, version = "",
1192
1294
  const outer = state.home ? Math.min(width, HOME_WIDTH) : width;
1193
1295
  const margin = state.home ? Math.floor((width - outer) / 2) : 0;
1194
1296
  const theme = ctx.ui.theme;
1195
- const label = modelLabel({ theme, model: ctx.model, thinking: pink.getThinkingLevel?.(), agent: PINK.agent, permission: PINK.permission });
1297
+ const label = modelLabel({ theme, model: ctx.model, thinking: pink.getThinkingLevel?.(), agent: PINK.agent, permission: PINK.permission, link: globalThis.__pinkLink });
1196
1298
  const text = outer - 4;
1197
1299
  // o rótulo fica embaixo, na linha das dicas: à direita da 1ª linha ele estreitava o editor e o pedido quebrava em
1198
1300
  // ~35 colunas na tela inicial (owner 2026-11-15)
@@ -1209,7 +1311,10 @@ export function install(pink, ctx, { CustomEditor, SessionManager, version = "",
1209
1311
  const working = globalThis.__pinkAgentBusy === true || (typeof ctx.isIdle === "function" && !ctx.isIdle());
1210
1312
  // tela inicial: a linha de atalhos embaixo já tem as dicas; na caixa ficam só o modelo e o microfone (owner 2026-11-28)
1211
1313
  const box = inputBox({ theme, content, width: outer, label, inline, mic: bar?.text, ...(working ? { hints: WORK_HINTS } : state.home ? { hints: "" } : {}),
1212
- ...(working && !still() ? { barRgb: breathe() } : {}) }); // a barra respira só com o agente trabalhando
1314
+ ...(() => {
1315
+ const tint = MODE_RGB[currentMode()]; // a cor da barra é a do modo; só no padrão ela é rosa
1316
+ return working && !still() ? { barRgb: breathe(Date.now(), 1600, tint ?? PINK_RGB) } : tint ? { barRgb: tint } : {}; // a barra respira só com o agente trabalhando
1317
+ })() });
1213
1318
  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;
1214
1319
  const lines = box.map((line) => " ".repeat(margin) + line);
1215
1320
  if (!state.home) return lines;
@@ -1762,7 +1867,7 @@ export function assistantFooter({ theme, model, agent, ms, output, run }) {
1762
1867
 
1763
1868
  // estado das funções do OpenCode, compartilhado entre os comandos e a interface
1764
1869
  // agentOf: o agente de cada resposta (pelo timestamp da mensagem); created: caminhos que o write criou (não existiam antes)
1765
- export const PINK = { agent: "build", permission: globalThis.__pinkPermissionSaved === "ask" ? "ask" : "edits", todos: [], snapshots: new Map(), redo: [], agentOf: new Map(), timing: new Map(), runOf: new Map(), run: undefined, runTimer: undefined, lastRun: undefined, lastRunEnd: 0, thinking: new Map(), created: new Set(), thoth: { data: { ok: false, loading: true }, timer: undefined, busy: false, redraw: undefined }, plan: { data: { ok: false, loading: true }, timer: undefined, busy: false }, mcpOpen: false, rightHits: {} };
1870
+ export const PINK = { agent: "build", permission: ["ask", "all"].includes(globalThis.__pinkPermissionSaved) ? globalThis.__pinkPermissionSaved : "edits", todos: [], snapshots: new Map(), redo: [], agentOf: new Map(), timing: new Map(), runOf: new Map(), run: undefined, runTimer: undefined, lastRun: undefined, lastRunEnd: 0, thinking: new Map(), created: new Set(), thoth: { data: { ok: false, loading: true }, timer: undefined, busy: false, redraw: undefined }, plan: { data: { ok: false, loading: true }, timer: undefined, busy: false }, mcpOpen: false, rightHits: {} };
1766
1871
  PINK.subagents = new Map();
1767
1872
 
1768
1873
  // mensagem do usuário como no Claude Code (patch user-bar): ">" na primeira linha, sem caixa nem fundo; o recuo de 1 do
@@ -1871,6 +1976,13 @@ function registerOpenCodeFunctions(pink) {
1871
1976
  command("help", t("Paleta de comandos (ctrl+p)", "Paleta de comandos (ctrl+p)", "Command palette (ctrl+p)"), async (_args, ctx) => openPalette(pink, ctx));
1872
1977
  command("details", t("Mostra ou esconde a saída das ferramentas (ctrl+o)", "Muestra u oculta la salida de las herramientas (ctrl+o)", "Show or hide tool output (ctrl+o)"), async (_args, ctx) => ctx.ui.setToolsExpanded?.(!ctx.ui.getToolsExpanded?.()));
1873
1978
  command("init", t("Cria ou atualiza o AGENTS.md do projeto", "Crea o actualiza el AGENTS.md del proyecto", "Create or update the project's AGENTS.md"), async () => pink.sendUserMessage?.(INIT_PROMPT));
1979
+ pink.registerCommand?.("efeitos", { description: t("Liga ou desliga animações e cores (fica salvo)", "Enciende o apaga animaciones y colores (queda guardado)", "Turns animations and colors on or off (it is saved)"), getArgumentCompletions: completeFrom(() => Object.keys(EFFECTS).map((value) => ({ value, label: value, description: EFFECTS[value].label }))), handler: async (args, ctx) => {
1980
+ const typed = String(args ?? "").trim().toLowerCase();
1981
+ const labels = Object.values(EFFECTS).map((item) => item.label);
1982
+ const name = EFFECTS[typed] ? typed : Object.keys(EFFECTS)[labels.indexOf(await ctx.ui.select?.(t("Efeitos", "Efectos", "Effects"), labels))];
1983
+ if (!name) return;
1984
+ ctx.ui.notify?.(saveEffects(name) ? t(`Efeitos: ${EFFECTS[name].label}`, `Efectos: ${EFFECTS[name].label}`, `Effects: ${EFFECTS[name].label}`) : t("Efeitos trocados só nesta sessão (não deu para salvar).", "Efectos cambiados solo en esta sesión (no se pudo guardar).", "Effects changed for this session only (could not save)."), "info");
1985
+ } });
1874
1986
  pink.registerCommand?.("themes", { description: t("Escolhe o tema (fica salvo)", "Elige el tema (queda guardado)", "Choose the theme (it is saved)"), getArgumentCompletions: completeFrom(themeChoices), handler: async (args, ctx) => {
1875
1987
  const themes = (ctx.ui.getAllThemes?.() ?? []).map((theme) => theme.name);
1876
1988
  const typed = String(args ?? "").trim();
@@ -2000,6 +2112,13 @@ function registerOpenCodeFunctions(pink) {
2000
2112
  else if (runs.length && runs.at(-1).ms === undefined) runs.at(-1).ms = Date.now() - runs.at(-1).start;
2001
2113
  PINK.thinking.set(key, runs);
2002
2114
  });
2115
+ pink.on("after_provider_response", async (event) => {
2116
+ globalThis.__pinkLink = classifyLink({ status: event?.status });
2117
+ });
2118
+ pink.on("session_compact", async (event, ctx) => toast(ctx?.ui, event?.reason === "overflow" ? t("Contexto estourou: conversa compactada, tento de novo.", "El contexto se desbordó: conversación compactada, reintento.", "Context overflowed: conversation compacted, retrying.") : t("Conversa compactada para caber no contexto.", "Conversación compactada para caber en el contexto.", "Conversation compacted to fit the context."), "info"));
2119
+ pink.on("session_compact_failed", async (event, ctx) => {
2120
+ if (!event?.aborted) toast(ctx?.ui, t(`Não deu para compactar: ${String(event?.errorMessage ?? "erro").slice(0, 80)}`, `No se pudo compactar: ${String(event?.errorMessage ?? "error").slice(0, 80)}`, `Could not compact: ${String(event?.errorMessage ?? "error").slice(0, 80)}`), "error");
2121
+ });
2003
2122
  pink.on("turn_start", async () => {
2004
2123
  PINK.turnStart = Date.now();
2005
2124
  });
@@ -2007,8 +2126,12 @@ function registerOpenCodeFunctions(pink) {
2007
2126
  PINK.run?.add(event?.message);
2008
2127
  for (const run of PINK.thinking.get(event?.message?.timestamp) ?? []) run.ms ??= Date.now() - run.start; // interrompido no meio: não fica "Pensando" para sempre
2009
2128
  const hint = chatgptLimitHint(event?.message?.errorMessage);
2010
- if (hint) ctx?.ui?.notify?.(hint, "warning");
2011
- const timing = event?.message?.role === "assistant" ? PINK.timing.get(event.message.timestamp) : undefined;
2129
+ if (hint) toast(ctx?.ui, hint, "warning", 12000); // um sistema de aviso só (Renoir)
2130
+ if (!hint && event?.message?.role === "assistant") {
2131
+ if (event.message.stopReason === "error") reportLink(ctx?.ui, { error: event.message.errorMessage ?? "" });
2132
+ else if (event.message.stopReason !== "aborted") globalThis.__pinkLink = "ok";
2133
+ }
2134
+ const timing =event?.message?.role === "assistant" ? PINK.timing.get(event.message.timestamp) : undefined;
2012
2135
  if (timing?.start) timing.ms = Date.now() - timing.start;
2013
2136
  });
2014
2137
  pink.on("tool_result", async (event) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@thothdev/pink",
3
- "version": "1.0.35",
3
+ "version": "1.0.40",
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": {