@thothdev/pink 1.0.15 → 1.0.23

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") {
@@ -425,12 +466,15 @@ export function acpModels(session: any): ModelChoice[] {
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
468
  export type Resume = { id?: string; keep?: boolean; live?: AcpConn };
428
- export function closeKept(resume?: Resume) {
469
+ // `force` (Esc): um agente preso (ex.: opencode esperando um subagente que não abre) ignora o fim da entrada, e no Windows
470
+ // 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
+ export function closeKept(resume?: Resume, force = false, kill: typeof spawn = spawn) {
429
472
  const conn = resume?.live;
430
473
  if (resume) resume.live = undefined;
431
474
  if (!conn) return;
432
475
  try {
433
476
  conn.child.stdin?.end?.(); // fim da entrada: o agente sai sozinho (o kill do .cmd do npm pega só o shell)
477
+ if (force && process.platform === "win32" && conn.child.pid) kill("taskkill", ["/PID", String(conn.child.pid), "/T", "/F"], { stdio: "ignore", windowsHide: true }).on?.("error", () => undefined);
434
478
  conn.child.kill();
435
479
  } catch {
436
480
  /* já saiu */
@@ -480,14 +524,17 @@ export function warmKept(agent: ExternalAgent, cwd: string, resume: Resume, star
480
524
  async function runAcpKept(agent: ExternalAgent, task: string, cwd: string, signal: AbortSignal | undefined, result: any, emit: () => void, start: typeof spawn, ask: () => Ask | undefined, resume: Resume): Promise<any> {
481
525
  const conn = openKept(agent, cwd, start, resume);
482
526
  let aborted = false;
527
+ let release: (code: number) => void = () => undefined;
528
+ const released = new Promise<number>((resolve) => (release = resolve));
483
529
  const stop = () => {
484
530
  aborted = true;
485
- closeKept(resume); // a próxima mensagem abre de novo e retoma a sessão pelo id
531
+ closeKept(resume, true); // a próxima mensagem abre de novo e retoma a sessão pelo id
532
+ release(1); // o Esc solta já, sem esperar o processo fechar os pipes
486
533
  };
487
534
  if (signal?.aborted) stop();
488
535
  else signal?.addEventListener?.("abort", stop, { once: true });
489
536
  try {
490
- result.exitCode = aborted ? 1 : await runAcp(conn.child, agent.name, task, cwd, result, emit, ask, conn.exited, resume, agent.model, agent.extras, conn);
537
+ result.exitCode = aborted ? 1 : await Promise.race([runAcp(conn.child, agent.name, task, cwd, result, emit, ask, conn.exited, resume, agent.model, agent.extras, conn), released]);
491
538
  } finally {
492
539
  signal?.removeEventListener?.("abort", stop);
493
540
  }
@@ -518,7 +565,7 @@ export async function runExternal(agent: ExternalAgent, task: string, cwd: strin
518
565
  if (agent.extras.mcp.pink) extra.push("--allowedTools", "mcp__pink__pink_tarefa,mcp__pink__pink_tela"); // a tela confirma cada ação no Pink
519
566
  extra.push("--append-system-prompt-file", rulesFile);
520
567
  }
521
- 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;
568
+ 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;
522
569
  const child = spawnAgent(agent, args, cwd, start);
523
570
  if (scratch) {
524
571
  const dir = scratch;
@@ -588,15 +635,23 @@ const failed = (result: any, name: string, message: string) => {
588
635
  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> {
589
636
  let done: (code: number) => void = () => {};
590
637
  const finished = new Promise<number>((resolve) => (done = resolve));
638
+ let main: string | undefined; // a conversa pedida; os subagentes do Codex rodam em outras
591
639
  const client = rpc(
592
640
  child,
593
641
  "codex",
594
642
  (method, params) => {
595
- if (method === "item/completed") applyCodexItem(params?.item, result, emit);
596
- else if (method === "item/started" && params?.item?.type === "collabAgentToolCall") applyCodexItem(params.item, result, emit); // o subagente aparece ao nascer
643
+ const mine = !main || !params?.threadId || params.threadId === main; // o que chega dos subagentes não vira "ao vivo"
644
+ if (method === "item/completed") {
645
+ if (mine) result.partial = undefined;
646
+ applyCodexItem(params?.item, result, emit);
647
+ } 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
648
+ else if (method === "item/agentMessage/delta") mine && partial(result, "text", params?.delta);
649
+ else if (method === "item/reasoning/summaryTextDelta" || method === "item/reasoning/textDelta") mine && partial(result, "thinking", params?.delta);
597
650
  else if (method === "thread/tokenUsage/updated") codexUsage(params?.tokenUsage, result);
598
651
  else if (method === "error" && params?.error?.message) result.errorMessage = String(params.error.message);
599
652
  else if (method === "turn/completed") {
653
+ // o fim de um subagente fecha a linha dele, não o pedido
654
+ if (main && params?.threadId && params.threadId !== main) return void (subagentEnd(result, String(params.threadId), params.turn?.status === "failed") && emit());
600
655
  const turn = params?.turn ?? {};
601
656
  if (turn.status === "failed" || turn.status === "interrupted") done(failed(result, "codex", String(turn.error?.message ?? result.errorMessage ?? turn.status)));
602
657
  else {
@@ -637,6 +692,7 @@ async function runCodex(child: any, task: string, cwd: string, result: any, emit
637
692
  if (thread.error) return failed(result, "codex", String(thread.error.message ?? "thread/start falhou"));
638
693
  if (typeof thread.result?.model === "string") result.model = thread.result.model;
639
694
  if (resume && thread.result?.thread?.id) resume.id = thread.result.thread.id;
695
+ main = thread.result?.thread?.id;
640
696
  const turn = await client.request("turn/start", { threadId: thread.result?.thread?.id, input: [{ type: "text", text: task, text_elements: [] }], ...(effort ? { effort } : {}) });
641
697
  if (turn.error) return failed(result, "codex", String(turn.error.message ?? "turn/start falhou"));
642
698
  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)}` : ""}`)))]);
@@ -58,7 +58,7 @@ 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
62
  return hits.length ? hits.map((choice) => ({ label: choice.value, ...choice })) : null;
63
63
  };
64
64
  export async function choose(ctx: any, title: string, choices: Choice[]): Promise<string | undefined> {
@@ -70,6 +70,27 @@ export async function choose(ctx: any, title: string, choices: Choice[]): Promis
70
70
  return at < 0 ? undefined : choices[at].value;
71
71
  }
72
72
 
73
+ // argumento que o comando não conhece: dizer o que vale, nunca fazer outra coisa calado (owner 2026-11-27)
74
+ export function unknown(ctx: any, command: string, typed: string, choices: Choice[]) {
75
+ const list = choices.map((choice) => (choice.description ? `${choice.value} (${choice.description})` : choice.value)).join(", ");
76
+ 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");
77
+ }
78
+ export const noArgs = (command: string, handler: (args: any, ctx: any) => any) => async (args: any, ctx: any) => {
79
+ const typed = String(args ?? "").trim();
80
+ 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");
81
+ return handler(args, ctx);
82
+ };
83
+
84
+ // comandos do motor que não aceitam argumento: com um texto depois, o motor manda a linha ao modelo como mensagem
85
+ // shortcut: lista fixa; um comando novo do motor sem argumento entra aqui
86
+ const BARE_BUILTINS = /^\/(resume|settings|logout|tree|fork|session|scoped-models|trust)[ \t]+\S[^\n]*$/;
87
+ export function builtinWithArgs(event: any, ctx: any) {
88
+ const name = event?.source === "extension" ? undefined : BARE_BUILTINS.exec(String(event?.text ?? "").trim())?.[1];
89
+ if (!name) return { action: "continue" };
90
+ 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");
91
+ return { action: "handled" };
92
+ }
93
+
73
94
  // para os patches do motor (rebrand.json), que não importam módulos: globalThis.__pinkT(pt, es, en)
74
95
  (globalThis as any).__pinkT = t;
75
96
  (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, 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,12 +400,19 @@ 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;
360
407
  const started = Date.now();
361
- const message = () => workingLabel({ ms: Date.now() - started, output: output() });
408
+ // sem token novo por muito tempo, o "Trabalhando" contava igual e não dava para saber se o agente tinha travado
409
+ // (owner 2026-11-26: o OpenCode ficou 30 min esperando um stream que nunca veio)
410
+ let seen = -1, since = started;
411
+ const message = () => {
412
+ const now = Date.now(), out = output();
413
+ if (out !== seen) (seen = out), (since = now);
414
+ return workingLabel({ ms: now - started, output: out }) + stallNote(now - since);
415
+ };
362
416
  (globalThis as any).__pinkAgentBusy = true; // a caixa mostra "esc interromper · ctrl+enter envia agora" (pink-ui)
363
417
  // a área dos widgets já deixa uma linha em branco antes: a linha vazia do topo do Loader sai
364
418
  if (tui?.Loader) {
@@ -367,12 +421,12 @@ export default function (pink: any, list: typeof externalAgents = externalAgents
367
421
  loader?.stop?.(); // a fábrica pode ser chamada de novo: o Loader anterior para de girar
368
422
  loader = new tui.Loader(screen, (s: string) => theme.fg("accent", s), (s: string) => theme.fg("muted", s), message());
369
423
  const own = loader;
370
- 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?.() };
371
425
  }, { placement: "aboveEditor" });
372
426
  ticker = setInterval(() => loader?.setMessage?.(message()), 1000);
373
427
  } else {
374
428
  let frame = 0;
375
- 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" });
376
430
  draw();
377
431
  ticker = setInterval(() => (frame++, draw()), 120);
378
432
  }
@@ -424,6 +478,13 @@ export default function (pink: any, list: typeof externalAgents = externalAgents
424
478
  active.controller.abort();
425
479
  return true;
426
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
+ };
427
488
  const stop = (ctx?: any) => {
428
489
  (ctx?.ui ?? lastUi)?.setWidget?.(QUEUE, undefined); // fila de versões antigas do widget (a de agora some junto com o agente)
429
490
  if (active) active.queue = []; // a fila é descartada junto
@@ -539,7 +600,7 @@ export default function (pink: any, list: typeof externalAgents = externalAgents
539
600
  ctx.ui?.setStatus?.(STATUS, `${name} ${t("trabalhando", "trabajando", "working")}${last ? `: ${last}` : "…"}`);
540
601
  };
541
602
  status();
542
- if (ctx.hasUI) busy(ctx.ui, () => outputOf(result));
603
+ if (ctx.hasUI) busy(ctx.ui, () => outputOf(result), (width) => liveLines(result, width, ctx.cwd));
543
604
  if (ctx.hasUI) watchChildren(ctx.ui);
544
605
  (globalThis as any).__pinkExternalAsk = ctx.hasUI ? (title: string, body: string) => ctx.ui.confirm(title, body) : undefined;
545
606
  try {
@@ -548,6 +609,8 @@ export default function (pink: any, list: typeof externalAgents = externalAgents
548
609
  result.stopReason = "error";
549
610
  result.errorMessage = controller.signal.aborted ? t("cancelado", "cancelado", "cancelled") : String(error?.message ?? error);
550
611
  }
612
+ // acabou a mensagem: subagente sem aviso de fim não pode ficar "rodando" para sempre
613
+ for (const id of Object.keys(result.subagents ?? {})) subagentEnd(result, id, result.stopReason === "error");
551
614
  if (current.controller === controller) current.controller = undefined;
552
615
  if (active === current || !active) idle();
553
616
  Reflect.get(globalThis, "__pinkTela")?.hide?.(); // o agente terminou: apaga o contorno da tela
@@ -557,7 +620,7 @@ export default function (pink: any, list: typeof externalAgents = externalAgents
557
620
  if (!current.agent.model && result.model && result.model !== name) (globalThis as any).__pinkExternalAgent = { name, model: result.model, effort: current.agent.effort };
558
621
  }
559
622
  const error = result.stopReason === "error" ? String(result.errorMessage ?? t("erro", "error", "error")) : undefined;
560
- 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) } });
623
+ 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) } });
561
624
  pink.events?.emit?.("pink:agent_settled", { ctx, aborted: controller.signal.aborted });
