@thothdev/pink 1.0.16 → 1.0.27

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.
@@ -163,23 +163,49 @@ function codexCollab(item: any, result: any): boolean {
163
163
  if (/spawn/i.test(String(item.tool ?? ""))) for (const thread of item.receiverThreadIds ?? []) changed = subagentStart(result, String(thread), item.agentType ?? item.model ?? "codex", item.prompt) || changed;
164
164
  for (const [thread, value] of Object.entries(item.agentsStates ?? {})) {
165
165
  const status = String((value as any)?.status ?? value ?? "");
166
- if (/err|fail/i.test(status)) changed = subagentEnd(result, thread, true) || changed;
166
+ if (/err|fail|interrupt|notfound/i.test(status)) changed = subagentEnd(result, thread, true) || changed;
167
167
  else if (/complet|done|shutdown|closed|finished/i.test(status)) changed = subagentEnd(result, thread) || changed;
168
168
  }
169
169
  if (/close/i.test(String(item.tool ?? ""))) for (const thread of item.receiverThreadIds ?? []) changed = subagentEnd(result, String(thread)) || changed;
170
170
  return changed;
171
171
  }
172
172
 
173
+ // pedaço do que está chegando (texto ou pensamento), para a tela ao vivo; some quando o bloco inteiro chega
174
+ const partial = (result: any, kind: "text" | "thinking", delta: unknown) => {
175
+ if (typeof delta !== "string" || !delta) return;
176
+ const before = result.partial?.kind === kind ? result.partial.text : "";
177
+ result.partial = { kind, text: `${before}${delta}`.slice(-2000) };
178
+ };
179
+
173
180
  // ---------- Claude Code: stream-json ----------
