@thothdev/pink 1.0.10 → 1.0.12

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.
@@ -131,6 +131,45 @@ function finalText(result: any, text: string) {
131
131
  if (text && lastText !== text) push(result, [{ type: "text", text }], "stop");
132
132
  }
133
133
 
134
+ // ---------- subagentes de todos os agentes (owner 2026-11-25: "tem que funcionar pra todos os subagents") ----------
135
+ // a chamada da ferramenta de subagente abre a linha e o resultado dela fecha: result.subagents[id] = { agent, task, ... }
136
+ export const SUBAGENT_TOOL = /^(task|agent|subagent|delegate|dispatch_agent|spawn_?agent)$/i;
137
+ export function subagentStart(result: any, id: string, agent: unknown, task: unknown): boolean {
138
+ if (!id) return false;
139
+ const known = result.subagents?.[id];
140
+ if (known) {
141
+ // o ACP manda a descrição só na atualização: completa o que veio vazio
142
+ const text = String(task ?? "").replace(/\s+/g, " ").trim().slice(0, 200);
143
+ const fill = (!known.task && text) || (known.agent === "subagente" && agent && agent !== "subagente");
144
+ if (!known.task && text) known.task = text;
145
+ if (known.agent === "subagente" && agent) known.agent = String(agent);
146
+ return Boolean(fill);
147
+ }
148
+ result.subagents ??= {};
149
+ result.subagents[id] = { agent: String(agent || "subagente"), task: String(task ?? "").replace(/\s+/g, " ").trim().slice(0, 200), started: Date.now(), state: "running" };
150
+ return true;
151
+ }
152
+ export function subagentEnd(result: any, id: string, failed = false): boolean {
153
+ const item = result.subagents?.[id];
154
+ if (!item || item.end) return false;
155
+ item.end = Date.now();
156
+ item.state = failed ? "failed" : "done";
157
+ return true;
158
+ }
159
+ // Codex (colaboração): spawnAgent abre um subagente por thread; agentsStates e closeAgent dizem quando acabou.
160
+ // shortcut: campos do app-server do Codex lidos pela documentação do protocolo, sem um Codex com colaboração para testar
161
+ function codexCollab(item: any, result: any): boolean {
162
+ let changed = false;
163
+ if (/spawn/i.test(String(item.tool ?? ""))) for (const thread of item.receiverThreadIds ?? []) changed = subagentStart(result, String(thread), item.agentType ?? item.model ?? "codex", item.prompt) || changed;
164
+ for (const [thread, value] of Object.entries(item.agentsStates ?? {})) {
165
+ const status = String((value as any)?.status ?? value ?? "");
166
+ if (/err|fail/i.test(status)) changed = subagentEnd(result, thread, true) || changed;
167
+ else if (/complet|done|shutdown|closed|finished/i.test(status)) changed = subagentEnd(result, thread) || changed;
168
+ }
169
+ if (/close/i.test(String(item.tool ?? ""))) for (const thread of item.receiverThreadIds ?? []) changed = subagentEnd(result, String(thread)) || changed;
170
+ return changed;
171
+ }
172
+
134
173
  // ---------- Claude Code: stream-json ----------
135
174
  export function applyClaudeEvent(event: any, result: any, emit: () => void): void {
136
175
  if (event?.type === "system" && event.subtype === "init") {
@@ -147,11 +186,19 @@ export function applyClaudeEvent(event: any, result: any, emit: () => void): voi
147
186
  : undefined,
148
187
  )
149
188
  .filter(Boolean);
189
+ for (const part of event.message.content) if (part?.type === "tool_use" && SUBAGENT_TOOL.test(String(part.name ?? ""))) subagentStart(result, String(part.id ?? ""), part.input?.subagent_type ?? "general-purpose", part.input?.description ?? part.input?.prompt);
150
190
  if (!content.length) return;
151
191
  push(result, content);
152
192
  emit();
153
193
  return;
154
194
  }
195
+ // o resultado da ferramenta volta numa mensagem "user": fecha o subagente daquela chamada
196
+ if (event?.type === "user" && Array.isArray(event.message?.content)) {
197
+ let changed = false;
198
+ for (const part of event.message.content) if (part?.type === "tool_result") changed = subagentEnd(result, String(part.tool_use_id ?? ""), part.is_error === true) || changed;
199
+ if (changed) emit();
200
+ return;
201
+ }
155
202
  if (event?.type === "result") {
156
203
  const usage = event.usage ?? {};
157
204
  result.usage.input += (usage.input_tokens || 0) + (usage.cache_creation_input_tokens || 0);
@@ -178,7 +225,9 @@ export function applyCodexItem(item: any, result: any, emit: () => void): void {
178
225
  else if (item.type === "fileChange") push(result, (item.changes ?? []).map((change: any) => tool(change?.kind?.type === "add" || change?.kind === "add" ? "write" : "edit", { path: String(change?.path ?? "") }, item.id)));
179
226
  else if (item.type === "mcpToolCall") push(result, [tool(`mcp__${item.server}__${item.tool}`, item.arguments && typeof item.arguments === "object" ? item.arguments : {}, item.id)]);
180
227
  else if (item.type === "webSearch") push(result, [tool("web_search", { query: String(item.query ?? "") }, item.id)]);
181
- else return;
228
+ else if (item.type === "collabAgentToolCall") {
229
+ if (!codexCollab(item, result)) return;
230
+ } else return;
182
231
  emit();
183
232
  }
184
233
 
@@ -206,6 +255,16 @@ function acpArgs(update: any, before: Record<string, unknown> = {}): Record<stri
206
255
  if (typeof input.code === "string") args.code = input.code; // opencode chama MCP por código: tools.pink.pink_tela({...})
207
256
  return args;
208
257
  }