562
625
  // trocaram o modelo do Pink no meio: o que o agente fez já está na sessão; o novo modelo continua o pedido
563
626
  if (current.handoff) return void pink.sendUserMessage?.(handoffText(name, [text, ...current.handoff]));
@@ -572,6 +635,7 @@ export default function (pink: any, list: typeof externalAgents = externalAgents
572
635
 
573
636
  // "/agente " lista as opções, como os outros comandos: off e os agentes; "/agente codex " lista os modelos dele
574
637
  const modelCache = new Map<string, Promise<any[]>>();
638
+ 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.");
575
639
  const completions = async (prefix: string) => {
576
640
  const text = String(prefix ?? "").replace(/^\s+/, "");
577
641
  const space = text.indexOf(" ");
@@ -581,6 +645,7 @@ export default function (pink: any, list: typeof externalAgents = externalAgents
581
645
  ...(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)`) }] : []),
582
646
  ...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`) })),
583
647
  ];
648
+ if (!agents.length && !text) items.push({ value: "", label: t("nenhum agente instalado", "ningún agente instalado", "no agent installed"), description: INSTALL() });
584
649
  const hits = items.filter((item) => item.value.startsWith(text.toLowerCase()));
585
650
  return hits.length ? hits : null;
586
651
  }
@@ -618,7 +683,7 @@ export default function (pink: any, list: typeof externalAgents = externalAgents
618
683
  }
