UNPKG

@code-yeongyu/senpi

Version:

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

175 lines (168 loc) • 42.5 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{DeviceFileError,FILE_CHANNEL_MAX_BYTES,LOCAL_DEVICE_FILES}from"./chunk-DPNC7S74.js";import{engineTrustAction}from"./chunk-R7J5TEYK.js";import{hasFunctions,realmRegistry}from"./chunk-XDEZA6U6.js";import{KILL_GUARD_TAG,refuse,refuseAll}from"./chunk-WOHQJ6JB.js";import{childEnvironmentOf}from"./chunk-IDTQWHTP.js";import{VERSION,getAgentDir,getBinDir,isBunBinary}from"./chunk-QJTWAOBX.js";import{adoptedEngineTrust}from"./chunk-RFFMEA4B.js";var ENV_NAME=/^[A-Za-z_][A-Za-z0-9_]*$/,HEADER_NAME=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,SCHEME=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,LOOPBACK_HOSTS=new Set(["localhost","127.0.0.1","[::1]"]),RESERVED_HEADERS=new Set(["connection","content-length","content-encoding","host","keep-alive","proxy-connection","te","trailer","transfer-encoding","upgrade"]);function parseOrigin(value){if(typeof value!="string"||value.length===0)return{problem:"origin must be a URL string"};let url;try{url=new URL(value)}catch{return{problem:"origin is not a valid URL"}}return url.username!==""||url.password!==""?{problem:"origin must not carry credentials"}:url.search!==""||url.hash!==""?{problem:"origin must not have a query or fragment"}:url.protocol!=="https:"&&!(url.protocol==="http:"&&LOOPBACK_HOSTS.has(url.hostname))?{problem:"origin must use https (plain http only for a loopback host)"}:{origin:`${url.origin}${url.pathname.replace(/\/+$/,"")}`}}function parsePathPrefixes(value){if(value===void 0)return{prefixes:void 0};if(!Array.isArray(value)||value.length===0)return{problem:"pathPrefixes must be a non-empty array"};let prefixes=[];for(let entry of value){if(typeof entry!="string"||!entry.startsWith("/")||hasUnsafePathSegment(entry))return{problem:"each pathPrefixes entry must be a plain absolute path"};prefixes.push(entry)}return{prefixes}}function hasUnsafePathSegment(path){return/%2e|%2f|%5c|\\/i.test(path)?!0:path.split("/").some(segment=>segment==="."||segment.startsWith("..")||segment.startsWith(".;"))}function parseCredentialDeclarations(raw){if(raw===void 0)return{credentials:[],withheldNames:[],problems:[]};let list=typeof raw=="object"&&raw!==null?Reflect.get(raw,"credentials"):void 0;if(list===void 0)return{credentials:[],withheldNames:[],problems:[]};if(!Array.isArray(list))return{credentials:[],withheldNames:[],problems:["credentialProxy.credentials must be an array"]};let credentials=[],withheld=new Set,problems=[],baseUrlNames=new Set;list.forEach((entry,index)=>{let at=`credentialProxy.credentials[${index}]`;if(typeof entry!="object"||entry===null){problems.push(`${at} must be an object`);return}let field=name=>Reflect.get(entry,name),env=field("env");if(typeof env!="string"||!ENV_NAME.test(env)){problems.push(`${at}.env must be an environment variable name`);return}let fail=problem=>problems.push(`${at} (${env}): ${problem}; the value is withheld and not proxied`);if(withheld.has(env)){fail("declared more than once");return}withheld.add(env);let origin=parseOrigin(field("origin"));if("problem"in origin)return fail(origin.problem);let rawHeader=field("header")??"authorization";if(typeof rawHeader!="string"||!HEADER_NAME.test(rawHeader)||RESERVED_HEADERS.has(rawHeader.toLowerCase()))return fail("header must be a request header name the proxy may set");let header=rawHeader.toLowerCase(),rawScheme=field("scheme");if(rawScheme!==void 0&&(typeof rawScheme!="string"||!SCHEME.test(rawScheme)))return fail("scheme must be a single token such as Bearer");let scheme=typeof rawScheme=="string"?rawScheme:header==="authorization"?"Bearer":void 0,baseUrlEnv=field("baseUrlEnv");if(baseUrlEnv!==void 0&&(typeof baseUrlEnv!="string"||!ENV_NAME.test(baseUrlEnv)))return fail("baseUrlEnv must be an environment variable name");if(typeof baseUrlEnv=="string"&&(baseUrlNames.has(baseUrlEnv)||baseUrlEnv===env))return fail("baseUrlEnv is already used");let prefixes=parsePathPrefixes(field("pathPrefixes"));if("problem"in prefixes)return fail(prefixes.problem);typeof baseUrlEnv=="string"&&baseUrlNames.add(baseUrlEnv),credentials.push({env,origin:origin.origin,header,scheme,baseUrlEnv:typeof baseUrlEnv=="string"?baseUrlEnv:void 0,pathPrefixes:prefixes.prefixes})});for(let credential of credentials)withheld.has(credential.baseUrlEnv??"")&&problems.push(`credentialProxy: ${credential.baseUrlEnv} is both a credential and a baseUrlEnv`);return{credentials,withheldNames:[...withheld],problems}}import{randomBytes,timingSafeEqual}from"node:crypto";import{createServer}from"node:http";import{Readable}from"node:stream";var MAX_REQUEST_BYTES=64*1024*1024,DROPPED_REQUEST_HEADERS=new Set(["accept-encoding","connection","content-length","host","keep-alive","proxy-authorization","proxy-connection","te","trailer","transfer-encoding","upgrade"]),DROPPED_RESPONSE_HEADERS=new Set(["connection","content-encoding","content-length","keep-alive","transfer-encoding"]);function refuse2(response,status,reason){if(response.headersSent){response.destroy();return}response.writeHead(status,{"content-type":"text/plain; charset=utf-8"}),response.end(`senpi credential proxy: ${reason} `)}function sameCapability(given,expected){let bytes=Buffer.from(given);return bytes.length===expected.length&&timingSafeEqual(bytes,expected)}async function readBody(request){if(request.method==="GET"||request.method==="HEAD")return;let chunks=[],size=0;for await(let chunk of request){let buffer=Buffer.isBuffer(chunk)?chunk:Buffer.from(String(chunk));if(size+=buffer.length,size>MAX_REQUEST_BYTES)throw new RangeError("request body too large");chunks.push(buffer)}let body=new Uint8Array(size),offset=0;for(let chunk of chunks)body.set(chunk,offset),offset+=chunk.length;return body}function forwardedHeaders(request,credential){let headers=new Headers;for(let[name,value]of Object.entries(request.headers)){let lower=name.toLowerCase();if(!(value===void 0||DROPPED_REQUEST_HEADERS.has(lower)||lower===credential.declaration.header))for(let item of Array.isArray(value)?value:[value])headers.append(lower,item)}let{scheme,header}=credential.declaration;return headers.set(header,scheme===void 0?credential.value:`${scheme} ${credential.value}`),headers.set("accept-encoding","identity"),headers}function allowedPath(path,credential){if(hasUnsafePathSegment(path))return!1;let prefixes=credential.declaration.pathPrefixes;return prefixes===void 0||prefixes.some(prefix=>path===prefix||path.startsWith(prefix.endsWith("/")?prefix:`${prefix}/`))}async function relay(upstream,response){let headers={};if(upstream.headers.forEach((value,name)=>{DROPPED_RESPONSE_HEADERS.has(name)||(headers[name]??=[]).push(value)}),response.writeHead(upstream.status,headers),upstream.body===null){response.end();return}await new Promise((resolve,reject)=>{let body=Readable.fromWeb(upstream.body);body.on("error",reject),response.on("close",()=>{body.destroy(),resolve()}),body.pipe(response).on("finish",resolve)})}function handler(capability,byEnv){return async(request,response)=>{let target=request.url??"";if(!target.startsWith("/"))return refuse2(response,400,"only origin-form requests are accepted");let queryAt=target.indexOf("?"),path=queryAt===-1?target:target.slice(0,queryAt),query=queryAt===-1?"":target.slice(queryAt),[,given="",env="",...rest]=path.split("/"),credential=byEnv.get(env);if(!sameCapability(given,capability)||credential===void 0)return refuse2(response,403,"unknown route");let upstreamPath=`/${rest.join("/")}`;if(!allowedPath(upstreamPath,credential))return refuse2(response,403,"path not allowed for this credential");let body;try{body=await readBody(request)}catch{return refuse2(response,413,"request body too large")}let upstream;try{upstream=await fetch(`${credential.declaration.origin}${upstreamPath==="/"?"":upstreamPath}${query}`,{method:request.method??"GET",headers:forwardedHeaders(request,credential),redirect:"manual",...body===void 0?{}:{body}})}catch{return refuse2(response,502,"upstream request failed")}try{await relay(upstream,response)}catch{response.destroy()}}}async function startCredentialProxy(credentials){let capabilityText=randomBytes(32).toString("base64url"),capability=Buffer.from(capabilityText),byEnv=new Map(credentials.map(credential=>[credential.declaration.env,credential])),server=createServer((request,response)=>{handler(capability,byEnv)(request,response)});await new Promise((resolve,reject)=>{server.once("error",reject),server.listen(0,"127.0.0.1",()=>{server.off("error",reject),resolve()})}),server.unref();let{port}=server.address();return{routeFor:env=>byEnv.has(env)?`http://127.0.0.1:${port}/${capabilityText}/${env}`:void 0,close:()=>new Promise(resolve=>{server.close(()=>resolve()),server.closeAllConnections()})}}var CREDENTIAL_PLACEHOLDER="senpi-credential-proxy-placeholder",holds=realmRegistry("@code-yeongyu/senpi/credential-proxy/v1",()=>{let byHolder=new Map;return{set:(holder,hold)=>{byHolder.delete(holder),byHolder.set(holder,hold)},release:holder=>{let hold=byHolder.get(holder);return byHolder.delete(holder),hold},all:()=>[...byHolder.values()]}},value=>hasFunctions(value,["set","release","all"])),proxies=new Map;function withCredentialProxy(env){let active=holds.all();if(active.length===0)return env;let names=new Set,values=new Set;for(let hold of active)for(let[name,value]of hold.withheld)names.add(name),value!==void 0&&value!==""&&values.add(value);let result={...env};for(let[name,value]of Object.entries(result))(names.has(name)||value!==void 0&&values.has(value))&&(result[name]=CREDENTIAL_PLACEHOLDER);for(let name of names)result[name]=CREDENTIAL_PLACEHOLDER;for(let hold of active)for(let[name,route]of hold.routes)result[name]=route;return result}async function activateCredentialProxy(options){let previous=detach(options.holder),env=options.env??process.env,parsed=parseCredentialDeclarations(options.settings),hold={withheld:new Map(parsed.withheldNames.map(name=>[name,env[name]])),routes:new Map};parsed.withheldNames.length>0&&holds.set(options.holder,hold),await previous?.close();for(let problem of parsed.problems)options.warn(problem);if(parsed.withheldNames.length===0)return;let proxied=[];for(let declaration of parsed.credentials){let value=env[declaration.env];value===void 0||value===""?options.warn(`credentialProxy: ${declaration.env} is not set in the engine environment; nothing to proxy`):proxied.push({declaration,value})}if(proxied.length===0)return;let proxy=await startCredentialProxy(proxied);if(!holds.all().includes(hold)){await proxy.close();return}proxies.set(options.holder,proxy);for(let{declaration}of proxied)setRoute(hold,declaration,proxy)}function setRoute(hold,declaration,proxy){let route=proxy.routeFor(declaration.env);route!==void 0&&declaration.baseUrlEnv!==void 0&&hold.routes.set(declaration.baseUrlEnv,route)}function detach(holder){holds.release(holder);let proxy=proxies.get(holder);return proxies.delete(holder),proxy}async function releaseCredentialProxy(holder){await detach(holder)?.close()}import{existsSync,mkdirSync,mkdtempSync,readFileSync,renameSync,rmSync,writeFileSync}from"node:fs";import{basename,delimiter,dirname,join}from"node:path";import{fileURLToPath}from"node:url";var KILL_GUARD_BASH_ENV="bash_env.sh",KILL_GUARD_BASH_KILL="bash_kill.sh",KILL_GUARD_PROMPT_HOOK_PREFIX="__senpi_kg_q=$?;",KILL_GUARD_SHIM_MARKER=".senpi-kill-guard",KILL_GUARD_JUDGE_DEADLINE_SECONDS=10,quote=text=>`'${text.replaceAll("'","'\\''")}'`,refusal=verdict=>verdict.action==="refuse"?verdict.message:"",ALL_PROCESSES=refusal(refuseAll()),PROTECTED_WITHOUT_JUDGE=refusal(refuse("R2","it names a pid the host marked protected, and the kill guard's judge is not installed to check it")),JUDGE_FAILED=refusal(refuse("R5","the kill guard's judge failed or did not answer in time, so nothing was signalled")),JUDGE_MISSING=`${KILL_GUARD_TAG} the kill guard's judge is not installed (SENPI_KILL_GUARD_EXEC), so this runs unjudged:`;function library(deadlineSeconds){return`__senpi_kg_all=${quote(ALL_PROCESSES)} __senpi_kg_protected=${quote(PROTECTED_WITHOUT_JUDGE)} __senpi_kg_failed=${quote(JUDGE_FAILED)} __senpi_kg_missing=${quote(JUDGE_MISSING)} __senpi_kg_deadline=${deadlineSeconds} # kill's arguments, decided in sh with no runtime start: 0 = only literal positive pids and none protected, # 1 = the judge decides, 2 = a literal -1 target, 3 = a literal pid the host marked protected. __senpi_kg_fast() { __senpi_kg_p=0 __senpi_kg_n=0 if [ "$#" -eq 1 ] && [ "$1" = "-1" ]; then return 2; fi case \${1-} in -l | -L) return 0 ;; --) ;; -*) shift ;; esac if [ "\${1-}" = "--" ]; then shift; fi if [ "$#" -eq 0 ]; then return 1; fi for __senpi_kg_a do case $__senpi_kg_a in -1) return 2 ;; '' | 0* | *[!0-9]*) __senpi_kg_n=1 ;; *) case ,\${SENPI_KILL_GUARD_PROTECTED-}, in *,"$__senpi_kg_a",*) __senpi_kg_p=1 ;; esac ;; esac done if [ "$__senpi_kg_p" -eq 1 ]; then return 3; fi return "$__senpi_kg_n" } __senpi_kg_present() { if [ -z "\${SENPI_KILL_GUARD_EXEC-}" ] || [ ! -f "$SENPI_KILL_GUARD_EXEC" ] || [ ! -x "$SENPI_KILL_GUARD_EXEC" ]; then return 1 fi [ -z "\${SENPI_KILL_GUARD_EXEC_ENTRY-}" ] || [ -f "$SENPI_KILL_GUARD_EXEC_ENTRY" ] } # The judge on the real argv, killed by a watchdog after the deadline: 0 allows, 126 refuses, anything else failed. __senpi_kg_judge() ( unset BUN_BE_BUN ELECTRON_RUN_AS_NODE=1 export ELECTRON_RUN_AS_NODE __senpi_kg_v=$1 shift if [ -n "\${SENPI_KILL_GUARD_EXEC_ENTRY-}" ]; then "$SENPI_KILL_GUARD_EXEC" "$SENPI_KILL_GUARD_EXEC_ENTRY" __kill-guard check --vantage "$__senpi_kg_v" -- "$@" </dev/null & else "$SENPI_KILL_GUARD_EXEC" __kill-guard check --vantage "$__senpi_kg_v" -- "$@" </dev/null & fi __senpi_kg_j=$! ( trap 'command kill "\${__senpi_kg_t-}" 2>/dev/null; exit 0' TERM command sleep "$__senpi_kg_deadline" & __senpi_kg_t=$! if wait "$__senpi_kg_t"; then command kill -KILL "$__senpi_kg_j" 2>/dev/null; fi ) </dev/null >/dev/null 2>&1 & __senpi_kg_w=$! __senpi_kg_s=0 wait "$__senpi_kg_j" || __senpi_kg_s=$? command kill "$__senpi_kg_w" 2>/dev/null || : exit "$__senpi_kg_s" ) # One invocation: $1 is the pid that will send the signal, the rest its argv. Returns 0 to run it, else its status. __senpi_kg_decide() { __senpi_kg_v=$1 shift __senpi_kg_f=1 if [ "$1" = kill ]; then shift __senpi_kg_f=0 __senpi_kg_fast "$@" || __senpi_kg_f=$? set -- kill "$@" case $__senpi_kg_f in 0) return 0 ;; 2) printf '%s\\n' "$__senpi_kg_all" >&2 return 126 ;; esac fi if ! __senpi_kg_present; then if [ "$__senpi_kg_f" -eq 3 ]; then printf '%s\\n' "$__senpi_kg_protected" >&2 return 126 fi printf '%s %s\\n' "$__senpi_kg_missing" "$1" >&2 return 0 fi __senpi_kg_s=0 __senpi_kg_judge "$__senpi_kg_v" "$@" || __senpi_kg_s=$? case $__senpi_kg_s in 0) return 0 ;; 126) return 126 ;; esac printf '%s (judge status %s)\\n' "$__senpi_kg_failed" "$__senpi_kg_s" >&2 return 126 } `}function shim(dir,name,deadlineSeconds){return`#!/bin/sh # senpi kill guard (senpi#5349): runs \`${name}\` only after the judge allows its real argv. Written by senpi. __senpi_kg_dir=${quote(dir)} __senpi_kg_name=${name} ${library(deadlineSeconds)} # The real binary: the first PATH match outside every kill-guard shim directory that no outer shim already ran. A # symlink to a shim elsewhere on PATH re-enters a shim, so each shim lists what it execs in SENPI_KILL_GUARD_VISITED and # skips every listed path: each re-entry removes one candidate, so the walk ends. __senpi_kg_find() ( set -f IFS=: for __senpi_kg_d in \${PATH-}; do if [ -z "$__senpi_kg_d" ]; then __senpi_kg_d=.; fi if [ "$__senpi_kg_d" = "$__senpi_kg_dir" ] || [ -f "$__senpi_kg_d/${KILL_GUARD_SHIM_MARKER}" ]; then continue; fi case :\${SENPI_KILL_GUARD_VISITED-}: in *:"$__senpi_kg_d/$1":*) continue ;; esac if [ -f "$__senpi_kg_d/$1" ] && [ -x "$__senpi_kg_d/$1" ]; then printf '%s\\n' "$__senpi_kg_d/$1" exit 0 fi done exit 1 ) __senpi_kg_s=0 __senpi_kg_decide "$$" "$__senpi_kg_name" "$@" || __senpi_kg_s=$? if [ "$__senpi_kg_s" -ne 0 ]; then exit "$__senpi_kg_s"; fi if __senpi_kg_real=$(__senpi_kg_find "$__senpi_kg_name"); then SENPI_KILL_GUARD_VISITED=\${SENPI_KILL_GUARD_VISITED:+$SENPI_KILL_GUARD_VISITED:}$__senpi_kg_real export SENPI_KILL_GUARD_VISITED exec "$__senpi_kg_real" "$@" fi printf '%s: command not found\\n' "$__senpi_kg_name" >&2 exit 127 `}function bashEnv(deadlineSeconds){return`# senpi kill guard (senpi#5349): BASH_ENV for agent shells. Sources the user's own BASH_ENV first, then judges # bash's builtin \`kill\` on its real argv. Written by senpi. if [ -n "\${SENPI_KILL_GUARD_USER_BASH_ENV-}" ] && [ "$SENPI_KILL_GUARD_USER_BASH_ENV" != "\${BASH_SOURCE[0]-}" ] && [ -f "$SENPI_KILL_GUARD_USER_BASH_ENV" ]; then . "$SENPI_KILL_GUARD_USER_BASH_ENV" fi ${killFunction(deadlineSeconds)}`}function killFunction(deadlineSeconds){return`${library(deadlineSeconds)} function kill { local __senpi_kg_v __senpi_kg_f __senpi_kg_s __senpi_kg_p __senpi_kg_n __senpi_kg_a __senpi_kg_decide "\${BASHPID:-$$}" kill "$@" || return command kill "$@" } `}function bashKill(deadlineSeconds){return`# senpi kill guard (senpi#5349): sourced into interactive bash by the PROMPT_COMMAND hook before the first prompt, # after the user's startup files; judges bash's builtin \`kill\` on its real argv. Written by senpi. ${killFunction(deadlineSeconds)}`}function killGuardPromptCommand(dir){let file=quote(`${dir}/${KILL_GUARD_BASH_KILL}`),user='"$SENPI_KILL_GUARD_USER_PROMPT_COMMAND"';return[KILL_GUARD_PROMPT_HOOK_PREFIX,`if [ "\${__senpi_kg_shell-}" != "$$" ]; then __senpi_kg_shell=$$; if [ -r ${file} ]; then . ${file}; fi; fi;`,'if [ -n "${SENPI_KILL_GUARD_USER_PROMPT_COMMAND-}" ] && [ "${__senpi_kg_in-}" != "$$" ]; then','__senpi_kg_rc() { return "$1"; }; __senpi_kg_run() { local __senpi_kg_in=$$;',`if __senpi_kg_rc "$__senpi_kg_q"; then eval ${user}; else eval ${user}; fi; }; __senpi_kg_run \${1+"$@"}; fi`].join(" ")}function renderKillGuardShims(dir,deadlineSeconds=KILL_GUARD_JUDGE_DEADLINE_SECONDS){return{kill:shim(dir,"kill",deadlineSeconds),pkill:shim(dir,"pkill",deadlineSeconds),killall:shim(dir,"killall",deadlineSeconds),[KILL_GUARD_BASH_ENV]:bashEnv(deadlineSeconds),[KILL_GUARD_BASH_KILL]:bashKill(deadlineSeconds)}}function installKillGuardShims(root,version,options={}){let dir=join(root,version.replace(/[^A-Za-z0-9._-]/g,"_")),files=renderKillGuardShims(dir,options.deadlineSeconds??KILL_GUARD_JUDGE_DEADLINE_SECONDS);if(matches(dir,files))return dir;mkdirSync(root,{recursive:!0});let staged=mkdtempSync(join(root,".staging-"));try{for(let[name,content]of Object.entries(files))writeFileSync(join(staged,name),content,{mode:name.endsWith(".sh")?420:493});writeFileSync(join(staged,KILL_GUARD_SHIM_MARKER),""),place(staged,dir,files)}finally{rmSync(staged,{recursive:!0,force:!0})}return dir}function matches(dir,files){return existsSync(join(dir,KILL_GUARD_SHIM_MARKER))?Object.entries(files).every(([name,content])=>{try{return readFileSync(join(dir,name),"utf8")===content}catch{return!1}}):!1}function place(staged,dir,files){try{renameSync(staged,dir);return}catch(error){if(matches(dir,files))return;if(!existsSync(dir))throw error}let stale=mkdtempSync(join(dirname(dir),".stale-"));rmSync(stale,{recursive:!0,force:!0}),renameSync(dir,stale);try{renameSync(staged,dir)}finally{rmSync(stale,{recursive:!0,force:!0})}}function isKillGuardBashEnv(base){return base.BASH_ENV!==void 0&&basename(base.BASH_ENV)===KILL_GUARD_BASH_ENV&&base.SENPI_KILL_GUARD_USER_BASH_ENV!==void 0}function nestedShellLevel(level){return level!==void 0&&/^[1-9]\d{0,2}$/.test(level)&&Number(level)<999}function killGuardEnvironment(base,runtime){let pathKey=Object.keys(base).find(key=>key.toLowerCase()==="path")??"PATH",rest=(base[pathKey]??"").split(delimiter).filter(entry=>entry!==""&&entry!==runtime.dir),userBashEnv=isKillGuardBashEnv(base)?base.SENPI_KILL_GUARD_USER_BASH_ENV:base.BASH_ENV,userPromptCommand=base.PROMPT_COMMAND?.startsWith(KILL_GUARD_PROMPT_HOOK_PREFIX)?base.SENPI_KILL_GUARD_USER_PROMPT_COMMAND:base.PROMPT_COMMAND;return{[pathKey]:[runtime.dir,...rest].join(delimiter),BASH_ENV:runtime.bashEnv,SENPI_KILL_GUARD_USER_BASH_ENV:userBashEnv??"",PROMPT_COMMAND:killGuardPromptCommand(runtime.dir),SENPI_KILL_GUARD_USER_PROMPT_COMMAND:userPromptCommand??"",SENPI_KILL_GUARD_PROTECTED:runtime.protectedPids.join(","),SENPI_KILL_GUARD_EXEC:runtime.exec,SENPI_KILL_GUARD_EXEC_ENTRY:runtime.entry??"",SENPI_KILL_GUARD_AGENT_PID:String(runtime.agentPid),...nestedShellLevel(base.SHLVL)?{}:{SHLVL:"1"}}}function judgeEntry(){if(isBunBinary)return;let here=import.meta.url;return/\/core\/kill-guard\/runtime\.(ts|js)$/.test(here)?fileURLToPath(new URL(here.endsWith(".ts")?"./check-entry.ts":"./check-entry.js",here)):fileURLToPath(new URL("./kill-guard-check.js",here))}var killGuardRuntimes=realmRegistry("@code-yeongyu/senpi/kill-guard/v1",()=>{let installed=new Map,holders=new Map;return{activate:(holder,agentDir,make)=>{let runtime=installed.get(agentDir);return runtime===void 0&&(runtime=make([...installed.values()][0]),installed.set(agentDir,runtime)),holders.delete(holder),holders.set(holder,runtime),runtime},release:holder=>{holders.delete(holder)},active:()=>{let active;for(let runtime of holders.values())active=runtime;return active}}},value=>hasFunctions(value,["activate","release","active"])),ownRecords=new Map,localRuntimes=new Map,isNumberArray=value=>Array.isArray(value)&&value.every(entry=>typeof entry=="number");function isKillGuardRuntime(value){if(typeof value!="object"||value===null)return!1;let field=name=>Reflect.get(value,name),entry=field("entry");return typeof field("dir")=="string"&&typeof field("bashEnv")=="string"&&typeof field("exec")=="string"&&(entry===void 0||typeof entry=="string")&&typeof field("agentPid")=="number"&&isNumberArray(field("protectedPids"))}function buildRuntime(agentDir,protectedPids){let dir=installKillGuardShims(join(agentDir,"kill-guard"),VERSION);return Object.freeze({dir,bashEnv:join(dir,KILL_GUARD_BASH_ENV),exec:process.execPath,entry:judgeEntry(),agentPid:process.pid,protectedPids})}function activateKillGuardRuntime(options){if((options.platform??process.platform)==="win32")return;let shared=killGuardRuntimes.activate(options.holder,options.agentDir,first=>{let firstPids=typeof first=="object"&&first!==null?Reflect.get(first,"protectedPids"):void 0;return buildRuntime(options.agentDir,isNumberArray(firstPids)?firstPids:options.protectedPids())});if(ownRecords.delete(options.holder),isKillGuardRuntime(shared))return ownRecords.set(options.holder,shared),shared;let local=localRuntimes.get(options.agentDir);return local===void 0&&(local=buildRuntime(options.agentDir,options.protectedPids()),localRuntimes.set(options.agentDir,local)),ownRecords.set(options.holder,local),options.warn?.(`[senpi:kill-guard] shared record unreadable; local record in use for ${options.agentDir}`),local}function releaseKillGuardRuntime(holder){ownRecords.delete(holder),killGuardRuntimes.release(holder)}function activeKillGuardRuntime(){let active=killGuardRuntimes.active();if(active===void 0||isKillGuardRuntime(active))return active;let own;for(let record of ownRecords.values())own=record;return own}function withKillGuardRuntime(env){let active=activeKillGuardRuntime();return active===void 0?env:{...env,...killGuardEnvironment(env,active)}}function activeKillGuardEnvironment(base){let active=activeKillGuardRuntime();return active===void 0?{}:killGuardEnvironment(base,active)}import{createHash}from"node:crypto";import{chmodSync,mkdirSync as mkdirSync2,readFileSync as readFileSync2,renameSync as renameSync2,writeFileSync as writeFileSync2}from"node:fs";import{tmpdir}from"node:os";import{delimiter as delimiter2,join as join2}from"node:path";var POSIX_VARIANTS=[{name:"bun",bunxArg:!1},{name:"bunx",bunxArg:!0}],CMD_VARIANTS=[{name:"bun.cmd",bunxArg:!1},{name:"bunx.cmd",bunxArg:!0}],UNREPRESENTABLE_EXIT=78;function noticeText(trust){if(trust.fallbackReason===null)return;let{text}=engineTrustAction(trust.fallbackReason);return`omo notice: certificate import is degraded (${trust.fallbackReason}); some TLS connections may fail. ${text}`}var quote2=value=>`'${value.replaceAll("'","'\\''")}'`;function posixShimFiles(execPath,dir,trust){return POSIX_VARIANTS.map(({name,bunxArg})=>{let target=`exec ${quote2(execPath)}${bunxArg?" x":""} "$@"`;if(trust===void 0)return[name,`#!/bin/sh BUN_BE_BUN=1 ${target} `];let lines=["#!/bin/sh"],notice=noticeText(trust);if(notice!==void 0){let sentinel=quote2(`${dir}/.fallback-noted`);lines.push(`[ -e ${sentinel} ] || { printf '%s\\n' ${quote2(notice)} >&2; true 2>/dev/null > ${sentinel} || :; }`)}trust.owner==="server"&&lines.push("unset NODE_USE_SYSTEM_CA BUN_OPTIONS");let closure=trust.defaults===null?"":` SSL_CERT_FILE=${quote2(trust.defaults.file)} SSL_CERT_DIR=${quote2(trust.defaults.dir)}`;return lines.push(`BUN_BE_BUN=1 NODE_EXTRA_CA_CERTS=${quote2(trust.file)}${closure} ${target}`,""),[name,lines.join(` `)]})}var cmdRepresentable=value=>!/["\u0000-\u001f]/u.test(value),cmdValue=value=>value.replaceAll("%","%%"),cmdEcho=value=>cmdValue(value).replace(/[\^&|<>()]/gu,char=>`^${char}`);function cmdShimFiles(execPath,dir,trust){if(trust===void 0)return CMD_VARIANTS.map(({name,bunxArg})=>{let run=`"${execPath}" ${bunxArg?"x ":""}%*`;return[name,`@echo off\r set BUN_BE_BUN=1\r ${run}\r exit /b %ERRORLEVEL%\r `]});if(![execPath,dir,trust.file,trust.defaults?.file??"",trust.defaults?.dir??""].every(cmdRepresentable)){let{text}=engineTrustAction("trust-path-unrepresentable"),failing=`@echo off\r >&2 echo omo: trust-path-unrepresentable: ${cmdEcho(text)}\r exit /b ${UNREPRESENTABLE_EXIT}\r `;return CMD_VARIANTS.map(({name})=>[name,failing])}return CMD_VARIANTS.map(({name,bunxArg})=>{let run=`"${cmdValue(execPath)}" ${bunxArg?"x ":""}%*`,lines=["@echo off","setlocal"],notice=noticeText(trust);if(notice!==void 0){let sentinel=`"${cmdValue(dir)}\\.fallback-noted"`;lines.push(`if not exist ${sentinel} ( >&2 echo ${cmdEcho(notice)}& type nul > ${sentinel} )`)}return trust.owner==="server"&&lines.push('set "NODE_USE_SYSTEM_CA="','set "BUN_OPTIONS="'),lines.push('set "BUN_BE_BUN=1"',`set "NODE_EXTRA_CA_CERTS=${cmdValue(trust.file)}"`),trust.defaults!==null&&lines.push(`set "SSL_CERT_FILE=${cmdValue(trust.defaults.file)}"`,`set "SSL_CERT_DIR=${cmdValue(trust.defaults.dir)}"`),lines.push(run,"exit /b %ERRORLEVEL%",""),[name,lines.join(`\r `)]})}var EMBEDDED_ENTRY=/^(?:\/\$bunfs\/|[A-Za-z]:[\\/]~BUN[\\/])/;function isCompiledBunExecutable(main){return main!==void 0&&EMBEDDED_ENTRY.test(main)}function currentHost(){return{main:globalThis.Bun?.main,execPath:process.execPath,platform:process.platform,shimRoots:[join2(getAgentDir(),"bundled-bun"),join2(tmpdir(),"senpi-bundled-bun")],trust:adoptedEngineTrust()}}function shimFiles(host,dir){return host.platform==="win32"?cmdShimFiles(host.execPath,dir,host.trust):posixShimFiles(host.execPath,dir,host.trust)}function shimKey(host){let{trust}=host;if(trust===void 0)return host.execPath;let closure=trust.defaults===null?"opt-in":`${trust.defaults.file}\0${trust.defaults.dir}`;return[host.execPath,trust.file,closure,trust.owner,trust.fallbackReason??"complete"].join("\0")}function writeIfChanged(path,content){let current;try{current=readFileSync2(path,"utf8")}catch{}if(current!==content){let staged=`${path}.${process.pid}.tmp`;writeFileSync2(staged,content,{mode:493}),renameSync2(staged,path)}chmodSync(path,493)}function materialize(root,host){let dir=join2(root,createHash("sha256").update(shimKey(host)).digest("hex").slice(0,16));try{mkdirSync2(dir,{recursive:!0});for(let[name,content]of shimFiles(host,dir))writeIfChanged(join2(dir,name),content);return dir}catch{return}}var resolved=new Map;function bundledBunDir(host=currentHost()){if(!isCompiledBunExecutable(host.main))return;let key=`${shimKey(host)}\0${host.shimRoots.join("\0")}`;if(!resolved.has(key)){let dir;for(let root of host.shimRoots)if(dir=materialize(root,host),dir!==void 0)break;resolved.set(key,dir)}return resolved.get(key)}function withBundledBunCommands(env,host){let dir=bundledBunDir(host);if(dir===void 0)return env;let pathKey=Object.keys(env).find(key=>key.toLowerCase()==="path")??"PATH",entries=(env[pathKey]??"").split(delimiter2).filter(Boolean);return entries.includes(dir)?env:{...env,[pathKey]:[...entries,dir].join(delimiter2)}}import{existsSync as existsSync2}from"node:fs";import{delimiter as delimiter3,join as join3}from"node:path";import{spawnSync}from"node:child_process";var WINDOWS_PROCESS_TREE_ROWS=`Get-CimInstance Win32_Process | Where-Object { $_.ProcessId -ne $PID } | ForEach-Object { $created = if ($_.CreationDate) { $_.CreationDate.ToFileTimeUtc() } else { 0 } "{0} {1} {2} {3}" -f $_.ProcessId, $_.ParentProcessId, $created, $_.Name }`;function parseWindowsProcessTreeRows(stdout){let rows=[];for(let line of stdout.split(/\r?\n/u)){let[pidText,parentText,createdText,...nameParts]=line.trim().split(/\s+/u),pid=Number(pidText),parentPid=Number(parentText);!Number.isInteger(pid)||pid<=0||!Number.isInteger(parentPid)||!/^\d+$/u.test(createdText??"")||rows.push({pid,parentPid,createdAt:BigInt(createdText??"0"),name:nameParts.join(" ")})}return rows}var PROTECTED_IMAGES=new Set(["system","smss.exe","csrss.exe","wininit.exe","winlogon.exe","services.exe","lsass.exe","lsaiso.exe","svchost.exe"]);function windowsTreeKillPlan(rows,rootPid,selfPid){let byPid=new Map(rows.map(row=>[row.pid,row]));if(byPid.get(rootPid)===void 0)return{kill:[],refused:[]};let tree=new Set([rootPid]),grew=!0;for(;grew;){grew=!1;for(let row of rows){if(tree.has(row.pid)||!tree.has(row.parentPid))continue;let parent=byPid.get(row.parentPid);parent===void 0||row.createdAt<parent.createdAt||(tree.add(row.pid),grew=!0)}}let ancestors=new Set([selfPid]);for(let current=byPid.get(selfPid);current!==void 0;){let parent=byPid.get(current.parentPid);if(parent===void 0||ancestors.has(parent.pid)||parent.createdAt>current.createdAt)break;ancestors.add(parent.pid),current=parent}let refused=[...tree].map(pid=>({pid,name:byPid.get(pid)?.name??""})).filter(entry=>PROTECTED_IMAGES.has(entry.name.toLowerCase())||ancestors.has(entry.pid));return refused.length===0?{kill:[...tree],refused}:{kill:refused.some(entry=>entry.pid===rootPid)?[]:[rootPid],refused}}function listWindowsProcessRowsSync(timeoutMs){let result=spawnSync("powershell.exe",["-NoProfile","-NonInteractive","-Command",WINDOWS_PROCESS_TREE_ROWS],{encoding:"utf8",windowsHide:!0,timeout:timeoutMs,maxBuffer:16777216});if(result.error!==void 0||result.status!==0||typeof result.stdout!="string")return;let rows=parseWindowsProcessTreeRows(result.stdout);return rows.length>0?rows:void 0}function windowsTreeKillArgs(rootPid,rows,selfPid=process.pid){if(rows===void 0)return["/F","/T","/PID",String(rootPid)];let pids=windowsTreeKillPlan(rows,rootPid,selfPid).kill;return pids.length===0?[]:["/F",...pids.flatMap(pid=>["/PID",String(pid)])]}var MAX_TIMEOUT_MS=2147483647,MAX_TIMEOUT_SECONDS=MAX_TIMEOUT_MS/1e3;var SPILL_HIGH_WATER_MARK=8*1024*1024;import{spawn}from"node:child_process";import{constants}from"node:fs";import{lstat,mkdir,open,readdir,rename,rm}from"node:fs/promises";import{dirname as dirname2}from"node:path";function deviceError(error,path){if(error instanceof DeviceFileError)return error;let code=error.code,message=error instanceof Error?error.message:String(error);return code==="ENOENT"?new DeviceFileError("not_found",path):code==="EEXIST"?new DeviceFileError("exists",path):code==="EISDIR"||code==="ENOTDIR"||code==="ENXIO"?new DeviceFileError("not_a_file",path):code==="ABORT_ERR"?new DeviceFileError("aborted",path):new DeviceFileError("io",message)}async function guarded(path,signal,run){if(signal?.aborted)throw new DeviceFileError("aborted",path);try{return await run()}catch(error){throw deviceError(error,path)}}async function openRegular(path,flags){let handle=await open(path,flags|constants.O_NONBLOCK,438);try{if(!(await handle.stat()).isFile())throw new DeviceFileError("not_a_file",path);return handle}catch(error){throw await handle.close(),error}}async function readBounded(path,signal){let handle=await openRegular(path,constants.O_RDONLY);try{let chunks=[],total=0;for(;;){if(signal?.aborted)throw new DeviceFileError("aborted",path);let chunk=new Uint8Array(64*1024),{bytesRead}=await handle.read(chunk,0,chunk.length,null);if(bytesRead===0)break;if(total+=bytesRead,total>FILE_CHANNEL_MAX_BYTES)throw new DeviceFileError("too_large",path);chunks.push(chunk.subarray(0,bytesRead))}let bytes=new Uint8Array(total),offset=0;for(let chunk of chunks)bytes.set(chunk,offset),offset+=chunk.length;return bytes}finally{await handle.close()}}function runDirect(request,signal){return new Promise((done,fail)=>{let child=spawn(request.exe,[...request.argv],{cwd:request.cwd,env:request.env===void 0?process.env:{...process.env,...request.env},shell:!1,windowsHide:!0,...signal===void 0?{}:{signal}}),out=[],err2=[];child.stdout.on("data",chunk=>out.push(chunk)),child.stderr.on("data",chunk=>err2.push(chunk));let killTimer,timer=request.timeoutMs===void 0?void 0:setTimeout(()=>{child.kill("SIGTERM"),killTimer=setTimeout(()=>child.kill("SIGKILL"),1e4)},request.timeoutMs);child.on("error",error=>fail(new DeviceFileError(signal?.aborted?"aborted":"io",error.message))),child.on("close",(code,exitSignal)=>{clearTimeout(timer),clearTimeout(killTimer),done({code,signal:exitSignal,stdout:new Uint8Array(Buffer.concat(out)),stderr:Buffer.concat(err2).toString("utf8")})}),child.stdin.on("error",()=>{}),child.stdin.end(request.stdin===void 0?void 0:Buffer.from(request.stdin))})}function statOf(entry){return{kind:entry.isFile()?"file":entry.isDirectory()?"directory":"other",size:entry.size,mtimeMs:entry.mtimeMs}}function localDeviceFiles(){return{read:(path,options)=>guarded(path,options?.signal,()=>readBounded(path,options?.signal)),write:(path,data,options)=>guarded(path,options?.signal,async()=>{if(data.byteLength>FILE_CHANNEL_MAX_BYTES)throw new DeviceFileError("too_large",path);await mkdir(dirname2(path),{recursive:!0});let handle=await openRegular(path,constants.O_WRONLY|constants.O_CREAT|constants.O_TRUNC|(options?.exclusive?constants.O_EXCL:0));try{await handle.writeFile(data)}finally{await handle.close()}}),list:(path,options)=>guarded(path,options?.signal,()=>readdir(path)),stat:(path,options)=>guarded(path,options?.signal,async()=>statOf(await lstat(path))),rename:(from,to,options)=>guarded(from,options?.signal,()=>rename(from,to)),remove:(path,options)=>guarded(path,options?.signal,async()=>{await lstat(path),await rm(path,{recursive:!0})}),mkdir:(path,options)=>guarded(path,options?.signal,async()=>{await mkdir(path,{recursive:!0})}),run:(request,options)=>runDirect(request,options?.signal),[LOCAL_DEVICE_FILES]:!0}}import{spawnSync as spawnSync2}from"child_process";var GIT_BASH_PATH_ENV="SENPI_GIT_BASH_PATH";function isLegacyWslBashPath(path){let normalized=path.replace(/\//g,"\\").toLowerCase();return/^[a-z]:\\windows\\(?:system32|sysnative)\\bash\.exe$/.test(normalized)}function resolveShellKind(shellPath){let base=shellPath.replace(/\\/g,"/").split("/").pop()?.toLowerCase().replace(/\.exe$/,"");return base==="cmd"?"cmd":base==="powershell"||base==="pwsh"?"powershell":base==="sh"?"sh":"bash"}function getBashShellConfig(shell){return isLegacyWslBashPath(shell)?{shell,args:["-s"],commandTransport:"stdin",kind:"bash"}:{shell,args:["-c"],kind:"bash"}}function getShellConfigForPath(shellPath){let kind=resolveShellKind(shellPath);switch(kind){case"cmd":return{shell:shellPath,args:["/c"],kind};case"powershell":return{shell:shellPath,args:["-NoProfile","-Command"],kind};case"sh":return{shell:shellPath,args:["-c"],kind};default:return getBashShellConfig(shellPath)}}function findExecutableOnPath(executable){if(process.platform==="win32"){try{let result=spawnSync2("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&&existsSync2(firstMatch))return firstMatch}}catch{}return null}try{let result=spawnSync2("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(existsSync2(customShellPath))return getShellConfigForPath(customShellPath);throw new Error(`Custom shell path not found: ${customShellPath}`)}let gitBashOverride=process.env[GIT_BASH_PATH_ENV];if(gitBashOverride){if(existsSync2(gitBashOverride))return getShellConfigForPath(gitBashOverride);throw new Error(`${GIT_BASH_PATH_ENV} points to a missing shell: ${gitBashOverride}`)}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(existsSync2(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(existsSync2("/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")??findExecutableOnPath("powershell.exe");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(){return withKillGuardRuntime(withCredentialProxy(getUserShellEnv()))}function getUserShellEnv(){let binDir=getBinDir(),pathKey=Object.keys(process.env).find(key=>key.toLowerCase()==="path")??"PATH",currentPath=process.env[pathKey]??"",updatedPath=currentPath.split(delimiter3).filter(Boolean).includes(binDir)?currentPath:[binDir,currentPath].filter(Boolean).join(delimiter3);return withBundledBunCommands({...childEnvironmentOf(process.env),[pathKey]:updatedPath})}function sanitizeBinaryOutput(str){return hasUnsafeDisplayCharacter(str)?str.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\uFFF9-\uFFFB]/g,""):str}function hasUnsafeDisplayCharacter(str){for(let i=0;i<str.length;i++){let code=str.charCodeAt(i),isAllowedControl=code===9||code===10||code===13;if(code<=31&&!isAllowedControl||code>=65529&&code<=65531)return!0}return!1}var trackedDetachedChildren=new Map;function trackDetachedChildPid(pid){trackedDetachedChildren.set(pid,{pid,pgid:pid,leaderExited:!1})}function untrackDetachedChildPid(pid){trackedDetachedChildren.delete(pid)}function noteDetachedChildExited(pid){let entry=trackedDetachedChildren.get(pid);if(entry!==void 0){if(process.platform==="win32"||!processGroupIsAlive(entry.pgid)){trackedDetachedChildren.delete(pid);return}entry.leaderExited=!0}}function pruneTrackedDetachedChildren(){if(process.platform!=="win32")for(let[pid,entry]of trackedDetachedChildren)trackedDetachedChildIsGone(entry)&&trackedDetachedChildren.delete(pid)}function signalTargetExists(target){try{return process.kill(target,0),!0}catch(error){return error.code!=="ESRCH"}}function processGroupIsAlive(pgid){return signalTargetExists(-pgid)}function trackedDetachedChildIsGone(entry){return processGroupIsAlive(entry.pgid)?!1:entry.leaderExited||!signalTargetExists(entry.pid)}function killTrackedDetachedChildren(){if(pruneTrackedDetachedChildren(),trackedDetachedChildren.size===0)return;let rows=process.platform==="win32"?listWindowsProcesses():void 0;for(let entry of trackedDetachedChildren.values())process.platform==="win32"?killWindowsProcessTree(entry.pid,void 0,()=>rows):killTrackedDetachedGroup(entry);trackedDetachedChildren.clear()}function killTrackedDetachedGroup(entry){try{process.kill(-entry.pgid,"SIGKILL");return}catch{}if(!entry.leaderExited)try{process.kill(entry.pid,"SIGKILL")}catch{}}function windowsTaskkillCandidates(env=process.env){let systemDrive=env.SystemDrive?`${env.SystemDrive}\\`:void 0,roots=[env.SystemRoot,env.SYSTEMROOT,env.windir,systemDrive&&join3(systemDrive,"Windows")],candidates=[];for(let root of roots)if(root)for(let systemDir of["System32","Sysnative"]){let absolute=join3(root,systemDir,"taskkill.exe");!candidates.includes(absolute)&&existsSync2(absolute)&&candidates.push(absolute)}return candidates.push("taskkill.exe"),candidates}function killProcessDirectly(pid){try{process.kill(pid)}catch{}}var TASKKILL_TIMEOUT_MS=5e3;function listWindowsProcesses(){return listWindowsProcessRowsSync(TASKKILL_TIMEOUT_MS)}function taskkillHandledTree(taskkillPath,killArgs){if(killArgs.length===0)return!0;try{let result=spawnSync2(taskkillPath,[...killArgs],{stdio:"ignore",windowsHide:!0,timeout:TASKKILL_TIMEOUT_MS});return result.error===void 0&&result.status!==null}catch{return!1}}function killWindowsProcessTree(pid,taskkillPaths=windowsTaskkillCandidates(),listProcesses=listWindowsProcesses){let killArgs=windowsTreeKillArgs(pid,listProcesses());for(let taskkillPath of taskkillPaths)if(taskkillHandledTree(taskkillPath,killArgs))return;killProcessDirectly(pid)}function killProcessTree(pid){if(process.platform==="win32")killWindowsProcessTree(pid);else try{process.kill(-pid,"SIGKILL")}catch{try{process.kill(pid,"SIGKILL")}catch{}}}export{localDeviceFiles,CREDENTIAL_PLACEHOLDER,withCredentialProxy,activateCredentialProxy,releaseCredentialProxy,activateKillGuardRuntime,releaseKillGuardRuntime,activeKillGuardEnvironment,withBundledBunCommands,getShellConfig,getPowerShellConfig,getShellEnv,getUserShellEnv,sanitizeBinaryOutput,trackDetachedChildPid,untrackDetachedChildPid,noteDetachedChildExited,pruneTrackedDetachedChildren,killTrackedDetachedChildren,killWindowsProcessTree,killProcessTree};