@thothdev/pink 1.0.15 → 1.0.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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
  "██████╗ ██╗███╗ ██╗██╗ ██╗",
@@ -104,11 +104,12 @@ export function inputBox({ theme, content, width, label, inline = false, hints =
104
104
  // os botões do microfone (opcional) vão antes das dicas; sem lugar para os dois, as dicas saem
105
105
  const tip = mic ? (visible(left) + 1 + visible(mic) + 3 + visible(hint) <= text ? `${mic} ${hint}` : mic) : hint;
106
106
  // a coluna onde os botões começam dentro da caixa (a barra e um espaço vêm antes), para o clique
107
- const at = (rowIndex) => Object.assign(out, mic ? { micAt: { y: rowIndex, x: 2 + Math.max(visible(left) + 1, text - visible(tip)) } } : {});
107
+ const at = (rowIndex) => Object.assign(out, mic ? { micAt: { y: rowIndex, x: own ? 2 : 2 + Math.max(visible(left) + 1, text - visible(tip)) } } : {});
108
108
  let out;
109
109
  if (own) {
110
- // rótulo e dicas não cabem juntos: o rótulo ganha a linha dele, em vez de cortar as dicas
111
- out = [row(""), ...lines.map(row), row(""), row(theme.fg("muted", label)), row(footerLine({ theme, width: text, left: "", right: tip })), row("")];
110
+ // rótulo e dicas não cabem juntos: o rótulo ganha a linha dele, em vez de cortar as dicas; as dicas embaixo,
111
+ // alinhadas à esquerda com o rótulo (à direita ficavam com um recuo solto na tela dividida, owner 2026-11-26)
112
+ out = [row(""), ...lines.map(row), row(""), row(theme.fg("muted", label)), row(tip), row("")];
112
113
  return at(out.length - 2);
113
114
  }
114
115
  // linha vazia também embaixo do rótulo, como a caixa do OpenCode (owner 2026-11-24)
@@ -121,20 +122,18 @@ export function footerLine({ theme, width, left, right }) {
121
122
  return fit(`${left}${" ".repeat(gap)}${right}`, width);
122
123
  }
123
124
 
124
- 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") };
125
-
126
125
  // "thoth thoth off" dizia modelo, provedor e nível sem explicar nada: agora o nome do modelo, o provedor só quando é
127
- // outro, e o pensamento só quando está ligado ("pensamento alto")
126
+ // outro, e o nível só quando está ligado ("Sonnet 5.5 · medium", o nível sempre na palavra em inglês)
128
127
  // como no OpenCode, o agente (Build/Plano) vem antes do modelo, na cor da marca
129
128
  export function modelLabel({ theme, model, thinking, agent, permission = "edits", external = Reflect.get(globalThis, "__pinkExternalAgent") }) {
130
129
  const mode = agent === "build" && permission === "ask" ? t(" (pergunta tudo)", " (pregunta todo)", " (ask everything)") : "";
131
130
  const who = AGENTS[agent] ? `${theme.fg("accent", `${AGENTS[agent].label}${mode}`)}${theme.fg("muted", " · ")}` : "";
132
131
  // /agente ligado (card 1dfwh7kgfjr): o Build fica; no lugar do modelo do Pink, o agente instalado e o modelo dele
133
- if (external?.name) return `${who}${external.name}${theme.fg("muted", ` · ${external.model ?? t("modelo padrão", "modelo predeterminado", "default model")}${external.effort ? ` · ${t("esforço", "esfuerzo", "effort")} ${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}` : ""}`)}`;
134
133
  if (!model) return `${who}${theme.fg("muted", t("sem modelo", "sin modelo", "no model"))}`;
135
134
  const name = model.name || model.id;
136
135
  const provider = model.provider && model.provider !== model.id && model.provider !== name ? theme.fg("muted", ` · ${model.provider}`) : "";
137
- const level = THINKING_PT[thinking] ? theme.fg("muted", ` · ${t("pensamento", "razonamiento", "thinking")} ${THINKING_PT[thinking]}`) : "";
136
+ const level = thinking && thinking !== "off" ? theme.fg("muted", ` · ${thinking}`) : "";
138
137
  return `${who}${name}${provider}${level}`;
139
138
  }
140
139
 
@@ -380,7 +379,7 @@ export function leftColumn({ theme, width, height, data }) {
380
379
  export function rightColumn({ theme, width, height, data }) {
381
380
  // CONTEXTO, PLANO (o todowrite), ALTERAÇÕES (edit/write desta sessão) e SESSÃO (tokens; custo só quando há)
382
381
  const inner = Math.max(6, width - 3);
383
- const out = [heading(theme, "CONTEXTO")];
382
+ const out = [heading(theme, t("CONTEXTO", "CONTEXTO", "CONTEXT"))];
384
383
  const ctx = data.context;
385
384
  if (ctx?.tokens != null && ctx.window) {
386
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)}`)}`);
@@ -413,18 +412,19 @@ export function rightColumn({ theme, width, height, data }) {
413
412
  } else {
414
413
  out.push(theme.fg("dim", t("nenhum arquivo alterado", "ningún archivo cambiado", "no files changed")));
415
414
  }
416
- 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}`) : ""));
417
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"))}`);
418
417
  if (data.models?.length) out.push(theme.fg("muted", `${t("modelo", "modelo", "model")} ${data.models.map(shortModel).join(", ")}`));
