@thothdev/pink 1.0.16 → 1.0.27

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -58,7 +58,9 @@ export function t(pt: string, es: string, en: string): string {
58
58
  export type Choice = { value: string; label?: string; description?: string };
59
59
  export const completeFrom = (choices: () => Choice[]) => (prefix: string) => {
60
60
  const typed = String(prefix ?? "").trimStart().toLowerCase();
61
- const hits = choices().filter((choice) => choice.value.startsWith(typed));
61
+ const hits = choices().filter((choice) => choice.value.toLowerCase().startsWith(typed));
62
+ // palavra já completa (só ela casa): sem lista aberta, o Enter roda o comando em vez de só aceitar a sugestão (Tifa, 2026-11-27)
63
+ if (hits.length === 1 && hits[0].value.toLowerCase() === typed) return null;
62
64
  return hits.length ? hits.map((choice) => ({ label: choice.value, ...choice })) : null;
63
65
  };
64
66
  export async function choose(ctx: any, title: string, choices: Choice[]): Promise<string | undefined> {
@@ -70,6 +72,27 @@ export async function choose(ctx: any, title: string, choices: Choice[]): Promis
70
72
  return at < 0 ? undefined : choices[at].value;
71
73
  }
72
74
 
75
+ // argumento que o comando não conhece: dizer o que vale, nunca fazer outra coisa calado (owner 2026-11-27)
76
+ export function unknown(ctx: any, command: string, typed: string, choices: Choice[]) {
77
+ const list = choices.map((choice) => (choice.description ? `${choice.value} (${choice.description})` : choice.value)).join(", ");
78
+ ctx?.ui?.notify?.(t(`${command}: "${typed}" não é uma opção. Opções: ${list}.`, `${command}: "${typed}" no es una opción. Opciones: ${list}.`, `${command}: "${typed}" is not an option. Options: ${list}.`), "warning");
79
+ }
80
+ export const noArgs = (command: string, handler: (args: any, ctx: any) => any) => async (args: any, ctx: any) => {
81
+ const typed = String(args ?? "").trim();
82
+ if (typed) return void ctx?.ui?.notify?.(t(`${command} não tem opções ("${typed}" não vale). Use só ${command}.`, `${command} no tiene opciones ("${typed}" no vale). Usa solo ${command}.`, `${command} takes no options ("${typed}" is not valid). Use just ${command}.`), "warning");
83
+ return handler(args, ctx);
84
+ };
85
+
86
+ // comandos do motor que não aceitam argumento: com um texto depois, o motor manda a linha ao modelo como mensagem
87
+ // shortcut: lista fixa; um comando novo do motor sem argumento entra aqui
88
+ const BARE_BUILTINS = /^\/(resume|settings|logout|tree|fork|session|scoped-models|trust)[ \t]+\S[^\n]*$/;
89
+ export function builtinWithArgs(event: any, ctx: any) {
90
+ const name = event?.source === "extension" ? undefined : BARE_BUILTINS.exec(String(event?.text ?? "").trim())?.[1];
91
+ if (!name) return { action: "continue" };
92
+ ctx?.ui?.notify?.(t(`/${name} não tem opções: nada foi enviado ao modelo. Use só /${name}.`, `/${name} no tiene opciones: no se envió nada al modelo. Usa solo /${name}.`, `/${name} takes no options: nothing was sent to the model. Use just /${name}.`), "warning");
93
+ return { action: "handled" };
94
+ }
95
+
73
96
  // para os patches do motor (rebrand.json), que não importam módulos: globalThis.__pinkT(pt, es, en)
74
97
  (globalThis as any).__pinkT = t;
75
98
  (globalThis as any).__pinkLang = lang;
@@ -3,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
 
@@ -5,7 +5,7 @@
5
5
  // atualiza, lê, lista e apaga; texto com cara de segredo é recusado. O AGENTS.md é da pessoa e fica de fora.
6
6
  // Pasta não confiável: nem entra no prompt nem grava (Argus A1: repositório estranho induziria o agente a guardar
7
7
  // instruções que voltariam no prompt de sistema de toda sessão). Subagente não lê nem grava.
8
- import { type Choice, choose, completeFrom, t } from "./pink-i18n.ts";
8
+ import { type Choice, choose, completeFrom, t, unknown } from "./pink-i18n.ts";
9
9
 
10
10
  const MEMORY_CHOICES = (): Choice[] => [
11
11
  { value: "mostrar", description: t("a pasta e o índice (MEMORY.md)", "la carpeta y el índice (MEMORY.md)", "the folder and the index (MEMORY.md)") },
@@ -233,6 +233,7 @@ export default function (pink: any) {
233
233
  ctx.ui.notify(t(`Abrindo ${dir}`, `Abriendo ${dir}`, `Opening ${dir}`), "info");
234
234
  return;
235
235
  }
236
+ if (verb && !["mostrar", "show"].includes(verb)) return unknown(ctx, "/memoria", verb, MEMORY_CHOICES());
236
237
  const off = isTrusted(ctx) ? "" : `\n\n${UNTRUSTED}`;
237
238
  ctx.ui.notify(`${t("Pasta", "Carpeta", "Folder")}: ${memoryDir(here)}${off}\n\n${readIndex(here) || t("Nenhuma memória neste projeto.", "Ninguna memoria en este proyecto.", "No memories in this project.")}`, "info");
238
239
  },
@@ -11,7 +11,7 @@ import { createRequire } from "node:module";
11
11
  import os from "node:os";
12
12
  import path from "node:path";
13
13
  import { fileURLToPath } from "node:url";
14
- import { type Choice, choose, completeFrom, t } from "./pink-i18n.ts";
14
+ import { type Choice, choose, completeFrom, t, unknown } from "./pink-i18n.ts";
15
15
 
16
16
  export const MODEL = {
17
17
  name: "sherpa-onnx-nemo-parakeet-tdt-0.6b-v3-int8",
@@ -380,6 +380,7 @@ export default function (pink: any) {
380
380
  const done = await install({ progress: (text) => ctx.ui.notify(text, "info") });
381
381
  return ctx.ui.notify(done, installed() ? "info" : "error");
382
382
  }
383
+ if (verb && !["status", "estado"].includes(verb)) return unknown(ctx, "/microfone", verb, MIC_CHOICES());
383
384
  const view = microfone.view();
384
385
  ctx.ui.notify(
385
386
  view.installed
@@ -5,7 +5,7 @@
5
5
  // - Headroom: o MCP da máquina (127.0.0.1:8789), só se ele se apresentar como headroom;
6
6
  // - graphify: o MCP do grafo do projeto (graphify-out/graph.json), só em pasta confiável.
7
7
  // Tudo falha aberto: sem a ferramenta, o Pink segue igual.
8
- import { t } from "./pink-i18n.ts";
8
+ import { noArgs, t } from "./pink-i18n.ts";
9
9
  import fs from "node:fs";
10
10
  import os from "node:os";
11
11
  import path from "node:path";
@@ -171,7 +171,7 @@ export async function natives(pink, deps) {
171
171
 
172
172
  pink.registerCommand?.("ferramentas", {
173
173
  description: t("Liga ou desliga as ferramentas opcionais (Ponytail, RTK, Headroom, graphify)", "Activa o desactiva las herramientas opcionales (Ponytail, RTK, Headroom, graphify)", "Turns the optional tools on or off (Ponytail, RTK, Headroom, graphify)"),
174
- handler: async (_args, ctx) => {
174
+ handler: noArgs("/ferramentas", async (_args, ctx) => {
175
175
  // a sonda do Headroom (até 1,5 s) roda uma vez por abertura do menu, não a cada Enter
176
176
  const headroomOnline = await installed.headroom();
177
177
  for (;;) {
@@ -197,7 +197,7 @@ export async function natives(pink, deps) {
197
197
  if (id === "graphify") syncGraphify(ctx);
198
198
  if (id === "ponytail") ctx.ui.notify?.(t("O Ponytail liga ou desliga depois do /reload", "Ponytail se activa o desactiva después de /reload", "Ponytail turns on or off after /reload"), "info");
199
199
  }
200
- },
200
+ }),
201
201
  });
202
202
  return { report, headroomDone, file };
203
203
  }
@@ -3,7 +3,7 @@
3
3
  // WezTerm, Ghostty). Terminal que nunca avisou foco: notifica só pedido longo (>= 20 s).
4
4
  // Windows: toast do sistema (pelo PowerShell). macOS: osascript. Linux: notify-send; sem ele, OSC 777.
5
5
  // Desligar: /notificacoes (fica salvo em <pasta do agente>/pink-notify.json) ou PINK_NOTIFY=0. Subagente não notifica.
6
- import { t } from "./pink-i18n.ts";
6
+ import { noArgs, t } from "./pink-i18n.ts";
7
7
  import { execFile } from "node:child_process";
8
8
  import fs from "node:fs";
9
9
  import os from "node:os";
@@ -98,11 +98,11 @@ export function notifyExtension(pink, deps = {}) {
98
98
  pink.events?.on?.("pink:agent_settled", (data) => settled(data, data?.ctx));
99
99
  pink.registerCommand?.("notificacoes", {
100
100
  description: t("Liga ou desliga a notificação do sistema quando o Pink termina e a janela está sem foco", "Activa o desactiva la notificación del sistema cuando Pink termina y la ventana no tiene el foco", "Turns the system notification on or off when Pink finishes and the window is not focused"),
101
- handler: async (_args, ctx) => {
101
+ handler: noArgs("/notificacoes", async (_args, ctx) => {
102
102
  on = !on;
103
103
  try { mkdir(path.dirname(file), { recursive: true }); write(file, `${JSON.stringify({ on }, null, 2)}\n`); } catch (error) { ctx.ui.notify?.(t(`Não deu para salvar ${file}: ${error?.message ?? error}`, `No se pudo guardar ${file}: ${error?.message ?? error}`, `Could not save ${file}: ${error?.message ?? error}`), "error"); }
104
104
  ctx.ui.notify?.(on ? t("Notificações ligadas", "Notificaciones activadas", "Notifications on") : t("Notificações desligadas", "Notificaciones desactivadas", "Notifications off"), "info");
105
- },
105
+ }),
106
106
  });
107
107
  // /sugestao [texto]: abre a página de ideias do Pink no navegador, com o texto como título (owner 2026-11-23)
108
108
  pink.registerCommand?.("sugestao", {
@@ -11,7 +11,7 @@
11
11
  // - Limite de rede de segurança: gravar por bash (echo > .env, cp, sed -i) não passa pela proteção de arquivos, e
12
12
  // ofuscação ($(echo rm), eval) escapa do padrão. Isolamento de verdade é o sandbox do sistema, não isto.
13
13
  // - /permissoes mostra as regras em uso.
14
- import { t } from "./pink-i18n.ts";
14
+ import { noArgs, t } from "./pink-i18n.ts";
15
15
  import fs from "node:fs";
16
16
  import os from "node:os";
17
17
  import path from "node:path";
@@ -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)"),
235
- handler: async (_args, ctx) => {
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"),
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 = [
@@ -244,7 +262,7 @@ export function permissions(pink, deps = {}) {
244
262
  ...rules.errors.map((e) => `${t("Erro", "Error", "Error")}: ${e}`),
245
263
  ];
246
264
  ctx.ui.notify?.(lines.join("\n"), rules.errors.length ? "warning" : "info");
247
- },
265
+ }),
248
266
  });
249
267
  return { sessionAllowed };
250
268
  }
@@ -3,7 +3,7 @@
3
3
  // branch (commits e o que não foi commitado). O primeiro termo é sempre o branch. O diff vai para um arquivo temporário e o
4
4
  // agente principal chama o subagente "revisor", que só lê (read, grep, find, ls, sem MCP) e não vê a conversa.
5
5
  // Só em pasta confiável: o git lê a configuração do repositório e ela pode rodar programas (textconv, fsmonitor).
6
- import { t } from "./pink-i18n.ts";
6
+ import { completeFrom, t } from "./pink-i18n.ts";
7
7
  import { spawnSync } from "node:child_process";
8
8
  import fs from "node:fs";
9
9
  import os from "node:os";
@@ -40,18 +40,23 @@ export const cleanName = (name: string) => {
40
40
  return clean.length > MAX_NAME ? `${clean.slice(0, MAX_NAME)}…` : clean;
41
41
  };
42
42
 
43
+ const branches = (cwd: string, run: Git = git) => String(run(["for-each-ref", "--format=%(refname:short)", "refs/heads"], cwd).out ?? "").split(/\r?\n/).filter(Boolean);
44
+
43
45
  type Found = { error?: string; empty?: boolean; diff?: string; files?: string[]; extra?: number; label?: string; root?: string };
44
46
 
45
47
  export function collect(cwd: string, base: string | undefined, run: Git = git): Found {
46
48
  const top = run(["rev-parse", "--show-toplevel"], cwd);
47
- if (!top.ok) return { error: t("Esta pasta não é um repositório git.", "Esta carpeta no es un repositorio git.", "This folder is not a git repository.") };
49
+ if (!top.ok) return { error: t("Esta pasta não é um repositório git. Abra o Pink numa pasta com git (ou rode git init).", "Esta carpeta no es un repositorio git. Abre Pink en una carpeta con git (o ejecuta git init).", "This folder is not a git repository. Open Pink in a git folder (or run git init).") };
48
50
  const root = path.resolve(top.out.trim()); // caminhos do diff e do ls-files ficam relativos à raiz
49
51
  let from = "HEAD";
50
52
  let label = t("mudanças não commitadas", "cambios sin commit", "uncommitted changes");
51
53
  if (base) {
52
54
  if (!validRef(base)) return { error: t(`Referência inválida: ${base}`, `Referencia no válida: ${base}`, `Invalid reference: ${base}`) };
53
55
  const mergeBase = run(["merge-base", base, "HEAD"], root);
54
- if (!mergeBase.ok) return { error: t(`Não achei a base com ${base}: ${mergeBase.err || "referência desconhecida"}`, `No encontré la base con ${base}: ${mergeBase.err || "referencia desconocida"}`, `Could not find the base with ${base}: ${mergeBase.err || "unknown reference"}`) };
56
+ if (!mergeBase.ok) {
57
+ const valid = ["HEAD", ...branches(root, run)].slice(0, 20).join(", ");
58
+ return { error: t(`Não achei a base com ${base}: ${mergeBase.err || "referência desconhecida"}\nVale: /review, ou /review <branch> com ${valid}`, `No encontré la base con ${base}: ${mergeBase.err || "referencia desconocida"}\nVale: /review, o /review <rama> con ${valid}`, `Could not find the base with ${base}: ${mergeBase.err || "unknown reference"}\nValid: /review, or /review <branch> with ${valid}`) };
59
+ }
55
60
  from = mergeBase.out.trim();
56
61
  label = t(`mudanças desde ${base}`, `cambios desde ${base}`, `changes since ${base}`);
57
62
  } else if (!run(["rev-parse", "--verify", "--quiet", "HEAD"], root).ok) from = EMPTY_TREE;
@@ -99,8 +104,18 @@ export function sweepStale(tmp = os.tmpdir(), now = Date.now()) {
99
104
  export default function (pink: any) {
100
105
  if (process.env.PINK_SUBAGENT) return; // subagente não abre outro subagente
101
106
  const dirs: string[] = [];
102
- pink.on("session_start", async () => sweepStale());
107
+ let session: any;
108
+ pink.on("session_start", async (_event: any, ctx: any) => {
109
+ session = ctx;
110
+ sweepStale();
111
+ });
103
112
  pink.registerCommand("review", {
113
+ // HEAD primeiro: Enter na primeira sugestão continua sendo "só o não commitado"
114
+ getArgumentCompletions: (prefix: string) => {
115
+ if (session?.isProjectTrusted?.() !== true) return null;
116
+ const found = branches(session.cwd ?? process.cwd());
117
+ return completeFrom(() => [{ value: "HEAD", description: t("só o que não foi commitado", "solo lo no confirmado", "only uncommitted changes") }, ...found.map((name) => ({ value: name, description: t(`tudo desde ${name}`, `todo desde ${name}`, `everything since ${name}`) }))])(prefix);
118
+ },
104
119
  description: t("Revisão independente (subagente só leitura) do que não foi commitado, ou de tudo desde um branch: /review [branch] [foco]", "Revisión independiente (subagente solo lectura) de lo no confirmado, o de todo desde una rama: /review [rama] [foco]", "Independent review (read-only subagent) of uncommitted changes, or of everything since a branch: /review [branch] [focus]"),
105
120
  handler: async (args: string, ctx: any) => {
106
121
  if (ctx?.isProjectTrusted?.() !== true) return ctx.ui.notify(t("Pasta não confiável: o /review fica desligado (o git do projeto poderia rodar programas dele). Confie na pasta para usar.", "Carpeta no confiable: /review está desactivado (el git del proyecto podría ejecutar programas suyos). Confía en la carpeta para usarlo.", "Untrusted folder: /review is disabled (the project's git could run its programs). Trust the folder to use it."), "error");
@@ -2,7 +2,7 @@
2
2
  // com globs no frontmatter, em <pasta do agente>/rules (da pessoa) e em .pink/rules (do projeto, só em pasta confiável).
3
3
  // A regra entra no contexto uma vez por sessão, no resultado do read/write/edit de um arquivo que casa com o glob; assim o
4
4
  // AGENTS.md não cresce com instrução que só vale para um tipo de arquivo. /regras lista as regras e quais já entraram.
5
- import { t } from "./pink-i18n.ts";
5
+ import { noArgs, t } from "./pink-i18n.ts";
6
6
  import fs from "node:fs";
7
7
  import os from "node:os";
8
8
  import path from "node:path";
@@ -194,6 +194,6 @@ export default function (pink: any) {
194
194
  for (const name of ["session_start", "session_compact", "session_tree"]) pink.on(name, async () => rules.reset());
195
195
  pink.registerCommand("regras", {
196
196
  description: t("Lista as regras por tipo de arquivo (globs) e quais já entraram no contexto", "Lista las reglas por tipo de archivo (globs) y cuáles ya entraron en el contexto", "Lists the rules by file type (globs) and which ones are already in context"),
197
- handler: async (_args: string, ctx: any) => ctx.ui.notify(rules.list(ctx), "info"),
197
+ handler: noArgs("/regras", async (_args: string, ctx: any) => ctx.ui.notify(rules.list(ctx), "info")),
198
198
  });
199
199
  }
@@ -4,7 +4,7 @@
4
4
  // processo só grava onde o SID do Pink tem permissão (a pasta do projeto e um temporário próprio) ou onde Todos já gravam
5
5
  // (limite conhecido). Leitura e rede não mudam. O Job Object do helper mata a árvore inteira junto com ele.
6
6
  // Os comandos que a pessoa roda com ! não passam pelo sandbox: são dela. Linux e macOS ficam para depois.
7
- import { type Choice, choose, completeFrom, t } from "./pink-i18n.ts";
7
+ import { type Choice, choose, completeFrom, t, unknown } from "./pink-i18n.ts";
8
8
 
9
9
  const SANDBOX_CHOICES = (): Choice[] => [
10
10
  { value: "status", description: t("ligado ou desligado?", "¿activado o desactivado?", "on or off?") },
@@ -297,6 +297,7 @@ export default function (pink: any) {
297
297
  if (["ligar", "on", "activar"].includes(verb)) text = await sandbox.on(root, (note) => ctx.ui.notify(note, "info"));
298
298
  else if (["desligar", "off", "desactivar"].includes(verb)) text = sandbox.off();
299
299
  else if (["remover", "remove", "quitar"].includes(verb)) text = await sandbox.remove(root);
300
+ else if (verb && !["status", "estado"].includes(verb)) return unknown(ctx, "/sandbox", verb, SANDBOX_CHOICES());
300
301
  else text = sandbox.status();
301
302
  label(ctx);
302
303
  ctx.ui.notify(text, /^(Não|No |Could not|Did not)|não consegui|não encontrad|no pude|no encontr|could not|not found/i.test(text) ? "error" : "info");
@@ -8,7 +8,7 @@
8
8
  // (pink -p) não se registram.
9
9
  // Risco aceito (Argus R1): mesmo usuário na mesma máquina; um processo que grave direto em bus/inbox pode alegar o id de
10
10
  // outra sessão. A confiança vem do registro, não de prova criptográfica; o aviso de "dado, não pedido" vale sempre.
11
- import { t } from "./pink-i18n.ts";
11
+ import { noArgs, t } from "./pink-i18n.ts";
12
12
  import fs from "node:fs";
13
13
  import os from "node:os";
14
14
  import path from "node:path";
@@ -279,10 +279,10 @@ export function createBus(pink: any, { env = process.env, now = Date.now, alive
279
279
  });
280
280
  pink.registerCommand("sessoes", {
281
281
  description: t("Outras sessões do Pink abertas nesta máquina (para o agente conversar com elas)", "Otras sesiones de Pink abiertas en esta máquina (para que el agente hable con ellas)", "Other Pink sessions open on this machine (so the agent can talk to them)"),
282
- handler: async (_args: string, ctx: any) => {
282
+ handler: noArgs("/sessoes", async (_args: string, ctx: any) => {
283
283
  const others = listSessions(env, alive, now).filter((entry) => entry.id !== me?.id);
284
- ctx.ui.notify(`${me ? `${t("Esta sessão", "Esta sesión", "This session")}: ${label(me)}` : t("Esta sessão não está no barramento.", "Esta sesión no está en el bus.", "This session is not on the bus.")}\n\n${others.length ? others.map(label).join("\n") : t("Nenhuma outra sessão aberta.", "Ninguna otra sesión abierta.", "No other open session.")}`, "info");
285
- },
284
+ ctx.ui.notify(`${me ? `${t("Esta sessão", "Esta sesión", "This session")}: ${label(me)}` : t("Esta sessão não está no barramento.", "Esta sesión no está en el bus.", "This session is not on the bus.")}\n\n${others.length ? others.map(label).join("\n") : t("Nenhuma outra sessão aberta. Abra o Pink em outra janela para o agente conversar com ela.", "Ninguna otra sesión abierta. Abre Pink en otra ventana para que el agente hable con ella.", "No other open session. Open Pink in another window so the agent can talk to it.")}`, "info");
285
+ }),
286
286
  });
287
287
 
288
288
  return { drain, register, unregister, me: () => me };
@@ -5,7 +5,7 @@
5
5
  // A ferramenta continua se chamando bash/powershell e a execução é a original (createBashToolDefinition), então
6
6
  // permissões, hooks, RTK e modo plano valem igual. Ao fechar, trocar ou recarregar a sessão os processos são encerrados.
7
7
  // Sem tela (pink -p, subagente) o processo acabaria antes do resultado: o comando espera como antes.
8
- import { choose, t } from "./pink-i18n.ts";
8
+ import { type Choice, choose, completeFrom, t, unknown } from "./pink-i18n.ts";
9
9
  import { createBashToolDefinition, createPowerShellToolDefinition, SettingsManager } from "@earendil-works/pi-coding-agent";
10
10
  import { Type } from "typebox";
11
11
 
@@ -197,27 +197,32 @@ export function createShellJobs(pink: any, { now = Date.now, write = muxWrite }
197
197
  },
198
198
  });
199
199
 
200
+ const none = () => t("Nenhum processo em segundo plano. Peça ao agente para rodar um comando em segundo plano.", "Ningún proceso en segundo plano. Pide al agente que ejecute un comando en segundo plano.", "No background processes. Ask the agent to run a background command.");
201
+ const options = (): Choice[] => [
202
+ { value: "listar", description: jobs.size ? t("mostra os que estão rodando", "muestra los que están corriendo", "shows the running ones") : t("nada rodando agora", "nada corriendo ahora", "nothing running now") },
203
+ ...(jobs.size ? [{ value: "encerrar todos", description: t("para todos", "detiene todos", "stops all") }] : []),
204
+ ...[...jobs.keys()].map((id) => ({ value: `encerrar ${id}` })),
205
+ ];
200
206
  pink.registerCommand("processos", {
201
207
  description: t("Comandos em segundo plano: lista; 'encerrar <n>' ou 'encerrar todos'", "Comandos en segundo plano: lista; 'encerrar <n>' o 'encerrar todos'", "Background commands: list; 'stop <n>' or 'stop all'"),
202
- getArgumentCompletions: (prefix: string) =>
203
- ["encerrar todos", ...[...jobs.keys()].map((id) => `encerrar ${id}`)].filter((item) => item.startsWith(prefix)).map((value) => ({ value, label: value })),
208
+ getArgumentCompletions: completeFrom(options),
204
209
  handler: async (args: string, ctx: any) => {
205
210
  if (!args.trim() && jobs.size) {
206
- const choice = await choose(ctx, "/processos", [
207
- { value: "listar", description: t("mostra os que estão rodando", "muestra los que están corriendo", "shows the running ones") },
208
- ...["encerrar todos", ...[...jobs.keys()].map((id) => `encerrar ${id}`)].map((value) => ({ value })),
209
- ]);
211
+ const choice = await choose(ctx, "/processos", options());
210
212
  if (choice === undefined) return;
211
- args = choice === "listar" ? "" : choice;
213
+ args = choice;
212
214
  }
213
215
  const [verb, target] = args.trim().split(/\s+/);
216
+ if (verb && !["listar", "list", "encerrar", "stop"].includes(verb)) return unknown(ctx, "/processos", args.trim(), options());
217
+ if ((verb === "encerrar" || verb === "stop") && !jobs.size) return void ctx.ui.notify(none(), "warning");
214
218
  if (verb === "encerrar" || verb === "stop") {
215
219
  const targets = target === "todos" || target === "all" ? [...jobs.values()] : ([find(target)].filter(Boolean) as Job[]);
216
220
  for (const job of targets) job.controller.abort();
217
- ctx.ui.notify(targets.length ? t(`Encerrando ${targets.length} processo(s).`, `Deteniendo ${targets.length} proceso(s).`, `Stopping ${targets.length} process(es).`) : t("Use /processos encerrar <n> ou /processos encerrar todos.", "Usa /processos encerrar <n> o /processos encerrar todos.", "Use /processos stop <n> or /processos stop all."), targets.length ? "info" : "warning");
221
+ if (!targets.length) return unknown(ctx, "/processos", args.trim(), options());
222
+ ctx.ui.notify(t(`Encerrando ${targets.length} processo(s).`, `Deteniendo ${targets.length} proceso(s).`, `Stopping ${targets.length} process(es).`), "info");
218
223
  return;
219
224
  }
220
- ctx.ui.notify(jobs.size ? lines().join("\n") : t("Nenhum processo em segundo plano.", "Ningún proceso en segundo plano.", "No background processes."), "info");
225
+ ctx.ui.notify(jobs.size ? lines().join("\n") : none(), "info");
221
226
  },
222
227
  });
223
228
 
@@ -132,6 +132,7 @@ export default function (pink: any) {
132
132
  description: t("Propõe uma skill a partir do que deu certo nesta sessão (você vê e aprova antes de gravar): /skill-nova [assunto]", "Propone una skill a partir de lo que funcionó en esta sesión (tú lo ves y apruebas antes de guardar): /skill-nova [asunto]", "Proposes a skill from what worked in this session (you see and approve it before it is saved): /skill-nova [topic]"),
133
133
  handler: async (args: string, ctx: any) => {
134
134
  const prompt = PROPOSE_PROMPT(String(args ?? "").trim());
135
+ ctx?.ui?.notify?.(t("Pedindo ao agente uma skill desta sessão; você vê e aprova antes de gravar.", "Pidiendo al agente una skill de esta sesión; la ves y apruebas antes de guardar.", "Asking the agent for a skill from this session; you see and approve it before it is saved."), "info");
135
136
  if (ctx?.isIdle?.() === false) pink.sendUserMessage?.(prompt, { deliverAs: "followUp" });
136
137
  else pink.sendUserMessage?.(prompt);
137
138
  },
@@ -6,7 +6,7 @@
6
6
  // O evento input roda depois dos comandos de extensão e antes da expansão de skills e templates (agent-session.prompt);
7
7
  // os comandos nativos (/model, /new...) são tratados pela interface antes de chegar aqui. Template com o mesmo nome vence.
8
8
 
9
- import { t } from "./pink-i18n.ts";
9
+ import { noArgs, t } from "./pink-i18n.ts";
10
10
  const NAME = /^\/([a-z0-9][a-z0-9._-]*)(?=\s|$)/i;
11
11
 
12
12
  type Command = { name: string; description?: string; source: string; sourceInfo?: { scope?: string; path?: string } };
@@ -51,7 +51,7 @@ export default function (pink: any) {
51
51
  });
52
52
  pink.registerCommand("skills", {
53
53
  description: t("Lista as skills (SKILL.md) desta sessão; chame uma com /nome", "Lista las skills (SKILL.md) de esta sesión; llama una con /nombre", "Lists this session's skills (SKILL.md); call one with /name"),
54
- handler: async (_args: string, ctx: any) => {
54
+ handler: noArgs("/skills", async (_args: string, ctx: any) => {
55
55
  const skills = skillsOf(commands());
56
56
  if (!skills.length) {
57
57
  const off = ctx?.isProjectTrusted?.() === false ? t(" As skills do projeto só carregam em pasta confiável.", " Las skills del proyecto solo se cargan en una carpeta de confianza.", " Project skills only load in a trusted folder.") : "";
@@ -59,6 +59,6 @@ export default function (pink: any) {
59
59
  }
60
60
  const lines = skills.map((skill) => `/${skill.name} (${SCOPE[skill.scope] ?? (skill.scope || t("pacote", "paquete", "package"))}) · ${skill.description}`);
61
61
  ctx.ui.notify(`Skills:\n${lines.join("\n")}`, "info");
62
- },
62
+ }),
63
63
  });
64
64
  }
@@ -14,7 +14,7 @@ import os from "node:os";
14
14
  import path from "node:path";
15
15
  import { fileURLToPath } from "node:url";
16
16
  import { Type } from "typebox";
17
- import { type Choice, choose, completeFrom, t } from "./pink-i18n.ts";
17
+ import { type Choice, choose, completeFrom, t, unknown } from "./pink-i18n.ts";
18
18
 
19
19
  const TELA_CHOICES = (): Choice[] => [
20
20
  { value: "status", description: t("ligada ou desligada?", "¿activada o desactivada?", "on or off?") },
@@ -662,6 +662,7 @@ export function createTela(pink: any, { env = process.env, run = mcpRun as Run,
662
662
  const done = await installer({ env });
663
663
  return ctx.ui.notify(done, /^(Tela|Pantalla|Screen): cua-driver .* (instalado|installed)/.test(done) ? "info" : "error");
664
664
  }
665
+ if (verb && !["ligar", "on", "activar", "desligar", "off", "desactivar", "status", "estado"].includes(verb)) return unknown(ctx, "/tela", verb, TELA_CHOICES());
665
666
  const text = ["ligar", "on", "activar"].includes(verb) ? await turnOn() : ["desligar", "off", "desactivar"].includes(verb) ? turnOff() : status();
666
667
  ctx.ui.notify(text, /^(Não|No pude|Could not|Tela: |Pantalla: |Screen: )/.test(text) ? "error" : "info");
667
668
  },