619
684
  let name = wanted;
620
685
  if (!name) {
621
- 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");
686
+ 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");
622
687
  // com um agente ligado, o primeiro item volta ao modelo/provedor do Pink (o mesmo que /agente off)
623
688
  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;
624
689
  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)) ?? "") : "";
@@ -630,9 +695,9 @@ export default function (pink: any, list: typeof externalAgents = externalAgents
630
695
  }
631
696
  }
632
697
  const agent = agents.find((item) => item.name === name);
633
- 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");
634
- 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");
635
- 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");
698
+ 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");
699
+ 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");
700
+ 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");
636
701
  if (!model && ctx.hasUI) {
637
702
  // menu com os modelos que o agente informa; o primeiro item mantém o padrão dele
638
703
  ctx.ui?.setStatus?.(STATUS, t(`${name}: buscando modelos…`, `${name}: buscando modelos…`, `${name}: fetching models…`));
@@ -679,6 +744,41 @@ export default function (pink: any, list: typeof externalAgents = externalAgents
679
744
  },
680
745
  });
681
746
 
747
+ // /esforco: troca o esforço do agente ligado sem abrir outra conversa. claude e codex sobem um processo por mensagem,
748
+ // então o novo nível já vale na próxima; os demais agentes não informam níveis
749
+ const effortsOf = async (agent: any, cwd: string): Promise<string[]> => {
750
+ const choices: any[] = await models(agent, cwd).catch(() => []);
751
+ const chosen = choices.find((choice) => choice.id === agent.model) ?? (agent.model ? undefined : choices.find((choice) => choice.current));
752
+ return chosen?.efforts ?? [];
753
+ };
754
+ pink.registerCommand("esforco", {
755
+ 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"),
756
+ getArgumentCompletions: async (prefix: string) => {
757
+ if (!active) return null;
758
+ const typed = String(prefix ?? "").trim().toLowerCase();
759
+ const hits = (await effortsOf(active.agent, process.cwd())).filter((level) => level.startsWith(typed)).map((level) => ({ value: level, label: level }));
760
+ return hits.length ? hits : null;
761
+ },
762
+ handler: async (args: string, ctx: any) => {
763
+ 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");
764
+ const current = active;
765
+ const name = current.agent.name;
766
+ const levels = await effortsOf(current.agent, ctx.cwd);
767
+ 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");
768
+ let level = String(args ?? "").trim().toLowerCase();
769
+ if (!level) {
770
+ 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
771
+ if (!level) return;
772
+ }
773
+ if (!levels.includes(level)) return unknown(ctx, "/esforco", level, levels.map((value) => ({ value })));
774
+ if (active !== current) return; // trocaram ou desligaram o agente com o menu aberto
775
+ current.agent = { ...current.agent, effort: level };
776
+ (globalThis as any).__pinkExternalAgent = { name, model: current.agent.model, effort: level };
777
+ ctx.ui?.setStatus?.(STATUS, `${t("agente", "agente", "agent")}: ${label(current.agent)}`);
778
+ 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");
779
+ },
780
+ });
781
+
682
782
  pink.on("input", async (event: any, ctx: any) => {
683
783
  if (!active || event.source === "extension" || String(event.text ?? "").trimStart().startsWith("/")) return { action: "continue" };
684
784
  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
 
@@ -58,7 +58,7 @@ 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
62
  return hits.length ? hits.map((choice) => ({ label: choice.value, ...choice })) : null;
63
63
  };
64
64
  export async function choose(ctx: any, title: string, choices: Choice[]): Promise<string | undefined> {
@@ -70,6 +70,27 @@ export async function choose(ctx: any, title: string, choices: Choice[]): Promis
70
70
  return at < 0 ? undefined : choices[at].value;
71
71
  }
72
72
 
73
+ // argumento que o comando não conhece: dizer o que vale, nunca fazer outra coisa calado (owner 2026-11-27)
74
+ export function unknown(ctx: any, command: string, typed: string, choices: Choice[]) {
75
+ const list = choices.map((choice) => (choice.description ? `${choice.value} (${choice.description})` : choice.value)).join(", ");
76
+ 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");
77
+ }
78
+ export const noArgs = (command: string, handler: (args: any, ctx: any) => any) => async (args: any, ctx: any) => {
79
+ const typed = String(args ?? "").trim();
80
+ 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");
81
+ return handler(args, ctx);
82
+ };
83
+
84
+ // comandos do motor que não aceitam argumento: com um texto depois, o motor manda a linha ao modelo como mensagem
85
+ // shortcut: lista fixa; um comando novo do motor sem argumento entra aqui
86
+ const BARE_BUILTINS = /^\/(resume|settings|logout|tree|fork|session|scoped-models|trust)[ \t]+\S[^\n]*$/;
87
+ export function builtinWithArgs(event: any, ctx: any) {
88
+ const name = event?.source === "extension" ? undefined : BARE_BUILTINS.exec(String(event?.text ?? "").trim())?.[1];
89
+ if (!name) return { action: "continue" };
90
+ 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");
91
+ return { action: "handled" };
92
+ }
93
+
73
94
  // para os patches do motor (rebrand.json), que não importam módulos: globalThis.__pinkT(pt, es, en)
74
95
  (globalThis as any).__pinkT = t;
75
96
  (globalThis as any).__pinkLang = lang;
@@ -3,7 +3,7 @@
3
3
  // /loop confere o deploy sem intervalo: o agente escolhe o ritmo chamando schedule_wakeup ao fim de cada rodada
4
4
  // /loop parar ou Esc encerra; /loop sozinho mostra o loop ativo
5
5
  // Tudo vive em timers desta sessão: fechar, trocar ou recarregar (session_shutdown) cancela; nada fica agendado fora dela.
6
- import { t } from "./pink-i18n.ts";
6
+ import { completeFrom, t } from "./pink-i18n.ts";
7
7
  import { Type } from "typebox";
8
8
 
9
9
  export const MIN_SECONDS = 60;
@@ -186,7 +186,10 @@ export default function (pink: any) {
186
186
  pink.on("session_shutdown", () => loop.shutdown());
187
187
  pink.registerCommand("loop", {
188
188
  description: t("Repete uma tarefa: /loop 5m <tarefa> (intervalo fixo), /loop <tarefa> (o agente escolhe o ritmo), /loop parar", "Repite una tarea: /loop 5m <tarea> (intervalo fijo), /loop <tarea> (el agente elige el ritmo), /loop parar", "Repeats a task: /loop 5m <task> (fixed interval), /loop <task> (the agent picks the pace), /loop stop"),
189
- getArgumentCompletions: (prefix: string) => ("parar".startsWith(prefix) ? [{ value: "parar", label: "parar" }] : null),
189
+ getArgumentCompletions: completeFrom(() => [
190
+ { value: "5m ", label: t("5m <tarefa>", "5m <tarea>", "5m <task>"), description: t("repete a cada 5 min; sem tempo (/loop <tarefa>) o agente escolhe o ritmo", "repite cada 5 min; sin tiempo (/loop <tarea>) el agente elige el ritmo", "repeats every 5 min; without a time (/loop <task>) the agent picks the pace") },
191
+ { value: "parar", description: t("encerra o loop", "termina el loop", "ends the loop") },
192
+ ]),
190
193
  handler: async (args: string, ctx: any) => loop.start(args ?? "", ctx),
191
194
  });
192
195
  }
@@ -15,7 +15,7 @@ const depth = Number(process.env.PINK_MCP_DEPTH || 0);
15
15
 
16
16
  const TOOL = {
17
17
  name: "pink_tarefa",
18
- description: "Entrega uma tarefa ao Pink (agente do Thoth nesta máquina) e devolve a resposta dele. Use para o que só o Pink tem: a memória do Pink, os subagentes do Pink e os MCPs dele. Para a tela do PC use pink_tela (quando existir), não esta. Escreva a tarefa completa: o Pink não vê esta conversa.",
18
+ description: "Entrega uma tarefa ao Pink (outro agente nesta máquina) e devolve a resposta dele. Use para o que só o Pink tem: a memória do Pink, os subagentes do Pink e os MCPs dele. Para a tela do PC use pink_tela (quando existir), não esta. Escreva a tarefa completa: o Pink não vê esta conversa.",
19
19
  inputSchema: { type: "object", properties: { tarefa: { type: "string", description: "O que o Pink deve fazer, com todo o contexto necessário." }, pasta: { type: "string", description: "Pasta de trabalho (padrão: a pasta atual)." } }, required: ["tarefa"] },
20
20
  };
21
21