419
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")));
420
420
  if (data.project) out.push(theme.fg("muted", `${t("projeto", "proyecto", "project")} ${data.project}`));
421
421
  // SUBAGENTES por último, abaixo da SESSÃO (owner 2026-11-25): a lista cresce no espaço livre do fim da coluna
422
422
  const agents = data.agents ?? [];
423
- if (agents.length) {
424
- out.push("", rule(theme, inner), heading(theme, t("SUBAGENTES", "SUBAGENTES", "SUBAGENTS"), theme.fg("muted", ` ${agents.length}`)));
425
- for (const item of agents) out.push(agentLine(theme, item, inner, data.now));
426
- }
427
- 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));
428
428
  return [...lines, ...Array(Math.max(0, height - lines.length)).fill(" ".repeat(inner))].map((line) => `${theme.fg("borderMuted", "│")} ${line} `);
429
429
  }
430
430
 
@@ -492,12 +492,12 @@ export function changesFromBranch(entries, created = new Set()) {
492
492
  // arquivos que as ferramentas edit/write tocaram no ramo atual (o /undo volta o ramo, e a lista volta junto)
493
493
  const seen = new Map();
494
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");
495
498
  const message = entry?.type === "message" ? entry.message : undefined;
496
499
  if (message?.role !== "assistant" || !Array.isArray(message.content)) continue;
497
- for (const part of message.content) {
498
- const path = part?.type === "toolCall" && (part.name === "edit" || part.name === "write") ? part.arguments?.path : undefined;
499
- if (typeof path === "string" && path && !seen.has(path)) seen.set(path, created.has(path) ? "novo" : "editado");
500
- }
500
+ for (const part of message.content) if (part?.type === "toolCall" && (part.name === "edit" || part.name === "write")) add(part.arguments?.path);
501
501
  }
502
502
  return [...seen.entries()].map(([path, status]) => ({ path: path.replace(/\\/g, "/"), status }));
503
503
  }
@@ -580,7 +580,7 @@ export function thothSnapshot({ approvals, cards, calls }, now = Date.now()) {
580
580
  }
581
581
 
582
582
  export function thothLines({ theme, thoth, width }) {
583
- // sem o Thoth instalado: uma apresentação curta no lugar da seção (owner 2026-11-24: "propaganda para todos")
583
+ // sem o Thoth: uma apresentação fixa, sem processo nem rede (owner 2026-11-24: "propaganda para todos")
584
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))];
585
585
  if (!thoth?.ok) return [theme.fg("dim", thoth?.loading ? t("consultando…", "consultando…", "loading…") : t("Thoth indisponível", "Thoth no disponible", "Thoth unavailable"))];
586
586
  const row = (label, value, tone = "text") => {
@@ -598,15 +598,13 @@ export function thothLines({ theme, thoth, width }) {
598
598
  ];
599
599
  }
