@thothdev/pink 1.0.23 → 1.0.29

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -3,6 +3,33 @@
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.29] - 2026-11-28
7
+
8
+ - 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.
9
+
10
+ ## [1.0.28] - 2026-11-28
11
+
12
+ - `/agente opencode`: subagente que o OpenCode lança sozinho, depois da resposta, volta a aparecer na lista, e o que está trabalhando não aparece mais como pausado.
13
+ - `/agente`: o trabalho que o agente faz depois do fim do turno sai num bloco só; antes cada passo virava um bloco repetindo o nome do agente e o modelo.
14
+
15
+ ## [1.0.27] - 2026-11-28
16
+
17
+ - `/agente` (OpenCode e outros ACP): a resposta que o agente manda depois do fim do turno (subagente ou comando em segundo plano que terminou) agora aparece no chat; antes era descartada e o agente parecia ter parado. Pedidos de permissão nesse intervalo continuam sendo perguntados.
18
+
19
+ ## [1.0.26] - 2026-11-28
20
+
21
+ - `web_search` usa o servidor wigolo local (`127.0.0.1:3333`) quando ele está no ar; sem ele, ou se a resposta não for dele, segue no DuckDuckGo como antes. Nada novo para configurar.
22
+
23
+ ## [1.0.25] - 2026-11-27
24
+
25
+ - Comando com argumento já completo (`/modo plano`, `/modo tudo`, `/themes <nome>`...) roda com um Enter; antes o Enter só aceitava a sugestão e o texto ia para o chat.
26
+ - Testes de tela dos comandos com `/` (`tests/test_pink_slash_commands.py`).
27
+
28
+ ## [1.0.24] - 2026-11-27
29
+
30
+ - `/permissoes` agora abre um menu: permitir tudo, só confirmar o perigoso (padrão), perguntar tudo ou ver as regras. Antes só mostrava um aviso e parecia não fazer nada.
31
+ - Novo modo "permitir tudo" (também `/modo tudo`): nada pede confirmação, nem comando destrutivo nem arquivo protegido; só as regras `deny` que você escreveu continuam bloqueando. Vale também para os agentes do `/agente` (o Claude Code roda com `bypassPermissions`). Pede confirmação ao ligar, aparece como "Build (permite tudo)" e não entra no ciclo do `alt+m`.
32
+
6
33
  ## [1.0.23] - 2026-11-27
7
34
 
8
35
  - A coluna de sessões e o seletor de sessão seguem o idioma (português, espanhol ou inglês), como o resto do Pink; o "erro" das linhas de comando também.
package/README.md CHANGED
@@ -82,7 +82,7 @@ The chosen agent also receives Pink's MCP servers, `AGENTS.md` and skills, and c
82
82
 
83
83
  ## Model providers
84
84
 
85
- Pink's own agent works with the providers inherited from Pi, including Anthropic, OpenAI, Google Gemini, OpenRouter, DeepSeek, Mistral, Groq, xAI, Amazon Bedrock, Google Vertex AI, Azure OpenAI and GitHub Copilot, plus local or self-hosted OpenAI-compatible servers through `~/.pink/agent/models.json`.
85
+ Pink's own agent works with many providers, including Anthropic, OpenAI, Google Gemini, OpenRouter, DeepSeek, Mistral, Groq, xAI, Amazon Bedrock, Google Vertex AI, Azure OpenAI and GitHub Copilot, plus local or self-hosted OpenAI-compatible servers through `~/.pink/agent/models.json`.
86
86
 
87
87
  ## Features
88
88
 
@@ -150,7 +150,7 @@ Several of these tools are not competitors: Pink can run them for you.
150
150
 
151
151
  | Tool | License | Relationship with Pink | Runs inside Pink |
152
152
  |---|---|---|---|
