UNPKG

@earendil-works/pi-coding-agent

Version:

Coding agent CLI with read, bash, edit, write tools and session management

14 lines (12 loc) • 8.85 kB
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); import{getBinDir}from"./chunk-36QC74V4.js";import{accessSync,constants}from"node:fs";import{delimiter,join,win32}from"node:path";import{spawn,spawnSync}from"child_process";function isLegacyWslBashPath(path){let normalized=win32.normalize(path).toLowerCase(),systemRoot=process.env.SystemRoot;return systemRoot?/^[a-z]:[\\/]/i.test(systemRoot)?["System32","Sysnative"].some(directory=>normalized===win32.join(systemRoot,directory,"bash.exe").toLowerCase()):!1:/^[a-z]:\\windows\\(?:system32|sysnative)\\bash\.exe$/.test(normalized)}function getBashShellConfig(shell){return isLegacyWslBashPath(shell)?{shell,args:["-s"],commandTransport:"stdin"}:{shell,args:["-c"]}}function shellPathExists(path){try{return accessSync(path,constants.F_OK),!0}catch{return!1}}function findExecutableOnPath(executable){if(process.platform==="win32"){try{let result=spawnSync("where",[executable],{encoding:"utf-8",timeout:5e3,windowsHide:!0});if(result.status===0&&result.stdout){let firstMatch=result.stdout.trim().split(/\r?\n/)[0];if(firstMatch&&shellPathExists(firstMatch))return firstMatch}}catch{}return null}try{let result=spawnSync("which",[executable],{encoding:"utf-8",timeout:5e3});if(result.status===0&&result.stdout){let firstMatch=result.stdout.trim().split(/\r?\n/)[0];if(firstMatch)return firstMatch}}catch{}return null}function getShellConfig(customShellPath){if(customShellPath){if(shellPathExists(customShellPath))return getBashShellConfig(customShellPath);throw new Error(`Custom shell path not found: ${customShellPath}`)}if(process.platform==="win32"){let paths=[],programFiles=process.env.ProgramFiles;programFiles&&paths.push(`${programFiles}\\Git\\bin\\bash.exe`);let programFilesX86=process.env["ProgramFiles(x86)"];programFilesX86&&paths.push(`${programFilesX86}\\Git\\bin\\bash.exe`);for(let path of paths)if(shellPathExists(path))return getBashShellConfig(path);let bashOnPath2=findExecutableOnPath("bash.exe");if(bashOnPath2)return getBashShellConfig(bashOnPath2);throw new Error(`No bash shell found. Options: 1. Install Git for Windows: https://git-scm.com/download/win 2. Add your bash to PATH (Cygwin, MSYS2, etc.) 3. Set shellPath in settings.json Searched Git Bash in: ${paths.map(p=>` ${p}`).join(` `)}`)}if(shellPathExists("/bin/bash"))return getBashShellConfig("/bin/bash");let bashOnPath=findExecutableOnPath("bash");return bashOnPath?getBashShellConfig(bashOnPath):{shell:"sh",args:["-c"]}}var POWERSHELL_ARGS=["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command"];function getPowerShellConfig(){if(process.platform!=="win32")throw new Error("The powershell tool is only available on Windows.");let shell=findExecutableOnPath("pwsh.exe"),programFiles=process.env.ProgramFiles;if(!shell&&programFiles){let pwsh7=win32.join(programFiles,"PowerShell","7","pwsh.exe");shellPathExists(pwsh7)&&(shell=pwsh7)}shell??=findExecutableOnPath("powershell.exe");let systemRoot=process.env.SystemRoot;if(!shell&&systemRoot){let windowsPowerShell=win32.join(systemRoot,"System32","WindowsPowerShell","v1.0","powershell.exe");shellPathExists(windowsPowerShell)&&(shell=windowsPowerShell)}if(!shell)throw new Error("No PowerShell executable found. Install PowerShell or add powershell.exe/pwsh.exe to PATH.");return{shell,args:[...POWERSHELL_ARGS]}}function getShellEnv(){let binDir=getBinDir(),pathKey=Object.keys(process.env).find(key=>key.toLowerCase()==="path")??"PATH",currentPath=process.env[pathKey]??"",updatedPath=currentPath.split(delimiter).filter(Boolean).includes(binDir)?currentPath:[binDir,currentPath].filter(Boolean).join(delimiter);return{...process.env,[pathKey]:updatedPath}}function sanitizeBinaryOutput(str){return str.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\uFFF9-\uFFFB]/g,"")}var trackedDetachedChildPids=new Set;function trackDetachedChildPid(pid){trackedDetachedChildPids.add(pid)}function untrackDetachedChildPid(pid){trackedDetachedChildPids.delete(pid)}function killTrackedDetachedChildren(){for(let pid of trackedDetachedChildPids)killProcessTree(pid);trackedDetachedChildPids.clear()}function killProcessTree(pid){if(process.platform==="win32")try{spawn(join(process.env.SystemRoot||"C:\\Windows","System32","taskkill.exe"),["/F","/T","/PID",String(pid)],{stdio:"ignore",detached:!0,windowsHide:!0}).once("error",()=>{})}catch{}else{if(process.platform==="darwin")try{process.kill(-pid,"SIGSTOP")}catch{}try{process.kill(-pid,"SIGKILL")}catch{try{process.kill(pid,"SIGKILL")}catch{}}}}var DEFAULT_MAX_LINES=2e3,DEFAULT_MAX_BYTES=51200;function splitLinesForCounting(content){if(content.length===0)return[];let lines=content.split(` `);return content.endsWith(` `)&&lines.pop(),lines}function formatSize(bytes){return bytes<1024?`${bytes}B`:bytes<1024*1024?`${(bytes/1024).toFixed(1)}KB`:`${(bytes/(1024*1024)).toFixed(1)}MB`}function truncateHead(content,options={}){let maxLines=options.maxLines??2e3,maxBytes=options.maxBytes??51200,totalBytes=Buffer.byteLength(content,"utf-8"),lines=splitLinesForCounting(content),totalLines=lines.length;if(totalLines<=maxLines&&totalBytes<=maxBytes)return{content,truncated:!1,truncatedBy:null,totalLines,totalBytes,outputLines:totalLines,outputBytes:totalBytes,lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines,maxBytes};if(Buffer.byteLength(lines[0],"utf-8")>maxBytes)return{content:"",truncated:!0,truncatedBy:"bytes",totalLines,totalBytes,outputLines:0,outputBytes:0,lastLinePartial:!1,firstLineExceedsLimit:!0,maxLines,maxBytes};let outputLinesArr=[],outputBytesCount=0,truncatedBy="lines";for(let i=0;i<lines.length&&i<maxLines;i++){let line=lines[i],lineBytes=Buffer.byteLength(line,"utf-8")+(i>0?1:0);if(outputBytesCount+lineBytes>maxBytes){truncatedBy="bytes";break}outputLinesArr.push(line),outputBytesCount+=lineBytes}outputLinesArr.length>=maxLines&&outputBytesCount<=maxBytes&&(truncatedBy="lines");let outputContent=outputLinesArr.join(` `),finalOutputBytes=Buffer.byteLength(outputContent,"utf-8");return{content:outputContent,truncated:!0,truncatedBy,totalLines,totalBytes,outputLines:outputLinesArr.length,outputBytes:finalOutputBytes,lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines,maxBytes}}function truncateTail(content,options={}){let maxLines=options.maxLines??2e3,maxBytes=options.maxBytes??51200,totalBytes=Buffer.byteLength(content,"utf-8"),lines=splitLinesForCounting(content),totalLines=lines.length;if(totalLines<=maxLines&&totalBytes<=maxBytes)return{content,truncated:!1,truncatedBy:null,totalLines,totalBytes,outputLines:totalLines,outputBytes:totalBytes,lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines,maxBytes};let outputLinesArr=[],outputBytesCount=0,truncatedBy="lines",lastLinePartial=!1;for(let i=lines.length-1;i>=0&&outputLinesArr.length<maxLines;i--){let line=lines[i],lineBytes=Buffer.byteLength(line,"utf-8")+(outputLinesArr.length>0?1:0);if(outputBytesCount+lineBytes>maxBytes){if(truncatedBy="bytes",outputLinesArr.length===0){let truncatedLine=truncateStringToBytesFromEnd(line,maxBytes);outputLinesArr.unshift(truncatedLine),outputBytesCount=Buffer.byteLength(truncatedLine,"utf-8"),lastLinePartial=!0}break}outputLinesArr.unshift(line),outputBytesCount+=lineBytes}outputLinesArr.length>=maxLines&&outputBytesCount<=maxBytes&&(truncatedBy="lines");let outputContent=outputLinesArr.join(` `),finalOutputBytes=Buffer.byteLength(outputContent,"utf-8");return{content:outputContent,truncated:!0,truncatedBy,totalLines,totalBytes,outputLines:outputLinesArr.length,outputBytes:finalOutputBytes,lastLinePartial,firstLineExceedsLimit:!1,maxLines,maxBytes}}function truncateStringToBytesFromEnd(str,maxBytes){let buf=Buffer.from(str,"utf-8");if(buf.length<=maxBytes)return str;let start=buf.length-maxBytes;for(;start<buf.length&&(buf[start]&192)===128;)start++;return buf.slice(start).toString("utf-8")}function truncateLine(line,maxChars=500){return line.length<=maxChars?{text:line,wasTruncated:!1}:{text:`${sliceHead(line,maxChars)}... [truncated]`,wasTruncated:!0}}function sliceHead(text,maxUnits){let end=Math.max(0,maxUnits);return isHighSurrogate(text.charCodeAt(end-1))&&isLowSurrogate(text.charCodeAt(end))?text.slice(0,end-1):text.slice(0,end)}function sliceTail(text,maxUnits){if(maxUnits<=0)return"";let start=Math.max(0,text.length-maxUnits);return isLowSurrogate(text.charCodeAt(start))&&isHighSurrogate(text.charCodeAt(start-1))?text.slice(start+1):text.slice(start)}function isHighSurrogate(code){return code>=55296&&code<=56319}function isLowSurrogate(code){return code>=56320&&code<=57343}export{getShellConfig,getPowerShellConfig,getShellEnv,sanitizeBinaryOutput,trackDetachedChildPid,untrackDetachedChildPid,killTrackedDetachedChildren,killProcessTree,DEFAULT_MAX_LINES,DEFAULT_MAX_BYTES,formatSize,truncateHead,truncateTail,truncateLine,sliceHead,sliceTail};