600
600
 
601
- // o Thoth é outro produto: THOTH e COTA só aparecem (e só consultam) com ele nesta máquina (variáveis ou CLI no PATH)
602
- export function thothInstalled(env = process.env, exists = (file) => Boolean(process.getBuiltinModule?.("node:fs")?.existsSync(file)), platform = process.platform) {
603
- if (env.THOTH_VAULT_PATH || env.THOTH_TOKEN) return true;
604
- const exts = platform === "win32" ? [".exe", ".cmd"] : [""];
605
- return String(env.PATH || env.Path || "").split(platform === "win32" ? ";" : ":").some((dir) => {
606
- const base = dir.trim().replace(/^"|"$/g, "").replace(/[\\/]+$/, "");
607
- return base && ["thoth", "thoth-client"].some((name) => exts.some((ext) => exists(`${base}/${name}${ext}`)));
608
- });
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");
609
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, "");
610
608
 
611
609
  // as fontes reais: o CLI `thoth approvals list --json`, o painel local (/api/work-center/cards) e as chamadas do
612
610
  // gateway thoth free (/v1/thoth/calls). Todas só leem; o token do gateway vai no
@@ -643,22 +641,23 @@ export function thothSources({ vault, project, env = process.env }) {
643
641
  };
644
642
  }
645
643
 
646
- // -- COTA: o mesmo uso do plano do painel local (thoth-client uso estado --json): 5 horas e semana do Claude e do Codex
647
- export const PLAN_POLL_MS = 180000; // o CLI leva ~15 s (pergunta ao Codex e soma o mês): de 3 em 3 minutos basta
648
- export function planSnapshot(raw, now = Date.now() / 1000) {
649
- const pick = (usage) => {
650
- const out = {};
651
- for (const key of ["h5", "week"]) {
652
- const window = usage?.[key];
653
- const pct = Number(window?.pct), resets = Number(window?.resets_at);
654
- if (!Number.isFinite(pct) || !Number.isFinite(resets)) continue;
655
- out[key] = resets <= now ? { pct: 0 } : { pct: Math.max(0, Math.min(100, pct)), resets };
656
- }
657
- return Object.keys(out).length ? out : undefined;
658
- };
659
- const claude = raw?.claude?.installed ? pick(raw.claude.usage) ?? null : undefined;
660
- const codex = raw?.codex?.installed ? pick(raw.codex.usage) ?? null : undefined;
661
- return { ok: claude !== undefined || codex !== undefined, claude, codex };
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
+ );
662
661
  }
663
662
 
