UNPKG

@code-yeongyu/senpi

Version:

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

4 lines (3 loc) • 26.3 kB
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } } import{GrepEngineError}from"./chunk-H4QOEVS5.js";import{signalSpawnedChild}from"./chunk-KLAX467B.js";import{fetchWithRetry}from"./chunk-2SOVDETB.js";import{APP_NAME,envValue,getBinDir}from"./chunk-QJTWAOBX.js";import{spawn}from"node:child_process";import{spawnSync}from"child_process";import{chmodSync,createWriteStream,existsSync,mkdirSync,readdirSync,renameSync,rmSync,statSync}from"fs";import{arch,platform}from"os";import{join}from"path";import{Readable}from"stream";import{pipeline}from"stream/promises";var TOOLS_DIR=getBinDir(),NETWORK_TIMEOUT_MS=1e4,DOWNLOAD_TIMEOUT_MS=12e4;function isOfflineModeEnabled(){let value=envValue("OFFLINE");return value?value==="1"||value.toLowerCase()==="true"||value.toLowerCase()==="yes":!1}var TOOLS={fd:{name:"fd",repo:"sharkdp/fd",binaryName:"fd",systemBinaryNames:["fd","fdfind"],tagPrefix:"v",getAssetName:(version,plat,architecture)=>plat==="darwin"?`fd-v${version}-${architecture==="arm64"?"aarch64":"x86_64"}-apple-darwin.tar.gz`:plat==="linux"?`fd-v${version}-${architecture==="arm64"?"aarch64":"x86_64"}-unknown-linux-musl.tar.gz`:plat==="win32"?`fd-v${version}-${architecture==="arm64"?"aarch64":"x86_64"}-pc-windows-msvc.zip`:null},rg:{name:"ripgrep",repo:"BurntSushi/ripgrep",binaryName:"rg",tagPrefix:"",getAssetName:(version,plat,architecture)=>plat==="darwin"?`ripgrep-${version}-${architecture==="arm64"?"aarch64":"x86_64"}-apple-darwin.tar.gz`:plat==="linux"?`ripgrep-${version}-${architecture==="arm64"?"aarch64":"x86_64"}-unknown-linux-musl.tar.gz`:plat==="win32"?`ripgrep-${version}-${architecture==="arm64"?"aarch64":"x86_64"}-pc-windows-msvc.zip`:null}};function executableCandidates(cmd){if(platform()!=="win32")return[cmd];let extensions=(process.env.PATHEXT??".COM;.EXE;.BAT;.CMD").split(";").filter(value=>value.length>0);return[cmd,...extensions.map(extension=>`${cmd}${extension.toLowerCase()}`)]}function commandExists(cmd){let pathValue=process.env.PATH;if(pathValue===void 0||pathValue.length===0)return!1;let separator=platform()==="win32"?";":":";for(let directory of pathValue.split(separator))if(directory.length!==0)for(let candidate of executableCandidates(cmd))try{let stats=statSync(join(directory,candidate));if(!stats.isFile())continue;if(platform()==="win32"||(stats.mode&73)!==0)return!0}catch{}return!1}function getToolPath(tool){let config=TOOLS[tool];if(!config)return null;let localPath=join(TOOLS_DIR,config.binaryName+(platform()==="win32"?".exe":""));if(existsSync(localPath))return localPath;let systemBinaryNames=config.systemBinaryNames??[config.binaryName];for(let systemBinaryName of systemBinaryNames)if(commandExists(systemBinaryName))return systemBinaryName;return null}async function getLatestVersion(repo){let response=await fetchWithRetry(`https://github.com/${repo}/releases/latest`,{headers:{"User-Agent":`${APP_NAME}-coding-agent`},redirect:"manual"},{timeoutMs:NETWORK_TIMEOUT_MS});try{await response.body?.cancel()}catch{}let location=response.status>=300&&response.status<400?response.headers.get("location"):null;if(!location)throw new Error(`Failed to resolve latest ${repo} release: HTTP ${response.status} without redirect`);let tag=new URL(location,"https://github.com").pathname.split("/").pop();if(!tag||!location.includes("/releases/tag/"))throw new Error(`Failed to resolve latest ${repo} release: unexpected redirect to ${location}`);return decodeURIComponent(tag).replace(/^v/,"")}async function downloadFile(url,dest){let response=await fetchWithRetry(url,void 0,{timeoutMs:DOWNLOAD_TIMEOUT_MS});if(!response.ok)throw new Error(`Download failed with HTTP ${response.status}: ${url}`);if(!response.body)throw new Error("No response body");let fileStream=createWriteStream(dest);await pipeline(Readable.fromWeb(response.body),fileStream)}function findBinaryRecursively(rootDir,binaryFileName){let stack=[rootDir];for(;stack.length>0;){let currentDir=stack.pop();if(!currentDir)continue;let entries=readdirSync(currentDir,{withFileTypes:!0});for(let entry of entries){let fullPath=join(currentDir,entry.name);if(entry.isFile()&&entry.name===binaryFileName)return fullPath;entry.isDirectory()&&stack.push(fullPath)}}return null}function formatSpawnFailure(result){if(result.error?.message)return result.error.message;let stderr=result.stderr?.toString().trim();if(stderr)return stderr;let stdout=result.stdout?.toString().trim();return stdout||`exit status ${result.status??"unknown"}`}function runExtractionCommand(command,args){let result=spawnSync(command,args,{stdio:"pipe"});return!result.error&&result.status===0?null:`${command}: ${formatSpawnFailure(result)}`}function extractTarGzArchive(archivePath,extractDir,assetName){let failure=runExtractionCommand("tar",["xzf",archivePath,"-C",extractDir]);if(failure)throw new Error(`Failed to extract ${assetName}: ${failure}`)}function getWindowsTarCommand(){let systemRoot=process.env.SystemRoot??process.env.WINDIR;if(systemRoot){let systemTar=join(systemRoot,"System32","tar.exe");if(existsSync(systemTar))return systemTar}return"tar.exe"}function extractZipArchive(archivePath,extractDir,assetName){let failures=[];if(platform()==="win32"){let tarFailure=runExtractionCommand(getWindowsTarCommand(),["xf",archivePath,"-C",extractDir]);if(!tarFailure)return;failures.push(tarFailure);let powershellFailure=runExtractionCommand("powershell.exe",["-NoLogo","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command","& { param($archive, $destination) $ErrorActionPreference = 'Stop'; Expand-Archive -LiteralPath $archive -DestinationPath $destination -Force }",archivePath,extractDir]);if(!powershellFailure)return;failures.push(powershellFailure)}else{let unzipFailure=runExtractionCommand("unzip",["-q",archivePath,"-d",extractDir]);if(!unzipFailure)return;failures.push(unzipFailure);let tarFailure=runExtractionCommand("tar",["xf",archivePath,"-C",extractDir]);if(!tarFailure)return;failures.push(tarFailure)}throw new Error(`Failed to extract ${assetName}: ${failures.join("; ")}`)}async function downloadTool(tool){let config=TOOLS[tool];if(!config)throw new Error(`Unknown tool: ${tool}`);let plat=platform(),architecture=arch(),version=tool==="fd"&&plat==="darwin"&&architecture==="x64"?"10.3.0":await getLatestVersion(config.repo),assetName=config.getAssetName(version,plat,architecture);if(!assetName)throw new Error(`Unsupported platform: ${plat}/${architecture}`);mkdirSync(TOOLS_DIR,{recursive:!0});let downloadUrl=`https://github.com/${config.repo}/releases/download/${config.tagPrefix}${version}/${assetName}`,archivePath=join(TOOLS_DIR,assetName),binaryExt=plat==="win32"?".exe":"",binaryPath=join(TOOLS_DIR,config.binaryName+binaryExt);await downloadFile(downloadUrl,archivePath);let extractDir=join(TOOLS_DIR,`extract_tmp_${config.binaryName}_${process.pid}_${Date.now()}_${Math.random().toString(36).slice(2,10)}`);mkdirSync(extractDir,{recursive:!0});try{if(assetName.endsWith(".tar.gz"))extractTarGzArchive(archivePath,extractDir,assetName);else if(assetName.endsWith(".zip"))extractZipArchive(archivePath,extractDir,assetName);else throw new Error(`Unsupported archive format: ${assetName}`);let binaryFileName=config.binaryName+binaryExt,extractedDir=join(extractDir,assetName.replace(/\.(tar\.gz|zip)$/,"")),extractedBinary=[join(extractedDir,binaryFileName),join(extractDir,binaryFileName)].find(candidate=>existsSync(candidate));if(extractedBinary||(extractedBinary=findBinaryRecursively(extractDir,binaryFileName)??void 0),extractedBinary)renameSync(extractedBinary,binaryPath);else throw new Error(`Binary not found in archive: expected ${binaryFileName} under ${extractDir}`);plat!=="win32"&&chmodSync(binaryPath,493)}finally{rmSync(archivePath,{force:!0}),rmSync(extractDir,{recursive:!0,force:!0})}return binaryPath}var TERMUX_PACKAGES={fd:"fd",rg:"ripgrep"};async function ensureTool(tool,onStatus){let existingPath=getToolPath(tool);if(existingPath)return existingPath;let config=TOOLS[tool];if(config){if(isOfflineModeEnabled()){onStatus?.({type:"warning",message:`${config.name} not found. Offline mode enabled, skipping download.`});return}if(platform()==="android"){let pkgName=TERMUX_PACKAGES[tool]??tool;onStatus?.({type:"warning",message:`${config.name} not found. Install with: pkg install ${pkgName}`});return}onStatus?.({type:"info",message:`${config.name} not found. Downloading...`});try{let path=await downloadTool(tool);return onStatus?.({type:"info",message:`${config.name} installed to ${path}`}),path}catch(e){let messages=[];for(let current=e,depth=0;current instanceof Error&&depth<5;current=current.cause,depth++)messages.includes(current.message)||messages.push(current.message);onStatus?.({type:"warning",message:`Failed to download ${config.name}: ${messages.length>0?messages.join(": "):String(e)}`});return}}}import{relative}from"node:path";function argvBudget(platform2=process.platform){return platform2==="win32"?32e3:256*1024}var EXECUTABLE_RESERVE=4096;function argvCost(argument,platform2=process.platform){if(platform2!=="win32")return argument.length+1;let quotes=argument.match(/"/g)?.length??0,doubled=argument.match(/\\+(?="|$)/g)?.join("").length??0;return argument.length+3+quotes+doubled}var LINUX_MAX_ARG_STRLEN=131072;function commandLineOverflow(args,platform2=process.platform){let budget=argvBudget(platform2),length=EXECUTABLE_RESERVE+args.reduce((sum,argument)=>sum+argvCost(argument,platform2),0);if(length>budget)return`the ripgrep command line would be ${length} characters, over the ${budget}-character limit on ${platform2}`;if(platform2!=="linux")return;let longest=Math.max(0,...args.map(argument=>Buffer.byteLength(argument)));if(longest>=LINUX_MAX_ARG_STRLEN)return`one ripgrep argument is ${longest} bytes, over Linux's ${LINUX_MAX_ARG_STRLEN-1}-byte per-argument limit`}function roomAfter(fixed,budget,platform2=process.platform){return budget-EXECUTABLE_RESERVE-fixed.reduce((sum,argument)=>sum+argvCost(argument,platform2),0)}function packArgv(items,costOf,room){let batches=[],used=0;for(let item of items){let cost=costOf(item),batch=batches.at(-1);batch&&used+cost<=room?(batch.push(item),used+=cost):(batches.push([item]),used=cost)}return batches}import{sep}from"node:path";var pathOrder=(a,b)=>Buffer.compare(Buffer.from(a),Buffer.from(b)),slashPath=path=>path.split(sep).join("/");import{open}from"node:fs/promises";import{createInterface}from"node:readline";import{resolve}from"node:path";function parseRgEvent(line){let event=JSON.parse(line);if(!event||!["begin","match","context","end","summary"].includes(event.type)||!event.data)throw new Error("Invalid ripgrep JSON event");return event}function decode(value){if(typeof value?.text=="string")return value.text;if(typeof value?.bytes=="string")return Buffer.from(value.bytes,"base64").toString("utf8");throw new GrepEngineError("ENGINE_UNAVAILABLE","Invalid ripgrep JSON text/bytes field")}function collectSegmentRows(segment,request,oversized){let first=segment[0],files=new Map,byPath=new Map(segment.map(candidate=>[candidate.absolute,candidate])),segmentBinary=new Set;return{files,segmentBinary,onEvent:event=>{if(event.type==="summary")return;let candidate=oversized?first:byPath.get(resolve(first.root.cwd,decode(event.data.path)));if(!candidate)throw new Error("ripgrep searched a file outside the ordered segment");if(event.type==="begin"){files.set(candidate.display,{candidate,rows:new Map});return}if(event.type==="end"){event.data.binary_offset!=null&&(files.delete(candidate.display),segmentBinary.add(candidate.display));return}let file=files.get(candidate.display);if(!file||typeof event.data.line_number!="number")throw new Error("ripgrep match/context without a begin or line number");let text=decode(event.data.lines).replace(/\n$/,"").split(` `);for(let[index,physical]of text.entries()){let line=event.data.line_number+index;if(line<(request.lineStart??1)||line>(request.lineEnd??1/0))continue;let isContext=event.type==="context",existing=file.rows.get(line);if(existing&&(!existing.isContext||isContext))continue;let column=!isContext&&index===0&&event.data.submatches?.[0]?event.data.submatches[0].start+1:void 0,content=physical.replace(/\r$/,""),truncated=!1;if(request.maxColumns!==void 0){let scalars=Array.from(content);scalars.length>request.maxColumns&&(content=`${scalars.slice(0,request.maxColumns).join("")}...`,truncated=!0)}file.rows.set(line,{path:candidate.display,line,column,text:content,isContext,truncated})}}}}var SearchTimeout=class extends Error{};function rgError(message){return/look-around|backreference/i.test(message)?new GrepEngineError("UNSUPPORTED_REGEX",message):/regex parse error|PCRE2: error compiling pattern|the literal .* is not allowed in a regex/i.test(message)?new GrepEngineError("INVALID_PATTERN",message):/error parsing glob/i.test(message)?new GrepEngineError("INVALID_GLOB",message):/unrecognized file type|unknown file type/i.test(message)?new GrepEngineError("UNKNOWN_TYPE",message):new GrepEngineError("ENGINE_UNAVAILABLE",message)}function onlyNoFilesWarnings(stderr){let lines=stderr.trim().split(/\r?\n/);return lines.some(line=>line.startsWith("No files were searched"))&&lines.every(line=>line.startsWith("No files were searched")||line==="Running with --debug will show why files are being skipped.")}function createRgRunner({executable,launch,now,deadline,signal,check}){return async(args,cwd,onEvent,input)=>{check();let overflow=commandLineOverflow(args);if(overflow)throw new GrepEngineError("ENGINE_UNAVAILABLE",`Cannot run ripgrep: ${overflow}. Search fewer paths at once.`);return new Promise((resolveRun,reject)=>{let child=launch(executable,args,{cwd,stdio:"pipe"}),chunks=[],stderr="",failure,timedOut=!1,stop=()=>{child.exitCode===null&&child.signalCode===null&&signalSpawnedChild(child,"SIGTERM")},onAbort=()=>{stop()},timer=setTimeout(()=>{timedOut=!0,stop()},Math.max(0,deadline-now()));signal?.addEventListener("abort",onAbort,{once:!0});let lines=onEvent?createInterface({input:child.stdout}):void 0;lines?.on("line",line=>{if(!failure)try{onEvent?.(parseRgEvent(line))}catch(error){failure=new GrepEngineError("ENGINE_UNAVAILABLE",`Malformed ripgrep JSON: ${String(error)}`),stop()}}),onEvent||child.stdout.on("data",chunk=>chunks.push(chunk)),child.stderr.setEncoding("utf8").on("data",chunk=>{stderr+=chunk}),child.on("error",error=>{failure=new GrepEngineError("ENGINE_UNAVAILABLE",`Failed to run ripgrep: ${error.message}`)}),child.stdin.on("error",error=>{error.code!=="EPIPE"&&(failure=new GrepEngineError("ENGINE_UNAVAILABLE",`Failed to write ripgrep input: ${error.message}`),stop())}),child.on("close",code=>{clearTimeout(timer),lines?.close(),signal?.removeEventListener("abort",onAbort),signal?.aborted?reject(new GrepEngineError("ABORTED","Grep search aborted")):timedOut||now()>=deadline?reject(new SearchTimeout):failure?reject(failure):code!==0&&code!==1&&!(code===2&&onlyNoFilesWarnings(stderr))?reject(rgError(stderr.trim()||`ripgrep exited with code ${code}`)):resolveRun(Buffer.concat(chunks))}),input!==void 0&&child.stdin.end(input),signal?.aborted&&onAbort()})}}var MAX_FILE_BYTES=4194304;async function readSearchablePrefix(candidate,result,check){let prefix;try{let file=await open(candidate.absolute,"r");try{let buffer=Buffer.alloc(MAX_FILE_BYTES),length=0;for(;length<buffer.length;){check();let{bytesRead}=await file.read(buffer,length,buffer.length-length,length);if(bytesRead===0)break;length+=bytesRead}prefix=buffer.subarray(0,length)}finally{await file.close()}}catch(error){if(error instanceof SearchTimeout||error instanceof GrepEngineError)throw error;check(),result.skippedOversized++,result.warnings.push({path:candidate.display,code:"SKIPPED_OVERSIZED",message:String(error)});return}if(check(),prefix.indexOf(0)!==-1){result.skippedBinary++;return}let newline=prefix.lastIndexOf(10);if(newline===-1){result.skippedOversized++;return}return prefix.subarray(0,newline+1)}function walkerFlags(request){let args=[];(request.hidden??!0)&&args.push("--hidden"),request.gitignore??!0?args.push("--no-require-git"):args.push("--no-ignore");for(let glob of request.glob?.filter(glob2=>!glob2.startsWith("!"))??[])args.push("-g",glob);for(let glob of request.glob?.filter(glob2=>glob2.startsWith("!"))??[])args.push("-g",glob);return request.type&&args.push("--type",request.type),(request.hidden??!0)&&args.push("-g","!.git"),args}function matcherFlags(request){let args=["--json","--line-number","--color=never","--encoding","none"];return request.ignoreCase&&args.push("-i"),request.literal&&args.push("-F"),request.multiline&&args.push("-U"),request.contextBefore!==void 0&&args.push("-B",String(request.contextBefore)),request.contextAfter!==void 0&&args.push("-A",String(request.contextAfter)),request.pcre2&&args.push("--pcre2"),request.mode==="files"?args.push("-m","1"):(request.mode??"content")==="content"&&request.maxCountPerFile!==void 0&&request.lineStart===void 0&&request.lineEnd===void 0&&args.push("-m",String(request.maxCountPerFile+1)),args}function candidateArgument(candidate){return candidate.root.file?candidate.root.path:`/${slashPath(relative(candidate.root.cwd,candidate.absolute)).replace(/[\\*?[\]{}!]/g,"\\$&")}`}function argumentCost(candidate,platform2=process.platform){let argument=argvCost(candidateArgument(candidate),platform2);return candidate.root.file?argument:argument+argvCost("-g",platform2)}function segmentFlags(segment,pattern,walk,matcher){let first=segment[0],limits=["--sort","path","--max-filesize",String(MAX_FILE_BYTES),...walk];if(first.root.file)return[...matcher,...limits,"--",pattern,...segment.map(candidateArgument)];let includes=["-g","!**/*","-g","**/"];for(let candidate of segment)includes.push("-g",candidateArgument(candidate));return[...matcher,...limits,...includes,"--",pattern,first.root.path]}import{realpath,stat}from"node:fs/promises";import{basename,dirname,relative as relative2,resolve as resolve2}from"node:path";async function resolveRoots(request,result){let roots=[];for(let path of new Set(request.paths))try{let[info,canonical]=await Promise.all([stat(path),realpath(path)]);roots.push({path:canonical,alias:path,cwd:info.isDirectory()?canonical:dirname(canonical),file:info.isFile()})}catch(error){if(error.code!=="ENOENT")throw error;result.missingPaths.push(path)}if(roots.length===0)throw new GrepEngineError("PATH_NOT_FOUND",`No search paths exist: ${request.paths.join(", ")}`);return roots}async function enumerateCandidates({roots,cwd,walk,run,check,result,budget=argvBudget()}){let candidates=new Map;for(let root of roots){let listed=root.file?[root.path]:(await run(["--files","--null","--sort","path",...walk,"--",root.path],root.cwd)).toString("utf8").split("\0").filter(Boolean);for(let path of listed){check();let absolute=resolve2(root.cwd,path),[canonical,info]=await Promise.all([realpath(absolute),stat(absolute)]).catch(error=>{throw root.file&&error.code==="ENOENT"?new GrepEngineError("ENGINE_UNAVAILABLE",`${root.path}: No such file or directory`):error}),alias=resolve2(root.alias,relative2(root.path,absolute)),display=slashPath(relative2(cwd,alias))||basename(alias),existing=candidates.get(canonical);(!existing||pathOrder(display,existing.display)<0)&&candidates.set(canonical,{absolute,canonical,display,root,size:info.size})}}let binaryPaths=new Set,scanned=roots.filter(root=>(candidates.get(root.path)?.size??0)<=MAX_FILE_BYTES),files=scanned.filter(root=>root.file),nulScan=["-a","-l","--null","--sort","path","--encoding","none","--max-filesize",String(MAX_FILE_BYTES),...walk,"-e","\\x00","--"],room=roomAfter(nulScan,budget),scans=[...packArgv(files,root=>argvCost(root.path),room).map(batch=>({cwd:batch[0].cwd,paths:batch.map(root=>root.path)})),...scanned.filter(root=>!root.file).map(root=>({cwd:root.cwd,paths:[root.path]}))];for(let scan of scans){let output=await run([...nulScan,...scan.paths],scan.cwd);for(let path of output.toString("utf8").split("\0").filter(Boolean))binaryPaths.add(await realpath(resolve2(scan.cwd,path)))}return result.skippedBinary=[...binaryPaths].filter(path=>candidates.has(path)).length,[...candidates.values()].sort((a,b)=>pathOrder(a.display,b.display)).map((candidate,index)=>({...candidate,ordinal:index+1,binary:binaryPaths.has(candidate.canonical)}))}var CAPPED_BATCH_SIZE=200,MAX_CAPPED_BATCH_SIZE=1600;function cappedLimit(head){return Math.min(MAX_CAPPED_BATCH_SIZE,Math.max(CAPPED_BATCH_SIZE,head.ordinal-1))}function joins(previous,candidate,request){let head=previous[0];return head.size>MAX_FILE_BYTES||candidate.size>MAX_FILE_BYTES?!1:(head.root.file&&candidate.root.file||!head.binary&&!candidate.binary&&head.root===candidate.root)&&(request.maxCount===void 0||previous.length<cappedLimit(head))}function planSegments(ordered,request,plan){let platform2=plan.platform??process.platform,budget=plan.budget??argvBudget(platform2),segments=[],room=0;for(let candidate of ordered){let previous=segments.at(-1),cost=candidate.binary?0:argumentCost(candidate,platform2);previous&&joins(previous,candidate,request)&&cost<=room?(previous.push(candidate),room-=cost):(segments.push([candidate]),room=roomAfter(segmentFlags([candidate],request.pattern,plan.walk,plan.matcher),budget,platform2))}return segments}function admitFiles(files,request,result){let lastCommitted,segmentFiles=[...files.values()].sort((a,b)=>pathOrder(a.candidate.display,b.candidate.display));for(let file of segmentFiles){let rows=[...file.rows.values()].sort((a,b)=>a.line-b.line||(a.column??0)-(b.column??0)),matching=rows.filter(row=>!row.isContext);if(matching.length===0)continue;let perFileCap=request.maxCountPerFile??1/0,perFileLimited=request.mode!=="files"&&matching.length>perFileCap;result.perFileLimitReached||=perFileLimited;let remaining=Math.max(0,(request.maxCount??1/0)-(request.mode==="files"?result.counts.files:result.counts.matches??0)),admitted=matching.slice(0,request.mode==="files"?remaining>0?1:0:Math.min(perFileCap,remaining)),available=request.mode==="files"?1:Math.min(matching.length,perFileCap);if(admitted.length<available&&(result.limitReached=!0),admitted.length!==0)if(lastCommitted=file.candidate,result.counts.files++,result.counts.matches!==null&&(result.counts.matches+=admitted.length),request.mode==="count"||request.mode==="files")result.fileCounts.push({path:file.candidate.display,count:request.mode==="files"?null:admitted.length,limitReached:perFileLimited});else{let lines=new Set(admitted.map(row=>row.line));for(let row of rows)(lines.has(row.line)||row.isContext&&admitted.some(match=>row.line>=match.line-(request.contextBefore??0)&&row.line<=match.line+(request.contextAfter??0)))&&result.matches.push(row)}}return lastCommitted}async function searchSegments({candidates,request,walk,matcher,run,check,result,budget}){let segments=planSegments(candidates,request,{walk,matcher,budget}),matcherRan=!1;for(let[segmentIndex,segment]of segments.entries()){check();let searchable=segment.filter(candidate=>!candidate.binary);if(searchable.length===0){result.filesSearched=segment[segment.length-1].ordinal;continue}let first=searchable[0],oversized=first.size>MAX_FILE_BYTES,prefix=oversized?await readSearchablePrefix(first,result,check):void 0;if(oversized&&prefix===void 0){result.filesSearched=first.ordinal;continue}let{files,segmentBinary,onEvent}=collectSegmentRows(searchable,request,oversized);matcherRan=!0,oversized?await run([...matcher,"--",request.pattern],request.cwd,onEvent,prefix):await run(segmentFlags(searchable,request.pattern,walk,matcher),first.root.cwd,onEvent),check(),oversized&&result.prefixSearched++,result.skippedBinary+=segmentBinary.size;let lastCommitted=admitFiles(files,request,result);result.filesSearched=segment[segment.length-1].ordinal;let admittedCount=request.mode==="files"?result.counts.files:result.counts.matches??0;if(request.maxCount!==void 0&&admittedCount>=request.maxCount){lastCommitted&&(result.filesSearched=lastCommitted.ordinal),segmentIndex<segments.length-1&&(result.limitReached=!0);break}}matcherRan||await run([...matcher,"--",request.pattern],request.cwd,()=>{},Buffer.alloc(0))}var RgGrepEngine=class{constructor(options={}){this.name="rg",this.launch=options.spawn??spawn,this.now=options.now??Date.now,this.batchBudget=options.batchBudget}async search(request,signal){let started=this.now(),deadline=started+(request.timeoutMs??3e4),result={matches:[],fileCounts:[],counts:{matches:request.mode==="files"?null:0,files:0,exact:!0},filesSearched:0,limitReached:!1,perFileLimitReached:!1,skippedOversized:0,prefixSearched:0,skippedBinary:0,missingPaths:[],warnings:[],timedOut:!1,elapsedMs:0,effectivePattern:request.pattern,patternKind:request.literal?"literal":"regex",regexEngine:request.pcre2?"pcre2":"rust"},check=()=>{if(signal?.aborted)throw new GrepEngineError("ABORTED","Grep search aborted");if(this.now()>=deadline)throw new SearchTimeout},overflow=commandLineOverflow([request.pattern]);if(overflow)throw new GrepEngineError("INVALID_PATTERN",`Pattern is too long to pass to ripgrep: ${overflow}. Shorten it.`);try{check();let roots=await resolveRoots(request,result);check();let executable=await ensureTool("rg");if(!executable)throw new GrepEngineError("ENGINE_UNAVAILABLE","ripgrep is unavailable and could not be downloaded");let walk=walkerFlags(request),matcher=matcherFlags(request),run=createRgRunner({executable,launch:(command,args,options)=>this.launch(command,args,options),now:()=>this.now(),deadline,signal,check}),candidates=await enumerateCandidates({roots,cwd:request.cwd,walk,run,check,result,budget:this.batchBudget});await searchSegments({candidates,request,walk,matcher,run,check,result,budget:this.batchBudget})}catch(error){if(!(error instanceof SearchTimeout))throw error;result.timedOut=!0,result.warnings.push({code:"TIMED_OUT",message:`Timed out after ${request.timeoutMs??3e4} ms; showing the completed ordered prefix.`})}return result.counts.exact=!result.limitReached&&!result.perFileLimitReached&&!result.timedOut,result.elapsedMs=Math.max(0,this.now()-started),result}};function createRgEngine(options={}){return new RgGrepEngine(options)}export{ensureTool,RgGrepEngine,createRgEngine};