@thothdev/pink 1.0.7 → 1.0.9
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
CHANGED
|
@@ -3,6 +3,26 @@
|
|
|
3
3
|
O Pink é um fork do Pi (MIT, veja `LICENSE-PI.txt` e `NOTICE.md`). Aqui só entra o que mudou no Pink; a base de cada
|
|
4
4
|
versão está no campo `upstream` do `rebrand.json` do repositório.
|
|
5
5
|
|
|
6
|
+
## [1.0.9] - 2026-11-24
|
|
7
|
+
|
|
8
|
+
- COTA: quando o uso do plano não chega, a lateral diz o motivo (`thoth-client` fora do PATH, antigo, lento ou com
|
|
9
|
+
resposta inválida) em vez de só "sem dado do plano"; um aviso impresso antes do JSON não quebra mais a leitura.
|
|
10
|
+
- THOTH: sem o Thoth instalado, a seção mostra uma apresentação curta com o site (thothdev.ia.br).
|
|
11
|
+
- Versão nova: ao abrir, o Pink avisa quando há versão mais nova no npm e diz para rodar `pink update` (com o Pink
|
|
12
|
+
fechado); o link do changelog leva ao CHANGELOG no GitHub. `PINK_SKIP_VERSION_CHECK=1` desliga a consulta.
|
|
13
|
+
- `/agente`: a mensagem enviada enquanto o agente trabalha aparece em cinza acima da caixa, como no Claude Code, no
|
|
14
|
+
lugar do aviso "Na fila"; ela some quando é enviada.
|
|
15
|
+
- `/agente` com opencode e outros agentes ACP: cada passo da partida (initialize, session/new, modelo) tem prazo de
|
|
16
|
+
2 min e percebe o agente morto; um agente travado (ex.: um MCP que não abre na máquina) vira erro em vez de
|
|
17
|
+
"Trabalhando" sem fim, e o Esc solta.
|
|
18
|
+
- Caixa de digitar: linha vazia também embaixo do rótulo ("Build · modelo"), como a do OpenCode.
|
|
19
|
+
- `/agente`: reabrir a mesma sessão do Pink (`/sessions`, `pink -c`) e escolher o mesmo agente continua a conversa
|
|
20
|
+
dele (claude `--resume`, codex `thread/resume`, opencode e ACP `session/load`); sessão nova do Pink começa do zero.
|
|
21
|
+
|
|
22
|
+
## [1.0.8] - 2026-11-24
|
|
23
|
+
|
|
24
|
+
- Publicada no meio do trabalho, com só parte das mudanças acima; use a 1.0.9.
|
|
25
|
+
|
|
6
26
|
## [1.0.7] - 2026-11-24
|
|
7
27
|
|
|
8
28
|
- `/agente`: os menus de agente, modelo e esforço têm busca, como o `/model` (digite para filtrar, setas, Enter, Esc).
|
package/NOTICE.md
CHANGED
|
@@ -8,7 +8,7 @@ O que o Pink muda em relação ao Pi 1.4.0 (a lista completa e verificada está
|
|
|
8
8
|
- o nome: tudo que é Pi vira Pink (comando, título, diretório de configuração `~/.pink/agent` e `.pink/` no projeto, variáveis `PINK_*`, mensagens e prompt de sistema);
|
|
9
9
|
- o tema `pink` como tema padrão: texto do agente quase branco, mensagem do usuário em rosa, pensamento em cinza, rosa
|
|
10
10
|
como cor da marca e dos destaques (2026-10-13; antes era tudo rosa);
|
|
11
|
-
- por privacidade, o Pink **não** envia a telemetria de instalação nem consulta versões no servidor do Pi: os endereços `pi.dev/api/*` foram trocados por `pink.invalid`
|
|
11
|
+
- por privacidade, o Pink **não** envia a telemetria de instalação nem consulta versões no servidor do Pi: os endereços `pi.dev/api/*` foram trocados por `pink.invalid`, exceto a consulta de versão nova, que pergunta ao registro do npm (`registry.npmjs.org/@thothdev/pink/latest`), de onde a atualização vem; `PINK_SKIP_VERSION_CHECK=1` desliga
|
|
12
12
|
e a telemetria de instalação vem desligada por padrão;
|
|
13
13
|
- a interface no estilo do OpenCode, na extensão `extensions/pink-ui.ts` (código do Pink, MIT), que o pacote carrega por padrão. Ela traz tela inicial, caixa de digitar,
|
|
14
14
|
moldura de tela cheia (topo, colunas de sessões e de contexto, rodapé), fechamento, paleta de comandos, agentes Build e Plano, `/undo` e `/redo` com arquivos, lista de tarefas (`todowrite`), `/sessions`, `/themes`, `/init` e `/details`;
|
|
@@ -943,7 +943,7 @@ ${output}`),text}};var TREE_GUTTER_WIDTH=2,MIN_VISIBLE_ANCHOR_CONTENT_WIDTH=4,MA
|
|
|
943
943
|
`).replace(/\\/g,"/"),matches=[],seen=new Set;for(let extension of extensions){let resolvedPath=normalizeStackPath(extension.resolvedPath),singleFilePackage=extension.sourceInfo.origin==="package"&&!/^(?:npm:|git:|https?:\/\/|ssh:\/\/)/u.test(extension.sourceInfo.source)&&/\.[cm]?[jt]s$/u.test(extension.sourceInfo.source),packageRoot=extension.sourceInfo.origin==="package"&&!singleFilePackage&&extension.sourceInfo.baseDir?extension.sourceInfo.baseDir:void 0,slashIndex=resolvedPath.lastIndexOf("/"),directoryEntry=/\/index\.[cm]?[jt]s$/u.test(resolvedPath);if(!(packageRoot?stackContainsPath(normalizedStack,packageRoot,!0):directoryEntry&&slashIndex!==-1?stackContainsPath(normalizedStack,resolvedPath.slice(0,slashIndex),!0):stackContainsPath(normalizedStack,resolvedPath,!1)))continue;let label=extension.sourceInfo.origin==="package"&&extension.sourceInfo.source?extension.sourceInfo.source:extension.path;seen.has(label)||(seen.add(label),matches.push(label))}return matches}function recordCrash(crash,path10=crashLogPath()){try{let{error}=crash,record={timestamp:new Date().toISOString(),version:VERSION,kind:crash.kind,message:error instanceof Error?error.message||error.name:String(error),stack:error instanceof Error&&error.stack?error.stack:null,sessionFile:crash.sessionFile??null,cwd:crash.cwd};return writeCrashLog([...readCrashLog(path10),record].slice(-MAX_CRASH_RECORDS),path10),record}catch{return}}function takeUnnotifiedCrash(path10=crashLogPath(),now=Date.now()){let records=readCrashLog(path10),crash=[...records].reverse().find(record=>!record.notified&&now-Date.parse(record.timestamp)<=MAX_AGE);if(crash){try{writeCrashLog(records.map(record=>record.notified?record:{...record,notified:!0}),path10)}catch{}return crash}}function clearCrashLog(path10=crashLogPath()){try{rmSync4(path10,{force:!0})}catch{}}var RADIUS_PROVIDER_ID="radius",ENV_RADIUS_GATEWAY="PINK_RADIUS_GATEWAY",RADIUS_MCP_URL=`${normalizeRadiusGatewayUrl(DEFAULT_RADIUS_GATEWAY)}/mcp`;function getRadiusGatewayUrl(){return normalizeRadiusGatewayUrl(process.env[ENV_RADIUS_GATEWAY]??DEFAULT_RADIUS_GATEWAY)}var BUILTIN_SLASH_COMMANDS=[{name:"settings",get description(){return globalThis.__pinkT?.("Abre as configurações","Abre la configuración","Open settings menu")??"Abre as configurações"}},{name:"model",get description(){return globalThis.__pinkT?.("Escolhe o modelo","Elige el modelo","Select model (opens selector UI)")??"Escolhe o modelo"},argumentHint:"<provider/model>"},{name:"tree",get description(){return globalThis.__pinkT?.("Navega pela árvore da sessão (troca de ramo)","Navega por el árbol de la sesión (cambia de rama)","Navigate session tree (switch branches)")??"Navega pela árvore da sessão (troca de ramo)"}},{name:"thinking",get description(){return globalThis.__pinkT?.("Define o nível de pensamento","Define el nivel de razonamiento","Set thinking level")??"Define o nível de pensamento"},argumentHint:"<level>"},{name:"scoped-models",get description(){return globalThis.__pinkT?.("Escolhe os modelos do ciclo do F2","Elige los modelos del ciclo de F2","Enable/disable models for Ctrl+P cycling")??"Escolhe os modelos do ciclo do F2"}},{name:"export",get description(){return globalThis.__pinkT?.("Exporta a sessão (HTML, ou informe o caminho .html/.jsonl)","Exporta la sesión (HTML, o indica la ruta .html/.jsonl)","Export session (HTML default, or specify path: .html/.jsonl)")??"Exporta a sessão (HTML, ou informe o caminho .html/.jsonl)"}},{name:"import",get description(){return globalThis.__pinkT?.("Importa e retoma uma sessão de um arquivo JSONL","Importa y retoma una sesión desde un archivo JSONL","Import and resume a session from a JSONL file")??"Importa e retoma uma sessão de um arquivo JSONL"}},{name:"share",get description(){return globalThis.__pinkT?.("Compartilha a sessão num gist secreto do GitHub (quem tiver o link vê)","Comparte la sesión en un gist secreto de GitHub (quien tenga el enlace la ve)","Share session via a GitHub gist")??"Compartilha a sessão num gist secreto do GitHub (quem tiver o link vê)"}},{name:"copy",get description(){return globalThis.__pinkT?.("Copia a última resposta do agente","Copia la última respuesta del agente","Copy last agent message to clipboard")??"Copia a última resposta do agente"}},{name:"name",get description(){return globalThis.__pinkT?.("Dá um nome à sessão","Da un nombre a la sesión","Set session display name")??"Dá um nome à sessão"}},{name:"session",get description(){return globalThis.__pinkT?.("Mostra os dados e números da sessão","Muestra los datos y números de la sesión","Show session info and stats")??"Mostra os dados e números da sessão"}},{name:"hotkeys",get description(){return globalThis.__pinkT?.("Mostra todos os atalhos de teclado","Muestra todos los atajos de teclado","Show all keyboard shortcuts")??"Mostra todos os atalhos de teclado"}},{name:"fork",get description(){return globalThis.__pinkT?.("Cria uma sessão nova a partir de uma mensagem anterior","Crea una sesión nueva a partir de un mensaje anterior","Create a new fork from a previous user message")??"Cria uma sessão nova a partir de uma mensagem anterior"}},{name:"clone",get description(){return globalThis.__pinkT?.("Duplica a sessão até aqui numa sessão nova","Duplica la sesión hasta aquí en una sesión nueva","Duplicate the current session at the current position")??"Duplica a sessão até aqui numa sessão nova"}},{name:"trust",get description(){return globalThis.__pinkT?.("Decide se confia neste projeto (vale nas próximas sessões)","Decide si confías en este proyecto (vale en las próximas sesiones)","Save project trust decision for future sessions")??"Decide se confia neste projeto (vale nas próximas sessões)"}},{name:"login",get description(){return globalThis.__pinkT?.("Entra num provedor (login)","Inicia sesión en un proveedor (login)","Configure provider authentication")??"Entra num provedor (login)"},argumentHint:"<provider>"},{name:"logout",get description(){return globalThis.__pinkT?.("Sai de um provedor (logout)","Cierra sesión en un proveedor (logout)","Remove provider authentication")??"Sai de um provedor (logout)"}},{name:"new",get description(){return globalThis.__pinkT?.("Começa uma sessão nova","Empieza una sesión nueva","Start a new session")??"Começa uma sessão nova"}},{name:"compact",get description(){return globalThis.__pinkT?.("Compacta o contexto da sessão agora","Compacta el contexto de la sesión ahora","Manually compact the session context")??"Compacta o contexto da sessão agora"}},{name:"resume",get description(){return globalThis.__pinkT?.("Retoma outra sessão","Retoma otra sesión","Resume a different session")??"Retoma outra sessão"}},{name:"reload",get description(){return globalThis.__pinkT?.("Recarrega atalhos, extensões, skills, prompts, temas e arquivos de contexto","Recarga atajos, extensiones, skills, prompts, temas y archivos de contexto","Reload keybindings, extensions, skills, prompts, themes, and context files")??"Recarrega atalhos, extensões, skills, prompts, temas e arquivos de contexto"}},{name:"quit",get description(){return globalThis.__pinkT?.(`Sai do ${APP_NAME}`,`Sale de ${APP_NAME}`,`Quit ${APP_NAME}`)??`Sai do ${APP_NAME}`}}];function createAllToolRenderers(){return{read:readRenderers,bash:createShellRenderers("$"),powershell:createShellRenderers("PS>"),edit:editRenderers,write:writeRenderers,grep:grepRenderers,find:findRenderers,ls:lsRenderers}}function withBuiltInRenderers(toolName,definition){let builtIn=createAllToolRenderers()[toolName];return definition?builtIn?{...definition,renderCall:definition.renderCall??builtIn.renderCall,renderResult:definition.renderResult??builtIn.renderResult}:definition:builtIn}import path6 from"node:path";import{existsSync as existsSync16,readFileSync as readFileSync14}from"fs";var GITHUB_REPO="earendil-works/pi",CHANGELOG_LINK_BASE_PATH="packages/coding-agent",LEGACY_REPO_RE=/^https:\/\/github\.com\/(?:badlogic|earendil-works)\/pi-mono(?=\/|$)/,URL_SCHEME_RE=/^[a-z][a-z0-9+.-]*:/i,INLINE_MARKDOWN_LINK_RE=/(!?\[[^\]\n]+\]\()([^\s)]+)((?:\s+[^)]*)?\))/g;function entryVersion(entry){return`${entry.major}.${entry.minor}.${entry.patch}`}function normalizeTag(version2){let versionString=typeof version2=="string"?version2:entryVersion(version2);return versionString.startsWith("v")?versionString:`v${versionString}`}function splitLocalTarget(target){let hashIndex=target.indexOf("#"),beforeHash=hashIndex===-1?target:target.slice(0,hashIndex),fragment=hashIndex===-1?"":target.slice(hashIndex),queryIndex=beforeHash.indexOf("?");return queryIndex===-1?{fragment,pathPart:beforeHash,query:""}:{fragment,pathPart:beforeHash.slice(0,queryIndex),query:beforeHash.slice(queryIndex)}}function normalizePathPart(value){return value.replaceAll("\\","/")}function resolveRepositoryPath(targetPath){let normalizedTarget=normalizePathPart(targetPath),joined=normalizedTarget.startsWith("/")?path6.posix.normalize(normalizedTarget.replace(/^\/+/,"")):path6.posix.normalize(path6.posix.join(CHANGELOG_LINK_BASE_PATH,normalizedTarget));if(!(joined==="."||joined.startsWith("../")||joined===".."))return joined}function isDirectoryTarget(originalPath,repositoryPath){return originalPath.endsWith("/")?!0:!path6.posix.basename(repositoryPath).includes(".")}function normalizeChangelogLinkTarget(target,tag){let canonicalTarget=target.replace(LEGACY_REPO_RE,`https://github.com/${GITHUB_REPO}`),repoUrl=`https://github.com/${GITHUB_REPO}`;for(let route2 of["blob","tree"])for(let branch of["main","master"]){let floatingRefPrefix=`${repoUrl}/${route2}/${branch}/`;canonicalTarget.startsWith(floatingRefPrefix)&&(canonicalTarget=`${repoUrl}/${route2}/${tag}/${canonicalTarget.slice(floatingRefPrefix.length)}`)}if(canonicalTarget.startsWith("#")||canonicalTarget.startsWith("//")||URL_SCHEME_RE.test(canonicalTarget))return canonicalTarget;let{fragment,pathPart,query}=splitLocalTarget(canonicalTarget);if(!pathPart)return canonicalTarget;let repositoryPath=resolveRepositoryPath(pathPart);if(!repositoryPath)return canonicalTarget;let route=isDirectoryTarget(pathPart,repositoryPath)?"tree":"blob";return`https://github.com/${GITHUB_REPO}/${route}/${tag}/${encodeURI(repositoryPath)}${query}${fragment}`}function normalizeChangelogLinks(markdown,version2){let tag=normalizeTag(version2);return markdown.replace(INLINE_MARKDOWN_LINK_RE,(_match,prefix,target,suffix)=>`${prefix}${normalizeChangelogLinkTarget(target,tag)}${suffix}`)}function parseChangelog(changelogPath){if(!existsSync16(changelogPath))return[];try{let lines=readFileSync14(changelogPath,"utf-8").split(`
|
|
944
944
|
`),entries=[],currentLines=[],currentVersion=null;for(let line of lines)if(line.startsWith("## ")){currentVersion&¤tLines.length>0&&entries.push({...currentVersion,content:currentLines.join(`
|
|
945
945
|
`).trim()});let versionMatch=line.match(/##\s+\[?(\d+)\.(\d+)\.(\d+)\]?/);versionMatch?(currentVersion={major:Number.parseInt(versionMatch[1],10),minor:Number.parseInt(versionMatch[2],10),patch:Number.parseInt(versionMatch[3],10)},currentLines=[line]):(currentVersion=null,currentLines=[])}else currentVersion&¤tLines.push(line);return currentVersion&¤tLines.length>0&&entries.push({...currentVersion,content:currentLines.join(`
|
|
946
|
-
`).trim()}),entries}catch(error){return console.error(`Warning: Could not parse changelog: ${error}`),[]}}function compareVersions(v1,v2){return v1.major!==v2.major?v1.major-v2.major:v1.minor!==v2.minor?v1.minor-v2.minor:v1.patch-v2.patch}function getNewEntries(entries,lastVersion){let parts=lastVersion.split(".").map(Number),last={major:parts[0]||0,minor:parts[1]||0,patch:parts[2]||0,content:""};return entries.filter(entry=>compareVersions(entry,last)>0)}import{randomUUID as randomUUID4}from"crypto";import{readFileSync as readFileSync15,unlinkSync as unlinkSync2}from"fs";import{tmpdir as tmpdir3}from"os";import{join as join23}from"path";var SUPPORTED_IMAGE_MIME_TYPES=["image/png","image/jpeg","image/webp","image/gif"],DEFAULT_LIST_TIMEOUT_MS=1e3,DEFAULT_POWERSHELL_TIMEOUT_MS=5e3;function isWaylandSession(env=process.env){return!!env.WAYLAND_DISPLAY||env.XDG_SESSION_TYPE==="wayland"}function baseMimeType2(mimeType){return mimeType.split(";")[0]?.trim().toLowerCase()??mimeType.toLowerCase()}function extensionForImageMimeType(mimeType){switch(baseMimeType2(mimeType)){case"image/png":return"png";case"image/jpeg":return"jpg";case"image/webp":return"webp";case"image/gif":return"gif";default:return null}}function selectPreferredImageMimeType(mimeTypes){let normalized=mimeTypes.map(t=>t.trim()).filter(Boolean).map(t=>({raw:t,base:baseMimeType2(t)}));for(let preferred of SUPPORTED_IMAGE_MIME_TYPES){let match2=normalized.find(t=>t.base===preferred);if(match2)return match2.raw}return normalized.find(t=>t.base.startsWith("image/"))?.raw??null}function isSupportedImageMimeType(mimeType){let base=baseMimeType2(mimeType);return SUPPORTED_IMAGE_MIME_TYPES.some(t=>t===base)}async function convertToPng2(bytes){let photon=await loadPhoton();if(!photon)return null;try{let image=photon.PhotonImage.new_from_byteslice(bytes);try{return image.get_bytes()}finally{image.free()}}catch{return null}}async function readClipboardImageViaWlPaste(){let list=await runClipboardCommand("wl-paste",["--list-types"],{timeoutMs:DEFAULT_LIST_TIMEOUT_MS});if(list===void 0)return;let types2=list.toString("utf-8").split(/\r?\n/).map(t=>t.trim()).filter(Boolean),selectedType=selectPreferredImageMimeType(types2);if(!selectedType)return null;let data=await runClipboardCommand("wl-paste",["--type",selectedType,"--no-newline"]);if(data!==void 0)return data.length===0?null:{bytes:data,mimeType:baseMimeType2(selectedType)}}async function readClipboardImageViaPowerShell(){let tmpFile=join23(tmpdir3(),`pi-wsl-clip-${randomUUID4()}.png`);try{let winPathResult=await runClipboardCommand("wslpath",["-w",tmpFile],{timeoutMs:DEFAULT_LIST_TIMEOUT_MS});if(winPathResult===void 0)return null;let winPath=winPathResult.toString("utf-8").trim();if(!winPath)return null;let psScript=["Add-Type -AssemblyName System.Windows.Forms","Add-Type -AssemblyName System.Drawing",`$path = '${winPath.replaceAll("'","''")}'`,"$img = [System.Windows.Forms.Clipboard]::GetImage()","if ($img) { $img.Save($path, [System.Drawing.Imaging.ImageFormat]::Png); Write-Output 'ok' } else { Write-Output 'empty' }"].join("; "),result=await runClipboardCommand("powershell.exe",["-NoProfile","-Command",psScript],{timeoutMs:DEFAULT_POWERSHELL_TIMEOUT_MS});if(result===void 0||result.toString("utf-8").trim()!=="ok")return null;let bytes=readFileSync15(tmpFile);return bytes.length===0?null:{bytes:new Uint8Array(bytes),mimeType:"image/png"}}catch{return null}finally{try{unlinkSync2(tmpFile)}catch{}}}async function readClipboardImageViaXclip(){let targets=await runClipboardCommand("xclip",["-selection","clipboard","-t","TARGETS","-o"],{timeoutMs:DEFAULT_LIST_TIMEOUT_MS});if(targets===void 0)return;let candidateTypes=targets.toString("utf-8").split(/\r?\n/).map(t=>t.trim()).filter(Boolean),preferred=selectPreferredImageMimeType(candidateTypes);if(!preferred)return null;let data=await runClipboardCommand("xclip",["-selection","clipboard","-t",preferred,"-o"]);if(data!==void 0)return data.length===0?null:{bytes:data,mimeType:baseMimeType2(preferred)}}async function readClipboardImageViaNativeClipboard(){let bytes=await getNativeClipboard()?.getImage();if(bytes!==void 0)return bytes?.length?{bytes,mimeType:detectSupportedImageMimeType(bytes)??"application/octet-stream"}:null}async function readClipboardImage(options){let env=options?.env??process.env,platform3=options?.platform??process.platform;if(env.TERMUX_VERSION)return null;let image;if(platform3==="linux"){let wsl=isWSL(env);(isWaylandSession(env)||wsl)&&(image=await readClipboardImageViaWlPaste()),image===void 0&&(image=await readClipboardImageViaXclip()),!image&&wsl&&(image=await readClipboardImageViaPowerShell()??image),image===void 0&&(image=await readClipboardImageViaNativeClipboard())}else image=await readClipboardImageViaNativeClipboard();if(!image)return null;if(!isSupportedImageMimeType(image.mimeType)){let pngBytes=await convertToPng2(image.bytes);return pngBytes?{bytes:pngBytes,mimeType:"image/png"}:null}return image}var import_semver2=__toESM(require_semver2(),1);var LATEST_VERSION_URL="https://
|
|
946
|
+
`).trim()}),entries}catch(error){return console.error(`Warning: Could not parse changelog: ${error}`),[]}}function compareVersions(v1,v2){return v1.major!==v2.major?v1.major-v2.major:v1.minor!==v2.minor?v1.minor-v2.minor:v1.patch-v2.patch}function getNewEntries(entries,lastVersion){let parts=lastVersion.split(".").map(Number),last={major:parts[0]||0,minor:parts[1]||0,patch:parts[2]||0,content:""};return entries.filter(entry=>compareVersions(entry,last)>0)}import{randomUUID as randomUUID4}from"crypto";import{readFileSync as readFileSync15,unlinkSync as unlinkSync2}from"fs";import{tmpdir as tmpdir3}from"os";import{join as join23}from"path";var SUPPORTED_IMAGE_MIME_TYPES=["image/png","image/jpeg","image/webp","image/gif"],DEFAULT_LIST_TIMEOUT_MS=1e3,DEFAULT_POWERSHELL_TIMEOUT_MS=5e3;function isWaylandSession(env=process.env){return!!env.WAYLAND_DISPLAY||env.XDG_SESSION_TYPE==="wayland"}function baseMimeType2(mimeType){return mimeType.split(";")[0]?.trim().toLowerCase()??mimeType.toLowerCase()}function extensionForImageMimeType(mimeType){switch(baseMimeType2(mimeType)){case"image/png":return"png";case"image/jpeg":return"jpg";case"image/webp":return"webp";case"image/gif":return"gif";default:return null}}function selectPreferredImageMimeType(mimeTypes){let normalized=mimeTypes.map(t=>t.trim()).filter(Boolean).map(t=>({raw:t,base:baseMimeType2(t)}));for(let preferred of SUPPORTED_IMAGE_MIME_TYPES){let match2=normalized.find(t=>t.base===preferred);if(match2)return match2.raw}return normalized.find(t=>t.base.startsWith("image/"))?.raw??null}function isSupportedImageMimeType(mimeType){let base=baseMimeType2(mimeType);return SUPPORTED_IMAGE_MIME_TYPES.some(t=>t===base)}async function convertToPng2(bytes){let photon=await loadPhoton();if(!photon)return null;try{let image=photon.PhotonImage.new_from_byteslice(bytes);try{return image.get_bytes()}finally{image.free()}}catch{return null}}async function readClipboardImageViaWlPaste(){let list=await runClipboardCommand("wl-paste",["--list-types"],{timeoutMs:DEFAULT_LIST_TIMEOUT_MS});if(list===void 0)return;let types2=list.toString("utf-8").split(/\r?\n/).map(t=>t.trim()).filter(Boolean),selectedType=selectPreferredImageMimeType(types2);if(!selectedType)return null;let data=await runClipboardCommand("wl-paste",["--type",selectedType,"--no-newline"]);if(data!==void 0)return data.length===0?null:{bytes:data,mimeType:baseMimeType2(selectedType)}}async function readClipboardImageViaPowerShell(){let tmpFile=join23(tmpdir3(),`pi-wsl-clip-${randomUUID4()}.png`);try{let winPathResult=await runClipboardCommand("wslpath",["-w",tmpFile],{timeoutMs:DEFAULT_LIST_TIMEOUT_MS});if(winPathResult===void 0)return null;let winPath=winPathResult.toString("utf-8").trim();if(!winPath)return null;let psScript=["Add-Type -AssemblyName System.Windows.Forms","Add-Type -AssemblyName System.Drawing",`$path = '${winPath.replaceAll("'","''")}'`,"$img = [System.Windows.Forms.Clipboard]::GetImage()","if ($img) { $img.Save($path, [System.Drawing.Imaging.ImageFormat]::Png); Write-Output 'ok' } else { Write-Output 'empty' }"].join("; "),result=await runClipboardCommand("powershell.exe",["-NoProfile","-Command",psScript],{timeoutMs:DEFAULT_POWERSHELL_TIMEOUT_MS});if(result===void 0||result.toString("utf-8").trim()!=="ok")return null;let bytes=readFileSync15(tmpFile);return bytes.length===0?null:{bytes:new Uint8Array(bytes),mimeType:"image/png"}}catch{return null}finally{try{unlinkSync2(tmpFile)}catch{}}}async function readClipboardImageViaXclip(){let targets=await runClipboardCommand("xclip",["-selection","clipboard","-t","TARGETS","-o"],{timeoutMs:DEFAULT_LIST_TIMEOUT_MS});if(targets===void 0)return;let candidateTypes=targets.toString("utf-8").split(/\r?\n/).map(t=>t.trim()).filter(Boolean),preferred=selectPreferredImageMimeType(candidateTypes);if(!preferred)return null;let data=await runClipboardCommand("xclip",["-selection","clipboard","-t",preferred,"-o"]);if(data!==void 0)return data.length===0?null:{bytes:data,mimeType:baseMimeType2(preferred)}}async function readClipboardImageViaNativeClipboard(){let bytes=await getNativeClipboard()?.getImage();if(bytes!==void 0)return bytes?.length?{bytes,mimeType:detectSupportedImageMimeType(bytes)??"application/octet-stream"}:null}async function readClipboardImage(options){let env=options?.env??process.env,platform3=options?.platform??process.platform;if(env.TERMUX_VERSION)return null;let image;if(platform3==="linux"){let wsl=isWSL(env);(isWaylandSession(env)||wsl)&&(image=await readClipboardImageViaWlPaste()),image===void 0&&(image=await readClipboardImageViaXclip()),!image&&wsl&&(image=await readClipboardImageViaPowerShell()??image),image===void 0&&(image=await readClipboardImageViaNativeClipboard())}else image=await readClipboardImageViaNativeClipboard();if(!image)return null;if(!isSupportedImageMimeType(image.mimeType)){let pngBytes=await convertToPng2(image.bytes);return pngBytes?{bytes:pngBytes,mimeType:"image/png"}:null}return image}var import_semver2=__toESM(require_semver2(),1);var LATEST_VERSION_URL="https://registry.npmjs.org/@thothdev/pink/latest",DEFAULT_VERSION_CHECK_TIMEOUT_MS=1e4;function formatVersionCheckError(error){let rootMessage=error instanceof Error&&error.message?error.message:String(error),cause=error instanceof Error?error.cause:void 0,causes=cause instanceof AggregateError?cause.errors:cause===void 0?[]:[cause],codes=causes.map(value=>typeof value=="object"&&value!==null&&"code"in value&&typeof value.code=="string"?value.code:void 0).filter(code=>code!==void 0);if(codes.length>0)return`${rootMessage} (${[...new Set(codes)].join(", ")})`;let causeMessage=causes.find(value=>value instanceof Error&&!!value.message)?.message;return causeMessage?`${rootMessage} (cause: ${causeMessage})`:rootMessage}function comparePackageVersions(leftVersion,rightVersion){let left=(0,import_semver2.valid)(leftVersion.trim()),right=(0,import_semver2.valid)(rightVersion.trim());if(!(!left||!right))return(0,import_semver2.compare)(left,right)}function isNewerPackageVersion(candidateVersion,currentVersion){let comparison=comparePackageVersions(candidateVersion,currentVersion);return comparison!==void 0?comparison>0:candidateVersion.trim()!==currentVersion.trim()}async function getLatestPiRelease(currentVersion,options={}){if(process.env.PINK_OFFLINE)return;let response=await fetchWithRetry(LATEST_VERSION_URL,{headers:{"User-Agent":getPiUserAgent(currentVersion),accept:"application/json"}},{maxRetries:options.retry?2:0,timeoutMs:options.timeoutMs??DEFAULT_VERSION_CHECK_TIMEOUT_MS});if(!response.ok)return;let data=await response.json();if(typeof data.version!="string"||!data.version.trim())return;let packageName=typeof data.packageName=="string"&&data.packageName.trim()?data.packageName.trim():void 0,note=typeof data.note=="string"&&data.note.trim()?data.note.trim():void 0;return{version:data.version.trim(),packageName,...note?{note}:{}}}async function checkForNewPiVersion(currentVersion){if(!process.env.PINK_SKIP_VERSION_CHECK)try{let latestRelease=await getLatestPiRelease(currentVersion);return latestRelease&&isNewerPackageVersion(latestRelease.version,currentVersion)?latestRelease:void 0}catch{return}}import*as path8 from"node:path";var AuthCommandError=class extends Error{},AUTH_COMMAND_USAGE={check:`${APP_NAME} auth check --provider <provider> [--json] [--credentials] [--no-refresh]`,api_key:`${APP_NAME} auth print-api-key --provider <provider> [--model <model>]`,bearer_token:`${APP_NAME} auth print-bearer-token --provider <provider> [--model <model>] [--min-expiry <duration>]`};function getAuthCommandName(kind){return kind==="check"?"auth check":kind==="api_key"?"auth print-api-key":"auth print-bearer-token"}function getAuthCommandUsage(kind){return AUTH_COMMAND_USAGE[kind]}function isAuthCommandHelp(args){return args[0]==="auth"&&(args[1]===void 0||args[1]==="help"||args.includes("--help")||args.includes("-h"))}function printAuthCommandHelp(){console.log(`Usage:
|
|
947
947
|
pink auth print-api-key [--provider <provider>] [--model <model>]
|
|
948
948
|
pink auth print-bearer-token [--provider <provider>] [--model <model>] [--min-expiry <duration>]
|
|
949
949
|
pink auth check [--provider <provider>] [--model <model>] [--json] [--credentials] [--no-refresh]
|
|
@@ -993,7 +993,7 @@ ${message}`,["Yes","No"],opts,{kind:"permission",message:title})==="Yes"}async p
|
|
|
993
993
|
`)[cursor.line]??"":"",characterBeforeCursor=cursor&&cursor.col>0?currentLine[cursor.col-1]:"",characterAfterCursor=cursor?currentLine[cursor.col]:"",leadingSpace=characterBeforeCursor&&!/\s/.test(characterBeforeCursor)?" ":"",trailingSpace=characterAfterCursor&&!/\s/.test(characterAfterCursor)?" ":"";this.editor.insertTextAtCursor?.(`${leadingSpace}${paths}${trailingSpace}`),this.ui.requestRender();return}let image=await readClipboardImage();if(image){let tmpDir=os4.tmpdir(),ext2=extensionForImageMimeType(image.mimeType)??"png",fileName=`pi-clipboard-${crypto2.randomUUID()}.${ext2}`,filePath=path9.join(tmpDir,fileName);fs5.writeFileSync(filePath,Buffer.from(image.bytes)),this.editor.insertTextAtCursor?.(filePath),this.ui.requestRender();return}let text=await readClipboardText();text&&(this.editor.insertTextAtCursor?.(text),this.ui.requestRender())}catch(error){this.showError(`Failed to paste from clipboard: ${error instanceof Error?error.message:String(error)}`)}}handleStartupSubmit(text){this.editor.setText(text),this.showStatus("Startup is still in progress")}setupEditorSubmitHandler(){this.defaultEditor.onSubmit=async text=>{if(text=text.trim(),!!text){if(text==="/settings"){this.showSettingsSelector(),this.editor.setText("");return}if(text==="/scoped-models"){this.editor.setText(""),await this.showModelsSelector();return}if(text==="/model"||text.startsWith("/model ")){let searchTerm=text.startsWith("/model ")?text.slice(7).trim():void 0;this.editor.setText(""),await this.handleModelCommand(searchTerm);return}if(text==="/thinking"||text.startsWith("/thinking ")){let searchTerm=text.startsWith("/thinking ")?text.slice(10).trim():void 0;this.editor.setText(""),this.handleThinkingCommand(searchTerm);return}if(text==="/export"||text.startsWith("/export ")){await this.handleExportCommand(text),this.editor.setText("");return}if(text==="/import"||text.startsWith("/import ")){await this.handleImportCommand(text),this.editor.setText("");return}if(text==="/share"){await this.handleShareCommand(),this.editor.setText("");return}if(text==="/copy"){await this.handleCopyCommand(),this.editor.setText("");return}if(text==="/name"||text.startsWith("/name ")){this.handleNameCommand(text),this.editor.setText("");return}if(text==="/session"){this.handleSessionCommand(),this.editor.setText("");return}if(text==="/hotkeys"){this.handleHotkeysCommand(),this.editor.setText("");return}if(text==="/fork"){this.showUserMessageSelector(),this.editor.setText("");return}if(text==="/clone"){this.editor.setText(""),await this.handleCloneCommand();return}if(text==="/tree"){this.showTreeSelector(),this.editor.setText("");return}if(text==="/trust"){this.showTrustSelector(),this.editor.setText("");return}if(text==="/login"||text.startsWith("/login ")){let providerRef=text.startsWith("/login ")?text.slice(7).trim():void 0;this.editor.setText(""),await this.handleLoginCommand(providerRef);return}if(text==="/logout"){this.showOAuthSelector("logout"),this.editor.setText("");return}if(text==="/new"){this.editor.setText(""),await this.handleClearCommand();return}if(text==="/compact"||text.startsWith("/compact ")){let customInstructions=text.startsWith("/compact ")?text.slice(9).trim():void 0;this.editor.setText(""),await this.handleCompactCommand(customInstructions);return}if(text==="/reload"){this.editor.setText(""),await this.handleReloadCommand();return}if(text==="/debug"){this.handleDebugCommand(),this.editor.setText("");return}if(text==="/arminsayshi"){this.handleArminSaysHi(),this.editor.setText("");return}if(text==="/dementedelves"){this.handleDementedDelves(),this.editor.setText("");return}if(text==="/resume"){this.showSessionSelector(),this.editor.setText("");return}if(text==="/quit"){this.editor.setText(""),await this.shutdown();return}if(text.startsWith("!")){let isExcluded=text.startsWith("!!"),command=isExcluded?text.slice(2).trim():text.slice(1).trim();if(command){if(this.session.isBashRunning){this.showWarning("A bash command is already running. Press Esc to cancel it first."),this.editor.setText(text);return}this.editor.addToHistory?.(text),await this.handleBashCommand(command,isExcluded),this.isBashMode=!1,this.updateEditorBorderColor();return}}if(this.session.isCompacting){this.isExtensionCommand(text)?(this.editor.addToHistory?.(text),this.editor.setText(""),await this.session.prompt(text)):this.queueCompactionMessage(text,"steer");return}if(this.session.isStreaming){this.editor.addToHistory?.(text),this.editor.setText(""),await this.session.prompt(text,{streamingBehavior:"steer"}),this.updatePendingMessagesDisplay(),this.ui.requestRender();return}this.flushPendingBashComponents(),this.onInputCallback?this.onInputCallback(text):this.pendingUserInputs.push(text),this.editor.addToHistory?.(text)}}}subscribeToAgent(){this.unsubscribe=this.session.subscribe(async event=>{await this.handleEvent(event)})}async handleEvent(event){switch(this.isInitialized||await this.init(),this.footer.invalidate(),this.programStatus.handleEvent(event),event.type){case"agent_start":this.pendingTools.clear(),this.retryEscapeHandler&&(this.defaultEditor.onEscape=this.retryEscapeHandler,this.retryEscapeHandler=void 0);break;case"turn_start":this.settingsManager.getShowTerminalProgress()&&this.ui.terminal.setProgress(!0),this.workingVisible?this.activeStatusIndicator?.kind!=="working"&&this.showWorkingStatusIndicator():this.clearStatusIndicator(),this.ui.requestRender();break;case"queue_update":this.updatePendingMessagesDisplay(),this.ui.requestRender();break;case"entry_appended":if(this.entriesRenderedByBoundaryCompaction.delete(event.entry.id))break;if(event.entry.type==="custom")this.addCustomEntryToChat(event.entry),this.ui.requestRender();else if(event.entry.type==="usage"&&event.entry.kind==="cache_warm")this.addCacheWarmingUsage(event.entry),this.ui.requestRender();else if(event.entry.type==="custom_message"&&event.entry.display)this.addMessageToChat(createCustomMessage(event.entry.customType,event.entry.content,event.entry.display,event.entry.details,event.entry.timestamp)),this.ui.requestRender();else if(event.entry.type==="compaction"){let entries=this.sessionManager.buildContextEntries();if(entries[0]?.id!==event.entry.id)break;this.chatContainer.clear();let branch=this.sessionManager.getBranch(),compactionIndex=branch.findIndex(entry=>entry.id===event.entry.id),entriesAfterCompaction=new Set(branch.slice(compactionIndex+1).map(entry=>entry.id)),retainedEntries=entries.slice(1);this.renderSessionEntries(retainedEntries.filter(entry=>!entriesAfterCompaction.has(entry.id))),this.addMessageToChat(createCompactionSummaryMessage(event.entry.summary,event.entry.tokensBefore,event.entry.timestamp)),event.entry.usage&&this.addCompactionCostNotice({type:"compaction_cost",kind:"compaction",usage:event.entry.usage}),this.renderSessionEntries(retainedEntries.filter(entry=>entriesAfterCompaction.has(entry.id)));for(let entryId of entriesAfterCompaction)this.entriesRenderedByBoundaryCompaction.add(entryId);this.footer.invalidate(),this.ui.requestRender()}break;case"session_info_changed":this.updateTerminalTitle(),this.footer.invalidate(),this.ui.requestRender();break;case"thinking_level_changed":this.footer.invalidate(),this.updateEditorBorderColor();break;case"message_start":event.message.role==="custom"?(this.addMessageToChat(event.message),this.ui.requestRender()):event.message.role==="user"?(this.addMessageToChat(event.message),this.updatePendingMessagesDisplay(),this.ui.requestRender()):event.message.role==="assistant"&&(this.streamingComponent=new AssistantMessageComponent(void 0,this.hideThinkingBlock,this.getMarkdownThemeWithSettings(),this.hiddenThinkingLabel,this.outputPad,this.getMarkdownTransformers()),this.streamingMessage=event.message,this.chatContainer.addChild(this.streamingComponent),this.streamingComponent.updateContent(this.streamingMessage,!0),this.ui.requestRender());break;case"message_update":if(this.streamingComponent&&event.message.role==="assistant"){this.streamingMessage=event.message,this.streamingComponent.updateContent(this.streamingMessage,!0);for(let content of this.streamingMessage.content)if(content.type==="toolCall")if(this.pendingTools.has(content.id)){let component=this.pendingTools.get(content.id);component&&component.updateArgs(content.arguments)}else{let component=new ToolExecutionComponent(content.name,content.id,content.arguments,{showImages:this.settingsManager.getShowImages(),imageWidthCells:this.settingsManager.getImageWidthCells(),outputPad:this.outputPad},this.getRegisteredToolDefinition(content.name),this.ui,this.sessionManager.getCwd());component.setExpanded(this.toolOutputExpanded),this.chatContainer.addChild(component),this.pendingTools.set(content.id,component)}this.ui.requestRender()}break;case"message_end":if(event.message.role==="user")break;if(this.streamingComponent&&event.message.role==="assistant"){this.streamingMessage=event.message;let errorMessage5;if(this.streamingMessage.stopReason==="aborted"){let retryAttempt=this.session.retryAttempt;errorMessage5=retryAttempt>0?`Aborted after ${retryAttempt} retry attempt${retryAttempt>1?"s":""}`:"Operation aborted",this.streamingMessage.errorMessage=errorMessage5}if(this.streamingComponent.updateContent(this.streamingMessage,!1),this.streamingMessage.stopReason==="aborted"||this.streamingMessage.stopReason==="error"){errorMessage5||(errorMessage5=this.streamingMessage.errorMessage||"Error");for(let[,component]of this.pendingTools.entries())component.updateResult({content:[{type:"text",text:errorMessage5}],isError:!0});this.pendingTools.clear(),this.maybeSuggestBugReport(this.streamingMessage)}else{for(let[,component]of this.pendingTools.entries())component.setArgsComplete();this.maybeShowThinkingDropNotice(this.streamingMessage),this.maybeShowCacheMissNotice(this.streamingMessage)}this.streamingComponent=void 0,this.streamingMessage=void 0,this.footer.invalidate()}this.ui.requestRender();break;case"bash_execution_update":break;case"tool_execution_start":{if(event.parentToolCallId)break;let component=this.pendingTools.get(event.toolCallId);component||(component=new ToolExecutionComponent(event.toolName,event.toolCallId,event.args,{showImages:this.settingsManager.getShowImages(),imageWidthCells:this.settingsManager.getImageWidthCells(),outputPad:this.outputPad},this.getRegisteredToolDefinition(event.toolName),this.ui,this.sessionManager.getCwd()),component.setExpanded(this.toolOutputExpanded),this.chatContainer.addChild(component),this.pendingTools.set(event.toolCallId,component)),component.markExecutionStarted(),this.ui.requestRender();break}case"tool_execution_update":{let component=this.pendingTools.get(event.toolCallId);component&&(component.updateResult({...event.partialResult,isError:!1},!0),this.ui.requestRender());break}case"tool_execution_end":{event.isError&&this.maybeShowInstallChangeWarning();let component=this.pendingTools.get(event.toolCallId);component&&(component.updateResult({...event.result,isError:event.isError,durationMs:event.durationMs}),this.pendingTools.delete(event.toolCallId),this.ui.requestRender());break}case"agent_end":this.settingsManager.getShowTerminalProgress()&&this.ui.terminal.setProgress(!1),this.clearStatusIndicator("working"),this.streamingComponent&&(this.chatContainer.removeChild(this.streamingComponent),this.streamingComponent=void 0,this.streamingMessage=void 0),this.pendingTools.clear(),this.ui.requestRender();break;case"agent_settled":await this.checkShutdownRequested();break;case"compaction_start":{this.settingsManager.getShowTerminalProgress()&&this.ui.terminal.setProgress(!0),this.autoCompactionEscapeHandler=this.defaultEditor.onEscape,this.defaultEditor.onEscape=()=>{this.session.abortCompaction()};let colorFn=isEmbeddedStatus(this.editor)?text=>(this.editor.borderColor??theme.getThinkingBorderColor(this.session.thinkingLevel||"off"))(text):void 0;this.showStatusIndicator(new CompactionStatusIndicator(this.ui,event.reason,colorFn)),this.ui.requestRender();break}case"compaction_end":{if(this.settingsManager.getShowTerminalProgress()&&this.ui.terminal.setProgress(!1),this.autoCompactionEscapeHandler&&(this.defaultEditor.onEscape=this.autoCompactionEscapeHandler,this.autoCompactionEscapeHandler=void 0),this.clearStatusIndicator("compaction"),event.aborted)event.reason==="manual"?this.showError("Compaction cancelled"):this.showStatus("Auto-compaction cancelled");else if(event.result){let entries=this.sessionManager.buildContextEntries();if(entries[0]?.type!=="compaction")throw new Error("Completed compaction is missing from the session context");this.chatContainer.clear(),this.renderSessionEntries(entries.slice(1)),this.addMessageToChat(createCompactionSummaryMessage(event.result.summary,event.result.tokensBefore,new Date().toISOString())),event.result.usage&&this.addCompactionCostNotice({type:"compaction_cost",kind:"compaction",usage:event.result.usage}),this.footer.invalidate()}else if(event.errorMessage)if(event.reason==="manual")this.showError(event.errorMessage);else{this.chatContainer.addChild(new Spacer(1));let errorMessage5=event.errorMessage;this.chatContainer.addChild(new ThemedText(()=>theme.fg("error",errorMessage5),1,0))}this.flushCompactionQueue({willRetry:event.willRetry}),this.ui.requestRender();break}case"auto_retry_start":{this.retryEscapeHandler=this.defaultEditor.onEscape,this.defaultEditor.onEscape=()=>{this.session.abortRetry()},this.showStatusIndicator(new RetryStatusIndicator(this.ui,event.attempt,event.maxAttempts,event.delayMs)),this.ui.requestRender();break}case"auto_retry_end":{this.retryEscapeHandler&&(this.defaultEditor.onEscape=this.retryEscapeHandler,this.retryEscapeHandler=void 0),this.clearStatusIndicator("retry"),event.success||this.showError(`Retry failed after ${event.attempt} attempts: ${event.finalError||"Unknown error"}`),this.ui.requestRender();break}case"summarization_retry_scheduled":{this.showError(event.errorMessage),this.showStatusIndicator(new RetryStatusIndicator(this.ui,event.attempt,event.maxAttempts,event.delayMs)),this.ui.requestRender();break}case"summarization_retry_attempt_start":{if(this.clearStatusIndicator("retry"),event.source==="branchSummary")this.showStatusIndicator(new BranchSummaryStatusIndicator(this.ui));else{let colorFn=isEmbeddedStatus(this.editor)?text=>(this.editor.borderColor??theme.getThinkingBorderColor(this.session.thinkingLevel||"off"))(text):void 0;this.showStatusIndicator(new CompactionStatusIndicator(this.ui,event.reason,colorFn))}this.ui.requestRender();break}case"summarization_retry_finished":{this.clearStatusIndicator("retry"),this.ui.requestRender();break}}}getUserMessageText(message){return message.role!=="user"?"":(typeof message.content=="string"?[{type:"text",text:message.content}]:message.content.filter(c=>c.type==="text")).map(c=>c.text).join("")}showManagedToolStatus(status){this.managedToolStatusStarted||(this.chatContainer.addChild(new Spacer(1)),this.managedToolStatusStarted=!0);let message=status.type==="warning"?`Warning: ${status.message}`:status.message,color=status.type==="warning"?"warning":"dim";this.chatContainer.addChild(new ThemedText(()=>theme.fg(color,message),1,0)),this.lastStatusSpacer=void 0,this.lastStatusText=void 0,this.ui.requestRender()}showStatus(message){let children=this.chatContainer.children,last=children.length>0?children[children.length-1]:void 0,secondLast=children.length>1?children[children.length-2]:void 0;if(last&&secondLast&&last===this.lastStatusText&&secondLast===this.lastStatusSpacer){this.lastStatusMessage=message,this.lastStatusText.invalidate(),this.ui.requestRender();return}let spacer=new Spacer(1);this.lastStatusMessage=message;let text=new ThemedText(()=>theme.fg("dim",this.lastStatusMessage),1,0);this.chatContainer.addChild(spacer),this.chatContainer.addChild(text),this.lastStatusSpacer=spacer,this.lastStatusText=text,this.ui.requestRender()}addCustomEntryToChat(entry){let renderer=this.session.extensionRunner.getEntryRenderer(entry.customType);if(!renderer)return;let component=new CustomEntryComponent(entry,renderer,this.outputPad);if(component.setExpanded(this.toolOutputExpanded),!!component.hasContent()){if(this.streamingComponent){let streamingIndex=this.chatContainer.children.indexOf(this.streamingComponent);if(streamingIndex>=0){this.chatContainer.children.splice(streamingIndex,0,component);return}}this.chatContainer.addChild(component)}}addMessageToChat(message,options){switch(message.role){case"bashExecution":{let component=new BashExecutionComponent(message.command,this.ui,message.excludeFromContext,this.outputPad);message.output&&component.appendOutput(message.output),component.setComplete(message.exitCode,message.cancelled,message.truncated?{truncated:!0}:void 0,message.fullOutputPath),this.chatContainer.addChild(component);break}case"custom":{if(message.display){let renderer=this.session.extensionRunner.getMessageRenderer(message.customType),component=new CustomMessageComponent(message,renderer,this.getMarkdownThemeWithSettings(),this.outputPad);component.setExpanded(this.toolOutputExpanded),this.chatContainer.addChild(component)}break}case"compactionSummary":{this.chatContainer.addChild(new Spacer(1));let component=new CompactionSummaryMessageComponent(message,this.getMarkdownThemeWithSettings(),this.outputPad);component.setExpanded(this.toolOutputExpanded),this.chatContainer.addChild(component);break}case"branchSummary":{this.chatContainer.addChild(new Spacer(1));let component=new BranchSummaryMessageComponent(message,this.getMarkdownThemeWithSettings(),this.outputPad);component.setExpanded(this.toolOutputExpanded),this.chatContainer.addChild(component);break}case"system":break;case"user":{let textContent=this.getUserMessageText(message);if(textContent){this.chatContainer.children.length>0&&this.chatContainer.addChild(new Spacer(1));let skillBlock=parseSkillBlock(textContent);if(skillBlock){let component=new SkillInvocationMessageComponent(skillBlock,this.getMarkdownThemeWithSettings(),this.outputPad);if(component.setExpanded(this.toolOutputExpanded),this.chatContainer.addChild(component),skillBlock.userMessage){this.chatContainer.addChild(new Spacer(1));let userComponent=new UserMessageComponent(skillBlock.userMessage,this.getMarkdownThemeWithSettings(),this.outputPad,this.getMarkdownTransformers());this.chatContainer.addChild(userComponent)}}else{let userComponent=new UserMessageComponent(textContent,this.getMarkdownThemeWithSettings(),this.outputPad,this.getMarkdownTransformers());this.chatContainer.addChild(userComponent)}options?.populateHistory&&this.editor.addToHistory?.(textContent)}break}case"assistant":{let assistantComponent=new AssistantMessageComponent(message,this.hideThinkingBlock,this.getMarkdownThemeWithSettings(),this.hiddenThinkingLabel,this.outputPad,this.getMarkdownTransformers());this.chatContainer.addChild(assistantComponent);break}case"toolResult":break;default:{let _exhaustive=message}}}renderSessionItems(items,options={}){this.pendingTools.clear();let renderedPendingTools=new Map,cacheMisses=this.settingsManager.getShowCacheMissNotices()?collectCacheMisses(this.sessionManager.getEntries(),this.session.modelRuntime):new Map;options.updateFooter&&(this.footer.invalidate(),this.updateEditorBorderColor());for(let item of items){if(isCustomSessionEntry(item)){this.addCustomEntryToChat(item);continue}if(isUsageSessionEntry(item)){this.addCacheWarmingUsage(item);continue}if(isCompactionCostNotice(item)){this.addCompactionCostNotice(item);continue}let message=item;if(message.role==="assistant"){this.addMessageToChat(message);for(let content of message.content)if(content.type==="toolCall"){let component=new ToolExecutionComponent(content.name,content.id,content.arguments,{showImages:this.settingsManager.getShowImages(),imageWidthCells:this.settingsManager.getImageWidthCells(),outputPad:this.outputPad},this.getRegisteredToolDefinition(content.name),this.ui,this.sessionManager.getCwd());if(component.setExpanded(this.toolOutputExpanded),this.chatContainer.addChild(component),message.stopReason==="aborted"||message.stopReason==="error"){let errorMessage5;if(message.stopReason==="aborted"){let retryAttempt=this.session.retryAttempt;errorMessage5=retryAttempt>0?`Aborted after ${retryAttempt} retry attempt${retryAttempt>1?"s":""}`:"Operation aborted"}else errorMessage5=message.errorMessage||"Error";component.updateResult({content:[{type:"text",text:errorMessage5}],isError:!0})}else renderedPendingTools.set(content.id,component)}if(message.stopReason!=="aborted"&&message.stopReason!=="error"){let miss=cacheMisses.get(message);miss&&this.addCacheMissNotice(miss)}}else if(message.role==="toolResult"){let component=renderedPendingTools.get(message.toolCallId);component&&(component.updateResult(message),renderedPendingTools.delete(message.toolCallId))}else this.addMessageToChat(message,options)}for(let[toolCallId,component]of renderedPendingTools)this.pendingTools.set(toolCallId,component);this.ui.requestRender()}renderSessionEntries(entries,options={}){this.renderer instanceof TuiAltScreen&&this.renderer.resetTextSelection();let items=entries.flatMap(entry=>{if(entry.type==="custom"||entry.type==="usage"&&entry.kind==="cache_warm")return[entry];let messages=sessionEntryToContextMessages(entry);return(entry.type==="compaction"||entry.type==="branch_summary")&&entry.usage&&messages.length>0?[...messages,{type:"compaction_cost",kind:entry.type,usage:entry.usage}]:messages});this.renderSessionItems(items,options)}addCacheWarmingUsage(entry){if(!this.settingsManager.getShowCacheMissNotices())return;this.chatContainer.addChild(new Spacer(1));let usage=formatCacheWarmingUsage(entry);this.chatContainer.addChild(new ThemedText(()=>theme.fg("dim",usage),1,0))}addCompactionCostNotice(notice){if(!this.settingsManager.getShowCacheMissNotices())return;let{usage}=notice,tokens=usage.input+usage.output+usage.cacheRead+usage.cacheWrite,cost=usage.cost.total>=.01?` (~$${usage.cost.total.toFixed(2)})`:"",label=notice.kind==="compaction"?"Compaction":"Branch summary";this.chatContainer.addChild(new Spacer(1)),this.chatContainer.addChild(new ThemedText(()=>theme.fg("warning",`${label}: ${formatTokens(tokens)} tokens billed${cost}`),1,0))}static countDroppedThinkingBlocks(message){let count=0;for(let diagnostic of message.diagnostics??[]){if(diagnostic.type!=="anthropic_input_transformations")continue;let transformations=diagnostic.details?.transformations;Array.isArray(transformations)&&(count+=transformations.filter(transformation=>typeof transformation=="object"&&transformation!==null&&transformation.type==="thinking_dropped").length)}return count}maybeShowThinkingDropNotice(message){if(!this.settingsManager.getShowCacheMissNotices())return;let droppedCount=_InteractiveMode.countDroppedThinkingBlocks(message);if(droppedCount===0)return;let previousDroppedCount=0,branch=this.sessionManager.getBranch();for(let i=branch.length-1;i>=0;i--){let entry=branch[i];if(entry.type==="message"&&entry.message.role==="assistant"){previousDroppedCount=_InteractiveMode.countDroppedThinkingBlocks(entry.message);break}}if(droppedCount<=previousDroppedCount)return;let noun=droppedCount===1?"thinking block":"thinking blocks";this.chatContainer.addChild(new Spacer(1)),this.chatContainer.addChild(new ThemedText(()=>theme.fg("warning",`Anthropic dropped ${droppedCount} ${noun} (details in session)`),1,0))}maybeShowCacheMissNotice(message){if(!this.settingsManager.getShowCacheMissNotices())return;let miss=detectCacheMiss(this.sessionManager.getEntries(),message,this.session.modelRuntime);miss&&this.addCacheMissNotice(miss)}addCacheMissNotice(miss){if(miss.missedTokens<2e4&&miss.missedCost<.1)return;let cost=miss.missedCost>=.01?` (~$${miss.missedCost.toFixed(2)})`:"",reBilled=`${formatTokens(miss.missedTokens)} tokens re-billed${cost}`,label="Cache miss";miss.modelChanged?label="Cache miss after model switch":miss.idleMs>=3e5&&(label=`Cache miss after ${Math.round(miss.idleMs/6e4)}m idle`),this.chatContainer.addChild(new Spacer(1)),this.chatContainer.addChild(new ThemedText(()=>theme.fg("warning",`${label}: ${reBilled}`),1,0))}renderInitialMessages(){let entries=this.sessionManager.buildContextEntries();this.renderSessionEntries(entries,{updateFooter:!0,populateHistory:!0}),this.renderProjectTrustWarningIfNeeded();let compactionCount=this.sessionManager.getEntries().filter(e=>e.type==="compaction").length;if(compactionCount>0){let times=compactionCount===1?"1 time":`${compactionCount} times`;this.showStatus(`Session compacted ${times}`)}}renderProjectTrustWarningIfNeeded(){this.settingsManager.isProjectTrusted()||!hasTrustRequiringProjectResources(this.sessionManager.getCwd())||(this.chatContainer.children.length>0&&this.chatContainer.addChild(new Spacer(1)),this.chatContainer.addChild(new ThemedText(()=>theme.fg("warning",`This project is not trusted. Project ${CONFIG_DIR_NAME} resources and packages are ignored. Use /trust to save a trust decision, then restart pink.`),1,0)))}async getUserInput(){let queuedInput=this.pendingUserInputs.shift();return queuedInput!==void 0?queuedInput:new Promise(resolve16=>{this.onInputCallback=text=>{this.onInputCallback=void 0,resolve16(text)}})}rebuildChatFromMessages(){this.chatContainer.clear(),this.renderSessionEntries(this.sessionManager.buildContextEntries())}handleCtrlC(){let now=Date.now();now-this.lastSigintTime<500?this.shutdown():(this.clearEditor(),this.lastSigintTime=now)}handleCtrlD(){this.shutdown()}isShuttingDown=!1;async shutdown(options){if(this.isShuttingDown)return;this.isShuttingDown=!0,options?.fromSignal&&(await this.runtimeHost.dispose(),this.themeController.disableAutoSync(),await this.ui.terminal.drainInput(1e3),this.stop(),process.exit(0)),this.themeController.disableAutoSync(),await this.ui.terminal.drainInput(1e3),this.stop(),await this.runtimeHost.dispose();let resumeCommand=formatResumeCommand(this.sessionManager);globalThis.__pinkExitBanner&&resumeCommand&&process.stdout.write(globalThis.__pinkExitBanner(resumeCommand)),!globalThis.__pinkExitBanner&&resumeCommand&&process.stdout.write(`${source_default.dim("To resume this session:")} ${resumeCommand}
|
|
994
994
|
`),process.exit(0)}emergencyTerminalExit(){this.isShuttingDown=!0,this.unregisterSignalHandlers(),killTrackedDetachedChildren(),process.exit(129)}uncaughtCrash(error){isDeadTerminalError(error)&&this.emergencyTerminalExit(),this.isShuttingDown&&process.exit(1),this.isShuttingDown=!0;try{this.unregisterSignalHandlers()}catch{}try{killTrackedDetachedChildren()}catch{}try{this.ui.stop()}catch{}console.error(`${APP_NAME} exiting due to uncaughtException:`),console.error(error);let extensionHint=this.getCrashExtensionHint(error);extensionHint&&console.error(`
|
|
995
995
|
${extensionHint}`),this.recordCrash("uncaught_exception",error)&&console.error(`
|
|
996
|
-
${this.crashReportInstructions()}`),process.exit(1)}async checkShutdownRequested(){this.shutdownRequested&&await this.shutdown()}registerSignalHandlers(){this.unregisterSignalHandlers();let signals=["SIGTERM"];process.platform!=="win32"&&signals.push("SIGHUP");for(let signal of signals){let handler=()=>{killTrackedDetachedChildren(),this.shutdown({fromSignal:!0})};process.prependListener(signal,handler),this.signalCleanupHandlers.push(()=>process.off(signal,handler))}let terminalErrorHandler=error=>{throw isDeadTerminalError(error)&&this.emergencyTerminalExit(),error};for(let stream2 of[process.stdin,process.stdout,process.stderr])stream2.on("error",terminalErrorHandler),this.signalCleanupHandlers.push(()=>stream2.off("error",terminalErrorHandler));let uncaughtExceptionHandler=error=>this.uncaughtCrash(error);process.prependListener("uncaughtException",uncaughtExceptionHandler),this.signalCleanupHandlers.push(()=>process.off("uncaughtException",uncaughtExceptionHandler))}unregisterSignalHandlers(){for(let cleanup of this.signalCleanupHandlers)cleanup();this.signalCleanupHandlers=[]}handleCtrlZ(){if(process.platform==="win32"){this.showStatus("Suspend to background is not supported on Windows");return}let suspendKeepAlive=setInterval(()=>{},2**30),ignoreSigint=()=>{};process.on("SIGINT",ignoreSigint),process.once("SIGCONT",()=>{clearInterval(suspendKeepAlive),process.removeListener("SIGINT",ignoreSigint),this.ui.start(),this.ui.requestRender(!0)});try{this.ui.stop(),process.kill(0,"SIGTSTP")}catch(error){throw clearInterval(suspendKeepAlive),process.removeListener("SIGINT",ignoreSigint),error}}async handleFollowUp(){let text=(this.editor.getExpandedText?.()??this.editor.getText()).trim();if(text){if(this.session.isCompacting){this.isExtensionCommand(text)?(this.editor.addToHistory?.(text),this.editor.setText(""),await this.session.prompt(text)):this.queueCompactionMessage(text,"followUp");return}this.session.isStreaming?(this.editor.addToHistory?.(text),this.editor.setText(""),await this.session.prompt(text,{streamingBehavior:"followUp"}),this.updatePendingMessagesDisplay(),this.ui.requestRender()):this.editor.onSubmit&&(this.editor.setText(""),this.editor.onSubmit(text))}}handleDequeue(){let restored=this.restoreQueuedMessagesToEditor();restored===0?this.showStatus("No queued messages to restore"):this.showStatus(`Restored ${restored} queued message${restored>1?"s":""} to editor`)}updateEditorBorderColor(){if(this.isBashMode)this.editor.borderColor=theme.getBashModeBorderColor();else{let level=this.session.thinkingLevel||"off";this.editor.borderColor=theme.getThinkingBorderColor(level)}this.activeStatusIndicator?.invalidate(),this.ui.requestRender()}cycleThinkingLevel(){let newLevel=this.session.cycleThinkingLevel();newLevel===void 0?this.showStatus("Current model does not support thinking"):(this.footer.invalidate(),this.updateEditorBorderColor(),this.showStatus(`Thinking level: ${newLevel}`))}async cycleModel(direction){try{let result=await this.session.cycleModel(direction);if(result===void 0){let msg=this.session.scopedModels.length>0?"Only one model in scope":"Only one model available";this.showStatus(msg)}else{this.footer.invalidate(),this.updateEditorBorderColor();let thinkingStr=result.model.reasoning&&result.thinkingLevel!=="off"?` (thinking: ${result.thinkingLevel})`:"";this.showStatus(`Switched to ${result.model.name||result.model.id}${thinkingStr}`),this.maybeWarnAboutAnthropicSubscriptionAuth(result.model)}}catch(error){this.showError(error instanceof Error?error.message:String(error))}}toggleToolOutputExpansion(){this.setToolsExpanded(!this.toolOutputExpanded)}setToolsExpanded(expanded){if(expanded===this.toolOutputExpanded)return;this.toolOutputExpanded=expanded;let activeHeader=this.customHeader??this.builtInHeader;isExpandable(activeHeader)&&activeHeader.setExpanded(expanded);for(let container of[this.loadedResourcesContainer,this.chatContainer])for(let child of container.children)isExpandable(child)&&child.setExpanded(expanded);this.showStatus(`Tool output: ${expanded?"expanded":"collapsed"}`)}updateThinkingBlockVisibility(){for(let child of this.chatContainer.children)child instanceof AssistantMessageComponent&&child.setHideThinkingBlock(this.hideThinkingBlock);this.ui.requestRender()}toggleThinkingBlockVisibility(){this.hideThinkingBlock=!this.hideThinkingBlock,this.settingsManager.setHideThinkingBlock(this.hideThinkingBlock),this.updateThinkingBlockVisibility(),this.showStatus(`Thinking blocks: ${this.hideThinkingBlock?"hidden":"visible"}`)}async handleOpenExternalEditor(){let editorCmd=this.settingsManager.getExternalEditorCommand(),content=this.editor.getExpandedText?.()??this.editor.getText();this.ui.stop();try{let result=await editInExternalEditor({command:editorCmd,content});result.status==="complete"&&this.editor.setText(result.content)}finally{this.ui.start(),this.ui.requestRender(!0)}}clearEditor(){this.editor.setText(""),this.ui.requestRender()}showError(errorMessage5){this.chatContainer.addChild(new Spacer(1)),this.chatContainer.addChild(new ThemedText(()=>theme.fg("error",`Error: ${errorMessage5}`),this.outputPad,0)),this.ui.requestRender()}showWarning(warningMessage){this.chatContainer.addChild(new Spacer(1)),this.chatContainer.addChild(new ThemedText(()=>theme.fg("warning",`Warning: ${warningMessage}`),1,0)),this.ui.requestRender()}showNewVersionNotification(release2){let updateInstruction=()=>theme.fg("muted",`New version ${release2.version} is available. Run `)+theme.fg("accent",`${APP_NAME} update`),changelogUrl="pink
|
|
996
|
+
${this.crashReportInstructions()}`),process.exit(1)}async checkShutdownRequested(){this.shutdownRequested&&await this.shutdown()}registerSignalHandlers(){this.unregisterSignalHandlers();let signals=["SIGTERM"];process.platform!=="win32"&&signals.push("SIGHUP");for(let signal of signals){let handler=()=>{killTrackedDetachedChildren(),this.shutdown({fromSignal:!0})};process.prependListener(signal,handler),this.signalCleanupHandlers.push(()=>process.off(signal,handler))}let terminalErrorHandler=error=>{throw isDeadTerminalError(error)&&this.emergencyTerminalExit(),error};for(let stream2 of[process.stdin,process.stdout,process.stderr])stream2.on("error",terminalErrorHandler),this.signalCleanupHandlers.push(()=>stream2.off("error",terminalErrorHandler));let uncaughtExceptionHandler=error=>this.uncaughtCrash(error);process.prependListener("uncaughtException",uncaughtExceptionHandler),this.signalCleanupHandlers.push(()=>process.off("uncaughtException",uncaughtExceptionHandler))}unregisterSignalHandlers(){for(let cleanup of this.signalCleanupHandlers)cleanup();this.signalCleanupHandlers=[]}handleCtrlZ(){if(process.platform==="win32"){this.showStatus("Suspend to background is not supported on Windows");return}let suspendKeepAlive=setInterval(()=>{},2**30),ignoreSigint=()=>{};process.on("SIGINT",ignoreSigint),process.once("SIGCONT",()=>{clearInterval(suspendKeepAlive),process.removeListener("SIGINT",ignoreSigint),this.ui.start(),this.ui.requestRender(!0)});try{this.ui.stop(),process.kill(0,"SIGTSTP")}catch(error){throw clearInterval(suspendKeepAlive),process.removeListener("SIGINT",ignoreSigint),error}}async handleFollowUp(){let text=(this.editor.getExpandedText?.()??this.editor.getText()).trim();if(text){if(this.session.isCompacting){this.isExtensionCommand(text)?(this.editor.addToHistory?.(text),this.editor.setText(""),await this.session.prompt(text)):this.queueCompactionMessage(text,"followUp");return}this.session.isStreaming?(this.editor.addToHistory?.(text),this.editor.setText(""),await this.session.prompt(text,{streamingBehavior:"followUp"}),this.updatePendingMessagesDisplay(),this.ui.requestRender()):this.editor.onSubmit&&(this.editor.setText(""),this.editor.onSubmit(text))}}handleDequeue(){let restored=this.restoreQueuedMessagesToEditor();restored===0?this.showStatus("No queued messages to restore"):this.showStatus(`Restored ${restored} queued message${restored>1?"s":""} to editor`)}updateEditorBorderColor(){if(this.isBashMode)this.editor.borderColor=theme.getBashModeBorderColor();else{let level=this.session.thinkingLevel||"off";this.editor.borderColor=theme.getThinkingBorderColor(level)}this.activeStatusIndicator?.invalidate(),this.ui.requestRender()}cycleThinkingLevel(){let newLevel=this.session.cycleThinkingLevel();newLevel===void 0?this.showStatus("Current model does not support thinking"):(this.footer.invalidate(),this.updateEditorBorderColor(),this.showStatus(`Thinking level: ${newLevel}`))}async cycleModel(direction){try{let result=await this.session.cycleModel(direction);if(result===void 0){let msg=this.session.scopedModels.length>0?"Only one model in scope":"Only one model available";this.showStatus(msg)}else{this.footer.invalidate(),this.updateEditorBorderColor();let thinkingStr=result.model.reasoning&&result.thinkingLevel!=="off"?` (thinking: ${result.thinkingLevel})`:"";this.showStatus(`Switched to ${result.model.name||result.model.id}${thinkingStr}`),this.maybeWarnAboutAnthropicSubscriptionAuth(result.model)}}catch(error){this.showError(error instanceof Error?error.message:String(error))}}toggleToolOutputExpansion(){this.setToolsExpanded(!this.toolOutputExpanded)}setToolsExpanded(expanded){if(expanded===this.toolOutputExpanded)return;this.toolOutputExpanded=expanded;let activeHeader=this.customHeader??this.builtInHeader;isExpandable(activeHeader)&&activeHeader.setExpanded(expanded);for(let container of[this.loadedResourcesContainer,this.chatContainer])for(let child of container.children)isExpandable(child)&&child.setExpanded(expanded);this.showStatus(`Tool output: ${expanded?"expanded":"collapsed"}`)}updateThinkingBlockVisibility(){for(let child of this.chatContainer.children)child instanceof AssistantMessageComponent&&child.setHideThinkingBlock(this.hideThinkingBlock);this.ui.requestRender()}toggleThinkingBlockVisibility(){this.hideThinkingBlock=!this.hideThinkingBlock,this.settingsManager.setHideThinkingBlock(this.hideThinkingBlock),this.updateThinkingBlockVisibility(),this.showStatus(`Thinking blocks: ${this.hideThinkingBlock?"hidden":"visible"}`)}async handleOpenExternalEditor(){let editorCmd=this.settingsManager.getExternalEditorCommand(),content=this.editor.getExpandedText?.()??this.editor.getText();this.ui.stop();try{let result=await editInExternalEditor({command:editorCmd,content});result.status==="complete"&&this.editor.setText(result.content)}finally{this.ui.start(),this.ui.requestRender(!0)}}clearEditor(){this.editor.setText(""),this.ui.requestRender()}showError(errorMessage5){this.chatContainer.addChild(new Spacer(1)),this.chatContainer.addChild(new ThemedText(()=>theme.fg("error",`Error: ${errorMessage5}`),this.outputPad,0)),this.ui.requestRender()}showWarning(warningMessage){this.chatContainer.addChild(new Spacer(1)),this.chatContainer.addChild(new ThemedText(()=>theme.fg("warning",`Warning: ${warningMessage}`),1,0)),this.ui.requestRender()}showNewVersionNotification(release2){let updateInstruction=()=>theme.fg("muted",`New version ${release2.version} is available. Run `)+theme.fg("accent",`${APP_NAME} update`),changelogUrl="https://github.com/ricardopiresqa/pink/blob/main/CHANGELOG.md",changelogLine=()=>{let changelogLink=getCapabilities().hyperlinks?hyperlink(theme.fg("accent",changelogUrl),changelogUrl):theme.fg("accent",changelogUrl);return theme.fg("muted","Changelog: ")+changelogLink},note=release2.note?.trim();this.chatContainer.addChild(new Spacer(1)),this.chatContainer.addChild(new DynamicBorder(text=>theme.fg("warning",text))),this.chatContainer.addChild(new ThemedText(()=>`${theme.bold(theme.fg("warning","Update Available"))}
|
|
997
997
|
${updateInstruction()}`,1,0)),note&&(this.chatContainer.addChild(new Spacer(1)),this.chatContainer.addChild(new Markdown(note,1,0,this.getMarkdownThemeWithSettings(),{color:text=>theme.fg("muted",text)})),this.chatContainer.addChild(new Spacer(1))),this.chatContainer.addChild(new ThemedText(changelogLine,1,0)),this.chatContainer.addChild(new DynamicBorder(text=>theme.fg("warning",text))),this.ui.requestRender()}showPackageUpdateNotification(packages){let updateInstruction=()=>theme.fg("muted","Package updates are available. Run ")+theme.fg("accent",`${APP_NAME} update --extensions`),packageLines=packages.map(pkg=>`- ${pkg}`).join(`
|
|
998
998
|
`);this.chatContainer.addChild(new Spacer(1)),this.chatContainer.addChild(new DynamicBorder(text=>theme.fg("warning",text))),this.chatContainer.addChild(new ThemedText(()=>`${theme.bold(theme.fg("warning","Package Updates Available"))}
|
|
999
999
|
${updateInstruction()}
|
|
@@ -619,8 +619,21 @@ async function runAcp(child: any, name: string, task: string, cwd: string, resul
|
|
|
619
619
|
|
|
620
620
|
// abre a sessão (initialize, session/new ou load, modelo). Uma vez por processo: o warmKept faz isto assim que a pessoa
|
|
621
621
|
// escolhe o agente, e a primeira mensagem só espera o que faltar. Devolve o erro, ou nada.
|
|
622
|
+
// cada passo da partida tem prazo e percebe o processo morto: sem isso, um agente travado (ex.: um MCP que não abre em
|
|
623
|
+
// session/new) deixava o "Trabalhando" contando para sempre, e nem o Esc soltava (owner 2026-11-24, opencode no outro PC)
|
|
624
|
+
export const ACP_SETUP_MS = 120000;
|
|
625
|
+
export function acpStep(conn: Pick<AcpConn, "exited">, name: string, step: string, request: Promise<any>, ms = ACP_SETUP_MS): Promise<any> {
|
|
626
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
627
|
+
const late = new Promise((resolve) => {
|
|
628
|
+
timer = setTimeout(() => resolve({ error: { message: `o ${name} não respondeu ${step} em ${Math.round(ms / 1000)} s${step === "session/new" ? " (um MCP que não abre nesta máquina pode travar aqui)" : ""}` } }), ms);
|
|
629
|
+
timer.unref?.();
|
|
630
|
+
});
|
|
631
|
+
const died = conn.exited.then((code) => ({ error: { message: `o ${name} saiu (código ${code}) durante ${step}` } }));
|
|
632
|
+
return Promise.race([request, late, died]).finally(() => clearTimeout(timer));
|
|
633
|
+
}
|
|
634
|
+
|
|
622
635
|
async function acpSetup(conn: AcpConn, name: string, cwd: string, resume?: { id?: string }, model?: string, extras?: Extras): Promise<string | undefined> {
|
|
623
|
-
const {
|
|
636
|
+
const client = { request: (method: string, params: any) => acpStep(conn, name, method, conn.client.request(method, params)) };
|
|
624
637
|
let config: any[] = [];
|
|
625
638
|
const init = await client.request("initialize", { protocolVersion: 1, clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false }, clientInfo: { name: "pink", version: "1" } });
|
|
626
639
|
if (init.error) return String(init.error.message ?? "initialize falhou");
|
|
@@ -11,7 +11,7 @@ import os from "node:os";
|
|
|
11
11
|
import path from "node:path";
|
|
12
12
|
import { fileURLToPath } from "node:url";
|
|
13
13
|
import { closeKept, externalAgents, listModels, pinkExtras, runExternal, warmKept } from "../examples/extensions/subagent/external.ts";
|
|
14
|
-
import { bulleted, runLabel, shortModel, streamedTokens, thinkingLabel, toolSummary, userLines, workingLabel } from "./pink-ui.ts";
|
|
14
|
+
import { bulleted, fit, runLabel, shortModel, streamedTokens, thinkingLabel, toolSummary, userLines, workingLabel } from "./pink-ui.ts";
|
|
15
15
|
|
|
16
16
|
// o Pink junto (card 1dfwh7kgfjx): MCPs do mcp.json, AGENTS.md e skills do Pink, mais o próprio Pink como MCP
|
|
17
17
|
const readJson = (file: string) => {
|
|
@@ -85,6 +85,13 @@ export function gatherExtras(pink: any, dir = process.env.PINK_CODING_AGENT_DIR
|
|
|
85
85
|
|
|
86
86
|
const STATUS = "pink-agente";
|
|
87
87
|
const WIDGET = "pink-agente-trabalhando";
|
|
88
|
+
const QUEUE = "pink-agente-fila";
|
|
89
|
+
// o id da conversa do agente fica nos detalhes de cada resposta gravada na sessão do Pink: reabrir a sessão e escolher o
|
|
90
|
+
// mesmo agente retoma a conversa dele (claude --resume, codex thread/resume, ACP session/load)
|
|
91
|
+
export const lastAgentSession = (entries: any[] | undefined, name: string): string | undefined =>
|
|
92
|
+
[...(entries ?? [])].reverse().find((e) => e?.type === "custom_message" && e.customType === "pink-agente" && e.details?.agent === name && typeof e.details?.session === "string" && e.details.session)?.details.session;
|
|
93
|
+
// fila como no Claude Code (owner 2026-11-24): cada mensagem esperando aparece em cinza acima da caixa, numa linha
|
|
94
|
+
export const queueLines = (queue: string[], width: number) => queue.map((text) => fit(`> ${String(text).replace(/\s+/g, " ").trim()}`, width));
|
|
88
95
|
const FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
|
|
89
96
|
|
|
90
97
|
const fresh = () => ({ messages: [] as any[], stderr: "", exitCode: 0, usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, contextTokens: 0, turns: 0 } });
|
|
@@ -250,7 +257,12 @@ export default function (pink: any, list: typeof externalAgents = externalAgents
|
|
|
250
257
|
ticker.unref?.();
|
|
251
258
|
};
|
|
252
259
|
|
|
260
|
+
const showQueue = (ui: any) => {
|
|
261
|
+
const queue = [...(active?.queue ?? [])];
|
|
262
|
+
ui?.setWidget?.(QUEUE, queue.length ? (_screen: any, theme: any) => ({ render: (width: number) => queueLines(queue, width).map((line) => theme.fg("dim", line)), invalidate() {} }) : undefined, { placement: "aboveEditor" });
|
|
263
|
+
};
|
|
253
264
|
const stop = (ctx?: any) => {
|
|
265
|
+
(ctx?.ui ?? lastUi)?.setWidget?.(QUEUE, undefined); // a fila é descartada junto
|
|
254
266
|
active?.controller?.abort();
|
|
255
267
|
closeKept(active?.resume); // fecha o processo do agente que ficou aberto entre as mensagens
|
|
256
268
|
active = undefined;
|
|
@@ -329,11 +341,12 @@ export default function (pink: any, list: typeof externalAgents = externalAgents
|
|
|
329
341
|
if (!current.agent.model && result.model && result.model !== name) (globalThis as any).__pinkExternalAgent = { name, model: result.model, effort: current.agent.effort };
|
|
330
342
|
}
|
|
331
343
|
const error = result.stopReason === "error" ? String(result.errorMessage ?? t("erro", "error", "error")) : undefined;
|
|
332
|
-
pink.sendMessage({ customType: "pink-agente", display: true, content: render(result, ctx.cwd), details: { agent: name, model: result.model, usage: result.usage, error, steps: steps(result, ctx.cwd), ms: Date.now() - started, output: outputOf(result) } });
|
|
344
|
+
pink.sendMessage({ customType: "pink-agente", display: true, content: render(result, ctx.cwd), details: { agent: name, session: current.resume?.id, model: result.model, usage: result.usage, error, steps: steps(result, ctx.cwd), ms: Date.now() - started, output: outputOf(result) } });
|
|
333
345
|
// a fila sai agora, numa mensagem só (como o Claude Code junta o que você digitou enquanto ele trabalhava)
|
|
334
346
|
if (active === current && current.queue?.length) {
|
|
335
347
|
const next = current.queue.join("\n\n");
|
|
336
348
|
current.queue = [];
|
|
349
|
+
showQueue(ctx.ui); // sai de cima da caixa: agora vira a mensagem enviada
|
|
337
350
|
await send(next, ctx);
|
|
338
351
|
}
|
|
339
352
|
};
|
|
@@ -429,11 +442,14 @@ export default function (pink: any, list: typeof externalAgents = externalAgents
|
|
|
429
442
|
}
|
|
430
443
|
}
|
|
431
444
|
stop(ctx);
|
|
432
|
-
|
|
445
|
+
// mesma sessão do Pink + mesmo agente: continua a conversa dele (owner 2026-11-24); sessão nova do Pink começa do zero
|
|
446
|
+
const saved = lastAgentSession(ctx.sessionManager?.getBranch?.(), agent.name);
|
|
447
|
+
active = { agent: { ...agent, ...(model ? { model } : {}), ...(effort ? { effort } : {}), extras: extras((screen ??= bridge(() => screenCtx))) }, resume: { keep: true, ...(saved ? { id: saved } : {}) } }; // keep: o processo do agente ACP fica aberto entre as mensagens; id: retoma a conversa
|
|
433
448
|
warm(active.agent, ctx.cwd, active.resume); // já liga o agente: a primeira mensagem não espera a partida a frio
|
|
434
449
|
(globalThis as any).__pinkExternalAgent = { name: active.agent.name, model: active.agent.model, effort: active.agent.effort }; // rótulo da caixa (pink-ui)
|
|
435
450
|
ctx.ui?.setStatus?.(STATUS, `${t("agente", "agente", "agent")}: ${label(active.agent)}`);
|
|
436
|
-
|
|
451
|
+
const again = saved ? t(" Continuando a conversa anterior dele.", " Continuando su conversación anterior.", " Continuing its previous conversation.") : "";
|
|
452
|
+
ctx.ui?.notify?.(t(`Agora suas mensagens vão para o ${label(active.agent)}, com o login e a cota dele.${again} /agente off volta ao Pink.`, `Ahora tus mensajes van a ${label(active.agent)}, con su login y su cuota.${again} /agente off vuelve a Pink.`, `Your messages now go to ${label(active.agent)}, with its own login and quota.${again} /agente off returns to Pink.`), "info");
|
|
437
453
|
},
|
|
438
454
|
});
|
|
439
455
|
|
|
@@ -442,8 +458,7 @@ export default function (pink: any, list: typeof externalAgents = externalAgents
|
|
|
442
458
|
if (active.controller) {
|
|
443
459
|
// fila (owner 2026-11-24): o que chega enquanto o agente responde vai junto, numa mensagem só, quando ele terminar
|
|
444
460
|
active.queue = [...(active.queue ?? []), String(event.text)];
|
|
445
|
-
|
|
446
|
-
ctx.ui?.notify?.(t(`Na fila: vai para o ${active.agent.name} quando ele terminar (${waiting} esperando; /agente off descarta).`, `En cola: va a ${active.agent.name} cuando termine (${waiting} en espera; /agente off la descarta).`, `Queued: goes to ${active.agent.name} when it finishes (${waiting} waiting; /agente off drops it).`), "info");
|
|
461
|
+
showQueue(ctx.ui);
|
|
447
462
|
return { action: "handled" };
|
|
448
463
|
}
|
|
449
464
|
const done = send(String(event.text), ctx);
|
package/extensions/pink-ui.ts
CHANGED
|
@@ -100,10 +100,11 @@ export function inputBox({ theme, content, width, label, inline = false, hints =
|
|
|
100
100
|
const lines = inline && label ? [footerLine({ theme, width: text, left: content[0] ?? "", right: label }), ...content.slice(1)] : content;
|
|
101
101
|
if (!inline && label && visible(label) + 1 + visible(tip) > text) {
|
|
102
102
|
// rótulo e dicas não cabem juntos: o rótulo ganha a linha dele, em vez de cortar as dicas
|
|
103
|
-
return [row(""), ...lines.map(row), row(""), row(theme.fg("muted", label)), row(footerLine({ theme, width: text, left: "", right: tip }))];
|
|
103
|
+
return [row(""), ...lines.map(row), row(""), row(theme.fg("muted", label)), row(footerLine({ theme, width: text, left: "", right: tip })), row("")];
|
|
104
104
|
}
|
|
105
105
|
const last = inline || !label ? footerLine({ theme, width: text, left: "", right: tip }) : footerLine({ theme, width: text, left: theme.fg("muted", label), right: tip });
|
|
106
|
-
|
|
106
|
+
// linha vazia também embaixo do rótulo, como a caixa do OpenCode (owner 2026-11-24)
|
|
107
|
+
return [row(""), ...lines.map(row), row(""), row(last), row("")];
|
|
107
108
|
}
|
|
108
109
|
|
|
109
110
|
export function footerLine({ theme, width, left, right }) {
|
|
@@ -521,6 +522,8 @@ export function thothSnapshot({ approvals, cards, calls }, now = Date.now()) {
|
|
|
521
522
|
}
|
|
522
523
|
|
|
523
524
|
export function thothLines({ theme, thoth, width }) {
|
|
525
|
+
// sem o Thoth instalado: uma apresentação curta no lugar da seção (owner 2026-11-24: "propaganda para todos")
|
|
526
|
+
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))];
|
|
524
527
|
if (!thoth?.ok) return [theme.fg("dim", thoth?.loading ? t("consultando…", "consultando…", "loading…") : t("Thoth indisponível", "Thoth no disponible", "Thoth unavailable"))];
|
|
525
528
|
const row = (label, value, tone = "text") => {
|
|
526
529
|
const left = theme.fg("muted", label);
|
|
@@ -608,8 +611,27 @@ export function resetLabel(epoch, now = new Date()) {
|
|
|
608
611
|
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}`;
|
|
609
612
|
}
|
|
610
613
|
|
|
614
|
+
// por que a leitura falhou: sem o motivo, "sem dado do plano" numa máquina nova não diz o que fazer
|
|
615
|
+
const PLAN_FAILURE = {
|
|
616
|
+
missing: t("thoth-client não achado no PATH", "thoth-client no está en el PATH", "thoth-client not on PATH"),
|
|
617
|
+
slow: t("thoth-client demorou mais de 60 s", "thoth-client tardó más de 60 s", "thoth-client took over 60 s"),
|
|
618
|
+
old: t("thoth-client antigo: atualize", "thoth-client antiguo: actualiza", "old thoth-client: update it"),
|
|
619
|
+
bad: t("resposta inválida do thoth-client", "respuesta inválida de thoth-client", "invalid thoth-client output"),
|
|
620
|
+
failed: t("rode: thoth-client uso estado", "ejecuta: thoth-client uso estado", "run: thoth-client uso estado"),
|
|
621
|
+
};
|
|
622
|
+
export function planFailure(error, stderr = "") {
|
|
623
|
+
if (error?.code === "ENOENT") return "missing";
|
|
624
|
+
if (error?.killed || error?.code === "ETIMEDOUT") return "slow";
|
|
625
|
+
if (/invalid choice|unrecognized arguments|escolha inválida/i.test(String(stderr))) return "old";
|
|
626
|
+
return "failed";
|
|
627
|
+
}
|
|
628
|
+
|
|
611
629
|
export function planLines({ theme, plan, width, now = new Date() }) {
|
|
612
|
-
if (!plan?.ok) return [theme.fg("dim",
|
|
630
|
+
if (!plan?.ok && plan?.loading) return [theme.fg("dim", t("consultando…", "consultando…", "loading…"))];
|
|
631
|
+
if (!plan?.ok) {
|
|
632
|
+
const why = PLAN_FAILURE[plan?.reason];
|
|
633
|
+
return [theme.fg("dim", t("sem dado do plano", "sin dato del plan", "no plan data")), ...(why ? [theme.fg("warning", fit(why, width))] : [])];
|
|
634
|
+
}
|
|
613
635
|
const out = [];
|
|
614
636
|
for (const [name, usage] of [["Claude", plan.claude], ["Codex", plan.codex]]) {
|
|
615
637
|
if (usage === undefined) continue;
|
|
@@ -670,12 +692,13 @@ export async function readClaudeFromPink(getKey, fetcher = fetch) {
|
|
|
670
692
|
export function readPlan(run = node("node:child_process")?.execFile) {
|
|
671
693
|
return new Promise((resolve, reject) => {
|
|
672
694
|
if (!run) return reject(new Error("no child_process"));
|
|
673
|
-
run("thoth-client", ["uso", "estado", "--json"], { timeout: 60000, windowsHide: true, maxBuffer: 4 << 20 }, (error, stdout) => {
|
|
674
|
-
if (error) return reject(error);
|
|
695
|
+
run("thoth-client", ["uso", "estado", "--json"], { timeout: 60000, windowsHide: true, maxBuffer: 4 << 20 }, (error, stdout, stderr) => {
|
|
696
|
+
if (error) return reject(Object.assign(error, { reason: planFailure(error, stderr) }));
|
|
697
|
+
const text = String(stdout ?? "");
|
|
675
698
|
try {
|
|
676
|
-
resolve(planSnapshot(JSON.parse(
|
|
699
|
+
resolve(planSnapshot(JSON.parse(text.slice(Math.max(0, text.indexOf("{")))))); // aviso impresso antes do JSON não derruba a leitura
|
|
677
700
|
} catch (parse) {
|
|
678
|
-
reject(parse);
|
|
701
|
+
reject(Object.assign(parse, { reason: "bad" }));
|
|
679
702
|
}
|
|
680
703
|
});
|
|
681
704
|
});
|
|
@@ -901,7 +924,7 @@ export function install(pink, ctx, { CustomEditor, SessionManager, version = "",
|
|
|
901
924
|
PINK.plan.busy = true;
|
|
902
925
|
const [cli, own] = await Promise.allSettled([readPlan(), readClaudeFromPink((provider) => ctx.modelRegistry?.getApiKeyForProvider?.(provider))]);
|
|
903
926
|
try {
|
|
904
|
-
const data = cli.status === "fulfilled" ? cli.value : { ok: false };
|
|
927
|
+
const data = cli.status === "fulfilled" ? cli.value : { ok: false, reason: cli.reason?.reason };
|
|
905
928
|
// o uso medido pelo login do Pink vale mais que o da linha de status do Claude Code (que só atualiza com ele aberto)
|
|
906
929
|
PINK.plan.data = own.status === "fulfilled" && own.value ? { ...data, ok: true, claude: own.value } : data;
|
|
907
930
|
} catch {
|
|
@@ -965,7 +988,7 @@ export function install(pink, ctx, { CustomEditor, SessionManager, version = "",
|
|
|
965
988
|
if (PINK.thothOn) startThoth();
|
|
966
989
|
const stats = sessionStats(ctx.sessionManager?.getEntries?.());
|
|
967
990
|
const total = stats.models.reduce((sum, item) => ({ input: sum.input + item.input, output: sum.output + item.output }), { input: 0, output: 0 });
|
|
968
|
-
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 :
|
|
991
|
+
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) } });
|
|
969
992
|
}, []),
|
|
970
993
|
};
|
|
971
994
|
// tarefas sobre a caixa de digitar quando a coluna da direita não cabe (com ela, as tarefas aparecem no PLANO)
|