664
663
  export function resetLabel(epoch, now = new Date()) {
@@ -669,33 +668,14 @@ export function resetLabel(epoch, now = new Date()) {
669
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}`;
670
669
  }
671
670
 
672
- // por que a leitura falhou: sem o motivo, "sem dado do plano" numa máquina nova não diz o que fazer
673
- const PLAN_FAILURE = {
674
- missing: t("thoth-client não achado no PATH", "thoth-client no está en el PATH", "thoth-client not on PATH"),
675
- slow: t("thoth-client demorou mais de 60 s", "thoth-client tardó más de 60 s", "thoth-client took over 60 s"),
676
- old: t("thoth-client antigo: atualize", "thoth-client antiguo: actualiza", "old thoth-client: update it"),
677
- bad: t("resposta inválida do thoth-client", "respuesta inválida de thoth-client", "invalid thoth-client output"),
678
- failed: t("rode: thoth-client uso estado", "ejecuta: thoth-client uso estado", "run: thoth-client uso estado"),
679
- };
680
- export function planFailure(error, stderr = "") {
681
- if (error?.code === "ENOENT") return "missing";
682
- if (error?.killed || error?.code === "ETIMEDOUT") return "slow";
683
- if (/invalid choice|unrecognized arguments|escolha inválida/i.test(String(stderr))) return "old";
684
- return "failed";
685
- }
686
-
687
671
  export function planLines({ theme, plan, width, now = new Date() }) {
688
- if (!plan?.ok && plan?.loading) return [theme.fg("dim", t("consultando…", "consultando…", "loading…"))];
689
- if (!plan?.ok) {
690
- const why = PLAN_FAILURE[plan?.reason];
691
- return [theme.fg("dim", t("sem dado do plano", "sin dato del plan", "no plan data")), ...(why ? [theme.fg("warning", fit(why, width))] : [])];
692
- }
672
+ if (!plan?.ok) return [theme.fg("dim", plan?.loading ? t("consultando…", "consultando…", "loading…") : t("sem leitura", "sin lectura", "no reading"))];
693
673
  const out = [];
694
674
  for (const [name, usage] of [["Claude", plan.claude], ["Codex", plan.codex]]) {
695
675
  if (usage === undefined) continue;
696
676
  out.push(theme.fg("text", name));
697
677
  if (!usage) {
698
- out.push(theme.fg("dim", name === "Claude" ? t(" ligue: thoth-client uso ativar", " activa: thoth-client uso activar", " turn on: thoth-client uso activar") : t(" sem leitura ainda", " sin lectura todavía", " no reading yet")));
678
+ out.push(theme.fg("dim", t(" sem leitura", " sin lectura", " no reading")));
699
679
  continue;
700
680
  }
701
681
  for (const [key, label] of [["h5", "5 h"], ["week", t("semana", "semana", "week")]]) {
@@ -708,7 +688,7 @@ export function planLines({ theme, plan, width, now = new Date() }) {
708
688
  out.push(` ${meter({ theme, percent: window.pct, cells: Math.max(4, width - 2) })}`);
709
689
  }
710
690
  }
711
- return out.length ? out : [theme.fg("dim", "nenhum plano conectado")];
691
+ return out.length ? out : [theme.fg("dim", t("sem leitura", "sin lectura", "no reading"))];
712
692
  }
713
693
 
714
694
  // -- MCP (como a lateral do OpenCode): título com a contagem; clique abre a lista completa com o estado de cada um
@@ -731,37 +711,107 @@ export function mcpLines({ theme, mcp, open, width }) {
731
711
  export function claudeUsageWindows(body, now = Date.now() / 1000) {
732
712
  const out = {};
733
713
  for (const [key, name] of [["five_hour", "h5"], ["seven_day", "week"]]) {
734
- const pct = Number(body?.[key]?.utilization);
735
- const resets = Date.parse(body?.[key]?.resets_at ?? "") / 1000;
736
- if (!Number.isFinite(pct) || !Number.isFinite(resets)) continue;
737
- 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);
738
717
  }
739
718
  return Object.keys(out).length ? out : undefined;
740
719
  }
741
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
742
732
  export async function readClaudeFromPink(getKey, fetcher = fetch) {
743
733
  const token = await getKey?.("anthropic");
744
734
  if (typeof token !== "string" || !token.startsWith("sk-ant-oat")) return undefined;
745
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) });
746
- if (!response.ok) return undefined;
747
- return claudeUsageWindows(await response.json());
736
+ if (!response.ok) return null;
737
+ return claudeUsageWindows(await response.json()) ?? null;
748
738
  }
749
739
 
750
- export function readPlan(run = node("node:child_process")?.execFile) {
751
- return new Promise((resolve, reject) => {
752
- if (!run) return reject(new Error("no child_process"));
753
- run("thoth-client", ["uso", "estado", "--json"], { timeout: 60000, windowsHide: true, maxBuffer: 4 << 20 }, (error, stdout, stderr) => {
754
- if (error) return reject(Object.assign(error, { reason: planFailure(error, stderr) }));
755
- const text = String(stdout ?? "");
756
- try {
757
- resolve(planSnapshot(JSON.parse(text.slice(Math.max(0, text.indexOf("{")))))); // aviso impresso antes do JSON não derruba a leitura
758
- } catch (parse) {
759
- reject(Object.assign(parse, { reason: "bad" }));
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);
760
785
  }
761
786
  });
787
+ child.stdin.write(input);
762
788
  });
763
789
  }
764
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
+
765
815
  export async function pollThoth(sources, now = Date.now()) {
766
816
  const names = ["approvals", "cards", "calls"];
767
817
  const settled = await Promise.allSettled(names.map((name) => Promise.resolve().then(() => sources[name]())));
@@ -822,8 +872,16 @@ export function install(pink, ctx, { CustomEditor, SessionManager, version = "",
822
872
  };
823
873
  // sessão do multiplexador (pink/mux): progresso (OSC 9;4) enquanto trabalha e sino ao terminar, para a lateral mostrar o estado
824
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();
825
882
  const runStarted = () => {
826
883
  signal("\x1b]9;4;3\x07");
884
+ signalSession();
827
885
  leaveHome();
828
886
  };
829
887
  pink.on("agent_start", runStarted);
@@ -843,9 +901,7 @@ export function install(pink, ctx, { CustomEditor, SessionManager, version = "",
843
901
  PINK.refreshSessions = loadSessions; // o "Apagar sessão" relê a coluna depois de mover o arquivo
844
902
  const runEnded = () => {
845
903
  signal("\x1b]9;4;0\x07\x07");
846
- // o multiplexador guarda o arquivo de cada sessão aberta para reabri-la no próximo Pink (card 1dfwh7kfyty)
847
- const file = ctx.sessionManager?.getSessionFile?.();
848
- if (file) signal(`\x1b]9;pink-session=${file}\x07`);
904
+ signalSession();
849
905
  // título automático (owner 2026-10-29): só quando a sessão ainda não tem nome
850
906
  if (!pink.getSessionName?.()) {
851
907
  const title = autoTitle(ctx.sessionManager?.getBranch?.());
@@ -864,7 +920,7 @@ export function install(pink, ctx, { CustomEditor, SessionManager, version = "",
864
920
  ctx.ui.setHeader((tui, theme) => {
865
921
  state.tui = tui;
866
922
  return {
867
- render: live((width) => (state.home ? homeHeader({ theme, width, rows: homeRows(), subtitle: `coding agent · ${t("modelo", "modelo", "model")} ${ctx.model?.id ?? "thoth"}` }) : []), []),
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")}` }) : []), []),
868
924
  invalidate() {},
