@thothdev/pink 1.0.13 → 1.0.15

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,29 @@
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.15] - 2026-11-26
7
+
8
+ - /agente funciona como um modelo logado:
9
+ - a sessão é gravada já na primeira mensagem ao agente e aparece na lista com o seu pedido como título (antes uma
10
+ sessão só com o agente não ia para o disco e sumia se o Pink fechasse);
11
+ - o fim de cada resposta do agente faz o mesmo que o do modelo do Pink: título automático, coluna de sessões
12
+ atualizada, círculo do pink mux, sessão lembrada pelo mux, notificação e hook Stop;
13
+ - /undo desfaz também o último pedido ao agente e os arquivos que ele mudou (a conversa interna do agente não volta).
14
+ - Trocar entre o modelo do Pink e o /agente continua de onde o outro parou, nos dois sentidos: o agente recebe o que
15
+ aconteceu na conversa desde a última resposta dele, e ir para o agente com o modelo respondendo para o modelo e passa
16
+ o pedido ao agente.
17
+ - Os subagentes do /agente seguem a mesma regra dos do Pink: com a lateral ligada, só nela; sem ela, embaixo da caixa.
18
+ - ctrl+enter funciona no Windows Terminal (o Pink pergunta ao Windows se o ctrl está apertado, como já fazia com o
19
+ shift).
20
+
21
+ ## [1.0.14] - 2026-11-25
22
+
23
+ - /agente opencode: os subagentes dele voltam a aparecer (o Pink olhava o transporte "acp" em vez do nome do agente).
24
+ - Uma linha vazia entre o "Trabalhando" e a caixa também no modelo do Pink, como já era com o /agente.
25
+ - Trocar o modelo do Pink com o agente trabalhando derruba o agente na hora e o novo modelo continua o pedido, com o
26
+ que o agente já fez na conversa. Antes os dois trabalhavam ao mesmo tempo.
27
+ - Com o /agente trabalhando, o círculo da sessão gira na lateral do pink mux.
28
+
6
29
  ## [1.0.13] - 2026-11-25
7
30
 
