@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
5 lines (4 loc) • 15.8 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_proper_lockfile}from"./chunk-GZVCRV7I.js";import{hasFunctions,realmRegistry}from"./chunk-XDEZA6U6.js";import{CONFIG_DIR_NAME,canonicalizePath,canonicalizePathStrict,findNodePackageDir,getDocsPath,getExamplesPath,getExportTemplateDir,getInstallPackageDir,getInteractiveAssetsDir,getPackageDir,getThemesDir,isBunBinary,resolvePath,stripBom}from"./chunk-QJTWAOBX.js";import{__toESM}from"./chunk-IKOFCODM.js";import{existsSync as existsSync2,readFileSync}from"node:fs";import{access,readFile}from"node:fs/promises";import{homedir}from"node:os";import{dirname as dirname3,join as join3,sep as sep2}from"node:path";import{existsSync}from"node:fs";import{createRequire}from"node:module";import{dirname as dirname2,join as join2,resolve,sep}from"node:path";import{fileURLToPath as fileURLToPath2}from"node:url";import{dirname,join}from"node:path";import{fileURLToPath}from"node:url";function imagegenSkillPath(baseDir=dirname(fileURLToPath(import.meta.url))){return join(baseDir,"skill","SKILL.md")}var moduleRequire=createRequire(import.meta.url),runningFromSource=fileURLToPath2(import.meta.url).includes(`${sep}src${sep}core${sep}`),bundledBuiltinExtensions=[{id:"codemode",resolvePackage:()=>resolveBundledPackageJson("@code-yeongyu/senpi-codemode/package.json","senpi-codemode/package.json",join2("node_modules","@code-yeongyu","senpi-codemode","package.json"))}];function resolveBundledPackageJson(packageSpecifier,workspaceRelativePath,binaryRelativePath){let packageRoot=getPackageDir(),workspacePath=resolve(packageRoot,"..",workspaceRelativePath);if(runningFromSource&&existsSync(workspacePath))return workspacePath;let binaryPath=resolve(packageRoot,binaryRelativePath);if(isBunBinary&&existsSync(binaryPath))return binaryPath;try{return moduleRequire.resolve(packageSpecifier)}catch(error){if(existsSync(workspacePath))return workspacePath;throw error}}function getBundledResourceRoots(){let roots=[getThemesDir(),getExportTemplateDir(),getInteractiveAssetsDir(),getDocsPath(),getExamplesPath(),dirname2(imagegenSkillPath())];!isBunBinary&&!runningFromSource?roots.push(getPackageDir(),getInstallPackageDir(),findNodePackageDir(dirname2(fileURLToPath2(import.meta.url)))):isBunBinary&&roots.push(dirname2(fileURLToPath2(import.meta.url)));for(let extension of bundledBuiltinExtensions)try{roots.push(dirname2(extension.resolvePackage()))}catch(error){if(!(error instanceof Error&&"code"in error&&error.code==="MODULE_NOT_FOUND"))throw error}return roots}var TRUST_REQUIRING_PROJECT_CONFIG_RESOURCES=["settings.json","mcp.json","extensions","skills","prompts","themes","SYSTEM.md","APPEND_SYSTEM.md"],LEGACY_PROJECT_CONFIG_DIR_NAME=".pi";function*exists(path){return(yield{kind:"exists",path})===!0}function*readText(path){let text=yield{kind:"read",path};return typeof text=="string"?text:void 0}function parseJson(text){try{return{ok:!0,value:JSON.parse(stripBom(text))}}catch{return{ok:!1}}}function valueAtPath(value,path){let current=value;for(let key of path.split(".")){if(typeof current!="object"||current===null)return;current=Reflect.get(current,key)}return current}function*codemodeExecutableSettings(){let codemode=bundledBuiltinExtensions.find(extension=>extension.id==="codemode"),packageJson;try{packageJson=codemode?.resolvePackage()}catch{return}if(packageJson===void 0)return;let text=yield*readText(join3(dirname3(packageJson),"src","config","executable-settings.json")),list=text===void 0?{ok:!1}:parseJson(text);if(!list.ok||typeof list.value!="object"||list.value===null)return;let paths=Reflect.get(list.value,"projectExecutableSettings");return Array.isArray(paths)&&paths.every(entry=>typeof entry=="string")?paths:void 0}function*projectCodemodeNamesExecutable(configDir){let path=join3(configDir,"codemode.json");if(!(yield*exists(path)))return!1;let executableSettings=yield*codemodeExecutableSettings();if(executableSettings===void 0)return!0;let text=yield*readText(path),parsed=text===void 0?{ok:!1}:parseJson(text);return parsed.ok?executableSettings.some(settingPath=>valueAtPath(parsed.value,settingPath)!==void 0):!0}function isHomeOrAboveDir(dir,homeDir){return dir===homeDir||homeDir.startsWith(dir.endsWith(sep2)?dir:`${dir}${sep2}`)}function*findGitRepoRoot(dir){let currentDir=dir;for(;!(yield*exists(join3(currentDir,".git")));){let parentDir=dirname3(currentDir);if(parentDir===currentDir)return;currentDir=parentDir}return currentDir}function homeDirectory(){return canonicalizePath(resolvePath(process.env.HOME||homedir()))}function*agentsSkillDirs(cwd){let homeDir=homeDirectory(),startDir=resolvePath(cwd),gitRepoRoot=yield*findGitRepoRoot(startDir),dirs=[],currentDir=startDir;for(;!isHomeOrAboveDir(canonicalizePath(currentDir),homeDir)&&(dirs.push(join3(currentDir,".agents","skills")),currentDir!==gitRepoRoot);){let parentDir=dirname3(currentDir);if(parentDir===currentDir)break;currentDir=parentDir}return dirs}function*trustRequiringResources(cwd){let homeDir=homeDirectory(),currentDir=canonicalizePath(resolvePath(cwd));if(!isHomeOrAboveDir(currentDir,homeDir)){for(let configDir of[join3(currentDir,CONFIG_DIR_NAME),join3(currentDir,LEGACY_PROJECT_CONFIG_DIR_NAME)])for(let entry of TRUST_REQUIRING_PROJECT_CONFIG_RESOURCES)if(yield*exists(join3(configDir,entry)))return!0;if(yield*projectCodemodeNamesExecutable(join3(currentDir,CONFIG_DIR_NAME)))return!0}for(let dir of yield*agentsSkillDirs(cwd))if(yield*exists(dir))return!0;return!1}function answerSync(probe){if(probe.kind==="exists")return existsSync2(probe.path);try{return readFileSync(probe.path,"utf8")}catch{return}}async function answerAsync(probe){return probe.kind==="exists"?access(probe.path).then(()=>!0,()=>!1):readFile(probe.path,"utf8").catch(()=>{})}function runSync(walk){let step=walk.next();for(;!step.done;)step=walk.next(answerSync(step.value));return step.value}async function runAsync(walk){let step=walk.next();for(;!step.done;)step=walk.next(await answerAsync(step.value));return step.value}function projectAgentsSkillDirs(cwd){return runSync(agentsSkillDirs(cwd))}function hasTrustRequiringProjectResources(cwd){return runSync(trustRequiringResources(cwd))}function hasTrustRequiringProjectResourcesAsync(cwd){return runAsync(trustRequiringResources(cwd))}var import_proper_lockfile=__toESM(require_proper_lockfile(),1);import{existsSync as existsSync3,mkdirSync,readFileSync as readFileSync2,writeFileSync}from"node:fs";import{readFile as readFile3,rename,stat as stat2,writeFile}from"node:fs/promises";import{dirname as dirname5,join as join5}from"node:path";import{readFile as readFile2,realpath,stat}from"node:fs/promises";import{basename,dirname as dirname4,join as join4,relative,resolve as resolve2}from"node:path";var GITDIR_POINTER=/^gitdir:\s*(.+)$/;async function readFirstLine(path){try{return(await readFile2(path,"utf-8")).split(/\r?\n/,1)[0]?.trim()||void 0}catch{return}}async function realPathOf(path){try{return await realpath(path)}catch{return}}async function entryKind(path){try{let stats=await stat(path);return stats.isDirectory()?"directory":stats.isFile()?"file":void 0}catch{return}}async function linkedWorktreeMainCheckoutDir(cwd){let dir=await realPathOf(resolvePath(cwd))??resolvePath(cwd),checkoutRoot=dir,markerKind=await entryKind(join4(checkoutRoot,".git"));for(;markerKind===void 0;){let parentDir=dirname4(checkoutRoot);if(parentDir===checkoutRoot)return;checkoutRoot=parentDir,markerKind=await entryKind(join4(checkoutRoot,".git"))}if(markerKind!=="file")return;let marker=join4(checkoutRoot,".git"),adminTarget=GITDIR_POINTER.exec(await readFirstLine(marker)??"")?.[1]?.trim();if(!adminTarget)return;let adminDir=await realPathOf(resolve2(checkoutRoot,adminTarget));if(adminDir===void 0)return;let commonDirPointer=await readFirstLine(join4(adminDir,"commondir")),backPointer=await readFirstLine(join4(adminDir,"gitdir"));if(commonDirPointer===void 0||backPointer===void 0)return;let markerRealPath=await realPathOf(marker);if(markerRealPath===void 0||await realPathOf(resolve2(adminDir,backPointer))!==markerRealPath)return;let commonDir=await realPathOf(resolve2(adminDir,commonDirPointer));if(commonDir===void 0||basename(commonDir)!==".git"||dirname4(adminDir)!==join4(commonDir,"worktrees"))return;let mainCheckout=dirname4(commonDir),mainMarker=join4(mainCheckout,".git");if(!(await entryKind(mainMarker)!=="directory"||await realPathOf(mainMarker)!==commonDir))return join4(mainCheckout,relative(checkoutRoot,dir))}var FS_CODE_OF_OP_CODE={not_found:"ENOENT",permission_denied:"EACCES",aborted:"ABORT_ERR"};function stringCode(value){return typeof value=="object"&&value!==null&&"code"in value&&typeof value.code=="string"?value.code:void 0}var isFsCode=code=>/^E[A-Z0-9]+$/.test(code)||code==="ABORT_ERR";function fsErrorCode(error){let code=stringCode(error);if(code===void 0)return;if(isFsCode(code))return code;let causeCode=typeof error=="object"&&error!==null&&"cause"in error?stringCode(error.cause):void 0;return causeCode!==void 0&&isFsCode(causeCode)?causeCode:FS_CODE_OF_OP_CODE[code]??code}var trustStoreWriters=realmRegistry("@code-yeongyu/senpi/trust-store-writers/v1",()=>{let tails=new Map,held=new Set;return{inTurn:(path,write)=>{let turn=(tails.get(path)??Promise.resolve()).then(write),tail=turn.then(()=>{},()=>{});return tails.set(path,tail),tail.then(()=>{tails.get(path)===tail&&tails.delete(path)}),turn},hold:path=>{held.add(path)},release:path=>{held.delete(path)},holds:path=>held.has(path)}},value=>hasFunctions(value,["inTurn","hold","release","holds"]));function inTrustStoreWriteTurn(path,write){return trustStoreWriters.inTurn(path,write)}function holdTrustStoreLockInRealm(path){return trustStoreWriters.hold(path),()=>trustStoreWriters.release(path)}function trustStoreLockHeldInRealm(path){return trustStoreWriters.holds(path)}function normalizeCwd(cwd){let resolved=resolvePath(cwd);try{return canonicalizePathStrict(resolved)}catch{return resolved}}function findNearestTrustEntry(data,cwd){let currentDir=normalizeCwd(cwd);for(;;){let value=data[currentDir];if(value===!0||value===!1||value===null)return{path:currentDir,decision:value};let parentDir=dirname5(currentDir);if(parentDir===currentDir)return null;currentDir=parentDir}}function getProjectTrustParentPath(cwd){let trustPath=normalizeCwd(cwd),parentDir=dirname5(trustPath);return parentDir===trustPath?void 0:parentDir}function getProjectTrustOptions(cwd,options){let trustPath=normalizeCwd(cwd),trustOptions=[{label:"Trust",trusted:!0,updates:[{path:trustPath,decision:!0}],savedPath:trustPath}],parentPath=getProjectTrustParentPath(cwd);return parentPath!==void 0&&trustOptions.push({label:`Trust parent folder (${parentPath})`,trusted:!0,updates:[{path:parentPath,decision:!0},{path:trustPath,decision:null}],savedPath:parentPath}),options?.includeSessionOnly&&trustOptions.push({label:"Trust (this session only)",trusted:!0,updates:[]}),trustOptions.push({label:"Do not trust",trusted:!1,updates:[{path:trustPath,decision:!1}],savedPath:trustPath}),options?.includeSessionOnly&&trustOptions.push({label:"Do not trust (this session only)",trusted:!1,updates:[]}),trustOptions}function getProjectTrustNoInheritOption(cwd){let trustPath=normalizeCwd(cwd);return{label:"No decision, and none inherited",trusted:!1,updates:[{path:trustPath,decision:"no_inherit"}],savedPath:trustPath}}function readTrustFile(path){if(!existsSync3(path))return{};let parsed;try{parsed=JSON.parse(stripBom(readFileSync2(path,"utf-8")))}catch(error){let message=error instanceof Error?error.message:String(error);throw new Error(`Failed to read trust store ${path}: ${message}`)}if(typeof parsed!="object"||parsed===null||Array.isArray(parsed))throw new Error(`Invalid trust store ${path}: expected an object`);let data={};for(let[key,value]of Object.entries(parsed)){if(value!==!0&&value!==!1&&value!==null)throw new Error(`Invalid trust store ${path}: value for ${JSON.stringify(key)} must be true, false, or null`);data[key]=value}return data}function writeTrustFile(path,data){let sorted={};for(let key of Object.keys(data).sort()){let value=data[key];(value===!0||value===!1||value===null)&&(sorted[key]=value)}mkdirSync(dirname5(path),{recursive:!0}),writeFileSync(path,`${JSON.stringify(sorted,null,2)}
`,"utf-8")}function acquireTrustLockSync(path){let trustDir=dirname5(path);mkdirSync(trustDir,{recursive:!0});let maxAttempts=10,delayMs=20,lastError;for(let attempt=1;attempt<=maxAttempts;attempt++)try{return import_proper_lockfile.default.lockSync(trustDir,{realpath:!1,lockfilePath:`${path}.lock`})}catch(error){if((typeof error=="object"&&error!==null&&"code"in error?String(error.code):void 0)!=="ELOCKED"||attempt===maxAttempts)throw error;lastError=error;let start=Date.now();for(;Date.now()-start<delayMs;);}throw lastError instanceof Error?lastError:new Error("Failed to acquire trust store lock")}function absentAsUndefined(error){if(fsErrorCode(error)!=="ENOENT")throw error}function withTrustFileLock(path,fn){if(trustStoreLockHeldInRealm(path))return fn();let release=acquireTrustLockSync(path);try{return fn()}finally{release()}}function withTrustFileWriteLock(path,write){return inTrustStoreWriteTurn(path,async()=>{let release=acquireTrustLockSync(path),releaseHold=holdTrustStoreLockInRealm(path);try{await write()}finally{releaseHold(),release()}})}var ProjectTrustStore=class{constructor(agentDir){this.trustPath=join5(resolvePath(agentDir),"trust.json"),this.generationPath=`${this.trustPath}.generation`}async revision(){let stats=await stat2(this.trustPath,{bigint:!0}).catch(absentAsUndefined);return`${await this.readGeneration()}:${stats===void 0?"absent":`${stats.mtimeNs}:${stats.size}`}`}async readGeneration(){let text=await readFile3(this.generationPath,"utf-8").catch(absentAsUndefined);if(text===void 0)return 0;let generation=Number.parseInt(text,10);return Number.isSafeInteger(generation)&&generation>=0?generation:0}get(cwd){return this.getNearestEntry(cwd)?.decision??null}getEntry(cwd){let entry=this.getNearestEntry(cwd);return entry===null||entry.decision===null?null:{path:entry.path,decision:entry.decision}}getNearestEntry(cwd){return withTrustFileLock(this.trustPath,()=>{let data=readTrustFile(this.trustPath);return findNearestTrustEntry(data,cwd)})}async set(cwd,decision){await this.setMany([{path:cwd,decision}])}async setMany(decisions){await withTrustFileWriteLock(this.trustPath,async()=>{let data=readTrustFile(this.trustPath);for(let{path,decision}of decisions){let key=normalizeCwd(path);decision===null?delete data[key]:data[key]=decision==="no_inherit"?null:decision}let nextGeneration=`${this.generationPath}.next`;await writeFile(nextGeneration,`${await this.readGeneration()+1}
`,"utf-8"),await rename(nextGeneration,this.generationPath),writeTrustFile(this.trustPath,data)})}};async function getSavedProjectTrustState(store,cwd){let own=store.getNearestEntry(cwd);if(own!==null)return own.decision??"no_inherit";let mainCheckoutDir=await linkedWorktreeMainCheckoutDir(cwd);if(mainCheckoutDir===void 0)return null;let main=store.getNearestEntry(mainCheckoutDir);return main===null?null:main.decision??"no_inherit"}async function getSavedProjectTrust(store,cwd){let saved=await getSavedProjectTrustState(store,cwd);return saved==="no_inherit"?null:saved}export{fsErrorCode,imagegenSkillPath,bundledBuiltinExtensions,getBundledResourceRoots,projectAgentsSkillDirs,hasTrustRequiringProjectResources,hasTrustRequiringProjectResourcesAsync,getProjectTrustOptions,getProjectTrustNoInheritOption,ProjectTrustStore,getSavedProjectTrustState,getSavedProjectTrust};