869
925
  };
870
926
  });
@@ -891,6 +947,11 @@ export function install(pink, ctx, { CustomEditor, SessionManager, version = "",
891
947
  if (globalThis.__pinkAgentSendNow?.(text)) return void this.setText("");
892
948
  return void super.handleInput("\r");
893
949
  }
950
+ // Esc com texto na caixa (e sem lista de sugestões aberta): limpa a caixa primeiro, como o Claude Code; o próximo
951
+ // Esc interrompe. Antes o Esc só interrompia, e um prompt longo na caixa não tinha como sair (owner 2026-11-26)
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;
894
955
  super.handleInput(data);
895
956
  }
896
957
 
@@ -967,7 +1028,12 @@ export function install(pink, ctx, { CustomEditor, SessionManager, version = "",
967
1028
  // o título do bloco aberto vem do patch thinking-header-when-shown
968
1029
  ctx.ui.setHiddenThinkingLabel?.(t("+ Pensou", "+ Pensó", "+ Thought"));
969
1030
  globalThis.__pinkThinkingHeader = t("− Pensou · clique ou ctrl+t recolhe", "− Pensó · haz clic o ctrl+t contrae", "− Thought · click or ctrl+t collapses");
970
- globalThis.__pinkThinkingLabel = (message, runIndex) => thinkingLabel(PINK.thinking.get(message?.timestamp)?.[runIndex]?.ms);
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
+ };
971
1037
  // "Pink · Build" sobre cada resposta (patch assistant-label); o agente é o da hora da resposta, desconhecido em sessão reaberta
972
1038
  // rodapé de cada resposta final (patch assistant-footer), lido a cada quadro: o tempo chega no message_end
973
1039
  globalThis.__pinkAssistantFooter = live((message, streaming, width, outputPad = 1) => {
@@ -988,15 +1054,14 @@ export function install(pink, ctx, { CustomEditor, SessionManager, version = "",
988
1054
  return "";
989
1055
  }
990
1056
  })();
991
- // a seção THOTH só consulta quando a coluna da direita aparece pela primeira vez; um único relógio para o processo todo
992
- // (trocar de sessão reinstala a interface e só troca quem redesenha), sem segurar a saída do Pink (unref)
993
- PINK.thothOn = thothInstalled();
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;
994
1060
  const startThoth = () => {
995
- PINK.thoth.redraw = redraw;
996
1061
  if (PINK.thoth.timer) return;
997
1062
  const sources = thothSources({ vault: process.env.THOTH_VAULT_PATH || "", project });
998
1063
  const tick = async () => {
999
- if (PINK.thoth.busy) return;
1064
+ if (PINK.thoth.busy || !PINK.thothOn) return;
1000
1065
  PINK.thoth.busy = true;
1001
1066
  try {
1002
1067
  PINK.thoth.data = await pollThoth(sources);
@@ -1014,14 +1079,14 @@ export function install(pink, ctx, { CustomEditor, SessionManager, version = "",
1014
1079
  PINK.thoth.timer = setInterval(tick, THOTH_POLL_MS);
1015
1080
  PINK.thoth.timer.unref?.();
1016
1081
  void tick();
1082
+ };
1083
+ const startQuota = () => {
1084
+ if (PINK.plan.timer || process.env.PINK_OFFLINE) return;
1017
1085
  const planTick = async () => {
1018
1086
  if (PINK.plan.busy) return;
1019
1087
  PINK.plan.busy = true;
1020
- const [cli, own] = await Promise.allSettled([readPlan(), readClaudeFromPink((provider) => ctx.modelRegistry?.getApiKeyForProvider?.(provider))]);
1021
1088
  try {
1022
- const data = cli.status === "fulfilled" ? cli.value : { ok: false, reason: cli.reason?.reason };
1023
- // o uso medido pelo login do Pink vale mais que o da linha de status do Claude Code (que só atualiza com ele aberto)
1024
- 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) });
1025
1090
  } catch {
1026
1091
  PINK.plan.data = { ok: false };
1027
1092
  } finally {
@@ -1080,10 +1145,16 @@ export function install(pink, ctx, { CustomEditor, SessionManager, version = "",
1080
1145
  const sessions = listed.some((item) => item.current) ? listed : [{ title, current: true, when: relativeTime(Date.now()) }, ...listed];
1081
1146
  return leftColumn({ theme, width: LEFT_WIDTH, height, data: { sessions, tools: (pink.getActiveTools?.() ?? []).length } });
1082
1147
  }
1148
+ const mcp = globalThis.__pinkMcp?.();
1149
+ PINK.thothOn = thothConfigured(mcp);
1150
+ startQuota();
1083
1151
  if (PINK.thothOn) startThoth();
1084
1152
  const stats = sessionStats(ctx.sessionManager?.getEntries?.());
1085
1153
  const total = stats.models.reduce((sum, item) => ({ input: sum.input + item.input, output: sum.output + item.output }), { input: 0, output: 0 });
1086
- return rightColumn({ theme, width: RIGHT_WIDTH, height, data: { ...total, cost: stats.cost, models: stats.models.map((item) => item.model).filter((model) => model && model !== "?"), project, context: bars().context, todos: PINK.todos, thoth: PINK.thothOn ? PINK.thoth.data : { ad: true }, plan: PINK.thothOn ? PINK.plan.data : undefined, mcp: globalThis.__pinkMcp?.(), mcpOpen: PINK.mcpOpen, hits: (PINK.rightHits = {}), changes: changesFromBranch(ctx.sessionManager?.getBranch?.(), PINK.created), agents: [...runningSubagents(PINK.subagents, globalThis.__pinkSubagentJobs), ...dagAgentsCached(ctx.cwd), ...(globalThis.__pinkAgentChildren ?? [])] } });
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 ?? [])] } });
1087
1158
  }, []),