8
31
  - Subagentes: na tela cheia ficam na coluna da direita, abaixo da SESSÃO; fora dela (modo regular ou terminal
@@ -542,8 +542,8 @@ Command exited with code ${msg.exitCode}`),msg.truncated&&msg.fullOutputPath&&(t
542
542
  `,lineStart)}pending=pending.slice(lineStart)}pending+=decoder.end();let finalEntry=parseSessionEntryLine(pending);finalEntry&&entries.push(finalEntry)}finally{closeSync(fd)}if(entries.length===0)return entries;let header=entries[0];return header.type!=="session"||typeof header.id!="string"?[]:(pending&&appendFileSync(resolvedFilePath,`
543
543
  `),entries)}function parseSessionHeaderCandidate(line){if(!line.trim())return;let entry=parseSessionEntryLine(line);if(entry)return entry.type!=="session"||typeof entry.id!="string"?null:entry}function readSessionHeader(filePath){let fd=openSync(filePath,"r");try{let decoder=new StringDecoder("utf8"),buffer=Buffer.allocUnsafe(SESSION_HEADER_READ_BUFFER_SIZE),lineChunks=[],scannedBytes=0;for(;scannedBytes<MAX_SESSION_HEADER_SCAN_BYTES;){let readLength=Math.min(buffer.length,MAX_SESSION_HEADER_SCAN_BYTES-scannedBytes),bytesRead=readSync(fd,buffer,0,readLength,null);if(bytesRead===0)return lineChunks.push(decoder.end()),parseSessionHeaderCandidate(lineChunks.join(""))??null;scannedBytes+=bytesRead;let chunk=decoder.write(buffer.subarray(0,bytesRead)),lineStart=0,newlineIndex=chunk.indexOf(`
544
544
  `,lineStart);for(;newlineIndex!==-1;){lineChunks.push(chunk.slice(lineStart,newlineIndex));let header=parseSessionHeaderCandidate(lineChunks.join(""));if(header!==void 0)return header;lineChunks.length=0,lineStart=newlineIndex+1,newlineIndex=chunk.indexOf(`
545
- `,lineStart)}lineChunks.push(chunk.slice(lineStart))}let probe=Buffer.allocUnsafe(1);if(readSync(fd,probe,0,probe.length,null)===0)return lineChunks.push(decoder.end()),parseSessionHeaderCandidate(lineChunks.join(""))??null;throw new SessionHeaderScanLimitError(filePath)}finally{closeSync(fd)}}function readSessionHeaderForDiscovery(filePath){try{return readSessionHeader(filePath)}catch{return null}}function getSessionHeaderCwd(header){let cwd=header.cwd;return typeof cwd=="string"?cwd:void 0}function sessionCwdMatches(cwd,resolvedCwd){return cwd!==void 0&&cwd!==""&&resolvePath(cwd)===resolvedCwd}function findMostRecentSession(sessionDir,cwd){let resolvedSessionDir=normalizePath(sessionDir),resolvedCwd=cwd?resolvePath(cwd):void 0;try{let files=readdirSync3(resolvedSessionDir).filter(file=>file.endsWith(".jsonl")).map(file=>join8(resolvedSessionDir,file)).map(path10=>({path:path10,mtime:statSync3(path10).mtimeMs})).sort((a,b)=>b.mtime-a.mtime);for(let{path:path10}of files){let header=readSessionHeaderForDiscovery(path10);if(header&&(!resolvedCwd||sessionCwdMatches(getSessionHeaderCwd(header),resolvedCwd)))return path10}return null}catch{return null}}function isMessageWithContent(message){return typeof message.role=="string"&&"content"in message}function extractTextContent(message){let content=message.content;return typeof content=="string"?content:content.filter(block=>block.type==="text").map(block=>block.text).join(" ")}function getMessageActivityTime(entry){let message=entry.message;if(!isMessageWithContent(message)||message.role!=="user"&&message.role!=="assistant")return;let msgTimestamp=message.timestamp;if(typeof msgTimestamp=="number")return msgTimestamp;let t=new Date(entry.timestamp).getTime();return Number.isNaN(t)?void 0:t}async function buildSessionInfo(filePath,signal,fileStats){try{let stats=fileStats??await stat(filePath),header=null,messageCount=0,firstMessage="",allMessages=[],name,lastActivityTime,rl=createInterface({input:createReadStream(filePath,{encoding:"utf8",signal}),crlfDelay:1/0});for await(let line of rl){let entry=parseSessionEntryLine(line);if(!entry)continue;if(!header){if(entry.type!=="session")return null;header=entry;continue}if(entry.type==="session_info"&&(name=entry.name?.trim()||void 0),entry.type!=="message")continue;messageCount++;let activityTime=getMessageActivityTime(entry);typeof activityTime=="number"&&(lastActivityTime=Math.max(lastActivityTime??0,activityTime));let message=entry.message;if(!isMessageWithContent(message)||message.role!=="user"&&message.role!=="assistant")continue;let textContent=extractTextContent(message);textContent&&(allMessages.push(textContent),!firstMessage&&message.role==="user"&&(firstMessage=textContent))}if(!header)return null;let cwd=typeof header.cwd=="string"?header.cwd:"",parentSessionPath=header.parentSession,headerTime=typeof header.timestamp=="string"?new Date(header.timestamp).getTime():NaN,modified=typeof lastActivityTime=="number"&&lastActivityTime>0?new Date(lastActivityTime):Number.isNaN(headerTime)?stats.mtime:new Date(headerTime);return{path:filePath,id:header.id,cwd,name,parentSessionPath,created:new Date(header.timestamp),modified,messageCount,firstMessage:firstMessage||"(no messages)",allMessagesText:allMessages.join(" ")}}catch{return signal?.throwIfAborted(),null}}var MAX_CONCURRENT_SESSION_INFO_LOADS=10,MAX_CONCURRENT_SESSION_DISCOVERY_LOADS=64,CURRENT_SESSION_LIST_PUBLISH_INTERVAL=10,ALL_SESSION_LIST_PUBLISH_INTERVAL=100;async function mapWithConcurrency(items,limit,map,signal){let results=new Array(items.length),nextIndex=0,worker=async()=>{for(;nextIndex<items.length;){signal?.throwIfAborted();let index3=nextIndex++;results[index3]=await map(items[index3],index3)}};return await Promise.all(Array.from({length:Math.min(limit,items.length)},()=>worker())),results}function sortSessionInfos(sessions){return sessions.sort((a,b)=>b.modified.getTime()-a.modified.getTime())}function buildSessionInfosWithConcurrency(files,onLoaded,signal){return mapWithConcurrency(files,MAX_CONCURRENT_SESSION_INFO_LOADS,async(file,index3)=>{let info=await buildSessionInfo(file.path,signal,file.stats);return onLoaded(info,index3),info},signal)}async function listSessionsFromDir(dir,onProgress,signal){if(signal?.throwIfAborted(),!existsSync6(dir))return[];try{let files=(await readdir(dir)).filter(file=>file.endsWith(".jsonl")).sort((a,b)=>b.localeCompare(a)).map(file=>({path:join8(dir,file)})),total=files.length,partialSessions=[],loaded=0;return(await buildSessionInfosWithConcurrency(files,info=>{loaded++,info&&partialSessions.push(info);let publishPartial=loaded===1||loaded%CURRENT_SESSION_LIST_PUBLISH_INTERVAL===0||loaded===files.length;onProgress?.(loaded,total,publishPartial?sortSessionInfos([...partialSessions]):void 0)},signal)).filter(info=>info!==null)}catch{return signal?.throwIfAborted(),[]}}var SessionManager=class _SessionManager{sessionId="";sessionFile;sessionDir;cwd;persist;flushed=!1;fileEntries=[];byId=new Map;labelsById=new Map;labelTimestampsById=new Map;leafId=null;constructor(cwd,sessionDir,sessionFile,persist,newSessionOptions,preloadedFileEntries){this.cwd=resolvePath(cwd),this.sessionDir=normalizePath(sessionDir),this.persist=persist,persist&&this.sessionDir&&!existsSync6(this.sessionDir)&&mkdirSync3(this.sessionDir,{recursive:!0}),sessionFile?this._setSessionFile(sessionFile,preloadedFileEntries):preloadedFileEntries?.length?this._loadEntries(preloadedFileEntries,newSessionOptions):this.newSession(newSessionOptions)}setSessionFile(sessionFile){this._setSessionFile(sessionFile)}_setSessionFile(sessionFile,preloadedFileEntries){if(this.sessionFile=resolvePath(sessionFile),existsSync6(this.sessionFile)){let entries=preloadedFileEntries??loadEntriesFromFile(this.sessionFile);if(entries.length===0){let explicitPath=this.sessionFile;if(statSync3(explicitPath).size>0)throw new Error(`Session file is not a valid ${APP_NAME} session: ${explicitPath}`);this.newSession(),this.sessionFile=explicitPath,this._rewriteFile(),this.flushed=!0;return}this._loadEntries(entries),this.flushed=!0}else{let explicitPath=this.sessionFile;this.newSession(),this.sessionFile=explicitPath}}newSession(options){options?.id!==void 0&&assertValidSessionId(options.id),this.sessionId=options?.id??createSessionId();let timestamp=new Date().toISOString(),header={type:"session",version:CURRENT_SESSION_VERSION,id:this.sessionId,timestamp,cwd:this.cwd,parentSession:options?.parentSession};if(this.fileEntries=[header],this.byId.clear(),this.labelsById.clear(),this.labelTimestampsById.clear(),this.leafId=null,this.flushed=!1,this.persist){let fileTimestamp=timestamp.replace(/[:.]/g,"-");this.sessionFile=join8(this.getSessionDir(),`${fileTimestamp}_${this.sessionId}.jsonl`)}return this.sessionFile}_loadEntries(entries,options){let header=entries.find(e=>e.type==="session");header?(this.fileEntries=entries,this.sessionId=header.id,migrateToCurrentVersion(this.fileEntries)&&this._rewriteFile()):(this.newSession(options),this.fileEntries=this.fileEntries.concat(entries)),this._buildIndex()}_buildIndex(){this.byId.clear(),this.labelsById.clear(),this.labelTimestampsById.clear(),this.leafId=null;for(let entry of this.fileEntries)entry.type!=="session"&&(this.byId.set(entry.id,entry),this.leafId=entry.id,entry.type==="label"&&(entry.label?(this.labelsById.set(entry.targetId,entry.label),this.labelTimestampsById.set(entry.targetId,entry.timestamp)):(this.labelsById.delete(entry.targetId),this.labelTimestampsById.delete(entry.targetId))))}_rewriteFile(){if(!this.persist||!this.sessionFile)return;let fd=openSync(this.sessionFile,"w");try{for(let entry of this.fileEntries)writeFileSync3(fd,`${JSON.stringify(entry)}
546
- `)}finally{closeSync(fd)}}isPersisted(){return this.persist}getCwd(){return this.cwd}getSessionDir(){return this.sessionDir}usesDefaultSessionDir(){return this.sessionDir===getDefaultSessionDirPath(this.cwd)}getSessionId(){return this.sessionId}getSessionFile(){return this.sessionFile}_hasConversation(){return this.fileEntries.some(e=>e.type==="message"&&(e.message.role==="user"||e.message.role==="assistant"))}_persist(entry){if(!(!this.persist||!this.sessionFile))if(this.flushed)appendFileSync(this.sessionFile,`${JSON.stringify(entry)}
545
+ `,lineStart)}lineChunks.push(chunk.slice(lineStart))}let probe=Buffer.allocUnsafe(1);if(readSync(fd,probe,0,probe.length,null)===0)return lineChunks.push(decoder.end()),parseSessionHeaderCandidate(lineChunks.join(""))??null;throw new SessionHeaderScanLimitError(filePath)}finally{closeSync(fd)}}function readSessionHeaderForDiscovery(filePath){try{return readSessionHeader(filePath)}catch{return null}}function getSessionHeaderCwd(header){let cwd=header.cwd;return typeof cwd=="string"?cwd:void 0}function sessionCwdMatches(cwd,resolvedCwd){return cwd!==void 0&&cwd!==""&&resolvePath(cwd)===resolvedCwd}function findMostRecentSession(sessionDir,cwd){let resolvedSessionDir=normalizePath(sessionDir),resolvedCwd=cwd?resolvePath(cwd):void 0;try{let files=readdirSync3(resolvedSessionDir).filter(file=>file.endsWith(".jsonl")).map(file=>join8(resolvedSessionDir,file)).map(path10=>({path:path10,mtime:statSync3(path10).mtimeMs})).sort((a,b)=>b.mtime-a.mtime);for(let{path:path10}of files){let header=readSessionHeaderForDiscovery(path10);if(header&&(!resolvedCwd||sessionCwdMatches(getSessionHeaderCwd(header),resolvedCwd)))return path10}return null}catch{return null}}function isMessageWithContent(message){return typeof message.role=="string"&&"content"in message}function extractTextContent(message){let content=message.content;return typeof content=="string"?content:content.filter(block=>block.type==="text").map(block=>block.text).join(" ")}function getMessageActivityTime(entry){let message=entry.message;if(!isMessageWithContent(message)||message.role!=="user"&&message.role!=="assistant")return;let msgTimestamp=message.timestamp;if(typeof msgTimestamp=="number")return msgTimestamp;let t=new Date(entry.timestamp).getTime();return Number.isNaN(t)?void 0:t}async function buildSessionInfo(filePath,signal,fileStats){try{let stats=fileStats??await stat(filePath),header=null,messageCount=0,firstMessage="",allMessages=[],name,lastActivityTime,rl=createInterface({input:createReadStream(filePath,{encoding:"utf8",signal}),crlfDelay:1/0});for await(let line of rl){let entry=parseSessionEntryLine(line);if(!entry)continue;if(!header){if(entry.type!=="session")return null;header=entry;continue}if(entry.type==="session_info"&&(name=entry.name?.trim()||void 0),entry.type==="custom_message"&&/^pink-agente/.test(entry.customType??"")){messageCount++;let pinkText=String(entry.details?.text??(typeof entry.content=="string"?entry.content:"")).trim();pinkText&&(allMessages.push(pinkText),!firstMessage&&entry.customType==="pink-agente-pedido"&&(firstMessage=pinkText));continue}if(entry.type!=="message")continue;messageCount++;let activityTime=getMessageActivityTime(entry);typeof activityTime=="number"&&(lastActivityTime=Math.max(lastActivityTime??0,activityTime));let message=entry.message;if(!isMessageWithContent(message)||message.role!=="user"&&message.role!=="assistant")continue;let textContent=extractTextContent(message);textContent&&(allMessages.push(textContent),!firstMessage&&message.role==="user"&&(firstMessage=textContent))}if(!header)return null;let cwd=typeof header.cwd=="string"?header.cwd:"",parentSessionPath=header.parentSession,headerTime=typeof header.timestamp=="string"?new Date(header.timestamp).getTime():NaN,modified=typeof lastActivityTime=="number"&&lastActivityTime>0?new Date(lastActivityTime):Number.isNaN(headerTime)?stats.mtime:new Date(headerTime);return{path:filePath,id:header.id,cwd,name,parentSessionPath,created:new Date(header.timestamp),modified,messageCount,firstMessage:firstMessage||"(no messages)",allMessagesText:allMessages.join(" ")}}catch{return signal?.throwIfAborted(),null}}var MAX_CONCURRENT_SESSION_INFO_LOADS=10,MAX_CONCURRENT_SESSION_DISCOVERY_LOADS=64,CURRENT_SESSION_LIST_PUBLISH_INTERVAL=10,ALL_SESSION_LIST_PUBLISH_INTERVAL=100;async function mapWithConcurrency(items,limit,map,signal){let results=new Array(items.length),nextIndex=0,worker=async()=>{for(;nextIndex<items.length;){signal?.throwIfAborted();let index3=nextIndex++;results[index3]=await map(items[index3],index3)}};return await Promise.all(Array.from({length:Math.min(limit,items.length)},()=>worker())),results}function sortSessionInfos(sessions){return sessions.sort((a,b)=>b.modified.getTime()-a.modified.getTime())}function buildSessionInfosWithConcurrency(files,onLoaded,signal){return mapWithConcurrency(files,MAX_CONCURRENT_SESSION_INFO_LOADS,async(file,index3)=>{let info=await buildSessionInfo(file.path,signal,file.stats);return onLoaded(info,index3),info},signal)}async function listSessionsFromDir(dir,onProgress,signal){if(signal?.throwIfAborted(),!existsSync6(dir))return[];try{let files=(await readdir(dir)).filter(file=>file.endsWith(".jsonl")).sort((a,b)=>b.localeCompare(a)).map(file=>({path:join8(dir,file)})),total=files.length,partialSessions=[],loaded=0;return(await buildSessionInfosWithConcurrency(files,info=>{loaded++,info&&partialSessions.push(info);let publishPartial=loaded===1||loaded%CURRENT_SESSION_LIST_PUBLISH_INTERVAL===0||loaded===files.length;onProgress?.(loaded,total,publishPartial?sortSessionInfos([...partialSessions]):void 0)},signal)).filter(info=>info!==null)}catch{return signal?.throwIfAborted(),[]}}var SessionManager=class _SessionManager{sessionId="";sessionFile;sessionDir;cwd;persist;flushed=!1;fileEntries=[];byId=new Map;labelsById=new Map;labelTimestampsById=new Map;leafId=null;constructor(cwd,sessionDir,sessionFile,persist,newSessionOptions,preloadedFileEntries){this.cwd=resolvePath(cwd),this.sessionDir=normalizePath(sessionDir),this.persist=persist,persist&&this.sessionDir&&!existsSync6(this.sessionDir)&&mkdirSync3(this.sessionDir,{recursive:!0}),sessionFile?this._setSessionFile(sessionFile,preloadedFileEntries):preloadedFileEntries?.length?this._loadEntries(preloadedFileEntries,newSessionOptions):this.newSession(newSessionOptions)}setSessionFile(sessionFile){this._setSessionFile(sessionFile)}_setSessionFile(sessionFile,preloadedFileEntries){if(this.sessionFile=resolvePath(sessionFile),existsSync6(this.sessionFile)){let entries=preloadedFileEntries??loadEntriesFromFile(this.sessionFile);if(entries.length===0){let explicitPath=this.sessionFile;if(statSync3(explicitPath).size>0)throw new Error(`Session file is not a valid ${APP_NAME} session: ${explicitPath}`);this.newSession(),this.sessionFile=explicitPath,this._rewriteFile(),this.flushed=!0;return}this._loadEntries(entries),this.flushed=!0}else{let explicitPath=this.sessionFile;this.newSession(),this.sessionFile=explicitPath}}newSession(options){options?.id!==void 0&&assertValidSessionId(options.id),this.sessionId=options?.id??createSessionId();let timestamp=new Date().toISOString(),header={type:"session",version:CURRENT_SESSION_VERSION,id:this.sessionId,timestamp,cwd:this.cwd,parentSession:options?.parentSession};if(this.fileEntries=[header],this.byId.clear(),this.labelsById.clear(),this.labelTimestampsById.clear(),this.leafId=null,this.flushed=!1,this.persist){let fileTimestamp=timestamp.replace(/[:.]/g,"-");this.sessionFile=join8(this.getSessionDir(),`${fileTimestamp}_${this.sessionId}.jsonl`)}return this.sessionFile}_loadEntries(entries,options){let header=entries.find(e=>e.type==="session");header?(this.fileEntries=entries,this.sessionId=header.id,migrateToCurrentVersion(this.fileEntries)&&this._rewriteFile()):(this.newSession(options),this.fileEntries=this.fileEntries.concat(entries)),this._buildIndex()}_buildIndex(){this.byId.clear(),this.labelsById.clear(),this.labelTimestampsById.clear(),this.leafId=null;for(let entry of this.fileEntries)entry.type!=="session"&&(this.byId.set(entry.id,entry),this.leafId=entry.id,entry.type==="label"&&(entry.label?(this.labelsById.set(entry.targetId,entry.label),this.labelTimestampsById.set(entry.targetId,entry.timestamp)):(this.labelsById.delete(entry.targetId),this.labelTimestampsById.delete(entry.targetId))))}_rewriteFile(){if(!this.persist||!this.sessionFile)return;let fd=openSync(this.sessionFile,"w");try{for(let entry of this.fileEntries)writeFileSync3(fd,`${JSON.stringify(entry)}
546
+ `)}finally{closeSync(fd)}}isPersisted(){return this.persist}getCwd(){return this.cwd}getSessionDir(){return this.sessionDir}usesDefaultSessionDir(){return this.sessionDir===getDefaultSessionDirPath(this.cwd)}getSessionId(){return this.sessionId}getSessionFile(){return this.sessionFile}_hasConversation(){return this.fileEntries.some(e=>e.type==="message"&&(e.message.role==="user"||e.message.role==="assistant")||e.type==="custom_message"&&/^pink-agente/.test(e.customType??""))}_persist(entry){if(!(!this.persist||!this.sessionFile))if(this.flushed)appendFileSync(this.sessionFile,`${JSON.stringify(entry)}
547
547
  `);else{if(!this._hasConversation())return;let fd=openSync(this.sessionFile,"wx");try{for(let e of this.fileEntries)writeFileSync3(fd,`${JSON.stringify(e)}
548
548
  `)}finally{closeSync(fd)}this.flushed=!0}}_appendEntry(entry){this.fileEntries.push(entry),this.byId.set(entry.id,entry),this.leafId=entry.id,this._persist(entry)}appendMessage(message){let entry={type:"message",id:generateId(this.byId),parentId:this.leafId,timestamp:new Date().toISOString(),message};return this._appendEntry(entry),entry.id}appendThinkingLevelChange(thinkingLevel){let entry={type:"thinking_level_change",id:generateId(this.byId),parentId:this.leafId,timestamp:new Date().toISOString(),thinkingLevel};return this._appendEntry(entry),entry.id}appendModelChange(provider,modelId){let entry={type:"model_change",id:generateId(this.byId),parentId:this.leafId,timestamp:new Date().toISOString(),provider,modelId};return this._appendEntry(entry),entry.id}appendUsage(kind,provider,model,usage,note){let entry={type:"usage",id:generateId(this.byId),parentId:this.leafId,timestamp:new Date().toISOString(),kind,provider,model,usage,...note?{note}:{}};return this._appendEntry(entry),entry}appendCompaction(summary,firstKeptEntryId,tokensBefore,details,fromHook,usage){let timestamp=new Date().toISOString(),systemMessage=getCurrentSystemMessage(this.buildSessionProjection().messages),id=generateId(this.byId),entry={type:"compaction",id,parentId:this.leafId,timestamp,summary,firstKeptEntryId:firstKeptEntryId??id,tokensBefore,details,usage,fromHook,...systemMessage?{systemMessage:{...systemMessage,timestamp:new Date(timestamp).getTime()}}:{}};return this._appendEntry(entry),entry.id}appendCustomEntry(customType,data){let entry={type:"custom",customType,data,id:generateId(this.byId),parentId:this.leafId,timestamp:new Date().toISOString()};return this._appendEntry(entry),entry.id}appendSessionInfo(name){let sanitizedName=name.replace(/[\r\n]+/g," ").trim(),entry={type:"session_info",id:generateId(this.byId),parentId:this.leafId,timestamp:new Date().toISOString(),name:sanitizedName};return this._appendEntry(entry),entry.id}getSessionName(){for(let i=this.fileEntries.length-1;i>=0;i--){let entry=this.fileEntries[i];if(entry.type==="session_info")return entry.name?.trim()||void 0}}appendCustomMessageEntry(customType,content,display,details){let entry={type:"custom_message",customType,content,display,details,id:generateId(this.byId),parentId:this.leafId,timestamp:new Date().toISOString()};return this._appendEntry(entry),entry.id}appendContextEdit(targetId,replacement){if(replacement!==null&&(typeof replacement!="object"||!("content"in replacement)||typeof replacement.content!="string"&&!Array.isArray(replacement.content)))throw new Error("Context edit replacement must be null or contain string/array content");let target=this.byId.get(targetId);if(!target)throw new Error(`Entry ${targetId} not found`);if(!this.getBranch().some(entry2=>entry2.id===targetId))throw new Error(`Entry ${targetId} is not on the active branch`);if(!(target.type==="custom_message"||target.type==="message"&&(target.message.role==="user"||target.message.role==="assistant"||target.message.role==="toolResult")))throw new Error(`Entry ${targetId} does not contribute editable model content`);let targetRole=target.type==="message"?target.message.role:"custom",normalizedReplacement=replacement!==null&&(targetRole==="assistant"||targetRole==="toolResult")&&typeof replacement.content=="string"?{content:[{type:"text",text:replacement.content}]}:replacement,entry={type:"context_edit",id:generateId(this.byId),parentId:this.leafId,timestamp:new Date().toISOString(),targetId,replacement:normalizedReplacement};return this._appendEntry(entry),entry.id}getLeafId(){return this.leafId}getLeafEntry(){return this.leafId?this.byId.get(this.leafId):void 0}getEntry(id){return this.byId.get(id)}getChildren(parentId){let children=[];for(let entry of this.byId.values())entry.parentId===parentId&&children.push(entry);return children}getLabel(id){return this.labelsById.get(id)}appendLabelChange(targetId,label){if(!this.byId.has(targetId))throw new Error(`Entry ${targetId} not found`);let entry={type:"label",id:generateId(this.byId),parentId:this.leafId,timestamp:new Date().toISOString(),targetId,label};return this._appendEntry(entry),label?(this.labelsById.set(targetId,label),this.labelTimestampsById.set(targetId,entry.timestamp)):(this.labelsById.delete(targetId),this.labelTimestampsById.delete(targetId)),entry.id}getBranch(fromId){let path10=[],startId=fromId??this.leafId,current=startId?this.byId.get(startId):void 0;for(;current;)path10.push(current),current=current.parentId?this.byId.get(current.parentId):void 0;return path10.reverse(),path10}buildContextEntries(){return buildContextEntries(this.getEntries(),this.leafId,this.byId)}buildSessionProjection(){return buildSessionProjection(this.getEntries(),this.leafId,this.byId)}buildSessionContext(){let{messages,thinkingLevel,model}=this.buildSessionProjection();return{messages,thinkingLevel,model}}getHeader(){let h=this.fileEntries.find(e=>e.type==="session");return h||null}getEntryCount(){return this.byId.size}getEntries(){return this.fileEntries.filter(e=>e.type!=="session")}getTree(){let entries=this.getEntries(),nodeMap=new Map,roots=[];for(let entry of entries){let label=this.labelsById.get(entry.id),labelTimestamp=this.labelTimestampsById.get(entry.id);nodeMap.set(entry.id,{entry,children:[],label,labelTimestamp})}for(let entry of entries){let node=nodeMap.get(entry.id);if(entry.parentId===null||entry.parentId===entry.id)roots.push(node);else{let parent=nodeMap.get(entry.parentId);parent?parent.children.push(node):roots.push(node)}}let stack=[...roots];for(;stack.length>0;){let node=stack.pop();node.children.sort((a,b)=>new Date(a.entry.timestamp).getTime()-new Date(b.entry.timestamp).getTime()),stack.push(...node.children)}return roots}branch(branchFromId){if(!this.byId.has(branchFromId))throw new Error(`Entry ${branchFromId} not found`);this.leafId=branchFromId}resetLeaf(){this.leafId=null}branchWithSummary(branchFromId,summary,details,fromHook,usage){if(branchFromId!==null&&!this.byId.has(branchFromId))throw new Error(`Entry ${branchFromId} not found`);let fromId=this.leafId??"root";this.leafId=branchFromId;let entry={type:"branch_summary",id:generateId(this.byId),parentId:branchFromId,timestamp:new Date().toISOString(),fromId,summary,details,usage,fromHook};return this._appendEntry(entry),entry.id}createBranchedSession(leafId){let previousSessionFile=this.sessionFile,path10=this.getBranch(leafId);if(path10.length===0)throw new Error(`Entry ${leafId} not found`);let pathWithoutLabels=[],replacementByLabelId=new Map,pendingLabelIds=[],pathParentId=null;for(let entry of path10){if(entry.type==="label"){pendingLabelIds.push(entry.id);continue}for(let labelId of pendingLabelIds)replacementByLabelId.set(labelId,entry.id);pendingLabelIds.length=0,pathWithoutLabels.push(entry.type==="compaction"?{...entry,parentId:pathParentId,firstKeptEntryId:entry.firstKeptEntryId===entry.id?entry.id:replacementByLabelId.get(entry.firstKeptEntryId)??entry.firstKeptEntryId}:{...entry,parentId:pathParentId}),pathParentId=entry.id}let newSessionId=createSessionId(),timestamp=new Date().toISOString(),fileTimestamp=timestamp.replace(/[:.]/g,"-"),newSessionFile=join8(this.getSessionDir(),`${fileTimestamp}_${newSessionId}.jsonl`),header={type:"session",version:CURRENT_SESSION_VERSION,id:newSessionId,timestamp,cwd:this.cwd,parentSession:this.persist?previousSessionFile:void 0},pathEntryIds=new Set(pathWithoutLabels.map(e=>e.id)),labelsToWrite=[];for(let[targetId,label]of this.labelsById)pathEntryIds.has(targetId)&&labelsToWrite.push({targetId,label,timestamp:this.labelTimestampsById.get(targetId)});if(this.persist){let parentId2=pathWithoutLabels[pathWithoutLabels.length-1]?.id||null,labelEntries2=[];for(let{targetId,label,timestamp:labelTimestamp}of labelsToWrite){let labelEntry={type:"label",id:generateId(new Set(pathEntryIds)),parentId:parentId2,timestamp:labelTimestamp,targetId,label};pathEntryIds.add(labelEntry.id),labelEntries2.push(labelEntry),parentId2=labelEntry.id}return this.fileEntries=[header,...pathWithoutLabels,...labelEntries2],this.sessionId=newSessionId,this.sessionFile=newSessionFile,this._buildIndex(),this._hasConversation()?(this._rewriteFile(),this.flushed=!0):this.flushed=!1,newSessionFile}let labelEntries=[],parentId=pathWithoutLabels[pathWithoutLabels.length-1]?.id||null;for(let{targetId,label,timestamp:labelTimestamp}of labelsToWrite){let labelEntry={type:"label",id:generateId(new Set([...pathEntryIds,...labelEntries.map(e=>e.id)])),parentId,timestamp:labelTimestamp,targetId,label};labelEntries.push(labelEntry),parentId=labelEntry.id}this.fileEntries=[header,...pathWithoutLabels,...labelEntries],this.sessionId=newSessionId,this._buildIndex()}static create(cwd,sessionDir,options){let dir=sessionDir?normalizePath(sessionDir):getDefaultSessionDir(cwd);return new _SessionManager(cwd,dir,void 0,!0,options)}static open(path10,sessionDir,cwdOverride){let resolvedPath=resolvePath(path10),header=null,preloadedFileEntries;if(cwdOverride===void 0&&existsSync6(resolvedPath))try{header=readSessionHeader(resolvedPath)}catch(error){if(!(error instanceof SessionHeaderScanLimitError))throw error;preloadedFileEntries=loadEntriesFromFile(resolvedPath);let firstEntry=preloadedFileEntries[0];header=firstEntry?.type==="session"?firstEntry:null}let cwd=cwdOverride??(header?getSessionHeaderCwd(header):void 0)??process.cwd(),dir=sessionDir?normalizePath(sessionDir):resolve3(resolvedPath,"..");return new _SessionManager(cwd,dir,resolvedPath,!0,void 0,preloadedFileEntries)}static continueRecent(cwd,sessionDir){let dir=sessionDir?normalizePath(sessionDir):getDefaultSessionDir(cwd),filterCwd=sessionDir!==void 0&&dir!==getDefaultSessionDirPath(cwd),mostRecent=findMostRecentSession(dir,filterCwd?cwd:void 0);return mostRecent?new _SessionManager(cwd,dir,mostRecent,!0):new _SessionManager(cwd,dir,void 0,!0)}static inMemory(cwd=process.cwd(),options,entries){return new _SessionManager(cwd,"",void 0,!1,options,entries)}static forkFrom(sourcePath,targetCwd,sessionDir,options){let resolvedSourcePath=resolvePath(sourcePath),resolvedTargetCwd=resolvePath(targetCwd),sourceEntries=loadEntriesFromFile(resolvedSourcePath);if(sourceEntries.length===0)throw new Error(`Cannot fork: source session file is empty or invalid: ${resolvedSourcePath}`);if(!sourceEntries.find(e=>e.type==="session"))throw new Error(`Cannot fork: source session has no header: ${resolvedSourcePath}`);let dir=sessionDir?normalizePath(sessionDir):getDefaultSessionDir(resolvedTargetCwd);existsSync6(dir)||mkdirSync3(dir,{recursive:!0}),options?.id!==void 0&&assertValidSessionId(options.id);let newSessionId=options?.id??createSessionId(),timestamp=new Date().toISOString(),fileTimestamp=timestamp.replace(/[:.]/g,"-"),newSessionFile=join8(dir,`${fileTimestamp}_${newSessionId}.jsonl`);writeFileSync3(newSessionFile,`${JSON.stringify({type:"session",version:CURRENT_SESSION_VERSION,id:newSessionId,timestamp,cwd:resolvedTargetCwd,parentSession:resolvedSourcePath})}
549
549
  `,{flag:"wx"});for(let entry of sourceEntries)entry.type!=="session"&&appendFileSync(newSessionFile,`${JSON.stringify(entry)}
@@ -104,7 +104,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
104
104
  `).map(segment=>applyText(segment)).join(`
105
105
  `);for(let token of tokens)switch(token.type){case"latex":{let latexToken=token,rendered=!latexToken.pending&&this.options.renderLatex!==!1?renderLatex(latexToken.text)??latexToken.raw:latexToken.raw;result+=applyTextWithNewlines(rendered);break}case"escape":result+=applyTextWithNewlines(this.options.preserveBackslashEscapes?token.raw:token.text);break;case"text":token.tokens&&token.tokens.length>0?result+=this.renderInlineTokens(token.tokens,resolvedStyleContext):result+=applyTextWithNewlines(token.text);break;case"paragraph":result+=this.renderInlineTokens(token.tokens||[],resolvedStyleContext);break;case"strong":{let boldContent=this.renderInlineTokens(token.tokens||[],resolvedStyleContext);result+=this.theme.bold(boldContent)+stylePrefix;break}case"em":{let italicContent=this.renderInlineTokens(token.tokens||[],resolvedStyleContext);result+=this.theme.italic(italicContent)+stylePrefix;break}case"codespan":result+=this.theme.code(token.text)+stylePrefix;break;case"link":{let linkText=this.renderInlineTokens(token.tokens||[],resolvedStyleContext),styledLink=this.theme.link(this.theme.underline(linkText));if(getCapabilities().hyperlinks)result+=hyperlink(styledLink,token.href)+stylePrefix;else{let hrefForComparison=token.href.startsWith("mailto:")?token.href.slice(7):token.href;token.text===token.href||token.text===hrefForComparison?result+=styledLink+stylePrefix:result+=styledLink+this.theme.linkUrl(` (${token.href})`)+stylePrefix}break}case"br":result+=`
106
106
  `;break;case"del":{let delContent=this.renderInlineTokens(token.tokens||[],resolvedStyleContext);result+=this.theme.strikethrough(delContent)+stylePrefix;break}case"html":"raw"in token&&typeof token.raw=="string"&&(result+=applyTextWithNewlines(token.raw));break;default:"text"in token&&typeof token.text=="string"&&(result+=applyTextWithNewlines(token.text))}for(;stylePrefix&&result.endsWith(stylePrefix);)result=result.slice(0,-stylePrefix.length);return result}getOrderedListMarker(item){let match=/^(?: {0,3})(\d{1,9}[.)])[ \t]+/.exec(item.raw);return match?`${match[1]} `:void 0}getUnorderedListMarker(item){let match=/^(?: {0,3})([-+*])(?:[ \t]+|(?=\r?\n|$))/.exec(item.raw);return match?`${match[1]} `:void 0}renderList(token,depth,width,styleContext){let lines=[],indent=" ".repeat(depth),startNumber=typeof token.start=="number"?token.start:1;for(let i=0;i<token.items.length;i++){let item=token.items[i],isLastItem=i===token.items.length-1,bullet=token.ordered?this.options.preserveOrderedListMarkers?this.getOrderedListMarker(item)??`${startNumber+i}. `:`${startNumber+i}. `:this.options.preserveOrderedListMarkers?this.getUnorderedListMarker(item)??"- ":"- ",taskMarker=item.task?`[${item.checked?"x":" "}] `:"",marker=bullet+taskMarker,firstPrefix=indent+this.theme.listBullet(marker),continuationPrefix=indent+" ".repeat(visibleWidth(marker)),itemWidth=Math.max(1,width-visibleWidth(firstPrefix)),renderedAnyLine=!1;for(let itemToken of item.tokens){if(itemToken.type==="list"){lines.push(...this.renderList(itemToken,depth+1,width,styleContext)),renderedAnyLine=!0;continue}let itemLines=this.renderToken(itemToken,itemWidth,void 0,styleContext);for(let line of itemLines)for(let wrappedLine of wrapTextWithAnsi(line,itemWidth)){let linePrefix=renderedAnyLine?continuationPrefix:firstPrefix;lines.push(linePrefix+wrappedLine),renderedAnyLine=!0}}renderedAnyLine||lines.push(firstPrefix),token.loose&&!isLastItem&&lines.push("")}return lines}getLongestWordWidth(text,maxWidth){let words=text.split(/\s+/).filter(word=>word.length>0),longest=0;for(let word of words)longest=Math.max(longest,visibleWidth(word));return maxWidth===void 0?longest:Math.min(longest,maxWidth)}wrapCellText(text,maxWidth,stylePrefix=""){let lines=wrapTextWithAnsi(text,Math.max(1,maxWidth));return lines.map((line,index)=>{let styleReset=index<lines.length-1?"\x1B[22;23;24;25;27;28;29;39m":"";return`${line}${styleReset}${stylePrefix}`})}renderTable(token,availableWidth,nextTokenType,styleContext){let lines=[],numCols=token.header.length;if(numCols===0)return lines;let borderOverhead=3*numCols+1,availableForCells=availableWidth-borderOverhead;if(availableForCells<numCols){let fallbackLines=token.raw?wrapTextWithAnsi(token.raw,availableWidth):[];return nextTokenType&&nextTokenType!=="space"&&fallbackLines.push(""),fallbackLines}let maxUnbrokenWordWidth=30,naturalWidths=[],minWordWidths=[];for(let i=0;i<numCols;i++){let headerText=this.renderInlineTokens(token.header[i].tokens||[],styleContext);naturalWidths[i]=visibleWidth(headerText),minWordWidths[i]=Math.max(1,this.getLongestWordWidth(headerText,maxUnbrokenWordWidth))}for(let row of token.rows)for(let i=0;i<row.length;i++){let cellText=this.renderInlineTokens(row[i].tokens||[],styleContext);naturalWidths[i]=Math.max(naturalWidths[i]||0,visibleWidth(cellText)),minWordWidths[i]=Math.max(minWordWidths[i]||1,this.getLongestWordWidth(cellText,maxUnbrokenWordWidth))}let minColumnWidths=minWordWidths,minCellsWidth=minColumnWidths.reduce((a,b2)=>a+b2,0);if(minCellsWidth>availableForCells){minColumnWidths=new Array(numCols).fill(1);let remaining=availableForCells-numCols;if(remaining>0){let totalWeight=minWordWidths.reduce((total,width)=>total+Math.max(0,width-1),0),growth=minWordWidths.map(width=>{let weight=Math.max(0,width-1);return totalWeight>0?Math.floor(weight/totalWeight*remaining):0});for(let i=0;i<numCols;i++)minColumnWidths[i]+=growth[i]??0;let allocated=growth.reduce((total,width)=>total+width,0),leftover=remaining-allocated;for(let i=0;leftover>0&&i<numCols;i++)minColumnWidths[i]++,leftover--}minCellsWidth=minColumnWidths.reduce((a,b2)=>a+b2,0)}let totalNaturalWidth=naturalWidths.reduce((a,b2)=>a+b2,0)+borderOverhead,columnWidths;if(totalNaturalWidth<=availableWidth)columnWidths=naturalWidths.map((width,index)=>Math.max(width,minColumnWidths[index]));else{let totalGrowPotential=naturalWidths.reduce((total,width,index)=>total+Math.max(0,width-minColumnWidths[index]),0),extraWidth=Math.max(0,availableForCells-minCellsWidth);columnWidths=minColumnWidths.map((minWidth,index)=>{let naturalWidth=naturalWidths[index],minWidthDelta=Math.max(0,naturalWidth-minWidth),grow=0;return totalGrowPotential>0&&(grow=Math.floor(minWidthDelta/totalGrowPotential*extraWidth)),minWidth+grow});let allocated=columnWidths.reduce((a,b2)=>a+b2,0),remaining=availableForCells-allocated;for(;remaining>0;){let grew=!1;for(let i=0;i<numCols&&remaining>0;i++)columnWidths[i]<naturalWidths[i]&&(columnWidths[i]++,remaining--,grew=!0);if(!grew)break}}let topBorderCells=columnWidths.map(w=>"\u2500".repeat(w));lines.push(`\u250C\u2500${topBorderCells.join("\u2500\u252C\u2500")}\u2500\u2510`);let headerCellLines=token.header.map((cell,i)=>{let text=this.renderInlineTokens(cell.tokens||[],styleContext);return this.wrapCellText(text,columnWidths[i],styleContext?.stylePrefix)}),headerLineCount=Math.max(...headerCellLines.map(c2=>c2.length));for(let lineIdx=0;lineIdx<headerLineCount;lineIdx++){let rowParts=headerCellLines.map((cellLines,colIdx)=>{let text=cellLines[lineIdx]||"",padded=text+" ".repeat(Math.max(0,columnWidths[colIdx]-visibleWidth(text)));return this.theme.bold(padded)});lines.push(`\u2502 ${rowParts.join(" \u2502 ")} \u2502`)}let separatorLine=`\u251C\u2500${columnWidths.map(w=>"\u2500".repeat(w)).join("\u2500\u253C\u2500")}\u2500\u2524`;lines.push(separatorLine);for(let rowIndex=0;rowIndex<token.rows.length;rowIndex++){let rowCellLines=token.rows[rowIndex].map((cell,i)=>{let text=this.renderInlineTokens(cell.tokens||[],styleContext);return this.wrapCellText(text,columnWidths[i],styleContext?.stylePrefix)}),rowLineCount=Math.max(...rowCellLines.map(c2=>c2.length));for(let lineIdx=0;lineIdx<rowLineCount;lineIdx++){let rowParts=rowCellLines.map((cellLines,colIdx)=>{let text=cellLines[lineIdx]||"";return text+" ".repeat(Math.max(0,columnWidths[colIdx]-visibleWidth(text)))});lines.push(`\u2502 ${rowParts.join(" \u2502 ")} \u2502`)}rowIndex<token.rows.length-1&&lines.push(separatorLine)}let bottomBorderCells=columnWidths.map(w=>"\u2500".repeat(w));return lines.push(`\u2514\u2500${bottomBorderCells.join("\u2500\u2534\u2500")}\u2500\u2518`),nextTokenType&&nextTokenType!=="space"&&lines.push(""),lines}};var MouseRegion=class{child;onMouse;constructor(child,onMouse){this.child=child,this.onMouse=onMouse}render(width){return this.child.render(width)}handleMouse(event){return dispatchMouseEvent(this.child,event)??this.onMouse(event)}invalidate(){this.child.invalidate()}};var ScrollView=class extends Container{child;followEnd;primary;overscroll;scrollbarTrackStyle;scrollbarThumbStyle;currentScrollbar;scrollbarHideDelayMs;currentScrollTop=0;contentHeight=0;currentViewportHeight=0;followingEnd;followSuppressedAtEnd=!1;requestRenderCallback;transientScrollbarVisible=!1;scrollbarActive=!1;scrollbarHideTimer;constructor(component,options={}){if(super(),options.axis!==void 0&&options.axis!=="vertical")throw new Error(`Unsupported ScrollView axis: ${options.axis}`);this.child=component,this.children.push(component),this.followEnd=(options.follow??"none")==="end",this.followingEnd=this.followEnd,this.primary=options.primary??!1,this.overscroll=options.overscroll??"chain",this.currentScrollbar=options.scrollbar??"hidden",this.scrollbarTrackStyle=options.scrollbarTrackStyle??(text=>`\x1B[90m${text}\x1B[39m`),this.scrollbarThumbStyle=options.scrollbarThumbStyle??(text=>`\x1B[37m${text}\x1B[39m`),this.scrollbarHideDelayMs=Math.max(0,Math.floor(options.scrollbarHideDelayMs??1e3))}get scrollTop(){return this.currentScrollTop}get isFollowingEnd(){return this.followingEnd}get viewportHeight(){return this.currentViewportHeight}get scrollbar(){return this.currentScrollbar}get isScrollbarVisible(){return this.scrollbar==="always"?this.currentViewportHeight>0:this.scrollbar==="auto"&&this.contentHeight>this.currentViewportHeight&&this.transientScrollbarVisible}get isScrollbarActive(){return this.scrollbarActive}setScrollbar(scrollbar){scrollbar!==this.currentScrollbar&&(this.currentScrollbar=scrollbar,scrollbar!=="auto"?this.hideTransientScrollbar():this.scrollbarActive&&this.markScrollbarActivity(),this.requestRenderCallback?.())}getContentWidth(width){return this.scrollbar==="always"&&width>1?width-1:width}markScrollbarActivity(){this.scrollbar!=="auto"||this.contentHeight<=this.currentViewportHeight||(this.transientScrollbarVisible=!0,this.scrollbarHideTimer&&(clearTimeout(this.scrollbarHideTimer),this.scrollbarHideTimer=void 0),!this.scrollbarActive&&(this.scrollbarHideTimer=setTimeout(()=>{this.scrollbarHideTimer=void 0,this.transientScrollbarVisible=!1,this.requestRenderCallback?.()},this.scrollbarHideDelayMs),this.scrollbarHideTimer.unref()))}hideTransientScrollbar(){this.transientScrollbarVisible=!1,this.scrollbarHideTimer&&(clearTimeout(this.scrollbarHideTimer),this.scrollbarHideTimer=void 0)}setScrollbarActive(active){active!==this.scrollbarActive&&(this.scrollbarActive=active,this.markScrollbarActivity(),this.requestRenderCallback?.())}scrollTo(scrollTop,options={}){let requested=Number.isFinite(scrollTop)?Math.trunc(scrollTop):this.currentScrollTop,maxScrollTop=Math.max(0,this.contentHeight-this.currentViewportHeight),next=Math.max(0,Math.min(maxScrollTop,requested)),nextFollowSuppressedAtEnd=options.disableFollow===!0&&next===maxScrollTop,nextFollowingEnd=!nextFollowSuppressedAtEnd&&this.followEnd&&next===maxScrollTop;if(next===this.currentScrollTop&&nextFollowingEnd===this.followingEnd&&nextFollowSuppressedAtEnd===this.followSuppressedAtEnd)return;let moved=next!==this.currentScrollTop;this.currentScrollTop=next,this.followingEnd=nextFollowingEnd,this.followSuppressedAtEnd=nextFollowSuppressedAtEnd,moved&&this.markScrollbarActivity(),this.requestRenderCallback?.()}scrollBy(lines){let requested=Number.isFinite(lines)?Math.trunc(lines):0;if(requested===0)return 0;let maxScrollTop=Math.max(0,this.contentHeight-this.currentViewportHeight),start=this.followingEnd?maxScrollTop:this.currentScrollTop,next=Math.max(0,Math.min(maxScrollTop,start+requested)),moved=next-start,wasFollowingEnd=this.followingEnd;return this.currentScrollTop=next,this.followingEnd=this.followEnd&&next===maxScrollTop,this.followSuppressedAtEnd=!1,moved!==0&&this.markScrollbarActivity(),(moved!==0||this.followingEnd!==wasFollowingEnd)&&this.requestRenderCallback?.(),requested-moved}scrollToStart(){let changed=this.currentScrollTop!==0||this.followingEnd!==(this.followEnd&&this.contentHeight<=this.currentViewportHeight);this.currentScrollTop=0,this.followingEnd=this.followEnd&&this.contentHeight<=this.currentViewportHeight,this.followSuppressedAtEnd=!1,changed&&(this.markScrollbarActivity(),this.requestRenderCallback?.())}scrollToEnd(){let next=Math.max(0,this.contentHeight-this.currentViewportHeight),changed=this.currentScrollTop!==next||this.followingEnd!==this.followEnd;this.currentScrollTop=next,this.followingEnd=this.followEnd,this.followSuppressedAtEnd=!1,changed&&(this.markScrollbarActivity(),this.requestRenderCallback?.())}updateLayout(contentHeight,viewportHeight,requestRender){this.contentHeight=Math.max(0,Math.floor(contentHeight)),this.currentViewportHeight=Math.max(0,Math.floor(viewportHeight)),this.requestRenderCallback=requestRender;let maxScrollTop=Math.max(0,this.contentHeight-this.currentViewportHeight);this.followingEnd?this.currentScrollTop=maxScrollTop:this.currentScrollTop=Math.max(0,Math.min(this.currentScrollTop,maxScrollTop)),this.currentScrollTop<maxScrollTop&&(this.followSuppressedAtEnd=!1),this.followEnd&&this.currentScrollTop===maxScrollTop&&!this.followSuppressedAtEnd&&(this.followingEnd=!0),this.contentHeight<=this.currentViewportHeight&&this.hideTransientScrollbar()}addChild(_component){throw new Error("ScrollView has exactly one child")}removeChild(_component){throw new Error("ScrollView child cannot be removed")}clear(){throw new Error("ScrollView child cannot be cleared")}render(width){let contentWidth=this.getContentWidth(width),lines=this.child.render(contentWidth);return contentWidth===width?lines:lines.map(line=>`${line} `)}[LAYOUT_NODE](){return{type:"scroll",component:this.child,state:this}}};var SettingsList=class{items;filteredItems;theme;selectedIndex=0;mousePressedIndex;maxVisible;onChange;onCancel;searchInput;searchEnabled;submenuComponent=null;submenuItemIndex=null;navigateAfterClose=null;constructor(items,maxVisible,theme2,onChange,onCancel,options={}){this.items=items,this.filteredItems=items,this.maxVisible=maxVisible,this.theme=theme2,this.onChange=onChange,this.onCancel=onCancel,this.searchEnabled=options.enableSearch??!1,this.searchEnabled&&(this.searchInput=new Input)}updateValue(id,newValue){let item=this.items.find(i=>i.id===id);item&&(item.currentValue=newValue)}selectItem(id){let index=(this.searchEnabled?this.filteredItems:this.items).findIndex(i=>i.id===id);index!==-1&&(this.selectedIndex=index)}invalidate(){this.submenuComponent?.invalidate?.()}render(width){return this.submenuComponent?this.submenuComponent.render(width):this.renderMainList(width)}renderMainList(width){let lines=[];if(this.searchEnabled&&this.searchInput&&(lines.push(...this.searchInput.render(width)),lines.push("")),this.items.length===0)return lines.push(this.theme.hint(" No settings available")),this.searchEnabled&&this.addHintLine(lines,width),lines;let displayItems=this.getDisplayItems();if(displayItems.length===0)return lines.push(truncateToWidth(this.theme.hint(" No matching settings"),width)),this.addHintLine(lines,width),lines;let{startIndex,endIndex}=this.getVisibleRange(displayItems),maxLabelWidth=Math.min(36,Math.max(...this.items.map(item=>visibleWidth(item.label))));for(let i=startIndex;i<endIndex;i++){let item=displayItems[i];if(!item)continue;let isSelected=i===this.selectedIndex,prefix=isSelected?this.theme.cursor:" ",prefixWidth=visibleWidth(prefix),labelPadded=item.label+" ".repeat(Math.max(0,maxLabelWidth-visibleWidth(item.label))),labelText=this.theme.label(labelPadded,isSelected),separator=" ",usedWidth=prefixWidth+maxLabelWidth+visibleWidth(separator),valueMaxWidth=width-usedWidth-2,valueText=this.theme.value(truncateToWidth(item.currentValue,valueMaxWidth,""),isSelected);lines.push(truncateToWidth(prefix+labelText+separator+valueText,width))}if(startIndex>0||endIndex<displayItems.length){let scrollText=` (${this.selectedIndex+1}/${displayItems.length})`;lines.push(this.theme.hint(truncateToWidth(scrollText,width-2,"")))}let selectedItem=displayItems[this.selectedIndex];if(selectedItem?.description){lines.push("");let wrappedDesc=wrapTextWithAnsi(selectedItem.description,width-4);for(let line of wrappedDesc)lines.push(this.theme.description(` ${line}`))}return this.addHintLine(lines,width),lines}handleMouse(event){if(this.submenuComponent){let result=this.submenuComponent.handleMouse?.(event);return result?{...result,focus:!0}:void 0}if(this.searchEnabled&&this.searchInput){if(event.y===0){let result=this.searchInput.handleMouse?.(event);return result?{...result,focus:!0}:void 0}if(event.y===1)return}let displayItems=this.getDisplayItems();if(displayItems.length===0)return;if(event.type==="wheel"&&event.wheelDelta){let delta=event.wheelDelta<0?-1:1,previousIndex=this.selectedIndex;return this.selectedIndex=Math.max(0,Math.min(displayItems.length-1,this.selectedIndex+delta)),{handled:!0,render:this.selectedIndex!==previousIndex}}if(event.button!=="left"||event.type!=="press"&&event.type!=="click")return;let rowOffset=this.searchEnabled?2:0,{startIndex,endIndex}=this.getVisibleRange(displayItems),itemIndex=startIndex+event.y-rowOffset;if(!(itemIndex<startIndex||itemIndex>=endIndex)){if(event.type==="press")return this.mousePressedIndex=itemIndex,this.selectedIndex=itemIndex,{handled:!0,focus:!0};if(event.type==="click")return this.selectedIndex=this.mousePressedIndex??itemIndex,this.mousePressedIndex=void 0,this.activateItem(),{handled:!0}}}handleInput(data){if(this.submenuComponent){this.submenuComponent.handleInput?.(data);return}let kb=getKeybindings(),displayItems=this.getDisplayItems();if(kb.matches(data,"tui.select.up")){if(displayItems.length===0)return;this.selectedIndex=this.selectedIndex===0?displayItems.length-1:this.selectedIndex-1}else if(kb.matches(data,"tui.select.down")){if(displayItems.length===0)return;this.selectedIndex=this.selectedIndex===displayItems.length-1?0:this.selectedIndex+1}else kb.matches(data,"tui.select.confirm")||data===" "&&(!this.searchEnabled||this.searchInput?.getValue().length===0)?this.activateItem():kb.matches(data,"tui.select.cancel")?this.onCancel():this.searchEnabled&&this.searchInput&&(this.searchInput.handleInput(data),this.applyFilter(this.searchInput.getValue()))}getDisplayItems(){return this.searchEnabled?this.filteredItems:this.items}getVisibleRange(displayItems){let startIndex=Math.max(0,Math.min(this.selectedIndex-Math.floor(this.maxVisible/2),displayItems.length-this.maxVisible));return{startIndex,endIndex:Math.min(startIndex+this.maxVisible,displayItems.length)}}activateItem(){let item=this.getDisplayItems()[this.selectedIndex];if(item){if(item.submenu)this.submenuItemIndex=this.selectedIndex,this.submenuComponent=item.submenu(item.currentValue,(selectedValue,options)=>{selectedValue!==void 0&&(item.currentValue=selectedValue,this.onChange(item.id,selectedValue)),options?.navigateTo&&(this.navigateAfterClose=options.navigateTo),this.closeSubmenu()});else if(item.values&&item.values.length>0){let nextIndex=(item.values.indexOf(item.currentValue)+1)%item.values.length,newValue=item.values[nextIndex];item.currentValue=newValue,this.onChange(item.id,newValue)}}}closeSubmenu(){if(this.submenuComponent=null,this.navigateAfterClose!==null){let id=this.navigateAfterClose;this.navigateAfterClose=null,this.submenuItemIndex=null,this.selectItem(id),this.activateItem()}else this.submenuItemIndex!==null&&(this.selectedIndex=this.submenuItemIndex,this.submenuItemIndex=null)}applyFilter(query){this.filteredItems=fuzzyFilter(this.items,query,item=>item.label),this.selectedIndex=0}addHintLine(lines,width){lines.push(""),lines.push(truncateToWidth(this.theme.hint(this.searchEnabled?" Type to search \xB7 Enter/Space to change \xB7 Esc to cancel":" Enter/Space to change \xB7 Esc to cancel"),width))}};var Spacer=class{lines;constructor(lines=1){this.lines=lines}setLines(lines){this.lines=lines}invalidate(){}render(_width){let result=[];for(let i=0;i<this.lines;i++)result.push("");return result}};var TruncatedText=class{text;paddingX;paddingY;constructor(text,paddingX=0,paddingY=0){this.text=text,this.paddingX=paddingX,this.paddingY=paddingY}invalidate(){}render(width){let result=[],emptyLine=" ".repeat(width);for(let i=0;i<this.paddingY;i++)result.push(emptyLine);let availableWidth=Math.max(1,width-this.paddingX*2),singleLineText=this.text,newlineIndex=this.text.indexOf(`
107
- `);newlineIndex!==-1&&(singleLineText=this.text.substring(0,newlineIndex));let displayText=truncateToWidth(singleLineText,availableWidth),leftPadding=" ".repeat(this.paddingX),rightPadding=" ".repeat(this.paddingX),lineWithPadding=leftPadding+displayText+rightPadding,lineVisibleWidth=visibleWidth(lineWithPadding),paddingNeeded=Math.max(0,width-lineVisibleWidth),finalLine=lineWithPadding+" ".repeat(paddingNeeded);result.push(finalLine);for(let i=0;i<this.paddingY;i++)result.push(emptyLine);return result}};var VStack=class extends Stack{layoutType="vstack";constructor(children=[],options={}){super(children,options)}render(width){let viewport={width:Math.max(1,width),height:Number.MAX_SAFE_INTEGER},entries=visibleStackEntries(this.entries,viewport),rendered=entries.map(entry=>entry.component.render(viewport.width)),sizes=allocateStackSizes(entries,rendered.map(lines2=>lines2.length),void 0,this.gap),lines=[];for(let index=0;index<entries.length;index++){if(index>0)for(let gap=0;gap<this.gap;gap++)lines.push("");let childLines=rendered[index].slice(0,sizes[index]);lines.push(...childLines);for(let padding=childLines.length;padding<sizes[index];padding++)lines.push("")}return lines}};import{createRequire as createRequire2}from"node:module";import*as path from"node:path";import{createRequire}from"node:module";import{dirname as dirname2,join as join2}from"node:path";import{fileURLToPath}from"node:url";var moduleRequire=createRequire(import.meta.url),TUI_PACKAGE_NAME="@earendil-works/pi-tui";function getNativeModuleCandidates(nativePath,options={}){let moduleDir=dirname2(fileURLToPath(options.moduleUrl??import.meta.url)),candidates=[];try{let packageEntry=(options.resolvePackage??moduleRequire.resolve)(TUI_PACKAGE_NAME);candidates.push(join2(dirname2(packageEntry),"..",nativePath))}catch{}return candidates.push(join2(moduleDir,"..",nativePath),join2(moduleDir,nativePath),join2(dirname2(options.execPath??process.execPath),nativePath)),Array.from(new Set(candidates))}var cjsRequire=createRequire2(import.meta.url),helpers=new Map;function loadNativePlatformHelper(platform,suffix=""){let arch=process.arch;if(arch!=="x64"&&arch!=="arm64")return;let nativePath=path.join("native",platform,"prebuilds",`${platform}-${arch}`,`${platform}-platform${suffix}.node`);if(helpers.has(nativePath))return helpers.get(nativePath);for(let modulePath of getNativeModuleCandidates(nativePath))try{let helper=cjsRequire(modulePath);if(typeof helper?.getText=="function"&&typeof helper.getImage=="function")return helpers.set(nativePath,helper),helper}catch{}helpers.set(nativePath,void 0)}function getNativePlatformHelper(){if(!(process.platform!=="darwin"&&process.platform!=="win32"))return loadNativePlatformHelper(process.platform)}function getNativeClipboard(){if(process.platform!=="linux")return getNativePlatformHelper();if(process.env.DISPLAY)return loadNativePlatformHelper("linux","-x11")}var PROGRAM_STATUS_QUERY="\x1B]7501;?\x1B\\";function isProgramStatusReply(sequence){return/^\x1b\]7501;\?[^\x07\x1b]*(?:\x07|\x1b\\)$/.test(sequence)}var APP_PATTERN=/^[A-Za-z0-9_.+-]{1,32}$/,CONTROL_CHARACTERS=/[\u0000-\u001f\u007f-\u009f]+/g,MAX_MESSAGE_BYTES=2048;function truncateUtf8(text,maxBytes){if(Buffer.byteLength(text,"utf8")<=maxBytes)return text;let bytes=0,end=0;for(let char of text){let size=Buffer.byteLength(char,"utf8");if(bytes+size>maxBytes)break;bytes+=size,end+=char.length}return text.slice(0,end)}function formatProgramStatus(status){let pairs=[`state=${status.state}`];status.app!==void 0&&APP_PATTERN.test(status.app)&&pairs.push(`app=${status.app}`),status.state==="blocked"&&status.kind&&pairs.push(`kind=${status.kind}`);let message=truncateUtf8((status.message??"").replace(CONTROL_CHARACTERS," ").trim(),MAX_MESSAGE_BYTES);return message&&pairs.push(`msg=${Buffer.from(message,"utf8").toString("base64")}`),`\x1B]7501;${pairs.join(":")}\x1B\\`}import{EventEmitter}from"events";var ESC="\x1B",DEFAULT_SEQUENCE_TIMEOUT_MS=50,DEFAULT_ESCAPE_TIMEOUT_MS=10,BRACKETED_PASTE_START="\x1B[200~",BRACKETED_PASTE_END="\x1B[201~",TERMINAL_REPLY_HEADER_PATTERN=/^\x1b(?:\](?:1[01];|4;\d{1,3};|7501;\?)|P>\||_G(?:[a-z]=\d+,)*[a-z]=\d+;)/;function isControlString(data){return data.startsWith(`${ESC}]`)||data.startsWith(`${ESC}P`)||data.startsWith(`${ESC}_`)}function isCompleteSequence(data){if(!data.startsWith(ESC))return"not-escape";if(data.length===1)return"incomplete";let afterEsc=data.slice(1);return afterEsc.startsWith("[")?afterEsc.startsWith("[M")?data.length>=6?"complete":"incomplete":isCompleteCsiSequence(data):afterEsc.startsWith("]")?isCompleteOscSequence(data):afterEsc.startsWith("P")?isCompleteDcsSequence(data):afterEsc.startsWith("_")?isCompleteApcSequence(data):afterEsc.startsWith("O")?afterEsc.length>=2?"complete":"incomplete":(afterEsc.length===1,"complete")}function isCompleteCsiSequence(data){if(!data.startsWith(`${ESC}[`))return"complete";if(data.length<3)return"incomplete";let payload=data.slice(2),lastChar=payload[payload.length-1],lastCharCode=lastChar.charCodeAt(0);if(lastCharCode>=64&&lastCharCode<=126){if(payload.startsWith("<")){if(/^<\d+;\d+;\d+[Mm]$/.test(payload))return"complete";if(lastChar==="M"||lastChar==="m"){let parts=payload.slice(1,-1).split(";");if(parts.length===3&&parts.every(p=>/^\d+$/.test(p)))return"complete"}return"incomplete"}return"complete"}return"incomplete"}function isCompleteOscSequence(data){return!data.startsWith(`${ESC}]`)||data.endsWith(`${ESC}\\`)||data.endsWith("\x07")?"complete":"incomplete"}function isCompleteDcsSequence(data){return!data.startsWith(`${ESC}P`)||data.endsWith(`${ESC}\\`)?"complete":"incomplete"}function isCompleteApcSequence(data){return!data.startsWith(`${ESC}_`)||data.endsWith(`${ESC}\\`)?"complete":"incomplete"}function parseUnmodifiedKittyPrintableCodepoint(sequence){let match=sequence.match(/^\x1b\[(\d+)(?::\d*)?(?::\d+)?u$/);if(!match)return;let codepoint=parseInt(match[1],10);return codepoint>=32?codepoint:void 0}function extractCompleteSequences(buffer){let sequences=[],pos=0;for(;pos<buffer.length;){let remaining=buffer.slice(pos);if(remaining.startsWith(ESC)){let terminalReply=isControlString(remaining)&&TERMINAL_REPLY_HEADER_PATTERN.test(remaining),seqEnd=1;for(;seqEnd<=remaining.length;){if(terminalReply&&seqEnd>2){let char=remaining[seqEnd-1];if(char===""||char===""){pos+=seqEnd;break}if(char===ESC&&seqEnd<remaining.length&&remaining[seqEnd]!=="\\"){pos+=seqEnd-1;break}}let candidate=remaining.slice(0,seqEnd),status=isCompleteSequence(candidate);if(status==="complete"){if(candidate==="\x1B\x1B"){let nextChar=remaining[seqEnd];if(nextChar==="["||nextChar==="]"||nextChar==="O"||nextChar==="P"||nextChar==="_"){sequences.push(ESC),pos+=1;break}}sequences.push(candidate),pos+=seqEnd;break}else if(status==="incomplete")seqEnd++;else{sequences.push(candidate),pos+=seqEnd;break}}if(seqEnd>remaining.length)return{sequences,remainder:remaining}}else sequences.push(remaining[0]),pos++}return{sequences,remainder:""}}var StdinBuffer=class extends EventEmitter{buffer="";timeout=null;timeoutMs;escapeTimeoutMs;pasteMode=!1;pasteBuffer="";pendingKittyPrintableCodepoint;constructor(options={}){super(),this.timeoutMs=options.timeout??DEFAULT_SEQUENCE_TIMEOUT_MS,this.escapeTimeoutMs=options.escapeTimeout??DEFAULT_ESCAPE_TIMEOUT_MS}process(data){this.timeout&&(clearTimeout(this.timeout),this.timeout=null);let str;if(Buffer.isBuffer(data))if(data.length===1&&data[0]>127){let byte=data[0]-128;str=`\x1B${String.fromCharCode(byte)}`}else str=data.toString();else str=data;if(str.length===0&&this.buffer.length===0){this.emitDataSequence("");return}if(this.buffer+=str,this.pasteMode){this.pasteBuffer+=this.buffer,this.buffer="";let endIndex=this.pasteBuffer.indexOf(BRACKETED_PASTE_END);if(endIndex!==-1){let pastedContent=this.pasteBuffer.slice(0,endIndex),remaining=this.pasteBuffer.slice(endIndex+BRACKETED_PASTE_END.length);this.pasteMode=!1,this.pasteBuffer="",this.pendingKittyPrintableCodepoint=void 0,this.emit("paste",pastedContent),remaining.length>0&&this.process(remaining)}return}let startIndex=this.buffer.indexOf(BRACKETED_PASTE_START);if(startIndex!==-1){if(startIndex>0){let beforePaste=this.buffer.slice(0,startIndex),result2=extractCompleteSequences(beforePaste);for(let sequence of result2.sequences)this.emitDataSequence(sequence)}this.pendingKittyPrintableCodepoint=void 0,this.buffer=this.buffer.slice(startIndex+BRACKETED_PASTE_START.length),this.pasteMode=!0,this.pasteBuffer=this.buffer,this.buffer="";let endIndex=this.pasteBuffer.indexOf(BRACKETED_PASTE_END);if(endIndex!==-1){let pastedContent=this.pasteBuffer.slice(0,endIndex),remaining=this.pasteBuffer.slice(endIndex+BRACKETED_PASTE_END.length);this.pasteMode=!1,this.pasteBuffer="",this.pendingKittyPrintableCodepoint=void 0,this.emit("paste",pastedContent),remaining.length>0&&this.process(remaining)}return}let result=extractCompleteSequences(this.buffer);this.buffer=result.remainder;for(let sequence of result.sequences)this.emitDataSequence(sequence);if(this.buffer.length>0){if(TERMINAL_REPLY_HEADER_PATTERN.test(this.buffer))return;let timeoutMs=this.buffer===ESC?this.escapeTimeoutMs:this.timeoutMs;this.timeout=setTimeout(()=>{let flushed=this.flush();for(let sequence of flushed)sequence.length>2&&isControlString(sequence)?(this.emitDataSequence(sequence.slice(0,2)),this.process(sequence.slice(2))):this.emitDataSequence(sequence)},timeoutMs)}}emitDataSequence(sequence){let rawCodepoint=sequence.length===1?sequence.codePointAt(0):void 0;if(rawCodepoint!==void 0&&rawCodepoint===this.pendingKittyPrintableCodepoint){this.pendingKittyPrintableCodepoint=void 0;return}this.pendingKittyPrintableCodepoint=parseUnmodifiedKittyPrintableCodepoint(sequence),this.emit("data",sequence)}flush(){if(this.timeout&&(clearTimeout(this.timeout),this.timeout=null),this.buffer.length===0)return[];let sequences=[this.buffer];return this.buffer="",this.pendingKittyPrintableCodepoint=void 0,sequences}clear(){this.timeout&&(clearTimeout(this.timeout),this.timeout=null),this.buffer="",this.pasteMode=!1,this.pasteBuffer="",this.pendingKittyPrintableCodepoint=void 0}getBuffer(){return this.buffer}destroy(){this.clear()}};import*as fs from"node:fs";import*as path2 from"node:path";function isNativeModifierPressed(key){let helper=getNativePlatformHelper();if(!helper?.isModifierPressed)return!1;try{return helper.isModifierPressed(key)===!0}catch{return!1}}var TERMINAL_PROGRESS_KEEPALIVE_MS=1e3,TERMINAL_PROGRESS_ACTIVE_SEQUENCE="\x1B]9;4;3\x07",TERMINAL_PROGRESS_CLEAR_SEQUENCE="\x1B]9;4;0\x07",NATIVE_SHIFT_ENTER_SEQUENCE="\x1B[13;2u",DESIRED_KITTY_KEYBOARD_PROTOCOL_FLAGS=7,KEYBOARD_PROTOCOL_RESPONSE_FRAGMENT_TIMEOUT_MS=150,KITTY_KEYBOARD_PROTOCOL_QUERY=`\x1B[>${DESIRED_KITTY_KEYBOARD_PROTOCOL_FLAGS}u\x1B[?u`,DEVICE_ATTRIBUTES_QUERY="\x1B[c";function parseKeyboardProtocolNegotiationSequence(sequence){let kittyFlags=sequence.match(/^\x1b\[\?(\d+)u$/);if(kittyFlags)return{type:"kitty-flags",flags:Number.parseInt(kittyFlags[1],10)};if(/^\x1b\[\?[\d;]*c$/.test(sequence))return{type:"device-attributes"}}function isKeyboardProtocolNegotiationSequencePrefix(sequence){return sequence==="\x1B["||/^\x1b\[\?[\d;]*$/.test(sequence)}function isAppleTerminalSession(){return process.platform==="darwin"&&process.env.TERM_PROGRAM==="Apple_Terminal"}function refreshTerminalDimensions(){if(!(process.platform==="win32"||process.pid<=0))try{process.kill(process.pid,"SIGWINCH")}catch{}}function normalizeNativeShiftEnterInput(data,shouldDetectNativeShiftEnter,isShiftPressed){return shouldDetectNativeShiftEnter&&data==="\r"&&isShiftPressed?NATIVE_SHIFT_ENTER_SEQUENCE:data}var DEFAULT_ESCAPE_TIMEOUT_MS2=10,DEFAULT_SSH_ESCAPE_TIMEOUT_MS=100;function resolveEscapeTimeoutMs(env=process.env){let configured=Number(env.PINK_TUI_ESC_TIMEOUT);return Number.isFinite(configured)&&configured>0?configured:env.SSH_CONNECTION||env.SSH_TTY?DEFAULT_SSH_ESCAPE_TIMEOUT_MS:DEFAULT_ESCAPE_TIMEOUT_MS2}var ProcessTerminal=class{wasRaw=!1;inputHandler;resizeHandler;_kittyProtocolActive=!1;_modifyOtherKeysActive=!1;keyboardProtocolPushed=!1;pendingKeyboardProtocolDeviceAttributes=0;keyboardProtocolNegotiationBuffer="";keyboardProtocolBufferFlushTimer;stdinBuffer;stdinDataHandler;progressInterval;programStatus;programStatusSupported=!1;programStatusQueryPending=!1;writeLogPath=(()=>{let env=process.env.PINK_TUI_WRITE_LOG||"";if(!env)return"";try{if(fs.statSync(env).isDirectory()){let now=new Date,ts=`${now.getFullYear()}-${String(now.getMonth()+1).padStart(2,"0")}-${String(now.getDate()).padStart(2,"0")}_${String(now.getHours()).padStart(2,"0")}-${String(now.getMinutes()).padStart(2,"0")}-${String(now.getSeconds()).padStart(2,"0")}`;return path2.join(env,`tui-${ts}-${process.pid}.log`)}}catch{}return env})();get kittyProtocolActive(){return this._kittyProtocolActive}get modifyOtherKeysActive(){return this._modifyOtherKeysActive}start(onInput,onResize){globalThis.__pinkReassertInput=()=>{if(!process.stdin.isTTY||!process.stdin.isRaw)return!1;process.stdin.setRawMode(!1),process.stdin.setRawMode(!0),this.enableWindowsVTInput();return!0};this.inputHandler=onInput,this.resizeHandler=onResize,this.wasRaw=process.stdin.isRaw||!1,process.stdin.setRawMode&&process.stdin.setRawMode(!0),process.stdin.setEncoding("utf8"),process.stdin.resume(),process.stdout.write("\x1B[?2004h"),process.stdout.on("resize",this.resizeHandler),refreshTerminalDimensions(),this.enableWindowsVTInput(),this.queryAndEnableKittyProtocol()}setupStdinBuffer(){this.stdinBuffer=new StdinBuffer({escapeTimeout:resolveEscapeTimeoutMs()}),this.stdinBuffer.on("data",sequence=>{if(isProgramStatusReply(sequence)){this.programStatusQueryPending&&(this.programStatusQueryPending=!1,this.programStatusSupported=!0,this.writeProgramStatus());return}let negotiation=this.readKeyboardProtocolNegotiationSequence(sequence);if(negotiation==="pending"){this.scheduleKeyboardProtocolNegotiationBufferFlush();return}negotiation&&this.handleKeyboardProtocolNegotiationSequence(negotiation.parsed)||this.forwardInputSequence(negotiation?.sequence??sequence)}),this.stdinBuffer.on("paste",content=>{this.inputHandler&&this.inputHandler(`\x1B[200~${content}\x1B[201~`)}),this.stdinDataHandler=data=>{this.stdinBuffer.process(data)}}queryAndEnableKittyProtocol(){this.setupStdinBuffer(),process.stdin.on("data",this.stdinDataHandler),this.keyboardProtocolPushed=!0,this.pendingKeyboardProtocolDeviceAttributes+=1,this.clearKeyboardProtocolNegotiationBuffer();let programStatusOverride=process.env.PINK_PROGRAM_STATUS;this.programStatusSupported=programStatusOverride==="1",this.programStatusQueryPending=programStatusOverride!=="1"&&programStatusOverride!=="0";let programStatusQuery=this.programStatusQueryPending?PROGRAM_STATUS_QUERY:"";process.stdout.write(`${KITTY_KEYBOARD_PROTOCOL_QUERY}${programStatusQuery}${DEVICE_ATTRIBUTES_QUERY}`),this.writeProgramStatus()}handleKeyboardProtocolNegotiationSequence(negotiationSequence){if(this.clearKeyboardProtocolNegotiationBuffer(),negotiationSequence.type==="device-attributes"){if(this.pendingKeyboardProtocolDeviceAttributes===0)return!1;this.pendingKeyboardProtocolDeviceAttributes-=1,this.pendingKeyboardProtocolDeviceAttributes===0&&(this.programStatusQueryPending=!1)}return negotiationSequence.type==="kitty-flags"?(negotiationSequence.flags!==0?(this.disableModifyOtherKeys(),this._kittyProtocolActive||(this._kittyProtocolActive=!0,setKittyProtocolActive(!0))):this.enableModifyOtherKeys(),!0):(this._kittyProtocolActive||this.enableModifyOtherKeys(),!0)}readKeyboardProtocolNegotiationSequence(sequence){if(this.keyboardProtocolNegotiationBuffer){let bufferedSequence=this.keyboardProtocolNegotiationBuffer+sequence,negotiationSequence2=parseKeyboardProtocolNegotiationSequence(bufferedSequence);if(negotiationSequence2)return this.clearKeyboardProtocolNegotiationBuffer(),{parsed:negotiationSequence2,sequence:bufferedSequence};if(isKeyboardProtocolNegotiationSequencePrefix(bufferedSequence))return this.setKeyboardProtocolNegotiationBuffer(bufferedSequence),"pending";this.flushKeyboardProtocolNegotiationBufferAsInput()}let negotiationSequence=parseKeyboardProtocolNegotiationSequence(sequence);if(negotiationSequence)return{parsed:negotiationSequence,sequence};if(isKeyboardProtocolNegotiationSequencePrefix(sequence))return this.setKeyboardProtocolNegotiationBuffer(sequence),"pending"}setKeyboardProtocolNegotiationBuffer(sequence){this.clearKeyboardProtocolNegotiationBufferFlushTimer(),this.keyboardProtocolNegotiationBuffer=sequence}clearKeyboardProtocolNegotiationBuffer(){this.clearKeyboardProtocolNegotiationBufferFlushTimer(),this.keyboardProtocolNegotiationBuffer=""}flushKeyboardProtocolNegotiationBufferAsInput(){if(!this.keyboardProtocolNegotiationBuffer)return;let sequence=this.keyboardProtocolNegotiationBuffer;this.clearKeyboardProtocolNegotiationBuffer(),this.forwardInputSequence(sequence)}scheduleKeyboardProtocolNegotiationBufferFlush(){!this.keyboardProtocolNegotiationBuffer||this.keyboardProtocolBufferFlushTimer||(this.keyboardProtocolBufferFlushTimer=setTimeout(()=>{this.keyboardProtocolBufferFlushTimer=void 0,this.flushKeyboardProtocolNegotiationBufferAsInput()},KEYBOARD_PROTOCOL_RESPONSE_FRAGMENT_TIMEOUT_MS))}clearKeyboardProtocolNegotiationBufferFlushTimer(){this.keyboardProtocolBufferFlushTimer&&(clearTimeout(this.keyboardProtocolBufferFlushTimer),this.keyboardProtocolBufferFlushTimer=void 0)}forwardInputSequence(sequence){if(!this.inputHandler)return;let shouldDetectNativeShiftEnter=sequence==="\r"&&(isAppleTerminalSession()||process.platform==="win32"),input=normalizeNativeShiftEnterInput(sequence,shouldDetectNativeShiftEnter,shouldDetectNativeShiftEnter&&isNativeModifierPressed("shift"));this.inputHandler(input)}enableModifyOtherKeys(){this._kittyProtocolActive||this._modifyOtherKeysActive||(process.stdout.write("\x1B[>4;2m"),this._modifyOtherKeysActive=!0)}disableModifyOtherKeys(){this._modifyOtherKeysActive&&(process.stdout.write("\x1B[>4;0m"),this._modifyOtherKeysActive=!1)}enableWindowsVTInput(){if(process.platform==="win32")try{getNativePlatformHelper()?.enableVirtualTerminalInput?.()}catch{}}async drainInput(maxMs=1e3,idleMs=50){let shouldDisableKittyProtocol=this.keyboardProtocolPushed||this._kittyProtocolActive;this.clearKeyboardProtocolNegotiationBuffer(),shouldDisableKittyProtocol&&(process.stdout.write("\x1B[<u"),this.keyboardProtocolPushed=!1,this._kittyProtocolActive=!1,setKittyProtocolActive(!1)),this.disableModifyOtherKeys();let previousHandler=this.inputHandler;this.inputHandler=void 0;let lastDataTime=Date.now(),onData=()=>{lastDataTime=Date.now()};process.stdin.on("data",onData);let endTime=Date.now()+maxMs;try{for(;;){let now=Date.now(),timeLeft=endTime-now;if(timeLeft<=0||now-lastDataTime>=idleMs)break;await new Promise(resolve=>setTimeout(resolve,Math.min(idleMs,timeLeft)))}}finally{process.stdin.removeListener("data",onData),this.inputHandler=previousHandler}}stop(){this.clearProgressInterval()&&process.stdout.write(TERMINAL_PROGRESS_CLEAR_SEQUENCE),this.programStatusSupported&&this.programStatus&&process.stdout.write(formatProgramStatus({state:"clear"})),this.programStatusSupported=!1,this.programStatusQueryPending=!1,process.stdout.write("\x1B[?2004l");let shouldDisableKittyProtocol=this.keyboardProtocolPushed||this._kittyProtocolActive;this.clearKeyboardProtocolNegotiationBuffer(),shouldDisableKittyProtocol&&(process.stdout.write("\x1B[<u"),this.keyboardProtocolPushed=!1,this._kittyProtocolActive=!1,setKittyProtocolActive(!1)),this.disableModifyOtherKeys(),this.stdinBuffer&&(this.stdinBuffer.destroy(),this.stdinBuffer=void 0),this.stdinDataHandler&&(process.stdin.removeListener("data",this.stdinDataHandler),this.stdinDataHandler=void 0),this.inputHandler=void 0,this.resizeHandler&&(process.stdout.removeListener("resize",this.resizeHandler),this.resizeHandler=void 0),process.stdin.pause(),process.stdin.setRawMode&&process.stdin.setRawMode(this.wasRaw)}restoreOnExit(before,after){let sequence=before;this.progressInterval&&(sequence+=TERMINAL_PROGRESS_CLEAR_SEQUENCE),sequence+="\x1B[?2004l",(this.keyboardProtocolPushed||this._kittyProtocolActive)&&(sequence+="\x1B[<u"),this._modifyOtherKeysActive&&(sequence+="\x1B[>4;0m"),sequence+=after;try{fs.writeSync(process.stdout.fd,sequence)}catch{}}write(data){if(process.stdout.write(data),this.writeLogPath)try{fs.appendFileSync(this.writeLogPath,data,{encoding:"utf8"})}catch{}}get columns(){return process.stdout.columns||Number(process.env.COLUMNS)||80}get rows(){return process.stdout.rows||Number(process.env.LINES)||24}moveBy(lines){lines>0?process.stdout.write(`\x1B[${lines}B`):lines<0&&process.stdout.write(`\x1B[${-lines}A`)}hideCursor(){process.stdout.write("\x1B[?25l")}showCursor(){process.stdout.write("\x1B[?25h")}clearLine(){process.stdout.write("\x1B[K")}clearFromCursor(){process.stdout.write("\x1B[J")}clearScreen(){process.stdout.write("\x1B[2J\x1B[H")}setTitle(title){process.stdout.write(`\x1B]0;${title}\x07`)}setProgramStatus(status){this.programStatus=status.state==="clear"?void 0:status,this.programStatusSupported&&process.stdout.write(formatProgramStatus(status))}writeProgramStatus(){this.programStatusSupported&&this.programStatus&&process.stdout.write(formatProgramStatus(this.programStatus))}setProgress(active){active?(process.stdout.write(TERMINAL_PROGRESS_ACTIVE_SEQUENCE),this.progressInterval||(this.progressInterval=setInterval(()=>{process.stdout.write(TERMINAL_PROGRESS_ACTIVE_SEQUENCE)},TERMINAL_PROGRESS_KEEPALIVE_MS))):(this.clearProgressInterval(),process.stdout.write(TERMINAL_PROGRESS_CLEAR_SEQUENCE))}clearProgressInterval(){return this.progressInterval?(clearInterval(this.progressInterval),this.progressInterval=void 0,!0):!1}};var segmenter2=getGraphemeSegmenter(),PRINTABLE_ASCII=/^[\x20-\x7e]*$/;function buildSearchCorpus(lines){let chunks=[],spans=[],textLength=0,pendingSeparator=!1,appendSeparator=()=>{pendingSeparator&&(chunks.push(" "),textLength+=1,pendingSeparator=!1)};for(let row=0;row<lines.length;row++){let line=stripTerminalSequences(lines[row]??""),column=0;if(PRINTABLE_ASCII.test(line)){let index=0;for(;index<line.length;){if(line.charCodeAt(index)===32){textLength>0&&(pendingSeparator=!0),column+=1,index+=1;continue}let end=index+1;for(;end<line.length&&line.charCodeAt(end)!==32;)end+=1;appendSeparator();let text=line.slice(index,end);chunks.push(text),spans.push({textStart:textLength,textEnd:textLength+text.length,row,startCol:column,endCol:column+text.length,linearColumns:!0}),textLength+=text.length,column+=text.length,index=end}}else for(let grapheme of segmenter2.segment(line)){let text=grapheme.segment,width=visibleWidth(text);if(/^\s+$/u.test(text)){textLength>0&&(pendingSeparator=!0),column+=width;continue}appendSeparator(),chunks.push(text),spans.push({textStart:textLength,textEnd:textLength+text.length,row,startCol:column,endCol:column+width,linearColumns:!1}),textLength+=text.length,column+=width}textLength>0&&(pendingSeparator=!0)}return{text:chunks.join(""),spans}}function normalizeQuery(query){return query.replace(/\s+/gu," ").trim()}function escapeRegExp(text){return text.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function findSearchCorpusMatches(corpus,normalizedQuery){if(!normalizedQuery)return[];let expression=new RegExp(escapeRegExp(normalizedQuery),"giu"),matches=[],spanIndex=0;for(let match of corpus.text.matchAll(expression)){let start=match.index,end=start+match[0].length;for(;spanIndex<corpus.spans.length&&corpus.spans[spanIndex].textEnd<=start;)spanIndex+=1;let segments=[];for(let index=spanIndex;index<corpus.spans.length;index++){let span=corpus.spans[index];if(span.textStart>=end)break;if(span.textEnd<=start)continue;let startCol=span.linearColumns?span.startCol+Math.max(start,span.textStart)-span.textStart:span.startCol,endCol=span.linearColumns?span.startCol+Math.min(end,span.textEnd)-span.textStart:span.endCol,previous=segments[segments.length-1];previous&&previous.row===span.row&&startCol<=previous.endCol?previous.endCol=Math.max(previous.endCol,endCol):segments.push({row:span.row,startCol,endCol})}for(;spanIndex<corpus.spans.length&&corpus.spans[spanIndex].textEnd<=end;)spanIndex+=1;segments.length>0&&matches.push({segments})}return matches}var AltScreenSearchIndex=class{sourceLines;corpus;normalizedQuery;matches=[];search(lines,query){let sourceChanged=this.sourceLines?.length!==lines.length;if(!sourceChanged&&this.sourceLines){for(let index=0;index<lines.length;index++)if(this.sourceLines[index]!==lines[index]){sourceChanged=!0;break}}(sourceChanged||!this.corpus)&&(this.sourceLines=Array.from(lines),this.corpus=buildSearchCorpus(lines));let normalizedQuery=normalizeQuery(query),changed=sourceChanged||normalizedQuery!==this.normalizedQuery;return changed&&(this.normalizedQuery=normalizedQuery,this.matches=findSearchCorpusMatches(this.corpus,normalizedQuery)),{matches:this.matches,changed}}};function getAltScreenSearchMatchKey(match){let first=match.segments[0],last=match.segments[match.segments.length-1];return first&&last?`${first.row}:${first.startCol}:${last.row}:${last.endCol}`:""}var AltScreenSearchComponent=class{input=new Input({prompt:" ",placeholder:"Find in transcript",placeholderStyle:text=>`\x1B[2m${text}\x1B[22m`});onQueryChange;navigationButtonStyle;resultCount=0;resultIndex=-1;previousButtonStart=-1;previousButtonEnd=-1;nextButtonStart=-1;nextButtonEnd=-1;hoveredNavigationDirection;_focused=!1;constructor(onQueryChange,navigationButtonStyle=text=>text){this.onQueryChange=onQueryChange,this.navigationButtonStyle=navigationButtonStyle}get focused(){return this._focused}set focused(value){this._focused=value,this.input.focused=value}setResult(index,count){this.resultIndex=index,this.resultCount=count}getNavigationDirectionAt(row,column){if(row===2){if(column>=this.previousButtonStart&&column<this.previousButtonEnd)return-1;if(column>=this.nextButtonStart&&column<this.nextButtonEnd)return 1}}setHoveredNavigationDirection(direction){return direction===this.hoveredNavigationDirection?!1:(this.hoveredNavigationDirection=direction,!0)}handleInput(data){let previous=this.input.getValue();this.input.handleInput(data);let query=this.input.getValue();query!==previous&&this.onQueryChange(query)}invalidate(){this.input.invalidate()}render(width){let safeWidth=Math.max(1,width),innerWidth=Math.max(0,safeWidth-2),formatKey=key=>key?key.split("+").map(part=>process.platform==="darwin"&&part.toLowerCase()==="alt"?"Option":part.charAt(0).toUpperCase()+part.slice(1)).join("+"):"Unbound",keybindings=getKeybindings(),previousKey=formatKey(keybindings.getKeys("tui.altScreen.searchPrevious")[0]),nextKey=formatKey(keybindings.getKeys("tui.altScreen.searchNext")[0]),result=this.input.getValue()?this.resultCount===0?"No matches":`${this.resultIndex+1}/${this.resultCount}`:"",resultSpace=Math.max(0,innerWidth-3),visibleResult=truncateToWidth(result,resultSpace,""),resultText=visibleResult?`\x1B[2m ${visibleResult} \x1B[22m`:"",inputWidth=Math.max(0,innerWidth-visibleWidth(resultText)),inputLine=truncateToWidth(this.input.render(Math.max(1,inputWidth))[0]??"",inputWidth,""),inputPadding=" ".repeat(Math.max(0,inputWidth-visibleWidth(inputLine))),content=`${inputLine}${inputPadding}${resultText}`,previousButton=`\u2191 ${previousKey}`,nextButton=`\u2193 ${nextKey}`,separator=" \xB7 ",outerGapWidth=1,availableControlsWidth=Math.max(0,innerWidth-outerGapWidth*2-1),controlsWidth=visibleWidth(previousButton)+visibleWidth(separator)+visibleWidth(nextButton);controlsWidth>availableControlsWidth&&(previousButton="\u2191",nextButton="\u2193",separator=" ",controlsWidth=visibleWidth(previousButton)+visibleWidth(separator)+visibleWidth(nextButton));let showButtons=controlsWidth<=availableControlsWidth,renderedButtons=showButtons?this.navigationButtonStyle(previousButton,this.hoveredNavigationDirection===-1)+separator+this.navigationButtonStyle(nextButton,this.hoveredNavigationDirection===1):"",outerGapsWidth=showButtons?outerGapWidth*2:0,rightRuleWidth=renderedButtons&&innerWidth>controlsWidth+outerGapsWidth?1:0,leftRuleWidth=Math.max(0,innerWidth-(showButtons?controlsWidth:0)-outerGapsWidth-rightRuleWidth),previousStart=1+leftRuleWidth+outerGapWidth;return this.previousButtonStart=showButtons?previousStart:-1,this.previousButtonEnd=showButtons?previousStart+visibleWidth(previousButton):-1,this.nextButtonStart=showButtons?this.previousButtonEnd+visibleWidth(separator):-1,this.nextButtonEnd=showButtons?this.nextButtonStart+visibleWidth(nextButton):-1,safeWidth===1?["\u250C","\u2502","\u2514"]:[`\u250C${"\u2500".repeat(innerWidth)}\u2510`,`\u2502${content}\u2502`,`\u2514${"\u2500".repeat(leftRuleWidth)}${renderedButtons?" ":""}${renderedButtons}${renderedButtons?" ":""}${"\u2500".repeat(rightRuleWidth)}\u2518`]}};var DEFAULT_DURATION_MS=1e3,AltScreenFlashContainer=class{entries=[];nextId=0;requestRender;constructor(requestRender){this.requestRender=requestRender}flash(message,durationMs=DEFAULT_DURATION_MS){let id=this.nextId++,timer=setTimeout(()=>{let index=this.entries.findIndex(entry=>entry.id===id);index!==-1&&(this.entries.splice(index,1),this.requestRender())},Math.max(0,durationMs));timer.unref(),this.entries.push({id,message,timer}),this.requestRender()}dispose(){for(let entry of this.entries)clearTimeout(entry.timer);this.entries.length=0}invalidate(){}render(width){return this.entries.map(entry=>`\x1B[7m${truncateToWidth(` ${entry.message} `,width,"")}\x1B[27m`)}};var OSC133_ZONE_PREFIX=/^(?:\x1b\]133;[ABC](?:\x07|\x1b\\))+/;function intersect(a,b2){let x2=Math.max(a.x,b2.x),y2=Math.max(a.y,b2.y),right=Math.min(a.x+a.width,b2.x+b2.width),bottom=Math.min(a.y+a.height,b2.y+b2.height);return{x:x2,y:y2,width:Math.max(0,right-x2),height:Math.max(0,bottom-y2)}}function renderCached(context,component,width){let safeWidth=Math.max(1,Math.floor(width)),widths=context.renderCache.get(component);widths||(widths=new Map,context.renderCache.set(component,widths));let lines=widths.get(safeWidth);return lines||(lines=component.render(safeWidth),widths.set(safeWidth,lines)),lines}function measureHeight(context,component,width){return renderCached(context,component,width).length}function measureWidth(context,component,width){return renderCached(context,component,width).reduce((max,line)=>Math.max(max,visibleWidth(line)),0)}function withParent(box,parent){return box.parent=parent,box}function translateBox(box,deltaY){box.rect.y+=deltaY;for(let child of box.children)translateBox(child,deltaY)}function updateClips(box,parentClip){box.clip=intersect(parentClip,box.rect);for(let child of box.children)updateClips(child,box.clip)}function layoutComponent(context,component,x2,y2,width,height,clip){let safeWidth=Math.max(1,Math.floor(width)),node=getLayoutNode(component);if(!node){let lines=renderCached(context,component,safeWidth),allocatedHeight2=height===void 0?lines.length:Math.max(0,Math.floor(height)),lineOffset=0;if(lines.length>allocatedHeight2&&allocatedHeight2>0){let cursorLine=lines.findIndex(line=>line.includes(CURSOR_MARKER));cursorLine>=allocatedHeight2&&(lineOffset=cursorLine-allocatedHeight2+1)}return{component,rect:{x:x2,y:y2,width:safeWidth,height:allocatedHeight2},clip:intersect(clip,{x:x2,y:y2,width:safeWidth,height:allocatedHeight2}),children:[],lines,lineOffset,layer:0}}if(node.type==="scroll"){let previousScrollTop=node.state.scrollTop,contentWidth=node.state.getContentWidth(safeWidth),childBox=layoutComponent(context,node.component,x2,y2-previousScrollTop,contentWidth,void 0,clip),contentHeight=childBox.rect.height,viewportHeight=height===void 0?contentHeight:Math.max(0,Math.floor(height));node.state.updateLayout(contentHeight,viewportHeight,context.requestRender),translateBox(childBox,previousScrollTop-node.state.scrollTop);let scrollView=node.state;(node.state.primary||!context.primaryScrollView)&&(context.primaryScrollView=scrollView);let rect2={x:x2,y:y2,width:safeWidth,height:viewportHeight},childClip=intersect(clip,rect2),box2={component,rect:rect2,clip:childClip,children:[childBox],scrollView,scrollContentLines:renderCached(context,node.component,contentWidth),layer:0};return childBox.parent=box2,updateClips(childBox,childClip),box2}let entries=visibleStackEntries(node.entries,context.viewport),gapTotal=Math.max(0,entries.length-1)*node.gap;if(node.type==="vstack"){let intrinsicHeights2=entries.map(entry=>typeof entry.basis=="number"?entry.basis:measureHeight(context,entry.component,safeWidth)),sizes=allocateStackSizes(entries,intrinsicHeights2,height,node.gap),naturalHeight=sizes.reduce((sum,size)=>sum+size,0)+gapTotal,allocatedHeight2=height===void 0?naturalHeight:Math.max(0,Math.floor(height)),rect2={x:x2,y:y2,width:safeWidth,height:allocatedHeight2},box2={component,rect:rect2,clip:intersect(clip,rect2),children:[],layer:0},childY=y2;for(let index=0;index<entries.length;index++)box2.children.push(withParent(layoutComponent(context,entries[index].component,x2,childY,safeWidth,sizes[index],box2.clip),box2)),childY+=sizes[index]+node.gap;return box2}let intrinsicWidths=entries.map(entry=>typeof entry.basis=="number"?entry.basis:measureWidth(context,entry.component,safeWidth)),widths=allocateStackSizes(entries,intrinsicWidths,safeWidth,node.gap),intrinsicHeights=entries.map((entry,index)=>measureHeight(context,entry.component,Math.max(1,widths[index]))),allocatedHeight=height===void 0?intrinsicHeights.reduce((max,childHeight)=>Math.max(max,childHeight),0):Math.max(0,height),rect={x:x2,y:y2,width:safeWidth,height:allocatedHeight},box={component,rect,clip:intersect(clip,rect),children:[],layer:0},childX=x2;for(let index=0;index<entries.length;index++){let naturalChildHeight=intrinsicHeights[index],childHeight=node.align==="stretch"?allocatedHeight:Math.min(allocatedHeight,naturalChildHeight),childY=y2;node.align==="center"?childY+=Math.floor((allocatedHeight-childHeight)/2):node.align==="end"&&(childY+=allocatedHeight-childHeight);let childWidth=widths[index];childWidth===0?box.children.push({component:entries[index].component,rect:{x:childX,y:childY,width:0,height:childHeight},clip:{x:childX,y:childY,width:0,height:0},children:[],parent:box,layer:0}):box.children.push(withParent(layoutComponent(context,entries[index].component,childX,childY,childWidth,childHeight,box.clip),box)),childX+=childWidth+node.gap}return box}function replaceScrollbarCell(line,column,totalWidth,replacement,preserveTargetBackground){if(isImageLine(line))return line;let graphemeRange=getGraphemeCellRange(line,column),start=graphemeRange?.start??column,end=graphemeRange?.end??column+1,before=sliceByColumn(line,0,start,!0),target=sliceByColumn(line,start,end-start,!0),after=sliceByColumn(line,end,Math.max(0,totalWidth-end),!0),targetPrefix="",targetIndex=0;for(;targetIndex<target.length;){let ansi=extractAnsiCode(target,targetIndex);if(!ansi)break;targetPrefix+=ansi.code,targetIndex+=ansi.length}let beforePadding=" ".repeat(Math.max(0,start-visibleWidth(before))),cellPaddingBefore=" ".repeat(Math.max(0,column-start)),cellPaddingAfter=" ".repeat(Math.max(0,end-column-1)),targetStyle=`\x1B[0m\x1B]8;;\x07${preserveTargetBackground?getActiveBackgroundAnsi(targetPrefix):""}`;return`${before}${beforePadding}${targetStyle}${cellPaddingBefore}${replacement}${cellPaddingAfter}${after}`}function getScrollbarGeometry(box,includeHiddenAuto=!1){if(!box.scrollView||box.rect.width<=0||box.rect.height<=0)return;let contentHeight=box.children[0]?.rect.height??box.scrollContentLines?.length??0,trackHeight=box.rect.height,canRevealHiddenAuto=includeHiddenAuto&&box.scrollView.scrollbar==="auto"&&contentHeight>trackHeight;if(!box.scrollView.isScrollbarVisible&&!canRevealHiddenAuto)return;let minThumbHeight=Math.min(2,trackHeight),thumbHeight=Math.max(minThumbHeight,Math.min(trackHeight,Math.round(trackHeight*trackHeight/contentHeight))),maxScrollTop=Math.max(0,contentHeight-trackHeight),maxThumbTop=trackHeight-thumbHeight,thumbOffset=maxScrollTop===0?0:Math.round(box.scrollView.scrollTop/maxScrollTop*maxThumbTop),column=box.rect.x+box.rect.width-1;if(!(column<box.clip.x||column>=box.clip.x+box.clip.width))return{column,trackTop:box.rect.y,trackHeight,thumbTop:box.rect.y+thumbOffset,thumbHeight,maxScrollTop}}function paintScrollbar(box,screen,totalWidth){let geometry=getScrollbarGeometry(box);if(!(!geometry||!box.scrollView))for(let offset=0;offset<geometry.trackHeight;offset++){let row=geometry.trackTop+offset;if(row<box.clip.y||row>=box.clip.y+box.clip.height||row<0||row>=screen.length)continue;let replacement=row>=geometry.thumbTop&&row<geometry.thumbTop+geometry.thumbHeight?box.scrollView.scrollbarThumbStyle(box.scrollView.isScrollbarActive?"\u2588":"\u2503"):box.scrollView.scrollbarTrackStyle("\u2502");screen[row]=replaceScrollbarCell(screen[row]??"",geometry.column,totalWidth,replacement,box.scrollView.scrollbar!=="always")}}function paintBox(box,screen,totalWidth){if(box.lines){let offset=box.lineOffset??0,firstRow=Math.max(box.rect.y,box.clip.y,0),lastRow=Math.min(box.rect.y+box.rect.height,box.clip.y+box.clip.height,screen.length);for(let row=firstRow;row<lastRow;row++){let sourceLine=box.lines[offset+row-box.rect.y];if(sourceLine===void 0)continue;let line=sourceLine.replace(OSC133_ZONE_PREFIX,""),imageMetadata=getKittyImageMetadata(line);if(imageMetadata){let clipBottom=Math.min(screen.length,box.clip.y+box.clip.height),visibleRows=Math.min(imageMetadata.rows,clipBottom-row);visibleRows<imageMetadata.rows&&(line=cropKittyImageLine(line,0,visibleRows))}box.rect.x===0&&box.rect.width>=totalWidth&&(isImageLine(line)||!screen[row])?screen[row]=line:screen[row]=compositeTuiLine(screen[row]??"",line,box.rect.x,box.rect.width,totalWidth)}}for(let child of box.children)paintBox(child,screen,totalWidth);if(box.scrollView&&box.scrollContentLines&&box.scrollView.scrollTop>0&&box.rect.height>0)for(let imageRow=box.scrollView.scrollTop-1;imageRow>=0;imageRow--){let imageLine=box.scrollContentLines[imageRow]??"",metadata=getKittyImageMetadata(imageLine);if(metadata){let hiddenRows=box.scrollView.scrollTop-imageRow;if(hiddenRows<metadata.rows){let visibleRows=Math.min(box.rect.height,metadata.rows-hiddenRows),cropped=cropKittyImageLine(imageLine,hiddenRows,visibleRows);box.rect.x===0&&box.rect.width>=totalWidth&&(screen[box.rect.y]=cropped)}break}if(imageLine!=="")break}paintScrollbar(box,screen,totalWidth)}function renderLayoutFrame(root,width,height,requestRender){let safeWidth=Math.max(1,Math.floor(width)),safeHeight=Math.max(1,Math.floor(height)),context={viewport:{width:safeWidth,height:safeHeight},renderCache:new Map,requestRender,primaryScrollView:void 0},rootBox=layoutComponent(context,root,0,0,safeWidth,safeHeight,{x:0,y:0,width:safeWidth,height:safeHeight}),lines=Array.from({length:safeHeight},()=>"");return paintBox(rootBox,lines,safeWidth),{root:rootBox,width:safeWidth,height:safeHeight,lines,...context.primaryScrollView===void 0?{}:{primaryScrollView:context.primaryScrollView}}}function containsPoint(rect,x2,y2){return x2>=rect.x&&x2<rect.x+rect.width&&y2>=rect.y&&y2<rect.y+rect.height}function getLayoutBoxesAt(frame,x2,y2){let result=[],visit=(box,depth)=>{if(containsPoint(box.clip,x2,y2)){result.push({box,depth});for(let child of box.children)visit(child,depth+1)}};return visit(frame.root,0),result.sort((a,b2)=>b2.box.layer-a.box.layer||b2.depth-a.depth),result.map(({box})=>box)}function getScrollViewBox(frame,scrollView){let visit=box=>{if(box.scrollView===scrollView)return box;for(let child of box.children){let match=visit(child);if(match)return match}};return visit(frame.root)}function getScrollViewsAt(frame,x2,y2){let result=[],visit=(box,depth)=>{if(containsPoint(box.clip,x2,y2)){box.scrollView&&containsPoint(box.rect,x2,y2)&&result.push({scrollView:box.scrollView,depth});for(let child of box.children)visit(child,depth+1)}};return visit(frame.root,0),result.sort((a,b2)=>b2.depth-a.depth),result.map(entry=>entry.scrollView)}function terminalAcceleratesWheel(){let env=process.env;return process.platform==="darwin"&&env.SSH_CONNECTION===void 0&&env.SSH_CLIENT===void 0&&env.SSH_TTY===void 0}var WheelScrollAccelerator=class{lines;accelerate;lastTime=Number.NEGATIVE_INFINITY;lastDirection=0;averageGap;carry=0;constructor(lines="auto",accelerate=!terminalAcceleratesWheel()){this.lines=lines,this.accelerate=accelerate}setLines(lines){this.lines=lines,this.reset()}next(direction,now){if(this.lines!=="auto")return Number.isFinite(this.lines)?Math.max(1,Math.floor(this.lines)):1;if(!this.accelerate)return 1;let gap=now-this.lastTime,sameGesture=direction===this.lastDirection&&gap<=200;if(this.lastTime=now,this.lastDirection=direction,!sameGesture)return this.averageGap=void 0,this.carry=0,1;if(gap<5)return 1;this.averageGap=this.averageGap===void 0?gap:(this.averageGap+gap)/2;let lines=Math.min(6,Math.max(1,100/this.averageGap))+this.carry,whole=Math.floor(lines);return this.carry=lines-whole,whole}reset(){this.lastTime=Number.NEGATIVE_INFINITY,this.lastDirection=0,this.averageGap=void 0,this.carry=0}};var ENTER_ALT_SCREEN="\x1B[?1049h",EXIT_ALT_SCREEN="\x1B[?1049l",DISABLE_AUTOWRAP="\x1B[?7l",ENABLE_AUTOWRAP="\x1B[?7h",ENABLE_BUTTON_MOTION_MOUSE="\x1B[?1000h\x1B[?1002h\x1B[?1004h\x1B[?1006h",ENABLE_ALL_MOTION_MOUSE="\x1B[?1000h\x1B[?1002h\x1B[?1003h\x1B[?1004h\x1B[?1006h",DISABLE_MOUSE="\x1B[?1006l\x1B[?1004l\x1B[?1003l\x1B[?1002l\x1B[?1000l",FOCUS_IN="\x1B[I",FOCUS_OUT="\x1B[O",BEGIN_SYNCHRONIZED_OUTPUT="\x1B[?2026h",END_SYNCHRONIZED_OUTPUT="\x1B[?2026l",OSC133_ZONE_PREFIX2=/^(?:\x1b\]133;[ABC](?:\x07|\x1b\\))+/,OSC133_PROMPT_START=/^\x1b\]133;A(?:\x07|\x1b\\)/,PAGE_SCROLL_OVERLAP=4,ALT_WHEEL_SCROLL_MULTIPLIER=5,MAX_CACHED_OFFSCREEN_KITTY_IMAGES=16,MAX_CACHED_OFFSCREEN_KITTY_TRANSMISSION_BYTES=32*1024*1024,MAX_CACHED_OFFSCREEN_KITTY_DECODED_BYTES=64*1024*1024,DOUBLE_CLICK_INTERVAL_MS=500,COPY_ERROR_FLASH_DURATION_MS=5e3,TERMINAL_WORD_SELECTION_JOINERS=new Set(["/","-"]),wordSegmenter4=getWordSegmenter(),TuiAltScreen=class extends TuiBase{mode="fullscreen";[VIEWPORT_TUI]=!0;previousScreen=[];lastDocument=[];previousScreenWidth=0;previousScreenHeight=0;layoutRoot;currentLayout;implicitDocument;implicitScrollView;flashes;altScreenActive=!1;imageProtocol=null;savedCapabilities;uploadedKittyImages=new Map;selectionAnchor;selectionFocus;selectionGranularity="character";selectionInitialRange;lastClick;selectionDragPointer;selectionAutoScrollDirection=0;selectionAutoScrollTimer;selectionPressActive=!1;scrollbarDrag;scrollbarHover;scrollToEndIndicatorRect;activeSearch;pressedUrl;selectionDragged=!1;mouseCapture;mousePressTarget;mousePressPoint;mousePressMoved=!1;lastComponentClick;wheelScroll;mouseEnabled;searchMatchStyle;searchCurrentMatchStyle;searchNavigationButtonStyle;scrollToEndIndicator;openUrl;onRightClickPaste;copyOnSelect;copySelection;constructor(terminal,showHardwareCursor,logDirectory,options={}){super(terminal,showHardwareCursor,logDirectory),this.implicitDocument={render:width=>super.render(width),handleMouse:event=>super.handleMouse(event),invalidate:()=>{for(let child of this.children)child.invalidate()}},this.implicitScrollView=new ScrollView(this.implicitDocument,{follow:"end",primary:!0}),this.flashes=new AltScreenFlashContainer(()=>this.requestRender()),this.wheelScroll=new WheelScrollAccelerator(options.wheelScrollLines??1),this.mouseEnabled=options.mouse??!0,this.searchMatchStyle=options.searchMatchStyle??(text=>`\x1B[4m${text}\x1B[24m`),this.searchCurrentMatchStyle=options.searchCurrentMatchStyle??(text=>`\x1B[1;7m${text}\x1B[22;27m`),this.searchNavigationButtonStyle=options.searchNavigationButtonStyle??(text=>text),this.scrollToEndIndicator=options.scrollToEndIndicator,this.openUrl=options.openUrl,this.onRightClickPaste=options.onRightClickPaste,this.copyOnSelect=options.copyOnSelect??!0,this.copySelection=options.copySelection,this.addInputListener(data=>this.handleViewportInput(data))}get viewportTop(){return this.getPrimaryScrollView().scrollTop}get isFollowingOutput(){return this.getPrimaryScrollView().isFollowingEnd}setWheelScrollLines(lines){this.wheelScroll.setLines(lines)}getCopyOnSelect(){return this.copyOnSelect}setCopyOnSelect(enabled){this.copyOnSelect=enabled}hasActiveSelection(){return this.getActiveSelectionText()!==void 0}async copyActiveSelectionToClipboard(){let text=this.getActiveSelectionText();return text?this.copyTextToClipboard(text):!1}resetTextSelection(){this.clearTextSelection(),this.lastClick=void 0}getScreenLines(){return[...this.previousScreen]}setLayoutRoot(component){this.layoutRoot!==component&&(this.layoutRoot=component,this.currentLayout=void 0,this.requestRender())}render(width){return this.layoutRoot?.render(width)??super.render(width)}getMountedRoots(){return this.layoutRoot?[this.layoutRoot]:this.children}getPrimaryScrollView(){return this.currentLayout?.primaryScrollView??this.implicitScrollView}beforeTerminalStart(){this.stopSelectionAutoScroll(),this.selectionPressActive=!1,this.stopScrollbarHover(),this.stopScrollbarDrag(),this.flashes.dispose(),this.altScreenActive=!0;let capabilities=getCapabilities();this.imageProtocol=capabilities.images,this.uploadedKittyImages.clear(),capabilities.images==="iterm2"&&(this.savedCapabilities=capabilities,setCapabilities({...capabilities,images:null}),this.invalidate()),this.lastDocument=[],this.selectionAnchor=void 0,this.selectionFocus=void 0,this.selectionGranularity="character",this.selectionInitialRange=void 0,this.lastClick=void 0,this.pressedUrl=void 0,this.selectionDragged=!1,this.clearComponentMouseGesture(),this.lastComponentClick=void 0,this.resetRenderState();let term=process.env.TERM?.toLowerCase()??"",mouseSequence=process.env.TMUX!==void 0||process.env.ZELLIJ!==void 0||process.env.STY!==void 0||term.startsWith("tmux")||term.startsWith("screen")?ENABLE_BUTTON_MOTION_MOUSE:ENABLE_ALL_MOTION_MOUSE;this.terminal.write(`${ENTER_ALT_SCREEN}${DISABLE_AUTOWRAP}${this.mouseEnabled?mouseSequence:""}\x1B[2J\x1B[H\x1B[?25l`)}beforeTerminalStop(_options){this.closeSearch(),this.stopSelectionAutoScroll(),this.selectionPressActive=!1,this.stopScrollbarHover(),this.stopScrollbarDrag(),this.clearComponentMouseGesture(),this.flashes.dispose(),this.altScreenActive&&(this.terminal.write(`${BEGIN_SYNCHRONIZED_OUTPUT}${this.deleteKittyImages()}${this.mouseEnabled?DISABLE_MOUSE:""}${ENABLE_AUTOWRAP}${END_SYNCHRONIZED_OUTPUT}`),this.uploadedKittyImages.clear())}afterTerminalStop(options){if(this.altScreenActive){if(this.altScreenActive=!1,options.preserveScreen)this.terminal.write(`${BEGIN_SYNCHRONIZED_OUTPUT}${EXIT_ALT_SCREEN}\x1B[?25h${END_SYNCHRONIZED_OUTPUT}`);else{let width=Math.max(1,this.terminal.columns),documentLines=this.resolveFakeCursors(this.render(width)).map(line=>line.replace(OSC133_ZONE_PREFIX2,""));this.lastDocument=this.applyLineResets(documentLines.map(line=>line.replaceAll(CURSOR_MARKER,""))).map(line=>isImageLine(line)||visibleWidth(line)<=width?line:sliceByColumn(line,0,width,!0));let buffer=`${BEGIN_SYNCHRONIZED_OUTPUT}${EXIT_ALT_SCREEN}${DISABLE_AUTOWRAP}`;for(let row=0;row<this.lastDocument.length;row++)row>0&&(buffer+=`\r
107
+ `);newlineIndex!==-1&&(singleLineText=this.text.substring(0,newlineIndex));let displayText=truncateToWidth(singleLineText,availableWidth),leftPadding=" ".repeat(this.paddingX),rightPadding=" ".repeat(this.paddingX),lineWithPadding=leftPadding+displayText+rightPadding,lineVisibleWidth=visibleWidth(lineWithPadding),paddingNeeded=Math.max(0,width-lineVisibleWidth),finalLine=lineWithPadding+" ".repeat(paddingNeeded);result.push(finalLine);for(let i=0;i<this.paddingY;i++)result.push(emptyLine);return result}};var VStack=class extends Stack{layoutType="vstack";constructor(children=[],options={}){super(children,options)}render(width){let viewport={width:Math.max(1,width),height:Number.MAX_SAFE_INTEGER},entries=visibleStackEntries(this.entries,viewport),rendered=entries.map(entry=>entry.component.render(viewport.width)),sizes=allocateStackSizes(entries,rendered.map(lines2=>lines2.length),void 0,this.gap),lines=[];for(let index=0;index<entries.length;index++){if(index>0)for(let gap=0;gap<this.gap;gap++)lines.push("");let childLines=rendered[index].slice(0,sizes[index]);lines.push(...childLines);for(let padding=childLines.length;padding<sizes[index];padding++)lines.push("")}return lines}};import{createRequire as createRequire2}from"node:module";import*as path from"node:path";import{createRequire}from"node:module";import{dirname as dirname2,join as join2}from"node:path";import{fileURLToPath}from"node:url";var moduleRequire=createRequire(import.meta.url),TUI_PACKAGE_NAME="@earendil-works/pi-tui";function getNativeModuleCandidates(nativePath,options={}){let moduleDir=dirname2(fileURLToPath(options.moduleUrl??import.meta.url)),candidates=[];try{let packageEntry=(options.resolvePackage??moduleRequire.resolve)(TUI_PACKAGE_NAME);candidates.push(join2(dirname2(packageEntry),"..",nativePath))}catch{}return candidates.push(join2(moduleDir,"..",nativePath),join2(moduleDir,nativePath),join2(dirname2(options.execPath??process.execPath),nativePath)),Array.from(new Set(candidates))}var cjsRequire=createRequire2(import.meta.url),helpers=new Map;function loadNativePlatformHelper(platform,suffix=""){let arch=process.arch;if(arch!=="x64"&&arch!=="arm64")return;let nativePath=path.join("native",platform,"prebuilds",`${platform}-${arch}`,`${platform}-platform${suffix}.node`);if(helpers.has(nativePath))return helpers.get(nativePath);for(let modulePath of getNativeModuleCandidates(nativePath))try{let helper=cjsRequire(modulePath);if(typeof helper?.getText=="function"&&typeof helper.getImage=="function")return helpers.set(nativePath,helper),helper}catch{}helpers.set(nativePath,void 0)}function getNativePlatformHelper(){if(!(process.platform!=="darwin"&&process.platform!=="win32"))return loadNativePlatformHelper(process.platform)}function getNativeClipboard(){if(process.platform!=="linux")return getNativePlatformHelper();if(process.env.DISPLAY)return loadNativePlatformHelper("linux","-x11")}var PROGRAM_STATUS_QUERY="\x1B]7501;?\x1B\\";function isProgramStatusReply(sequence){return/^\x1b\]7501;\?[^\x07\x1b]*(?:\x07|\x1b\\)$/.test(sequence)}var APP_PATTERN=/^[A-Za-z0-9_.+-]{1,32}$/,CONTROL_CHARACTERS=/[\u0000-\u001f\u007f-\u009f]+/g,MAX_MESSAGE_BYTES=2048;function truncateUtf8(text,maxBytes){if(Buffer.byteLength(text,"utf8")<=maxBytes)return text;let bytes=0,end=0;for(let char of text){let size=Buffer.byteLength(char,"utf8");if(bytes+size>maxBytes)break;bytes+=size,end+=char.length}return text.slice(0,end)}function formatProgramStatus(status){let pairs=[`state=${status.state}`];status.app!==void 0&&APP_PATTERN.test(status.app)&&pairs.push(`app=${status.app}`),status.state==="blocked"&&status.kind&&pairs.push(`kind=${status.kind}`);let message=truncateUtf8((status.message??"").replace(CONTROL_CHARACTERS," ").trim(),MAX_MESSAGE_BYTES);return message&&pairs.push(`msg=${Buffer.from(message,"utf8").toString("base64")}`),`\x1B]7501;${pairs.join(":")}\x1B\\`}import{EventEmitter}from"events";var ESC="\x1B",DEFAULT_SEQUENCE_TIMEOUT_MS=50,DEFAULT_ESCAPE_TIMEOUT_MS=10,BRACKETED_PASTE_START="\x1B[200~",BRACKETED_PASTE_END="\x1B[201~",TERMINAL_REPLY_HEADER_PATTERN=/^\x1b(?:\](?:1[01];|4;\d{1,3};|7501;\?)|P>\||_G(?:[a-z]=\d+,)*[a-z]=\d+;)/;function isControlString(data){return data.startsWith(`${ESC}]`)||data.startsWith(`${ESC}P`)||data.startsWith(`${ESC}_`)}function isCompleteSequence(data){if(!data.startsWith(ESC))return"not-escape";if(data.length===1)return"incomplete";let afterEsc=data.slice(1);return afterEsc.startsWith("[")?afterEsc.startsWith("[M")?data.length>=6?"complete":"incomplete":isCompleteCsiSequence(data):afterEsc.startsWith("]")?isCompleteOscSequence(data):afterEsc.startsWith("P")?isCompleteDcsSequence(data):afterEsc.startsWith("_")?isCompleteApcSequence(data):afterEsc.startsWith("O")?afterEsc.length>=2?"complete":"incomplete":(afterEsc.length===1,"complete")}function isCompleteCsiSequence(data){if(!data.startsWith(`${ESC}[`))return"complete";if(data.length<3)return"incomplete";let payload=data.slice(2),lastChar=payload[payload.length-1],lastCharCode=lastChar.charCodeAt(0);if(lastCharCode>=64&&lastCharCode<=126){if(payload.startsWith("<")){if(/^<\d+;\d+;\d+[Mm]$/.test(payload))return"complete";if(lastChar==="M"||lastChar==="m"){let parts=payload.slice(1,-1).split(";");if(parts.length===3&&parts.every(p=>/^\d+$/.test(p)))return"complete"}return"incomplete"}return"complete"}return"incomplete"}function isCompleteOscSequence(data){return!data.startsWith(`${ESC}]`)||data.endsWith(`${ESC}\\`)||data.endsWith("\x07")?"complete":"incomplete"}function isCompleteDcsSequence(data){return!data.startsWith(`${ESC}P`)||data.endsWith(`${ESC}\\`)?"complete":"incomplete"}function isCompleteApcSequence(data){return!data.startsWith(`${ESC}_`)||data.endsWith(`${ESC}\\`)?"complete":"incomplete"}function parseUnmodifiedKittyPrintableCodepoint(sequence){let match=sequence.match(/^\x1b\[(\d+)(?::\d*)?(?::\d+)?u$/);if(!match)return;let codepoint=parseInt(match[1],10);return codepoint>=32?codepoint:void 0}function extractCompleteSequences(buffer){let sequences=[],pos=0;for(;pos<buffer.length;){let remaining=buffer.slice(pos);if(remaining.startsWith(ESC)){let terminalReply=isControlString(remaining)&&TERMINAL_REPLY_HEADER_PATTERN.test(remaining),seqEnd=1;for(;seqEnd<=remaining.length;){if(terminalReply&&seqEnd>2){let char=remaining[seqEnd-1];if(char===""||char===""){pos+=seqEnd;break}if(char===ESC&&seqEnd<remaining.length&&remaining[seqEnd]!=="\\"){pos+=seqEnd-1;break}}let candidate=remaining.slice(0,seqEnd),status=isCompleteSequence(candidate);if(status==="complete"){if(candidate==="\x1B\x1B"){let nextChar=remaining[seqEnd];if(nextChar==="["||nextChar==="]"||nextChar==="O"||nextChar==="P"||nextChar==="_"){sequences.push(ESC),pos+=1;break}}sequences.push(candidate),pos+=seqEnd;break}else if(status==="incomplete")seqEnd++;else{sequences.push(candidate),pos+=seqEnd;break}}if(seqEnd>remaining.length)return{sequences,remainder:remaining}}else sequences.push(remaining[0]),pos++}return{sequences,remainder:""}}var StdinBuffer=class extends EventEmitter{buffer="";timeout=null;timeoutMs;escapeTimeoutMs;pasteMode=!1;pasteBuffer="";pendingKittyPrintableCodepoint;constructor(options={}){super(),this.timeoutMs=options.timeout??DEFAULT_SEQUENCE_TIMEOUT_MS,this.escapeTimeoutMs=options.escapeTimeout??DEFAULT_ESCAPE_TIMEOUT_MS}process(data){this.timeout&&(clearTimeout(this.timeout),this.timeout=null);let str;if(Buffer.isBuffer(data))if(data.length===1&&data[0]>127){let byte=data[0]-128;str=`\x1B${String.fromCharCode(byte)}`}else str=data.toString();else str=data;if(str.length===0&&this.buffer.length===0){this.emitDataSequence("");return}if(this.buffer+=str,this.pasteMode){this.pasteBuffer+=this.buffer,this.buffer="";let endIndex=this.pasteBuffer.indexOf(BRACKETED_PASTE_END);if(endIndex!==-1){let pastedContent=this.pasteBuffer.slice(0,endIndex),remaining=this.pasteBuffer.slice(endIndex+BRACKETED_PASTE_END.length);this.pasteMode=!1,this.pasteBuffer="",this.pendingKittyPrintableCodepoint=void 0,this.emit("paste",pastedContent),remaining.length>0&&this.process(remaining)}return}let startIndex=this.buffer.indexOf(BRACKETED_PASTE_START);if(startIndex!==-1){if(startIndex>0){let beforePaste=this.buffer.slice(0,startIndex),result2=extractCompleteSequences(beforePaste);for(let sequence of result2.sequences)this.emitDataSequence(sequence)}this.pendingKittyPrintableCodepoint=void 0,this.buffer=this.buffer.slice(startIndex+BRACKETED_PASTE_START.length),this.pasteMode=!0,this.pasteBuffer=this.buffer,this.buffer="";let endIndex=this.pasteBuffer.indexOf(BRACKETED_PASTE_END);if(endIndex!==-1){let pastedContent=this.pasteBuffer.slice(0,endIndex),remaining=this.pasteBuffer.slice(endIndex+BRACKETED_PASTE_END.length);this.pasteMode=!1,this.pasteBuffer="",this.pendingKittyPrintableCodepoint=void 0,this.emit("paste",pastedContent),remaining.length>0&&this.process(remaining)}return}let result=extractCompleteSequences(this.buffer);this.buffer=result.remainder;for(let sequence of result.sequences)this.emitDataSequence(sequence);if(this.buffer.length>0){if(TERMINAL_REPLY_HEADER_PATTERN.test(this.buffer))return;let timeoutMs=this.buffer===ESC?this.escapeTimeoutMs:this.timeoutMs;this.timeout=setTimeout(()=>{let flushed=this.flush();for(let sequence of flushed)sequence.length>2&&isControlString(sequence)?(this.emitDataSequence(sequence.slice(0,2)),this.process(sequence.slice(2))):this.emitDataSequence(sequence)},timeoutMs)}}emitDataSequence(sequence){let rawCodepoint=sequence.length===1?sequence.codePointAt(0):void 0;if(rawCodepoint!==void 0&&rawCodepoint===this.pendingKittyPrintableCodepoint){this.pendingKittyPrintableCodepoint=void 0;return}this.pendingKittyPrintableCodepoint=parseUnmodifiedKittyPrintableCodepoint(sequence),this.emit("data",sequence)}flush(){if(this.timeout&&(clearTimeout(this.timeout),this.timeout=null),this.buffer.length===0)return[];let sequences=[this.buffer];return this.buffer="",this.pendingKittyPrintableCodepoint=void 0,sequences}clear(){this.timeout&&(clearTimeout(this.timeout),this.timeout=null),this.buffer="",this.pasteMode=!1,this.pasteBuffer="",this.pendingKittyPrintableCodepoint=void 0}getBuffer(){return this.buffer}destroy(){this.clear()}};import*as fs from"node:fs";import*as path2 from"node:path";function isNativeModifierPressed(key){let helper=getNativePlatformHelper();if(!helper?.isModifierPressed)return!1;try{return helper.isModifierPressed(key)===!0}catch{return!1}}var TERMINAL_PROGRESS_KEEPALIVE_MS=1e3,TERMINAL_PROGRESS_ACTIVE_SEQUENCE="\x1B]9;4;3\x07",TERMINAL_PROGRESS_CLEAR_SEQUENCE="\x1B]9;4;0\x07",NATIVE_SHIFT_ENTER_SEQUENCE="\x1B[13;2u",DESIRED_KITTY_KEYBOARD_PROTOCOL_FLAGS=7,KEYBOARD_PROTOCOL_RESPONSE_FRAGMENT_TIMEOUT_MS=150,KITTY_KEYBOARD_PROTOCOL_QUERY=`\x1B[>${DESIRED_KITTY_KEYBOARD_PROTOCOL_FLAGS}u\x1B[?u`,DEVICE_ATTRIBUTES_QUERY="\x1B[c";function parseKeyboardProtocolNegotiationSequence(sequence){let kittyFlags=sequence.match(/^\x1b\[\?(\d+)u$/);if(kittyFlags)return{type:"kitty-flags",flags:Number.parseInt(kittyFlags[1],10)};if(/^\x1b\[\?[\d;]*c$/.test(sequence))return{type:"device-attributes"}}function isKeyboardProtocolNegotiationSequencePrefix(sequence){return sequence==="\x1B["||/^\x1b\[\?[\d;]*$/.test(sequence)}function isAppleTerminalSession(){return process.platform==="darwin"&&process.env.TERM_PROGRAM==="Apple_Terminal"}function refreshTerminalDimensions(){if(!(process.platform==="win32"||process.pid<=0))try{process.kill(process.pid,"SIGWINCH")}catch{}}function normalizeNativeShiftEnterInput(data,shouldDetectNativeShiftEnter,isShiftPressed){return shouldDetectNativeShiftEnter&&data==="\r"&&isShiftPressed?NATIVE_SHIFT_ENTER_SEQUENCE:data}var DEFAULT_ESCAPE_TIMEOUT_MS2=10,DEFAULT_SSH_ESCAPE_TIMEOUT_MS=100;function resolveEscapeTimeoutMs(env=process.env){let configured=Number(env.PINK_TUI_ESC_TIMEOUT);return Number.isFinite(configured)&&configured>0?configured:env.SSH_CONNECTION||env.SSH_TTY?DEFAULT_SSH_ESCAPE_TIMEOUT_MS:DEFAULT_ESCAPE_TIMEOUT_MS2}var ProcessTerminal=class{wasRaw=!1;inputHandler;resizeHandler;_kittyProtocolActive=!1;_modifyOtherKeysActive=!1;keyboardProtocolPushed=!1;pendingKeyboardProtocolDeviceAttributes=0;keyboardProtocolNegotiationBuffer="";keyboardProtocolBufferFlushTimer;stdinBuffer;stdinDataHandler;progressInterval;programStatus;programStatusSupported=!1;programStatusQueryPending=!1;writeLogPath=(()=>{let env=process.env.PINK_TUI_WRITE_LOG||"";if(!env)return"";try{if(fs.statSync(env).isDirectory()){let now=new Date,ts=`${now.getFullYear()}-${String(now.getMonth()+1).padStart(2,"0")}-${String(now.getDate()).padStart(2,"0")}_${String(now.getHours()).padStart(2,"0")}-${String(now.getMinutes()).padStart(2,"0")}-${String(now.getSeconds()).padStart(2,"0")}`;return path2.join(env,`tui-${ts}-${process.pid}.log`)}}catch{}return env})();get kittyProtocolActive(){return this._kittyProtocolActive}get modifyOtherKeysActive(){return this._modifyOtherKeysActive}start(onInput,onResize){globalThis.__pinkReassertInput=()=>{if(!process.stdin.isTTY||!process.stdin.isRaw)return!1;process.stdin.setRawMode(!1),process.stdin.setRawMode(!0),this.enableWindowsVTInput();return!0};this.inputHandler=onInput,this.resizeHandler=onResize,this.wasRaw=process.stdin.isRaw||!1,process.stdin.setRawMode&&process.stdin.setRawMode(!0),process.stdin.setEncoding("utf8"),process.stdin.resume(),process.stdout.write("\x1B[?2004h"),process.stdout.on("resize",this.resizeHandler),refreshTerminalDimensions(),this.enableWindowsVTInput(),this.queryAndEnableKittyProtocol()}setupStdinBuffer(){this.stdinBuffer=new StdinBuffer({escapeTimeout:resolveEscapeTimeoutMs()}),this.stdinBuffer.on("data",sequence=>{if(isProgramStatusReply(sequence)){this.programStatusQueryPending&&(this.programStatusQueryPending=!1,this.programStatusSupported=!0,this.writeProgramStatus());return}let negotiation=this.readKeyboardProtocolNegotiationSequence(sequence);if(negotiation==="pending"){this.scheduleKeyboardProtocolNegotiationBufferFlush();return}negotiation&&this.handleKeyboardProtocolNegotiationSequence(negotiation.parsed)||this.forwardInputSequence(negotiation?.sequence??sequence)}),this.stdinBuffer.on("paste",content=>{this.inputHandler&&this.inputHandler(`\x1B[200~${content}\x1B[201~`)}),this.stdinDataHandler=data=>{this.stdinBuffer.process(data)}}queryAndEnableKittyProtocol(){this.setupStdinBuffer(),process.stdin.on("data",this.stdinDataHandler),this.keyboardProtocolPushed=!0,this.pendingKeyboardProtocolDeviceAttributes+=1,this.clearKeyboardProtocolNegotiationBuffer();let programStatusOverride=process.env.PINK_PROGRAM_STATUS;this.programStatusSupported=programStatusOverride==="1",this.programStatusQueryPending=programStatusOverride!=="1"&&programStatusOverride!=="0";let programStatusQuery=this.programStatusQueryPending?PROGRAM_STATUS_QUERY:"";process.stdout.write(`${KITTY_KEYBOARD_PROTOCOL_QUERY}${programStatusQuery}${DEVICE_ATTRIBUTES_QUERY}`),this.writeProgramStatus()}handleKeyboardProtocolNegotiationSequence(negotiationSequence){if(this.clearKeyboardProtocolNegotiationBuffer(),negotiationSequence.type==="device-attributes"){if(this.pendingKeyboardProtocolDeviceAttributes===0)return!1;this.pendingKeyboardProtocolDeviceAttributes-=1,this.pendingKeyboardProtocolDeviceAttributes===0&&(this.programStatusQueryPending=!1)}return negotiationSequence.type==="kitty-flags"?(negotiationSequence.flags!==0?(this.disableModifyOtherKeys(),this._kittyProtocolActive||(this._kittyProtocolActive=!0,setKittyProtocolActive(!0))):this.enableModifyOtherKeys(),!0):(this._kittyProtocolActive||this.enableModifyOtherKeys(),!0)}readKeyboardProtocolNegotiationSequence(sequence){if(this.keyboardProtocolNegotiationBuffer){let bufferedSequence=this.keyboardProtocolNegotiationBuffer+sequence,negotiationSequence2=parseKeyboardProtocolNegotiationSequence(bufferedSequence);if(negotiationSequence2)return this.clearKeyboardProtocolNegotiationBuffer(),{parsed:negotiationSequence2,sequence:bufferedSequence};if(isKeyboardProtocolNegotiationSequencePrefix(bufferedSequence))return this.setKeyboardProtocolNegotiationBuffer(bufferedSequence),"pending";this.flushKeyboardProtocolNegotiationBufferAsInput()}let negotiationSequence=parseKeyboardProtocolNegotiationSequence(sequence);if(negotiationSequence)return{parsed:negotiationSequence,sequence};if(isKeyboardProtocolNegotiationSequencePrefix(sequence))return this.setKeyboardProtocolNegotiationBuffer(sequence),"pending"}setKeyboardProtocolNegotiationBuffer(sequence){this.clearKeyboardProtocolNegotiationBufferFlushTimer(),this.keyboardProtocolNegotiationBuffer=sequence}clearKeyboardProtocolNegotiationBuffer(){this.clearKeyboardProtocolNegotiationBufferFlushTimer(),this.keyboardProtocolNegotiationBuffer=""}flushKeyboardProtocolNegotiationBufferAsInput(){if(!this.keyboardProtocolNegotiationBuffer)return;let sequence=this.keyboardProtocolNegotiationBuffer;this.clearKeyboardProtocolNegotiationBuffer(),this.forwardInputSequence(sequence)}scheduleKeyboardProtocolNegotiationBufferFlush(){!this.keyboardProtocolNegotiationBuffer||this.keyboardProtocolBufferFlushTimer||(this.keyboardProtocolBufferFlushTimer=setTimeout(()=>{this.keyboardProtocolBufferFlushTimer=void 0,this.flushKeyboardProtocolNegotiationBufferAsInput()},KEYBOARD_PROTOCOL_RESPONSE_FRAGMENT_TIMEOUT_MS))}clearKeyboardProtocolNegotiationBufferFlushTimer(){this.keyboardProtocolBufferFlushTimer&&(clearTimeout(this.keyboardProtocolBufferFlushTimer),this.keyboardProtocolBufferFlushTimer=void 0)}forwardInputSequence(sequence){if(!this.inputHandler)return;if(process.platform==="win32"&&(sequence==="\r"||sequence==="\n")&&isNativeModifierPressed("control")){this.inputHandler("\x1b[13;5u");return}let shouldDetectNativeShiftEnter=sequence==="\r"&&(isAppleTerminalSession()||process.platform==="win32"),input=normalizeNativeShiftEnterInput(sequence,shouldDetectNativeShiftEnter,shouldDetectNativeShiftEnter&&isNativeModifierPressed("shift"));this.inputHandler(input)}enableModifyOtherKeys(){this._kittyProtocolActive||this._modifyOtherKeysActive||(process.stdout.write("\x1B[>4;2m"),this._modifyOtherKeysActive=!0)}disableModifyOtherKeys(){this._modifyOtherKeysActive&&(process.stdout.write("\x1B[>4;0m"),this._modifyOtherKeysActive=!1)}enableWindowsVTInput(){if(process.platform==="win32")try{getNativePlatformHelper()?.enableVirtualTerminalInput?.()}catch{}}async drainInput(maxMs=1e3,idleMs=50){let shouldDisableKittyProtocol=this.keyboardProtocolPushed||this._kittyProtocolActive;this.clearKeyboardProtocolNegotiationBuffer(),shouldDisableKittyProtocol&&(process.stdout.write("\x1B[<u"),this.keyboardProtocolPushed=!1,this._kittyProtocolActive=!1,setKittyProtocolActive(!1)),this.disableModifyOtherKeys();let previousHandler=this.inputHandler;this.inputHandler=void 0;let lastDataTime=Date.now(),onData=()=>{lastDataTime=Date.now()};process.stdin.on("data",onData);let endTime=Date.now()+maxMs;try{for(;;){let now=Date.now(),timeLeft=endTime-now;if(timeLeft<=0||now-lastDataTime>=idleMs)break;await new Promise(resolve=>setTimeout(resolve,Math.min(idleMs,timeLeft)))}}finally{process.stdin.removeListener("data",onData),this.inputHandler=previousHandler}}stop(){this.clearProgressInterval()&&process.stdout.write(TERMINAL_PROGRESS_CLEAR_SEQUENCE),this.programStatusSupported&&this.programStatus&&process.stdout.write(formatProgramStatus({state:"clear"})),this.programStatusSupported=!1,this.programStatusQueryPending=!1,process.stdout.write("\x1B[?2004l");let shouldDisableKittyProtocol=this.keyboardProtocolPushed||this._kittyProtocolActive;this.clearKeyboardProtocolNegotiationBuffer(),shouldDisableKittyProtocol&&(process.stdout.write("\x1B[<u"),this.keyboardProtocolPushed=!1,this._kittyProtocolActive=!1,setKittyProtocolActive(!1)),this.disableModifyOtherKeys(),this.stdinBuffer&&(this.stdinBuffer.destroy(),this.stdinBuffer=void 0),this.stdinDataHandler&&(process.stdin.removeListener("data",this.stdinDataHandler),this.stdinDataHandler=void 0),this.inputHandler=void 0,this.resizeHandler&&(process.stdout.removeListener("resize",this.resizeHandler),this.resizeHandler=void 0),process.stdin.pause(),process.stdin.setRawMode&&process.stdin.setRawMode(this.wasRaw)}restoreOnExit(before,after){let sequence=before;this.progressInterval&&(sequence+=TERMINAL_PROGRESS_CLEAR_SEQUENCE),sequence+="\x1B[?2004l",(this.keyboardProtocolPushed||this._kittyProtocolActive)&&(sequence+="\x1B[<u"),this._modifyOtherKeysActive&&(sequence+="\x1B[>4;0m"),sequence+=after;try{fs.writeSync(process.stdout.fd,sequence)}catch{}}write(data){if(process.stdout.write(data),this.writeLogPath)try{fs.appendFileSync(this.writeLogPath,data,{encoding:"utf8"})}catch{}}get columns(){return process.stdout.columns||Number(process.env.COLUMNS)||80}get rows(){return process.stdout.rows||Number(process.env.LINES)||24}moveBy(lines){lines>0?process.stdout.write(`\x1B[${lines}B`):lines<0&&process.stdout.write(`\x1B[${-lines}A`)}hideCursor(){process.stdout.write("\x1B[?25l")}showCursor(){process.stdout.write("\x1B[?25h")}clearLine(){process.stdout.write("\x1B[K")}clearFromCursor(){process.stdout.write("\x1B[J")}clearScreen(){process.stdout.write("\x1B[2J\x1B[H")}setTitle(title){process.stdout.write(`\x1B]0;${title}\x07`)}setProgramStatus(status){this.programStatus=status.state==="clear"?void 0:status,this.programStatusSupported&&process.stdout.write(formatProgramStatus(status))}writeProgramStatus(){this.programStatusSupported&&this.programStatus&&process.stdout.write(formatProgramStatus(this.programStatus))}setProgress(active){active?(process.stdout.write(TERMINAL_PROGRESS_ACTIVE_SEQUENCE),this.progressInterval||(this.progressInterval=setInterval(()=>{process.stdout.write(TERMINAL_PROGRESS_ACTIVE_SEQUENCE)},TERMINAL_PROGRESS_KEEPALIVE_MS))):(this.clearProgressInterval(),process.stdout.write(TERMINAL_PROGRESS_CLEAR_SEQUENCE))}clearProgressInterval(){return this.progressInterval?(clearInterval(this.progressInterval),this.progressInterval=void 0,!0):!1}};var segmenter2=getGraphemeSegmenter(),PRINTABLE_ASCII=/^[\x20-\x7e]*$/;function buildSearchCorpus(lines){let chunks=[],spans=[],textLength=0,pendingSeparator=!1,appendSeparator=()=>{pendingSeparator&&(chunks.push(" "),textLength+=1,pendingSeparator=!1)};for(let row=0;row<lines.length;row++){let line=stripTerminalSequences(lines[row]??""),column=0;if(PRINTABLE_ASCII.test(line)){let index=0;for(;index<line.length;){if(line.charCodeAt(index)===32){textLength>0&&(pendingSeparator=!0),column+=1,index+=1;continue}let end=index+1;for(;end<line.length&&line.charCodeAt(end)!==32;)end+=1;appendSeparator();let text=line.slice(index,end);chunks.push(text),spans.push({textStart:textLength,textEnd:textLength+text.length,row,startCol:column,endCol:column+text.length,linearColumns:!0}),textLength+=text.length,column+=text.length,index=end}}else for(let grapheme of segmenter2.segment(line)){let text=grapheme.segment,width=visibleWidth(text);if(/^\s+$/u.test(text)){textLength>0&&(pendingSeparator=!0),column+=width;continue}appendSeparator(),chunks.push(text),spans.push({textStart:textLength,textEnd:textLength+text.length,row,startCol:column,endCol:column+width,linearColumns:!1}),textLength+=text.length,column+=width}textLength>0&&(pendingSeparator=!0)}return{text:chunks.join(""),spans}}function normalizeQuery(query){return query.replace(/\s+/gu," ").trim()}function escapeRegExp(text){return text.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function findSearchCorpusMatches(corpus,normalizedQuery){if(!normalizedQuery)return[];let expression=new RegExp(escapeRegExp(normalizedQuery),"giu"),matches=[],spanIndex=0;for(let match of corpus.text.matchAll(expression)){let start=match.index,end=start+match[0].length;for(;spanIndex<corpus.spans.length&&corpus.spans[spanIndex].textEnd<=start;)spanIndex+=1;let segments=[];for(let index=spanIndex;index<corpus.spans.length;index++){let span=corpus.spans[index];if(span.textStart>=end)break;if(span.textEnd<=start)continue;let startCol=span.linearColumns?span.startCol+Math.max(start,span.textStart)-span.textStart:span.startCol,endCol=span.linearColumns?span.startCol+Math.min(end,span.textEnd)-span.textStart:span.endCol,previous=segments[segments.length-1];previous&&previous.row===span.row&&startCol<=previous.endCol?previous.endCol=Math.max(previous.endCol,endCol):segments.push({row:span.row,startCol,endCol})}for(;spanIndex<corpus.spans.length&&corpus.spans[spanIndex].textEnd<=end;)spanIndex+=1;segments.length>0&&matches.push({segments})}return matches}var AltScreenSearchIndex=class{sourceLines;corpus;normalizedQuery;matches=[];search(lines,query){let sourceChanged=this.sourceLines?.length!==lines.length;if(!sourceChanged&&this.sourceLines){for(let index=0;index<lines.length;index++)if(this.sourceLines[index]!==lines[index]){sourceChanged=!0;break}}(sourceChanged||!this.corpus)&&(this.sourceLines=Array.from(lines),this.corpus=buildSearchCorpus(lines));let normalizedQuery=normalizeQuery(query),changed=sourceChanged||normalizedQuery!==this.normalizedQuery;return changed&&(this.normalizedQuery=normalizedQuery,this.matches=findSearchCorpusMatches(this.corpus,normalizedQuery)),{matches:this.matches,changed}}};function getAltScreenSearchMatchKey(match){let first=match.segments[0],last=match.segments[match.segments.length-1];return first&&last?`${first.row}:${first.startCol}:${last.row}:${last.endCol}`:""}var AltScreenSearchComponent=class{input=new Input({prompt:" ",placeholder:"Find in transcript",placeholderStyle:text=>`\x1B[2m${text}\x1B[22m`});onQueryChange;navigationButtonStyle;resultCount=0;resultIndex=-1;previousButtonStart=-1;previousButtonEnd=-1;nextButtonStart=-1;nextButtonEnd=-1;hoveredNavigationDirection;_focused=!1;constructor(onQueryChange,navigationButtonStyle=text=>text){this.onQueryChange=onQueryChange,this.navigationButtonStyle=navigationButtonStyle}get focused(){return this._focused}set focused(value){this._focused=value,this.input.focused=value}setResult(index,count){this.resultIndex=index,this.resultCount=count}getNavigationDirectionAt(row,column){if(row===2){if(column>=this.previousButtonStart&&column<this.previousButtonEnd)return-1;if(column>=this.nextButtonStart&&column<this.nextButtonEnd)return 1}}setHoveredNavigationDirection(direction){return direction===this.hoveredNavigationDirection?!1:(this.hoveredNavigationDirection=direction,!0)}handleInput(data){let previous=this.input.getValue();this.input.handleInput(data);let query=this.input.getValue();query!==previous&&this.onQueryChange(query)}invalidate(){this.input.invalidate()}render(width){let safeWidth=Math.max(1,width),innerWidth=Math.max(0,safeWidth-2),formatKey=key=>key?key.split("+").map(part=>process.platform==="darwin"&&part.toLowerCase()==="alt"?"Option":part.charAt(0).toUpperCase()+part.slice(1)).join("+"):"Unbound",keybindings=getKeybindings(),previousKey=formatKey(keybindings.getKeys("tui.altScreen.searchPrevious")[0]),nextKey=formatKey(keybindings.getKeys("tui.altScreen.searchNext")[0]),result=this.input.getValue()?this.resultCount===0?"No matches":`${this.resultIndex+1}/${this.resultCount}`:"",resultSpace=Math.max(0,innerWidth-3),visibleResult=truncateToWidth(result,resultSpace,""),resultText=visibleResult?`\x1B[2m ${visibleResult} \x1B[22m`:"",inputWidth=Math.max(0,innerWidth-visibleWidth(resultText)),inputLine=truncateToWidth(this.input.render(Math.max(1,inputWidth))[0]??"",inputWidth,""),inputPadding=" ".repeat(Math.max(0,inputWidth-visibleWidth(inputLine))),content=`${inputLine}${inputPadding}${resultText}`,previousButton=`\u2191 ${previousKey}`,nextButton=`\u2193 ${nextKey}`,separator=" \xB7 ",outerGapWidth=1,availableControlsWidth=Math.max(0,innerWidth-outerGapWidth*2-1),controlsWidth=visibleWidth(previousButton)+visibleWidth(separator)+visibleWidth(nextButton);controlsWidth>availableControlsWidth&&(previousButton="\u2191",nextButton="\u2193",separator=" ",controlsWidth=visibleWidth(previousButton)+visibleWidth(separator)+visibleWidth(nextButton));let showButtons=controlsWidth<=availableControlsWidth,renderedButtons=showButtons?this.navigationButtonStyle(previousButton,this.hoveredNavigationDirection===-1)+separator+this.navigationButtonStyle(nextButton,this.hoveredNavigationDirection===1):"",outerGapsWidth=showButtons?outerGapWidth*2:0,rightRuleWidth=renderedButtons&&innerWidth>controlsWidth+outerGapsWidth?1:0,leftRuleWidth=Math.max(0,innerWidth-(showButtons?controlsWidth:0)-outerGapsWidth-rightRuleWidth),previousStart=1+leftRuleWidth+outerGapWidth;return this.previousButtonStart=showButtons?previousStart:-1,this.previousButtonEnd=showButtons?previousStart+visibleWidth(previousButton):-1,this.nextButtonStart=showButtons?this.previousButtonEnd+visibleWidth(separator):-1,this.nextButtonEnd=showButtons?this.nextButtonStart+visibleWidth(nextButton):-1,safeWidth===1?["\u250C","\u2502","\u2514"]:[`\u250C${"\u2500".repeat(innerWidth)}\u2510`,`\u2502${content}\u2502`,`\u2514${"\u2500".repeat(leftRuleWidth)}${renderedButtons?" ":""}${renderedButtons}${renderedButtons?" ":""}${"\u2500".repeat(rightRuleWidth)}\u2518`]}};var DEFAULT_DURATION_MS=1e3,AltScreenFlashContainer=class{entries=[];nextId=0;requestRender;constructor(requestRender){this.requestRender=requestRender}flash(message,durationMs=DEFAULT_DURATION_MS){let id=this.nextId++,timer=setTimeout(()=>{let index=this.entries.findIndex(entry=>entry.id===id);index!==-1&&(this.entries.splice(index,1),this.requestRender())},Math.max(0,durationMs));timer.unref(),this.entries.push({id,message,timer}),this.requestRender()}dispose(){for(let entry of this.entries)clearTimeout(entry.timer);this.entries.length=0}invalidate(){}render(width){return this.entries.map(entry=>`\x1B[7m${truncateToWidth(` ${entry.message} `,width,"")}\x1B[27m`)}};var OSC133_ZONE_PREFIX=/^(?:\x1b\]133;[ABC](?:\x07|\x1b\\))+/;function intersect(a,b2){let x2=Math.max(a.x,b2.x),y2=Math.max(a.y,b2.y),right=Math.min(a.x+a.width,b2.x+b2.width),bottom=Math.min(a.y+a.height,b2.y+b2.height);return{x:x2,y:y2,width:Math.max(0,right-x2),height:Math.max(0,bottom-y2)}}function renderCached(context,component,width){let safeWidth=Math.max(1,Math.floor(width)),widths=context.renderCache.get(component);widths||(widths=new Map,context.renderCache.set(component,widths));let lines=widths.get(safeWidth);return lines||(lines=component.render(safeWidth),widths.set(safeWidth,lines)),lines}function measureHeight(context,component,width){return renderCached(context,component,width).length}function measureWidth(context,component,width){return renderCached(context,component,width).reduce((max,line)=>Math.max(max,visibleWidth(line)),0)}function withParent(box,parent){return box.parent=parent,box}function translateBox(box,deltaY){box.rect.y+=deltaY;for(let child of box.children)translateBox(child,deltaY)}function updateClips(box,parentClip){box.clip=intersect(parentClip,box.rect);for(let child of box.children)updateClips(child,box.clip)}function layoutComponent(context,component,x2,y2,width,height,clip){let safeWidth=Math.max(1,Math.floor(width)),node=getLayoutNode(component);if(!node){let lines=renderCached(context,component,safeWidth),allocatedHeight2=height===void 0?lines.length:Math.max(0,Math.floor(height)),lineOffset=0;if(lines.length>allocatedHeight2&&allocatedHeight2>0){let cursorLine=lines.findIndex(line=>line.includes(CURSOR_MARKER));cursorLine>=allocatedHeight2&&(lineOffset=cursorLine-allocatedHeight2+1)}return{component,rect:{x:x2,y:y2,width:safeWidth,height:allocatedHeight2},clip:intersect(clip,{x:x2,y:y2,width:safeWidth,height:allocatedHeight2}),children:[],lines,lineOffset,layer:0}}if(node.type==="scroll"){let previousScrollTop=node.state.scrollTop,contentWidth=node.state.getContentWidth(safeWidth),childBox=layoutComponent(context,node.component,x2,y2-previousScrollTop,contentWidth,void 0,clip),contentHeight=childBox.rect.height,viewportHeight=height===void 0?contentHeight:Math.max(0,Math.floor(height));node.state.updateLayout(contentHeight,viewportHeight,context.requestRender),translateBox(childBox,previousScrollTop-node.state.scrollTop);let scrollView=node.state;(node.state.primary||!context.primaryScrollView)&&(context.primaryScrollView=scrollView);let rect2={x:x2,y:y2,width:safeWidth,height:viewportHeight},childClip=intersect(clip,rect2),box2={component,rect:rect2,clip:childClip,children:[childBox],scrollView,scrollContentLines:renderCached(context,node.component,contentWidth),layer:0};return childBox.parent=box2,updateClips(childBox,childClip),box2}let entries=visibleStackEntries(node.entries,context.viewport),gapTotal=Math.max(0,entries.length-1)*node.gap;if(node.type==="vstack"){let intrinsicHeights2=entries.map(entry=>typeof entry.basis=="number"?entry.basis:measureHeight(context,entry.component,safeWidth)),sizes=allocateStackSizes(entries,intrinsicHeights2,height,node.gap),naturalHeight=sizes.reduce((sum,size)=>sum+size,0)+gapTotal,allocatedHeight2=height===void 0?naturalHeight:Math.max(0,Math.floor(height)),rect2={x:x2,y:y2,width:safeWidth,height:allocatedHeight2},box2={component,rect:rect2,clip:intersect(clip,rect2),children:[],layer:0},childY=y2;for(let index=0;index<entries.length;index++)box2.children.push(withParent(layoutComponent(context,entries[index].component,x2,childY,safeWidth,sizes[index],box2.clip),box2)),childY+=sizes[index]+node.gap;return box2}let intrinsicWidths=entries.map(entry=>typeof entry.basis=="number"?entry.basis:measureWidth(context,entry.component,safeWidth)),widths=allocateStackSizes(entries,intrinsicWidths,safeWidth,node.gap),intrinsicHeights=entries.map((entry,index)=>measureHeight(context,entry.component,Math.max(1,widths[index]))),allocatedHeight=height===void 0?intrinsicHeights.reduce((max,childHeight)=>Math.max(max,childHeight),0):Math.max(0,height),rect={x:x2,y:y2,width:safeWidth,height:allocatedHeight},box={component,rect,clip:intersect(clip,rect),children:[],layer:0},childX=x2;for(let index=0;index<entries.length;index++){let naturalChildHeight=intrinsicHeights[index],childHeight=node.align==="stretch"?allocatedHeight:Math.min(allocatedHeight,naturalChildHeight),childY=y2;node.align==="center"?childY+=Math.floor((allocatedHeight-childHeight)/2):node.align==="end"&&(childY+=allocatedHeight-childHeight);let childWidth=widths[index];childWidth===0?box.children.push({component:entries[index].component,rect:{x:childX,y:childY,width:0,height:childHeight},clip:{x:childX,y:childY,width:0,height:0},children:[],parent:box,layer:0}):box.children.push(withParent(layoutComponent(context,entries[index].component,childX,childY,childWidth,childHeight,box.clip),box)),childX+=childWidth+node.gap}return box}function replaceScrollbarCell(line,column,totalWidth,replacement,preserveTargetBackground){if(isImageLine(line))return line;let graphemeRange=getGraphemeCellRange(line,column),start=graphemeRange?.start??column,end=graphemeRange?.end??column+1,before=sliceByColumn(line,0,start,!0),target=sliceByColumn(line,start,end-start,!0),after=sliceByColumn(line,end,Math.max(0,totalWidth-end),!0),targetPrefix="",targetIndex=0;for(;targetIndex<target.length;){let ansi=extractAnsiCode(target,targetIndex);if(!ansi)break;targetPrefix+=ansi.code,targetIndex+=ansi.length}let beforePadding=" ".repeat(Math.max(0,start-visibleWidth(before))),cellPaddingBefore=" ".repeat(Math.max(0,column-start)),cellPaddingAfter=" ".repeat(Math.max(0,end-column-1)),targetStyle=`\x1B[0m\x1B]8;;\x07${preserveTargetBackground?getActiveBackgroundAnsi(targetPrefix):""}`;return`${before}${beforePadding}${targetStyle}${cellPaddingBefore}${replacement}${cellPaddingAfter}${after}`}function getScrollbarGeometry(box,includeHiddenAuto=!1){if(!box.scrollView||box.rect.width<=0||box.rect.height<=0)return;let contentHeight=box.children[0]?.rect.height??box.scrollContentLines?.length??0,trackHeight=box.rect.height,canRevealHiddenAuto=includeHiddenAuto&&box.scrollView.scrollbar==="auto"&&contentHeight>trackHeight;if(!box.scrollView.isScrollbarVisible&&!canRevealHiddenAuto)return;let minThumbHeight=Math.min(2,trackHeight),thumbHeight=Math.max(minThumbHeight,Math.min(trackHeight,Math.round(trackHeight*trackHeight/contentHeight))),maxScrollTop=Math.max(0,contentHeight-trackHeight),maxThumbTop=trackHeight-thumbHeight,thumbOffset=maxScrollTop===0?0:Math.round(box.scrollView.scrollTop/maxScrollTop*maxThumbTop),column=box.rect.x+box.rect.width-1;if(!(column<box.clip.x||column>=box.clip.x+box.clip.width))return{column,trackTop:box.rect.y,trackHeight,thumbTop:box.rect.y+thumbOffset,thumbHeight,maxScrollTop}}function paintScrollbar(box,screen,totalWidth){let geometry=getScrollbarGeometry(box);if(!(!geometry||!box.scrollView))for(let offset=0;offset<geometry.trackHeight;offset++){let row=geometry.trackTop+offset;if(row<box.clip.y||row>=box.clip.y+box.clip.height||row<0||row>=screen.length)continue;let replacement=row>=geometry.thumbTop&&row<geometry.thumbTop+geometry.thumbHeight?box.scrollView.scrollbarThumbStyle(box.scrollView.isScrollbarActive?"\u2588":"\u2503"):box.scrollView.scrollbarTrackStyle("\u2502");screen[row]=replaceScrollbarCell(screen[row]??"",geometry.column,totalWidth,replacement,box.scrollView.scrollbar!=="always")}}function paintBox(box,screen,totalWidth){if(box.lines){let offset=box.lineOffset??0,firstRow=Math.max(box.rect.y,box.clip.y,0),lastRow=Math.min(box.rect.y+box.rect.height,box.clip.y+box.clip.height,screen.length);for(let row=firstRow;row<lastRow;row++){let sourceLine=box.lines[offset+row-box.rect.y];if(sourceLine===void 0)continue;let line=sourceLine.replace(OSC133_ZONE_PREFIX,""),imageMetadata=getKittyImageMetadata(line);if(imageMetadata){let clipBottom=Math.min(screen.length,box.clip.y+box.clip.height),visibleRows=Math.min(imageMetadata.rows,clipBottom-row);visibleRows<imageMetadata.rows&&(line=cropKittyImageLine(line,0,visibleRows))}box.rect.x===0&&box.rect.width>=totalWidth&&(isImageLine(line)||!screen[row])?screen[row]=line:screen[row]=compositeTuiLine(screen[row]??"",line,box.rect.x,box.rect.width,totalWidth)}}for(let child of box.children)paintBox(child,screen,totalWidth);if(box.scrollView&&box.scrollContentLines&&box.scrollView.scrollTop>0&&box.rect.height>0)for(let imageRow=box.scrollView.scrollTop-1;imageRow>=0;imageRow--){let imageLine=box.scrollContentLines[imageRow]??"",metadata=getKittyImageMetadata(imageLine);if(metadata){let hiddenRows=box.scrollView.scrollTop-imageRow;if(hiddenRows<metadata.rows){let visibleRows=Math.min(box.rect.height,metadata.rows-hiddenRows),cropped=cropKittyImageLine(imageLine,hiddenRows,visibleRows);box.rect.x===0&&box.rect.width>=totalWidth&&(screen[box.rect.y]=cropped)}break}if(imageLine!=="")break}paintScrollbar(box,screen,totalWidth)}function renderLayoutFrame(root,width,height,requestRender){let safeWidth=Math.max(1,Math.floor(width)),safeHeight=Math.max(1,Math.floor(height)),context={viewport:{width:safeWidth,height:safeHeight},renderCache:new Map,requestRender,primaryScrollView:void 0},rootBox=layoutComponent(context,root,0,0,safeWidth,safeHeight,{x:0,y:0,width:safeWidth,height:safeHeight}),lines=Array.from({length:safeHeight},()=>"");return paintBox(rootBox,lines,safeWidth),{root:rootBox,width:safeWidth,height:safeHeight,lines,...context.primaryScrollView===void 0?{}:{primaryScrollView:context.primaryScrollView}}}function containsPoint(rect,x2,y2){return x2>=rect.x&&x2<rect.x+rect.width&&y2>=rect.y&&y2<rect.y+rect.height}function getLayoutBoxesAt(frame,x2,y2){let result=[],visit=(box,depth)=>{if(containsPoint(box.clip,x2,y2)){result.push({box,depth});for(let child of box.children)visit(child,depth+1)}};return visit(frame.root,0),result.sort((a,b2)=>b2.box.layer-a.box.layer||b2.depth-a.depth),result.map(({box})=>box)}function getScrollViewBox(frame,scrollView){let visit=box=>{if(box.scrollView===scrollView)return box;for(let child of box.children){let match=visit(child);if(match)return match}};return visit(frame.root)}function getScrollViewsAt(frame,x2,y2){let result=[],visit=(box,depth)=>{if(containsPoint(box.clip,x2,y2)){box.scrollView&&containsPoint(box.rect,x2,y2)&&result.push({scrollView:box.scrollView,depth});for(let child of box.children)visit(child,depth+1)}};return visit(frame.root,0),result.sort((a,b2)=>b2.depth-a.depth),result.map(entry=>entry.scrollView)}function terminalAcceleratesWheel(){let env=process.env;return process.platform==="darwin"&&env.SSH_CONNECTION===void 0&&env.SSH_CLIENT===void 0&&env.SSH_TTY===void 0}var WheelScrollAccelerator=class{lines;accelerate;lastTime=Number.NEGATIVE_INFINITY;lastDirection=0;averageGap;carry=0;constructor(lines="auto",accelerate=!terminalAcceleratesWheel()){this.lines=lines,this.accelerate=accelerate}setLines(lines){this.lines=lines,this.reset()}next(direction,now){if(this.lines!=="auto")return Number.isFinite(this.lines)?Math.max(1,Math.floor(this.lines)):1;if(!this.accelerate)return 1;let gap=now-this.lastTime,sameGesture=direction===this.lastDirection&&gap<=200;if(this.lastTime=now,this.lastDirection=direction,!sameGesture)return this.averageGap=void 0,this.carry=0,1;if(gap<5)return 1;this.averageGap=this.averageGap===void 0?gap:(this.averageGap+gap)/2;let lines=Math.min(6,Math.max(1,100/this.averageGap))+this.carry,whole=Math.floor(lines);return this.carry=lines-whole,whole}reset(){this.lastTime=Number.NEGATIVE_INFINITY,this.lastDirection=0,this.averageGap=void 0,this.carry=0}};var ENTER_ALT_SCREEN="\x1B[?1049h",EXIT_ALT_SCREEN="\x1B[?1049l",DISABLE_AUTOWRAP="\x1B[?7l",ENABLE_AUTOWRAP="\x1B[?7h",ENABLE_BUTTON_MOTION_MOUSE="\x1B[?1000h\x1B[?1002h\x1B[?1004h\x1B[?1006h",ENABLE_ALL_MOTION_MOUSE="\x1B[?1000h\x1B[?1002h\x1B[?1003h\x1B[?1004h\x1B[?1006h",DISABLE_MOUSE="\x1B[?1006l\x1B[?1004l\x1B[?1003l\x1B[?1002l\x1B[?1000l",FOCUS_IN="\x1B[I",FOCUS_OUT="\x1B[O",BEGIN_SYNCHRONIZED_OUTPUT="\x1B[?2026h",END_SYNCHRONIZED_OUTPUT="\x1B[?2026l",OSC133_ZONE_PREFIX2=/^(?:\x1b\]133;[ABC](?:\x07|\x1b\\))+/,OSC133_PROMPT_START=/^\x1b\]133;A(?:\x07|\x1b\\)/,PAGE_SCROLL_OVERLAP=4,ALT_WHEEL_SCROLL_MULTIPLIER=5,MAX_CACHED_OFFSCREEN_KITTY_IMAGES=16,MAX_CACHED_OFFSCREEN_KITTY_TRANSMISSION_BYTES=32*1024*1024,MAX_CACHED_OFFSCREEN_KITTY_DECODED_BYTES=64*1024*1024,DOUBLE_CLICK_INTERVAL_MS=500,COPY_ERROR_FLASH_DURATION_MS=5e3,TERMINAL_WORD_SELECTION_JOINERS=new Set(["/","-"]),wordSegmenter4=getWordSegmenter(),TuiAltScreen=class extends TuiBase{mode="fullscreen";[VIEWPORT_TUI]=!0;previousScreen=[];lastDocument=[];previousScreenWidth=0;previousScreenHeight=0;layoutRoot;currentLayout;implicitDocument;implicitScrollView;flashes;altScreenActive=!1;imageProtocol=null;savedCapabilities;uploadedKittyImages=new Map;selectionAnchor;selectionFocus;selectionGranularity="character";selectionInitialRange;lastClick;selectionDragPointer;selectionAutoScrollDirection=0;selectionAutoScrollTimer;selectionPressActive=!1;scrollbarDrag;scrollbarHover;scrollToEndIndicatorRect;activeSearch;pressedUrl;selectionDragged=!1;mouseCapture;mousePressTarget;mousePressPoint;mousePressMoved=!1;lastComponentClick;wheelScroll;mouseEnabled;searchMatchStyle;searchCurrentMatchStyle;searchNavigationButtonStyle;scrollToEndIndicator;openUrl;onRightClickPaste;copyOnSelect;copySelection;constructor(terminal,showHardwareCursor,logDirectory,options={}){super(terminal,showHardwareCursor,logDirectory),this.implicitDocument={render:width=>super.render(width),handleMouse:event=>super.handleMouse(event),invalidate:()=>{for(let child of this.children)child.invalidate()}},this.implicitScrollView=new ScrollView(this.implicitDocument,{follow:"end",primary:!0}),this.flashes=new AltScreenFlashContainer(()=>this.requestRender()),this.wheelScroll=new WheelScrollAccelerator(options.wheelScrollLines??1),this.mouseEnabled=options.mouse??!0,this.searchMatchStyle=options.searchMatchStyle??(text=>`\x1B[4m${text}\x1B[24m`),this.searchCurrentMatchStyle=options.searchCurrentMatchStyle??(text=>`\x1B[1;7m${text}\x1B[22;27m`),this.searchNavigationButtonStyle=options.searchNavigationButtonStyle??(text=>text),this.scrollToEndIndicator=options.scrollToEndIndicator,this.openUrl=options.openUrl,this.onRightClickPaste=options.onRightClickPaste,this.copyOnSelect=options.copyOnSelect??!0,this.copySelection=options.copySelection,this.addInputListener(data=>this.handleViewportInput(data))}get viewportTop(){return this.getPrimaryScrollView().scrollTop}get isFollowingOutput(){return this.getPrimaryScrollView().isFollowingEnd}setWheelScrollLines(lines){this.wheelScroll.setLines(lines)}getCopyOnSelect(){return this.copyOnSelect}setCopyOnSelect(enabled){this.copyOnSelect=enabled}hasActiveSelection(){return this.getActiveSelectionText()!==void 0}async copyActiveSelectionToClipboard(){let text=this.getActiveSelectionText();return text?this.copyTextToClipboard(text):!1}resetTextSelection(){this.clearTextSelection(),this.lastClick=void 0}getScreenLines(){return[...this.previousScreen]}setLayoutRoot(component){this.layoutRoot!==component&&(this.layoutRoot=component,this.currentLayout=void 0,this.requestRender())}render(width){return this.layoutRoot?.render(width)??super.render(width)}getMountedRoots(){return this.layoutRoot?[this.layoutRoot]:this.children}getPrimaryScrollView(){return this.currentLayout?.primaryScrollView??this.implicitScrollView}beforeTerminalStart(){this.stopSelectionAutoScroll(),this.selectionPressActive=!1,this.stopScrollbarHover(),this.stopScrollbarDrag(),this.flashes.dispose(),this.altScreenActive=!0;let capabilities=getCapabilities();this.imageProtocol=capabilities.images,this.uploadedKittyImages.clear(),capabilities.images==="iterm2"&&(this.savedCapabilities=capabilities,setCapabilities({...capabilities,images:null}),this.invalidate()),this.lastDocument=[],this.selectionAnchor=void 0,this.selectionFocus=void 0,this.selectionGranularity="character",this.selectionInitialRange=void 0,this.lastClick=void 0,this.pressedUrl=void 0,this.selectionDragged=!1,this.clearComponentMouseGesture(),this.lastComponentClick=void 0,this.resetRenderState();let term=process.env.TERM?.toLowerCase()??"",mouseSequence=process.env.TMUX!==void 0||process.env.ZELLIJ!==void 0||process.env.STY!==void 0||term.startsWith("tmux")||term.startsWith("screen")?ENABLE_BUTTON_MOTION_MOUSE:ENABLE_ALL_MOTION_MOUSE;this.terminal.write(`${ENTER_ALT_SCREEN}${DISABLE_AUTOWRAP}${this.mouseEnabled?mouseSequence:""}\x1B[2J\x1B[H\x1B[?25l`)}beforeTerminalStop(_options){this.closeSearch(),this.stopSelectionAutoScroll(),this.selectionPressActive=!1,this.stopScrollbarHover(),this.stopScrollbarDrag(),this.clearComponentMouseGesture(),this.flashes.dispose(),this.altScreenActive&&(this.terminal.write(`${BEGIN_SYNCHRONIZED_OUTPUT}${this.deleteKittyImages()}${this.mouseEnabled?DISABLE_MOUSE:""}${ENABLE_AUTOWRAP}${END_SYNCHRONIZED_OUTPUT}`),this.uploadedKittyImages.clear())}afterTerminalStop(options){if(this.altScreenActive){if(this.altScreenActive=!1,options.preserveScreen)this.terminal.write(`${BEGIN_SYNCHRONIZED_OUTPUT}${EXIT_ALT_SCREEN}\x1B[?25h${END_SYNCHRONIZED_OUTPUT}`);else{let width=Math.max(1,this.terminal.columns),documentLines=this.resolveFakeCursors(this.render(width)).map(line=>line.replace(OSC133_ZONE_PREFIX2,""));this.lastDocument=this.applyLineResets(documentLines.map(line=>line.replaceAll(CURSOR_MARKER,""))).map(line=>isImageLine(line)||visibleWidth(line)<=width?line:sliceByColumn(line,0,width,!0));let buffer=`${BEGIN_SYNCHRONIZED_OUTPUT}${EXIT_ALT_SCREEN}${DISABLE_AUTOWRAP}`;for(let row=0;row<this.lastDocument.length;row++)row>0&&(buffer+=`\r
108
108
  `),buffer+=`\r\x1B[2K${this.lastDocument[row]??""}`;buffer+=`\x1B[0m${ENABLE_AUTOWRAP}\r
109
109
  \x1B[?25h${END_SYNCHRONIZED_OUTPUT}`,this.terminal.write(buffer)}this.savedCapabilities&&(setCapabilities(this.savedCapabilities),this.savedCapabilities=void 0)}}getExitRestorePrefix(){let prefix=super.getExitRestorePrefix();return this.altScreenActive?`${END_SYNCHRONIZED_OUTPUT}${this.mouseEnabled?DISABLE_MOUSE:""}${ENABLE_AUTOWRAP}${prefix}`:prefix}getExitRestoreSuffix(){return`${super.getExitRestoreSuffix()}${this.altScreenActive?`${EXIT_ALT_SCREEN}\x1B[?25h`:""}`}deleteKittyImages(){return this.imageProtocol==="kitty"?deleteAllKittyImages():""}prepareKittyScreen(screen){let visibleImageIds=new Set,lines=screen.map(line=>{let placement=getKittyImagePlacement(line);if(!placement)return line;visibleImageIds.add(placement.imageId);let cachedImage=this.uploadedKittyImages.get(placement.imageId),nextCachedImage={transmissionGeneration:placement.transmissionGeneration,transmissionBytes:placement.transmissionBytes,estimatedDecodedBytes:placement.estimatedDecodedBytes};return cachedImage&&this.uploadedKittyImages.delete(placement.imageId),this.uploadedKittyImages.set(placement.imageId,nextCachedImage),cachedImage?.transmissionGeneration===placement.transmissionGeneration?placement.replacementLine:line}),cachedOffscreenImageCount=0,cachedOffscreenTransmissionBytes=0,cachedOffscreenDecodedBytes=0;for(let[imageId,cachedImage]of this.uploadedKittyImages)visibleImageIds.has(imageId)||(cachedOffscreenImageCount+=1,cachedOffscreenTransmissionBytes+=cachedImage.transmissionBytes,cachedOffscreenDecodedBytes+=cachedImage.estimatedDecodedBytes);let evictedImageDeletion="";for(let[imageId,cachedImage]of this.uploadedKittyImages){if(cachedOffscreenImageCount<=MAX_CACHED_OFFSCREEN_KITTY_IMAGES&&cachedOffscreenTransmissionBytes<=MAX_CACHED_OFFSCREEN_KITTY_TRANSMISSION_BYTES&&cachedOffscreenDecodedBytes<=MAX_CACHED_OFFSCREEN_KITTY_DECODED_BYTES)break;visibleImageIds.has(imageId)||(evictedImageDeletion+=deleteKittyImage(imageId),this.uploadedKittyImages.delete(imageId),cachedOffscreenImageCount-=1,cachedOffscreenTransmissionBytes-=cachedImage.transmissionBytes,cachedOffscreenDecodedBytes-=cachedImage.estimatedDecodedBytes)}return{lines,evictedImageDeletion}}resetRenderState(){this.previousScreen=[],this.previousScreenWidth=0,this.previousScreenHeight=0,this.currentLayout=void 0}scrollBy(lines){this.getPrimaryScrollView().scrollBy(lines),this.requestRender()}scrollToTop(){this.getPrimaryScrollView().scrollToStart(),this.requestRender()}scrollToBottom(){this.getPrimaryScrollView().scrollToEnd(),this.requestRender()}scrollToPrompt(direction){if(!this.currentLayout)return;let scrollView=this.getPrimaryScrollView(),lines=getScrollViewBox(this.currentLayout,scrollView)?.scrollContentLines;if(lines){for(let row=scrollView.scrollTop+direction;row>=0&&row<lines.length;row+=direction)if(OSC133_PROMPT_START.test(lines[row]??"")){scrollView.scrollTo(row),this.requestRender();return}}}toggleSearch(){if(this.activeSearch){this.closeSearch();return}let component=new AltScreenSearchComponent(query=>this.updateSearchQuery(query),this.searchNavigationButtonStyle),search={component,index:new AltScreenSearchIndex,query:"",matches:[],selectedIndex:-1,anchorRow:this.getPrimaryScrollView().scrollTop,selectionMode:"query"};this.activeSearch=search,search.overlay=this.showOverlay(component,{anchor:"top-right",width:"40%",minWidth:32,margin:1})}closeSearch(){let search=this.activeSearch;search&&(this.activeSearch=void 0,search.overlay?.hide(),this.requestRender())}updateSearchQuery(query){let search=this.activeSearch;if(!search||query===search.query)return;let selected=search.matches[search.selectedIndex];search.anchorRow=selected?.segments[0]?.row??this.getPrimaryScrollView().scrollTop,search.query=query,search.selectionMode="query",search.component.setResult(-1,0),this.requestRender()}navigateSearch(direction){let search=this.activeSearch;search?.query&&(search.selectionMode=direction<0?"previous":"next",this.requestRender())}getSearchNavigationDirectionAt(x2,y2){let search=this.activeSearch,bounds=search?.overlay?.getBounds();if(!(!search||!bounds)&&!(x2<bounds.col||x2>=bounds.col+bounds.width||y2<bounds.row||y2>=bounds.row+bounds.height))return search.component.getNavigationDirectionAt(y2-bounds.row,x2-bounds.col)}handleSearchMouseEvent(event){let search=this.activeSearch;if(!search)return!1;let direction=this.getSearchNavigationDirectionAt(event.x,event.y);return search.component.setHoveredNavigationDirection(direction)&&this.requestRender(),direction===void 0||event.release||(event.button&32)!==0||(event.button&3)!==0?!1:(this.navigateSearch(direction),!0)}refreshSearch(layout){let search=this.activeSearch;if(!search)return!1;let scrollView=layout.primaryScrollView??this.implicitScrollView,box=getScrollViewBox(layout,scrollView),lines=box?.scrollContentLines;if(!lines||!search.query.trim())return search.matches=[],search.selectedIndex=-1,search.selectedKey=void 0,search.selectionMode="retain",search.component.setResult(-1,0),!1;let shouldRevealSelection=search.selectionMode!=="retain",result=search.index.search(lines,search.query),matches=result.matches;if(search.matches=matches,!result.changed&&search.selectionMode==="retain")return!1;let exactIndex=result.changed?search.selectedKey?matches.findIndex(match=>getAltScreenSearchMatchKey(match)===search.selectedKey):-1:search.selectedIndex,selectedIndex=-1;if(matches.length>0)if(search.selectionMode==="query"){let low=0,high=matches.length;for(;low<high;){let middle=low+Math.floor((high-low)/2);(matches[middle].segments[0]?.row??0)<search.anchorRow?low=middle+1:high=middle}selectedIndex=low<matches.length?low:0}else if(search.selectionMode==="next"){let baseIndex=exactIndex>=0?exactIndex:Math.min(search.selectedIndex,matches.length-1);selectedIndex=baseIndex<0?0:(baseIndex+1)%matches.length}else if(search.selectionMode==="previous"){let baseIndex=exactIndex>=0?exactIndex:Math.min(search.selectedIndex,matches.length-1);selectedIndex=baseIndex<0?matches.length-1:(baseIndex-1+matches.length)%matches.length}else selectedIndex=exactIndex>=0?exactIndex:Math.min(Math.max(0,search.selectedIndex),matches.length-1);if(search.selectedIndex=selectedIndex,search.selectedKey=selectedIndex>=0?getAltScreenSearchMatchKey(matches[selectedIndex]):void 0,search.selectionMode="retain",search.component.setResult(selectedIndex,matches.length),!shouldRevealSelection)return!1;let selected=matches[selectedIndex],firstSegment=selected?.segments[0],lastSegment=selected?.segments[selected.segments.length-1];if(!box||!firstSegment||!lastSegment||scrollView.viewportHeight<=0)return!1;let before=scrollView.scrollTop,visibleBottom=before+scrollView.viewportHeight-1,target=before;return(firstSegment.row<before||lastSegment.row>visibleBottom)&&(target=firstSegment.row-Math.floor(scrollView.viewportHeight/3)),scrollView.scrollTo(target,{disableFollow:!0}),scrollView.scrollTop!==before}flash(message,durationMs){this.flashes.flash(message,durationMs)}shouldDeferViewportInputToOverlay(){return this.isOverlayFocused()&&this.activeSearch?.overlay?.isFocused()!==!0}clearComponentMouseGesture(){this.mouseCapture=void 0,this.mousePressTarget=void 0,this.mousePressPoint=void 0,this.mousePressMoved=!1}handleViewportInput(data){if(data===FOCUS_OUT){let hadActiveSelection=this.selectionPressActive,hadNonEmptyActiveSelection=hadActiveSelection&&this.getSelectionBounds()!==void 0;return this.selectionPressActive=!1,this.stopSelectionAutoScroll(),this.stopScrollbarHover(),this.activeSearch?.component.setHoveredNavigationDirection(void 0)&&this.requestRender(),this.stopScrollbarDrag(),this.pressedUrl=void 0,this.selectionDragged=!1,this.clearComponentMouseGesture(),this.lastComponentClick=void 0,hadActiveSelection&&(this.selectionAnchor=void 0,this.selectionFocus=void 0,this.selectionGranularity="character",this.selectionInitialRange=void 0,hadNonEmptyActiveSelection&&this.requestRender()),this.lastClick=void 0,{consume:!0}}if(data===FOCUS_IN)return{consume:!0};let wheelEvent=this.parseWheelEvent(data);if(wheelEvent){let lines=this.wheelScroll.next(wheelEvent.direction,performance.now()),wheelDelta=wheelEvent.direction*((wheelEvent.button&8)!==0?lines*ALT_WHEEL_SCROLL_MULTIPLIER:lines),event=this.createMouseEvent("wheel",wheelEvent.button,wheelEvent.x,wheelEvent.y,{wheelDelta}),overlay=this.dispatchMouseToOverlay(event),result=overlay.result??(overlay.hit?void 0:this.dispatchMouseToLayout(event));return result?(this.applyMouseDispatchResult(event,result)&&this.requestRender(),{consume:!0}):(this.routeWheel(wheelEvent,wheelDelta),{consume:!0})}let mouseEvent=this.parseSgrMouseEvent(data);if(mouseEvent)return this.handleMouseEvent(mouseEvent),{consume:!0};if(this.isMouseSequence(data))return{consume:!0};let keybindings=getKeybindings(),isRelease=isKeyRelease(data);if(keybindings.matches(data,"tui.altScreen.search"))return isRelease||this.toggleSearch(),{consume:!0};if(this.activeSearch?.overlay?.isFocused()){if(keybindings.matches(data,"tui.altScreen.searchNext"))return isRelease||this.navigateSearch(1),{consume:!0};if(keybindings.matches(data,"tui.altScreen.searchPrevious"))return isRelease||this.navigateSearch(-1),{consume:!0};if(keybindings.matches(data,"tui.altScreen.searchClose"))return isRelease||this.closeSearch(),{consume:!0}}if(!this.shouldDeferViewportInputToOverlay()){if(keybindings.matches(data,"tui.altScreen.pageUp"))return isRelease||this.scrollBy(-Math.max(1,this.getPrimaryScrollView().viewportHeight-PAGE_SCROLL_OVERLAP)),{consume:!0};if(keybindings.matches(data,"tui.altScreen.pageDown"))return isRelease||this.scrollBy(Math.max(1,this.getPrimaryScrollView().viewportHeight-PAGE_SCROLL_OVERLAP)),{consume:!0};if(keybindings.matches(data,"tui.altScreen.halfPageUp"))return isRelease||this.scrollBy(-Math.max(1,Math.floor(this.getPrimaryScrollView().viewportHeight/2))),{consume:!0};if(keybindings.matches(data,"tui.altScreen.halfPageDown"))return isRelease||this.scrollBy(Math.max(1,Math.floor(this.getPrimaryScrollView().viewportHeight/2))),{consume:!0};if(keybindings.matches(data,"tui.altScreen.lineUp"))return isRelease||this.scrollBy(-1),{consume:!0};if(keybindings.matches(data,"tui.altScreen.lineDown"))return isRelease||this.scrollBy(1),{consume:!0};if(keybindings.matches(data,"tui.altScreen.previousPrompt"))return isRelease||this.scrollToPrompt(-1),{consume:!0};if(keybindings.matches(data,"tui.altScreen.nextPrompt"))return isRelease||this.scrollToPrompt(1),{consume:!0};if(keybindings.matches(data,"tui.altScreen.top"))return isRelease||this.scrollToTop(),{consume:!0};if(keybindings.matches(data,"tui.altScreen.bottom"))return isRelease||this.scrollToBottom(),{consume:!0}}}decodeMouseButton(button){switch(button&3){case 0:return"left";case 1:return"middle";case 2:return"right";default:return"none"}}createMouseEvent(type,button,x2,y2,extra={}){return{type,button:type==="wheel"?"none":this.decodeMouseButton(button),x:x2,y:y2,screenX:x2,screenY:y2,width:Math.max(1,this.terminal.columns),height:Math.max(1,this.terminal.rows),shift:(button&4)!==0,alt:(button&8)!==0,ctrl:(button&16)!==0,...extra.wheelDelta===void 0?{}:{wheelDelta:extra.wheelDelta},...extra.clickCount===void 0?{}:{clickCount:extra.clickCount}}}dispatchMouseToLayout(event){if(!this.currentLayout)return;let visited=new Set,boxes=getLayoutBoxesAt(this.currentLayout,event.screenX,event.screenY);for(let box of boxes){if(visited.has(box.component)||getLayoutNode(box.component)&&box.component.handleMouse===Container.prototype.handleMouse)continue;visited.add(box.component);let result=dispatchMouseEvent(box.component,{...event,x:event.screenX-box.rect.x,y:event.screenY-box.rect.y,width:box.rect.width,height:box.rect.height});if(result)return result}}applyMouseDispatchResult(event,result){let focusTarget=this.resolveMouseFocusTarget(result.focusTarget??result.target.component),focusChanged=result.focus===!0&&this.getFocusedComponent()!==focusTarget;return result.focus&&this.setFocus(focusTarget),result.capture&&(this.mouseCapture=result.target),result.render??(focusChanged||event.type==="press"||event.type==="click"||event.type==="drag"||event.type==="wheel")}dispatchMouseToTarget(event,target){return dispatchMouseEvent(target.component,retargetMouseEvent(event,target))}getComponentClickCount(target,x2,y2){let now=Date.now(),previous=this.lastComponentClick,count=previous&&now-previous.timestamp<=DOUBLE_CLICK_INTERVAL_MS&&previous.component===target.component&&previous.x===x2&&previous.y===y2?previous.count%3+1:1;return this.lastComponentClick={timestamp:now,count,component:target.component,x:x2,y:y2},count}clearTextSelection(){this.stopSelectionAutoScroll(),this.selectionPressActive=!1,this.selectionAnchor=void 0,this.selectionFocus=void 0,this.selectionGranularity="character",this.selectionInitialRange=void 0,this.pressedUrl=void 0,this.selectionDragged=!1}handleMouseEvent(raw){let isMotion=(raw.button&32)!==0,type=raw.release?"release":isMotion?this.decodeMouseButton(raw.button)==="none"?"move":"drag":"press",event=this.createMouseEvent(type,raw.button,raw.x,raw.y);if(this.mouseCapture||this.mousePressTarget){let target=this.mouseCapture??this.mousePressTarget;this.mousePressPoint&&(raw.x!==this.mousePressPoint.x||raw.y!==this.mousePressPoint.y)&&(this.mousePressMoved=!0,this.lastComponentClick=void 0);let render=!1,targetResult=this.dispatchMouseToTarget(event,target);if(targetResult&&(render=this.applyMouseDispatchResult(event,targetResult)),raw.release){if(!this.mousePressMoved&&this.mousePressPoint?.x===raw.x&&this.mousePressPoint.y===raw.y){let clickEvent=this.createMouseEvent("click",raw.button,raw.x,raw.y,{clickCount:this.getComponentClickCount(target,raw.x,raw.y)}),clickResult=this.dispatchMouseToTarget(clickEvent,target);clickResult&&(render=this.applyMouseDispatchResult(clickEvent,clickResult)||render)}this.clearComponentMouseGesture()}render&&this.requestRender();return}if(this.handleSearchMouseEvent(raw))return;let overlay=this.dispatchMouseToOverlay(event);if(overlay.hit)this.stopScrollbarHover();else{if(this.handleScrollToEndIndicatorMouseEvent(raw))return;let scrollbarHandled=this.handleScrollbarMouseEvent(raw);if(this.scrollbarDrag||this.updateScrollbarHover(raw.x,raw.y),scrollbarHandled)return}let result=overlay.result??(overlay.hit?void 0:this.dispatchMouseToLayout(event));if(result){let render=this.applyMouseDispatchResult(event,result);type==="press"&&(this.clearTextSelection(),this.mousePressTarget=result.target,this.mousePressPoint={x:raw.x,y:raw.y},this.mousePressMoved=!1),render&&this.requestRender();return}this.handleRightClickPaste(raw)||this.handleSelectionMouseEvent(raw)}parseWheelEvent(data){let sgr=/^\x1b\[<(\d+);(\d+);(\d+)[Mm]$/.exec(data);if(sgr){let button=Number.parseInt(sgr[1],10);if((button&64)===0)return;let direction=button&3;return direction!==0&&direction!==1?void 0:{direction:direction===0?-1:1,x:Number.parseInt(sgr[2],10)-1,y:Number.parseInt(sgr[3],10)-1,button}}if(data.length===6&&data.startsWith("\x1B[M")){let button=data.charCodeAt(3)-32;if((button&64)===0)return;let direction=button&3;return direction!==0&&direction!==1?void 0:{direction:direction===0?-1:1,x:data.charCodeAt(4)-33,y:data.charCodeAt(5)-33,button}}}routeWheel(event,delta){if(globalThis.__pinkHome)return;let remaining=delta,seen=new Set;for(let scrollView of this.currentLayout?getScrollViewsAt(this.currentLayout,event.x,event.y):[])if(seen.add(scrollView),remaining=scrollView.scrollBy(remaining),remaining===0||scrollView.overscroll==="contain")break;let primary=this.getPrimaryScrollView();remaining!==0&&!seen.has(primary)&&primary.scrollBy(remaining),this.updateScrollbarHover(event.x,event.y),this.requestRender()}parseSgrMouseEvent(data){let match=/^\x1b\[<(\d+);(\d+);(\d+)([Mm])$/.exec(data);if(match)return{button:Number.parseInt(match[1],10),x:Number.parseInt(match[2],10)-1,y:Number.parseInt(match[3],10)-1,release:match[4]==="m"}}handleRightClickPaste(event){if(!this.onRightClickPaste||process.platform!=="win32"||process.env.TERM_PROGRAM?.toLowerCase()==="vscode"||event.release||event.button!==2)return!1;try{this.onRightClickPaste()}catch{}return!0}handleScrollToEndIndicatorMouseEvent(event){let rect=this.scrollToEndIndicatorRect;return!rect||event.release||(event.button&32)!==0||(event.button&3)!==0||event.y!==rect.row||event.x<rect.column||event.x>=rect.column+rect.width?!1:(this.scrollToBottom(),!0)}getScrollbarTargetAt(x2,y2,includeHiddenAuto=!1){if(!(this.hasOverlay()||!this.currentLayout))for(let scrollView of getScrollViewsAt(this.currentLayout,x2,y2)){let box=getScrollViewBox(this.currentLayout,scrollView),geometry=box?getScrollbarGeometry(box,includeHiddenAuto):void 0;if(geometry&&x2===geometry.column&&y2>=geometry.trackTop&&y2<geometry.trackTop+geometry.trackHeight)return{scrollView,geometry}}}setScrollbarHover(scrollView){scrollView!==this.scrollbarHover&&(this.scrollbarHover?.setScrollbarActive(!1),this.scrollbarHover=scrollView,this.scrollbarHover?.setScrollbarActive(!0))}updateScrollbarHover(x2,y2){this.setScrollbarHover(this.getScrollbarTargetAt(x2,y2,!0)?.scrollView)}stopScrollbarHover(){this.setScrollbarHover(void 0)}scrollScrollbarToPointer(scrollView,geometry,pointerY,grabOffset){let maxThumbOffset=geometry.trackHeight-geometry.thumbHeight,thumbOffset=Math.max(0,Math.min(maxThumbOffset,pointerY-geometry.trackTop-grabOffset)),scrollTop=maxThumbOffset===0?0:Math.round(thumbOffset/maxThumbOffset*geometry.maxScrollTop);scrollView.scrollTo(scrollTop)}handleScrollbarMouseEvent(event){if(this.scrollbarDrag){if(event.release)return this.stopScrollbarDrag(),!0;let box=this.currentLayout?getScrollViewBox(this.currentLayout,this.scrollbarDrag.scrollView):void 0,geometry=box?getScrollbarGeometry(box):void 0;return geometry&&this.scrollScrollbarToPointer(this.scrollbarDrag.scrollView,geometry,event.y,this.scrollbarDrag.grabOffset),!0}if(event.release||(event.button&32)!==0||(event.button&3)!==0)return!1;let target=this.getScrollbarTargetAt(event.x,event.y);if(!target)return!1;this.stopSelectionAutoScroll(),this.selectionPressActive=!1,this.selectionAnchor=void 0,this.selectionFocus=void 0,this.selectionGranularity="character",this.selectionInitialRange=void 0,this.lastClick=void 0,this.pressedUrl=void 0,this.selectionDragged=!1,this.setScrollbarHover(target.scrollView);let onThumb=event.y>=target.geometry.thumbTop&&event.y<target.geometry.thumbTop+target.geometry.thumbHeight,grabOffset=onThumb?event.y-target.geometry.thumbTop:Math.floor(target.geometry.thumbHeight/2);return onThumb||this.scrollScrollbarToPointer(target.scrollView,target.geometry,event.y,grabOffset),this.scrollbarDrag={scrollView:target.scrollView,grabOffset},!0}stopScrollbarDrag(){this.scrollbarDrag=void 0}getScrollSelectionPoint(scrollView,x2,y2){if(!this.currentLayout)return;let box=getScrollViewBox(this.currentLayout,scrollView);if(!box||box.rect.height<=0||box.clip.height<=0)return;let visibleTop=Math.max(0,box.rect.y,box.clip.y),visibleBottom=Math.min(this.terminal.rows-1,box.rect.y+box.rect.height-1,box.clip.y+box.clip.height-1);if(visibleBottom<visibleTop)return;let pointerRow=Math.max(visibleTop,Math.min(visibleBottom,y2)),maxContentRow=Math.max(0,(box.scrollContentLines?.length??1)-1);return{row:Math.max(0,Math.min(maxContentRow,scrollView.scrollTop+pointerRow-box.rect.y)),col:Math.max(0,Math.min(box.rect.width-1,x2-box.rect.x)),scrollView}}getSelectionPoint(event,scrollView){if(scrollView){let point=this.getScrollSelectionPoint(scrollView,event.x,event.y);if(point)return point}return{row:Math.max(0,Math.min(this.terminal.rows-1,event.y)),col:Math.max(0,Math.min(this.terminal.columns-1,event.x))}}getSelectionSourceLine(point){if(point.scrollView&&this.currentLayout){let lines=getScrollViewBox(this.currentLayout,point.scrollView)?.scrollContentLines;if(lines)return lines[point.row]??""}return this.previousScreen[point.row]??""}getWordSelection(point){let line=stripTerminalSequences(this.getSelectionSourceLine(point)),segments=[],start=0;for(let segment of wordSegmenter4.segment(line)){let end=start+visibleWidth(segment.segment),joiner=TERMINAL_WORD_SELECTION_JOINERS.has(segment.segment);segments.push({start,end,selectable:segment.isWordLike===!0||joiner,joiner}),start=end}let clickedSegmentIndex=segments.findIndex(segment=>point.col>=segment.start&&point.col<segment.end);if(clickedSegmentIndex<0)return;let canJoin=(left,right)=>left.selectable&&right.selectable&&(left.joiner||right.joiner),selectionStart=segments[clickedSegmentIndex].start,selectionEnd=segments[clickedSegmentIndex].end;for(let index=clickedSegmentIndex;index>0&&canJoin(segments[index-1],segments[index]);index--)selectionStart=segments[index-1].start;for(let index=clickedSegmentIndex;index<segments.length-1&&canJoin(segments[index],segments[index+1]);index++)selectionEnd=segments[index+1].end;return{start:{...point,col:selectionStart},end:{...point,col:selectionEnd,boundary:!0}}}getLineSelection(point){return{start:{...point,col:0},end:{...point,col:visibleWidth(this.getSelectionSourceLine(point)),boundary:!0}}}updateSelectionFocus(point){if(this.selectionGranularity==="character"||!this.selectionInitialRange){this.selectionFocus=point;return}let range=this.selectionGranularity==="word"?this.getWordSelection(point):this.getLineSelection(point);if(!range)return;let initial=this.selectionInitialRange;range.start.row<initial.start.row||range.start.row===initial.start.row&&range.start.col<initial.start.col?(this.selectionAnchor=initial.end,this.selectionFocus=range.start):(this.selectionAnchor=initial.start,this.selectionFocus=range.end)}getClickCount(point,word){let now=Date.now(),previous=this.lastClick,count=word&&previous&&now-previous.timestamp<=DOUBLE_CLICK_INTERVAL_MS&&previous.row===point.row&&previous.scrollView===point.scrollView&&previous.wordStart===word.start.col&&previous.wordEnd===word.end.col?previous.count%3+1:1;return this.lastClick=word?{timestamp:now,count,row:point.row,scrollView:point.scrollView,wordStart:word.start.col,wordEnd:word.end.col}:void 0,count}updateSelectionAutoScroll(event){let scrollView=this.selectionAnchor?.scrollView;if(!scrollView||!this.currentLayout){this.stopSelectionAutoScroll();return}let box=getScrollViewBox(this.currentLayout,scrollView);if(!box||box.rect.height<=0||box.clip.height<=0){this.stopSelectionAutoScroll();return}let visibleTop=Math.max(0,box.rect.y,box.clip.y),visibleBottom=Math.min(this.terminal.rows-1,box.rect.y+box.rect.height-1,box.clip.y+box.clip.height-1);if(this.selectionDragPointer={x:event.x,y:event.y},this.selectionAutoScrollDirection=event.y<=visibleTop?-1:event.y>=visibleBottom?1:0,this.selectionAutoScrollDirection===0){this.stopSelectionAutoScroll();return}this.selectionAutoScrollTimer||(this.selectionAutoScrollTimer=setInterval(()=>this.autoScrollSelection(),50),this.selectionAutoScrollTimer.unref())}autoScrollSelection(){let scrollView=this.selectionAnchor?.scrollView,pointer=this.selectionDragPointer,direction=this.selectionAutoScrollDirection;if(!scrollView||!pointer||direction===0){this.stopSelectionAutoScroll();return}if(scrollView.scrollBy(direction)===direction){this.stopSelectionAutoScroll();return}let point=this.getScrollSelectionPoint(scrollView,pointer.x,pointer.y);point&&this.updateSelectionFocus(point),this.requestRender()}stopSelectionAutoScroll(){this.selectionAutoScrollTimer&&(clearInterval(this.selectionAutoScrollTimer),this.selectionAutoScrollTimer=void 0),this.selectionAutoScrollDirection=0,this.selectionDragPointer=void 0}handleSelectionMouseEvent(event){let button=event.button&3;if(button!==0&&!(event.release&&button===3))return;let anchorScrollView=this.selectionAnchor?.scrollView,point=this.getSelectionPoint(event,anchorScrollView);if(event.release){if(!this.selectionPressActive||(this.selectionPressActive=!1,this.stopSelectionAutoScroll(),!this.selectionAnchor))return;this.updateSelectionFocus(point);let isClick=!this.selectionDragged&&this.selectionAnchor.scrollView===point.scrollView&&this.selectionAnchor.row===point.row&&this.selectionAnchor.col===point.col,clickedUrl=isClick?this.pressedUrl:void 0;if(this.pressedUrl=void 0,clickedUrl&&this.openUrl){this.selectionAnchor=void 0,this.selectionFocus=void 0;try{this.openUrl(clickedUrl)}catch{}this.requestRender();return}if(isClick){let clickEvent=this.createMouseEvent("click",event.button,event.x,event.y,{clickCount:this.lastClick?.count??1}),overlay=this.dispatchMouseToOverlay(clickEvent),result=overlay.result??(overlay.hit?void 0:this.dispatchMouseToLayout(clickEvent));if(result){let render=this.applyMouseDispatchResult(clickEvent,result);this.clearTextSelection(),render&&this.requestRender();return}}this.copyOnSelect&&this.copySelectionToClipboard(),this.requestRender();return}if((event.button&32)!==0){if(!this.selectionPressActive||!this.selectionAnchor)return;this.selectionDragged=!0,this.lastClick=void 0,this.pressedUrl=void 0,this.updateSelectionFocus(point),this.updateSelectionAutoScroll(event),this.requestRender();return}this.stopSelectionAutoScroll(),this.selectionPressActive=!0;let scrollView=!this.hasOverlay()&&this.currentLayout?getScrollViewsAt(this.currentLayout,event.x,event.y)[0]:void 0,anchor=this.getSelectionPoint(event,scrollView),word=this.getWordSelection(anchor),clickCount=this.getClickCount(anchor,word),range=clickCount===2?word:clickCount===3?this.getLineSelection(anchor):void 0;this.selectionGranularity=range?clickCount===2?"word":"line":"character",this.selectionInitialRange=range,this.selectionAnchor=range?.start??anchor,this.selectionFocus=range?.end??anchor,this.selectionDragged=!1,this.pressedUrl=range?void 0:getOsc8LinkAtColumn(this.previousScreen[Math.max(0,Math.min(this.terminal.rows-1,event.y))]??"",Math.max(0,Math.min(this.terminal.columns-1,event.x))),this.requestRender()}getSelectionBounds(){if(!this.selectionAnchor||!this.selectionFocus||this.selectionAnchor.scrollView!==this.selectionFocus.scrollView)return;let anchorBeforeFocus=this.selectionAnchor.row<this.selectionFocus.row||this.selectionAnchor.row===this.selectionFocus.row&&this.selectionAnchor.col<this.selectionFocus.col;if(!(this.selectionAnchor.row===this.selectionFocus.row&&this.selectionAnchor.col===this.selectionFocus.col))return anchorBeforeFocus?{start:this.selectionAnchor,end:this.selectionFocus}:{start:this.selectionFocus,end:this.selectionAnchor}}getSelectionColumns(line,row,selection,minColumn=0,maxColumn=visibleWidth(line)){let lineWidth=visibleWidth(line),start=Math.max(0,minColumn),end=Math.min(lineWidth,maxColumn);return row===selection.start.row&&(start=getGraphemeCellRange(line,selection.start.col)?.start??Math.min(selection.start.col,lineWidth)),row===selection.end.row&&(end=selection.end.boundary?Math.min(selection.end.col,lineWidth):getGraphemeCellRange(line,selection.end.col)?.end??Math.min(selection.end.col+1,lineWidth)),{start:Math.max(minColumn,start),end:Math.min(maxColumn,end)}}getActiveSelectionText(){let selection=this.getSelectionBounds();if(!selection)return;let sourceLines=this.previousScreen;if(selection.start.scrollView){if(!this.currentLayout)return;let box=getScrollViewBox(this.currentLayout,selection.start.scrollView);if(!box?.scrollContentLines)return;sourceLines=box.scrollContentLines}let lines=[];for(let row=selection.start.row;row<=selection.end.row;row++){let line=sourceLines[row]??"",columns=this.getSelectionColumns(line,row,selection);lines.push(stripTerminalSequences(sliceByColumn(line,columns.start,Math.max(0,columns.end-columns.start),!0)).trimEnd())}let text=lines.join(`
110
110
  `);return text.length===0?void 0:text}async copySelectionToClipboard(){let text=this.getActiveSelectionText();return text?this.copyTextToClipboard(text):!1}async copyTextToClipboard(text){if(this.copySelection){let result=await this.copySelection(text),ok=result===!0;return this.flash(ok?"Copied!":typeof result=="string"?result:"Copy failed",ok?void 0:COPY_ERROR_FLASH_DURATION_MS),ok}return this.terminal.write(`\x1B]52;c;${Buffer.from(text).toString("base64")}\x07`),this.flash("Copied!"),!0}applySearchTextHighlight(text,current){let style=current?this.searchCurrentMatchStyle:this.searchMatchStyle,result="",plainStart=0,index=0;for(;index<text.length;){let ansi=extractAnsiCode(text,index);if(!ansi){index+=1;continue}index>plainStart&&(result+=style(text.slice(plainStart,index))),result+=ansi.code,index+=ansi.length,plainStart=index}return plainStart<text.length&&(result+=style(text.slice(plainStart))),result}applySearchHighlights(screen,layout){let search=this.activeSearch;if(!search||search.selectedIndex<0||search.matches.length===0)return screen;let scrollView=layout.primaryScrollView??this.implicitScrollView,box=getScrollViewBox(layout,scrollView);if(!box)return screen;let rangesByRow=new Map,scrollbarColumn=getScrollbarGeometry(box)?.column,minRow=Math.max(0,box.rect.y,box.clip.y),maxRow=Math.min(screen.length,box.rect.y+box.rect.height,box.clip.y+box.clip.height),minColumn=Math.max(0,box.rect.x,box.clip.x),maxColumn=Math.min(this.terminal.columns,box.rect.x+box.rect.width,box.clip.x+box.clip.width,scrollbarColumn??Number.POSITIVE_INFINITY),minContentRow=scrollView.scrollTop+minRow-box.rect.y,maxContentRow=scrollView.scrollTop+maxRow-box.rect.y-1,low=0,high=search.matches.length;for(;low<high;){let middle=low+Math.floor((high-low)/2),match=search.matches[middle];(match.segments[match.segments.length-1]?.row??-1)<minContentRow?low=middle+1:high=middle}for(let matchIndex=low;matchIndex<search.matches.length;matchIndex++){let match=search.matches[matchIndex];if((match.segments[0]?.row??0)>maxContentRow)break;for(let segment of match.segments){let row=box.rect.y+segment.row-scrollView.scrollTop;if(row<minRow||row>=maxRow)continue;let startCol=Math.max(minColumn,box.rect.x+segment.startCol),endCol=Math.min(maxColumn,box.rect.x+segment.endCol);if(endCol<=startCol)continue;let ranges=rangesByRow.get(row)??[];ranges.push({startCol,endCol,current:matchIndex===search.selectedIndex}),rangesByRow.set(row,ranges)}}let result=[...screen];for(let[row,ranges]of rangesByRow){let line=result[row]??"";if(isImageLine(line))continue;let lineWidth=visibleWidth(line);for(let range of ranges.sort((a,b2)=>b2.startCol-a.startCol)){let startCol=Math.min(range.startCol,lineWidth),endCol=Math.min(range.endCol,lineWidth);if(endCol<=startCol)continue;let before=sliceByColumn(line,0,startCol,!0),highlighted=sliceByColumn(line,startCol,endCol-startCol,!0),after=sliceByColumn(line,endCol,Math.max(0,lineWidth-endCol),!0);line=`${before}${this.applySearchTextHighlight(highlighted,range.current)}${after}`}result[row]=line}return result}applySelectionHighlight(text){let result="\x1B[7m",index=0;for(;index<text.length;){let ansi=extractAnsiCode(text,index);if(!ansi){result+=text[index],index+=1;continue}result+=ansi.code,ansi.code.endsWith("m")&&(result+="\x1B[7m"),index+=ansi.length}return`${result}\x1B[27m`}applySelection(screen,layout=this.currentLayout){let selection=this.getSelectionBounds();if(!selection)return screen;let screenSelection=selection,minRow=0,maxRow=screen.length-1,minColumn=0,maxColumn=this.terminal.columns;if(selection.start.scrollView){if(!layout)return screen;let box=getScrollViewBox(layout,selection.start.scrollView);if(!box)return screen;minRow=Math.max(0,box.rect.y,box.clip.y),maxRow=Math.min(screen.length-1,box.rect.y+box.rect.height-1,box.clip.y+box.clip.height-1),minColumn=Math.max(0,box.rect.x,box.clip.x),maxColumn=Math.min(this.terminal.columns,box.rect.x+box.rect.width,box.clip.x+box.clip.width),screenSelection={start:{...selection.start,row:box.rect.y+selection.start.row-selection.start.scrollView.scrollTop,col:box.rect.x+selection.start.col},end:{...selection.end,row:box.rect.y+selection.end.row-selection.start.scrollView.scrollTop,col:box.rect.x+selection.end.col}}}return screen.map((line,row)=>{if(row<minRow||row>maxRow||row<screenSelection.start.row||row>screenSelection.end.row||isImageLine(line))return line;let lineWidth=visibleWidth(line),columns=this.getSelectionColumns(line,row,screenSelection,minColumn,maxColumn);if(columns.end<=columns.start)return line;let before=sliceByColumn(line,0,columns.start,!0),selected=sliceByColumn(line,columns.start,columns.end-columns.start,!0),after=sliceByColumn(line,columns.end,Math.max(0,lineWidth-columns.end),!0);return`${before}${this.applySelectionHighlight(selected)}${after}`})}isMouseSequence(data){return/^\x1b\[<\d+;\d+;\d+[Mm]$/.test(data)||data.length===6&&data.startsWith("\x1B[M")}compositeScrollToEndIndicator(screen,layout,width){this.scrollToEndIndicatorRect=void 0;let scrollView=layout.primaryScrollView??this.implicitScrollView;if(!this.scrollToEndIndicator||!scrollView.followEnd||scrollView.isFollowingEnd)return screen;let box=getScrollViewBox(layout,scrollView),clip=box?.clip;if(!clip||clip.width<=0||clip.height<=0)return screen;let row=clip.y+clip.height-1;if(row>=screen.length||isImageLine(screen[row]??""))return screen;let scrollbarColumn=box?getScrollbarGeometry(box)?.column:void 0,label=truncateToWidth(this.scrollToEndIndicator(),clip.width,""),labelWidth=visibleWidth(label),column=clip.x+Math.floor((clip.width-labelWidth)/2),rightEdge=scrollbarColumn??clip.x+clip.width,availableWidth=Math.max(0,rightEdge-column),text=truncateToWidth(label,availableWidth,""),textWidth=visibleWidth(text);if(textWidth===0)return screen;let result=[...screen];return result[row]=compositeTuiLine(result[row]??"",text,column,textWidth,width),this.scrollToEndIndicatorRect={row,column,width:textWidth},result}compositeFlashes(screen,width,height){let flashLines=this.flashes.render(width).slice(-height);if(flashLines.length===0)return screen;let result=[...screen];for(;result.length<height;)result.push("");for(let row=0;row<flashLines.length;row++){let line=flashLines[row],flashWidth=visibleWidth(line);flashWidth!==0&&(result[row]=compositeTuiLine(result[row]??"",line,width-flashWidth,flashWidth,width))}return result}doRender(){if(this.stopped||!this.altScreenActive)return;let width=Math.max(1,this.terminal.columns),height=Math.max(1,this.terminal.rows),root=this.layoutRoot??this.implicitScrollView,nextLayout=renderLayoutFrame(root,width,height,()=>this.requestRender());this.refreshSearch(nextLayout)&&(nextLayout=renderLayoutFrame(root,width,height,()=>this.requestRender()));let screen=this.resolveFakeCursors(nextLayout.lines.map(line=>line.replace(OSC133_ZONE_PREFIX2,"")));screen=this.applySearchHighlights(screen,nextLayout),screen=this.compositeScrollToEndIndicator(screen,nextLayout,width),screen=this.compositeOverlays(screen,width,height),screen.length>height&&(screen=screen.slice(screen.length-height)),screen=this.applySelection(screen,nextLayout),screen=this.compositeFlashes(screen,width,height);let cursorPos=this.extractCursorPosition(screen,height);screen=this.applyLineResets(screen).map(line=>isImageLine(line)||visibleWidth(line)<=width?line:sliceByColumn(line,0,width,!0));let fullRedraw=this.previousScreen.length===0||this.previousScreenWidth!==width||this.previousScreenHeight!==height,changedRows=screen.map((line,row)=>line!==this.previousScreen[row]),imageAnchorsNeedRedraw=screen.some((line,row)=>changedRows[row]&&(isImageLine(line)||isImageLine(this.previousScreen[row]??""))),isWezTerm=!!process.env.WEZTERM_PANE||process.env.TERM_PROGRAM?.toLowerCase()==="wezterm",imageCellsNeedRedraw=!imageAnchorsNeedRedraw&&isWezTerm&&this.imageProtocol==="kitty"&&changedRows.some(Boolean)&&screen.some((line,row)=>{let placementRows=getKittyImagePlacementRows(line);if(placementRows===void 0)return!1;for(let coveredRow=row;coveredRow<row+placementRows;coveredRow++)if(changedRows[coveredRow])return!0;return!1}),imagesNeedRedraw=imageAnchorsNeedRedraw||imageCellsNeedRedraw,redrawImages=fullRedraw||imagesNeedRedraw,hadUploadedKittyImages=this.uploadedKittyImages.size>0,preparedKittyScreen=redrawImages&&this.imageProtocol==="kitty"?this.prepareKittyScreen(screen):{lines:screen,evictedImageDeletion:""},buffer=BEGIN_SYNCHRONIZED_OUTPUT;if(fullRedraw){this.fullRedrawCount+=1;let clearImages=this.imageProtocol==="kitty"&&hadUploadedKittyImages?deleteAllKittyPlacements():this.deleteKittyImages();buffer+=`${clearImages}\x1B[2J`}else imagesNeedRedraw&&(this.imageProtocol==="iterm2"?buffer+="\x1B[2J":this.imageProtocol==="kitty"&&(buffer+=deleteAllKittyPlacements()));if(buffer+=preparedKittyScreen.evictedImageDeletion,redrawImages&&this.imageProtocol==="kitty"&&screen.some(isImageLine)&&isWezTerm){for(let row=0;row<height;row++)!fullRedraw&&!imagesNeedRedraw&&screen[row]===this.previousScreen[row]||(buffer+=`\x1B[${row+1};1H\x1B[2K`);for(let row=0;row<height;row++)!fullRedraw&&!imagesNeedRedraw&&screen[row]===this.previousScreen[row]||isImageLine(preparedKittyScreen.lines[row]??"")||(buffer+=`\x1B[${row+1};1H${preparedKittyScreen.lines[row]??""}`);for(let row=0;row<height;row++)!fullRedraw&&!imagesNeedRedraw&&screen[row]===this.previousScreen[row]||isImageLine(preparedKittyScreen.lines[row]??"")&&(buffer+=`\x1B[${row+1};1H${preparedKittyScreen.lines[row]??""}`)}else for(let row=0;row<height;row++)!fullRedraw&&!imagesNeedRedraw&&screen[row]===this.previousScreen[row]||(buffer+=`\x1B[${row+1};1H\x1B[2K${preparedKittyScreen.lines[row]??""}`);cursorPos?(buffer+=`\x1B[${cursorPos.row+1};${Math.min(width,cursorPos.col)+1}H`,buffer+=this.getShowHardwareCursor()?"\x1B[?25h":"\x1B[?25l"):buffer+="\x1B[?25l",buffer+=END_SYNCHRONIZED_OUTPUT,this.terminal.write(buffer),this.previousScreen=screen,this.previousScreenWidth=width,this.previousScreenHeight=height,this.currentLayout=nextLayout}};import*as fs2 from"node:fs";import*as os from"node:os";import*as path3 from"node:path";var KITTY_SEQUENCE_PREFIX="\x1B_G",MAX_RENDER_WRITE_CHARS=1024*1024,BoundedTerminalWriter=class{buffer="";writtenChars=0;write;constructor(write){this.write=write}append(value){let offset=0;for(;offset<value.length;){let capacity=MAX_RENDER_WRITE_CHARS-this.buffer.length;if(capacity===0){this.flush();continue}let end=Math.min(value.length,offset+capacity);if(end<value.length&&value.charCodeAt(end-1)>=55296&&value.charCodeAt(end-1)<=56319&&value.charCodeAt(end)>=56320&&value.charCodeAt(end)<=57343&&end--,end===offset){this.flush();continue}this.buffer+=value.slice(offset,end),offset=end,this.buffer.length===MAX_RENDER_WRITE_CHARS&&this.flush()}}flush(){this.buffer&&(this.write(this.buffer),this.writtenChars+=this.buffer.length,this.buffer="")}get length(){return this.writtenChars+this.buffer.length}};function parseKittyImageHeader(line){let sequenceStart=line.indexOf(KITTY_SEQUENCE_PREFIX);if(sequenceStart===-1)return;let paramsStart=sequenceStart+KITTY_SEQUENCE_PREFIX.length,paramsEnd=line.indexOf(";",paramsStart);if(paramsEnd===-1)return;let ids=[],rows=1;for(let param of line.slice(paramsStart,paramsEnd).split(",")){let[key,value]=param.split("=",2);if(value===void 0)continue;let numberValue=Number(value);!Number.isInteger(numberValue)||numberValue<=0||numberValue>4294967295||(key==="i"?ids.push(numberValue):key==="r"&&(rows=numberValue))}return{ids,rows}}function extractKittyImageIds(line){return parseKittyImageHeader(line)?.ids??[]}function extractKittyImageRows(line){return parseKittyImageHeader(line)?.rows??1}function isTermuxSession(){return!!process.env.TERMUX_VERSION}var TuiMainScreen=class extends TuiBase{mode="regular";previousLines=[];previousKittyImageIds=new Set;previousWidth=0;previousHeight=0;cursorRow=0;hardwareCursorRow=0;maxLinesRendered=0;previousViewportTop=0;captureRenderState(){return{previousLines:[...this.previousLines],previousWidth:this.previousWidth,previousHeight:this.previousHeight,cursorRow:this.cursorRow,hardwareCursorRow:this.hardwareCursorRow,maxLinesRendered:this.maxLinesRendered,previousViewportTop:this.previousViewportTop}}restoreRenderState(state){this.previousLines=state.previousLines.map(line=>isImageLine(line)?"":line),this.previousKittyImageIds=new Set,this.previousWidth=state.previousWidth,this.previousHeight=state.previousHeight,this.cursorRow=state.cursorRow,this.hardwareCursorRow=state.hardwareCursorRow,this.maxLinesRendered=state.maxLinesRendered,this.previousViewportTop=state.previousViewportTop}resetRenderState(){this.previousLines=[],this.previousWidth=-1,this.previousHeight=-1,this.cursorRow=0,this.hardwareCursorRow=0,this.maxLinesRendered=0,this.previousViewportTop=0}beforeTerminalStop(options){if(options.preserveScreen||this.previousLines.length===0)return;this.terminal.write(" ");let lineDiff=this.previousLines.length-this.hardwareCursorRow;lineDiff>0?this.terminal.write(`\x1B[${lineDiff}B`):lineDiff<0&&this.terminal.write(`\x1B[${-lineDiff}A`),this.terminal.write(`\r
@@ -98,6 +98,36 @@ FROM session_v2 s JOIN tree ON s.id = tree.id WHERE s.time_updated > ? ORDER BY
98
98
  const LEGACY_SQL = `${tree("session")}
99
99
  SELECT s.title, s.agent, s.time_created AS created, s.time_updated AS updated, (SELECT data FROM message m WHERE m.session_id = s.id ORDER BY m.time_created DESC LIMIT 1) AS last
100
100
  FROM session s JOIN tree ON s.id = tree.id WHERE s.time_updated > ? ORDER BY s.time_created`;
101
+ // `external` é o transporte ("acp"), não o agente: olhar o nome e o executável (owner 2026-11-25, subagentes sumiam)
102
+ export const isOpencode = (agent: any) => /opencode/i.test(`${agent?.name ?? ""} ${agent?.bin ?? ""}`);
103
+ // o que o agente não viu: a conversa depois da última resposta dele (ou toda, se ele nunca falou nesta sessão), com o modelo
104
+ // do Pink e outros agentes; vai antes do pedido para ele continuar de onde o outro parou (owner 2026-11-26)
105
+ const textOfContent = (content: any) => (typeof content === "string" ? content : (content ?? []).filter((part: any) => part?.type === "text").map((part: any) => part.text).join("\n")).trim();
106
+ export function contextFor(entries: any[] | undefined, agent: string, max = 16000): string {
107
+ const list = entries ?? [];
108
+ let from = 0;
109
+ list.forEach((entry, index) => {
110
+ if (entry?.type === "custom_message" && entry.customType === "pink-agente" && entry.details?.agent === agent) from = index + 1;
111
+ });
112
+ const lines = list.slice(from).map((entry) => {
113
+ if (entry?.type === "message" && entry.message?.role === "user") return `${t("Pessoa", "Persona", "User")}: ${textOfContent(entry.message.content)}`;
114
+ if (entry?.type === "message" && entry.message?.role === "assistant") {
115
+ const text = textOfContent(entry.message.content);
116
+ return text ? `${t("Modelo do Pink", "Modelo de Pink", "Pink model")}${entry.message.model ? ` (${entry.message.model})` : ""}: ${text}` : "";
117
+ }
118
+ if (entry?.type === "custom_message" && entry.customType === "pink-agente-pedido") return `${t("Pessoa", "Persona", "User")} → ${entry.details?.agent}: ${entry.details?.text ?? ""}`;
119
+ if (entry?.type === "custom_message" && entry.customType === "pink-agente") return `${entry.details?.agent}: ${textOfContent(entry.content)}`;
120
+ return "";
121
+ }).filter((line) => line.replace(/^[^:]*:\s*/, "").trim());
122
+ if (!lines.length) return "";
123
+ let body = lines.join("\n\n");
124
+ if (body.length > max) body = `…${body.slice(body.length - max)}`; // shortcut: corta pelo começo; um resumo pelo modelo seria melhor em conversa muito longa
125
+ return `${t("Contexto: antes deste pedido a conversa no Pink seguiu sem você. O que aconteceu:", "Contexto: antes de este pedido la conversación en Pink siguió sin ti. Lo que pasó:", "Context: before this request the conversation in Pink went on without you. What happened:")}\n\n${body}\n\n${t("Pedido atual:", "Pedido actual:", "Current request:")}`;
126
+ }
127
+
128
+ // o pedido que o agente largou ao trocarem o modelo, para o novo modelo do Pink continuar
129
+ export const handoffText = (agent: string, asks: string[]) =>
130
+ `${t(`O ${agent} foi interrompido na troca de modelo. O que ele já fez está acima; continue este pedido:`, `${agent} fue interrumpido al cambiar de modelo. Lo que ya hizo está arriba; continúa este pedido:`, `${agent} was stopped by the model switch. What it already did is above; continue this request:`)}\n\n${asks.filter((ask) => ask.trim()).join("\n\n")}`;
101
131
  export const CHILD_DONE_SHOWN_MS = 15000;
102
132
  function childState(row: any): { state: "running" | "paused" | "done" | "failed" | "stopped"; end?: number } {
103
133
  if (row.last === undefined) {
@@ -306,7 +336,7 @@ export async function pick(ctx: any, title: string, options: string[], load: ()
306
336
  export default function (pink: any, list: typeof externalAgents = externalAgents, run: typeof runExternal = runExternal, models: typeof listModels = listModels, extras: (tela?: { pipe: string; key: string }) => any = (tela) => gatherExtras(pink, undefined, tela), load: () => Promise<any[]> = loadTui, bridge: typeof telaBridge = telaBridge, warm: typeof warmKept = run === runExternal ? warmKept : () => undefined) {
307
337
  let screen: ReturnType<typeof telaBridge> | undefined; // pink_tela: aberto no primeiro /agente, fechado ao sair do Pink
308
338
  let screenCtx: any; // a janela deste Pink, onde a tela pede confirmação
309
- let active: { agent: any; resume: any; controller?: AbortController; queue?: string[]; live?: any } | undefined;
339
+ let active: { agent: any; resume: any; controller?: AbortController; queue?: string[]; live?: any; handoff?: string[] } | undefined;
310
340
  let ticker: ReturnType<typeof setInterval> | undefined;
311
341
  let lastUi: any;
312
342
 
@@ -342,7 +372,7 @@ export default function (pink: any, list: typeof externalAgents = externalAgents
342
372
  ticker = setInterval(() => loader?.setMessage?.(message()), 1000);
343
373
  } else {
344
374
  let frame = 0;
345
- const draw = () => ui.setWidget(WIDGET, (_screen: any, theme: any) => ({ render: (width: number) => around([` ${FRAMES[frame % FRAMES.length]} ${message()}`], width, theme), invalidate() {} }), { placement: "aboveEditor" });
375
+ const draw = () => ui.setWidget(WIDGET, (screen: any, theme: any) => ((screenRef = screen), { render: (width: number) => around([` ${FRAMES[frame % FRAMES.length]} ${message()}`], width, theme), invalidate() {} }), { placement: "aboveEditor" });
346
376
  draw();
347
377
  ticker = setInterval(() => (frame++, draw()), 120);
348
378
  }
@@ -362,12 +392,12 @@ export default function (pink: any, list: typeof externalAgents = externalAgents
362
392
  if (childTimer || !ui?.setWidget) return;
363
393
  const tick = () => {
364
394
  // opencode: o banco dele mostra também os de segundo plano; os outros (e o opencode sem node:sqlite): o fluxo
365
- const opencode = /opencode/i.test(String(active?.agent?.external ?? active?.agent?.name ?? ""));
395
+ const opencode = isOpencode(active?.agent);
366
396
  const fromDb = opencode && active?.resume?.id ? read(dbFile, active.resume.id) : [];
367
397
  const items = fromDb.length ? fromDb : liveAgents(active?.live, Date.now());
368
398
  (globalThis as any).__pinkAgentChildren = items; // a lateral mostra em SUBAGENTES, abaixo da SESSÃO
369
399
  if (!items.length && !active?.controller) return stopChildren(ui);
370
- const side = Date.now() - Number((globalThis as any).__pinkSideAt ?? 0) < 5000; // lateral desenhada há pouco: está na tela
400
+ const side = (globalThis as any).__pinkRightOn === true; // lateral ligada (pink-ui): os subagentes ficam só nela, como os do Pink
371
401
  ui.setWidget(CHILDREN, items.length && !side ? (_screen: any, theme: any) => ({
372
402
  render: (width: number) => items.map((item: any) => {
373
403
  const clock = item.clock ?? elapsedLabel(Date.now() - item.started);
@@ -495,7 +525,11 @@ export default function (pink: any, list: typeof externalAgents = externalAgents
495
525
  const controller = new AbortController();
496
526
  current.controller = controller;
497
527
  const name = current.agent.name;
528
+ const before = contextFor(ctx.sessionManager?.getBranch?.(), name); // antes de gravar o pedido: só o que veio antes dele
498
529
  pink.sendMessage({ customType: "pink-agente-pedido", display: true, content: `› ${name}: ${text}`, details: { agent: name, text } });
530
+ // o mesmo começo e fim de turno do modelo do Pink (o círculo do mux, o ponto do /undo, o título, a coluna de sessões,
531
+ // a notificação e o hook Stop reagem a eles); owner 2026-11-26: "/agente tem que funcionar como um modelo logado"
532
+ pink.events?.emit?.("pink:agent_start", { ctx });
499
533
  const result = fresh();
500
534
  current.live = result; // os subagentes desta mensagem (liveAgents)
501
535
  const started = Date.now();
@@ -509,7 +543,7 @@ export default function (pink: any, list: typeof externalAgents = externalAgents
509
543
  if (ctx.hasUI) watchChildren(ctx.ui);
510
544
  (globalThis as any).__pinkExternalAsk = ctx.hasUI ? (title: string, body: string) => ctx.ui.confirm(title, body) : undefined;
511
545
  try {
512
- await run(current.agent, text, ctx.cwd, controller.signal, result, status, undefined, undefined, current.resume);
546
+ await run(current.agent, before ? `${before}\n${text}` : text, ctx.cwd, controller.signal, result, status, undefined, undefined, current.resume);
513
547
  } catch (error: any) {
514
548
  result.stopReason = "error";
515
549
  result.errorMessage = controller.signal.aborted ? t("cancelado", "cancelado", "cancelled") : String(error?.message ?? error);
@@ -524,6 +558,9 @@ export default function (pink: any, list: typeof externalAgents = externalAgents
524
558
  }
525
559
  const error = result.stopReason === "error" ? String(result.errorMessage ?? t("erro", "error", "error")) : undefined;
526
560
  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) } });
561
+ pink.events?.emit?.("pink:agent_settled", { ctx, aborted: controller.signal.aborted });
562
+ // trocaram o modelo do Pink no meio: o que o agente fez já está na sessão; o novo modelo continua o pedido
563
+ if (current.handoff) return void pink.sendUserMessage?.(handoffText(name, [text, ...current.handoff]));
527
564
  // a fila sai agora, numa mensagem só (como o Claude Code junta o que você digitou enquanto ele trabalhava)
528
565
  if (active === current && current.queue?.length) {
529
566
  const next = current.queue.join("\n\n");
@@ -623,6 +660,12 @@ export default function (pink: any, list: typeof externalAgents = externalAgents
623
660
  }
624
661
  }
625
662
  }
663
+ // o modelo do Pink estava respondendo: para agora e o agente continua o pedido (só um trabalha; owner 2026-11-26)
664
+ const busyAsk = ctx.isIdle?.() === false ? [...(ctx.sessionManager?.getBranch?.() ?? [])].reverse().find((entry: any) => entry?.type === "message" && entry.message?.role === "user") : undefined;
665
+ if (busyAsk) {
666
+ ctx.abort?.();
667
+ await ctx.waitForIdle?.();
668
+ }
626
669
  stop(ctx);
627
670
  // mesma sessão do Pink + mesmo agente: continua a conversa dele (owner 2026-11-24); sessão nova do Pink começa do zero
628
671
  const saved = lastAgentSession(ctx.sessionManager?.getBranch?.(), agent.name);
@@ -632,6 +675,7 @@ export default function (pink: any, list: typeof externalAgents = externalAgents
632
675
  ctx.ui?.setStatus?.(STATUS, `${t("agente", "agente", "agent")}: ${label(active.agent)}`);
633
676
  const again = saved ? t(" Continuando a conversa anterior dele.", " Continuando su conversación anterior.", " Continuing its previous conversation.") : "";
634
677
  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");
678
+ if (busyAsk) void send(handoffText(t("modelo do Pink", "modelo de Pink", "Pink model"), [textOfContent(busyAsk.message.content)]), ctx);
635
679
  },
636
680
  });
637
681
 
@@ -648,6 +692,16 @@ export default function (pink: any, list: typeof externalAgents = externalAgents
648
692
  return { action: "handled" };
649
693
  });
650
694
 
695
+ // escolher um modelo do Pink com o agente ligado volta ao Pink na hora: só um trabalha (owner 2026-11-25, os dois rodavam juntos)
696
+ pink.on("model_select", (event: any, ctx: any) => {
697
+ if (!active || event?.source === "restore") return;
698
+ const current = active;
699
+ const was = current.agent.name;
700
+ if (current.controller) current.handoff = [...(current.queue ?? [])];
701
+ stop(ctx);
702
+ ctx?.ui?.notify?.(t(`Voltou ao Pink (${was} desligado).`, `Volviste a Pink (${was} apagado).`, `Back to Pink (${was} off).`), "info");
703
+ });
704
+
651
705
  pink.on("session_shutdown", () => {
652
706
  stop();
653
707
  screen?.close();
@@ -130,6 +130,8 @@ export function hooksExtension(pink, deps = {}) {
130
130
  pink.on("agent_settled", async (event, ctx) => {
131
131
  await fire("Stop", ctx, { aborted: Boolean(event?.aborted) });
132
132
  });
133
+ // o /agente também termina um turno: o hook Stop roda igual (owner 2026-11-26)
134
+ pink.events?.on?.("pink:agent_settled", (data) => void Promise.resolve(fire("Stop", data?.ctx, { aborted: Boolean(data?.aborted) })).catch(() => undefined));
133
135
  pink.registerCommand?.("hooks", {
134
136
  description: t("Mostra os hooks em uso (usuário e projeto confiável)", "Muestra los hooks en uso (usuario y proyecto de confianza)", "Shows the hooks in use (user and trusted project)"),
135
137
  handler: async (_args, ctx) => {
@@ -84,13 +84,18 @@ export function notifyExtension(pink, deps = {}) {
84
84
  state.unsubscribe?.();
85
85
  out.write("\x1b[?1004l");
86
86
  });
87
- pink.on("agent_start", async () => { if (!state.start) state.start = now(); });
88
- pink.on("agent_settled", async (event, ctx) => {
87
+ const started = () => { if (!state.start) state.start = now(); };
88
+ const settled = (event, ctx) => {
89
89
  const elapsed = state.start ? now() - state.start : 0;
90
90
  state.start = 0;
91
91
  if (!state.active || event?.aborted || !shouldNotify({ on, focused: state.focused, focusKnown: state.focusKnown, elapsed })) return;
92
92
  send("Pink", t(`Terminou em ${path.basename(ctx?.cwd ?? process.cwd())}: pronto para o próximo pedido`, `Terminó en ${path.basename(ctx?.cwd ?? process.cwd())}: listo para el próximo pedido`, `Finished in ${path.basename(ctx?.cwd ?? process.cwd())}: ready for the next request`));
93
- });
93
+ };
94
+ pink.on("agent_start", async () => started());
95
+ pink.on("agent_settled", async (event, ctx) => settled(event, ctx));
96
+ // o /agente avisa pelo barramento (owner 2026-11-26: funciona como um modelo logado)
97
+ pink.events?.on?.("pink:agent_start", started);
98
+ pink.events?.on?.("pink:agent_settled", (data) => settled(data, data?.ctx));
94
99
  pink.registerCommand?.("notificacoes", {
95
100
  description: t("Liga ou desliga a notificação do sistema quando o Pink termina e a janela está sem foco", "Activa o desactiva la notificación del sistema cuando Pink termina y la ventana no tiene el foco", "Turns the system notification on or off when Pink finishes and the window is not focused"),
96
101
  handler: async (_args, ctx) => {
@@ -201,8 +201,11 @@ export function todosFromBranch(entries) {
201
201
 
202
202
  // /undo e /redo como no OpenCode: voltam a conversa E os arquivos. Os arquivos vão para um índice do Git só do Pink
203
203
  // (GIT_INDEX_FILE à parte): o índice, o HEAD e o stash do usuário não mudam; arquivos ignorados pelo .gitignore ficam de fora.
204
+ // um pedido da pessoa: a mensagem dela ao modelo do Pink ou ao /agente (que fica na sessão como custom_message)
205
+ export const isAsk = (entry) => (entry?.type === "message" && entry.message?.role === "user") || (entry?.type === "custom_message" && entry.customType === "pink-agente-pedido");
206
+
204
207
  export function lastUserEntry(branch) {
205
- return [...(branch ?? [])].reverse().find((entry) => entry?.type === "message" && entry.message?.role === "user");
208
+ return [...(branch ?? [])].reverse().find(isAsk);
206
209
  }
207
210
 
208
211
  export function parseNameStatus(text) {
@@ -819,10 +822,13 @@ export function install(pink, ctx, { CustomEditor, SessionManager, version = "",
819
822
  };
820
823
  // sessão do multiplexador (pink/mux): progresso (OSC 9;4) enquanto trabalha e sino ao terminar, para a lateral mostrar o estado
821
824
  const signal = (text) => process.env.PINK_MUX_CHILD === "1" && process.stdout.isTTY && process.stdout.write(text);
822
- pink.on("agent_start", () => {
825
+ const runStarted = () => {
823
826
  signal("\x1b]9;4;3\x07");
824
827
  leaveHome();
825
- });
828
+ };
829
+ pink.on("agent_start", runStarted);
830
+ // o /agente roda fora do ciclo do Pink e avisa pelo barramento: o resto reage como a um modelo logado (owner 2026-11-26)
831
+ pink.events?.on?.("pink:agent_start", runStarted);
826
832
  pink.on("input", leaveHome);
827
833
  void pink.exec?.("git", ["branch", "--show-current"], { cwd: ctx.cwd }).then((result) => {
828
834
  state.branch = (result?.stdout ?? "").trim();
@@ -835,7 +841,7 @@ export function install(pink, ctx, { CustomEditor, SessionManager, version = "",
835
841
  }).catch(() => undefined);
836
842
  loadSessions();
837
843
  PINK.refreshSessions = loadSessions; // o "Apagar sessão" relê a coluna depois de mover o arquivo
838
- pink.on("agent_end", () => {
844
+ const runEnded = () => {
839
845
  signal("\x1b]9;4;0\x07\x07");
840
846
  // o multiplexador guarda o arquivo de cada sessão aberta para reabri-la no próximo Pink (card 1dfwh7kfyty)
841
847
  const file = ctx.sessionManager?.getSessionFile?.();
@@ -846,7 +852,9 @@ export function install(pink, ctx, { CustomEditor, SessionManager, version = "",
846
852
  if (title) pink.setSessionName?.(title);
847
853
  }
848
854
  loadSessions();
849
- });
855
+ };
856
+ pink.on("agent_end", runEnded);
857
+ pink.events?.on?.("pink:agent_settled", runEnded);
850
858
 
851
859
  // a moldura só existe na tela cheia; no modo regular do Pink (--tui-mode regular) fica o rodapé de uma linha
852
860
  const framed = () => (state.tui?.mode ?? "fullscreen") === "fullscreen";
@@ -1075,7 +1083,6 @@ export function install(pink, ctx, { CustomEditor, SessionManager, version = "",
1075
1083
  if (PINK.thothOn) startThoth();
1076
1084
  const stats = sessionStats(ctx.sessionManager?.getEntries?.());
1077
1085
  const total = stats.models.reduce((sum, item) => ({ input: sum.input + item.input, output: sum.output + item.output }), { input: 0, output: 0 });
1078
- globalThis.__pinkSideAt = Date.now(); // pink-agente: com a lateral na tela, os subagentes ficam só nela
1079
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 ?? [])] } });
1080
1087
  }, []),
1081
1088
  };
@@ -1119,9 +1126,9 @@ export function relativeTime(when, now = new Date()) {
1119
1126
  // título automático: a primeira mensagem do usuário com mais de 3 palavras (as sessões ficavam todas "oi")
1120
1127
  export function autoTitle(entries, max = 50) {
1121
1128
  for (const entry of entries ?? []) {
1122
- const message = entry?.type === "message" ? entry.message : undefined;
1123
- if (message?.role !== "user") continue;
1124
- const content = Array.isArray(message.content) ? message.content.filter((part) => part?.type === "text").map((part) => part.text).join(" ") : message.content;
1129
+ if (!isAsk(entry)) continue;
1130
+ const message = entry.message;
1131
+ const content = entry.type === "custom_message" ? entry.details?.text : Array.isArray(message.content) ? message.content.filter((part) => part?.type === "text").map((part) => part.text).join(" ") : message.content;
1125
1132
  const text = String(content ?? "").replace(/\s+/g, " ").trim();
1126
1133
  if (text.startsWith("/") || text.split(" ").length <= 3) continue;
1127
1134
  return text.length > max ? `${text.slice(0, max - 1)}…` : text;
@@ -1440,6 +1447,7 @@ export function skipThinking(message) {
1440
1447
  }
1441
1448
 
1442
1449
  function userText(entry) {
1450
+ if (entry?.type === "custom_message") return String(entry.details?.text ?? "");
1443
1451
  const content = entry?.message?.content;
1444
1452
  return Array.isArray(content) ? content.filter((part) => part?.type === "text").map((part) => part.text).join("\n") : String(content ?? "");
1445
1453
  }
@@ -1574,9 +1582,10 @@ function registerOpenCodeFunctions(pink) {
1574
1582
  PINK.runTimer = setInterval(show, 1000);
1575
1583
  PINK.runTimer.unref?.();
1576
1584
  // uma linha vazia entre o "Trabalhando" e a caixa; o relógio de cima (1 s) redesenha a tela e a lista de baixo junto
1577
- ctx.ui.setWidget?.(ABOVE_BOX, [""], { placement: "aboveEditor" });
1585
+ // fábrica, não [""]: a lista vira Text(""), que não desenha nada, e o "Trabalhando" ficava colado (owner 2026-11-25)
1586
+ ctx.ui.setWidget?.(ABOVE_BOX, () => ({ render: () => [""], invalidate() {} }), { placement: "aboveEditor" });
1578
1587
  ctx.ui.setWidget?.(BELOW_BOX, (_tui, theme) => ({
1579
- render: (width) => belowBox(theme, width, { agents: [...runningSubagents(PINK.subagents), ...dagAgentsCached(ctx.cwd)], side: Date.now() - (globalThis.__pinkSideAt ?? 0) < 5000 }),
1588
+ render: (width) => belowBox(theme, width, { agents: [...runningSubagents(PINK.subagents), ...dagAgentsCached(ctx.cwd)], side: globalThis.__pinkRightOn === true }),
1580
1589
  invalidate() {},
1581
1590
  }), { placement: "belowEditor" });
1582
1591
  });
@@ -1590,16 +1599,18 @@ function registerOpenCodeFunctions(pink) {
1590
1599
  [PINK.lastRun, PINK.lastRunEnd, PINK.run, PINK.runShow] = [PINK.run, Date.now(), undefined, undefined];
1591
1600
  });
1592
1601
  // ponto de restauração dos arquivos antes de cada mensagem (só na TUI, só num repositório Git)
1593
- pink.on("agent_start", async (_event, ctx) => {
1594
- const leaf = ctx.sessionManager?.getLeafEntry?.();
1595
- if (ctx.mode !== "tui" || leaf?.type !== "message" || leaf.message?.role !== "user") return;
1602
+ const restorePoint = async (ctx) => {
1603
+ const leaf = ctx?.sessionManager?.getLeafEntry?.();
1604
+ if (ctx?.mode !== "tui" || !isAsk(leaf)) return;
1596
1605
  PINK.redo.length = 0;
1597
1606
  const snapshot = await gitSnapshot(ctx.cwd).catch(() => undefined);
1598
1607
  if (!snapshot) return;
1599
1608
  PINK.snapshots.set(leaf.id, snapshot);
1600
1609
  // card 1dfwh7kfmqr: o ponto também vai para a sessão (fora do contexto do modelo); o /undo funciona depois de reabrir
1601
1610
  try { pink.appendEntry?.(UNDO_ENTRY, { entryId: leaf.id, top: snapshot.top, tree: snapshot.tree }); } catch { /* sem gravar: o /undo desta execução ainda vale */ }
1602
- });
1611
+ };
1612
+ pink.on("agent_start", async (_event, ctx) => restorePoint(ctx));
1613
+ pink.events?.on?.("pink:agent_start", (data) => void restorePoint(data?.ctx));
1603
1614
  pink.on("message_start", async (event) => {
1604
1615
  if (event?.message?.role !== "assistant") return;
1605
1616
  PINK.agentOf.set(event.message.timestamp, PINK.agent);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@thothdev/pink",
3
- "version": "1.0.13",
3
+ "version": "1.0.15",
4
4
  "description": "Pink: coding agent of the Thoth project, with a pink theme",
5
5
  "type": "module",
6
6
  "piConfig": {