@thothdev/pink 1.0.31 → 1.0.33
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 +13 -0
- package/examples/extensions/subagent/external.ts +16 -0
- package/extensions/pink-agente.ts +19 -9
- package/extensions/pink-permissions.ts +4 -1
- package/extensions/pink-ui.ts +260 -19
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -3,6 +3,19 @@
|
|
|
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.33] - 2026-11-29
|
|
7
|
+
|
|
8
|
+
- Reabrir uma sessão com conversa só do `/agente` abre direto na conversa, com a caixa de digitar embaixo, em vez da tela inicial.
|
|
9
|
+
|
|
10
|
+
## [1.0.32] - 2026-11-28
|
|
11
|
+
|
|
12
|
+
- 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.
|
|
13
|
+
- O resultado de comando (e de ferramenta com erro) aparece preso ao comando com `⎿`, com as últimas linhas e "N linhas ocultas".
|
|
14
|
+
- Pedido de permissão vem numa caixa com moldura.
|
|
15
|
+
- ↑ e ↓ trazem as mensagens já enviadas, também depois de reabrir o Pink.
|
|
16
|
+
- 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.
|
|
17
|
+
- 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).
|
|
18
|
+
|
|
6
19
|
## [1.0.29] - 2026-11-28
|
|
7
20
|
|
|
8
21
|
- 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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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") };
|
package/extensions/pink-ui.ts
CHANGED
|
@@ -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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
100
|
-
const
|
|
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
|
-
|
|
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);
|
|
@@ -841,7 +1021,8 @@ function tilde(cwd) {
|
|
|
841
1021
|
|
|
842
1022
|
export function hasMessages(ctx) {
|
|
843
1023
|
try {
|
|
844
|
-
|
|
1024
|
+
// o /agente grava o pedido como custom_message: sem contá-lo, a sessão só dele abria como nova (owner 2026-11-28)
|
|
1025
|
+
return ctx.sessionManager.getEntries().some((entry) => entry.type === "message" || isAsk(entry) || (entry.type === "custom_message" && entry.customType === "pink-agente"));
|
|
845
1026
|
} catch {
|
|
846
1027
|
return false;
|
|
847
1028
|
}
|
|
@@ -917,10 +1098,19 @@ export function install(pink, ctx, { CustomEditor, SessionManager, version = "",
|
|
|
917
1098
|
const rows = () => state.tui?.terminal?.rows ?? 24;
|
|
918
1099
|
const homeRows = () => (framed() ? rows() - 2 * barRows(rows()) + 1 : rows()); // homeTop/homeBottomPad já descontam uma linha de rodapé
|
|
919
1100
|
|
|
1101
|
+
// varredura de luz no logo: uma vez por abertura, só na tela inicial, a 12 quadros/s por 0,8 s; qualquer tecla encerra
|
|
1102
|
+
state.sweepAt = state.home && !process.env.PINK_REDUCED_MOTION && !process.env.NO_COLOR && ctx.mode === "tui" ? Date.now() : 0;
|
|
1103
|
+
const sweepProgress = () => {
|
|
1104
|
+
if (!state.sweepAt) return null;
|
|
1105
|
+
const progress = (Date.now() - state.sweepAt) / SWEEP_MS;
|
|
1106
|
+
if (progress >= 1) return void (state.sweepAt = 0) ?? null;
|
|
1107
|
+
return progress;
|
|
1108
|
+
};
|
|
1109
|
+
if (state.sweepAt) for (let i = 1; i <= 11; i++) setTimeout(() => state.sweepAt && state.tui?.requestRender?.(), i * 75).unref?.();
|
|
920
1110
|
ctx.ui.setHeader((tui, theme) => {
|
|
921
1111
|
state.tui = tui;
|
|
922
1112
|
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")}` }) : []), []),
|
|
1113
|
+
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
1114
|
invalidate() {},
|
|
925
1115
|
};
|
|
926
1116
|
});
|
|
@@ -931,10 +1121,17 @@ export function install(pink, ctx, { CustomEditor, SessionManager, version = "",
|
|
|
931
1121
|
state.tui = tui;
|
|
932
1122
|
state.editor = this;
|
|
933
1123
|
this.pinkKeys = keybindings;
|
|
1124
|
+
if (Array.isArray(this.history) && !this.history.length) this.history.push(...loadHistory());
|
|
1125
|
+
}
|
|
1126
|
+
|
|
1127
|
+
addToHistory(text) {
|
|
1128
|
+
super.addToHistory?.(text);
|
|
1129
|
+
if (Array.isArray(this.history)) saveHistory(this.history);
|
|
934
1130
|
}
|
|
935
1131
|
|
|
936
1132
|
// ctrl+p abre a paleta e tab com a caixa vazia troca o agente (OpenCode); o resto segue para o editor do Pink
|
|
937
1133
|
handleInput(data) {
|
|
1134
|
+
state.sweepAt = 0; // qualquer tecla pula a varredura do logo
|
|
938
1135
|
if (matchesKey?.(data, "ctrl+p") && onPalette) return void onPalette();
|
|
939
1136
|
if (matchesKey?.(data, "tab") && onAgent && !String(this.getText?.() ?? "").trim()) return void onAgent();
|
|
940
1137
|
// 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 +1196,9 @@ export function install(pink, ctx, { CustomEditor, SessionManager, version = "",
|
|
|
999
1196
|
const mic = globalThis.__pinkMicrofone;
|
|
1000
1197
|
const bar = framed() && mic ? micBar(theme, mic.view()) : undefined;
|
|
1001
1198
|
const working = globalThis.__pinkAgentBusy === true || (typeof ctx.isIdle === "function" && !ctx.isIdle());
|
|
1002
|
-
|
|
1199
|
+
// tela inicial: a linha de atalhos embaixo já tem as dicas; na caixa ficam só o modelo e o microfone (owner 2026-11-28)
|
|
1200
|
+
const box = inputBox({ theme, content, width: outer, label, inline, mic: bar?.text, ...(working ? { hints: WORK_HINTS } : state.home ? { hints: "" } : {}),
|
|
1201
|
+
...(working && !still() ? { barRgb: breathe() } : {}) }); // a barra respira só com o agente trabalhando
|
|
1003
1202
|
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
1203
|
const lines = box.map((line) => " ".repeat(margin) + line);
|
|
1005
1204
|
if (!state.home) return lines;
|
|
@@ -1107,7 +1306,7 @@ export function install(pink, ctx, { CustomEditor, SessionManager, version = "",
|
|
|
1107
1306
|
const columns = (width) => frameColumns(width, { home: state.home, on: globalThis.__pinkSidebarOn ?? true, sessions: process.env.PINK_MUX_CHILD !== "1" });
|
|
1108
1307
|
const bars = () => {
|
|
1109
1308
|
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 };
|
|
1309
|
+
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
1310
|
};
|
|
1112
1311
|
globalThis.__pinkFrame = {
|
|
1113
1312
|
// clique na coluna SESSÕES: linha 0 título, 1 em branco, depois as sessões e "+ Nova sessão"
|
|
@@ -1377,6 +1576,30 @@ export function subagentLaunch(args, theme, pad, width) {
|
|
|
1377
1576
|
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
1577
|
}
|
|
1379
1578
|
|
|
1579
|
+
// o resultado fica preso ao comando com ⎿ (owner 2026-11-28): as últimas linhas; o resto vira "… N linhas ocultas (ctrl+o)"
|
|
1580
|
+
export const TAIL_LINES = 3;
|
|
1581
|
+
export function outputTail(text, max = TAIL_LINES) {
|
|
1582
|
+
const all = String(text ?? "").split("\n").map((row) => cleanLine(row)).filter(Boolean);
|
|
1583
|
+
return { lines: all.slice(-max), hidden: Math.max(0, all.length - max) };
|
|
1584
|
+
}
|
|
1585
|
+
export function tailRows(theme, tail, { width, pad = 0, error = false, hint = " (ctrl+o)" }) {
|
|
1586
|
+
if (!tail?.lines?.length) return [];
|
|
1587
|
+
const margin = " ".repeat(pad + 2);
|
|
1588
|
+
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))];
|
|
1589
|
+
return rows.map((row, i) => fit(`${margin}${i ? " " : theme.fg("dim", "⎿ ")}${row}`, width));
|
|
1590
|
+
}
|
|
1591
|
+
|
|
1592
|
+
// pedido de permissão com moldura (só ele: a conversa segue sem caixas); amarelo é "esperando você"
|
|
1593
|
+
export function framedAsk(title, body, width = Math.min(90, (process.stdout.columns || 80) - 6)) {
|
|
1594
|
+
const inner = Math.max(20, width - 4);
|
|
1595
|
+
const wrap = (text) => String(text).split("\n").flatMap((row) => row.replace(/\s+$/, "").match(new RegExp(`.{1,${inner}}`, "g")) ?? [""]);
|
|
1596
|
+
const edge = (text) => paint(250, 204, 21, text);
|
|
1597
|
+
const head = `─ ${String(title).slice(0, inner - 2)} `;
|
|
1598
|
+
return [edge(`╭${head}${"─".repeat(Math.max(0, inner + 2 - head.length))}╮`),
|
|
1599
|
+
...wrap(body).map((row) => `${edge("│")} ${row}${" ".repeat(Math.max(0, inner - [...row].length))} ${edge("│")}`),
|
|
1600
|
+
edge(`╰${"─".repeat(inner + 2)}╯`)].join("\n");
|
|
1601
|
+
}
|
|
1602
|
+
|
|
1380
1603
|
export function compactToolRenderer(toolName, next) {
|
|
1381
1604
|
const base = next?.();
|
|
1382
1605
|
const empty = { render: () => [], invalidate() {} };
|
|
@@ -1416,12 +1639,21 @@ export function compactToolRenderer(toolName, next) {
|
|
|
1416
1639
|
const summary = line(theme, context.outputPad, toolSummary(toolName, context.args ?? {}, result), `${time}${context.isError ? theme.fg("error", t(" · erro", " · error", " · error")) : ""}`);
|
|
1417
1640
|
// edit e write: o diff fica aberto sob a linha (como no Claude Code); o write mostra as primeiras 40 linhas
|
|
1418
1641
|
const diff = context.isError ? "" : toolName === "edit" ? result?.details?.diff : toolName === "write" ? writeDiff(context.args?.content) : "";
|
|
1419
|
-
if (!diff)
|
|
1642
|
+
if (!diff) {
|
|
1643
|
+
// comando e ferramenta com erro mostram o fim da saída; em grupo segue uma linha só
|
|
1644
|
+
const shell = toolName === "bash" || toolName === "powershell";
|
|
1645
|
+
const text = shell || context.isError ? (result?.content ?? []).filter((part) => part?.type === "text").map((part) => part.text).join("\n") : "";
|
|
1646
|
+
const tail = outputTail(text);
|
|
1647
|
+
return grouped(theme, context.outputPad, context.toolCallId, !tail.lines.length ? summary : {
|
|
1648
|
+
render: (width) => [...summary.render(width), ...tailRows(theme, tail, { width, pad: context.outputPad, error: context.isError })],
|
|
1649
|
+
invalidate() {},
|
|
1650
|
+
});
|
|
1651
|
+
}
|
|
1420
1652
|
const cache = new Map();
|
|
1421
1653
|
const pad2 = context.outputPad + 2;
|
|
1422
1654
|
return {
|
|
1423
1655
|
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)]);
|
|
1656
|
+
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
1657
|
return cache.get(width);
|
|
1426
1658
|
},
|
|
1427
1659
|
invalidate: () => cache.clear(),
|
|
@@ -1693,7 +1925,10 @@ function registerOpenCodeFunctions(pink) {
|
|
|
1693
1925
|
PINK.runTimer.unref?.();
|
|
1694
1926
|
// 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
1927
|
// fábrica, não [""]: a lista vira Text(""), que não desenha nada, e o "Trabalhando" ficava colado (owner 2026-11-25)
|
|
1696
|
-
|
|
1928
|
+
// as etapas (interpretar, mapear, investigar...) vão aqui, embaixo do "Trabalhando"; o spinner do motor já redesenha a tela
|
|
1929
|
+
PINK.stages = [{ key: "interpret", count: 1 }];
|
|
1930
|
+
clearDone();
|
|
1931
|
+
ctx.ui.setWidget?.(ABOVE_BOX, (_tui, theme) => ({ render: (width) => [...stageLines(theme, PINK.stages ?? [], { width }), ""], invalidate() {} }), { placement: "aboveEditor" });
|
|
1697
1932
|
ctx.ui.setWidget?.(BELOW_BOX, (_tui, theme) => ({
|
|
1698
1933
|
render: (width) => belowBox(theme, width, { agents: [...runningSubagents(PINK.subagents), ...dagAgentsCached(ctx.cwd)], side: globalThis.__pinkRightOn === true }),
|
|
1699
1934
|
invalidate() {},
|
|
@@ -1703,8 +1938,11 @@ function registerOpenCodeFunctions(pink) {
|
|
|
1703
1938
|
clearInterval(PINK.runTimer);
|
|
1704
1939
|
PINK.subagents.clear(); // ferramenta bloqueada ou interrompida não manda tool_result
|
|
1705
1940
|
ctx.ui.setWorkingMessage?.();
|
|
1706
|
-
ctx.ui.setWidget?.(ABOVE_BOX, undefined);
|
|
1707
1941
|
ctx.ui.setWidget?.(BELOW_BOX, undefined);
|
|
1942
|
+
let summary = "";
|
|
1943
|
+
try { summary = PINK.run ? runLabel(PINK.run.summary()) : ""; } catch {}
|
|
1944
|
+
if (PINK.stages?.length) showDone(ctx.ui, PINK.stages, summary);
|
|
1945
|
+
else clearDone(ctx.ui);
|
|
1708
1946
|
if (PINK.run?.last !== undefined) PINK.runOf.set(PINK.run.last, PINK.run.summary());
|
|
1709
1947
|
[PINK.lastRun, PINK.lastRunEnd, PINK.run, PINK.runShow] = [PINK.run, Date.now(), undefined, undefined];
|
|
1710
1948
|
});
|
|
@@ -1732,6 +1970,7 @@ function registerOpenCodeFunctions(pink) {
|
|
|
1732
1970
|
PINK.runShow?.();
|
|
1733
1971
|
}
|
|
1734
1972
|
const kind = event?.assistantMessageEvent?.type;
|
|
1973
|
+
if (kind === "text_delta" && PINK.stages && PINK.stages.at(-1)?.key !== "answer") PINK.stages = pushStage(PINK.stages, { key: "answer" });
|
|
1735
1974
|
if (kind !== "thinking_start" && kind !== "thinking_end") return;
|
|
1736
1975
|
const key = event.message?.timestamp;
|
|
1737
1976
|
const runs = PINK.thinking.get(key) ?? [];
|
|
@@ -1752,6 +1991,7 @@ function registerOpenCodeFunctions(pink) {
|
|
|
1752
1991
|
});
|
|
1753
1992
|
pink.on("tool_result", async (event) => {
|
|
1754
1993
|
trackSubagent(PINK.subagents, event);
|
|
1994
|
+
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
1995
|
// Git Bash, docker e cia. mexem no modo do console do Windows: o teclado parava de chegar ao Pink ("trava")
|
|
1756
1996
|
if (process.platform === "win32" && (event?.toolName === "bash" || event?.toolName === "powershell")) {
|
|
1757
1997
|
try {
|
|
@@ -1761,6 +2001,7 @@ function registerOpenCodeFunctions(pink) {
|
|
|
1761
2001
|
});
|
|
1762
2002
|
pink.on("tool_call", async (event, ctx) => {
|
|
1763
2003
|
trackSubagent(PINK.subagents, event);
|
|
2004
|
+
if (PINK.stages) PINK.stages = pushStage(PINK.stages, stageOf(event?.toolName, event?.input ?? {}));
|
|
1764
2005
|
const target = event.toolName === "write" ? event.input?.path : undefined;
|
|
1765
2006
|
if (typeof target === "string" && target) {
|
|
1766
2007
|
try {
|
|
@@ -1772,7 +2013,7 @@ function registerOpenCodeFunctions(pink) {
|
|
|
1772
2013
|
if (PINK.agent !== "plan") return;
|
|
1773
2014
|
const decision = planDecision(event.toolName, pink.getAllTools?.().find((tool) => tool.name === event.toolName)?.annotations);
|
|
1774
2015
|
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;
|
|
2016
|
+
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
2017
|
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
2018
|
});
|
|
1778
2019
|
// 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.
|
|
3
|
+
"version": "1.0.33",
|
|
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": {
|