1088
1159
  };
1089
1160
  // tarefas sobre a caixa de digitar quando a coluna da direita não cabe (com ela, as tarefas aparecem no PLANO)
@@ -1331,7 +1402,7 @@ export function compactToolRenderer(toolName, next) {
1331
1402
  if (options.expanded) return wrap(base?.renderResult?.(result, options, theme, context) ?? output(result, theme, 0), context.outputPad);
1332
1403
  if (options.isPartial) return empty;
1333
1404
  const time = context.durationMs >= 100 ? theme.fg("dim", ` · ${(context.durationMs / 1000).toFixed(1)}s`) : "";
1334
- 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")) : ""}`);
1335
1406
  // edit e write: o diff fica aberto sob a linha (como no Claude Code); o write mostra as primeiras 40 linhas
1336
1407
  const diff = context.isError ? "" : toolName === "edit" ? result?.details?.diff : toolName === "write" ? writeDiff(context.args?.content) : "";
1337
1408
  if (!diff) return grouped(theme, context.outputPad, context.toolCallId, summary);
@@ -1348,6 +1419,14 @@ export function compactToolRenderer(toolName, next) {
1348
1419
  };
1349
1420
  }
1350
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
+
1351
1430
  export function thinkingLabel(ms) {
1352
1431
  return `+ ${t("Pensou", "Pensó", "Thought")}${ms > 0 ? ` · ${(ms / 1000).toFixed(1)}s` : ""}`;
1353
1432
  }
