@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
package/extensions/pink-ui.ts
CHANGED
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
// assistant-footer, user-bar) that only call globalThis.__pinkFrame, __pinkAssistantFooter and __pinkUserBar.
|
|
11
11
|
// The layout functions are pure and exported for tests.
|
|
12
12
|
|
|
13
|
-
import { t } from "./pink-i18n.ts";
|
|
13
|
+
import { builtinWithArgs, completeFrom, noArgs, t, unknown } from "./pink-i18n.ts";
|
|
14
14
|
import { micBar } from "./pink-microfone.ts";
|
|
15
15
|
export const LOGO = [
|
|
16
16
|
"██████╗ ██╗███╗ ██╗██╗ ██╗",
|
|
@@ -122,20 +122,18 @@ export function footerLine({ theme, width, left, right }) {
|
|
|
122
122
|
return fit(`${left}${" ".repeat(gap)}${right}`, width);
|
|
123
123
|
}
|
|
124
124
|
|
|
125
|
-
const THINKING_PT = { minimal: t("mínimo", "mínimo", "minimal"), low: t("baixo", "bajo", "low"), medium: t("médio", "medio", "medium"), high: t("alto", "alto", "high"), xhigh: t("muito alto", "muy alto", "very high"), max: t("máximo", "máximo", "max") };
|
|
126
|
-
|
|
127
125
|
// "thoth thoth off" dizia modelo, provedor e nível sem explicar nada: agora o nome do modelo, o provedor só quando é
|
|
128
|
-
// outro, e o
|
|
126
|
+
// outro, e o nível só quando está ligado ("Sonnet 5.5 · medium", o nível sempre na palavra em inglês)
|
|
129
127
|
// como no OpenCode, o agente (Build/Plano) vem antes do modelo, na cor da marca
|
|
130
128
|
export function modelLabel({ theme, model, thinking, agent, permission = "edits", external = Reflect.get(globalThis, "__pinkExternalAgent") }) {
|
|
131
129
|
const mode = agent === "build" && permission === "ask" ? t(" (pergunta tudo)", " (pregunta todo)", " (ask everything)") : "";
|
|
132
130
|
const who = AGENTS[agent] ? `${theme.fg("accent", `${AGENTS[agent].label}${mode}`)}${theme.fg("muted", " · ")}` : "";
|
|
133
131
|
// /agente ligado (card 1dfwh7kgfjr): o Build fica; no lugar do modelo do Pink, o agente instalado e o modelo dele
|
|
134
|
-
if (external?.name) return `${who}${external.name}${theme.fg("muted", ` · ${external.model ?? t("modelo padrão", "modelo predeterminado", "default model")}${external.effort ? ` · ${
|
|
132
|
+
if (external?.name) return `${who}${external.name}${theme.fg("muted", ` · ${external.model ?? t("modelo padrão", "modelo predeterminado", "default model")}${external.effort ? ` · ${external.effort}` : ""}`)}`;
|
|
135
133
|
if (!model) return `${who}${theme.fg("muted", t("sem modelo", "sin modelo", "no model"))}`;
|
|
136
134
|
const name = model.name || model.id;
|
|
137
135
|
const provider = model.provider && model.provider !== model.id && model.provider !== name ? theme.fg("muted", ` · ${model.provider}`) : "";
|
|
138
|
-
const level =
|
|
136
|
+
const level = thinking && thinking !== "off" ? theme.fg("muted", ` · ${thinking}`) : "";
|
|
139
137
|
return `${who}${name}${provider}${level}`;
|
|
140
138
|
}
|
|
141
139
|
|
|
@@ -381,7 +379,7 @@ export function leftColumn({ theme, width, height, data }) {
|
|
|
381
379
|
export function rightColumn({ theme, width, height, data }) {
|
|
382
380
|
// CONTEXTO, PLANO (o todowrite), ALTERAÇÕES (edit/write desta sessão) e SESSÃO (tokens; custo só quando há)
|
|
383
381
|
const inner = Math.max(6, width - 3);
|
|
384
|
-
const out = [heading(theme, "CONTEXTO")];
|
|
382
|
+
const out = [heading(theme, t("CONTEXTO", "CONTEXTO", "CONTEXT"))];
|
|
385
383
|
const ctx = data.context;
|
|
386
384
|
if (ctx?.tokens != null && ctx.window) {
|
|
387
385
|
out.push(meter({ theme, percent: ctx.percent, cells: inner }), `${theme.fg("accent", `${kTokens(ctx.tokens)} tokens`)}${theme.fg("muted", ` · ${Math.round(ctx.percent ?? 0)}% ${t("de", "de", "of")} ${kTokens(ctx.window)}`)}`);
|
|
@@ -414,18 +412,19 @@ export function rightColumn({ theme, width, height, data }) {
|
|
|
414
412
|
} else {
|
|
415
413
|
out.push(theme.fg("dim", t("nenhum arquivo alterado", "ningún archivo cambiado", "no files changed")));
|
|
416
414
|
}
|
|
417
|
-
out.push("", rule(theme, inner), heading(theme, t("SESSÃO", "SESIÓN", "SESSION")));
|
|
415
|
+
out.push("", rule(theme, inner), heading(theme, t("SESSÃO", "SESIÓN", "SESSION"), data.agent ? theme.fg("muted", ` ${data.agent}`) : ""));
|
|
418
416
|
out.push(`${theme.fg("text", formatTokens(data.input))} ${theme.fg("muted", t("entrada", "entrada", "in"))}${theme.fg("dim", " │ ")}${theme.fg("text", formatTokens(data.output))} ${theme.fg("muted", t("saída", "salida", "out"))}`);
|
|
419
417
|
if (data.models?.length) out.push(theme.fg("muted", `${t("modelo", "modelo", "model")} ${data.models.map(shortModel).join(", ")}`));
|
|
420
418
|
if (data.cost > 0) out.push(theme.fg("muted", `$${data.cost.toFixed(2)} ${t("gasto", "gastado", "spent")}`));
|
|
419
|
+
if (data.unreported) out.push(theme.fg("dim", t("o agente não informa o uso", "el agente no informa el uso", "the agent reports no usage")));
|
|
421
420
|
if (data.project) out.push(theme.fg("muted", `${t("projeto", "proyecto", "project")} ${data.project}`));
|
|
422
421
|
// SUBAGENTES por último, abaixo da SESSÃO (owner 2026-11-25): a lista cresce no espaço livre do fim da coluna
|
|
423
422
|
const agents = data.agents ?? [];
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
const lines = out.slice(0, height).map((line) => pad(fit(line, inner), inner));
|
|
423
|
+
const tail = agents.length ? ["", rule(theme, inner), heading(theme, t("SUBAGENTES", "SUBAGENTES", "SUBAGENTS"), theme.fg("muted", ` ${agents.length}`)), ...agents.map((item) => agentLine(theme, item, inner, data.now))] : [];
|
|
424
|
+
// coluna cheia corta o que vem antes, nunca os subagentes: com a lateral ligada eles não aparecem em outro lugar
|
|
425
|
+
const room = Math.max(0, height - tail.length);
|
|
426
|
+
if (data.hits?.mcp >= room) delete data.hits.mcp;
|
|
427
|
+
const lines = [...out.slice(0, room), ...tail].slice(0, height).map((line) => pad(fit(line, inner), inner));
|
|
429
428
|
return [...lines, ...Array(Math.max(0, height - lines.length)).fill(" ".repeat(inner))].map((line) => `${theme.fg("borderMuted", "│")} ${line} `);
|
|
430
429
|
}
|
|
431
430
|
|
|
@@ -493,12 +492,12 @@ export function changesFromBranch(entries, created = new Set()) {
|
|
|
493
492
|
// arquivos que as ferramentas edit/write tocaram no ramo atual (o /undo volta o ramo, e a lista volta junto)
|
|
494
493
|
const seen = new Map();
|
|
495
494
|
for (const entry of entries ?? []) {
|
|
495
|
+
const add = (path, isNew) => { if (typeof path === "string" && path && !seen.has(path)) seen.set(path, isNew || created.has(path) ? "novo" : "editado"); };
|
|
496
|
+
// /agente: as ferramentas dele não são mensagens do Pink; a resposta guarda o que ele alterou
|
|
497
|
+
if (entry?.type === "custom_message" && entry.customType === "pink-agente") for (const item of entry.details?.changes ?? []) add(item?.path, item?.status === "novo");
|
|
496
498
|
const message = entry?.type === "message" ? entry.message : undefined;
|
|
497
499
|
if (message?.role !== "assistant" || !Array.isArray(message.content)) continue;
|
|
498
|
-
for (const part of message.content)
|
|
499
|
-
const path = part?.type === "toolCall" && (part.name === "edit" || part.name === "write") ? part.arguments?.path : undefined;
|
|
500
|
-
if (typeof path === "string" && path && !seen.has(path)) seen.set(path, created.has(path) ? "novo" : "editado");
|
|
501
|
-
}
|
|
500
|
+
for (const part of message.content) if (part?.type === "toolCall" && (part.name === "edit" || part.name === "write")) add(part.arguments?.path);
|
|
502
501
|
}
|
|
503
502
|
return [...seen.entries()].map(([path, status]) => ({ path: path.replace(/\\/g, "/"), status }));
|
|
504
503
|
}
|
|
@@ -581,7 +580,7 @@ export function thothSnapshot({ approvals, cards, calls }, now = Date.now()) {
|
|
|
581
580
|
}
|
|
582
581
|
|
|
583
582
|
export function thothLines({ theme, thoth, width }) {
|
|
584
|
-
// sem o Thoth
|
|
583
|
+
// sem o Thoth: uma apresentação fixa, sem processo nem rede (owner 2026-11-24: "propaganda para todos")
|
|
585
584
|
if (thoth?.ad) return [theme.fg("text", fit(t("Governança e memória", "Gobernanza y memoria", "Governance and memory"), width)), theme.fg("dim", fit(t("para seus agentes:", "para tus agentes:", "for your agents:"), width)), theme.fg("accent", fit("thothdev.ia.br", width))];
|
|
586
585
|
if (!thoth?.ok) return [theme.fg("dim", thoth?.loading ? t("consultando…", "consultando…", "loading…") : t("Thoth indisponível", "Thoth no disponible", "Thoth unavailable"))];
|
|
587
586
|
const row = (label, value, tone = "text") => {
|
|
@@ -599,15 +598,13 @@ export function thothLines({ theme, thoth, width }) {
|
|
|
599
598
|
];
|
|
600
599
|
}
|
|
601
600
|
|
|
602
|
-
// o Thoth é outro produto:
|
|
603
|
-
export function
|
|
604
|
-
|
|
605
|
-
const exts = platform === "win32" ? [".exe", ".cmd"] : [""];
|
|
606
|
-
return String(env.PATH || env.Path || "").split(platform === "win32" ? ";" : ":").some((dir) => {
|
|
607
|
-
const base = dir.trim().replace(/^"|"$/g, "").replace(/[\\/]+$/, "");
|
|
608
|
-
return base && ["thoth", "thoth-client"].some((name) => exts.some((ext) => exists(`${base}/${name}${ext}`)));
|
|
609
|
-
});
|
|
601
|
+
// o Thoth é outro produto: só aparece, consulta e vale com um MCP dele configurado no Pink (e não desligado)
|
|
602
|
+
export function thothConfigured(servers = globalThis.__pinkMcp?.()) {
|
|
603
|
+
return Array.isArray(servers) && servers.some((server) => /thoth/i.test(String(server?.name)) && server.state !== "disabled");
|
|
610
604
|
}
|
|
605
|
+
globalThis.__pinkThothConfigured = () => thothConfigured(); // o subagent do pacote não importa este arquivo
|
|
606
|
+
// sem ele, o bloco que o instalador do Thoth grava no AGENTS.md não vai para o modelo
|
|
607
|
+
export const stripThothRules = (text) => String(text ?? "").replace(/<!-- thoth:begin[\s\S]*?<!-- thoth:end[^>]*-->(\r?\n)?/g, "");
|
|
611
608
|
|
|
612
609
|
// as fontes reais: o CLI `thoth approvals list --json`, o painel local (/api/work-center/cards) e as chamadas do
|
|
613
610
|
// gateway thoth free (/v1/thoth/calls). Todas só leem; o token do gateway vai no
|
|
@@ -644,22 +641,23 @@ export function thothSources({ vault, project, env = process.env }) {
|
|
|
644
641
|
};
|
|
645
642
|
}
|
|
646
643
|
|
|
647
|
-
// -- COTA:
|
|
648
|
-
|
|
649
|
-
export
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
644
|
+
// -- COTA: 5 horas e semana do Claude e do Codex, lidos pelo próprio Pink: o login dele (Claude) e o protocolo oficial de
|
|
645
|
+
// cada CLI instalado, que responde com o login dele (o Pink não lê credencial). Nenhuma das perguntas chama modelo.
|
|
646
|
+
export const PLAN_POLL_MS = 180000; // o claude leva ~7 s para responder: de 3 em 3 minutos basta
|
|
647
|
+
function usageWindow(pct, resets, now) {
|
|
648
|
+
if (Number.isFinite(resets) && resets <= now) return { pct: 0 };
|
|
649
|
+
return { pct: Math.max(0, Math.min(100, pct)), ...(Number.isFinite(resets) ? { resets } : {}) };
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
// o "Sign in with ChatGPT" (provedor openai) chama api.openai.com e tem um limite próprio de compartilhamento; o Codex CLI
|
|
653
|
+
// e o provedor openai-codex chamam chatgpt.com/backend-api, que é a cota do Codex que a lateral mostra
|
|
654
|
+
export function chatgptLimitHint(error) {
|
|
655
|
+
if (!/subscription_sharing_usage_limit_exceeded|Subscription Sharing usage limit/i.test(String(error ?? ""))) return "";
|
|
656
|
+
return t(
|
|
657
|
+
'Este limite é o do "Sign in with ChatGPT" (compartilhamento da assinatura), não a cota do Codex. Para usar o plano do Codex: /login openai-codex e escolha um modelo openai-codex em /model, ou use /agente codex.',
|
|
658
|
+
'Este límite es el de "Sign in with ChatGPT" (uso compartido de la suscripción), no la cuota de Codex. Para usar el plan de Codex: /login openai-codex y elige un modelo openai-codex en /model, o usa /agente codex.',
|
|
659
|
+
'This is the "Sign in with ChatGPT" (subscription sharing) limit, not your Codex quota. To use the Codex plan: /login openai-codex and pick an openai-codex model in /model, or use /agente codex.',
|
|
660
|
+
);
|
|
663
661
|
}
|
|
664
662
|
|
|
665
663
|
export function resetLabel(epoch, now = new Date()) {
|
|
@@ -670,33 +668,14 @@ export function resetLabel(epoch, now = new Date()) {
|
|
|
670
668
|
return `${t("dom,seg,ter,qua,qui,sex,sáb", "dom,lun,mar,mié,jue,vie,sáb", "Sun,Mon,Tue,Wed,Thu,Fri,Sat").split(",")[when.getDay()]} ${hm}`;
|
|
671
669
|
}
|
|
672
670
|
|
|
673
|
-
// por que a leitura falhou: sem o motivo, "sem dado do plano" numa máquina nova não diz o que fazer
|
|
674
|
-
const PLAN_FAILURE = {
|
|
675
|
-
missing: t("thoth-client não achado no PATH", "thoth-client no está en el PATH", "thoth-client not on PATH"),
|
|
676
|
-
slow: t("thoth-client demorou mais de 60 s", "thoth-client tardó más de 60 s", "thoth-client took over 60 s"),
|
|
677
|
-
old: t("thoth-client antigo: atualize", "thoth-client antiguo: actualiza", "old thoth-client: update it"),
|
|
678
|
-
bad: t("resposta inválida do thoth-client", "respuesta inválida de thoth-client", "invalid thoth-client output"),
|
|
679
|
-
failed: t("rode: thoth-client uso estado", "ejecuta: thoth-client uso estado", "run: thoth-client uso estado"),
|
|
680
|
-
};
|
|
681
|
-
export function planFailure(error, stderr = "") {
|
|
682
|
-
if (error?.code === "ENOENT") return "missing";
|
|
683
|
-
if (error?.killed || error?.code === "ETIMEDOUT") return "slow";
|
|
684
|
-
if (/invalid choice|unrecognized arguments|escolha inválida/i.test(String(stderr))) return "old";
|
|
685
|
-
return "failed";
|
|
686
|
-
}
|
|
687
|
-
|
|
688
671
|
export function planLines({ theme, plan, width, now = new Date() }) {
|
|
689
|
-
if (!plan?.ok
|
|
690
|
-
if (!plan?.ok) {
|
|
691
|
-
const why = PLAN_FAILURE[plan?.reason];
|
|
692
|
-
return [theme.fg("dim", t("sem dado do plano", "sin dato del plan", "no plan data")), ...(why ? [theme.fg("warning", fit(why, width))] : [])];
|
|
693
|
-
}
|
|
672
|
+
if (!plan?.ok) return [theme.fg("dim", plan?.loading ? t("consultando…", "consultando…", "loading…") : t("sem leitura", "sin lectura", "no reading"))];
|
|
694
673
|
const out = [];
|
|
695
674
|
for (const [name, usage] of [["Claude", plan.claude], ["Codex", plan.codex]]) {
|
|
696
675
|
if (usage === undefined) continue;
|
|
697
676
|
out.push(theme.fg("text", name));
|
|
698
677
|
if (!usage) {
|
|
699
|
-
out.push(theme.fg("dim",
|
|
678
|
+
out.push(theme.fg("dim", t(" sem leitura", " sin lectura", " no reading")));
|
|
700
679
|
continue;
|
|
701
680
|
}
|
|
702
681
|
for (const [key, label] of [["h5", "5 h"], ["week", t("semana", "semana", "week")]]) {
|
|
@@ -709,7 +688,7 @@ export function planLines({ theme, plan, width, now = new Date() }) {
|
|
|
709
688
|
out.push(` ${meter({ theme, percent: window.pct, cells: Math.max(4, width - 2) })}`);
|
|
710
689
|
}
|
|
711
690
|
}
|
|
712
|
-
return out.length ? out : [theme.fg("dim", "
|
|
691
|
+
return out.length ? out : [theme.fg("dim", t("sem leitura", "sin lectura", "no reading"))];
|
|
713
692
|
}
|
|
714
693
|
|
|
715
694
|
// -- MCP (como a lateral do OpenCode): título com a contagem; clique abre a lista completa com o estado de cada um
|
|
@@ -732,37 +711,107 @@ export function mcpLines({ theme, mcp, open, width }) {
|
|
|
732
711
|
export function claudeUsageWindows(body, now = Date.now() / 1000) {
|
|
733
712
|
const out = {};
|
|
734
713
|
for (const [key, name] of [["five_hour", "h5"], ["seven_day", "week"]]) {
|
|
735
|
-
const pct =
|
|
736
|
-
|
|
737
|
-
if (
|
|
738
|
-
out[name] = resets <= now ? { pct: 0 } : { pct: Math.max(0, Math.min(100, pct)), resets };
|
|
714
|
+
const pct = body?.[key]?.utilization;
|
|
715
|
+
// resets_at nulo: nenhuma janela aberta ainda (0% logo depois de ela virar)
|
|
716
|
+
if (Number.isFinite(pct)) out[name] = usageWindow(pct, Date.parse(body[key].resets_at ?? "") / 1000, now);
|
|
739
717
|
}
|
|
740
718
|
return Object.keys(out).length ? out : undefined;
|
|
741
719
|
}
|
|
742
720
|
|
|
721
|
+
// resposta de account/rateLimits/read do codex app-server (a fonte do /status dele); primary/secondary não dizem qual é
|
|
722
|
+
// qual: até um dia é a janela de 5 h, o resto é a semana
|
|
723
|
+
export function codexUsageWindows(result, now = Date.now() / 1000) {
|
|
724
|
+
const out = {};
|
|
725
|
+
for (const raw of [result?.rateLimits?.primary, result?.rateLimits?.secondary]) {
|
|
726
|
+
if (Number.isFinite(raw?.usedPercent)) out[raw.windowDurationMins <= 1440 ? "h5" : "week"] = usageWindow(raw.usedPercent, raw.resetsAt ?? NaN, now);
|
|
727
|
+
}
|
|
728
|
+
return Object.keys(out).length ? out : undefined;
|
|
729
|
+
}
|
|
730
|
+
|
|
731
|
+
// undefined: sem token de assinatura; null: com ele, mas a leitura falhou
|
|
743
732
|
export async function readClaudeFromPink(getKey, fetcher = fetch) {
|
|
744
733
|
const token = await getKey?.("anthropic");
|
|
745
734
|
if (typeof token !== "string" || !token.startsWith("sk-ant-oat")) return undefined;
|
|
746
735
|
const response = await fetcher("https://api.anthropic.com/api/oauth/usage", { headers: { Authorization: `Bearer ${token}`, "anthropic-beta": "oauth-2025-04-20" }, signal: AbortSignal.timeout(10000) });
|
|
747
|
-
if (!response.ok) return
|
|
748
|
-
return claudeUsageWindows(await response.json());
|
|
736
|
+
if (!response.ok) return null;
|
|
737
|
+
return claudeUsageWindows(await response.json()) ?? null;
|
|
749
738
|
}
|
|
750
739
|
|
|
751
|
-
export function
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
740
|
+
export function onPath(name, env = process.env, exists = (file) => Boolean(node("node:fs")?.existsSync(file)), platform = process.platform) {
|
|
741
|
+
const exts = platform === "win32" ? [".exe", ".cmd"] : [""];
|
|
742
|
+
return String(env.PATH || env.Path || "").split(platform === "win32" ? ";" : ":").some((dir) => {
|
|
743
|
+
const base = dir.trim().replace(/^"|"$/g, "").replace(/[\\/]+$/, "");
|
|
744
|
+
return base && exts.some((ext) => exists(`${base}/${name}${ext}`));
|
|
745
|
+
});
|
|
746
|
+
}
|
|
747
|
+
|
|
748
|
+
// pergunta em linhas JSON a um CLI: comando fixo (o shell acha o .cmd do npm), na home para o projeto não interferir.
|
|
749
|
+
// pick devolve undefined enquanto a resposta não chega; fechar a entrada faz o CLI sair sozinho
|
|
750
|
+
export function askCli(command, input, pick, { start = node("node:child_process")?.spawn, timeoutMs = 60000 } = {}) {
|
|
751
|
+
return new Promise((resolve) => {
|
|
752
|
+
let child;
|
|
753
|
+
try {
|
|
754
|
+
child = start(command, { shell: true, cwd: process.env.USERPROFILE || process.env.HOME || undefined, windowsHide: true, stdio: ["pipe", "pipe", "ignore"] });
|
|
755
|
+
} catch {
|
|
756
|
+
return resolve(undefined);
|
|
757
|
+
}
|
|
758
|
+
let buffer = "";
|
|
759
|
+
const finish = (value) => {
|
|
760
|
+
clearTimeout(timer);
|
|
761
|
+
child.stdin.end();
|
|
762
|
+
resolve(value);
|
|
763
|
+
};
|
|
764
|
+
const timer = setTimeout(() => {
|
|
765
|
+
// travado: no Windows o kill pegaria só o shell, então vai a árvore deste filho
|
|
766
|
+
if (process.platform === "win32" && child.pid) node("node:child_process")?.execFile("taskkill", ["/T", "/F", "/PID", String(child.pid)], { windowsHide: true }, () => undefined);
|
|
767
|
+
else child.kill?.();
|
|
768
|
+
finish(undefined);
|
|
769
|
+
}, timeoutMs);
|
|
770
|
+
timer.unref?.();
|
|
771
|
+
child.on("error", () => finish(undefined));
|
|
772
|
+
child.on("close", () => finish(undefined));
|
|
773
|
+
child.stdin.on("error", () => undefined);
|
|
774
|
+
child.stdout.on("data", (chunk) => {
|
|
775
|
+
const rows = (buffer + chunk).split("\n");
|
|
776
|
+
buffer = rows.pop();
|
|
777
|
+
for (const row of rows) {
|
|
778
|
+
let value;
|
|
779
|
+
try {
|
|
780
|
+
value = pick(JSON.parse(row));
|
|
781
|
+
} catch {
|
|
782
|
+
continue; // aviso em texto no meio do protocolo
|
|
783
|
+
}
|
|
784
|
+
if (value !== undefined) return finish(value);
|
|
761
785
|
}
|
|
762
786
|
});
|
|
787
|
+
child.stdin.write(input);
|
|
763
788
|
});
|
|
764
789
|
}
|
|
765
790
|
|
|
791
|
+
// get_usage do Claude Code (o mesmo do /usage), sem hooks, MCPs nem sessão gravada
|
|
792
|
+
export const CLAUDE_QUOTA = {
|
|
793
|
+
command: "claude -p --input-format stream-json --output-format stream-json --verbose --strict-mcp-config --setting-sources= --no-session-persistence",
|
|
794
|
+
input: `${JSON.stringify({ type: "control_request", request_id: "pink-usage", request: { subtype: "get_usage" } })}\n`,
|
|
795
|
+
pick: (message) => (message?.type === "control_response" && message.response?.request_id === "pink-usage" ? (message.response.response?.rate_limits ?? null) : undefined),
|
|
796
|
+
};
|
|
797
|
+
export const CODEX_QUOTA = {
|
|
798
|
+
command: "codex app-server",
|
|
799
|
+
input: `${[{ id: 1, method: "initialize", params: { clientInfo: { name: "pink", version: "1" } } }, { method: "initialized" }, { id: 2, method: "account/rateLimits/read" }].map((message) => JSON.stringify(message)).join("\n")}\n`,
|
|
800
|
+
pick: (message) => (message?.id === 2 ? (message.result ?? null) : undefined),
|
|
801
|
+
};
|
|
802
|
+
|
|
803
|
+
// por provedor: undefined = não há de onde ler (some da lateral), null = há, mas sem leitura agora
|
|
804
|
+
export async function readQuota({ getKey, has = onPath, ask = askCli, fetcher = fetch } = {}) {
|
|
805
|
+
const own = await readClaudeFromPink(getKey, fetcher).catch(() => undefined);
|
|
806
|
+
const cli = async (name, source, parse) => (has(name) ? (parse(await ask(source.command, source.input, source.pick)) ?? null) : undefined);
|
|
807
|
+
const [claude, codex] = await Promise.all([
|
|
808
|
+
// o login do Pink vale primeiro; sem leitura por ele, o Claude Code instalado
|
|
809
|
+
own || cli("claude", CLAUDE_QUOTA, claudeUsageWindows).then((value) => (value === undefined ? own : value)),
|
|
810
|
+
cli("codex", CODEX_QUOTA, codexUsageWindows),
|
|
811
|
+
]);
|
|
812
|
+
return claude === undefined && codex === undefined ? undefined : { ok: true, claude, codex };
|
|
813
|
+
}
|
|
814
|
+
|
|
766
815
|
export async function pollThoth(sources, now = Date.now()) {
|
|
767
816
|
const names = ["approvals", "cards", "calls"];
|
|
768
817
|
const settled = await Promise.allSettled(names.map((name) => Promise.resolve().then(() => sources[name]())));
|
|
@@ -823,8 +872,16 @@ export function install(pink, ctx, { CustomEditor, SessionManager, version = "",
|
|
|
823
872
|
};
|
|
824
873
|
// sessão do multiplexador (pink/mux): progresso (OSC 9;4) enquanto trabalha e sino ao terminar, para a lateral mostrar o estado
|
|
825
874
|
const signal = (text) => process.env.PINK_MUX_CHILD === "1" && process.stdout.isTTY && process.stdout.write(text);
|
|
875
|
+
// o multiplexador guarda o arquivo de cada sessão aberta para reabri-la no próximo Pink (card 1dfwh7kfyty); avisa já no
|
|
876
|
+
// começo para uma sessão que cai no meio também voltar
|
|
877
|
+
const signalSession = () => {
|
|
878
|
+
const file = ctx.sessionManager?.getSessionFile?.();
|
|
879
|
+
if (file) signal(`\x1b]9;pink-session=${file}\x07`);
|
|
880
|
+
};
|
|
881
|
+
signalSession();
|
|
826
882
|
const runStarted = () => {
|
|
827
883
|
signal("\x1b]9;4;3\x07");
|
|
884
|
+
signalSession();
|
|
828
885
|
leaveHome();
|
|
829
886
|
};
|
|
830
887
|
pink.on("agent_start", runStarted);
|
|
@@ -844,9 +901,7 @@ export function install(pink, ctx, { CustomEditor, SessionManager, version = "",
|
|
|
844
901
|
PINK.refreshSessions = loadSessions; // o "Apagar sessão" relê a coluna depois de mover o arquivo
|
|
845
902
|
const runEnded = () => {
|
|
846
903
|
signal("\x1b]9;4;0\x07\x07");
|
|
847
|
-
|
|
848
|
-
const file = ctx.sessionManager?.getSessionFile?.();
|
|
849
|
-
if (file) signal(`\x1b]9;pink-session=${file}\x07`);
|
|
904
|
+
signalSession();
|
|
850
905
|
// título automático (owner 2026-10-29): só quando a sessão ainda não tem nome
|
|
851
906
|
if (!pink.getSessionName?.()) {
|
|
852
907
|
const title = autoTitle(ctx.sessionManager?.getBranch?.());
|
|
@@ -865,7 +920,7 @@ export function install(pink, ctx, { CustomEditor, SessionManager, version = "",
|
|
|
865
920
|
ctx.ui.setHeader((tui, theme) => {
|
|
866
921
|
state.tui = tui;
|
|
867
922
|
return {
|
|
868
|
-
render: live((width) => (state.home ? homeHeader({ theme, width, rows: homeRows(), subtitle: `coding agent · ${t("modelo", "modelo", "model")} ${ctx.model?.id ?? "
|
|
923
|
+
render: live((width) => (state.home ? homeHeader({ theme, width, rows: homeRows(), subtitle: `coding agent · ${t("modelo", "modelo", "model")} ${ctx.model?.id ?? t("nenhum", "ninguno", "none")}` }) : []), []),
|
|
869
924
|
invalidate() {},
|
|
870
925
|
};
|
|
871
926
|
});
|
|
@@ -895,6 +950,8 @@ export function install(pink, ctx, { CustomEditor, SessionManager, version = "",
|
|
|
895
950
|
// Esc com texto na caixa (e sem lista de sugestões aberta): limpa a caixa primeiro, como o Claude Code; o próximo
|
|
896
951
|
// Esc interrompe. Antes o Esc só interrompia, e um prompt longo na caixa não tinha como sair (owner 2026-11-26)
|
|
897
952
|
if (matchesKey?.(data, "escape") && String(this.getText?.() ?? "") !== "" && !(Number(this.renderedAutocompleteHeight) > 0)) return void this.setText("");
|
|
953
|
+
// caixa vazia e /agente trabalhando: o Esc interrompe o agente e não chega à conversa (o duplo Esc abriria a árvore)
|
|
954
|
+
if (matchesKey?.(data, "escape") && globalThis.__pinkAgentInterrupt?.()) return;
|
|
898
955
|
super.handleInput(data);
|
|
899
956
|
}
|
|
900
957
|
|
|
@@ -971,7 +1028,12 @@ export function install(pink, ctx, { CustomEditor, SessionManager, version = "",
|
|
|
971
1028
|
// o título do bloco aberto vem do patch thinking-header-when-shown
|
|
972
1029
|
ctx.ui.setHiddenThinkingLabel?.(t("+ Pensou", "+ Pensó", "+ Thought"));
|
|
973
1030
|
globalThis.__pinkThinkingHeader = t("− Pensou · clique ou ctrl+t recolhe", "− Pensó · haz clic o ctrl+t contrae", "− Thought · click or ctrl+t collapses");
|
|
974
|
-
globalThis.__pinkThinkingLabel = (message, runIndex) =>
|
|
1031
|
+
globalThis.__pinkThinkingLabel = (message, runIndex) => {
|
|
1032
|
+
const run = PINK.thinking.get(message?.timestamp)?.[runIndex];
|
|
1033
|
+
// ainda pensando: o mesmo "∴ Pensando…" com o fim do raciocínio que o /agente mostra (provedor logado e modelo local)
|
|
1034
|
+
if (run && run.ms === undefined) return thinkingNow(message.content?.findLast?.((part) => part?.type === "thinking")?.thinking, (process.stdout.columns || 80) - 6).join("\n");
|
|
1035
|
+
return thinkingLabel(run?.ms);
|
|
1036
|
+
};
|
|
975
1037
|
// "Pink · Build" sobre cada resposta (patch assistant-label); o agente é o da hora da resposta, desconhecido em sessão reaberta
|
|
976
1038
|
// rodapé de cada resposta final (patch assistant-footer), lido a cada quadro: o tempo chega no message_end
|
|
977
1039
|
globalThis.__pinkAssistantFooter = live((message, streaming, width, outputPad = 1) => {
|
|
@@ -992,15 +1054,14 @@ export function install(pink, ctx, { CustomEditor, SessionManager, version = "",
|
|
|
992
1054
|
return "";
|
|
993
1055
|
}
|
|
994
1056
|
})();
|
|
995
|
-
//
|
|
996
|
-
// (trocar de sessão reinstala a interface e só troca quem redesenha), sem segurar a saída do Pink (unref)
|
|
997
|
-
PINK.
|
|
1057
|
+
// COTA e THOTH só consultam quando a coluna da direita aparece pela primeira vez; um relógio de cada para o processo
|
|
1058
|
+
// todo (trocar de sessão reinstala a interface e só troca quem redesenha), sem segurar a saída do Pink (unref)
|
|
1059
|
+
PINK.thoth.redraw = redraw;
|
|
998
1060
|
const startThoth = () => {
|
|
999
|
-
PINK.thoth.redraw = redraw;
|
|
1000
1061
|
if (PINK.thoth.timer) return;
|
|
1001
1062
|
const sources = thothSources({ vault: process.env.THOTH_VAULT_PATH || "", project });
|
|
1002
1063
|
const tick = async () => {
|
|
1003
|
-
if (PINK.thoth.busy) return;
|
|
1064
|
+
if (PINK.thoth.busy || !PINK.thothOn) return;
|
|
1004
1065
|
PINK.thoth.busy = true;
|
|
1005
1066
|
try {
|
|
1006
1067
|
PINK.thoth.data = await pollThoth(sources);
|
|
@@ -1018,14 +1079,14 @@ export function install(pink, ctx, { CustomEditor, SessionManager, version = "",
|
|
|
1018
1079
|
PINK.thoth.timer = setInterval(tick, THOTH_POLL_MS);
|
|
1019
1080
|
PINK.thoth.timer.unref?.();
|
|
1020
1081
|
void tick();
|
|
1082
|
+
};
|
|
1083
|
+
const startQuota = () => {
|
|
1084
|
+
if (PINK.plan.timer || process.env.PINK_OFFLINE) return;
|
|
1021
1085
|
const planTick = async () => {
|
|
1022
1086
|
if (PINK.plan.busy) return;
|
|
1023
1087
|
PINK.plan.busy = true;
|
|
1024
|
-
const [cli, own] = await Promise.allSettled([readPlan(), readClaudeFromPink((provider) => ctx.modelRegistry?.getApiKeyForProvider?.(provider))]);
|
|
1025
1088
|
try {
|
|
1026
|
-
|
|
1027
|
-
// o uso medido pelo login do Pink vale mais que o da linha de status do Claude Code (que só atualiza com ele aberto)
|
|
1028
|
-
PINK.plan.data = own.status === "fulfilled" && own.value ? { ...data, ok: true, claude: own.value } : data;
|
|
1089
|
+
PINK.plan.data = await readQuota({ getKey: (provider) => ctx.modelRegistry?.getApiKeyForProvider?.(provider) });
|
|
1029
1090
|
} catch {
|
|
1030
1091
|
PINK.plan.data = { ok: false };
|
|
1031
1092
|
} finally {
|
|
@@ -1084,10 +1145,16 @@ export function install(pink, ctx, { CustomEditor, SessionManager, version = "",
|
|
|
1084
1145
|
const sessions = listed.some((item) => item.current) ? listed : [{ title, current: true, when: relativeTime(Date.now()) }, ...listed];
|
|
1085
1146
|
return leftColumn({ theme, width: LEFT_WIDTH, height, data: { sessions, tools: (pink.getActiveTools?.() ?? []).length } });
|
|
1086
1147
|
}
|
|
1148
|
+
const mcp = globalThis.__pinkMcp?.();
|
|
1149
|
+
PINK.thothOn = thothConfigured(mcp);
|
|
1150
|
+
startQuota();
|
|
1087
1151
|
if (PINK.thothOn) startThoth();
|
|
1088
1152
|
const stats = sessionStats(ctx.sessionManager?.getEntries?.());
|
|
1089
1153
|
const total = stats.models.reduce((sum, item) => ({ input: sum.input + item.input, output: sum.output + item.output }), { input: 0, output: 0 });
|
|
1090
|
-
|
|
1154
|
+
const branch = ctx.sessionManager?.getBranch?.() ?? [];
|
|
1155
|
+
const external = globalThis.__pinkAgentPanel?.(branch); // com /agente, SESSÃO é a dele, não a do modelo do Pink
|
|
1156
|
+
const used = external ?? { ...total, cost: stats.cost, models: stats.models.map((item) => item.model).filter((model) => model && model !== "?") };
|
|
1157
|
+
return rightColumn({ theme, width: RIGHT_WIDTH, height, data: { input: used.input, output: used.output, cost: used.cost, models: used.models, agent: external?.name, unreported: Boolean(external?.answered && !external.input && !external.output), project: PINK.thothOn ? project : "", context: bars().context, todos: PINK.todos, thoth: PINK.thothOn ? PINK.thoth.data : { ad: true }, plan: PINK.plan.data, mcp, mcpOpen: PINK.mcpOpen, hits: (PINK.rightHits = {}), changes: changesFromBranch([...branch, ...(external?.pending ?? [])], PINK.created), agents: [...runningSubagents(PINK.subagents, globalThis.__pinkSubagentJobs), ...(PINK.thothOn ? dagAgentsCached(ctx.cwd) : []), ...(globalThis.__pinkAgentChildren ?? [])] } });
|
|
1091
1158
|
}, []),
|
|
1092
1159
|
};
|
|
1093
1160
|
// tarefas sobre a caixa de digitar quando a coluna da direita não cabe (com ela, as tarefas aparecem no PLANO)
|
|
@@ -1335,7 +1402,7 @@ export function compactToolRenderer(toolName, next) {
|
|
|
1335
1402
|
if (options.expanded) return wrap(base?.renderResult?.(result, options, theme, context) ?? output(result, theme, 0), context.outputPad);
|
|
1336
1403
|
if (options.isPartial) return empty;
|
|
1337
1404
|
const time = context.durationMs >= 100 ? theme.fg("dim", ` · ${(context.durationMs / 1000).toFixed(1)}s`) : "";
|
|
1338
|
-
const summary = line(theme, context.outputPad, toolSummary(toolName, context.args ?? {}, result), `${time}${context.isError ? theme.fg("error", " · erro") : ""}`);
|
|
1405
|
+
const summary = line(theme, context.outputPad, toolSummary(toolName, context.args ?? {}, result), `${time}${context.isError ? theme.fg("error", t(" · erro", " · error", " · error")) : ""}`);
|
|
1339
1406
|
// edit e write: o diff fica aberto sob a linha (como no Claude Code); o write mostra as primeiras 40 linhas
|
|
1340
1407
|
const diff = context.isError ? "" : toolName === "edit" ? result?.details?.diff : toolName === "write" ? writeDiff(context.args?.content) : "";
|
|
1341
1408
|
if (!diff) return grouped(theme, context.outputPad, context.toolCallId, summary);
|
|
@@ -1352,6 +1419,14 @@ export function compactToolRenderer(toolName, next) {
|
|
|
1352
1419
|
};
|
|
1353
1420
|
}
|
|
1354
1421
|
|
|
1422
|
+
// texto de fora na tela: uma linha só, sem sequências de terminal nem caracteres de controle
|
|
1423
|
+
export const cleanLine = (text) => String(text ?? "").replace(/\x1b\[[0-9;?]*[A-Za-z]/g, "").replace(/[\u0000-\u001f\u007f-\u009f]|\p{Cf}/gu, " ").replace(/\s+/g, " ").trim();
|
|
1424
|
+
export const tailLine = (text, room) => { const line = cleanLine(text); return line.length > room ? `…${line.slice(1 - room)}` : line; };
|
|
1425
|
+
export function thinkingNow(text, room) {
|
|
1426
|
+
const line = tailLine(text, Math.max(10, room));
|
|
1427
|
+
return [t("∴ Pensando…", "∴ Pensando…", "∴ Thinking…"), ...(line ? [` ${line}`] : [])];
|
|
1428
|
+
}
|
|
1429
|
+
|
|
1355
1430
|
export function thinkingLabel(ms) {
|
|
1356
1431
|
return `+ ${t("Pensou", "Pensó", "Thought")}${ms > 0 ? ` · ${(ms / 1000).toFixed(1)}s` : ""}`;
|
|
1357
1432
|
}
|
|
@@ -1486,6 +1561,12 @@ export function setMode(ctx, mode) {
|
|
|
1486
1561
|
Object.defineProperty(globalThis, "__pinkPermissionMode", { get: () => currentMode(), configurable: true });
|
|
1487
1562
|
const MODE_ARGS = { perguntar: "ask", preguntar: "ask", ask: "ask", editar: "edits", edit: "edits", plano: "plan", plan: "plan" };
|
|
1488
1563
|
|
|
1564
|
+
const modeChoices = () => [
|
|
1565
|
+
{ value: t("perguntar", "preguntar", "ask"), description: t("pergunta antes de cada ação", "pregunta antes de cada acción", "asks before each action") },
|
|
1566
|
+
{ value: t("editar", "editar", "edit"), description: t("aceita edições de arquivo", "acepta ediciones de archivos", "accepts file edits") },
|
|
1567
|
+
{ value: t("plano", "plan", "plan"), description: t("só lê e planeja", "solo lee y planifica", "reads and plans only") },
|
|
1568
|
+
];
|
|
1569
|
+
|
|
1489
1570
|
export const INIT_PROMPT = "Analise este repositório e crie o arquivo AGENTS.md na raiz (ou atualize, se já existir, sem perder o que vale). Inclua, de forma concisa: os comandos de build, teste e lint (e como rodar um único teste), a arquitetura em alto nível e as convenções de código que um agente precisa seguir. Não invente o que não estiver no repositório.";
|
|
1490
1571
|
|
|
1491
1572
|
const DELETE_ITEM = t("× Apagar uma sessão…", "× Borrar una sesión…", "× Delete a session…");
|
|
@@ -1511,13 +1592,16 @@ async function deleteSession(ctx) {
|
|
|
1511
1592
|
}
|
|
1512
1593
|
|
|
1513
1594
|
function registerOpenCodeFunctions(pink) {
|
|
1514
|
-
const command = (name, description, handler) => pink.registerCommand?.(name, { description, handler });
|
|
1595
|
+
const command = (name, description, handler) => pink.registerCommand?.(name, { description, handler: noArgs(`/${name}`, handler) });
|
|
1596
|
+
let session;
|
|
1597
|
+
pink.on?.("session_start", async (_event, ctx) => { session = ctx; });
|
|
1598
|
+
const themeChoices = () => (session?.ui?.getAllThemes?.() ?? []).map((theme) => ({ value: theme.name }));
|
|
1515
1599
|
command("plan", t("Agente Plano: só lê e planeja, não edita (tab troca)", "Agente Plan: solo lee y planifica, no edita (tab cambia)", "Plan agent: reads and plans, does not edit (tab switches)"), async (_args, ctx) => switchAgent(ctx, "plan"));
|
|
1516
1600
|
command("build", t("Agente Build: edita e roda comandos (tab troca)", "Agente Build: edita y ejecuta comandos (tab cambia)", "Build agent: edits and runs commands (tab switches)"), async (_args, ctx) => switchAgent(ctx, "build"));
|
|
1517
1601
|
pink.registerShortcut?.("alt+m", { description: t("Troca o modo de permissão: pergunta tudo, aceita edições, plano", "Cambia el modo de permisos: pregunta todo, acepta ediciones, plan", "Switches the permission mode: ask everything, accept edits, plan"), handler: (ctx) => setMode(ctx, nextMode()) });
|
|
1518
1602
|
pink.registerCommand?.("modo", {
|
|
1519
1603
|
description: t("Modo de permissão: perguntar, editar ou plano (sem nome, troca para o próximo; alt+m)", "Modo de permisos: preguntar, editar o plan (sin nombre, pasa al siguiente; alt+m)", "Permission mode: ask, edit or plan (no name, moves to the next; alt+m)"),
|
|
1520
|
-
getArgumentCompletions: (
|
|
1604
|
+
getArgumentCompletions: completeFrom(modeChoices),
|
|
1521
1605
|
handler: async (args, ctx) => {
|
|
1522
1606
|
const name = String(args ?? "").trim().toLowerCase();
|
|
1523
1607
|
if (name && !MODE_ARGS[name]) return void ctx.ui.notify?.(t("Use /modo perguntar, /modo editar ou /modo plano", "Usa /modo preguntar, /modo editar o /modo plan", "Use /modo ask, /modo edit or /modo plan"), "warning");
|
|
@@ -1527,28 +1611,32 @@ function registerOpenCodeFunctions(pink) {
|
|
|
1527
1611
|
command("help", t("Paleta de comandos (ctrl+p)", "Paleta de comandos (ctrl+p)", "Command palette (ctrl+p)"), async (_args, ctx) => openPalette(pink, ctx));
|
|
1528
1612
|
command("details", t("Mostra ou esconde a saída das ferramentas (ctrl+o)", "Muestra u oculta la salida de las herramientas (ctrl+o)", "Show or hide tool output (ctrl+o)"), async (_args, ctx) => ctx.ui.setToolsExpanded?.(!ctx.ui.getToolsExpanded?.()));
|
|
1529
1613
|
command("init", t("Cria ou atualiza o AGENTS.md do projeto", "Crea o actualiza el AGENTS.md del proyecto", "Create or update the project's AGENTS.md"), async () => pink.sendUserMessage?.(INIT_PROMPT));
|
|
1530
|
-
|
|
1531
|
-
const
|
|
1614
|
+
pink.registerCommand?.("themes", { description: t("Escolhe o tema (fica salvo)", "Elige el tema (queda guardado)", "Choose the theme (it is saved)"), getArgumentCompletions: completeFrom(themeChoices), handler: async (args, ctx) => {
|
|
1615
|
+
const themes = (ctx.ui.getAllThemes?.() ?? []).map((theme) => theme.name);
|
|
1616
|
+
const typed = String(args ?? "").trim();
|
|
1617
|
+
if (typed && !themes.includes(typed)) return void unknown(ctx, "/themes", typed, themes.map((value) => ({ value })));
|
|
1618
|
+
const name = typed || (await ctx.ui.select?.("Temas", themes));
|
|
1532
1619
|
if (!name) return;
|
|
1533
1620
|
const done = ctx.ui.setTheme?.(name);
|
|
1534
1621
|
ctx.ui.notify?.(done?.success ? t(`Tema ${name}`, `Tema ${name}`, `Theme ${name}`) : t(`Tema ${name} não carregou: ${done?.error ?? "?"}`, `El tema ${name} no se cargó: ${done?.error ?? "?"}`, `Theme ${name} did not load: ${done?.error ?? "?"}`), done?.success ? "info" : "error");
|
|
1535
|
-
});
|
|
1622
|
+
} });
|
|
1536
1623
|
command("sessions", t("Lista as sessões desta pasta e troca de sessão", "Lista las sesiones de esta carpeta y cambia de sesión", "Lists this folder's sessions and switches session"), async (_args, ctx) => {
|
|
1537
1624
|
const { SessionManager } = await import("@earendil-works/pi-coding-agent");
|
|
1538
1625
|
const list = (await SessionManager.list(ctx.cwd)).sort((a, b) => b.modified - a.modified).slice(0, 40);
|
|
1539
|
-
if (!list.length) return void ctx.ui.notify?.(t("Nenhuma sessão salva nesta pasta", "
|
|
1626
|
+
if (!list.length) return void ctx.ui.notify?.(t("Nenhuma sessão salva nesta pasta ainda (ela é salva quando você conversa). /resume mostra as de outras pastas.", "Todavía no hay sesiones guardadas en esta carpeta (se guarda cuando conversas). /resume muestra las de otras carpetas.", "No saved sessions in this folder yet (one is saved when you chat). /resume shows other folders'."), "info");
|
|
1540
1627
|
const labels = list.map((item, i) => `${i + 1}. ${String(item.name || item.firstMessage || t("(sem título)", "(sin título)", "(untitled)")).replace(/\s+/g, " ").slice(0, 60)} · ${new Date(item.modified).toLocaleString(t("pt-BR", "es-419", "en-US"))}`);
|
|
1541
1628
|
const choice = await ctx.ui.select?.(t("Sessões", "Sesiones", "Sessions"), [DELETE_ITEM, ...labels]);
|
|
1542
1629
|
if (choice === DELETE_ITEM) return void (await deleteSession(ctx));
|
|
1543
1630
|
if (choice) await ctx.switchSession(list[labels.indexOf(choice)].path);
|
|
1544
1631
|
});
|
|
1545
|
-
|
|
1632
|
+
pink.registerCommand?.("session-open", { description: t("Abrir uma sessão pelo arquivo (o clique e alt+↑/↓ na coluna SESSÕES usam este)", "Abre una sesión por archivo (el clic y alt+↑/↓ en la columna SESIONES usan este)", "Open a session by file (the click and alt+↑/↓ in the SESSIONS column use this)"), handler: async (args, ctx) => {
|
|
1546
1633
|
const target = String(args ?? "").trim();
|
|
1547
|
-
if (target) await ctx.switchSession(target);
|
|
1548
|
-
|
|
1634
|
+
if (target && node("node:fs").existsSync(target)) return void (await ctx.switchSession(target));
|
|
1635
|
+
ctx.ui.notify?.(target ? t(`Sessão não encontrada: ${target}. Use /sessions para escolher na lista.`, `Sesión no encontrada: ${target}. Usa /sessions para elegir de la lista.`, `Session not found: ${target}. Use /sessions to pick from the list.`) : t("/session-open pede o arquivo da sessão. Use /sessions para escolher na lista.", "/session-open pide el archivo de la sesión. Usa /sessions para elegir de la lista.", "/session-open needs the session file. Use /sessions to pick from the list."), "warning");
|
|
1636
|
+
} });
|
|
1549
1637
|
command("delete-session", t("Apagar sessão (vai para a lixeira .trash, com confirmação)", "Borrar sesión (va a la papelera .trash, con confirmación)", "Delete session (moves it to the .trash bin, with confirmation)"), async (_args, ctx) => deleteSession(ctx));
|
|
1550
1638
|
command("todos", t("Mostra a lista de tarefas do agente", "Muestra la lista de tareas del agente", "Show the agent's task list"), async (_args, ctx) => {
|
|
1551
|
-
const lines = PINK.todos.length ? todoLines({ theme: ctx.ui.theme, todos: PINK.todos, width: 100 }) : [t("Sem tarefas nesta sessão", "Sin tareas en esta sesión", "No tasks in this session")];
|
|
1639
|
+
const lines = PINK.todos.length ? todoLines({ theme: ctx.ui.theme, todos: PINK.todos, width: 100 }) : [t("Sem tarefas nesta sessão (o agente cria a lista quando o pedido tem vários passos)", "Sin tareas en esta sesión (el agente crea la lista cuando el pedido tiene varios pasos)", "No tasks in this session (the agent creates the list when a request has several steps)")];
|
|
1552
1640
|
ctx.ui.notify?.(lines.join("\n"), "info");
|
|
1553
1641
|
});
|
|
1554
1642
|
command("undo", t("Desfaz a última mensagem, as respostas e as mudanças nos arquivos", "Deshace el último mensaje, las respuestas y los cambios en los archivos", "Undo the last message, the responses and the file changes"), async (_args, ctx) => {
|
|
@@ -1639,8 +1727,11 @@ function registerOpenCodeFunctions(pink) {
|
|
|
1639
1727
|
pink.on("turn_start", async () => {
|
|
1640
1728
|
PINK.turnStart = Date.now();
|
|
1641
1729
|
});
|
|
1642
|
-
pink.on("message_end", async (event) => {
|
|
1730
|
+
pink.on("message_end", async (event, ctx) => {
|
|
1643
1731
|
PINK.run?.add(event?.message);
|
|
1732
|
+
for (const run of PINK.thinking.get(event?.message?.timestamp) ?? []) run.ms ??= Date.now() - run.start; // interrompido no meio: não fica "Pensando" para sempre
|
|
1733
|
+
const hint = chatgptLimitHint(event?.message?.errorMessage);
|
|
1734
|
+
if (hint) ctx?.ui?.notify?.(hint, "warning");
|
|
1644
1735
|
const timing = event?.message?.role === "assistant" ? PINK.timing.get(event.message.timestamp) : undefined;
|
|
1645
1736
|
if (timing?.start) timing.ms = Date.now() - timing.start;
|
|
1646
1737
|
});
|
|
@@ -1671,6 +1762,7 @@ function registerOpenCodeFunctions(pink) {
|
|
|
1671
1762
|
});
|
|
1672
1763
|
// seções do prompt, não o prompt inteiro: devolver systemPrompt forçava o texto e apagava as seções das outras extensões (Ponytail)
|
|
1673
1764
|
pink.on("before_agent_start", async (event) => {
|
|
1765
|
+
if (!thothConfigured()) for (const file of event?.systemPromptOptions?.contextFiles ?? []) file.content = stripThothRules(file.content);
|
|
1674
1766
|
const sections = event?.systemPromptOptions?.sections;
|
|
1675
1767
|
if (!sections || typeof sections !== "object") return { systemPrompt: `${event.systemPrompt ?? ""}${LANGUAGE_PROMPT}${PINK.agent === "plan" ? PLAN_PROMPT : ""}` };
|
|
1676
1768
|
sections.pink_language = LANGUAGE_PROMPT.trim();
|
|
@@ -1723,12 +1815,13 @@ export default function (pink) {
|
|
|
1723
1815
|
globalThis.__pinkExitBanner = undefined; // sem fechamento, o Pink imprime a linha dele
|
|
1724
1816
|
}
|
|
1725
1817
|
});
|
|
1818
|
+
pink.on("input", builtinWithArgs);
|
|
1726
1819
|
pink.registerCommand?.("lateral", {
|
|
1727
1820
|
description: t("Mostra ou esconde a lateral (sessão, contexto, tokens)", "Muestra u oculta la barra lateral (sesión, contexto, tokens)", "Show or hide the sidebar (session, context, tokens)"),
|
|
1728
|
-
handler: async (_args, ctx) => {
|
|
1821
|
+
handler: noArgs("/lateral", async (_args, ctx) => {
|
|
1729
1822
|
globalThis.__pinkSidebarOn = !(globalThis.__pinkSidebarOn ?? true);
|
|
1730
1823
|
ctx.ui.notify?.(globalThis.__pinkSidebarOn ? t("Lateral visível", "Barra lateral visible", "Sidebar shown") : t("Lateral escondida", "Barra lateral oculta", "Sidebar hidden"), "info");
|
|
1731
|
-
},
|
|
1824
|
+
}),
|
|
1732
1825
|
});
|
|
1733
1826
|
registerOpenCodeFunctions(pink);
|
|
1734
1827
|
pink.registerToolRenderer?.(compactToolRenderer);
|