258
+ // subagente no ACP: ferramenta "task"/"agent"... ou entrada com subagent_type; status completed/failed fecha a linha
259
+ function acpSubagent(update: any, result: any): boolean {
260
+ const id = String(update.toolCallId ?? "");
261
+ const input = update.rawInput && typeof update.rawInput === "object" ? update.rawInput : {};
262
+ let changed = false;
263
+ if (input.subagent_type || input.agent_type || SUBAGENT_TOOL.test(String(update.title ?? "")) || SUBAGENT_TOOL.test(String(input.tool ?? "")))
264
+ changed = subagentStart(result, id, input.subagent_type ?? input.agent_type ?? input.agent ?? "subagente", input.description ?? input.prompt ?? (SUBAGENT_TOOL.test(String(update.title ?? "")) ? "" : update.title));
265
+ if (update.status === "completed" || update.status === "failed") changed = subagentEnd(result, id, update.status === "failed") || changed;
266
+ return changed;
267
+ }
209
268
  const flushThinking = (result: any, state: any) => {
210
269
  if (state.thinking) push(result, [{ type: "thinking", thinking: state.thinking, ms: Date.now() - state.thoughtAt }]);
211
270
  state.thinking = "";
@@ -228,11 +287,13 @@ export function applyAcpUpdate(update: any, result: any, state: { text: string;
228
287
  if (state.text) push(result, [{ type: "text", text: state.text }]), (state.text = "");
229
288
  const name = ACP_TOOLS[update.kind] ?? (typeof update.kind === "string" && update.kind !== "other" ? update.kind : "tool");
230
289
  push(result, [tool(name, acpArgs(update), String(update.toolCallId ?? ""))]);
290
+ acpSubagent(update, result);
231
291
  emit();
232
292
  return;
233
293
  }
234
294
  // o opencode manda o comando e o arquivo só na atualização (o tool_call chega com título "shell" e entrada vazia)
235
295
  if (update.sessionUpdate === "tool_call_update" && update.toolCallId) {
296
+ if (acpSubagent(update, result)) emit();
236
297
  for (const message of result.messages) {
237
298
  const part = message.content?.find((item: any) => item.type === "toolCall" && item.id === String(update.toolCallId));
238
299
  if (!part) continue;
@@ -532,6 +593,7 @@ async function runCodex(child: any, task: string, cwd: string, result: any, emit
532
593
  "codex",
533
594
  (method, params) => {
534
595
  if (method === "item/completed") applyCodexItem(params?.item, result, emit);
596
+ else if (method === "item/started" && params?.item?.type === "collabAgentToolCall") applyCodexItem(params.item, result, emit); // o subagente aparece ao nascer
535
597
  else if (method === "thread/tokenUsage/updated") codexUsage(params?.tokenUsage, result);
536
598
  else if (method === "error" && params?.error?.message) result.errorMessage = String(params.error.message);
537
599
  else if (method === "turn/completed") {
@@ -583,6 +645,24 @@ async function runCodex(child: any, task: string, cwd: string, result: any, emit
583
645
  // a ligação com um agente ACP: o processo, a sessão aberta e a mensagem em andamento (turn), para servir várias mensagens
584
646
  type AcpTurn = { result: any; state: { text: string; loading: boolean }; emit: () => void; ask: () => Ask | undefined };
585
647
  type AcpConn = { child: any; client: ReturnType<typeof rpc>; exited: Promise<number>; turn?: AcpTurn; sessionId?: string; model?: string; setup?: Promise<string | undefined>; fresh?: boolean; loading?: boolean };
648
+ // o que o agente quer fazer, em palavras: o título do ACP sozinho às vezes é só "bash" ou "edit" (owner 2026-11-25:
649
+ // "permitindo no escuro"). Junta o tipo, o comando ou os arquivos e diz que o sim vale só para esta vez.
650
+ const PERMISSION_KINDS: Record<string, string> = { read: "Ler arquivo", edit: "Editar arquivo", delete: "Apagar arquivo", move: "Mover arquivo", search: "Buscar nos arquivos", execute: "Rodar um comando", fetch: "Acessar a internet", think: "Pensar", other: "Outra ação" };
651
+ export function permissionText(call: any): string {
652
+ const input = call?.rawInput && typeof call.rawInput === "object" ? call.rawInput : {};
653
+ const title = String(call?.title ?? "").trim();
654
+ const kind = PERMISSION_KINDS[String(call?.kind ?? "")];
655
+ const command = [input.command, input.cmd].find((v) => typeof v === "string" && v.trim()) ?? (Array.isArray(input.command) ? input.command.join(" ") : "");
656
+ const files = [...new Set([...(Array.isArray(call?.locations) ? call.locations.map((l: any) => l?.path) : []), input.filePath, input.file_path, input.path, input.url].filter((v) => typeof v === "string" && v.trim()))];
657
+ const lines = [kind && kind.toLowerCase() !== title.toLowerCase() ? `${kind}: ${title || "?"}` : title || kind || "Executar uma ação."];
658
+ if (command && !title.includes(command)) lines.push(`Comando: ${command}`);
659
+ for (const file of files.slice(0, 5)) if (!title.includes(file)) lines.push(`Arquivo: ${file}`);
660
+ if (typeof input.description === "string" && input.description.trim()) lines.push(`Motivo: ${input.description.trim()}`);
661
+ if (!title && !kind && !command && !files.length) lines.push("O agente não disse mais nada sobre esta ação.");
662
+ lines.push("Sim vale só para esta vez.");
663
+ return lines.join("\n");
664
+ }
665
+
586
666
  function acpOpen(child: any, name: string, exited: Promise<number>): AcpConn {
587
667
  const conn = { child, exited } as AcpConn;
588
668
  conn.client = rpc(
@@ -598,7 +678,7 @@ function acpOpen(child: any, name: string, exited: Promise<number>): AcpConn {
598
678
  const allow = options.find((option) => option?.kind === "allow_once") ?? options.find((option) => String(option?.kind).startsWith("allow"));
599
679
  const reject = options.find((option) => option?.kind === "reject_once") ?? options.find((option) => String(option?.kind).startsWith("reject"));
600
680
  const confirm = conn.turn?.ask();
601
- const ok = Boolean(allow && confirm && (await confirm(`O ${name} pede permissão`, String(params?.toolCall?.title ?? "Executar uma ação."))));
681
+ const ok = Boolean(allow && confirm && (await confirm(`O ${name} pede permissão`, permissionText(params?.toolCall))));
602
682
  if (ok) return { outcome: { outcome: "selected", optionId: allow.optionId } };
603
683
  return reject ? { outcome: { outcome: "selected", optionId: reject.optionId } } : { outcome: { outcome: "cancelled" } };
604
684
  },
@@ -53,6 +53,23 @@ export function t(pt: string, es: string, en: string): string {
53
53
  return which === "pt" ? pt : which === "es" ? es : en;
54
54
  }
55
55
 
56
+ // Opções de um comando (owner 2026-11-25): as mesmas no autocomplete (/cmd + Tab ou espaço) e no menu do Enter sem nada.
57
+ // Aqui porque toda extensão já importa este módulo; a primeira opção é o padrão quando não há tela (rpc, print).
58
+ export type Choice = { value: string; label?: string; description?: string };
59
+ export const completeFrom = (choices: () => Choice[]) => (prefix: string) => {
60
+ const typed = String(prefix ?? "").trimStart().toLowerCase();
61
+ const hits = choices().filter((choice) => choice.value.startsWith(typed));
62
+ return hits.length ? hits.map((choice) => ({ label: choice.value, ...choice })) : null;
63
+ };
64
+ export async function choose(ctx: any, title: string, choices: Choice[]): Promise<string | undefined> {
65
+ if (!choices.length) return undefined;
66
+ if (!ctx?.hasUI || typeof ctx.ui?.select !== "function") return choices[0].value;
67
+ const labels = choices.map((choice) => (choice.description ? `${choice.label ?? choice.value} · ${choice.description}` : (choice.label ?? choice.value)));
68
+ const picked = await ctx.ui.select(title, labels);
69
+ const at = picked === undefined ? -1 : labels.indexOf(picked);
70
+ return at < 0 ? undefined : choices[at].value;
71
+ }
72
+
56
73
  // para os patches do motor (rebrand.json), que não importam módulos: globalThis.__pinkT(pt, es, en)
57
74
  (globalThis as any).__pinkT = t;
58
75
  (globalThis as any).__pinkLang = lang;
@@ -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, warmKept } from "../examples/extensions/subagent/external.ts";
14
- import { bulleted, fit, runLabel, shortModel, streamedTokens, thinkingLabel, toolSummary, userLines, workingLabel } from "./pink-ui.ts";
14
+ import { bulleted, elapsedLabel, fit, runLabel, shortModel, streamedTokens, thinkingLabel, toolSummary, userLines, workingLabel } from "./pink-ui.ts";
15
15
 
16
16
  // o Pink junto (card 1dfwh7kgfjx): MCPs do mcp.json, AGENTS.md e skills do Pink, mais o próprio Pink como MCP
17
17
  const readJson = (file: string) => {
@@ -84,7 +84,77 @@ export function gatherExtras(pink: any, dir = process.env.PINK_CODING_AGENT_DIR
84
84
  }
85
85
 
86
86
  const STATUS = "pink-agente";
87
+ // subagentes do opencode (owner 2026-11-25: "ta usando subagente, mas eu não vejo"): pelo ACP só chega a chamada da
88
+ // ferramenta; cada subagente é uma sessão filha no banco do opencode, com a última mensagem dizendo se terminou
89
+ export function opencodeDb(env: NodeJS.ProcessEnv = process.env, home = os.homedir()) {
90
+ return path.join(env.XDG_DATA_HOME || path.join(home, ".local", "share"), "opencode", "opencode.db");
91
+ }
92
+ const tree = (table: string) => `WITH RECURSIVE tree(id, depth) AS (SELECT id, 1 FROM ${table} WHERE parent_id = ? UNION ALL SELECT s.id, depth + 1 FROM ${table} s JOIN tree ON s.parent_id = tree.id WHERE depth < 3)`;
93
+ // opencode 2.x: session_v2 diz o estado (ocupado, ocioso com o resultado, suspenso)
94
+ const CHILDREN_SQL = `${tree("session_v2")}
95
+ SELECT s.title, s.agent, s.time_created AS created, s.time_updated AS updated, s.time_busy AS busy, s.time_idle AS idle, s.idle_outcome AS outcome, s.time_suspended AS suspended
96
+ FROM session_v2 s JOIN tree ON s.id = tree.id WHERE s.time_updated > ? ORDER BY s.time_created`;
97
+ // opencode 1.x (até 14/10): a última mensagem diz se terminou
98
+ const LEGACY_SQL = `${tree("session")}
99
+ SELECT s.title, s.agent, s.time_created AS created, s.time_updated AS updated, (SELECT data FROM message m WHERE m.session_id = s.id ORDER BY m.time_created DESC LIMIT 1) AS last
100
+ FROM session s JOIN tree ON s.id = tree.id WHERE s.time_updated > ? ORDER BY s.time_created`;
101
+ export const CHILD_DONE_SHOWN_MS = 15000;
102
+ function childState(row: any): { state: "running" | "paused" | "done" | "failed" | "stopped"; end?: number } {
103
+ if (row.last === undefined) {
104
+ const busy = Number(row.busy) || 0;
105
+ const idle = Number(row.idle) || 0;
106
+ if (idle && idle >= busy) return { state: row.outcome === "failed" ? "failed" : row.outcome === "interrupted" ? "stopped" : "done", end: idle };
107
+ if (row.suspended && Number(row.suspended) >= busy) return { state: "paused" };
108
+ return { state: "running" };
109
+ }
110
+ let last: any = {};
111
+ try {
112
+ last = row.last ? JSON.parse(row.last) : {};
113
+ } catch {}
114
+ if (last.error) return { state: "failed", end: Number(row.updated) };
115
+ const done = last.role === "assistant" && Boolean(last.time?.completed) && Boolean(last.finish) && last.finish !== "tool-calls";
116
+ return done ? { state: "done", end: Number(row.updated) } : { state: "running" };
117
+ }
118
+ const CHILD_MARK: Record<string, string | undefined> = { running: undefined, paused: "‖", done: "✓", failed: "✗", stopped: "−" };
119
+ export function childAgents(rows: any[], now: number) {
120
+ const out: any[] = [];
121
+ for (const row of rows ?? []) {
122
+ const { state, end } = childState(row);
123
+ if (end && now - end > CHILD_DONE_SHOWN_MS) continue; // terminou há tempo: sai da lista
124
+ if (!end && now - Number(row.updated) > 10 * 60000) continue; // parado há 10 min: o processo morreu
125
+ const title = String(row.title ?? "");
126
+ const named = title.match(/^(.*?)\s*\(@([\w.-]+) subagent\)\s*$/);
127
+ out.push({ agent: named?.[2] ?? (row.agent || "subagente"), task: (named?.[1] ?? title).trim(), started: Number(row.created), mark: CHILD_MARK[state], clock: end ? `${Math.round((end - Number(row.created)) / 1000)}s` : state === "paused" ? t("pausado", "pausado", "paused") : undefined, running: !end });
128
+ }
129
+ return out;
130
+ }
131
+ export function readChildren(file: string, rootId: string, now = Date.now(), open = (f: string) => new (process.getBuiltinModule?.("node:sqlite") as any).DatabaseSync(f, { readOnly: true })) {
132
+ if (!rootId || !fs.existsSync(file)) return [];
133
+ let db: any;
134
+ try {
135
+ db = open(file);
136
+ const since = now - 10 * 60000;
137
+ const has = (table: string) => Boolean(db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(table));
138
+ const rows = [...(has("session_v2") ? db.prepare(CHILDREN_SQL).all(rootId, since) : []), ...(has("session") ? db.prepare(LEGACY_SQL).all(rootId, since) : [])];
139
+ return childAgents(rows, now);
140
+ } catch {
141
+ return []; // banco trancado, versão sem a tabela ou Node sem node:sqlite: só não mostra
142
+ } finally {
143
+ try {
144
+ db?.close?.();
145
+ } catch {}
146
+ }
147
+ }
148
+
149
+ // os subagentes que o próprio fluxo do agente contou (Claude, Codex e ACP: pink-external-agents marca início e fim)
150
+ export function liveAgents(result: any, now: number) {
151
+ return Object.values(result?.subagents ?? {})
152
+ .filter((item: any) => !item.end || now - item.end <= CHILD_DONE_SHOWN_MS)
153
+ .map((item: any) => ({ agent: item.agent, task: item.task, started: item.started, mark: item.state === "failed" ? "✗" : item.end ? "✓" : undefined, clock: item.end ? `${Math.round((item.end - item.started) / 1000)}s` : undefined, running: !item.end }));
154
+ }
155
+
87
156
  const WIDGET = "pink-agente-trabalhando";
157
+ const CHILDREN = "pink-agente-subagentes";
88
158
  const QUEUE = "pink-agente-fila";
89
159
  // o id da conversa do agente fica nos detalhes de cada resposta gravada na sessão do Pink: reabrir a sessão e escolher o
90
160
  // mesmo agente retoma a conversa dele (claude --resume, codex thread/resume, ACP session/load)
@@ -93,6 +163,21 @@ export const lastAgentSession = (entries: any[] | undefined, name: string): stri
93
163
  // fila como no Claude Code (owner 2026-11-24): cada mensagem esperando aparece em cinza acima da caixa, numa linha
94
164
  export const queueLines = (queue: string[], width: number) => queue.map((text) => fit(`> ${String(text).replace(/\s+/g, " ").trim()}`, width));
95
165
  const FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
166
+ const THOUGHT_MAX = 8000; // o pensamento guardado na sessão, por passo
167
+ // como o OpenCode: o trabalho antes da resposta vira uma linha "+ 4 comandos, 4 pensamentos" que abre com clique
168
+ export function workSummary(list: any[]) {
169
+ const tools = list.filter((step) => step.kind === "tool").reduce((sum, step) => sum + (Number(String(step.line).match(/ ×(\d+)$/)?.[1]) || 1), 0);
170
+ const thoughts = list.filter((step) => step.kind === "thinking").length;
171
+ const parts = [];
172
+ if (tools) parts.push(`${tools} ${tools === 1 ? t("comando", "comando", "command") : t("comandos", "comandos", "commands")}`);
173
+ if (thoughts) parts.push(`${thoughts} ${thoughts === 1 ? t("pensamento", "pensamiento", "thought") : t("pensamentos", "pensamientos", "thoughts")}`);
174
+ return parts.join(", ");
175
+ }
176
+ // a resposta final fica de fora do grupo; o que vem antes dela (pensamentos, ferramentas e textos do meio) entra
177
+ export function splitWork(list: any[]) {
178
+ const last = list.map((step) => step.kind).lastIndexOf("text");
179
+ return last < 0 ? { work: list, answer: [] } : { work: list.slice(0, last), answer: list.slice(last) };
180
+ }
96
181
 
97
182
  const fresh = () => ({ messages: [] as any[], stderr: "", exitCode: 0, usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, contextTokens: 0, turns: 0 } });
98
183
 
@@ -129,7 +214,8 @@ export function steps(result: any, cwd = "") {
129
214
  for (const message of result.messages) {
130
215
  for (const part of message.content ?? []) {
131
216
  if (part.type === "text" && part.text?.trim()) out.push({ kind: "text", text: part.text });
132
- else if (part.type === "thinking") out.push({ kind: "thinking", ms: part.ms >= 100 ? part.ms : 0 }); // o pensamento chega de uma vez: tempo quase 0 não diz nada
217
+ // o pensamento chega de uma vez: tempo quase 0 não diz nada; o texto fica para abrir com clique ou ctrl+t (owner 2026-11-25)
218
+ 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) });
133
219
  else if (part.type === "toolCall") out.push({ kind: "tool", line: pinkTool(part, cwd) });
134
220
  }
135
221
  }
@@ -220,7 +306,7 @@ export async function pick(ctx: any, title: string, options: string[], load: ()
220
306
  export default function (pink: any, list: typeof externalAgents = externalAgents, run: typeof runExternal = runExternal, models: typeof listModels = listModels, extras: (tela?: { pipe: string; key: string }) => any = (tela) => gatherExtras(pink, undefined, tela), load: () => Promise<any[]> = loadTui, bridge: typeof telaBridge = telaBridge, warm: typeof warmKept = run === runExternal ? warmKept : () => undefined) {
221
307
  let screen: ReturnType<typeof telaBridge> | undefined; // pink_tela: aberto no primeiro /agente, fechado ao sair do Pink
222
308
  let screenCtx: any; // a janela deste Pink, onde a tela pede confirmação
223
- let active: { agent: any; resume: any; controller?: AbortController; queue?: string[] } | undefined;
309
+ let active: { agent: any; resume: any; controller?: AbortController; queue?: string[]; live?: any } | undefined;
224
310
  let ticker: ReturnType<typeof setInterval> | undefined;
225
311
  let lastUi: any;
226
312
 
@@ -233,40 +319,89 @@ export default function (pink: any, list: typeof externalAgents = externalAgents
233
319
  loader?.stop?.();
234
320
  loader = undefined;
235
321
  lastUi?.setWidget?.(WIDGET, undefined);
322
+ (globalThis as any).__pinkAgentBusy = false; // a caixa volta às dicas de sempre (pink-ui)
236
323
  };
324
+ // 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)
325
+ const around = (lines: string[], width: number, theme: any) => [...queueLines(active?.queue ?? [], width).map((line) => theme.fg("dim", line)), ...lines, ""];
237
326
  const busy = (ui: any, output: () => number) => {
238
327
  idle();
239
328
  lastUi = ui;
240
329
  if (!ui?.setWidget) return;
241
330
  const started = Date.now();
242
331
  const message = () => workingLabel({ ms: Date.now() - started, output: output() });
332
+ (globalThis as any).__pinkAgentBusy = true; // a caixa mostra "esc interromper · ctrl+enter envia agora" (pink-ui)
243
333
  // a área dos widgets já deixa uma linha em branco antes: a linha vazia do topo do Loader sai
244
334
  if (tui?.Loader) {
245
335
  ui.setWidget(WIDGET, (screen: any, theme: any) => {
336
+ screenRef = screen;
337
+ loader?.stop?.(); // a fábrica pode ser chamada de novo: o Loader anterior para de girar
246
338
  loader = new tui.Loader(screen, (s: string) => theme.fg("accent", s), (s: string) => theme.fg("muted", s), message());
247
339
  const own = loader;
248
- return { render: (width: number) => own.render(width).slice(1), invalidate: () => own.invalidate?.() };
340
+ return { render: (width: number) => around(own.render(width).slice(1), width, theme), invalidate: () => own.invalidate?.() };
249
341
  }, { placement: "aboveEditor" });
250
342
  ticker = setInterval(() => loader?.setMessage?.(message()), 1000);
251
343
  } else {
252
344
  let frame = 0;
253
- const draw = () => ui.setWidget(WIDGET, [` ${FRAMES[frame++ % FRAMES.length]} ${message()}`], { placement: "aboveEditor" });
345
+ const draw = () => ui.setWidget(WIDGET, (_screen: any, theme: any) => ({ render: (width: number) => around([` ${FRAMES[frame % FRAMES.length]} ${message()}`], width, theme), invalidate() {} }), { placement: "aboveEditor" });
254
346
  draw();
255
- ticker = setInterval(draw, 120);
347
+ ticker = setInterval(() => (frame++, draw()), 120);
256
348
  }
257
349
  ticker.unref?.();
258
350
  };
259
351
 
260
- const showQueue = (ui: any) => {
261
- const queue = [...(active?.queue ?? [])];
262
- ui?.setWidget?.(QUEUE, queue.length ? (_screen: any, theme: any) => ({ render: (width: number) => queueLines(queue, width).map((line) => theme.fg("dim", line)), invalidate() {} }) : undefined, { placement: "aboveEditor" });
352
+ // subagentes do opencode acima da caixa, a cada 2 s, enquanto a mensagem roda ou algum subagente segue vivo (os de
353
+ // segundo plano continuam depois da resposta, como no Claude Code)
354
+ let childTimer: ReturnType<typeof setInterval> | undefined;
355
+ const stopChildren = (ui?: any) => {
356
+ if (childTimer) clearInterval(childTimer);
357
+ childTimer = undefined;
358
+ (globalThis as any).__pinkAgentChildren = undefined;
359
+ (ui ?? lastUi)?.setWidget?.(CHILDREN, undefined);
360
+ };
361
+ const watchChildren = (ui: any, read = readChildren, dbFile = opencodeDb()) => {
362
+ if (childTimer || !ui?.setWidget) return;
363
+ const tick = () => {
364
+ // opencode: o banco dele mostra também os de segundo plano; os outros (e o opencode sem node:sqlite): o fluxo
365
+ const opencode = /opencode/i.test(String(active?.agent?.external ?? active?.agent?.name ?? ""));
366
+ const fromDb = opencode && active?.resume?.id ? read(dbFile, active.resume.id) : [];
367
+ const items = fromDb.length ? fromDb : liveAgents(active?.live, Date.now());
368
+ (globalThis as any).__pinkAgentChildren = items; // a lateral mostra em SUBAGENTES, abaixo da SESSÃO
369
+ if (!items.length && !active?.controller) return stopChildren(ui);
370
+ const side = Date.now() - Number((globalThis as any).__pinkSideAt ?? 0) < 5000; // lateral desenhada há pouco: está na tela
371
+ ui.setWidget(CHILDREN, items.length && !side ? (_screen: any, theme: any) => ({
372
+ render: (width: number) => items.map((item: any) => {
373
+ const clock = item.clock ?? elapsedLabel(Date.now() - item.started);
374
+ const mark = theme.fg(item.mark === "✗" ? "error" : item.mark === "✓" ? "success" : "accent", item.mark ?? "●");
375
+ return fit(` ${mark} ${theme.fg("text", item.agent)} ${theme.fg("muted", item.task)} ${theme.fg("dim", clock)}`, width);
376
+ }),
377
+ invalidate() {},
378
+ }) : undefined, { placement: "aboveEditor" });
379
+ screenRef?.requestRender?.(); // a lateral relê a lista mesmo com a conversa parada
380
+ };
381
+ tick();
382
+ childTimer = setInterval(tick, 2000);
383
+ childTimer.unref?.();
384
+ };
385
+
386
+ // a fila é desenhada dentro do widget do "Trabalhando" (around): aqui só pede o redesenho
387
+ let screenRef: any;
388
+ const showQueue = (_ui: any) => screenRef?.requestRender?.();
389
+ // ctrl+enter com o agente trabalhando: o texto entra na fila e o agente é interrompido; a fila sai na hora, numa mensagem
390
+ (globalThis as any).__pinkAgentSendNow = (text: string) => {
391
+ if (!active?.controller) return false;
392
+ const value = String(text ?? "").trim();
393
+ if (value) (active.queue ??= []).push(value);
394
+ active.controller.abort();
395
+ return true;
263
396
  };
264
397
  const stop = (ctx?: any) => {
265
- (ctx?.ui ?? lastUi)?.setWidget?.(QUEUE, undefined); // a fila é descartada junto
398
+ (ctx?.ui ?? lastUi)?.setWidget?.(QUEUE, undefined); // fila de versões antigas do widget (a de agora some junto com o agente)
399
+ if (active) active.queue = []; // a fila é descartada junto
266
400
  active?.controller?.abort();
267
401
  closeKept(active?.resume); // fecha o processo do agente que ficou aberto entre as mensagens
268
402
  active = undefined;
269
403
  idle();
404
+ stopChildren(ctx?.ui);
270
405
  (globalThis as any).__pinkExternalAgent = undefined; // o rótulo da caixa volta a "Build · modelo" (pink-ui)
271
406
  ctx?.ui?.setStatus?.(STATUS, undefined);
272
407
  };
@@ -290,23 +425,68 @@ export default function (pink: any, list: typeof externalAgents = externalAgents
290
425
  if (!tui || !coding?.getMarkdownTheme) return undefined;
291
426
  const details = message.details ?? {};
292
427
  const pad = options.outputPad ?? 1;
293
- const box = new tui.Container();
294
428
  const list = compact(Array.isArray(details.steps) ? details.steps : [{ kind: "text", text: textOf(message) }]);
295
- // o Pink já põe uma linha em branco antes de cada mensagem: entre o pedido e a resposta fica só ela, como no Claude Code
296
- for (const [index, step] of list.entries()) {
297
- // ferramentas seguidas ficam juntas (uma busca na tela são dezenas de chamadas: com linha em branco virava uma tela inteira)
298
- if (index && !(step.kind === "tool" && list[index - 1]?.kind === "tool")) box.addChild(new tui.Spacer(1));
299
- if (step.kind === "thinking") box.addChild(new tui.Text(theme.fg("thinkingText", thinkingLabel(step.ms)), pad, 0));
300
- else if (step.kind === "tool") box.addChild(new tui.Text(theme.fg("muted", `→ ${step.line}`), pad, 0));
301
- else box.addChild(bulleted(new tui.Markdown(String(step.text).trim(), pad, 0, coding.getMarkdownTheme())));
302
- }
303
- if (details.error) box.addChild(new tui.Spacer(1)), box.addChild(new tui.Text(theme.fg("error", `⚠ ${details.error}`), pad, 0));
304
- const footer = [bold(theme, theme.fg("accent", details.agent ?? t("agente", "agente", "agent")))];
305
- if (details.model) footer.push(theme.fg("text", shortModel(details.model)));
306
- if (details.ms !== undefined) footer.push(theme.fg("muted", runLabel({ ms: details.ms, output: details.output ?? 0 })));
307
- box.addChild(new tui.Spacer(1));
308
- box.addChild(new tui.Text(footer.join(theme.fg("dim", " · ")), pad, 0));
309
- return box;
429
+ const { work, answer } = splitWork(list);
430
+ const summary = workSummary(work);
431
+ const grouped = work.length >= 2 && Boolean(summary);
432
+ // aberto pelo clique (esta mensagem) ou por ctrl+t (todas: o Pink avisa em __pinkThinkingShown)
433
+ const opened = { work: false, thoughts: new Set<number>() };
434
+ const all = () => (globalThis as any).__pinkThinkingShown === true;
435
+ const MouseRegion = tui.MouseRegion;
436
+ let current: any;
437
+ let drawnWithAll = all();
438
+ const clickable = (child: any, toggle: () => void) =>
439
+ MouseRegion
440
+ ? new MouseRegion(child, (event: any) => {
441
+ if (event?.type !== "click" || event.button !== "left") return undefined;
442
+ toggle();
443
+ current = build();
444
+ return { handled: true };
445
+ })
446
+ : child;
447
+ const thought = (box: any, step: any, index: number) => {
448
+ const open = all() || opened.thoughts.has(index);
449
+ const head = open && step.text ? `− ${thinkingLabel(step.ms).slice(2)}` : thinkingLabel(step.ms);
450
+ box.addChild(clickable(new tui.Text(theme.fg("thinkingText", head), pad, 0), () => (opened.thoughts.has(index) ? opened.thoughts.delete(index) : opened.thoughts.add(index))));
451
+ if (open && step.text) box.addChild(new tui.Text(theme.italic ? theme.italic(theme.fg("thinkingText", step.text)) : theme.fg("thinkingText", step.text), pad + 2, 0));
452
+ };
453
+ const drawSteps = (box: any, steps: any[], offset: number) => {
454
+ for (const [index, step] of steps.entries()) {
455
+ // ferramentas seguidas ficam juntas (uma busca na tela são dezenas de chamadas: com linha em branco virava uma tela inteira)
456
+ if (index && !(step.kind === "tool" && steps[index - 1]?.kind === "tool")) box.addChild(new tui.Spacer(1));
457
+ if (step.kind === "thinking") thought(box, step, offset + index);
458
+ else if (step.kind === "tool") box.addChild(new tui.Text(theme.fg("muted", `→ ${step.line}`), pad, 0));
459
+ else box.addChild(bulleted(new tui.Markdown(String(step.text).trim(), pad, 0, coding.getMarkdownTheme())));
460
+ }
461
+ };
462
+ const build = () => {
463
+ drawnWithAll = all();
464
+ const box = new tui.Container();
465
+ // o Pink já põe uma linha em branco antes de cada mensagem: entre o pedido e a resposta fica só ela, como no Claude Code
466
+ if (grouped) {
467
+ const open = opened.work || all();
468
+ box.addChild(clickable(new tui.Text(theme.fg("muted", `${open ? "−" : "+"} ${summary}`), pad, 0), () => (opened.work = !opened.work)));
469
+ if (open) box.addChild(new tui.Spacer(1)), drawSteps(box, work, 0);
470
+ if (answer.length) box.addChild(new tui.Spacer(1));
471
+ drawSteps(box, answer, work.length);
472
+ } else drawSteps(box, list, 0);
473
+ if (details.error) box.addChild(new tui.Spacer(1)), box.addChild(new tui.Text(theme.fg("error", `⚠ ${details.error}`), pad, 0));
474
+ const footer = [bold(theme, theme.fg("accent", details.agent ?? t("agente", "agente", "agent")))];
475
+ if (details.model) footer.push(theme.fg("text", shortModel(details.model)));
476
+ if (details.ms !== undefined) footer.push(theme.fg("muted", runLabel({ ms: details.ms, output: details.output ?? 0 })));
477
+ box.addChild(new tui.Spacer(1));
478
+ box.addChild(new tui.Text(footer.join(theme.fg("dim", " · ")), pad, 0));
479
+ return box;
480
+ };
481
+ current = build();
482
+ return {
483
+ render: (width: number) => {
484
+ if (all() !== drawnWithAll) current = build(); // ctrl+t abriu ou fechou o pensamento de todas
485
+ return current.render(width);
486
+ },
487
+ invalidate: () => current.invalidate?.(),
488
+ handleMouse: (event: any) => current.handleMouse?.(event),
489
+ };
310
490
  });
311
491
 
312
492
  const send = async (text: string, ctx: any) => {
@@ -317,6 +497,7 @@ export default function (pink: any, list: typeof externalAgents = externalAgents
317
497
  const name = current.agent.name;
318
498
  pink.sendMessage({ customType: "pink-agente-pedido", display: true, content: `› ${name}: ${text}`, details: { agent: name, text } });
319
499
  const result = fresh();
500
+ current.live = result; // os subagentes desta mensagem (liveAgents)
320
501
  const started = Date.now();
321
502
  const lastTool = () => result.messages.at(-1)?.content?.find((part: any) => part.type === "toolCall")?.name;
322
503
  const status = () => {
@@ -325,6 +506,7 @@ export default function (pink: any, list: typeof externalAgents = externalAgents
325
506
  };
326
507
  status();
327
508
  if (ctx.hasUI) busy(ctx.ui, () => outputOf(result));
509
+ if (ctx.hasUI) watchChildren(ctx.ui);
328
510
  (globalThis as any).__pinkExternalAsk = ctx.hasUI ? (title: string, body: string) => ctx.ui.confirm(title, body) : undefined;
329
511
  try {
330
512
  await run(current.agent, text, ctx.cwd, controller.signal, result, status, undefined, undefined, current.resume);
@@ -53,6 +53,23 @@ export function t(pt: string, es: string, en: string): string {
53
53
  return which === "pt" ? pt : which === "es" ? es : en;
54
54
  }
55
55
 
56
+ // Opções de um comando (owner 2026-11-25): as mesmas no autocomplete (/cmd + Tab ou espaço) e no menu do Enter sem nada.
57
+ // Aqui porque toda extensão já importa este módulo; a primeira opção é o padrão quando não há tela (rpc, print).
58
+ export type Choice = { value: string; label?: string; description?: string };
59
+ export const completeFrom = (choices: () => Choice[]) => (prefix: string) => {
60
+ const typed = String(prefix ?? "").trimStart().toLowerCase();
61
+ const hits = choices().filter((choice) => choice.value.startsWith(typed));
62
+ return hits.length ? hits.map((choice) => ({ label: choice.value, ...choice })) : null;
63
+ };
64
+ export async function choose(ctx: any, title: string, choices: Choice[]): Promise<string | undefined> {
65
+ if (!choices.length) return undefined;
66
+ if (!ctx?.hasUI || typeof ctx.ui?.select !== "function") return choices[0].value;
67
+ const labels = choices.map((choice) => (choice.description ? `${choice.label ?? choice.value} · ${choice.description}` : (choice.label ?? choice.value)));
68
+ const picked = await ctx.ui.select(title, labels);
69
+ const at = picked === undefined ? -1 : labels.indexOf(picked);
70
+ return at < 0 ? undefined : choices[at].value;
71
+ }
72
+
56
73
  // para os patches do motor (rebrand.json), que não importam módulos: globalThis.__pinkT(pt, es, en)
57
74
  (globalThis as any).__pinkT = t;
58
75
  (globalThis as any).__pinkLang = lang;
@@ -5,7 +5,12 @@
5
5
  // atualiza, lê, lista e apaga; texto com cara de segredo é recusado. O AGENTS.md é da pessoa e fica de fora.
6
6
  // Pasta não confiável: nem entra no prompt nem grava (Argus A1: repositório estranho induziria o agente a guardar
7
7
  // instruções que voltariam no prompt de sistema de toda sessão). Subagente não lê nem grava.
8
- import { t } from "./pink-i18n.ts";
8
+ import { type Choice, choose, completeFrom, t } from "./pink-i18n.ts";
9
+
10
+ const MEMORY_CHOICES = (): Choice[] => [
11
+ { value: "mostrar", description: t("a pasta e o índice (MEMORY.md)", "la carpeta y el índice (MEMORY.md)", "the folder and the index (MEMORY.md)") },
12
+ { value: "abrir", description: t("abre a pasta da memória", "abre la carpeta de la memoria", "opens the memory folder") },
13
+ ];
9
14
  import { spawn } from "node:child_process";
10
15
  import { createHash } from "node:crypto";
11
16
  import fs from "node:fs";
@@ -214,10 +219,12 @@ export default function (pink: any) {
214
219
  });
215
220
  pink.registerCommand("memoria", {
216
221
  description: t("Memória deste projeto: mostra a pasta e o índice (MEMORY.md); 'abrir' abre a pasta", "Memoria de este proyecto: muestra la carpeta y el índice (MEMORY.md); 'abrir' abre la carpeta", "This project's memory: shows the folder and the index (MEMORY.md); 'open' opens the folder"),
217
- getArgumentCompletions: (prefix: string) => ("abrir".startsWith(prefix) ? [{ value: "abrir", label: "abrir" }] : null),
222
+ getArgumentCompletions: completeFrom(MEMORY_CHOICES),
218
223
  handler: async (args: string, ctx: any) => {
219
224
  const here = ctx?.cwd ?? cwd;
220
- if (["abrir", "open"].includes(args.trim())) {
225
+ let verb: string | undefined = String(args ?? "").trim();
226
+ if (!verb && (verb = await choose(ctx, "/memoria", MEMORY_CHOICES())) === undefined) return;
227
+ if (["abrir", "open"].includes(verb)) {
221
228
  const dir = memoryDir(here);
222
229
  fs.mkdirSync(dir, { recursive: true });
223
230
  const opener = process.platform === "win32" ? "explorer" : process.platform === "darwin" ? "open" : "xdg-open";