@@ -1375,6 +1454,9 @@ export function tokenLabel(n) {
1375
1454
  export const runLabel = ({ ms, output }) => `${elapsedLabel(ms)} · ↓ ${tokenLabel(output)} tokens`;
1376
1455
  // "Trabalhando… (6s · ↓ 306 tokens)", como o "Thinking… (...)" do Claude Code; o /agente usa o mesmo
1377
1456
  export const workingLabel = (run) => `${t("Trabalhando", "Trabajando", "Working")}… (${runLabel(run)})`;
1457
+ // 3 min sem token novo: avisa (um comando longo, como um build, também cai aqui; por isso "sem resposta", não "travou")
1458
+ export const STALL_MS = 3 * 60 * 1000;
1459
+ export const stallNote = (quietMs) => (quietMs >= STALL_MS ? ` · ${t("sem resposta há", "sin respuesta hace", "no output for")} ${elapsedLabel(quietMs).replace(/ \d+s$/, "")} · ${t("esc interrompe", "esc interrumpe", "esc stops")}` : "");
1378
1460
 
1379
1461
  // os provedores só mandam usage.output no fim de cada passo: durante o passo, estima pelo texto que já chegou (~4 caracteres/token)
1380
1462
  export function streamedTokens(message) {
@@ -1479,6 +1561,12 @@ export function setMode(ctx, mode) {
1479
1561
  Object.defineProperty(globalThis, "__pinkPermissionMode", { get: () => currentMode(), configurable: true });
1480
1562
  const MODE_ARGS = { perguntar: "ask", preguntar: "ask", ask: "ask", editar: "edits", edit: "edits", plano: "plan", plan: "plan" };
1481
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
+
1482
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.";
1483
1571
 
1484
1572
  const DELETE_ITEM = t("× Apagar uma sessão…", "× Borrar una sesión…", "× Delete a session…");
@@ -1504,13 +1592,16 @@ async function deleteSession(ctx) {
1504
1592
  }
1505
1593
 
1506
1594
  function registerOpenCodeFunctions(pink) {
1507
- 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 }));
1508
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"));
1509
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"));
1510
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()) });
1511
1602
  pink.registerCommand?.("modo", {
1512
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)"),
1513
- getArgumentCompletions: (prefix) => Object.keys(MODE_ARGS).filter((name) => name.startsWith(prefix)).map((name) => ({ value: name, label: name })),
1604
+ getArgumentCompletions: completeFrom(modeChoices),
1514
1605
  handler: async (args, ctx) => {
1515
1606
  const name = String(args ?? "").trim().toLowerCase();
1516
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");
@@ -1520,28 +1611,32 @@ function registerOpenCodeFunctions(pink) {
1520
1611
  command("help", t("Paleta de comandos (ctrl+p)", "Paleta de comandos (ctrl+p)", "Command palette (ctrl+p)"), async (_args, ctx) => openPalette(pink, ctx));
1521
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?.()));
1522
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));
1523
- command("themes", t("Escolhe o tema (fica salvo)", "Elige el tema (queda guardado)", "Choose the theme (it is saved)"), async (_args, ctx) => {
1524
- const name = await ctx.ui.select?.("Temas", (ctx.ui.getAllThemes?.() ?? []).map((theme) => theme.name));
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));
1525
1619
  if (!name) return;