174
181
  export function applyClaudeEvent(event: any, result: any, emit: () => void): void {
175
182
  if (event?.type === "system" && event.subtype === "init") {
176
183
  if (typeof event.model === "string") result.model = event.model;
177
184
  return;
178
185
  }
186
+ // --include-partial-messages: o texto e o pensamento enquanto chegam (os dos subagentes ficam de fora)
187
+ if (event?.type === "stream_event") {
188
+ if (event.parent_tool_use_id) return;
189
+ const inner = event.event ?? {};
190
+ if (inner.type === "content_block_start") result.partial = undefined;
191
+ else if (inner.type === "content_block_delta") {
192
+ if (inner.delta?.type === "text_delta") partial(result, "text", inner.delta.text);
193
+ else if (inner.delta?.type === "thinking_delta") partial(result, "thinking", inner.delta.thinking);
194
+ }
195
+ return;
196
+ }
197
+ // subagente em segundo plano do Claude Code: o fim chega neste aviso, não no resultado da ferramenta
198
+ if (event?.type === "system" && event.subtype === "task_notification") {
199
+ if (subagentEnd(result, String(event.tool_use_id ?? ""), event.status !== "completed")) emit();
200
+ return;
201
+ }
179
202
  if (event?.type === "assistant" && Array.isArray(event.message?.content)) {
203
+ result.partial = undefined;
180
204
  const content = event.message.content
181
205
  .map((part: any) =>
182
- part?.type === "text" && typeof part.text === "string"
206
+ part?.type === "thinking" && typeof part.thinking === "string" && part.thinking.trim()
207
+ ? { type: "thinking", thinking: part.thinking, ms: 0 }
208
+ : part?.type === "text" && typeof part.text === "string"
183
209
  ? { type: "text", text: part.text }
184
210
  : part?.type === "tool_use"
185
211
  ? tool(String(part.name ?? "tool"), part.input && typeof part.input === "object" ? part.input : {}, String(part.id ?? ""))
@@ -195,7 +221,11 @@ export function applyClaudeEvent(event: any, result: any, emit: () => void): voi
195
221
  // o resultado da ferramenta volta numa mensagem "user": fecha o subagente daquela chamada
196
222
  if (event?.type === "user" && Array.isArray(event.message?.content)) {
197
223
  let changed = false;
198
- for (const part of event.message.content) if (part?.type === "tool_result") changed = subagentEnd(result, String(part.tool_use_id ?? ""), part.is_error === true) || changed;
224
+ for (const part of event.message.content) {
225
+ // "Async agent launched": só começou em segundo plano, segue rodando
226
+ const text = String((Array.isArray(part?.content) ? part.content[0]?.text : part?.content) ?? "");
227
+ if (part?.type === "tool_result" && !text.startsWith("Async agent launched")) changed = subagentEnd(result, String(part.tool_use_id ?? ""), part.is_error === true) || changed;
228
+ }
199
229
  if (changed) emit();
200
230
  return;
201
231
  }
@@ -220,13 +250,21 @@ export function applyClaudeEvent(event: any, result: any, emit: () => void): voi
220
250
  // ---------- Codex: itens do app-server ----------
221
251
  export function applyCodexItem(item: any, result: any, emit: () => void): void {
222
252
  if (!item || typeof item !== "object") return;
223
- if (item.type === "agentMessage" && typeof item.text === "string" && item.text) push(result, [{ type: "text", text: item.text }]);
253
+ // o comando aparece ao começar (item/started): ao terminar, não entra de novo
254
+ if (item.id && result.messages.some((message: any) => message.content?.some((part: any) => part.type === "toolCall" && part.id === item.id))) return;
255
+ const thought = item.type === "reasoning" ? [...(item.summary ?? []), ...(item.content ?? [])].join("\n").trim() : "";
256
+ if (thought) push(result, [{ type: "thinking", thinking: thought, ms: 0 }]);
257
+ else if (item.type === "agentMessage" && typeof item.text === "string" && item.text) push(result, [{ type: "text", text: item.text }]);
224
258
  else if (item.type === "commandExecution") push(result, [tool("bash", { command: String(item.command ?? "") }, item.id)]);
225
- else if (item.type === "fileChange") push(result, (item.changes ?? []).map((change: any) => tool(change?.kind?.type === "add" || change?.kind === "add" ? "write" : "edit", { path: String(change?.path ?? "") }, item.id)));
259
+ else if (item.type === "fileChange") push(result, (item.changes ?? []).map((change: any) => change?.kind?.type === "add" || change?.kind === "add" ? tool("write", { path: String(change?.path ?? ""), created: true }, item.id) : tool("edit", { path: String(change?.path ?? "") }, item.id)));
226
260
  else if (item.type === "mcpToolCall") push(result, [tool(`mcp__${item.server}__${item.tool}`, item.arguments && typeof item.arguments === "object" ? item.arguments : {}, item.id)]);
227
261
  else if (item.type === "webSearch") push(result, [tool("web_search", { query: String(item.query ?? "") }, item.id)]);
228
262
  else if (item.type === "collabAgentToolCall") {
229
263
  if (!codexCollab(item, result)) return;
264
+ } else if (item.type === "subAgentActivity") {
265
+ const id = String(item.agentThreadId ?? "");
266
+ const name = String(item.agentPath ?? "").split("/").filter(Boolean).at(-1) ?? "codex";
267
+ if (!(item.kind === "completed" || item.kind === "interrupted" ? subagentEnd(result, id, item.kind === "interrupted") : subagentStart(result, id, name, ""))) return;
230
268
  } else return;
231
269
  emit();
232
270
  }
@@ -269,17 +307,20 @@ const flushThinking = (result: any, state: any) => {
269
307
  if (state.thinking) push(result, [{ type: "thinking", thinking: state.thinking, ms: Date.now() - state.thoughtAt }]);
270
308
  state.thinking = "";
271
309
  state.thoughtAt = undefined;
310
+ result.partial = undefined;
272
311
  };
273
312
  export function applyAcpUpdate(update: any, result: any, state: { text: string; thinking?: string; thoughtAt?: number }, emit: () => void): void {
274
313
  if (!update || typeof update !== "object") return;
275
314
  if (update.sessionUpdate === "agent_thought_chunk" && update.content?.type === "text") {
276
315
  state.thoughtAt ??= Date.now();
277
316
  state.thinking = (state.thinking ?? "") + String(update.content.text ?? "");
317
+ result.partial = { kind: "thinking", text: state.thinking.slice(-2000) };
278
318
  return;
279
319
  }
280
320
  if (update.sessionUpdate === "agent_message_chunk" && update.content?.type === "text") {
281
321
  flushThinking(result, state);
282
322
  state.text += String(update.content.text ?? "");
323
+ result.partial = { kind: "text", text: state.text.slice(-2000) };
283
324
  return;
284
325
  }
285
326
  if (update.sessionUpdate === "tool_call") {
@@ -424,13 +465,19 @@ export function acpModels(session: any): ModelChoice[] {
424
465
  // resume: a conversa continua entre chamadas (sessão inteira no agente, card 1dfwh7kgf8k); o id é gravado nele
425
466
  // /agente com ACP (opencode, cline...): o processo fica aberto entre as mensagens (keep), porque subir o agente e abrir a
426
467
  // sessão custa ~10 s e uma mensagem no processo aberto ~3 s; fecha com closeKept (off, troca, cancelar, erro, saída do Pink)
427
- export type Resume = { id?: string; keep?: boolean; live?: AcpConn };
468
+ export type Resume = { id?: string; keep?: boolean; live?: AcpConn; late?: LateTurn };
469
+ // o que o agente manda sozinho, sem turno aberto: um subagente ou comando em segundo plano terminou e ele respondeu
470
+ // (owner 2026-11-28: o Pink descartava e o agente "parava"); quem abriu o agente diz como montar e mostrar
471
+ export type LateTurn = { fresh: () => any; deliver: (result: any) => void; ask?: () => Ask | undefined; quietMs?: number };
472
+ export const LATE_QUIET_MS = 4000; // o ACP não avisa o fim desse turno: silêncio por este tempo fecha a resposta
428
473
  // `force` (Esc): um agente preso (ex.: opencode esperando um subagente que não abre) ignora o fim da entrada, e no Windows
429
474
  // o kill pega só o cmd do npm: o opencode.exe seguia vivo, segurando os pipes, e o Esc não soltava (owner 2026-11-26)
430
475
  export function closeKept(resume?: Resume, force = false, kill: typeof spawn = spawn) {
431
476
  const conn = resume?.live;
432
477
  if (resume) resume.live = undefined;
433
478
  if (!conn) return;
479
+ clearTimeout(conn.lateTimer);
480
+ conn.lateBuffer = undefined;
434
481
  try {
435
482
  conn.child.stdin?.end?.(); // fim da entrada: o agente sai sozinho (o kill do .cmd do npm pega só o shell)
436
483
  if (force && process.platform === "win32" && conn.child.pid) kill("taskkill", ["/PID", String(conn.child.pid), "/T", "/F"], { stdio: "ignore", windowsHide: true }).on?.("error", () => undefined);
@@ -451,7 +498,7 @@ function openKept(agent: ExternalAgent, cwd: string, start: typeof spawn, resume
451
498
  resolve(1);
452
499
  });
453
500
  });
454
- conn = resume.live = acpOpen(child, agent.name, exited);
501
+ conn = resume.live = acpOpen(child, agent.name, exited, resume);
455
502
  const opened = conn;
456
503
  child.stderr?.on?.("data", (data: any) => {
457
504
  const target = opened.turn?.result;
@@ -524,7 +571,9 @@ export async function runExternal(agent: ExternalAgent, task: string, cwd: strin
524
571
  if (agent.extras.mcp.pink) extra.push("--allowedTools", "mcp__pink__pink_tarefa,mcp__pink__pink_tela"); // a tela confirma cada ação no Pink
525
572
  extra.push("--append-system-prompt-file", rulesFile);
526
573
  }
527
- const args = agent.external === "claude" ? [...agent.args, ...(agent.model ? ["--model", agent.model] : []), ...(agent.effort ? ["--effort", agent.effort] : []), ...extra, ...(resume?.id ? ["--resume", resume.id] : [])] : agent.args;
574
+ // "permitir tudo" no Pink: sem isto o claude -p recusa em silêncio a ferramenta que não foi liberada
575
+ if (agent.external === "claude" && (globalThis as any).__pinkPermissionMode === "all") extra.push("--permission-mode", "bypassPermissions");
576
+ const args = agent.external === "claude" ? [...agent.args, "--include-partial-messages", ...(agent.model ? ["--model", agent.model] : []), ...(agent.effort ? ["--effort", agent.effort] : []), ...extra, ...(resume?.id ? ["--resume", resume.id] : [])] : agent.args;
528
577
  const child = spawnAgent(agent, args, cwd, start);
529
578
  if (scratch) {
530
579
  const dir = scratch;
@@ -594,15 +643,23 @@ const failed = (result: any, name: string, message: string) => {
594
643
  async function runCodex(child: any, task: string, cwd: string, result: any, emit: () => void, ask: () => Ask | undefined, exited: Promise<number>, resume?: { id?: string }, model?: string, extras?: Extras, effort?: string): Promise<number> {
595
644
  let done: (code: number) => void = () => {};
596
645
  const finished = new Promise<number>((resolve) => (done = resolve));
646
+ let main: string | undefined; // a conversa pedida; os subagentes do Codex rodam em outras
597
647
  const client = rpc(
598
648
  child,
599
649
  "codex",
600
650
  (method, params) => {
601
- if (method === "item/completed") applyCodexItem(params?.item, result, emit);
602
- else if (method === "item/started" && params?.item?.type === "collabAgentToolCall") applyCodexItem(params.item, result, emit); // o subagente aparece ao nascer
651
+ const mine = !main || !params?.threadId || params.threadId === main; // o que chega dos subagentes não vira "ao vivo"
652
+ if (method === "item/completed") {
653
+ if (mine) result.partial = undefined;
654
+ applyCodexItem(params?.item, result, emit);
655
+ } else if (method === "item/started" && ["collabAgentToolCall", "commandExecution", "mcpToolCall", "webSearch"].includes(params?.item?.type)) applyCodexItem(params.item, result, emit); // o subagente e o comando aparecem ao começar
656
+ else if (method === "item/agentMessage/delta") mine && partial(result, "text", params?.delta);
657
+ else if (method === "item/reasoning/summaryTextDelta" || method === "item/reasoning/textDelta") mine && partial(result, "thinking", params?.delta);
603
658
  else if (method === "thread/tokenUsage/updated") codexUsage(params?.tokenUsage, result);
604
659
  else if (method === "error" && params?.error?.message) result.errorMessage = String(params.error.message);
605
660
  else if (method === "turn/completed") {
661
+ // o fim de um subagente fecha a linha dele, não o pedido
662
+ if (main && params?.threadId && params.threadId !== main) return void (subagentEnd(result, String(params.threadId), params.turn?.status === "failed") && emit());
606
663
  const turn = params?.turn ?? {};
607
664
  if (turn.status === "failed" || turn.status === "interrupted") done(failed(result, "codex", String(turn.error?.message ?? result.errorMessage ?? turn.status)));
608
665
  else {
@@ -643,6 +700,7 @@ async function runCodex(child: any, task: string, cwd: string, result: any, emit
643
700
  if (thread.error) return failed(result, "codex", String(thread.error.message ?? "thread/start falhou"));
644
701
  if (typeof thread.result?.model === "string") result.model = thread.result.model;
645
702
  if (resume && thread.result?.thread?.id) resume.id = thread.result.thread.id;
703
+ main = thread.result?.thread?.id;
646
704
  const turn = await client.request("turn/start", { threadId: thread.result?.thread?.id, input: [{ type: "text", text: task, text_elements: [] }], ...(effort ? { effort } : {}) });
647
705
  if (turn.error) return failed(result, "codex", String(turn.error.message ?? "turn/start falhou"));
648
706
  return Promise.race([finished, exited.then((code) => (result.stopReason ? code : failed(result, "codex", result.errorMessage || `o codex saiu (código ${code}) antes de terminar.${result.stderr ? `\n${result.stderr.slice(-400)}` : ""}`)))]);
@@ -650,7 +708,7 @@ async function runCodex(child: any, task: string, cwd: string, result: any, emit
650
708
 
651
709
  // a ligação com um agente ACP: o processo, a sessão aberta e a mensagem em andamento (turn), para servir várias mensagens
652
710
  type AcpTurn = { result: any; state: { text: string; loading: boolean }; emit: () => void; ask: () => Ask | undefined };
653
- 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 };
711
+ 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; lateBuffer?: { result: any; state: AcpTurn["state"] }; lateTimer?: ReturnType<typeof setTimeout> };
654
712
  // o que o agente quer fazer, em palavras: o título do ACP sozinho às vezes é só "bash" ou "edit" (owner 2026-11-25:
655
713
  // "permitindo no escuro"). Junta o tipo, o comando ou os arquivos e diz que o sim vale só para esta vez.
656
714
  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" };
@@ -669,21 +727,50 @@ export function permissionText(call: any): string {
669
727
  return lines.join("\n");
670
728
  }
671
729
 
672
- function acpOpen(child: any, name: string, exited: Promise<number>): AcpConn {
730
+ // junta as atualizações sem turno numa resposta; entrega quando o agente fica em silêncio (ou antes da próxima mensagem)
731
+ function flushLate(conn: AcpConn, resume?: Resume) {
732
+ clearTimeout(conn.lateTimer);
733
+ const late = conn.lateBuffer;
734
+ conn.lateBuffer = undefined;
735
+ if (!late || !resume?.late) return;
736
+ flushThinking(late.result, late.state);
737
+ finalText(late.result, late.state.text);
738
+ if (!late.result.messages.length) return;
739
+ late.result.stopReason = "stop";
740
+ try {
741
+ resume.late.deliver(late.result);
742
+ } catch {
743
+ /* sessão do Pink já fechada */
744
+ }
745
+ }
746
+ function lateUpdate(conn: AcpConn, update: any, resume?: Resume) {
747
+ if (!resume?.late) return;
748
+ // só começa com algo que a pessoa veria: avisos de uso e de comandos não viram resposta
749
+ if (!conn.lateBuffer && !["agent_message_chunk", "agent_thought_chunk", "tool_call"].includes(update?.sessionUpdate)) return;
750
+ conn.lateBuffer ??= { result: resume.late.fresh(), state: { text: "" } };
751
+ if (conn.model) conn.lateBuffer.result.model = conn.model;
752
+ applyAcpUpdate(update, conn.lateBuffer.result, conn.lateBuffer.state, () => {});
753
+ clearTimeout(conn.lateTimer);
754
+ conn.lateTimer = setTimeout(() => flushLate(conn, resume), resume.late.quietMs ?? LATE_QUIET_MS);
755
+ conn.lateTimer.unref?.();
756
+ }
757
+ function acpOpen(child: any, name: string, exited: Promise<number>, resume?: Resume): AcpConn {
673
758
  const conn = { child, exited } as AcpConn;
674
759
  conn.client = rpc(
675
760
  child,
676
761
  name,
677
762
  (method, params) => {
678
763
  const turn = conn.turn;
679
- if (method === "session/update" && turn && !conn.loading) applyAcpUpdate(params?.update, turn.result, turn.state, turn.emit); // session/load repete o histórico: não mostrar de novo
764
+ if (method !== "session/update" || conn.loading) return; // session/load repete o histórico: não mostrar de novo
765
+ if (turn) applyAcpUpdate(params?.update, turn.result, turn.state, turn.emit);
766
+ else lateUpdate(conn, params?.update, resume);
680
767
  },
681
768
  async (method, params) => {
682
769
  if (method !== "session/request_permission") return undefined; // sem fs nem terminal do cliente: o agente usa os dele
683
770
  const options: any[] = Array.isArray(params?.options) ? params.options : [];
684
771
  const allow = options.find((option) => option?.kind === "allow_once") ?? options.find((option) => String(option?.kind).startsWith("allow"));
685
772
  const reject = options.find((option) => option?.kind === "reject_once") ?? options.find((option) => String(option?.kind).startsWith("reject"));
686
- const confirm = conn.turn?.ask();
773
+ const confirm = conn.turn ? conn.turn.ask() : resume?.late?.ask?.();
687
774
  const ok = Boolean(allow && confirm && (await confirm(`O ${name} pede permissão`, permissionText(params?.toolCall))));
688
775
  if (ok) return { outcome: { outcome: "selected", optionId: allow.optionId } };
689
776
  return reject ? { outcome: { outcome: "selected", optionId: reject.optionId } } : { outcome: { outcome: "cancelled" } };
@@ -694,6 +781,7 @@ function acpOpen(child: any, name: string, exited: Promise<number>): AcpConn {
694
781
 
695
782
  async function runAcp(child: any, name: string, task: string, cwd: string, result: any, emit: () => void, ask: () => Ask | undefined, exited: Promise<number>, resume?: { id?: string }, model?: string, extras?: Extras, kept?: AcpConn): Promise<number> {
696
783
  const conn = kept ?? acpOpen(child, name, exited);
784
+ flushLate(conn, resume as Resume | undefined); // o que ficou pendente sai antes da resposta nova
697
785
  const state = { text: "", loading: false };
698
786
  conn.turn = { result, state, emit, ask };
699
787
  try {
@@ -58,7 +58,9 @@ export function t(pt: string, es: string, en: string): string {
58
58
  export type Choice = { value: string; label?: string; description?: string };
59
59
  export const completeFrom = (choices: () => Choice[]) => (prefix: string) => {
60
60
  const typed = String(prefix ?? "").trimStart().toLowerCase();
61
- const hits = choices().filter((choice) => choice.value.startsWith(typed));
61
+ const hits = choices().filter((choice) => choice.value.toLowerCase().startsWith(typed));
62
+ // palavra já completa (só ela casa): sem lista aberta, o Enter roda o comando em vez de só aceitar a sugestão (Tifa, 2026-11-27)
63
+ if (hits.length === 1 && hits[0].value.toLowerCase() === typed) return null;
62
64
  return hits.length ? hits.map((choice) => ({ label: choice.value, ...choice })) : null;
63
65
  };
64
66
  export async function choose(ctx: any, title: string, choices: Choice[]): Promise<string | undefined> {
@@ -70,6 +72,27 @@ export async function choose(ctx: any, title: string, choices: Choice[]): Promis
70
72
  return at < 0 ? undefined : choices[at].value;
71
73
  }
72
74
 
75
+ // argumento que o comando não conhece: dizer o que vale, nunca fazer outra coisa calado (owner 2026-11-27)
76
+ export function unknown(ctx: any, command: string, typed: string, choices: Choice[]) {
77
+ const list = choices.map((choice) => (choice.description ? `${choice.value} (${choice.description})` : choice.value)).join(", ");
78
+ ctx?.ui?.notify?.(t(`${command}: "${typed}" não é uma opção. Opções: ${list}.`, `${command}: "${typed}" no es una opción. Opciones: ${list}.`, `${command}: "${typed}" is not an option. Options: ${list}.`), "warning");
79
+ }
80
+ export const noArgs = (command: string, handler: (args: any, ctx: any) => any) => async (args: any, ctx: any) => {
81
+ const typed = String(args ?? "").trim();
82
+ if (typed) return void ctx?.ui?.notify?.(t(`${command} não tem opções ("${typed}" não vale). Use só ${command}.`, `${command} no tiene opciones ("${typed}" no vale). Usa solo ${command}.`, `${command} takes no options ("${typed}" is not valid). Use just ${command}.`), "warning");
83
+ return handler(args, ctx);
84
+ };
85
+
86
+ // comandos do motor que não aceitam argumento: com um texto depois, o motor manda a linha ao modelo como mensagem
87
+ // shortcut: lista fixa; um comando novo do motor sem argumento entra aqui
88
+ const BARE_BUILTINS = /^\/(resume|settings|logout|tree|fork|session|scoped-models|trust)[ \t]+\S[^\n]*$/;
89
+ export function builtinWithArgs(event: any, ctx: any) {
90
+ const name = event?.source === "extension" ? undefined : BARE_BUILTINS.exec(String(event?.text ?? "").trim())?.[1];
91
+ if (!name) return { action: "continue" };
92
+ ctx?.ui?.notify?.(t(`/${name} não tem opções: nada foi enviado ao modelo. Use só /${name}.`, `/${name} no tiene opciones: no se envió nada al modelo. Usa solo /${name}.`, `/${name} takes no options: nothing was sent to the model. Use just /${name}.`), "warning");
93
+ return { action: "handled" };
94
+ }
95
+
73
96
  // para os patches do motor (rebrand.json), que não importam módulos: globalThis.__pinkT(pt, es, en)
74
97
  (globalThis as any).__pinkT = t;
75
98
  (globalThis as any).__pinkLang = lang;
@@ -3,15 +3,15 @@
3
3
  // histórico dele, e a resposta aparece no Pink. A conversa continua entre mensagens (claude --resume, codex
4
4
  // thread/resume, ACP session/load). /agente off volta ao modelo do Pink, que vê a conversa (as mensagens ficam na sessão).
5
5
  // O transporte é o mesmo dos subagentes externos (examples/extensions/subagent/external.ts, cards 1dfwh7kgf8g/h/j).
6
- import { t } from "./pink-i18n.ts";
6
+ import { t, unknown } from "./pink-i18n.ts";
7
7
  import crypto from "node:crypto";
8
8
  import fs from "node:fs";
9
9
  import net from "node:net";
10
10
  import os from "node:os";
11
11
  import path from "node:path";
12
12
  import { fileURLToPath } from "node:url";
13
- import { closeKept, externalAgents, listModels, pinkExtras, runExternal, warmKept } from "../examples/extensions/subagent/external.ts";
14
- import { bulleted, elapsedLabel, fit, runLabel, shortModel, stallNote, streamedTokens, thinkingLabel, toolSummary, userLines, workingLabel } from "./pink-ui.ts";
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";
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) => {
@@ -70,6 +70,7 @@ export function gatherExtras(pink: any, dir = process.env.PINK_CODING_AGENT_DIR
70
70
  let rules = "";
71
71
  try {
72
72
  rules = fs.readFileSync(path.join(dir, "AGENTS.md"), "utf8");
73
+ if (!thothConfigured()) rules = stripThothRules(rules);
73
74
  } catch {
74
75
  /* sem regras globais */
75
76
  }
@@ -238,6 +239,34 @@ function tela(action: unknown, args: any = {}) {
238
239
  return ["tela ·", String(action || "?"), what].filter(Boolean).join(" ");
239
240
  }
240
241
 
242
+ // arquivos que o agente editou ou criou nesta resposta, para ALTERAÇÕES (mesmos nomes de ferramenta de pinkTool)
243
+ export function fileChanges(result: any, cwd = "") {
244
+ const out: { path: string; status: string }[] = [];
245
+ for (const message of result.messages) {
246
+ for (const part of message.content ?? []) {
247
+ if (part.type !== "toolCall") continue;
248
+ const raw = String(part.name ?? "").toLowerCase();
249
+ const args = part.arguments ?? {};
250
+ const file = args.path ?? args.file_path ?? args.filePath ?? args.notebook_path;
251
+ if (!file || !["edit", "write"].includes(NAMES[raw] ?? raw)) continue;
252
+ out.push({ path: cwd && path.isAbsolute(String(file)) ? path.relative(cwd, String(file)) : String(file), status: args.created ? "novo" : "editado" });
253
+ }
254
+ }
255
+ return out;
256
+ }
257
+
258
+ // SESSÃO e ALTERAÇÕES com o agente ligado: os turnos dele nesta sessão mais o que está em andamento
259
+ export function agentPanel(entries: any[] | undefined, name: string, model = "", live?: any, session = "", cwd = "") {
260
+ const turns = (entries ?? []).filter((entry) => entry?.type === "custom_message" && entry.customType === "pink-agente" && entry.details?.agent === name).map((entry) => entry.details);
261
+ if (live) turns.push({ usage: live.usage, model: live.model, session });
262
+ // o codex informa o total da conversa inteira (vale o último de cada uma); os outros, só o de cada resposta
263
+ const usages = name === "codex" ? [...new Map(turns.filter((turn) => turn.usage?.input || turn.usage?.output).map((turn) => [turn.session, turn.usage])).values()] : turns.map((turn) => turn.usage);
264
+ const sum = (key: string) => usages.reduce((total: number, usage: any) => total + (Number(usage?.[key]) || 0), 0);
265
+ const models = [...new Set(turns.map((turn) => turn.model).filter((used) => used && used !== name))];
266
+ const pending = live ? [{ type: "custom_message", customType: "pink-agente", details: { changes: fileChanges(live, cwd) } }] : [];
267
+ return { name, models: models.length ? models : model ? [model] : [], input: sum("input"), output: sum("output"), cost: sum("cost"), answered: turns.length - (live ? 1 : 0), pending };
268
+ }
269
+
241
270
  // os passos da resposta, na ordem: pensou, ferramentas e textos (o desenho usa; o modelo do Pink lê o texto puro)
242
271
  export function steps(result: any, cwd = "") {
243
272
  const out: any[] = [];
@@ -284,6 +313,23 @@ export function render(result: any, cwd = ""): string {
284
313
  return body || t("(sem resposta)", "(sin respuesta)", "(no answer)");
285
314
  }
286
315
 
316
+ // o que o agente está fazendo, ao vivo, acima do "Trabalhando" (owner 2026-11-27, como o OpenCode): os últimos passos
317
+ // (pensou, ferramentas, textos) e o que ainda está chegando. O texto vem de fora: sem caracteres de controle
318
+ const LIVE_STEPS = 6;
319
+ export function liveLines(result: any, width: number, cwd = ""): string[] {
320
+ const room = Math.max(10, width - 4);
321
+ const head = (text: unknown) => { const line = clean(text); return line.length > room ? `${line.slice(0, room - 1)}…` : line; };
322
+ const tail = (text: unknown) => tailLine(text, room);
323
+ const done = compact(steps(result, cwd)).map((step: any) => (step.kind === "tool" ? `→ ${head(step.line)}` : step.kind === "thinking" ? thinkingLabel(step.ms) : `● ${head(step.text)}`));
324
+ const part = result.partial;
325
+ const now = !part?.text ? [] : part.kind === "thinking"
326
+ ? thinkingNow(part.text, room)
327
+ : String(part.text).split("\n").filter((line) => clean(line)).slice(-3).map((line, index) => `${index ? " " : "●"} ${tail(line)}`);
328
+ const hidden = done.length - LIVE_STEPS;
329
+ const earlier = hidden > 0 ? [t(` … ${hidden} passos antes`, ` … ${hidden} pasos antes`, ` … ${hidden} earlier steps`)] : [];
330
+ return [...earlier, ...done.slice(-LIVE_STEPS), ...now].map((line) => ` ${line}`);
331
+ }
332
+
287
333
  const outputOf = (result: any) => result.usage?.output || result.messages.reduce((sum: number, message: any) => sum + streamedTokens(message), 0);
288
334
 
289
335
  const label = (agent: any) => [agent.name, agent.model, agent.effort].filter(Boolean).join(" · ");
@@ -339,6 +385,7 @@ export default function (pink: any, list: typeof externalAgents = externalAgents
339
385
  let active: { agent: any; resume: any; controller?: AbortController; queue?: string[]; live?: any; handoff?: string[] } | undefined;
340
386
  let ticker: ReturnType<typeof setInterval> | undefined;
341
387
  let lastUi: any;
388
+ (globalThis as any).__pinkAgentPanel = (entries: any[]) => active && agentPanel(entries, active.agent.name, active.agent.model, active.controller ? active.live : undefined, active.resume?.id, screenCtx?.cwd);
342
389
 
343
390
  // "⠴ Trabalhando · 2s · ↓ 0 tokens" acima da caixa, com o mesmo Loader do Pink: o dele só aparece quando o modelo do Pink
344
391
  // responde, e este ocupa o mesmo lugar
@@ -353,7 +400,7 @@ export default function (pink: any, list: typeof externalAgents = externalAgents
353
400
  };
354
401
  // 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)
355
402
  const around = (lines: string[], width: number, theme: any) => [...queueLines(active?.queue ?? [], width).map((line) => theme.fg("dim", line)), ...lines, ""];
356
- const busy = (ui: any, output: () => number) => {
403
+ const busy = (ui: any, output: () => number, doing: (width: number) => string[] = () => []) => {
357
404
  idle();
358
405
  lastUi = ui;
359
406
  if (!ui?.setWidget) return;
@@ -374,12 +421,12 @@ export default function (pink: any, list: typeof externalAgents = externalAgents
374
421
  loader?.stop?.(); // a fábrica pode ser chamada de novo: o Loader anterior para de girar
375
422
  loader = new tui.Loader(screen, (s: string) => theme.fg("accent", s), (s: string) => theme.fg("muted", s), message());
376
423
  const own = loader;
377
- return { render: (width: number) => around(own.render(width).slice(1), width, theme), invalidate: () => own.invalidate?.() };
424
+ 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?.() };
378
425
  }, { placement: "aboveEditor" });
379
426
  ticker = setInterval(() => loader?.setMessage?.(message()), 1000);
380
427
  } else {
381
428
  let frame = 0;
382
- const draw = () => ui.setWidget(WIDGET, (screen: any, theme: any) => ((screenRef = screen), { render: (width: number) => around([` ${FRAMES[frame % FRAMES.length]} ${message()}`], width, theme), invalidate() {} }), { placement: "aboveEditor" });
429
+ 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" });
383
430
  draw();
384
431
  ticker = setInterval(() => (frame++, draw()), 120);
385
432
  }
@@ -431,6 +478,13 @@ export default function (pink: any, list: typeof externalAgents = externalAgents
431
478
  active.controller.abort();
432
479
  return true;
433
480
  };
481
+ // Esc com o agente trabalhando: interrompe ele. Antes o Esc ia para a conversa, que não sabe do /agente: dois Esc abriam a árvore
482
+ // da conversa, voltavam a sessão para antes do pedido e punham o prompt de volta na caixa (owner 2026-11-26)
483
+ (globalThis as any).__pinkAgentInterrupt = () => {
484
+ if (!active?.controller) return false;
485
+ active.controller.abort();
486
+ return true;
487
+ };
434
488
  const stop = (ctx?: any) => {
435
489
  (ctx?.ui ?? lastUi)?.setWidget?.(QUEUE, undefined); // fila de versões antigas do widget (a de agora some junto com o agente)
436
490
  if (active) active.queue = []; // a fila é descartada junto
@@ -526,6 +580,16 @@ export default function (pink: any, list: typeof externalAgents = externalAgents
526
580
  };
527
581
  });
528
582
 
583
+ // resposta que o agente manda depois do fim do turno (subagente ou comando em segundo plano que terminou)
584
+ const lateTurn = (name: string, resume: any, ctx: any) => ({
585
+ fresh,
586
+ ask: () => (globalThis as any).__pinkExternalAsk,
587
+ deliver: (result: any) => {
588
+ if (active?.resume !== resume) return; // agente desligado ou trocado: não cai em outra conversa
589
+ pink.sendMessage({ customType: "pink-agente", display: true, content: render(result, ctx.cwd), details: { agent: name, session: resume.id, model: result.model, usage: result.usage, steps: steps(result, ctx.cwd), changes: fileChanges(result, ctx.cwd), output: outputOf(result) } });
590
+ },
591
+ });
592
+
529
593
  const send = async (text: string, ctx: any) => {
530
594
  const current = active!;
531
595
  screenCtx = ctx;
@@ -546,15 +610,18 @@ export default function (pink: any, list: typeof externalAgents = externalAgents
546
610
  ctx.ui?.setStatus?.(STATUS, `${name} ${t("trabalhando", "trabajando", "working")}${last ? `: ${last}` : "…"}`);
547
611
  };
548
612
  status();
549
- if (ctx.hasUI) busy(ctx.ui, () => outputOf(result));
613
+ if (ctx.hasUI) busy(ctx.ui, () => outputOf(result), (width) => liveLines(result, width, ctx.cwd));
550
614
  if (ctx.hasUI) watchChildren(ctx.ui);
551
- (globalThis as any).__pinkExternalAsk = ctx.hasUI ? (title: string, body: string) => ctx.ui.confirm(title, body) : undefined;
615
+ // "permitir tudo" (/permissoes): o que o agente pede é aceito sem perguntar
616
+ (globalThis as any).__pinkExternalAsk = ctx.hasUI ? (title: string, body: string) => ((globalThis as any).__pinkPermissionMode === "all" ? Promise.resolve(true) : ctx.ui.confirm(title, body)) : undefined;
552
617
  try {
553
618
  await run(current.agent, before ? `${before}\n${text}` : text, ctx.cwd, controller.signal, result, status, undefined, undefined, current.resume);
554
619
  } catch (error: any) {
555
620
  result.stopReason = "error";
556
621
  result.errorMessage = controller.signal.aborted ? t("cancelado", "cancelado", "cancelled") : String(error?.message ?? error);
557
622
  }
623
+ // acabou a mensagem: subagente sem aviso de fim não pode ficar "rodando" para sempre
624
+ for (const id of Object.keys(result.subagents ?? {})) subagentEnd(result, id, result.stopReason === "error");
558
625
  if (current.controller === controller) current.controller = undefined;
559
626
  if (active === current || !active) idle();
560
627
  Reflect.get(globalThis, "__pinkTela")?.hide?.(); // o agente terminou: apaga o contorno da tela
@@ -564,7 +631,7 @@ export default function (pink: any, list: typeof externalAgents = externalAgents
564
631
  if (!current.agent.model && result.model && result.model !== name) (globalThis as any).__pinkExternalAgent = { name, model: result.model, effort: current.agent.effort };
565
632
  }
566
633
  const error = result.stopReason === "error" ? String(result.errorMessage ?? t("erro", "error", "error")) : undefined;
567
- pink.sendMessage({ customType: "pink-agente", display: true, content: render(result, ctx.cwd), details: { agent: name, session: current.resume?.id, model: result.model, usage: result.usage, error, steps: steps(result, ctx.cwd), ms: Date.now() - started, output: outputOf(result) } });
634
+ pink.sendMessage({ customType: "pink-agente", display: true, content: render(result, ctx.cwd), details: { agent: name, session: current.resume?.id, model: result.model, usage: result.usage, error, steps: steps(result, ctx.cwd), changes: fileChanges(result, ctx.cwd), ms: Date.now() - started, output: outputOf(result) } });
568
635
  pink.events?.emit?.("pink:agent_settled", { ctx, aborted: controller.signal.aborted });
569
636
  // trocaram o modelo do Pink no meio: o que o agente fez já está na sessão; o novo modelo continua o pedido
570
637
  if (current.handoff) return void pink.sendUserMessage?.(handoffText(name, [text, ...current.handoff]));
@@ -579,6 +646,7 @@ export default function (pink: any, list: typeof externalAgents = externalAgents
579
646
 
580
647
  // "/agente " lista as opções, como os outros comandos: off e os agentes; "/agente codex " lista os modelos dele
581
648
  const modelCache = new Map<string, Promise<any[]>>();
649
+ const INSTALL = () => t("Instale um deles (ex.: Claude Code, Codex ou OpenCode), faça o login e abra o Pink de novo.", "Instala uno (ej.: Claude Code, Codex u OpenCode), inicia sesión y vuelve a abrir Pink.", "Install one (e.g. Claude Code, Codex or OpenCode), log in and reopen Pink.");
582
650
  const completions = async (prefix: string) => {
583
651
  const text = String(prefix ?? "").replace(/^\s+/, "");
584
652
  const space = text.indexOf(" ");
@@ -588,6 +656,7 @@ export default function (pink: any, list: typeof externalAgents = externalAgents
588
656
  ...(active ? [{ value: "off", label: "off", description: t(`volta ao Pink (desliga o ${active.agent.name})`, `vuelve a Pink (apaga ${active.agent.name})`, `back to Pink (turns ${active.agent.name} off)`) }] : []),
589
657
  ...agents.map((agent) => ({ value: agent.name, label: agent.name, description: t(`conversar com o ${agent.name}, com o login dele`, `conversar con ${agent.name}, con su login`, `talk to ${agent.name}, with its own login`) })),
590
658
  ];
659
+ if (!agents.length && !text) items.push({ value: "", label: t("nenhum agente instalado", "ningún agente instalado", "no agent installed"), description: INSTALL() });
591
660
  const hits = items.filter((item) => item.value.startsWith(text.toLowerCase()));
592
661
  return hits.length ? hits : null;
593
662
  }
@@ -625,7 +694,7 @@ export default function (pink: any, list: typeof externalAgents = externalAgents
625
694
  }
626
695
  let name = wanted;
627
696
  if (!name) {
628
- if (!agents.length) return ctx.ui?.notify?.(t("Nenhum agente instalado encontrado (claude, codex, opencode, cline, copilot, qwen, goose, gemini).", "No se encontró ningún agente instalado (claude, codex, opencode, cline, copilot, qwen, goose, gemini).", "No installed agent found (claude, codex, opencode, cline, copilot, qwen, goose, gemini)."), "warning");
697
+ if (!agents.length) return ctx.ui?.notify?.(`${t("Nenhum agente instalado encontrado (claude, codex, opencode, cline, copilot, qwen, goose, gemini).", "No se encontró ningún agente instalado (claude, codex, opencode, cline, copilot, qwen, goose, gemini).", "No installed agent found (claude, codex, opencode, cline, copilot, qwen, goose, gemini).")} ${INSTALL()}`, "warning");
629
698
  // com um agente ligado, o primeiro item volta ao modelo/provedor do Pink (o mesmo que /agente off)
630
699
  const back = active ? t(`Voltar ao Pink (desliga o ${active.agent.name})`, `Volver a Pink (apaga ${active.agent.name})`, `Back to Pink (turns ${active.agent.name} off)`) : undefined;
631
700
  name = ctx.hasUI ? ((await pick(ctx, t("Conversar com qual agente?", "¿Con qué agente conversar?", "Talk to which agent?"), [...(back ? [back] : []), ...agents.map((agent) => agent.name)], load)) ?? "") : "";
@@ -637,9 +706,9 @@ export default function (pink: any, list: typeof externalAgents = externalAgents
637
706
  }
638
707
  }
639
708
  const agent = agents.find((item) => item.name === name);
640
- if (!agent) return ctx.ui?.notify?.(t(`${name} não está instalado. Disponíveis: ${agents.map((a) => a.name).join(", ") || "nenhum"}.`, `${name} no está instalado. Disponibles: ${agents.map((a) => a.name).join(", ") || "ninguno"}.`, `${name} is not installed. Available: ${agents.map((a) => a.name).join(", ") || "none"}.`), "warning");
641
- if (rest.length > 2 || (model && !/^[\w./:@-]+$/.test(model))) return ctx.ui?.notify?.(t(`Nome de modelo inválido: ${rest.join(" ")}`, `Nombre de modelo no válido: ${rest.join(" ")}`, `Invalid model name: ${rest.join(" ")}`), "warning");
642
- if (effort && !/^[a-z]+$/.test(effort)) return ctx.ui?.notify?.(t(`Esforço inválido: ${effort}`, `Esfuerzo no válido: ${effort}`, `Invalid effort: ${effort}`), "warning");
709
+ if (!agent) return ctx.ui?.notify?.(t(`${name} não está instalado. Disponíveis: ${agents.map((a) => a.name).join(", ") || "nenhum"}. /agente off volta ao Pink.`, `${name} no está instalado. Disponibles: ${agents.map((a) => a.name).join(", ") || "ninguno"}. /agente off vuelve a Pink.`, `${name} is not installed. Available: ${agents.map((a) => a.name).join(", ") || "none"}. /agente off returns to Pink.`) + (agents.length ? "" : ` ${INSTALL()}`), "warning");
710
+ if (rest.length > 2 || (model && !/^[\w./:@-]+$/.test(model))) return ctx.ui?.notify?.(t(`Nome de modelo inválido: ${rest.join(" ")}. Use /agente ${name} <modelo> <esforço>; digite "/agente ${name} " para ver os modelos.`, `Nombre de modelo no válido: ${rest.join(" ")}. Usa /agente ${name} <modelo> <esfuerzo>; escribe "/agente ${name} " para ver los modelos.`, `Invalid model name: ${rest.join(" ")}. Use /agente ${name} <model> <effort>; type "/agente ${name} " to see the models.`), "warning");
711
+ if (effort && !/^[a-z]+$/.test(effort)) return ctx.ui?.notify?.(t(`Esforço inválido: ${effort}. É uma palavra como low, medium ou high; digite "/agente ${name} ${model} " para ver os do modelo.`, `Esfuerzo no válido: ${effort}. Es una palabra como low, medium o high; escribe "/agente ${name} ${model} " para ver los del modelo.`, `Invalid effort: ${effort}. It is a word like low, medium or high; type "/agente ${name} ${model} " to see the model's.`), "warning");
643
712
  if (!model && ctx.hasUI) {
644
713
  // menu com os modelos que o agente informa; o primeiro item mantém o padrão dele
645
714
  ctx.ui?.setStatus?.(STATUS, t(`${name}: buscando modelos…`, `${name}: buscando modelos…`, `${name}: fetching models…`));
@@ -677,6 +746,7 @@ export default function (pink: any, list: typeof externalAgents = externalAgents
677
746
  // mesma sessão do Pink + mesmo agente: continua a conversa dele (owner 2026-11-24); sessão nova do Pink começa do zero
678
747
  const saved = lastAgentSession(ctx.sessionManager?.getBranch?.(), agent.name);
679
748
  active = { agent: { ...agent, ...(model ? { model } : {}), ...(effort ? { effort } : {}), extras: extras((screen ??= bridge(() => screenCtx))) }, resume: { keep: true, ...(saved ? { id: saved } : {}) } }; // keep: o processo do agente ACP fica aberto entre as mensagens; id: retoma a conversa
749
+ active.resume.late = lateTurn(active.agent.name, active.resume, ctx);
680
750
  warm(active.agent, ctx.cwd, active.resume); // já liga o agente: a primeira mensagem não espera a partida a frio
681
751
  (globalThis as any).__pinkExternalAgent = { name: active.agent.name, model: active.agent.model, effort: active.agent.effort }; // rótulo da caixa (pink-ui)
682
752
  ctx.ui?.setStatus?.(STATUS, `${t("agente", "agente", "agent")}: ${label(active.agent)}`);
@@ -686,6 +756,41 @@ export default function (pink: any, list: typeof externalAgents = externalAgents
686
756
  },
687
757
  });
688
758
 
759
+ // /esforco: troca o esforço do agente ligado sem abrir outra conversa. claude e codex sobem um processo por mensagem,
760
+ // então o novo nível já vale na próxima; os demais agentes não informam níveis
761
+ const effortsOf = async (agent: any, cwd: string): Promise<string[]> => {
762
+ const choices: any[] = await models(agent, cwd).catch(() => []);
763
+ const chosen = choices.find((choice) => choice.id === agent.model) ?? (agent.model ? undefined : choices.find((choice) => choice.current));
764
+ return chosen?.efforts ?? [];
765
+ };
766
+ pink.registerCommand("esforco", {
767
+ description: t("Troca o esforço do agente ligado pelo /agente (low, medium, high...), na mesma conversa", "Cambia el esfuerzo del agente encendido con /agente (low, medium, high...), en la misma conversación", "Change the effort of the agent turned on with /agente (low, medium, high...), same conversation"),
768
+ getArgumentCompletions: async (prefix: string) => {
769
+ if (!active) return null;
770
+ const typed = String(prefix ?? "").trim().toLowerCase();
771
+ const hits = (await effortsOf(active.agent, process.cwd())).filter((level) => level.startsWith(typed)).map((level) => ({ value: level, label: level }));
772
+ return hits.length ? hits : null;
773
+ },
774
+ handler: async (args: string, ctx: any) => {
775
+ if (!active) return ctx.ui?.notify?.(t("Nenhum agente ligado. Ligue um com /agente; o esforço do modelo do Pink troca com ctrl+t ou /thinking.", "Ningún agente encendido. Enciende uno con /agente; el esfuerzo del modelo de Pink cambia con ctrl+t o /thinking.", "No agent on. Turn one on with /agente; the Pink model's effort changes with ctrl+t or /thinking."), "warning");
776
+ const current = active;
777
+ const name = current.agent.name;
778
+ const levels = await effortsOf(current.agent, ctx.cwd);
779
+ if (!levels.length) return ctx.ui?.notify?.(t(`Esforço indisponível: ${label(current.agent)} não informa níveis. Troque o modelo com /agente ${name}.`, `Esfuerzo no disponible: ${label(current.agent)} no informa niveles. Cambia el modelo con /agente ${name}.`, `Effort unavailable: ${label(current.agent)} reports no levels. Change the model with /agente ${name}.`), "warning");
780
+ let level = String(args ?? "").trim().toLowerCase();
781
+ if (!level) {
782
+ level = (await pick(ctx, t(`Esforço do ${name}`, `Esfuerzo de ${name}`, `${name} effort`), levels, load)) ?? ""; // sem tela o select não responde e nada muda
783
+ if (!level) return;
784
+ }
785
+ if (!levels.includes(level)) return unknown(ctx, "/esforco", level, levels.map((value) => ({ value })));
786
+ if (active !== current) return; // trocaram ou desligaram o agente com o menu aberto
787
+ current.agent = { ...current.agent, effort: level };
788
+ (globalThis as any).__pinkExternalAgent = { name, model: current.agent.model, effort: level };
789
+ ctx.ui?.setStatus?.(STATUS, `${t("agente", "agente", "agent")}: ${label(current.agent)}`);
790
+ ctx.ui?.notify?.(t(`Esforço do ${name}: ${level}. Vale a partir da próxima mensagem, na mesma conversa.`, `Esfuerzo de ${name}: ${level}. Vale desde el próximo mensaje, en la misma conversación.`, `${name} effort: ${level}. Applies from the next message, same conversation.`), "info");
791
+ },
792
+ });
793
+
689
794
  pink.on("input", async (event: any, ctx: any) => {
690
795
  if (!active || event.source === "extension" || String(event.text ?? "").trimStart().startsWith("/")) return { action: "continue" };
691
796
  if (active.controller) {
@@ -3,7 +3,7 @@
3
3
  // O total vem do núcleo (getContextUsage, medido na última resposta); as partes são estimadas.
4
4
  // shortcut: estimativa por caracteres/4, como o estimateTokens do núcleo; trocar por tokenizador do modelo se a diferença importar
5
5
 
6
- import { t } from "./pink-i18n.ts";
6
+ import { noArgs, t } from "./pink-i18n.ts";
7
7
  export const estimate = (text: unknown) => Math.ceil(String(text ?? "").length / 4);
8
8
  const IMAGE_TOKENS = 1200; // como o núcleo: imagem conta fixo, não o base64
9
9
 
@@ -95,7 +95,7 @@ export default function (pink: any) {
95
95
  if (process.env.PINK_SUBAGENT) return;
96
96
  pink.registerCommand("context", {
97
97
  description: t("Mostra o que ocupa o contexto: prompt, ferramentas, AGENTS.md, memória, skills, conversa e espaço livre", "Muestra lo que ocupa el contexto: prompt, herramientas, AGENTS.md, memoria, skills, conversación y espacio libre", "Shows what fills the context: prompt, tools, AGENTS.md, memory, skills, conversation and free space"),
98
- handler: async (_args: string, ctx: any) => {
98
+ handler: noArgs("/context", async (_args: string, ctx: any) => {
99
99
  const options = ctx.getSystemPromptOptions?.() ?? {};
100
100
  const active = new Set<string>(pink.getActiveTools?.() ?? []);
101
101
  const usage = ctx.getContextUsage?.();
@@ -111,6 +111,6 @@ export default function (pink: any) {
111
111
  conversationEstimate: conversationEstimate(branch),
112
112
  });
113
113
  ctx.ui.notify(render(result), "info");
114
- },
114
+ }),
115
115
  });
116
116
  }
@@ -11,7 +11,7 @@
11
11
  // matcher: expressão regular sobre o nome da ferramenta, inteira, sem diferença de maiúsculas; vazio ou "*" = todas.
12
12
  // Diferença do Claude Code: tool_name chega como no Pink (bash, write, edit), sem session_id/transcript_path.
13
13
  // Em subagente (PINK_SUBAGENT) só rodam PreToolUse e PostToolUse.
14
- import { t } from "./pink-i18n.ts";
14
+ import { noArgs, t } from "./pink-i18n.ts";
15
15
  import { spawn, spawnSync } from "node:child_process";
16
16
  import fs from "node:fs";
17
17
  import os from "node:os";
@@ -134,12 +134,12 @@ export function hooksExtension(pink, deps = {}) {
134
134
  pink.events?.on?.("pink:agent_settled", (data) => void Promise.resolve(fire("Stop", data?.ctx, { aborted: Boolean(data?.aborted) })).catch(() => undefined));
135
135
  pink.registerCommand?.("hooks", {
136
136
  description: t("Mostra os hooks em uso (usuário e projeto confiável)", "Muestra los hooks en uso (usuario y proyecto de confianza)", "Shows the hooks in use (user and trusted project)"),
137
- handler: async (_args, ctx) => {
137
+ handler: noArgs("/hooks", async (_args, ctx) => {
138
138
  const files = filesFor(ctx);
139
139
  const { hooks, errors } = loadHooks(files, read);
140
140
  const lines = [`${t("Arquivos", "Archivos", "Files")}: ${files.join(" · ")}`, ...EVENTS.map((e) => `${e}: ${hooks[e].map((h) => h.command).join(" | ") || "-"}`), ...errors.map((e) => `${t("Erro", "Error", "Error")}: ${e}`)];
141
141
  ctx.ui.notify?.(lines.join("\n"), errors.length ? "warning" : "info");
142
- },
142
+ }),
143
143
  });
144
144
  }
145
145