153
- | [Pi](https://github.com/earendil-works/pi) | MIT | The base Pink is forked from | no |
153
+ | [Pi](https://github.com/earendil-works/pi) | MIT | Pink is a fork of Pi | no |
154
154
  | [OpenCode](https://github.com/anomalyco/opencode) | MIT | Alternative, also usable from Pink | `/agente opencode` |
155
155
  | [Claude Code](https://github.com/anthropics/claude-code) | Proprietary | Complement | `/agente claude` |
156
156
  | [Codex CLI](https://github.com/openai/codex) | Apache-2.0 | Complement | `/agente codex` |
@@ -158,7 +158,7 @@ Several of these tools are not competitors: Pink can run them for you.
158
158
  | [Goose](https://github.com/aaif-goose/goose) | Apache-2.0 | Alternative, also usable from Pink | `/agente goose` |
159
159
  | [Aider](https://github.com/Aider-AI/aider) | Apache-2.0 | Alternative | no |
160
160
 
161
- If you want a minimal, extensible harness, use Pi itself. Pink is for people who want the screen, the parallel sessions and several agents in one place.
161
+ Pink is for people who want the screen, the parallel sessions and several agents in one place.
162
162
 
163
163
  ## Configuration
164
164
 
@@ -220,7 +220,7 @@ An agent runs commands on your computer: review what it asks to do. To report a
220
220
 
221
221
  ## Documentation
222
222
 
223
- [What is specific to Pink](docs/PINK.md) (in Portuguese) · [Changelog](CHANGELOG.md) (in Portuguese) · [What changed from Pi](NOTICE.md) (in Portuguese). The full manual ships with the package, in its `docs/` folder.
223
+ [What is specific to Pink](docs/PINK.md) (in Portuguese) · [Changelog](CHANGELOG.md) (in Portuguese) · [What this fork of Pi changes](NOTICE.md) (in Portuguese). The full manual ships with the package, in its `docs/` folder.
224
224
 
225
225
  ## Contributing
226
226
 
@@ -465,13 +465,22 @@ export function acpModels(session: any): ModelChoice[] {
465
465
  // resume: a conversa continua entre chamadas (sessão inteira no agente, card 1dfwh7kgf8k); o id é gravado nele
466
466
  // /agente com ACP (opencode, cline...): o processo fica aberto entre as mensagens (keep), porque subir o agente e abrir a
467
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)
468
- 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; idleMs?: number };
472
+ // o ACP não avisa o fim desse turno. Silêncio depois de texto fecha a resposta; depois de pensamento ou comando o agente
473
+ // ainda está trabalhando e espera bem mais, senão cada passo vira um bloco com o nome do agente (owner 2026-11-28)
474
+ export const LATE_QUIET_MS = 8000;
475
+ export const LATE_IDLE_MS = 180000;
469
476
  // `force` (Esc): um agente preso (ex.: opencode esperando um subagente que não abre) ignora o fim da entrada, e no Windows
470
477
  // 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)
471
478
  export function closeKept(resume?: Resume, force = false, kill: typeof spawn = spawn) {
472
479
  const conn = resume?.live;
473
480
  if (resume) resume.live = undefined;
474
481
  if (!conn) return;
482
+ clearTimeout(conn.lateTimer);
483
+ conn.lateBuffer = undefined;
475
484
  try {
476
485
  conn.child.stdin?.end?.(); // fim da entrada: o agente sai sozinho (o kill do .cmd do npm pega só o shell)
477
486
  if (force && process.platform === "win32" && conn.child.pid) kill("taskkill", ["/PID", String(conn.child.pid), "/T", "/F"], { stdio: "ignore", windowsHide: true }).on?.("error", () => undefined);
@@ -492,7 +501,7 @@ function openKept(agent: ExternalAgent, cwd: string, start: typeof spawn, resume
492
501
  resolve(1);
493
502
  });
494
503
  });
495
- conn = resume.live = acpOpen(child, agent.name, exited);
504
+ conn = resume.live = acpOpen(child, agent.name, exited, resume);
496
505
  const opened = conn;
497
506
  child.stderr?.on?.("data", (data: any) => {
498
507
  const target = opened.turn?.result;
@@ -565,6 +574,8 @@ export async function runExternal(agent: ExternalAgent, task: string, cwd: strin
565
574
  if (agent.extras.mcp.pink) extra.push("--allowedTools", "mcp__pink__pink_tarefa,mcp__pink__pink_tela"); // a tela confirma cada ação no Pink
566
575
  extra.push("--append-system-prompt-file", rulesFile);
567
576
  }
577
+ // "permitir tudo" no Pink: sem isto o claude -p recusa em silêncio a ferramenta que não foi liberada
578
+ if (agent.external === "claude" && (globalThis as any).__pinkPermissionMode === "all") extra.push("--permission-mode", "bypassPermissions");
568
579
  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;
569
580
  const child = spawnAgent(agent, args, cwd, start);
570
581
  if (scratch) {
@@ -700,7 +711,7 @@ async function runCodex(child: any, task: string, cwd: string, result: any, emit
700
711
 
701
712
  // a ligação com um agente ACP: o processo, a sessão aberta e a mensagem em andamento (turn), para servir várias mensagens
702
713
  type AcpTurn = { result: any; state: { text: string; loading: boolean }; emit: () => void; ask: () => Ask | undefined };
703
- 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 };
714
+ 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> };
704
715
  // o que o agente quer fazer, em palavras: o título do ACP sozinho às vezes é só "bash" ou "edit" (owner 2026-11-25:
705
716
  // "permitindo no escuro"). Junta o tipo, o comando ou os arquivos e diz que o sim vale só para esta vez.
706
717
  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" };
@@ -719,21 +730,52 @@ export function permissionText(call: any): string {
719
730
  return lines.join("\n");
720
731
  }
721
732
 
722
- function acpOpen(child: any, name: string, exited: Promise<number>): AcpConn {
733
+ // junta as atualizações sem turno numa resposta; entrega quando o agente fica em silêncio (ou antes da próxima mensagem)
734
+ function flushLate(conn: AcpConn, resume?: Resume) {
735
+ clearTimeout(conn.lateTimer);
736
+ const late = conn.lateBuffer;
737
+ conn.lateBuffer = undefined;
738
+ if (!late || !resume?.late) return;
739
+ flushThinking(late.result, late.state);
740
+ finalText(late.result, late.state.text);
741
+ if (!late.result.messages.length) return;
742
+ late.result.stopReason = "stop";
743
+ try {
744
+ resume.late.deliver(late.result);
745
+ } catch {
746
+ /* sessão do Pink já fechada */
747
+ }
748
+ }
749
+ function lateUpdate(conn: AcpConn, update: any, resume?: Resume) {
750
+ if (!resume?.late) return;
751
+ // só começa com algo que a pessoa veria: avisos de uso e de comandos não viram resposta
752
+ const kind = update?.sessionUpdate;
753
+ if (!conn.lateBuffer && !["agent_message_chunk", "agent_thought_chunk", "tool_call"].includes(kind)) return;
754
+ conn.lateBuffer ??= { result: resume.late.fresh(), state: { text: "" } };
755
+ if (conn.model) conn.lateBuffer.result.model = conn.model;
756
+ applyAcpUpdate(update, conn.lateBuffer.result, conn.lateBuffer.state, () => {});
757
+ if (!["agent_message_chunk", "agent_thought_chunk", "tool_call", "tool_call_update"].includes(kind)) return; // uso e comandos não mexem no prazo
758
+ clearTimeout(conn.lateTimer);
759
+ conn.lateTimer = setTimeout(() => flushLate(conn, resume), kind === "agent_message_chunk" || update?.rawOutput?.metadata?.status === "running" ? (resume.late.quietMs ?? LATE_QUIET_MS) : (resume.late.idleMs ?? LATE_IDLE_MS));
760
+ conn.lateTimer.unref?.();
761
+ }
762
+ function acpOpen(child: any, name: string, exited: Promise<number>, resume?: Resume): AcpConn {
723
763
  const conn = { child, exited } as AcpConn;
724
764
  conn.client = rpc(
725
765
  child,
726
766
  name,
727
767
  (method, params) => {
728
768
  const turn = conn.turn;
729
- 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
769
+ if (method !== "session/update" || conn.loading) return; // session/load repete o histórico: não mostrar de novo
770
+ if (turn) applyAcpUpdate(params?.update, turn.result, turn.state, turn.emit);
771
+ else lateUpdate(conn, params?.update, resume);
730
772
  },
731
773
  async (method, params) => {
732
774
  if (method !== "session/request_permission") return undefined; // sem fs nem terminal do cliente: o agente usa os dele
733
775
  const options: any[] = Array.isArray(params?.options) ? params.options : [];
734
776
  const allow = options.find((option) => option?.kind === "allow_once") ?? options.find((option) => String(option?.kind).startsWith("allow"));
735
777
  const reject = options.find((option) => option?.kind === "reject_once") ?? options.find((option) => String(option?.kind).startsWith("reject"));
736
- const confirm = conn.turn?.ask();
778
+ const confirm = conn.turn ? conn.turn.ask() : resume?.late?.ask?.();
737
779
  const ok = Boolean(allow && confirm && (await confirm(`O ${name} pede permissão`, permissionText(params?.toolCall))));
738
780
  if (ok) return { outcome: { outcome: "selected", optionId: allow.optionId } };
739
781
  return reject ? { outcome: { outcome: "selected", optionId: reject.optionId } } : { outcome: { outcome: "cancelled" } };
@@ -744,6 +786,7 @@ function acpOpen(child: any, name: string, exited: Promise<number>): AcpConn {
744
786
 
745
787
  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> {
746
788
  const conn = kept ?? acpOpen(child, name, exited);
789
+ flushLate(conn, resume as Resume | undefined); // o que ficou pendente sai antes da resposta nova
747
790
  const state = { text: "", loading: false };
748
791
  conn.turn = { result, state, emit, ask };
749
792
  try {
@@ -59,6 +59,8 @@ 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
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> {
@@ -130,12 +130,14 @@ export function contextFor(entries: any[] | undefined, agent: string, max = 1600
130
130
  export const handoffText = (agent: string, asks: string[]) =>
131
131
  `${t(`O ${agent} foi interrompido na troca de modelo. O que ele já fez está acima; continue este pedido:`, `${agent} fue interrumpido al cambiar de modelo. Lo que ya hizo está arriba; continúa este pedido:`, `${agent} was stopped by the model switch. What it already did is above; continue this request:`)}\n\n${asks.filter((ask) => ask.trim()).join("\n\n")}`;
132
132
  export const CHILD_DONE_SHOWN_MS = 15000;
133
- function childState(row: any): { state: "running" | "paused" | "done" | "failed" | "stopped"; end?: number } {
133
+ function childState(row: any, now: number): { state: "running" | "paused" | "done" | "failed" | "stopped"; end?: number } {
134
134
  if (row.last === undefined) {
135
135
  const busy = Number(row.busy) || 0;
136
136
  const idle = Number(row.idle) || 0;
137
137
  if (idle && idle >= busy) return { state: row.outcome === "failed" ? "failed" : row.outcome === "interrupted" ? "stopped" : "done", end: idle };
138
- if (row.suspended && Number(row.suspended) >= busy) return { state: "paused" };
138
+ // o opencode grava time_suspended também na sessão que está trabalhando (owner 2026-11-28: aparecia "pausado");
139
+ // só vale como pausa se ela parou de gravar. shortcut: um comando mudo por mais de 5 min também aparece pausado
140
+ if (row.suspended && Number(row.suspended) >= busy && now - Number(row.updated) > 5 * 60000) return { state: "paused" };
139
141
  return { state: "running" };
140
142
  }
141
143
  let last: any = {};
@@ -150,7 +152,7 @@ const CHILD_MARK: Record<string, string | undefined> = { running: undefined, pau
150
152
  export function childAgents(rows: any[], now: number) {
151
153
  const out: any[] = [];
152
154
  for (const row of rows ?? []) {
153
- const { state, end } = childState(row);
155
+ const { state, end } = childState(row, now);
154
156
  if (end && now - end > CHILD_DONE_SHOWN_MS) continue; // terminou há tempo: sai da lista
155
157
  if (!end && now - Number(row.updated) > 10 * 60000) continue; // parado há 10 min: o processo morreu
156
158
  const title = String(row.title ?? "");
@@ -275,7 +277,10 @@ export function steps(result: any, cwd = "") {
275
277
  if (part.type === "text" && part.text?.trim()) out.push({ kind: "text", text: part.text });
276
278
  // 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)
277
279
  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) });
278
- else if (part.type === "toolCall") out.push({ kind: "tool", line: pinkTool(part, cwd) });
280
+ else if (part.type === "toolCall") {
281
+ const child = result.subagents?.[part.id]; // lançamento de subagente: bloco próprio com nome e tarefa
282
+ out.push(child ? { kind: "agents", list: [{ agent: child.agent, task: child.task }] } : { kind: "tool", line: pinkTool(part, cwd) });
283
+ }
279
284
  }
280
285
  }
281
286
  return out;
@@ -283,10 +288,19 @@ export function steps(result: any, cwd = "") {
283
288
 
284
289
  // como no Claude Code: ferramentas seguidas viram uma linha de resumo. A tela vira "tela · 16 ações: list_windows,
285
290
  // get_window_state ×5, click ×4..." e linhas iguais em sequência viram "linha ×N" (antes eram dezenas de linhas iguais)
291
+ // como no Claude Code: "● 3 subagentes lançados" e uma linha por subagente, com a tarefa (owner 2026-11-28)
292
+ export function agentLines(list: { agent: string; task?: string }[]) {
293
+ const head = list.length === 1 ? t("1 subagente lançado", "1 subagente lanzado", "1 subagent launched") : `${list.length} ${t("subagentes lançados", "subagentes lanzados", "subagents launched")}`;
294
+ return { head, items: list.map((item, index) => ({ branch: index === list.length - 1 ? "└" : "├", agent: clean(item.agent), task: clean(item.task) })) };
295
+ }
286
296
  export function compact(list: any[]) {
287
297
  const out: any[] = [];
288
298
  for (const step of list) {
289
299
  const last = out.at(-1);
300
+ if (step.kind === "agents" && last?.kind === "agents") {
301
+ out[out.length - 1] = { kind: "agents", list: [...last.list, ...step.list] };
302
+ continue;
303
+ }
290
304
  const screen = step.kind === "tool" && String(step.line).startsWith("tela · ");
291
305
  if (screen && last?.screen) last.actions.push(String(step.line).split(" ")[2]);
292
306
  else if (step.kind === "tool" && last?.kind === "tool" && !last.screen && last.base === step.line) last.count++;
@@ -306,7 +320,7 @@ export function compact(list: any[]) {
306
320
 
307
321
  export function render(result: any, cwd = ""): string {
308
322
  const all = compact(steps(result, cwd));
309
- const tools = all.filter((step) => step.kind === "tool").map((step) => `→ ${step.line}`);
323
+ const tools = all.filter((step) => step.kind === "tool" || step.kind === "agents").map((step) => (step.kind === "tool" ? `→ ${step.line}` : step.list.map((item: any) => `→ ${t("subagente", "subagente", "subagent")} ${item.agent}: ${item.task}`).join("\n")));
310
324
  const answer = all.filter((step) => step.kind === "text").at(-1)?.text ?? "";
311
325
  const body = [tools.join("\n"), answer].filter(Boolean).join("\n\n");
312
326
  if (result.stopReason === "error") return [body, `⚠ ${result.errorMessage}`].filter(Boolean).join("\n\n");
@@ -320,7 +334,13 @@ export function liveLines(result: any, width: number, cwd = ""): string[] {
320
334
  const room = Math.max(10, width - 4);
321
335
  const head = (text: unknown) => { const line = clean(text); return line.length > room ? `${line.slice(0, room - 1)}…` : line; };
322
336
  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)}`));
337
+ const done = compact(steps(result, cwd)).flatMap((step: any) => {
338
+ if (step.kind === "agents") {
339
+ const block = agentLines(step.list);
340
+ return [`● ${block.head}`, ...block.items.map((item) => ` ${item.branch} ${head(`${item.agent}${item.task ? ` (${item.task})` : ""}`)}`)];
341
+ }
342
+ return [step.kind === "tool" ? `→ ${head(step.line)}` : step.kind === "thinking" ? thinkingLabel(step.ms) : `● ${head(step.text)}`];
343
+ });
324
344
  const part = result.partial;
325
345
  const now = !part?.text ? [] : part.kind === "thinking"
326
346
  ? thinkingNow(part.text, room)
@@ -444,13 +464,17 @@ export default function (pink: any, list: typeof externalAgents = externalAgents
444
464
  };
445
465
  const watchChildren = (ui: any, read = readChildren, dbFile = opencodeDb()) => {
446
466
  if (childTimer || !ui?.setWidget) return;
467
+ let shown = false;
447
468
  const tick = () => {
448
469
  // opencode: o banco dele mostra também os de segundo plano; os outros (e o opencode sem node:sqlite): o fluxo
449
470
  const opencode = isOpencode(active?.agent);
450
471
  const fromDb = opencode && active?.resume?.id ? read(dbFile, active.resume.id) : [];
451
472
  const items = fromDb.length ? fromDb : liveAgents(active?.live, Date.now());
452
473
  (globalThis as any).__pinkAgentChildren = items; // a lateral mostra em SUBAGENTES, abaixo da SESSÃO
453
- if (!items.length && !active?.controller) return stopChildren(ui);
474
+ // segue olhando enquanto o /agente estiver ligado: o agente lança subagente sozinho, depois da resposta
475
+ if (!active) return stopChildren(ui);
476
+ if (!items.length && !shown) return;
477
+ shown = items.length > 0;
454
478
  const side = (globalThis as any).__pinkRightOn === true; // lateral ligada (pink-ui): os subagentes ficam só nela, como os do Pink
455
479
  ui.setWidget(CHILDREN, items.length && !side ? (_screen: any, theme: any) => ({
456
480
  render: (width: number) => items.map((item: any) => {
@@ -541,11 +565,17 @@ export default function (pink: any, list: typeof externalAgents = externalAgents
541
565
  box.addChild(clickable(new tui.Text(theme.fg("thinkingText", head), pad, 0), () => (opened.thoughts.has(index) ? opened.thoughts.delete(index) : opened.thoughts.add(index))));
542
566
  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));
543
567
  };
568
+ const drawAgents = (box: any, step: any) => {
569
+ const block = agentLines(step.list);
570
+ box.addChild(new tui.Text(`${theme.fg("success", "●")} ${theme.fg("text", block.head)}`, pad, 0));
571
+ for (const item of block.items) box.addChild(new tui.Text(`${theme.fg("muted", item.branch)} ${bold(theme, theme.fg("text", item.agent))}${item.task ? theme.fg("muted", ` (${item.task})`) : ""}`, pad + 2, 0));
572
+ };
544
573
  const drawSteps = (box: any, steps: any[], offset: number) => {
545
574
  for (const [index, step] of steps.entries()) {
546
575
  // ferramentas seguidas ficam juntas (uma busca na tela são dezenas de chamadas: com linha em branco virava uma tela inteira)
547
576
  if (index && !(step.kind === "tool" && steps[index - 1]?.kind === "tool")) box.addChild(new tui.Spacer(1));
548
577
  if (step.kind === "thinking") thought(box, step, offset + index);
578
+ else if (step.kind === "agents") drawAgents(box, step);
549
579
  else if (step.kind === "tool") box.addChild(new tui.Text(theme.fg("muted", `→ ${step.line}`), pad, 0));
550
580
  else box.addChild(bulleted(new tui.Markdown(String(step.text).trim(), pad, 0, coding.getMarkdownTheme())));
551
581
  }
@@ -558,6 +588,7 @@ export default function (pink: any, list: typeof externalAgents = externalAgents
558
588
  const open = opened.work || all();
559
589
  box.addChild(clickable(new tui.Text(theme.fg("muted", `${open ? "−" : "+"} ${summary}`), pad, 0), () => (opened.work = !opened.work)));
560
590
  if (open) box.addChild(new tui.Spacer(1)), drawSteps(box, work, 0);
591
+ else for (const step of work) if (step.kind === "agents") box.addChild(new tui.Spacer(1)), drawAgents(box, step); // lançamento não fica escondido no resumo
561
592
  if (answer.length) box.addChild(new tui.Spacer(1));
562
593
  drawSteps(box, answer, work.length);
563
594
  } else drawSteps(box, list, 0);
@@ -580,6 +611,16 @@ export default function (pink: any, list: typeof externalAgents = externalAgents
580
611
  };
581
612
  });
582
613
 
614
+ // resposta que o agente manda depois do fim do turno (subagente ou comando em segundo plano que terminou)
615
+ const lateTurn = (name: string, resume: any, ctx: any) => ({
616
+ fresh,
617
+ ask: () => (globalThis as any).__pinkExternalAsk,
618
+ deliver: (result: any) => {
619
+ if (active?.resume !== resume) return; // agente desligado ou trocado: não cai em outra conversa
620
+ 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) } });
621
+ },
622
+ });
623
+
583
624
  const send = async (text: string, ctx: any) => {
584
625
  const current = active!;
585
626
  screenCtx = ctx;
@@ -602,7 +643,8 @@ export default function (pink: any, list: typeof externalAgents = externalAgents
602
643
  status();
603
644
  if (ctx.hasUI) busy(ctx.ui, () => outputOf(result), (width) => liveLines(result, width, ctx.cwd));
604
645
  if (ctx.hasUI) watchChildren(ctx.ui);
605
- (globalThis as any).__pinkExternalAsk = ctx.hasUI ? (title: string, body: string) => ctx.ui.confirm(title, body) : undefined;
646
+ // "permitir tudo" (/permissoes): o que o agente pede é aceito sem perguntar
647
+ (globalThis as any).__pinkExternalAsk = ctx.hasUI ? (title: string, body: string) => ((globalThis as any).__pinkPermissionMode === "all" ? Promise.resolve(true) : ctx.ui.confirm(title, body)) : undefined;
606
648
  try {
607
649
  await run(current.agent, before ? `${before}\n${text}` : text, ctx.cwd, controller.signal, result, status, undefined, undefined, current.resume);
608
650
  } catch (error: any) {
@@ -735,6 +777,7 @@ export default function (pink: any, list: typeof externalAgents = externalAgents
735
777
  // mesma sessão do Pink + mesmo agente: continua a conversa dele (owner 2026-11-24); sessão nova do Pink começa do zero
736
778
  const saved = lastAgentSession(ctx.sessionManager?.getBranch?.(), agent.name);
737
779
  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
780
+ active.resume.late = lateTurn(active.agent.name, active.resume, ctx);
738
781
  warm(active.agent, ctx.cwd, active.resume); // já liga o agente: a primeira mensagem não espera a partida a frio
739
782
  (globalThis as any).__pinkExternalAgent = { name: active.agent.name, model: active.agent.model, effort: active.agent.effort }; // rótulo da caixa (pink-ui)
740
783
  ctx.ui?.setStatus?.(STATUS, `${t("agente", "agente", "agent")}: ${label(active.agent)}`);
@@ -59,6 +59,8 @@ 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
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> {
@@ -212,6 +212,11 @@ export function permissions(pink, deps = {}) {
212
212
  if (AGENT_FILES.some((name) => path.join(agentDir(env), name).toLowerCase() === abs))
213
213
  return { block: true, reason: t("Bloqueado pelas permissões do Pink: o agente não edita as próprias regras e hooks (a pessoa edita)", "Bloqueado por los permisos de Pink: el agente no edita sus propias reglas ni hooks (la persona los edita)", "Blocked by Pink permissions: the agent does not edit its own rules and hooks (the person does)") };
214
214
  }
215
+ // "permitir tudo" (/modo tudo, /permissoes): só as regras deny que a pessoa escreveu ainda bloqueiam
216
+ if (globalThis.__pinkPermissionMode === "all") {
217
+ const rule = rules.deny.find((item) => matches(item, toolName, target, "deny"));
218
+ return rule ? { block: true, reason: t(`Bloqueado pelas permissões do Pink: regra deny ${rule}`, `Bloqueado por los permisos de Pink: regla deny ${rule}`, `Blocked by Pink permissions: deny rule ${rule}`) } : undefined;
219
+ }
215
220
  let { action, why } = decide(rules, toolName, target);
216
221
  // modo "pergunta tudo" (alt+m, pink-ui): o que só lê segue livre; o resto confirma, mesmo com allow (deny continua valendo)
217
222
  if (action === "allow" && globalThis.__pinkPermissionMode === "ask" && !readsOnly(pink, toolName)) {
@@ -231,8 +236,21 @@ export function permissions(pink, deps = {}) {
231
236
  return { block: true, reason: t("A pessoa negou esta ação", "La persona denegó esta acción", "The person denied this action") };
232
237
  });
233
238
  pink.registerCommand?.("permissoes", {
234
- description: t("Mostra as permissões em uso (regras do usuário, do projeto e o padrão do Pink)", "Muestra los permisos en uso (reglas del usuario, del proyecto y el predeterminado de Pink)", "Shows the permissions in use (user rules, project rules and Pink's default)"),
239
+ description: t("Escolhe o quanto o agente faz sem perguntar (inclusive permitir tudo) e mostra as regras", "Elige cuánto hace el agente sin preguntar (incluso permitir todo) y muestra las reglas", "Chooses how much the agent does without asking (including allow everything) and shows the rules"),
235
240
  handler: noArgs("/permissoes", async (_args, ctx) => {
241
+ // um menu, não só um aviso: escolher /permissoes parecia não fazer nada (owner 2026-11-27)
242
+ const options = [
243
+ ["all", t("Permitir tudo (não pergunta nada)", "Permitir todo (no pregunta nada)", "Allow everything (never asks)")],
244
+ ["edits", t("Só confirmar o perigoso (padrão)", "Solo confirmar lo peligroso (predeterminado)", "Only confirm risky actions (default)")],
245
+ ["ask", t("Perguntar tudo", "Preguntar todo", "Ask everything")],
246
+ ["rules", t("Ver as regras em uso", "Ver las reglas en uso", "Show the rules in use")],
247
+ ];
248
+ const now = globalThis.__pinkPermissionMode;
249
+ const labels = options.map(([value, label]) => (value === now ? `${label} ✓` : label));
250
+ const picked = ctx.hasUI && ctx.ui?.select ? await ctx.ui.select(t("Permissões do agente", "Permisos del agente", "Agent permissions"), labels) : labels[3];
251
+ if (!picked) return;
252
+ const value = options[labels.indexOf(picked)]?.[0];
253
+ if (value && value !== "rules") return void (await globalThis.__pinkSetMode?.(ctx, value));
236
254
  const files = filesFor(ctx);
237
255
  const rules = loadRules(files, read);
238
256
  const lines = [
@@ -126,7 +126,7 @@ export function footerLine({ theme, width, left, right }) {
126
126
  // outro, e o nível só quando está ligado ("Sonnet 5.5 · medium", o nível sempre na palavra em inglês)
127
127
  // como no OpenCode, o agente (Build/Plano) vem antes do modelo, na cor da marca
128
128
  export function modelLabel({ theme, model, thinking, agent, permission = "edits", external = Reflect.get(globalThis, "__pinkExternalAgent") }) {
129
- const mode = agent === "build" && permission === "ask" ? t(" (pergunta tudo)", " (pregunta todo)", " (ask everything)") : "";
129
+ const mode = agent !== "build" ? "" : permission === "ask" ? t(" (pergunta tudo)", " (pregunta todo)", " (ask everything)") : permission === "all" ? t(" (permite tudo)", " (permite todo)", " (allows everything)") : "";
130
130
  const who = AGENTS[agent] ? `${theme.fg("accent", `${AGENTS[agent].label}${mode}`)}${theme.fg("muted", " · ")}` : "";
131
131
  // /agente ligado (card 1dfwh7kgfjr): o Build fica; no lugar do modelo do Pink, o agente instalado e o modelo dele
132
132
  if (external?.name) return `${who}${external.name}${theme.fg("muted", ` · ${external.model ?? t("modelo padrão", "modelo predeterminado", "default model")}${external.effort ? ` · ${external.effort}` : ""}`)}`;
@@ -1307,7 +1307,7 @@ export function toolSummary(name, args = {}, result) {
1307
1307
 
1308
1308
  // chamadas seguidas sem texto do modelo no meio viram uma linha só, como no Claude Code ("Rodou 3 comandos, leu 2 arquivos");
1309
1309
  // edit, write e o plano ficam de fora: cada um tem a própria linha (e o diff)
1310
- const GROUP_SKIP = new Set(["edit", "write", "todowrite"]);
1310
+ const GROUP_SKIP = new Set(["edit", "write", "todowrite", "subagent"]);
1311
1311
  export function toolGroups(entries) {
1312
1312
  const groups = new Map();
1313
1313
  let group;
@@ -1367,6 +1367,16 @@ function groupOf(id) {
1367
1367
  return PINK.groups.map.get(id);
1368
1368
  }
1369
1369
 
1370
+ // lançamento de subagentes nos modelos do Pink, no mesmo formato do /agente: nome e tarefa de cada um (owner 2026-11-28)
1371
+ export function subagentLaunch(args, theme, pad, width) {
1372
+ const list = (Array.isArray(args?.tasks) ? args.tasks : Array.isArray(args?.chain) ? args.chain : [args]).filter((item) => item?.agent);
1373
+ if (!list.length) return [];
1374
+ const flat = (text) => String(text ?? "").replace(/\{previous\}/g, "").replace(/[\x00-\x1f\x7f]+/g, " ").replace(/\s+/g, " ").trim();
1375
+ const head = list.length === 1 ? t("1 subagente lançado", "1 subagente lanzado", "1 subagent launched") : `${list.length} ${t("subagentes lançados", "subagentes lanzados", "subagents launched")}`;
1376
+ const margin = " ".repeat(pad);
1377
+ 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
+ }
1379
+
1370
1380
  export function compactToolRenderer(toolName, next) {
1371
1381
  const base = next?.();
1372
1382
  const empty = { render: () => [], invalidate() {} };
@@ -1396,6 +1406,7 @@ export function compactToolRenderer(toolName, next) {
1396
1406
  renderShell: "self",
1397
1407
  renderCall(args, theme, context) {
1398
1408
  if (context.expanded) return wrap(base?.renderCall?.(args, theme, context) ?? line(theme, 0, `${toolName} ${shorten(JSON.stringify(args ?? {}), 80)}`), context.outputPad);
1409
+ if (toolName === "subagent") return { render: (width) => subagentLaunch(args, theme, context.outputPad, width), invalidate() {} };
1399
1410
  return context.isPartial ? grouped(theme, context.outputPad, context.toolCallId, line(theme, context.outputPad, toolSummary(toolName, args ?? {}), theme.fg("dim", " …"))) : empty;
1400
1411
  },
1401
1412
  renderResult(result, options, theme, context) {
@@ -1546,12 +1557,14 @@ function switchAgent(ctx, next = PINK.agent === "build" ? "plan" : "build") {
1546
1557
 
1547
1558
  // modo de permissão (card 1dfwh7kfzfg), alt+m roda: pergunta tudo → aceita edições → plano. Não usa tab (Build/Plano) nem
1548
1559
  // shift+tab (pensamento). O pink-permissions lê o modo por globalThis.__pinkPermissionMode na hora de cada ferramenta.
1549
- export const MODES = { ask: t("Pergunta tudo: confirma cada edição e comando", "Pregunta todo: confirma cada edición y comando", "Ask everything: confirms every edit and command"), edits: t("Aceita edições: só confirma o perigoso (padrão)", "Acepta ediciones: solo confirma lo peligroso (predeterminado)", "Accept edits: only confirms risky actions (default)"), plan: t("Plano: só leitura", "Plan: solo lectura", "Plan: read-only") };
1560
+ export const MODES = { ask: t("Pergunta tudo: confirma cada edição e comando", "Pregunta todo: confirma cada edición y comando", "Ask everything: confirms every edit and command"), edits: t("Aceita edições: só confirma o perigoso (padrão)", "Acepta ediciones: solo confirma lo peligroso (predeterminado)", "Accept edits: only confirms risky actions (default)"), plan: t("Plano: só leitura", "Plan: solo lectura", "Plan: read-only"), all: t("Permitir tudo: não pergunta nada; só as suas regras deny valem", "Permitir todo: no pregunta nada; solo valen tus reglas deny", "Allow everything: never asks; only your deny rules apply") };
1550
1561
  export const currentMode = () => (PINK.agent === "plan" ? "plan" : PINK.permission);
1551
- export const nextMode = (mode = currentMode()) => ({ ask: "edits", edits: "plan", plan: "ask" })[mode] ?? "edits";
1552
- export function setMode(ctx, mode) {
1562
+ // "tudo" fica fora do alt+m: só entra de propósito, por /modo tudo ou /permissoes, e com confirmação
1563
+ export const nextMode = (mode = currentMode()) => ({ ask: "edits", edits: "plan", plan: "ask", all: "edits" })[mode] ?? "edits";
1564
+ export async function setMode(ctx, mode) {
1553
1565
  if (!MODES[mode]) return;
1554
1566
  if (mode === "plan") return switchAgent(ctx, "plan");
1567
+ if (mode === "all" && currentMode() !== "all" && ctx.ui?.confirm && !(await ctx.ui.confirm(t("Permitir tudo?", "¿Permitir todo?", "Allow everything?"), t("O agente edita e roda comandos sem perguntar, inclusive os destrutivos (apagar pastas, push forçado) e os arquivos protegidos (segredos e .git). Os agentes do /agente também. Vale até fechar o Pink ou trocar o modo.", "El agente edita y ejecuta comandos sin preguntar, incluso los destructivos (borrar carpetas, push forzado) y los archivos protegidos (secretos y .git). Los agentes de /agente también. Vale hasta cerrar Pink o cambiar el modo.", "The agent edits and runs commands without asking, including destructive ones (deleting folders, forced push) and protected files (secrets and .git). /agente agents too. Lasts until Pink closes or the mode changes.")))) return;
1555
1568
  PINK.permission = mode;
1556
1569
  // fora do PINK: o /reload reimporta o módulo e o "pergunta tudo" não pode voltar sozinho ao padrão menos seguro
1557
1570
  globalThis.__pinkPermissionSaved = mode;
@@ -1559,12 +1572,14 @@ export function setMode(ctx, mode) {
1559
1572
  ctx.ui?.notify?.(`${t("Modo", "Modo", "Mode")} ${MODES[mode]} (${t("alt+m troca", "alt+m cambia", "alt+m switches")})`, "info");
1560
1573
  }
1561
1574
  Object.defineProperty(globalThis, "__pinkPermissionMode", { get: () => currentMode(), configurable: true });
1562
- const MODE_ARGS = { perguntar: "ask", preguntar: "ask", ask: "ask", editar: "edits", edit: "edits", plano: "plan", plan: "plan" };
1575
+ globalThis.__pinkSetMode = setMode; // o /permissoes (pink-permissions) troca o modo por aqui
1576
+ const MODE_ARGS = { perguntar: "ask", preguntar: "ask", ask: "ask", editar: "edits", edit: "edits", plano: "plan", plan: "plan", tudo: "all", todo: "all", all: "all" };
1563
1577
 
1564
1578
  const modeChoices = () => [
1565
1579
  { value: t("perguntar", "preguntar", "ask"), description: t("pergunta antes de cada ação", "pregunta antes de cada acción", "asks before each action") },
1566
1580
  { value: t("editar", "editar", "edit"), description: t("aceita edições de arquivo", "acepta ediciones de archivos", "accepts file edits") },
1567
1581
  { value: t("plano", "plan", "plan"), description: t("só lê e planeja", "solo lee y planifica", "reads and plans only") },
1582
+ { value: t("tudo", "todo", "all"), description: t("permite tudo, sem perguntar", "permite todo, sin preguntar", "allows everything, never asks") },
1568
1583
  ];
1569
1584
 
1570
1585
  export const INIT_PROMPT = "Analise este repositório e crie o arquivo AGENTS.md na raiz (ou atualize, se já existir, sem perder o que vale). Inclua, de forma concisa: os comandos de build, teste e lint (e como rodar um único teste), a arquitetura em alto nível e as convenções de código que um agente precisa seguir. Não invente o que não estiver no repositório.";
@@ -1604,8 +1619,8 @@ function registerOpenCodeFunctions(pink) {
1604
1619
  getArgumentCompletions: completeFrom(modeChoices),
1605
1620
  handler: async (args, ctx) => {
1606
1621
  const name = String(args ?? "").trim().toLowerCase();
1607
- if (name && !MODE_ARGS[name]) return void ctx.ui.notify?.(t("Use /modo perguntar, /modo editar ou /modo plano", "Usa /modo preguntar, /modo editar o /modo plan", "Use /modo ask, /modo edit or /modo plan"), "warning");
1608
- setMode(ctx, name ? MODE_ARGS[name] : nextMode());
1622
+ if (name && !MODE_ARGS[name]) return void ctx.ui.notify?.(t("Use /modo perguntar, editar, plano ou tudo", "Usa /modo preguntar, editar, plan o todo", "Use /modo ask, edit, plan or all"), "warning");
1623
+ await setMode(ctx, name ? MODE_ARGS[name] : nextMode());
1609
1624
  },
1610
1625
  });
1611
1626
  command("help", t("Paleta de comandos (ctrl+p)", "Paleta de comandos (ctrl+p)", "Command palette (ctrl+p)"), async (_args, ctx) => openPalette(pink, ctx));
@@ -133,9 +133,33 @@ export function parseDuckDuckGo(html, limit = 8) {
133
133
  return results;
134
134
  }
135
135
 
136
+ // wigolo (servidor de busca que a pessoa roda na própria máquina, vários buscadores, sem chave): usado só quando já está no ar
137
+ export const WIGOLO_URL = "http://127.0.0.1:3333/v1/search";
138
+
139
+ // null = sem wigolo, resposta que não é dele ou sem resultado: quem chama cai no DuckDuckGo
140
+ async function wigoloSearch(query, { fetchImpl, signal, timeoutMs }) {
141
+ try {
142
+ const res = await fetchImpl(WIGOLO_URL, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ query, max_results: 8 }), redirect: "manual", signal: signalFor(signal, timeoutMs) });
143
+ if (!res.ok) return null;
144
+ const found = JSON.parse((await readCapped(res)).text)?.results;
145
+ if (!Array.isArray(found)) return null;
146
+ const line = (s, max) => String(s ?? "").replace(/\s+/g, " ").trim().slice(0, max);
147
+ const results = found.filter((r) => /^https?:\/\//i.test(r?.url ?? "") && r?.title).slice(0, 8)
148
+ .map((r) => ({ title: line(r.title, 200), url: line(r.url, 2000), snippet: line(r.snippet || r.excerpt, 400) }));
149
+ return results.length ? results : null;
150
+ } catch { return null; }
151
+ }
152
+
153
+ const searchAnswer = (query, results, engine) => {
154
+ const text = `${OUTSIDE}\nBusca: ${query}\n\n${results.map((r, i) => `${i + 1}. ${r.title}\n ${r.url}${r.snippet ? `\n ${r.snippet}` : ""}`).join("\n")}`;
155
+ return { content: [{ type: "text", text }], details: { ok: true, query, engine, results } };
156
+ };
157
+
136
158
  export async function webSearch(query, { fetchImpl = fetch, signal, timeoutMs = FETCH_TIMEOUT_MS } = {}) {
137
159
  const q = String(query ?? "").trim();
138
160
  if (!q) return fail(t("Busca vazia", "Búsqueda vacía", "Empty search"));
161
+ const local = await wigoloSearch(q, { fetchImpl, signal, timeoutMs });
162
+ if (local) return searchAnswer(q, local, "wigolo");
139
163
  let res, html;
140
164
  try {
141
165
  res = await fetchImpl(`https://html.duckduckgo.com/html/?q=${encodeURIComponent(q)}`, { headers: { "user-agent": UA }, signal: signalFor(signal, timeoutMs) });
@@ -144,8 +168,7 @@ export async function webSearch(query, { fetchImpl = fetch, signal, timeoutMs =
144
168
  if (!res.ok) return fail(t(`O buscador respondeu ${res.status}; tente de novo mais tarde ou abra uma página conhecida com web_fetch`, `El buscador respondió ${res.status}; intenta de nuevo más tarde o abre una página conocida con web_fetch`, `The search engine responded ${res.status}; try again later or open a known page with web_fetch`));
145
169
  const results = parseDuckDuckGo(html);
146
170
  if (!results.length) return fail(/anomaly|captcha|challenge/i.test(html) ? t("O buscador pediu verificação de robô; abra uma página conhecida com web_fetch", "El buscador pidió verificación de robot; abre una página conocida con web_fetch", "The search engine asked for a robot check; open a known page with web_fetch") : t(`Nenhum resultado para: ${q}`, `Ningún resultado para: ${q}`, `No results for: ${q}`));
147
- const text = `${OUTSIDE}\nBusca: ${q}\n\n${results.map((r, i) => `${i + 1}. ${r.title}\n ${r.url}${r.snippet ? `\n ${r.snippet}` : ""}`).join("\n")}`;
148
- return { content: [{ type: "text", text }], details: { ok: true, query: q, results } };
171
+ return searchAnswer(q, results, "duckduckgo");
149
172
  }
150
173
 
151
174
  export function webExtension(pink, deps = {}) {
@@ -162,7 +185,7 @@ export function webExtension(pink, deps = {}) {
162
185
  pink.registerTool({
163
186
  name: "web_search",
164
187
  label: t("Buscar na web", "Buscar en la web", "Search the web"),
165
- description: "Search the web (DuckDuckGo, no key) and return titles, links and snippets. Use web_fetch to read a result.",
188
+ description: "Search the web (the local wigolo server when running, else DuckDuckGo; no key) and return titles, links and snippets. Use web_fetch to read a result.",
166
189
  parameters: one("query", "What to search for"),
167
190
  exposure: "codemode",
168
191
  annotations,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@thothdev/pink",
3
- "version": "1.0.23",
3
+ "version": "1.0.29",
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": {