1526
1620
  const done = ctx.ui.setTheme?.(name);
1527
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");
1528
- });
1622
+ } });
1529
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) => {
1530
1624
  const { SessionManager } = await import("@earendil-works/pi-coding-agent");
1531
1625
  const list = (await SessionManager.list(ctx.cwd)).sort((a, b) => b.modified - a.modified).slice(0, 40);
1532
- if (!list.length) return void ctx.ui.notify?.(t("Nenhuma sessão salva nesta pasta", "Ninguna sesión guardada en esta carpeta", "No saved sessions in this folder"), "info");
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");
1533
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"))}`);
1534
1628
  const choice = await ctx.ui.select?.(t("Sessões", "Sesiones", "Sessions"), [DELETE_ITEM, ...labels]);
1535
1629
  if (choice === DELETE_ITEM) return void (await deleteSession(ctx));
1536
1630
  if (choice) await ctx.switchSession(list[labels.indexOf(choice)].path);
1537
1631
  });
1538
- command("session-open", 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)"), async (args, ctx) => {
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) => {
1539
1633
  const target = String(args ?? "").trim();
1540
- if (target) await ctx.switchSession(target);
1541
- });
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
+ } });
1542
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));
1543
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) => {
1544
- 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)")];
1545
1640
  ctx.ui.notify?.(lines.join("\n"), "info");
1546
1641
  });
1547
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) => {
@@ -1632,8 +1727,11 @@ function registerOpenCodeFunctions(pink) {
1632
1727
  pink.on("turn_start", async () => {
1633
1728
  PINK.turnStart = Date.now();
1634
1729
  });
1635
- pink.on("message_end", async (event) => {
1730
+ pink.on("message_end", async (event, ctx) => {
1636
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");
1637
1735
  const timing = event?.message?.role === "assistant" ? PINK.timing.get(event.message.timestamp) : undefined;
1638
1736
  if (timing?.start) timing.ms = Date.now() - timing.start;
1639
1737
  });
@@ -1664,6 +1762,7 @@ function registerOpenCodeFunctions(pink) {
1664
1762
  });
1665
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)
1666
1764
  pink.on("before_agent_start", async (event) => {
1765
+ if (!thothConfigured()) for (const file of event?.systemPromptOptions?.contextFiles ?? []) file.content = stripThothRules(file.content);
1667
1766
  const sections = event?.systemPromptOptions?.sections;
1668
1767
  if (!sections || typeof sections !== "object") return { systemPrompt: `${event.systemPrompt ?? ""}${LANGUAGE_PROMPT}${PINK.agent === "plan" ? PLAN_PROMPT : ""}` };
1669
1768
  sections.pink_language = LANGUAGE_PROMPT.trim();
@@ -1716,12 +1815,13 @@ export default function (pink) {
1716
1815
  globalThis.__pinkExitBanner = undefined; // sem fechamento, o Pink imprime a linha dele
1717
1816
  }
1718
1817
  });
1818
+ pink.on("input", builtinWithArgs);
1719
1819
  pink.registerCommand?.("lateral", {
1720
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)"),
1721
- handler: async (_args, ctx) => {
1821
+ handler: noArgs("/lateral", async (_args, ctx) => {
1722
1822
  globalThis.__pinkSidebarOn = !(globalThis.__pinkSidebarOn ?? true);
1723
1823
  ctx.ui.notify?.(globalThis.__pinkSidebarOn ? t("Lateral visível", "Barra lateral visible", "Sidebar shown") : t("Lateral escondida", "Barra lateral oculta", "Sidebar hidden"), "info");
1724
- },
1824
+ }),
1725
1825
  });
1726
1826
  registerOpenCodeFunctions(pink);
1727
1827
  pink.registerToolRenderer?.(compactToolRenderer);