@thothdev/pink 1.0.16 → 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.
- package/CHANGELOG.md +45 -0
- package/README.md +155 -54
- package/dist/bundle/chunks/chunk-T726RZZU.js +1 -1
- package/dist/mux/pink.mjs +153 -72
- package/examples/extensions/subagent/agents.ts +1 -1
- package/examples/extensions/subagent/background.ts +15 -10
- package/examples/extensions/subagent/external.ts +58 -8
- package/examples/extensions/subagent/pink-i18n.ts +22 -1
- package/extensions/pink-agente.ts +105 -12
- package/extensions/pink-context.ts +3 -3
- package/extensions/pink-hooks.ts +3 -3
- package/extensions/pink-i18n.ts +22 -1
- package/extensions/pink-loop.ts +5 -2
- package/extensions/pink-mcp-server.mjs +1 -1
- package/extensions/pink-memory.ts +2 -1
- package/extensions/pink-microfone.ts +2 -1
- package/extensions/pink-natives.ts +3 -3
- package/extensions/pink-notify.ts +3 -3
- package/extensions/pink-permissions.ts +3 -3
- package/extensions/pink-review.ts +19 -4
- package/extensions/pink-rules.ts +2 -2
- package/extensions/pink-sandbox.ts +2 -1
- package/extensions/pink-sessions-bus.ts +4 -4
- package/extensions/pink-shell-bg.ts +15 -10
- package/extensions/pink-skill-propose.ts +1 -0
- package/extensions/pink-skills.ts +3 -3
- package/extensions/pink-tela.ts +2 -1
- package/extensions/pink-ui.ts +202 -109
- package/package.json +16 -4
|
@@ -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, stallNote, streamedTokens, thinkingLabel, toolSummary, userLines, workingLabel } from "./pink-ui.ts";
|
|
13
|
+
import { closeKept, externalAgents, listModels, pinkExtras, runExternal, subagentEnd, warmKept } from "../examples/extensions/subagent/external.ts";
|
|
14
|
+
import { bulleted, elapsedLabel, fit, runLabel, shortModel, stallNote, streamedTokens, thinkingLabel, cleanLine as clean, tailLine, thinkingNow, stripThothRules, thothConfigured, toolSummary, userLines, workingLabel } from "./pink-ui.ts";
|
|
15
15
|
|
|
16
16
|
// o Pink junto (card 1dfwh7kgfjx): MCPs do mcp.json, AGENTS.md e skills do Pink, mais o próprio Pink como MCP
|
|
17
17
|
const readJson = (file: string) => {
|
|
@@ -70,6 +70,7 @@ export function gatherExtras(pink: any, dir = process.env.PINK_CODING_AGENT_DIR
|
|
|
70
70
|
let rules = "";
|
|
71
71
|
try {
|
|
72
72
|
rules = fs.readFileSync(path.join(dir, "AGENTS.md"), "utf8");
|
|
73
|
+
if (!thothConfigured()) rules = stripThothRules(rules);
|
|
73
74
|
} catch {
|
|
74
75
|
/* sem regras globais */
|
|
75
76
|
}
|
|
@@ -238,6 +239,34 @@ function tela(action: unknown, args: any = {}) {
|
|
|
238
239
|
return ["tela ·", String(action || "?"), what].filter(Boolean).join(" ");
|
|
239
240
|
}
|
|
240
241
|
|
|
242
|
+
// arquivos que o agente editou ou criou nesta resposta, para ALTERAÇÕES (mesmos nomes de ferramenta de pinkTool)
|
|
243
|
+
export function fileChanges(result: any, cwd = "") {
|
|
244
|
+
const out: { path: string; status: string }[] = [];
|
|
245
|
+
for (const message of result.messages) {
|
|
246
|
+
for (const part of message.content ?? []) {
|
|
247
|
+
if (part.type !== "toolCall") continue;
|
|
248
|
+
const raw = String(part.name ?? "").toLowerCase();
|
|
249
|
+
const args = part.arguments ?? {};
|
|
250
|
+
const file = args.path ?? args.file_path ?? args.filePath ?? args.notebook_path;
|
|
251
|
+
if (!file || !["edit", "write"].includes(NAMES[raw] ?? raw)) continue;
|
|
252
|
+
out.push({ path: cwd && path.isAbsolute(String(file)) ? path.relative(cwd, String(file)) : String(file), status: args.created ? "novo" : "editado" });
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
return out;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
// SESSÃO e ALTERAÇÕES com o agente ligado: os turnos dele nesta sessão mais o que está em andamento
|
|
259
|
+
export function agentPanel(entries: any[] | undefined, name: string, model = "", live?: any, session = "", cwd = "") {
|
|
260
|
+
const turns = (entries ?? []).filter((entry) => entry?.type === "custom_message" && entry.customType === "pink-agente" && entry.details?.agent === name).map((entry) => entry.details);
|
|
261
|
+
if (live) turns.push({ usage: live.usage, model: live.model, session });
|
|
262
|
+
// o codex informa o total da conversa inteira (vale o último de cada uma); os outros, só o de cada resposta
|
|
263
|
+
const usages = name === "codex" ? [...new Map(turns.filter((turn) => turn.usage?.input || turn.usage?.output).map((turn) => [turn.session, turn.usage])).values()] : turns.map((turn) => turn.usage);
|
|
264
|
+
const sum = (key: string) => usages.reduce((total: number, usage: any) => total + (Number(usage?.[key]) || 0), 0);
|
|
265
|
+
const models = [...new Set(turns.map((turn) => turn.model).filter((used) => used && used !== name))];
|
|
266
|
+
const pending = live ? [{ type: "custom_message", customType: "pink-agente", details: { changes: fileChanges(live, cwd) } }] : [];
|
|
267
|
+
return { name, models: models.length ? models : model ? [model] : [], input: sum("input"), output: sum("output"), cost: sum("cost"), answered: turns.length - (live ? 1 : 0), pending };
|
|
268
|
+
}
|
|
269
|
+
|
|
241
270
|
// os passos da resposta, na ordem: pensou, ferramentas e textos (o desenho usa; o modelo do Pink lê o texto puro)
|
|
242
271
|
export function steps(result: any, cwd = "") {
|
|
243
272
|
const out: any[] = [];
|
|
@@ -284,6 +313,23 @@ export function render(result: any, cwd = ""): string {
|
|
|
284
313
|
return body || t("(sem resposta)", "(sin respuesta)", "(no answer)");
|
|
285
314
|
}
|
|
286
315
|
|
|
316
|
+
// o que o agente está fazendo, ao vivo, acima do "Trabalhando" (owner 2026-11-27, como o OpenCode): os últimos passos
|
|
317
|
+
// (pensou, ferramentas, textos) e o que ainda está chegando. O texto vem de fora: sem caracteres de controle
|
|
318
|
+
const LIVE_STEPS = 6;
|
|
319
|
+
export function liveLines(result: any, width: number, cwd = ""): string[] {
|
|
320
|
+
const room = Math.max(10, width - 4);
|
|
321
|
+
const head = (text: unknown) => { const line = clean(text); return line.length > room ? `${line.slice(0, room - 1)}…` : line; };
|
|
322
|
+
const tail = (text: unknown) => tailLine(text, room);
|
|
323
|
+
const done = compact(steps(result, cwd)).map((step: any) => (step.kind === "tool" ? `→ ${head(step.line)}` : step.kind === "thinking" ? thinkingLabel(step.ms) : `● ${head(step.text)}`));
|
|
324
|
+
const part = result.partial;
|
|
325
|
+
const now = !part?.text ? [] : part.kind === "thinking"
|
|
326
|
+
? thinkingNow(part.text, room)
|
|
327
|
+
: String(part.text).split("\n").filter((line) => clean(line)).slice(-3).map((line, index) => `${index ? " " : "●"} ${tail(line)}`);
|
|
328
|
+
const hidden = done.length - LIVE_STEPS;
|
|
329
|
+
const earlier = hidden > 0 ? [t(` … ${hidden} passos antes`, ` … ${hidden} pasos antes`, ` … ${hidden} earlier steps`)] : [];
|
|
330
|
+
return [...earlier, ...done.slice(-LIVE_STEPS), ...now].map((line) => ` ${line}`);
|
|
331
|
+
}
|
|
332
|
+
|
|
287
333
|
const outputOf = (result: any) => result.usage?.output || result.messages.reduce((sum: number, message: any) => sum + streamedTokens(message), 0);
|
|
288
334
|
|
|
289
335
|
const label = (agent: any) => [agent.name, agent.model, agent.effort].filter(Boolean).join(" · ");
|
|
@@ -339,6 +385,7 @@ export default function (pink: any, list: typeof externalAgents = externalAgents
|
|
|
339
385
|
let active: { agent: any; resume: any; controller?: AbortController; queue?: string[]; live?: any; handoff?: string[] } | undefined;
|
|
340
386
|
let ticker: ReturnType<typeof setInterval> | undefined;
|
|
341
387
|
let lastUi: any;
|
|
388
|
+
(globalThis as any).__pinkAgentPanel = (entries: any[]) => active && agentPanel(entries, active.agent.name, active.agent.model, active.controller ? active.live : undefined, active.resume?.id, screenCtx?.cwd);
|
|
342
389
|
|
|
343
390
|
// "⠴ Trabalhando · 2s · ↓ 0 tokens" acima da caixa, com o mesmo Loader do Pink: o dele só aparece quando o modelo do Pink
|
|
344
391
|
// responde, e este ocupa o mesmo lugar
|
|
@@ -353,7 +400,7 @@ export default function (pink: any, list: typeof externalAgents = externalAgents
|
|
|
353
400
|
};
|
|
354
401
|
// a fila em cinza fica em cima do "Trabalhando" e uma linha vazia o separa da caixa (owner 2026-11-25, como o Claude Code)
|
|
355
402
|
const around = (lines: string[], width: number, theme: any) => [...queueLines(active?.queue ?? [], width).map((line) => theme.fg("dim", line)), ...lines, ""];
|
|
356
|
-
const busy = (ui: any, output: () => number) => {
|
|
403
|
+
const busy = (ui: any, output: () => number, doing: (width: number) => string[] = () => []) => {
|
|
357
404
|
idle();
|
|
358
405
|
lastUi = ui;
|
|
359
406
|
if (!ui?.setWidget) return;
|
|
@@ -374,12 +421,12 @@ export default function (pink: any, list: typeof externalAgents = externalAgents
|
|
|
374
421
|
loader?.stop?.(); // a fábrica pode ser chamada de novo: o Loader anterior para de girar
|
|
375
422
|
loader = new tui.Loader(screen, (s: string) => theme.fg("accent", s), (s: string) => theme.fg("muted", s), message());
|
|
376
423
|
const own = loader;
|
|
377
|
-
return { render: (width: number) => around(own.render(width).slice(1), width, theme), invalidate: () => own.invalidate?.() };
|
|
424
|
+
return { render: (width: number) => around([...doing(width).map((line) => theme.fg("muted", tui.truncateToWidth?.(line, width) ?? line)), ...own.render(width).slice(1)], width, theme), invalidate: () => own.invalidate?.() };
|
|
378
425
|
}, { placement: "aboveEditor" });
|
|
379
426
|
ticker = setInterval(() => loader?.setMessage?.(message()), 1000);
|
|
380
427
|
} else {
|
|
381
428
|
let frame = 0;
|
|
382
|
-
const draw = () => ui.setWidget(WIDGET, (screen: any, theme: any) => ((screenRef = screen), { render: (width: number) => around([` ${FRAMES[frame % FRAMES.length]} ${message()}`], width, theme), invalidate() {} }), { placement: "aboveEditor" });
|
|
429
|
+
const draw = () => ui.setWidget(WIDGET, (screen: any, theme: any) => ((screenRef = screen), { render: (width: number) => around([...doing(width).map((line) => tui?.truncateToWidth?.(line, width) ?? line), ` ${FRAMES[frame % FRAMES.length]} ${message()}`], width, theme), invalidate() {} }), { placement: "aboveEditor" });
|
|
383
430
|
draw();
|
|
384
431
|
ticker = setInterval(() => (frame++, draw()), 120);
|
|
385
432
|
}
|
|
@@ -431,6 +478,13 @@ export default function (pink: any, list: typeof externalAgents = externalAgents
|
|
|
431
478
|
active.controller.abort();
|
|
432
479
|
return true;
|
|
433
480
|
};
|
|
481
|
+
// Esc com o agente trabalhando: interrompe ele. Antes o Esc ia para a conversa, que não sabe do /agente: dois Esc abriam a árvore
|
|
482
|
+
// da conversa, voltavam a sessão para antes do pedido e punham o prompt de volta na caixa (owner 2026-11-26)
|
|
483
|
+
(globalThis as any).__pinkAgentInterrupt = () => {
|
|
484
|
+
if (!active?.controller) return false;
|
|
485
|
+
active.controller.abort();
|
|
486
|
+
return true;
|
|
487
|
+
};
|
|
434
488
|
const stop = (ctx?: any) => {
|
|
435
489
|
(ctx?.ui ?? lastUi)?.setWidget?.(QUEUE, undefined); // fila de versões antigas do widget (a de agora some junto com o agente)
|
|
436
490
|
if (active) active.queue = []; // a fila é descartada junto
|
|
@@ -546,7 +600,7 @@ export default function (pink: any, list: typeof externalAgents = externalAgents
|
|
|
546
600
|
ctx.ui?.setStatus?.(STATUS, `${name} ${t("trabalhando", "trabajando", "working")}${last ? `: ${last}` : "…"}`);
|
|
547
601
|
};
|
|
548
602
|
status();
|
|
549
|
-
if (ctx.hasUI) busy(ctx.ui, () => outputOf(result));
|
|
603
|
+
if (ctx.hasUI) busy(ctx.ui, () => outputOf(result), (width) => liveLines(result, width, ctx.cwd));
|
|
550
604
|
if (ctx.hasUI) watchChildren(ctx.ui);
|
|
551
605
|
(globalThis as any).__pinkExternalAsk = ctx.hasUI ? (title: string, body: string) => ctx.ui.confirm(title, body) : undefined;
|
|
552
606
|
try {
|
|
@@ -555,6 +609,8 @@ export default function (pink: any, list: typeof externalAgents = externalAgents
|
|
|
555
609
|
result.stopReason = "error";
|
|
556
610
|
result.errorMessage = controller.signal.aborted ? t("cancelado", "cancelado", "cancelled") : String(error?.message ?? error);
|
|
557
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");
|
|
558
614
|
if (current.controller === controller) current.controller = undefined;
|
|
559
615
|
if (active === current || !active) idle();
|
|
560
616
|
Reflect.get(globalThis, "__pinkTela")?.hide?.(); // o agente terminou: apaga o contorno da tela
|
|
@@ -564,7 +620,7 @@ export default function (pink: any, list: typeof externalAgents = externalAgents
|
|
|
564
620
|
if (!current.agent.model && result.model && result.model !== name) (globalThis as any).__pinkExternalAgent = { name, model: result.model, effort: current.agent.effort };
|
|
565
621
|
}
|
|
566
622
|
const error = result.stopReason === "error" ? String(result.errorMessage ?? t("erro", "error", "error")) : undefined;
|
|
567
|
-
pink.sendMessage({ customType: "pink-agente", display: true, content: render(result, ctx.cwd), details: { agent: name, session: current.resume?.id, model: result.model, usage: result.usage, error, steps: steps(result, ctx.cwd), ms: Date.now() - started, output: outputOf(result) } });
|
|
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) } });
|
|
568
624
|
pink.events?.emit?.("pink:agent_settled", { ctx, aborted: controller.signal.aborted });
|
|
569
625
|
// trocaram o modelo do Pink no meio: o que o agente fez já está na sessão; o novo modelo continua o pedido
|
|
570
626
|
if (current.handoff) return void pink.sendUserMessage?.(handoffText(name, [text, ...current.handoff]));
|
|
@@ -579,6 +635,7 @@ export default function (pink: any, list: typeof externalAgents = externalAgents
|
|
|
579
635
|
|
|
580
636
|
// "/agente " lista as opções, como os outros comandos: off e os agentes; "/agente codex " lista os modelos dele
|
|
581
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.");
|
|
582
639
|
const completions = async (prefix: string) => {
|
|
583
640
|
const text = String(prefix ?? "").replace(/^\s+/, "");
|
|
584
641
|
const space = text.indexOf(" ");
|
|
@@ -588,6 +645,7 @@ export default function (pink: any, list: typeof externalAgents = externalAgents
|
|
|
588
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)`) }] : []),
|
|
589
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`) })),
|
|
590
647
|
];
|
|
648
|
+
if (!agents.length && !text) items.push({ value: "", label: t("nenhum agente instalado", "ningún agente instalado", "no agent installed"), description: INSTALL() });
|
|
591
649
|
const hits = items.filter((item) => item.value.startsWith(text.toLowerCase()));
|
|
592
650
|
return hits.length ? hits : null;
|
|
593
651
|
}
|
|
@@ -625,7 +683,7 @@ export default function (pink: any, list: typeof externalAgents = externalAgents
|
|
|
625
683
|
}
|
|
626
684
|
let name = wanted;
|
|
627
685
|
if (!name) {
|
|
628
|
-
if (!agents.length) return ctx.ui?.notify?.(t("Nenhum agente instalado encontrado (claude, codex, opencode, cline, copilot, qwen, goose, gemini).", "No se encontró ningún agente instalado (claude, codex, opencode, cline, copilot, qwen, goose, gemini).", "No installed agent found (claude, codex, opencode, cline, copilot, qwen, goose, gemini).")
|
|
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");
|
|
629
687
|
// com um agente ligado, o primeiro item volta ao modelo/provedor do Pink (o mesmo que /agente off)
|
|
630
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;
|
|
631
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)) ?? "") : "";
|
|
@@ -637,9 +695,9 @@ export default function (pink: any, list: typeof externalAgents = externalAgents
|
|
|
637
695
|
}
|
|
638
696
|
}
|
|
639
697
|
const agent = agents.find((item) => item.name === name);
|
|
640
|
-
if (!agent) return ctx.ui?.notify?.(t(`${name} não está instalado. Disponíveis: ${agents.map((a) => a.name).join(", ") || "nenhum"}.`, `${name} no está instalado. Disponibles: ${agents.map((a) => a.name).join(", ") || "ninguno"}.`, `${name} is not installed. Available: ${agents.map((a) => a.name).join(", ") || "none"}.`), "warning");
|
|
641
|
-
if (rest.length > 2 || (model && !/^[\w./:@-]+$/.test(model))) return ctx.ui?.notify?.(t(`Nome de modelo inválido: ${rest.join(" ")}
|
|
642
|
-
if (effort && !/^[a-z]+$/.test(effort)) return ctx.ui?.notify?.(t(`Esforço inválido: ${effort}
|
|
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");
|
|
643
701
|
if (!model && ctx.hasUI) {
|
|
644
702
|
// menu com os modelos que o agente informa; o primeiro item mantém o padrão dele
|
|
645
703
|
ctx.ui?.setStatus?.(STATUS, t(`${name}: buscando modelos…`, `${name}: buscando modelos…`, `${name}: fetching models…`));
|
|
@@ -686,6 +744,41 @@ export default function (pink: any, list: typeof externalAgents = externalAgents
|
|
|
686
744
|
},
|
|
687
745
|
});
|
|
688
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
|
+
|
|
689
782
|
pink.on("input", async (event: any, ctx: any) => {
|
|
690
783
|
if (!active || event.source === "extension" || String(event.text ?? "").trimStart().startsWith("/")) return { action: "continue" };
|
|
691
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
|
}
|
package/extensions/pink-hooks.ts
CHANGED
|
@@ -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
|
|
package/extensions/pink-i18n.ts
CHANGED
|
@@ -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;
|
package/extensions/pink-loop.ts
CHANGED
|
@@ -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: (
|
|
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
|
|
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";
|
|
@@ -232,7 +232,7 @@ export function permissions(pink, deps = {}) {
|
|
|
232
232
|
});
|
|
233
233
|
pink.registerCommand?.("permissoes", {
|
|
234
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) => {
|
|
235
|
+
handler: noArgs("/permissoes", async (_args, ctx) => {
|
|
236
236
|
const files = filesFor(ctx);
|
|
237
237
|
const rules = loadRules(files, read);
|
|
238
238
|
const lines = [
|
|
@@ -244,7 +244,7 @@ export function permissions(pink, deps = {}) {
|
|
|
244
244
|
...rules.errors.map((e) => `${t("Erro", "Error", "Error")}: ${e}`),
|
|
245
245
|
];
|
|
246
246
|
ctx.ui.notify?.(lines.join("\n"), rules.errors.length ? "warning" : "info");
|
|
247
|
-
},
|
|
247
|
+
}),
|
|
248
248
|
});
|
|
249
249
|
return { sessionAllowed };
|
|
250
250
|
}
|
|
@@ -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)
|
|
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
|
-
|
|
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");
|
package/extensions/pink-rules.ts
CHANGED
|
@@ -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");
|