@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
15 lines (14 loc) • 29.2 kB
JavaScript
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{require_cross_spawn}from"./chunk-ATQFN5HI.js";import{__toESM}from"./chunk-IKOFCODM.js";import{isAbsolute}from"node:path";var BRAND_ENV_VAR="SENPI_BRAND";function readChangelog(source){let value=source.changelog;if(typeof value!="object"||value===null||Array.isArray(value))return;let changelog=value,path=readString(changelog,"path");if(!path?.startsWith("/")||path.includes("\0"))return;let version=readString(changelog,"version");return{path,...version?{version}:{}}}function readExtensions(source){let value=source.extensions;if(!Array.isArray(value))return;let paths=value.filter(path=>typeof path=="string"&&isAbsolute(path)&&!path.includes("\0"));return paths.length>0?paths:void 0}function readUpdateChannel(source){let update=source.update;if(typeof update!="object"||update===null||Array.isArray(update))return;let channel=update,packageName=readString(channel,"packageName"),command=readString(channel,"command");if(!(!packageName||!command))return{packageName,distTag:readString(channel,"distTag")||"latest",command,changelogUrl:readString(channel,"changelogUrl")}}function isSafeConfigDirName(value){return value!=="."&&value!==".."&&!/[\\/]/.test(value)}function readString(source,key){let value=source[key];return typeof value=="string"&&value.trim()?value.trim():void 0}function parseBrandProfile(raw){if(!raw?.trim())return;let parsed;try{parsed=JSON.parse(raw)}catch{process.stderr.write(`warning: ignoring malformed ${BRAND_ENV_VAR} (expected JSON)
`);return}if(typeof parsed!="object"||parsed===null||Array.isArray(parsed)){process.stderr.write(`warning: ignoring malformed ${BRAND_ENV_VAR} (expected a JSON object)
`);return}let source=parsed,name=readString(source,"name");if(!name){process.stderr.write(`warning: ignoring ${BRAND_ENV_VAR} without a "name"
`);return}let configDir=readString(source,"configDir")||`.${name}`;if(!isSafeConfigDirName(configDir)){process.stderr.write(`warning: ignoring ${BRAND_ENV_VAR} with an unsafe "configDir"
`);return}let changelog=readChangelog(source),extensions=readExtensions(source);return{name,command:readString(source,"command"),displayVersion:readString(source,"displayVersion"),configDir,flatLayout:source.flatLayout===!0,envPrefix:(readString(source,"envPrefix")||name).toUpperCase(),userAgent:readString(source,"userAgent")||name,originator:readString(source,"originator"),logo:readString(source,"logo"),update:readUpdateChannel(source),...changelog?{changelog}:{},...extensions?{extensions}:{}}}function consumeBrandProfile(env=process.env){return parseBrandProfile(env[BRAND_ENV_VAR])}function scrubBrandFromEnvironment(env=process.env){delete env[BRAND_ENV_VAR]}var LEGACY_ENV_PREFIXES=["SENPI","PI"],cachedProfile,profileResolved=!1;function brandProfile(){return profileResolved||(cachedProfile=consumeBrandProfile(),profileResolved=!0),cachedProfile}function brandEnvNames(suffix,profile=brandProfile()){let prefixes=[profile?.envPrefix,...LEGACY_ENV_PREFIXES].filter(prefix=>typeof prefix=="string"&&prefix.length>0);return[...new Set(prefixes)].map(prefix=>`${prefix}_${suffix}`)}function envValue(suffix,env=process.env){for(let name of brandEnvNames(suffix)){let value=env[name];if(value!==void 0)return value}}var import_cross_spawn=__toESM(require_cross_spawn(),1);import{spawn as nodeSpawn,spawnSync as nodeSpawnSync}from"node:child_process";var EXIT_STDIO_GRACE_MS=250,ABORT_EXIT_GRACE_MS=5e3;function spawnProcess(command,args,options){return process.platform==="win32"?(0,import_cross_spawn.default)(command,args,options):nodeSpawn(command,args,options)}function spawnProcessSync(command,args,options){return process.platform==="win32"?import_cross_spawn.default.sync(command,args,options):nodeSpawnSync(command,args,options)}function waitForChildProcess(child,options){return new Promise((resolve2,reject)=>{let settled=!1,exited=!1,exitCode=null,postExitTimer,abortGraceTimer,detachAbortListener,stdoutEnded=child.stdout===null,stderrEnded=child.stderr===null,cleanup=()=>{postExitTimer&&(clearTimeout(postExitTimer),postExitTimer=void 0),abortGraceTimer&&(clearTimeout(abortGraceTimer),abortGraceTimer=void 0),detachAbortListener&&(detachAbortListener(),detachAbortListener=void 0),child.removeListener("error",onError),child.removeListener("exit",onExit),child.removeListener("close",onClose),child.stdout?.removeListener("end",onStdoutEnd),child.stderr?.removeListener("end",onStderrEnd),child.stdout?.removeListener("data",onData),child.stderr?.removeListener("data",onData)},finalize=code=>{settled||(settled=!0,cleanup(),child.stdout?.destroy(),child.stderr?.destroy(),resolve2(code))},maybeFinalizeAfterExit=()=>{!exited||settled||stdoutEnded&&stderrEnded&&finalize(exitCode)},armIdleTimer=()=>{postExitTimer&&clearTimeout(postExitTimer),postExitTimer=setTimeout(()=>finalize(exitCode),EXIT_STDIO_GRACE_MS)},onData=()=>{exited&&!settled&&armIdleTimer()},onStdoutEnd=()=>{stdoutEnded=!0,maybeFinalizeAfterExit()},onStderrEnd=()=>{stderrEnded=!0,maybeFinalizeAfterExit()},onError=err=>{settled||(settled=!0,cleanup(),reject(err))},onExit=code=>{exited=!0,exitCode=code,maybeFinalizeAfterExit(),settled||armIdleTimer()},onClose=code=>{finalize(code)},onAbortRelease=()=>{if(child.stdout?.destroy(),child.stderr?.destroy(),stdoutEnded=!0,stderrEnded=!0,exited){maybeFinalizeAfterExit();return}abortGraceTimer=setTimeout(()=>finalize(exitCode),options?.abortExitGraceMs??ABORT_EXIT_GRACE_MS)};child.stdout?.once("end",onStdoutEnd),child.stderr?.once("end",onStderrEnd),child.stdout?.on("data",onData),child.stderr?.on("data",onData),child.once("error",onError),child.once("exit",onExit),child.once("close",onClose);let abortSignal=options?.signal;abortSignal&&(abortSignal.aborted?onAbortRelease():(abortSignal.addEventListener("abort",onAbortRelease,{once:!0}),detachAbortListener=()=>abortSignal.removeEventListener("abort",onAbortRelease)))})}import{createHash}from"node:crypto";import{lstatSync,readFileSync,readlinkSync,realpathSync,statSync}from"node:fs";import{homedir}from"node:os";import{isAbsolute as isAbsolute2,join,resolve as nodeResolvePath,parse,relative,sep}from"node:path";import{fileURLToPath}from"node:url";var UNICODE_SPACES=/[\u00A0\u2000-\u200A\u202F\u205F\u3000]/g;function canonicalizePath(path){try{return realpathSync.native(path)}catch{return path}}function canonicalizePathStrict(path){return realpathSync.native(path)}var MAX_SYMLINK_HOPS=40,MISSING_PATH_CODES=new Set(["ENOENT","ENOTDIR"]);function splitParts(pathSegment){return pathSegment.split(sep).filter(part=>part.length>0)}function resolveWithoutOpen(inputPath){let absolutePath=isAbsolute2(inputPath)?inputPath:nodeResolvePath(inputPath),{root}=parse(absolutePath),pending=splitParts(absolutePath.slice(root.length)),resolved=[],hops=0;for(;pending.length>0;){let part=pending.shift();if(part===void 0)break;if(part===".")continue;if(part===".."){resolved.pop();continue}let candidate=join(root,...resolved,part),link;try{if(!lstatSync(candidate).isSymbolicLink()){resolved.push(part);continue}if(hops+=1,hops>MAX_SYMLINK_HOPS)return{path:join(candidate,...pending),errorCode:"ELOOP"};link=readlinkSync(candidate)}catch(error){let code=error?.code??"UNKNOWN";return{path:join(candidate,...pending),errorCode:code}}isAbsolute2(link)?(resolved.length=0,pending.unshift(...splitParts(link.slice(parse(link).root.length)))):pending.unshift(...splitParts(link))}return{path:join(root,...resolved)}}function realpathWithoutOpen(inputPath){return resolveWithoutOpen(inputPath).path}function realpathWithoutOpenStrict(inputPath){let resolution=resolveWithoutOpen(inputPath);if(resolution.errorCode!==void 0&&!MISSING_PATH_CODES.has(resolution.errorCode))throw Object.assign(new Error(`${resolution.errorCode}: cannot resolve path '${inputPath}' without opening it`),{code:resolution.errorCode,path:inputPath});return resolution.path}function getFileRevision(path){try{let stats=statSync(path,{bigint:!0});return`${stats.dev}:${stats.ino}:${stats.size}:${stats.mtimeNs}:${stats.ctimeNs}`}catch{return}}function getFileContentRevision(path){try{return createHash("sha256").update(readFileSync(path)).digest("hex")}catch{return}}function isLocalPath(value){let trimmed=value.trim();return!(trimmed.startsWith("npm:")||trimmed.startsWith("git:")||trimmed.startsWith("github:")||trimmed.startsWith("http:")||trimmed.startsWith("https:")||trimmed.startsWith("ssh:")||trimmed.startsWith("builtin:"))}function normalizeWindowsShellPath(filePath){if(!filePath.startsWith("/")||filePath.startsWith("//")||filePath.includes("\\"))return filePath;let match=filePath.match(/^\/(?:mnt\/|cygdrive\/)?([a-z])(?:\/(.*))?$/i);if(!match)return filePath;let suffix=match[2]?.replaceAll("/","\\");return`${match[1].toUpperCase()}:\\${suffix??""}`}function normalizePath(input,options={}){let normalized=options.trim?input.trim():input;if(options.normalizeUnicodeSpaces&&(normalized=normalized.replace(UNICODE_SPACES," ")),options.stripAtPrefix&&normalized.startsWith("@")&&(normalized=normalized.slice(1)),process.platform==="win32"&&(normalized=normalizeWindowsShellPath(normalized)),options.expandTilde??!0){let home=options.homeDir??homedir();if(normalized==="~")return home;if(normalized.startsWith("~/")||process.platform==="win32"&&normalized.startsWith("~\\"))return join(home,normalized.slice(2))}return/^file:\/\//.test(normalized)?fileURLToPath(normalized):normalized}function resolvePath(input,baseDir=process.cwd(),options={}){let normalized=normalizePath(input,options),normalizedBaseDir=normalizePath(baseDir);return isAbsolute2(normalized)?nodeResolvePath(normalized):nodeResolvePath(normalizedBaseDir,normalized)}function getCwdRelativePath(filePath,cwd){let resolvedCwd=resolvePath(cwd),resolvedPath=resolvePath(filePath,resolvedCwd),relativePath=relative(resolvedCwd,resolvedPath);return relativePath===""||relativePath!==".."&&!relativePath.startsWith(`..${sep}`)&&!isAbsolute2(relativePath)?relativePath||".":void 0}function formatPathRelativeToCwdOrAbsolute(filePath,cwd){let absolutePath=resolvePath(filePath,cwd);return(getCwdRelativePath(absolutePath,cwd)??absolutePath).split(sep).join("/")}function shortenPath(path){if(!path)return path;let home=homedir();return path.startsWith(home)?`~${path.slice(home.length)}`:path}function markPathIgnoredByCloudSync(path){let attrs=process.platform==="darwin"?["com.dropbox.ignored","com.apple.fileprovider.ignore#P"]:process.platform==="linux"?["user.com.dropbox.ignored"]:[];for(let attr of attrs)process.platform==="darwin"?spawnProcessSync("xattr",["-w",attr,"1",path],{encoding:"utf-8",stdio:"ignore"}):spawnProcessSync("setfattr",["-n",attr,"-v","1",path],{encoding:"utf-8",stdio:"ignore"})}import{accessSync,constants,existsSync,readFileSync as readFileSync3,realpathSync as realpathSync2}from"fs";import{homedir as homedir2,userInfo as userInfo2}from"os";import{basename,dirname as dirname3,join as join5,resolve,sep as sep2,win32}from"path";import{fileURLToPath as fileURLToPath2}from"url";import{dirname,join as join2}from"node:path";var BUN_LAUNCHER_REPAIR_SOURCE=`
import { renameSync, writeFileSync } from "node:fs";
const [launcher, entrypoint] = process.argv.slice(1);
if (!launcher || !entrypoint) throw new Error("Missing Bun launcher repair path");
const quote = (value) => "'" + value.replaceAll("'", "'\\"'\\"'") + "'";
const temporary = launcher + "." + process.pid + ".tmp";
writeFileSync(temporary, "#!/bin/sh\\nexec " + quote(process.execPath) + " " + quote(entrypoint) + " \\"$@\\"\\n", { mode: 0o755 });
renameSync(temporary, launcher);
`.trim();function createBunLauncherRepairCommand(binDir,packageName,executableName){let packageDir=join2(dirname(binDir),"install","global","node_modules",...packageName.split("/")),launcher=join2(binDir,executableName),entrypoint=join2(packageDir,"dist","cli.js");return{command:"bun",args:["-e",BUN_LAUNCHER_REPAIR_SOURCE,launcher,entrypoint],display:`repair Bun launcher ${launcher}`}}import{lstatSync as lstatSync2}from"node:fs";import{userInfo}from"node:os";import{dirname as dirname2,join as join3,normalize}from"node:path";var MAX_PARENT_CONFIG_SEARCH_DEPTH=100;function isDirectory(path){try{return lstatSync2(path).isDirectory()}catch{return!1}}function isFile(path){try{return lstatSync2(path).isFile()}catch{return!1}}function realAccountHomeDir(){try{return normalize(userInfo().homedir)}catch{return}}var ACCOUNT_HOME_DIR=realAccountHomeDir();function findNearestParentConfigDir(cwd,homeDir,configDirName,requiredChildDir,requiredChildFile){let normalizedHomeDir=normalize(homeDir),accountHomeDir=ACCOUNT_HOME_DIR,stopAtAccountHome=accountHomeDir!==void 0&&dirname2(accountHomeDir)!==accountHomeDir,currentDir=normalize(cwd);for(let depth=0;depth<=MAX_PARENT_CONFIG_SEARCH_DEPTH;depth+=1){if(currentDir===normalizedHomeDir||stopAtAccountHome&¤tDir===accountHomeDir)return;let configDir=join3(currentDir,configDirName),hasRequiredChild=requiredChildFile?isFile(join3(configDir,requiredChildFile)):!requiredChildDir||isDirectory(join3(configDir,requiredChildDir));if(isDirectory(configDir)&&hasRequiredChild)return configDir;let parentDir=dirname2(currentDir);if(parentDir===currentDir)return;currentDir=parentDir}}import{readFileSync as readFileSync2}from"node:fs";import{isAbsolute as isAbsolute3,join as join4,relative as relative2}from"node:path";var RUNTIME_SNAPSHOT_MARKER="runtime-snapshot.json";function readRuntimeSnapshotMarker(packageRoot){let text;try{text=readFileSync2(join4(packageRoot,RUNTIME_SNAPSHOT_MARKER),"utf8")}catch(error){if(error instanceof Error&&"code"in error&&(error.code==="ENOENT"||error.code==="ENOTDIR"))return;throw error}let parsed=JSON.parse(text);if(typeof parsed=="object"&&parsed!==null&&"buildId"in parsed&&typeof parsed.buildId=="string"&&"installPackageDir"in parsed&&typeof parsed.installPackageDir=="string")return{buildId:parsed.buildId,installPackageDir:parsed.installPackageDir}}function resolveInstallPath(path,packageRoot){let marker=readRuntimeSnapshotMarker(packageRoot);if(!marker)return path;let inside=relative2(packageRoot,path);return inside.startsWith("..")||isAbsolute3(inside)?path:join4(marker.installPackageDir,inside)}function splitBom(content){return content.startsWith("\uFEFF")?{bom:"\uFEFF",text:content.slice(1)}:{bom:"",text:content}}function stripBom(content){return splitBom(content).text}var __filename=fileURLToPath2(import.meta.url),__dirname=dirname3(__filename),isBunBinary=import.meta.url.includes("$bunfs")||import.meta.url.includes("~BUN")||import.meta.url.includes("%7EBUN"),isBunRuntime=!!process.versions.bun,isBundledNode=!0;function normalizeSelfUpdatePackageTarget(target){return typeof target=="string"?{packageName:target,installSpec:target}:{packageName:target.packageName,installSpec:target.installSpec??target.packageName}}function makeSelfUpdateCommand(installStep,uninstallStep,postInstallStep){let steps=[...uninstallStep?[uninstallStep]:[],installStep,...postInstallStep?[postInstallStep]:[]];return steps.length===1?installStep:{...installStep,display:steps.map(step=>step.display).join(" && "),steps}}function makeSelfUpdateCommandStep(command,args){return{command,args,display:[command,...args].map(arg=>/\s/.test(arg)?`"${arg}"`:arg).join(" ")}}function detectInstallMethod(){if(isBunBinary)return"bun-binary";let resolvedPath=`${resolveInstallPath(__dirname,findNodePackageDir(__dirname))}\0${process.execPath||""}`.toLowerCase().replace(/\\/g,"/");return resolvedPath.includes("/pnpm/")||resolvedPath.includes("/.pnpm/")?"pnpm":resolvedPath.includes("/yarn/")||resolvedPath.includes("/.yarn/")?"yarn":isBunRuntime||resolvedPath.includes("/install/global/node_modules/")?"bun":resolvedPath.includes("/npm/")||resolvedPath.includes("/node_modules/")?"npm":"unknown"}function getInferredNpmInstall(){let packageDir=getInstallPackageDir(),path=process.platform==="win32"||packageDir.includes("\\")?win32:{basename,dirname:dirname3},parent=path.dirname(packageDir),root;if(path.basename(parent).startsWith("@")&&path.basename(path.dirname(parent))==="node_modules"?root=path.dirname(parent):path.basename(parent)==="node_modules"&&(root=parent),!root)return;let rootParent=path.dirname(root);if(path.basename(rootParent)==="lib")return{root,prefix:path.dirname(rootParent)}}function getSelfUpdateCommandForMethod(method,installedPackageName,updatePackageTarget=installedPackageName,npmCommand){let target=normalizeSelfUpdatePackageTarget(updatePackageTarget);switch(method){case"bun-binary":return;case"pnpm":{let match=readCommandOutput("pnpm",["root","-g"])?void 0:/^(.*[\\/]global[\\/][^\\/]+)[\\/]\.pnpm[\\/]/.exec(getInstallPackageDir()),binDirArgs=match?[`--config.global-bin-dir=${process.env.PNPM_HOME||dirname3(dirname3(match[1]))}`]:[];return makeSelfUpdateCommand(makeSelfUpdateCommandStep("pnpm",["install","-g","--ignore-scripts","--config.minimumReleaseAge=0",...binDirArgs,target.installSpec]),target.packageName===installedPackageName?void 0:makeSelfUpdateCommandStep("pnpm",["remove","-g",...binDirArgs,installedPackageName]))}case"yarn":return makeSelfUpdateCommand(makeSelfUpdateCommandStep("yarn",["global","add","--ignore-scripts",target.installSpec]),target.packageName===installedPackageName?void 0:makeSelfUpdateCommandStep("yarn",["global","remove",installedPackageName]));case"bun":{let binDir=readCommandOutput("bun",["pm","bin","-g"]);return binDir?makeSelfUpdateCommand(makeSelfUpdateCommandStep("bun",["install","-g","--ignore-scripts","--minimum-release-age=0",target.installSpec]),target.packageName===installedPackageName?void 0:makeSelfUpdateCommandStep("bun",["uninstall","-g",installedPackageName]),process.platform==="win32"?void 0:createBunLauncherRepairCommand(binDir,target.packageName,APP_NAME)):void 0}case"npm":{let[command="npm",...npmArgs]=npmCommand??[],inferred=npmCommand?.length?void 0:getInferredNpmInstall(),prefixArgs=[...npmArgs,...inferred?["--prefix",inferred.prefix]:[]],installStep=makeSelfUpdateCommandStep(command,[...prefixArgs,"install","-g","--ignore-scripts","--min-release-age=0",target.installSpec]),uninstallStep=target.packageName===installedPackageName?void 0:makeSelfUpdateCommandStep(command,[...prefixArgs,"uninstall","-g",installedPackageName]);return makeSelfUpdateCommand(installStep,uninstallStep)}case"unknown":return}}function readCommandOutput(command,args,options={}){let result=spawnProcessSync(command,args,{encoding:"utf-8",stdio:["ignore","pipe","pipe"]});if(result.status===0)return result.stdout.trim()||void 0;if(options.requireSuccess){let reason=result.error?.message||result.stderr.trim()||`exit code ${result.status??"unknown"}`;throw new Error(`Failed to run ${[command,...args].join(" ")}: ${reason}`)}}function getGlobalPackageRoots(method,_packageName,npmCommand){switch(method){case"npm":{let configured=!!npmCommand?.length,[command="npm",...npmArgs]=npmCommand??[];if(configured&&command==="bun"){let bunBin=readCommandOutput(command,[...npmArgs,"pm","bin","-g"],{requireSuccess:!0}),roots=[join5(homedir2(),".bun","install","global","node_modules")];return bunBin&&roots.push(join5(dirname3(bunBin),"install","global","node_modules")),roots}let root=readCommandOutput(command,[...npmArgs,"root","-g"],{requireSuccess:configured}),inferred=configured?void 0:getInferredNpmInstall();return[root,inferred?.root].filter(x=>!!x)}case"pnpm":{let root=readCommandOutput("pnpm",["root","-g"]);if(root)return[root,dirname3(root)];let match=/^(.*[\\/]global[\\/][^\\/]+)[\\/]\.pnpm[\\/]/.exec(getInstallPackageDir());return match?[match[1]]:[]}case"yarn":{let dir=readCommandOutput("yarn",["global","dir"]);return dir?[dir,join5(dir,"node_modules")]:[]}case"bun":{let bunBin=readCommandOutput("bun",["pm","bin","-g"]),roots=[join5(homedir2(),".bun","install","global","node_modules")];return bunBin&&roots.push(join5(dirname3(bunBin),"install","global","node_modules")),roots}case"bun-binary":case"unknown":return[]}}function normalizeExistingPathForComparison(path,resolveSymlinks){let resolvedPath=resolve(path);if(!existsSync(resolvedPath))return;let normalizedPath=resolvedPath;if(resolveSymlinks)try{normalizedPath=realpathSync2(resolvedPath)}catch{return}return process.platform==="win32"&&(normalizedPath=normalizedPath.toLowerCase()),normalizedPath}function getPathComparisonCandidates(path){return Array.from(new Set([normalizeExistingPathForComparison(path,!1),normalizeExistingPathForComparison(path,!0)].filter(candidate=>!!candidate)))}function getEntrypointPackageDir(){let entrypoint=process.argv[1];if(!entrypoint)return;let dir=dirname3(entrypoint);for(;dir!==dirname3(dir);){if(existsSync(join5(dir,"package.json")))return dir;dir=dirname3(dir)}}function isSelfUpdatePathWritable(){let packageDir=getInstallPackageDir();try{return accessSync(packageDir,constants.W_OK),accessSync(dirname3(packageDir),constants.W_OK),!0}catch{return!1}}function isManagedByGlobalPackageManager(method,packageName,npmCommand){let packageDirCandidates=[getInstallPackageDir(),getEntrypointPackageDir()].filter(dir=>!!dir).flatMap(dir=>getPathComparisonCandidates(dir));return getGlobalPackageRoots(method,packageName,npmCommand).some(root=>getPathComparisonCandidates(root).some(normalizedRoot=>{let rootPrefix=normalizedRoot.endsWith(sep2)?normalizedRoot:`${normalizedRoot}${sep2}`;return packageDirCandidates.some(packageDir=>packageDir.startsWith(rootPrefix))}))}function getSelfUpdateCommand(packageName,npmCommand,updatePackageTarget=packageName){let method=detectInstallMethod(),command=getSelfUpdateCommandForMethod(method,packageName,updatePackageTarget,npmCommand);if(!(!command||!isManagedByGlobalPackageManager(method,packageName,npmCommand)||!isSelfUpdatePathWritable()))return command}function getSelfUpdateUnavailableInstruction(packageName,npmCommand,updatePackageTarget=packageName){let method=detectInstallMethod(),target=normalizeSelfUpdatePackageTarget(updatePackageTarget);if(method==="bun-binary")return"Download from: https://github.com/code-yeongyu/senpi/releases/latest";let command=getSelfUpdateCommandForMethod(method,packageName,target,npmCommand);return command?isManagedByGlobalPackageManager(method,packageName,npmCommand)&&!isSelfUpdatePathWritable()?`This installation is managed by a global ${method} install, but the install path is not writable. Update it yourself with: ${command.display}`:`This installation is not managed by a global ${method} install. Update it with the package manager, wrapper, or source checkout that provides it.`:`Update ${target.installSpec} using the package manager, wrapper, or source checkout that provides this installation.`}function findNodePackageDir(startDir){let dir=startDir;for(;dir!==dirname3(dir);){if(existsSync(join5(dir,"package.json"))){let parent=dirname3(dir);return basename(dir)==="dist"&&existsSync(join5(parent,"package.json"))?parent:dir}dir=dirname3(dir)}return startDir}function getPackageDir(){let envDir=envValue("PACKAGE_DIR");return envDir?normalizePath(envDir):isBunBinary?dirname3(process.execPath):(nodePackageDir??=findNodePackageDir(__dirname),nodePackageDir)}var nodePackageDir;function getInstallPackageDir(){let packageDir=getPackageDir();return resolveInstallPath(packageDir,packageDir)}var THEMES_ASSET={binaryDir:"theme",sourceSegments:["modes","interactive","theme"],probe:"dark.json"},EXPORT_TEMPLATE_ASSET={binaryDir:"export-html",sourceSegments:["core","export-html"],probe:"template.html"},INTERACTIVE_ASSETS={binaryDir:"assets",sourceSegments:["modes","interactive","assets"],probe:"clankolas.png"};function assetDirIn(root,asset){if(isBunBinary)return join5(root,asset.binaryDir);let srcOrDist=existsSync(join5(root,"src"))?"src":"dist";return join5(root,srcOrDist,...asset.sourceSegments)}function resolveShippedAssetDir(asset){let preferred=assetDirIn(getPackageDir(),asset);return existsSync(join5(preferred,asset.probe))?preferred:assetDirIn(isBunBinary?dirname3(process.execPath):findNodePackageDir(__dirname),asset)}function getThemesDir(){return resolveShippedAssetDir(THEMES_ASSET)}function getExportTemplateDir(){return resolveShippedAssetDir(EXPORT_TEMPLATE_ASSET)}function getPackageJsonPath(){return join5(getPackageDir(),"package.json")}function getReadmePath(){return resolve(join5(getPackageDir(),"README.md"))}function getDocsPath(){return resolve(join5(getPackageDir(),"docs"))}function getExamplesPath(){return resolve(join5(getPackageDir(),"examples"))}function getChangelogPath(){return resolve(join5(getPackageDir(),"CHANGELOG.md"))}function getInteractiveAssetsDir(){return resolveShippedAssetDir(INTERACTIVE_ASSETS)}function getBundledInteractiveAssetPath(name){return join5(getInteractiveAssetsDir(),name)}var pkg={};try{pkg=JSON.parse(stripBom(readFileSync3(getPackageJsonPath(),"utf-8")))}catch(e){if(e.code!=="ENOENT")throw e}var piConfigName=pkg.piConfig?.name,BRAND=brandProfile(),PACKAGE_NAME=pkg.name||"@earendil-works/pi-coding-agent",APP_NAME=BRAND?.name||piConfigName||"pi",APP_COMMAND=BRAND?.command??APP_NAME,APP_TITLE=BRAND?.name||(piConfigName?APP_NAME:"\u03C0"),CONFIG_DIR_NAME=BRAND?.configDir||pkg.piConfig?.configDir||".pi",CONFIG_FLAT_LAYOUT=BRAND?.flatLayout===!0,VERSION=pkg.version||"0.0.0",DISPLAY_VERSION=BRAND?.displayVersion||VERSION,ENV_PREFIX=BRAND?.envPrefix||APP_NAME.toUpperCase(),ENV_AGENT_DIR=`${ENV_PREFIX}_CODING_AGENT_DIR`,ENV_SESSION_DIR=`${ENV_PREFIX}_CODING_AGENT_SESSION_DIR`;function expandTildePath(path){return normalizePath(path)}function getShareViewerBase(){return envValue("SHARE_VIEWER_URL")?.trim()||void 0}function isShareDisabledByEnvironment(){let value=envValue("DISABLE_SHARE")?.trim().toLowerCase();return value!==void 0&&value!==""&&value!=="0"&&value!=="false"}var FLAT_LAYOUT_SENTINEL="settings.json";function resolveAgentDir(cwd,homeDir,envDir){if(envDir)return normalizePath(envDir,{homeDir});if(CONFIG_FLAT_LAYOUT)return findNearestParentConfigDir(cwd,homeDir,CONFIG_DIR_NAME,void 0,FLAT_LAYOUT_SENTINEL)??join5(homeDir,CONFIG_DIR_NAME);let projectConfigDir=findNearestParentConfigDir(cwd,homeDir,CONFIG_DIR_NAME,"agent");return projectConfigDir?join5(projectConfigDir,"agent"):join5(homeDir,CONFIG_DIR_NAME,"agent")}var KNOWN_BRAND_CONFIG_DIRS=[".senpi",".omo",".pi"],RealAgentDirInTestError=class extends Error{constructor(agentDir){super(`Refusing to use the real agent directory ${agentDir} from a test run. Point <BRAND>_CODING_AGENT_DIR at a temp dir, or set SENPI_TEST_USE_REAL_AGENT_DIR=1 to opt in.`),this.name="RealAgentDirInTestError",this.agentDir=agentDir}};function isGuardedTestRun(env){return env.SENPI_TEST_AGENT_DIR_GUARD==="1"}function realHomeDir(){try{return userInfo2().homedir}catch{return}}function assertAgentDirAllowedInTests(agentDir,activeConfigDirName,env=process.env){if(!isGuardedTestRun(env)||env.SENPI_TEST_USE_REAL_AGENT_DIR==="1")return;let home=realHomeDir();if(!home)return;let target=resolve(agentDir);for(let configDir of new Set([...KNOWN_BRAND_CONFIG_DIRS,activeConfigDirName])){let root=join5(home,configDir);if(target===root||target.startsWith(root+sep2))throw new RealAgentDirInTestError(target)}}function getAgentDir(){let agentDir=resolveAgentDir(process.cwd(),homedir2(),envValue("CODING_AGENT_DIR"));return assertAgentDirAllowedInTests(agentDir,CONFIG_DIR_NAME),agentDir}function agentDirLabel(){return CONFIG_FLAT_LAYOUT?`~/${CONFIG_DIR_NAME}`:`~/${CONFIG_DIR_NAME}/agent`}function getCustomThemesDir(){return join5(getAgentDir(),"themes")}function getModelsPath(){return join5(getAgentDir(),"models.json")}function getAuthPath(){return join5(getAgentDir(),"auth.json")}function getSettingsPath(){return join5(getAgentDir(),"settings.json")}function getBinDir(){return join5(getAgentDir(),"bin")}function getSessionsDir(){return join5(getAgentDir(),"sessions")}function getDebugLogPath(){return join5(getAgentDir(),`${APP_NAME}-debug.log`)}export{scrubBrandFromEnvironment,brandProfile,brandEnvNames,envValue,findNearestParentConfigDir,RUNTIME_SNAPSHOT_MARKER,readRuntimeSnapshotMarker,resolveInstallPath,spawnProcess,spawnProcessSync,waitForChildProcess,canonicalizePath,canonicalizePathStrict,realpathWithoutOpen,realpathWithoutOpenStrict,getFileRevision,getFileContentRevision,isLocalPath,normalizePath,resolvePath,getCwdRelativePath,formatPathRelativeToCwdOrAbsolute,shortenPath,markPathIgnoredByCloudSync,splitBom,stripBom,isBunBinary,isBunRuntime,isBundledNode,detectInstallMethod,getSelfUpdateCommand,getSelfUpdateUnavailableInstruction,findNodePackageDir,getPackageDir,getInstallPackageDir,getThemesDir,getExportTemplateDir,getReadmePath,getDocsPath,getExamplesPath,getChangelogPath,getInteractiveAssetsDir,getBundledInteractiveAssetPath,BRAND,PACKAGE_NAME,APP_NAME,APP_COMMAND,APP_TITLE,CONFIG_DIR_NAME,CONFIG_FLAT_LAYOUT,VERSION,DISPLAY_VERSION,ENV_PREFIX,ENV_AGENT_DIR,ENV_SESSION_DIR,expandTildePath,getShareViewerBase,isShareDisabledByEnvironment,FLAT_LAYOUT_SENTINEL,resolveAgentDir,getAgentDir,agentDirLabel,getCustomThemesDir,getModelsPath,getAuthPath,getSettingsPath,getBinDir,getSessionsDir,getDebugLogPath};