@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
94 lines • 73.5 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{DefaultResourceLoader,LEGACY_PI_CONFIG_FILES,ModelRuntime,cleanupWindowsSelfUpdateQuarantine,createProjectTrustContext,importLegacyPiConfig,isBuiltinExtension,quarantineWindowsNativeDependencies,resolveProjectTrusted}from"./chunk-MDMF5VUG.js";import"./chunk-2NI6ZIXW.js";import"./chunk-VHOAN5G5.js";import"./chunk-SFBHMFSI.js";import"./chunk-ARIPHUYY.js";import"./chunk-PB5JAI6A.js";import"./chunk-PWGJGKPI.js";import"./chunk-R3F4JKFN.js";import"./chunk-XLJDXEBB.js";import"./chunk-TQHNFP77.js";import{DefaultPackageManager,SettingsManager}from"./chunk-WIPTRIAJ.js";import"./chunk-DEUEMEV3.js";import"./chunk-XI6THO4F.js";import"./chunk-WZ4IZIR2.js";import"./chunk-4R7JSL3B.js";import"./chunk-KQYPGYFV.js";import{ProjectTrustStore,hasTrustRequiringProjectResources}from"./chunk-7AEFFKBD.js";import{DynamicBorder,initTheme,keyHint,rawKeyHint,stopThemeWatcher,theme}from"./chunk-KAQBXCAT.js";import"./chunk-5QZIEDOI.js";import"./chunk-CSCNDNNU.js";import"./chunk-B4V35GCK.js";import"./chunk-3MCOVENJ.js";import"./chunk-3VN5RC6W.js";import"./chunk-4B5JSLLR.js";import"./chunk-UWUN3IBB.js";import"./chunk-MOVB6H22.js";import"./chunk-ETOGZ74E.js";import"./chunk-H4ELF6OO.js";import"./chunk-H4QOEVS5.js";import"./chunk-RNLFZ67U.js";import"./chunk-SOMFLLPD.js";import"./chunk-MTQQ2VQH.js";import"./chunk-2EXKZR3F.js";import"./chunk-OPUPPWQY.js";import{BUILTIN_PATH_PREFIX}from"./chunk-QMRJYMNH.js";import"./chunk-BICMCIHT.js";import"./chunk-2C4UHQNO.js";import{source_default}from"./chunk-26UBFF6N.js";import"./chunk-4SA7RJES.js";import"./chunk-E25CXSWH.js";import"./chunk-AT5G5BUI.js";import"./chunk-7WYJAYHH.js";import"./chunk-YNF5MPCP.js";import"./chunk-Q5HNTEVZ.js";import"./chunk-O5NRXQZ2.js";import"./chunk-2ZYJNMJZ.js";import"./chunk-YQHLIPNR.js";import"./chunk-SF4MQDKZ.js";import"./chunk-2JKFVGLS.js";import"./chunk-KMWFC44T.js";import"./chunk-N7EA2JAR.js";import"./chunk-KLAX467B.js";import"./chunk-OPWT74QF.js";import"./chunk-PQGNLQCI.js";import{lockWithLossHandling}from"./chunk-ZZU4J6QP.js";import{require_proper_lockfile}from"./chunk-GZVCRV7I.js";import"./chunk-236TAYFX.js";import"./chunk-36BLGKRO.js";import"./chunk-FKX6EWFV.js";import"./chunk-U3VOXCGP.js";import"./chunk-7X72IACK.js";import{appendHiddenTuiStdout}from"./chunk-WHTAR5IS.js";import"./chunk-WHQ2QPP5.js";import"./chunk-SY5HNH77.js";import"./chunk-WB4BUHOH.js";import"./chunk-NJ43NBSP.js";import"./chunk-KDUJCDLM.js";import"./chunk-6APXZK7W.js";import"./chunk-YU2P3CAR.js";import"./chunk-6QQL3SKM.js";import"./chunk-WB6WW5V6.js";import"./chunk-KJR3XXMI.js";import"./chunk-IYL5E4QQ.js";import"./chunk-7THM57HH.js";import"./chunk-AC72EWI5.js";import"./chunk-RQFD6LG2.js";import"./chunk-QELZQPCJ.js";import{Container,Input,Markdown,ProcessTerminal,Spacer,TUI,getKeybindings,matchesKey,truncateToWidth,visibleWidth}from"./chunk-4PMRUR4L.js";import"./chunk-LPYBKMPT.js";import{killProcessTree}from"./chunk-T4O3Z7IC.js";import"./chunk-DPNC7S74.js";import"./chunk-R7J5TEYK.js";import"./chunk-62OVOJPI.js";import"./chunk-G7U4BOJP.js";import"./chunk-OBXBNBXE.js";import"./chunk-XDEZA6U6.js";import"./chunk-WOHQJ6JB.js";import"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import"./chunk-Y7QPP7BG.js";import"./chunk-7K42R46I.js";import"./chunk-GVSBCJFI.js";import"./chunk-QTS2XGPQ.js";import"./chunk-Z6TEQEZO.js";import"./chunk-ZG3MNTNX.js";import"./chunk-WHPDEDCC.js";import"./chunk-HK46JMSC.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-QD45L5SP.js";import"./chunk-WDTJ6JKE.js";import"./chunk-AFDUWYAX.js";import"./chunk-NDNQ23SK.js";import"./chunk-JGKH3D6W.js";import"./chunk-3SASTB6Y.js";import"./chunk-PJ34QVL5.js";import"./chunk-BMX2U22F.js";import{formatVersionCheckError,getLatestPiRelease,getPiUserAgent,isNewerPackageVersion}from"./chunk-GM2CSWYR.js";import"./chunk-E5RLUYMN.js";import"./chunk-ZFIC2DZV.js";import"./chunk-ZOFZRJSL.js";import"./chunk-2SOVDETB.js";import{runtimeExecArgv}from"./chunk-6S66JQWD.js";import"./chunk-GKBPYB3Q.js";import"./chunk-42XRJQM6.js";import"./chunk-REXE2FGU.js";import"./chunk-5XHOHZIR.js";import"./chunk-HW6AAS3R.js";import"./chunk-IDTQWHTP.js";import{APP_COMMAND,APP_NAME,CONFIG_DIR_NAME,DISPLAY_VERSION,PACKAGE_NAME,VERSION,brandProfile,canonicalizePath,detectInstallMethod,getAgentDir,getCwdRelativePath,getInstallPackageDir,getSelfUpdateCommand,getSelfUpdateUnavailableInstruction,isLocalPath,resolvePath,spawnProcess,spawnProcessSync,waitForChildProcess}from"./chunk-QJTWAOBX.js";import"./chunk-ATQFN5HI.js";import"./chunk-4EGD7FGJ.js";import"./chunk-MIKPY3E7.js";import"./chunk-OXNWERO4.js";import"./chunk-44BJPS5I.js";import"./chunk-5GCZFK4X.js";import"./chunk-YWBNR4MT.js";import"./chunk-RFFMEA4B.js";import{__toESM}from"./chunk-IKOFCODM.js";import{existsSync as existsSync3,mkdirSync as mkdirSync3,mkdtempSync,readdirSync as readdirSync2,readFileSync as readFileSync2,renameSync as renameSync2,rmSync as rmSync2,writeFileSync as writeFileSync2}from"node:fs";import{join as join5,resolve as resolve3}from"node:path";var import_proper_lockfile=__toESM(require_proper_lockfile(),1);import{randomUUID}from"node:crypto";import{cpSync,existsSync as existsSync2,mkdirSync as mkdirSync2,readFileSync,renameSync,rmSync,writeFileSync}from"node:fs";import{homedir}from"node:os";import{dirname as dirname2,join as join3,relative as relative2,resolve as resolve2}from"node:path";import{existsSync,readdirSync}from"node:fs";import{join,relative,sep}from"node:path";var REQUIRED_BUILD_ARTIFACTS=["extensions/omo.js","runtime/lsp-daemon/dist/cli.js","runtime/lsp-daemon/dist/index.js","runtime/lsp-daemon/dist/.omo-runtime-manifest.json","scripts/install.mjs"];function walkFiles(rootDir){let files=[],pending=[rootDir];for(;pending.length>0;){let dir=pending.pop();if(dir===void 0)continue;let entries;try{entries=readdirSync(dir,{withFileTypes:!0})}catch(error){if(error instanceof Error)continue;throw error}for(let entry of entries){let full=join(dir,entry.name);entry.isDirectory()?pending.push(full):entry.isFile()&&files.push(full)}}return files}function collectArtifactInventory(pluginPath){let inventory=[],collectUnder=(relativeDir,filter)=>{for(let filePath of walkFiles(join(pluginPath,relativeDir))){let posixPath=relative(pluginPath,filePath).split(sep).join("/");(filter===void 0||filter(posixPath))&&inventory.push(posixPath)}};return collectUnder("extensions"),collectUnder(join("runtime","lsp-daemon","dist")),collectUnder("skills",posixPath=>posixPath.endsWith("/SKILL.md")),existsSync(join(pluginPath,"scripts","install.mjs"))&&inventory.push("scripts/install.mjs"),inventory.sort(),inventory}function currentRequiredBuildArtifactsExist(pluginPath){return findMissingBuildArtifacts(pluginPath).length===0}function findMissingBuildArtifacts(pluginPath){let missing=[];for(let required of REQUIRED_BUILD_ARTIFACTS)existsSync(join(pluginPath,required))||missing.push(required);let skillCount=0;try{for(let entry of readdirSync(join(pluginPath,"skills"),{withFileTypes:!0}))entry.isDirectory()&&existsSync(join(pluginPath,"skills",entry.name,"SKILL.md"))&&skillCount++}catch(error){if(!(error instanceof Error))throw error}return skillCount===0&&missing.push("skills/*/SKILL.md"),missing}import{createHash}from"node:crypto";var EXCLUDED_ROOT_PATHS=new Set([".agents",".claude",".codex",".cursor",".devcontainer",".env.example",".gitattributes",".github",".idea",".mcp.json",".omo",".opencode",".vscode","AGENTS.md","CHANGELOG.md","CLA.md","CLAUDE.md","CONTRIBUTING.md","LICENSE","LICENSE.md","ROADMAP.md","THIRD-PARTY-NOTICES.md","assets","docs"]);function isBuildInputRootPath(name){return!EXCLUDED_ROOT_PATHS.has(name)&&!name.startsWith("README")}function computeBuildInputsHashFromLsTree(lsTreeOutput){let hash=createHash("sha256");for(let entry of lsTreeOutput.split("\0")){let tabIndex=entry.indexOf(" ");if(tabIndex===-1)continue;let name=entry.slice(tabIndex+1);if(!isBuildInputRootPath(name))continue;let objectHash=entry.slice(0,tabIndex).split(" ")[2]??"";hash.update(`${objectHash} ${name}
`)}return hash.digest("hex")}import{spawn}from"node:child_process";import{closeSync,mkdirSync,openSync}from"node:fs";import{dirname,join as join2,resolve}from"node:path";import{fileURLToPath}from"node:url";function omoLocalUpdateWorkerLogPath(agentDir){return join2(agentDir,"omo-local-update","worker.log")}function workerCommandArgs(force){let updateArgs=["update","--omo-local-update-worker",...force?["--force"]:[]];if(detectInstallMethod()==="bun-binary")return updateArgs;let modulePath=fileURLToPath(import.meta.url),extension=modulePath.endsWith(".ts")?".ts":".js",cliMainPath=resolve(dirname(modulePath),"..",`cli-main${extension}`);return[...runtimeExecArgv(),cliMainPath,...updateArgs]}var defaultSpawnWorker=request=>{let logPath=omoLocalUpdateWorkerLogPath(request.agentDir);try{mkdirSync(dirname(logPath),{recursive:!0});let logFd=openSync(logPath,"w");try{let child=spawn(process.execPath,workerCommandArgs(request.force),{detached:!0,env:process.env,stdio:["ignore",logFd,logFd],windowsHide:!0});return child.unref(),{ok:!0,pid:child.pid,logPath}}finally{closeSync(logFd)}}catch(error){return{ok:!1,message:error instanceof Error?error.message:String(error)}}};async function defaultRun(command,args,options){let child=spawnProcess(command,args,{cwd:options.cwd,stdio:["ignore","pipe","pipe"],env:{...process.env,...options.env},detached:process.platform!=="win32",windowsHide:!0}),stdout="",stderr="";child.stdout.on("data",chunk=>{stdout+=chunk.toString()}),child.stderr.on("data",chunk=>{stderr+=chunk.toString()});let abort=new AbortController,timedOut=!1,pid=child.pid,timer=options.timeoutMs===void 0?void 0:setTimeout(()=>{timedOut=!0,pid!==void 0&&killProcessTree(pid),abort.abort()},options.timeoutMs);try{return{code:await waitForChildProcess(child,{signal:abort.signal}),stdout,stderr,timedOut}}finally{timer!==void 0&&clearTimeout(timer)}}function isKillSwitched(env){return env.SENPI_OMO_LOCAL_UPDATE==="0"}function defaultReadJson(path){try{return JSON.parse(readFileSync(path,"utf-8"))}catch{return}}function packageNameOf(json){if(typeof json!="object"||json===null)return;let name=json.name;return typeof name=="string"?name:void 0}function homeDir(){return process.env.HOME||homedir()}async function detectOmoLocalInstall(options){let readJson=options.readJson??defaultReadJson,exists=options.exists??existsSync2;if(options.packages)for(let entry of options.packages){let source=typeof entry=="string"?entry:entry.source;if(!isLocalPath(source))continue;let pluginPath=resolvePath(source,options.agentDir,{homeDir:homeDir(),trim:!0});if(packageNameOf(readJson(join3(pluginPath,"package.json")))!=="@code-yeongyu/omo-senpi")continue;let repoRoot=resolve2(pluginPath,"..","..",".."),omoSenpiPkgPath=join3(repoRoot,"packages","omo-senpi","package.json"),senpiTaskPkgPath=join3(repoRoot,"packages","senpi-task","package.json");if(!exists(omoSenpiPkgPath)||packageNameOf(readJson(omoSenpiPkgPath))!=="@oh-my-opencode/omo-senpi"||!exists(senpiTaskPkgPath)||packageNameOf(readJson(senpiTaskPkgPath))!=="@oh-my-opencode/senpi-task")continue;let topLevel;try{let result=await options.run("git",["-C",repoRoot,"rev-parse","--show-toplevel"],{});if(result.code!==0)continue;topLevel=result.stdout.trim()}catch{continue}if(!(topLevel===""||canonicalizePath(topLevel)!==canonicalizePath(repoRoot)))return{pluginPath,repoRoot}}}function omoLocalUpdateStampPath(agentDir){return join3(agentDir,"omo-local-update-state.json")}function readStamp(agentDir){let json=defaultReadJson(omoLocalUpdateStampPath(agentDir));if(typeof json!="object"||json===null)return;let candidate=json;if(typeof candidate.repoRoot!="string"||typeof candidate.sha!="string"||typeof candidate.omoSenpiTree!="string"||typeof candidate.senpiTaskTree!="string"||typeof candidate.buildInputsHash!="string"||typeof candidate.installedAt!="string"||!Array.isArray(candidate.artifacts))return;let artifacts=[];for(let artifact of candidate.artifacts){if(typeof artifact!="string")return;artifacts.push(artifact)}return{repoRoot:candidate.repoRoot,sha:candidate.sha,omoSenpiTree:candidate.omoSenpiTree,senpiTaskTree:candidate.senpiTaskTree,buildInputsHash:candidate.buildInputsHash,installedAt:candidate.installedAt,artifacts}}function writeStamp(agentDir,stamp){mkdirSync2(agentDir,{recursive:!0}),writeFileSync(omoLocalUpdateStampPath(agentDir),`${JSON.stringify(stamp,null,2)}
`,"utf-8")}function shouldSkipUpdate(options){if(options.force)return!1;let stamp=options.stamp;return!stamp||stamp.repoRoot!==options.repoRoot||stamp.sha!==options.remoteSha&&stamp.buildInputsHash!==options.remoteBuildInputsHash||stamp.artifacts.length===0?!1:options.stampArtifactsExist}var OmoLocalStepError=class extends Error{constructor(stage,message,output){super(message),this.name="OmoLocalStepError",this.stage=stage,this.output=output}};function firstErrorLine(result){for(let text of[result.stderr,result.stdout])for(let line of text.split(`
`)){let trimmed=line.trim();if(trimmed!=="")return trimmed}return"unknown error"}async function computeRemoteState(options){let{repoRoot,run}=options,git=(args,timeoutMs)=>run("git",args,{cwd:repoRoot,timeoutMs}),requireOk=async(args,timeoutMs)=>{let result=await git(args,timeoutMs);if(result.timedOut)throw new OmoLocalStepError("fetch",`git ${args.join(" ")} timed out`);if(result.code!==0)throw new OmoLocalStepError("fetch",`git ${args.join(" ")}: ${firstErrorLine(result)}`,`${result.stdout}${result.stderr}`);return result.stdout.trim()};await requireOk(["fetch","origin","dev"],12e4);let sha=await requireOk(["rev-parse","origin/dev"]);if(sha==="")throw new OmoLocalStepError("fetch","git rev-parse origin/dev: empty output");let subject=await requireOk(["log","-1","--format=%s","origin/dev"]),omoSenpiTree=await requireOk(["rev-parse","origin/dev:packages/omo-senpi"]),senpiTaskTree=await requireOk(["rev-parse","origin/dev:packages/senpi-task"]),buildInputsHash=computeBuildInputsHashFromLsTree(await requireOk(["ls-tree","-z","origin/dev"]));return{sha,subject,omoSenpiTree,senpiTaskTree,buildInputsHash}}function omoLocalUpdateLockPath(agentDir){return join3(agentDir,"omo-local-update.lock")}function omoLocalUpdateBuildWorktreePath(agentDir){return join3(agentDir,"omo-local-update","build-worktree")}function readLockFile(path){try{let json=JSON.parse(readFileSync(path,"utf-8"));return typeof json.pid!="number"||typeof json.nonce!="string"?void 0:{pid:json.pid,nonce:json.nonce}}catch{return}}function pidIsAlive(pid){try{return process.kill(pid,0),!0}catch(error){return error.code==="EPERM"}}function acquireOmoLocalLock(agentDir,log){mkdirSync2(agentDir,{recursive:!0});let path=omoLocalUpdateLockPath(agentDir),lock={path,pid:process.pid,nonce:randomUUID()},payload=JSON.stringify({pid:lock.pid,nonce:lock.nonce,startedAt:new Date().toISOString()}),tryCreate=()=>{try{return writeFileSync(path,payload,{flag:"wx"}),!0}catch(error){if(error.code==="EEXIST")return!1;throw error}},reportBusy=()=>{let existing2=readLockFile(path);log(source_default.dim(`OMO local plugin update already running (pid ${existing2?.pid??"unknown"}); skipping.`))};if(tryCreate())return lock;let existing=readLockFile(path);if(existing!==void 0&&pidIsAlive(existing.pid))return reportBusy();try{rmSync(path)}catch{}return tryCreate()?lock:reportBusy()}function releaseOmoLocalLock(lock){try{let existing=readLockFile(lock.path);existing!==void 0&&existing.pid===lock.pid&&existing.nonce===lock.nonce&&rmSync(lock.path)}catch{}}var OmoLocalBunMissingError=class extends Error{constructor(){super("bun not found on PATH"),this.name="OmoLocalBunMissingError"}};async function runBunStep(stage,args,worktree,run,timeoutMs){let result;try{result=await run("bun",args,{cwd:worktree,timeoutMs})}catch(error){throw error.code==="ENOENT"?new OmoLocalBunMissingError:new OmoLocalStepError(stage,`bun ${args.join(" ")} failed to start: ${error instanceof Error?error.message:String(error)}`)}let output=`${result.stdout}${result.stderr}`;if(result.timedOut)throw new OmoLocalStepError(stage,`bun ${args.join(" ")} timed out after ${Math.round(timeoutMs/1e3)}s`,output);if(result.code!==0)throw new OmoLocalStepError(stage,`bun ${args.join(" ")} exited with code ${result.code??"unknown"}`,output)}async function ensureBuildWorktree(options){let{worktree,repoRoot,sha,run}=options;if(existsSync2(worktree)){let commonDir=await run("git",["-C",worktree,"rev-parse","--git-common-dir"],{});if(commonDir.code===0&&commonDir.stdout.trim()!==""&&canonicalizePath(resolve2(worktree,commonDir.stdout.trim()))===canonicalizePath(join3(repoRoot,".git"))){let checkout=await run("git",["-C",worktree,"checkout","--detach","--force",sha],{});if(checkout.code!==0)throw new OmoLocalStepError("worktree",`git checkout --detach --force: ${firstErrorLine(checkout)}`,`${checkout.stdout}${checkout.stderr}`);return}((await run("git",["-C",repoRoot,"worktree","remove","--force",worktree],{})).code!==0||existsSync2(worktree))&&rmSync(worktree,{recursive:!0,force:!0})}mkdirSync2(dirname2(worktree),{recursive:!0});let add=await run("git",["-C",repoRoot,"worktree","add","--detach",worktree,sha],{});if(add.code===0)return;await run("git",["-C",repoRoot,"worktree","prune"],{});let retry=await run("git",["-C",repoRoot,"worktree","add","--detach",worktree,sha],{});if(retry.code!==0)throw new OmoLocalStepError("worktree",`git worktree add: ${firstErrorLine(retry)}`,`${add.stdout}${add.stderr}${retry.stdout}${retry.stderr}`)}var defaultFsSeam={cpSync:(source,destination)=>{cpSync(source,destination,{recursive:!0})},renameSync:(oldPath,newPath)=>{renameSync(oldPath,newPath)},rmSync:path=>{rmSync(path,{recursive:!0,force:!0})}},swapCounter=0;function swapPluginDir(options){let seam=options.fs??defaultFsSeam;swapCounter+=1;let tag=`${Date.now()}-${process.pid}-${swapCounter}`,staging=`${options.pluginPath}.staging-${tag}`,prev=`${options.pluginPath}.prev-${tag}`;seam.cpSync(options.sourceDir,staging),seam.renameSync(options.pluginPath,prev);try{seam.renameSync(staging,options.pluginPath)}catch(error){throw seam.renameSync(prev,options.pluginPath),seam.rmSync(staging),error}seam.rmSync(prev)}function firstLine(text){for(let line of text.split(`
`)){let trimmed=line.trim();if(trimmed!=="")return trimmed}return"unknown error"}function lastNonEmptyLines(text,count){let lines=[];for(let line of text.split(`
`))line.trim()!==""&&lines.push(line);return lines.slice(-count)}async function runOmoLocalUpdateBeta(options){let log=options.log??(message=>{console.log(message)}),run=options.run??defaultRun,dispatchRequested=(options.mode??"build")==="dispatch"&&options.env.SENPI_OMO_LOCAL_UPDATE_SYNC!=="1",repoRoot;try{if(isKillSwitched(options.env))return;let install=await detectOmoLocalInstall({packages:options.settings?.packages,agentDir:options.agentDir,run});if(!install)return;repoRoot=install.repoRoot;let{pluginPath}=install,lock=acquireOmoLocalLock(options.agentDir,log);if(lock===void 0)return;try{log(source_default.dim("Updating OMO local plugins: fetching origin/dev..."));let remoteState=await computeRemoteState({repoRoot,run}),stamp=readStamp(options.agentDir),stampArtifactsExist=(stamp?.artifacts.every(artifact=>existsSync2(join3(pluginPath,artifact)))??!1)&¤tRequiredBuildArtifactsExist(pluginPath);if(shouldSkipUpdate({stamp,repoRoot,remoteSha:remoteState.sha,remoteBuildInputsHash:remoteState.buildInputsHash,stampArtifactsExist,force:options.force??!1})){let shortSkip=remoteState.sha.slice(0,7);log(stamp?.sha===remoteState.sha?source_default.dim(`OMO local plugins already at origin/dev @${shortSkip}; skipping rebuild.`):source_default.dim(`OMO local plugins already match origin/dev @${shortSkip} (build inputs unchanged); skipping rebuild.`));return}if(dispatchRequested){releaseOmoLocalLock(lock);let spawned=(options.spawnWorker??defaultSpawnWorker)({agentDir:options.agentDir,force:options.force??!1});spawned.ok?log(source_default.dim(`Updating OMO local plugins in background: origin/dev @${remoteState.sha.slice(0,7)} - ${remoteState.subject} (log: ${spawned.logPath})`)):(log(source_default.yellow(`OMO local plugin background update could not start: ${spawned.message}`)),log(source_default.dim("Run `senpi update` again, or set SENPI_OMO_LOCAL_UPDATE_SYNC=1 to update in the foreground.")));return}let worktree=omoLocalUpdateBuildWorktreePath(options.agentDir);await ensureBuildWorktree({worktree,repoRoot,sha:remoteState.sha,run});try{log(source_default.dim("Updating OMO local plugins: installing deps...")),await runBunStep("install",["install"],worktree,run,6e5),log(source_default.dim("Updating OMO local plugins: building plugin...")),await runBunStep("build",["run","build:senpi-plugin"],worktree,run,9e5)}catch(stepError){if(stepError instanceof OmoLocalBunMissingError){log(source_default.yellow("OMO local plugin update skipped: bun is required to install and build the plugin but was not found on PATH. Install bun and re-run `senpi update`."));return}throw stepError}let worktreePluginDir=join3(worktree,relative2(repoRoot,pluginPath)),missing=findMissingBuildArtifacts(worktreePluginDir);if(missing.length>0)throw new OmoLocalStepError("artifacts",`build incomplete - missing: ${missing.join(", ")}`);try{swapPluginDir({pluginPath,sourceDir:worktreePluginDir})}catch(swapError){throw new OmoLocalStepError("swap",`atomic swap failed: ${swapError instanceof Error?swapError.message:String(swapError)}`)}writeStamp(options.agentDir,{repoRoot,sha:remoteState.sha,omoSenpiTree:remoteState.omoSenpiTree,senpiTaskTree:remoteState.senpiTaskTree,buildInputsHash:remoteState.buildInputsHash,installedAt:new Date().toISOString(),artifacts:collectArtifactInventory(pluginPath)});let short=remoteState.sha.slice(0,7);if(log(source_default.green(`Updated OMO local plugins (omo-senpi + senpi-task) to origin/dev @${short} - ${remoteState.subject}`)),stamp!==void 0){let omoLine=stamp.omoSenpiTree===remoteState.omoSenpiTree?"unchanged":"updated",taskLine=stamp.senpiTaskTree===remoteState.senpiTaskTree?"unchanged":"updated";log(source_default.dim(`omo-senpi: ${omoLine}, senpi-task: ${taskLine}`))}}finally{releaseOmoLocalLock(lock)}}catch(error){let stage=error instanceof OmoLocalStepError?error.stage:"unknown",message=error instanceof Error?error.message:String(error);if(log(source_default.yellow(`OMO local plugin update failed (${stage}): ${firstLine(message)}`)),error instanceof OmoLocalStepError&&error.output!==void 0)for(let line of lastNonEmptyLines(error.output,40))log(source_default.dim(line));repoRoot!==void 0&&log(source_default.dim(`To update manually: git -C ${repoRoot} pull origin dev && bun install && bun run build:senpi-plugin`))}}var CONFIG_IMPORT_PI_ARGV="import-pi",CONFIG_IMPORT_PI_USAGE=`${APP_COMMAND} config ${CONFIG_IMPORT_PI_ARGV} [${LEGACY_PI_CONFIG_FILES.join("|")} ...]`;function runConfigImportPi(files){let result=importLegacyPiConfig(files);if(result.imported.length===0&&result.failures.length===0){console.log(`Nothing to import: no config file in ${result.piAgentDir} changed after it was copied to ${result.agentDir}.`);return}for(let entry of result.imported)console.log(source_default.green(`Imported ${entry.from} \u2192 ${entry.to}`)),entry.backupPath!==void 0&&console.log(source_default.dim(`The previous ${entry.file} is saved as ${entry.backupPath}`));for(let failure of result.failures)console.error(source_default.red(`Skipped ${failure.file}: ${failure.reason}`));result.failures.length>0&&(process.exitCode=1)}var CONFIG_COMMAND_USAGE=`${APP_NAME} config [-l] [--approve|--no-approve]`;function printConfigCommandHelp(){console.log(`${source_default.bold("Usage:")}
${CONFIG_COMMAND_USAGE}
Open the resource configuration TUI to enable or disable package resources.
Without -l, starts in global settings (~/${CONFIG_DIR_NAME}/agent/settings.json).
Press Tab in the TUI to switch between global and project-local modes.
Options:
-l, --local Edit project overrides (${CONFIG_DIR_NAME}/settings.json)
-a, --approve Trust project-local files for this command with -l
-na, --no-approve Ignore project-local files for this command with -l
${APP_NAME} config agent-dir --json
Read the session engine's agent-directory selection without opening settings or starting a host.
Every outcome is one versioned JSON record: exit 0 for success, 2 for invalid arguments,
or 1 when the directory cannot be resolved. See docs/agent-directory-selection.md.
${CONFIG_IMPORT_PI_USAGE}
Copy config files you edited in ~/.pi/agent after its one-time copy into ~/${CONFIG_DIR_NAME}/agent,
saving each replaced file as <file>.bak-<time> first. Without file names, imports every edited file.
~/.pi/agent itself is only read.
`)}import{homedir as homedir2}from"node:os";import{basename,dirname as dirname3,join as join4,relative as relative3}from"node:path";var RESOURCE_TYPES=["extensions","skills","prompts","themes"],RESOURCE_TYPE_LABELS={extensions:"Extensions",skills:"Skills",prompts:"Prompts",themes:"Themes"};function formatBaseDir(baseDir){let homeDir2=homedir2(),displayPath;return baseDir===homeDir2?displayPath="~":baseDir.startsWith(homeDir2)?displayPath=`~${baseDir.slice(homeDir2.length).replace(/\\/g,"/")}`:displayPath=baseDir.replace(/\\/g,"/"),displayPath.endsWith("/")?displayPath:`${displayPath}/`}function getGroupLabel(metadata,agentDir){return metadata.origin==="package"?`${metadata.source} (${metadata.scope})`:metadata.source==="builtin"?metadata.scope==="user"?"Built-in":"Built-in (project override)":metadata.source==="auto"?metadata.baseDir?metadata.scope==="user"?`User (${formatBaseDir(metadata.baseDir)})`:`Project (${formatBaseDir(metadata.baseDir)})`:metadata.scope==="user"?`User (${formatBaseDir(agentDir)})`:`Project (${CONFIG_DIR_NAME}/)`:metadata.scope==="user"?"User settings":"Project settings"}function buildGroups(resolved,agentDir){let groupMap=new Map,addToGroup=(resources,resourceType)=>{for(let res of resources){let{path,enabled,metadata}=res,groupKey=`${metadata.origin}:${metadata.scope}:${metadata.source}:${metadata.baseDir??""}`;groupMap.has(groupKey)||groupMap.set(groupKey,{key:groupKey,label:getGroupLabel(metadata,agentDir),scope:metadata.scope,origin:metadata.origin,source:metadata.source,subgroups:[]});let group=groupMap.get(groupKey),subgroupKey=`${groupKey}:${resourceType}`,subgroup=group.subgroups.find(sg=>sg.type===resourceType);subgroup||(subgroup={type:resourceType,label:RESOURCE_TYPE_LABELS[resourceType],items:[]},group.subgroups.push(subgroup));let fileName=basename(path),parentFolder=basename(dirname3(path)),displayName;metadata.source==="builtin"?displayName=path.slice(BUILTIN_PATH_PREFIX.length):resourceType==="extensions"&&parentFolder!=="extensions"?displayName=`${parentFolder}/${fileName}`:resourceType==="skills"&&fileName==="SKILL.md"?displayName=parentFolder:displayName=fileName,subgroup.items.push({path,enabled,metadata,resourceType,displayName,groupKey,subgroupKey})}};addToGroup(resolved.extensions,"extensions"),addToGroup(resolved.skills,"skills"),addToGroup(resolved.prompts,"prompts"),addToGroup(resolved.themes,"themes");let groups=Array.from(groupMap.values());groups.sort((a,b)=>a.origin!==b.origin?a.origin==="package"?-1:1:a.scope!==b.scope?a.scope==="user"?-1:1:a.source.localeCompare(b.source));let typeOrder={extensions:0,skills:1,prompts:2,themes:3};for(let group of groups){group.subgroups.sort((a,b)=>typeOrder[a.type]-typeOrder[b.type]);for(let subgroup of group.subgroups)subgroup.items.sort((a,b)=>a.displayName.localeCompare(b.displayName))}return groups}var ConfigSelectorHeader=class{constructor(writeScope,projectModeAvailable){this.writeScope=writeScope,this.projectModeAvailable=projectModeAvailable}setWriteScope(writeScope){this.writeScope=writeScope}invalidate(){}render(width){let title=theme.bold(this.writeScope==="project"?"Project Local Resources":"Global Resources"),sep2=theme.fg("muted"," \xB7 "),switchHint=this.projectModeAvailable?keyHint("tui.input.tab","switch mode")+sep2:"",actionHint=this.writeScope==="project"?rawKeyHint("space","cycle inherit/+/-"):rawKeyHint("space","toggle"),hint=switchHint+actionHint+sep2+rawKeyHint("esc","close"),spacing=Math.max(1,width-visibleWidth(title)-visibleWidth(hint)),scopeHint=this.writeScope==="project"?theme.fg("muted",`${CONFIG_DIR_NAME}/settings.json \xB7 inherited global resources are dimmed`):theme.fg("muted",`~/${CONFIG_DIR_NAME}/agent/settings.json`);return[truncateToWidth(`${title}${" ".repeat(spacing)}${hint}`,width,""),truncateToWidth(scopeHint,width,"")]}},ResourceList=class{get focused(){return this._focused}set focused(value){this._focused=value,this.searchInput.focused=value}constructor(groupsByScope,settingsManager,cwd,agentDir,terminalHeight,writeScope="global"){this.flatItems=[],this.filteredItems=[],this.selectedIndex=0,this._focused=!1,this.groupsByScope=groupsByScope,this.settingsManager=settingsManager,this.cwd=cwd,this.agentDir=agentDir,this.writeScope=writeScope,this.inheritedEnabledByKey=this.buildInheritedEnabledMap(groupsByScope.global),this.searchInput=new Input;let chrome=8;this.maxVisible=Math.max(5,(terminalHeight??24)-chrome),this.buildFlatList(),this.filteredItems=[...this.flatItems]}setWriteScope(writeScope){this.writeScope=writeScope,this.buildFlatList(),this.filterItems(this.searchInput.getValue())}get groups(){return this.groupsByScope[this.writeScope]}buildInheritedEnabledMap(groups){let result=new Map;for(let group of groups)for(let subgroup of group.subgroups)for(let item of subgroup.items)result.set(this.getResourceItemKey(item),item.enabled);return result}buildFlatList(){this.flatItems=[];for(let group of this.groups){this.flatItems.push({type:"group",group});for(let subgroup of group.subgroups){this.flatItems.push({type:"subgroup",subgroup,group});for(let item of subgroup.items)this.flatItems.push({type:"item",item})}}this.selectedIndex=this.flatItems.findIndex(e=>e.type==="item"),this.selectedIndex<0&&(this.selectedIndex=0)}findNextItem(fromIndex,direction){let idx=fromIndex+direction;for(;idx>=0&&idx<this.filteredItems.length;){if(this.filteredItems[idx].type==="item")return idx;idx+=direction}return fromIndex}filterItems(query){if(!query.trim()){this.filteredItems=[...this.flatItems],this.selectFirstItem();return}let lowerQuery=query.toLowerCase(),matchingItems=new Set,matchingSubgroups=new Set,matchingGroups=new Set;for(let entry of this.flatItems)if(entry.type==="item"){let item=entry.item;(item.displayName.toLowerCase().includes(lowerQuery)||item.resourceType.toLowerCase().includes(lowerQuery)||item.path.toLowerCase().includes(lowerQuery))&&matchingItems.add(item)}for(let group of this.groups)for(let subgroup of group.subgroups)for(let item of subgroup.items)matchingItems.has(item)&&(matchingSubgroups.add(subgroup),matchingGroups.add(group));this.filteredItems=[];for(let entry of this.flatItems)entry.type==="group"&&matchingGroups.has(entry.group)?this.filteredItems.push(entry):entry.type==="subgroup"&&matchingSubgroups.has(entry.subgroup)?this.filteredItems.push(entry):entry.type==="item"&&matchingItems.has(entry.item)&&this.filteredItems.push(entry);this.selectFirstItem()}selectFirstItem(){let firstItemIndex=this.filteredItems.findIndex(e=>e.type==="item");this.selectedIndex=firstItemIndex>=0?firstItemIndex:0}updateItem(item,enabled){item.enabled=enabled;for(let group of this.groups)for(let subgroup of group.subgroups){let found=subgroup.items.find(i=>i.path===item.path&&i.resourceType===item.resourceType);if(found){found.enabled=enabled;return}}}invalidate(){}render(width){let lines=[];if(lines.push(...this.searchInput.render(width)),lines.push(""),this.filteredItems.length===0)return lines.push(theme.fg("muted"," No resources found")),lines;let startIndex=Math.max(0,Math.min(this.selectedIndex-Math.floor(this.maxVisible/2),this.filteredItems.length-this.maxVisible)),endIndex=Math.min(startIndex+this.maxVisible,this.filteredItems.length);for(let i=startIndex;i<endIndex;i++){let entry=this.filteredItems[i],isSelected=i===this.selectedIndex;if(entry.type==="group"){let inherited=this.writeScope==="project"&&entry.group.scope==="user",label=theme.bold(`${entry.group.label}${inherited?" \xB7 inherited global":""}`),groupLine=theme.fg(inherited?"dim":"accent",label);lines.push(truncateToWidth(` ${groupLine}`,width,""))}else if(entry.type==="subgroup"){let color=this.writeScope==="project"&&entry.group.scope==="user"?"dim":"muted",subgroupLine=theme.fg(color,entry.subgroup.label);lines.push(truncateToWidth(` ${subgroupLine}`,width,""))}else{let item=entry.item,cursor=isSelected?"> ":" ",dimmed=this.isDimmedItem(item),nameText=isSelected&&!dimmed?theme.bold(item.displayName):item.displayName,name=dimmed?theme.fg("dim",nameText):nameText;lines.push(truncateToWidth(`${cursor} ${this.renderCheckbox(item)} ${name}${this.getItemSuffix(item)}`,width,"..."))}}if(startIndex>0||endIndex<this.filteredItems.length){let itemCount=this.filteredItems.filter(e=>e.type==="item").length,currentItemIndex=this.filteredItems.slice(0,this.selectedIndex).filter(e=>e.type==="item").length+1;lines.push(theme.fg("dim",` (${currentItemIndex}/${itemCount})`))}return lines}handleInput(data){let kb=getKeybindings();if(kb.matches(data,"tui.select.up")){this.selectedIndex=this.findNextItem(this.selectedIndex,-1);return}if(kb.matches(data,"tui.select.down")){this.selectedIndex=this.findNextItem(this.selectedIndex,1);return}if(kb.matches(data,"tui.select.pageUp")){let target=Math.max(0,this.selectedIndex-this.maxVisible);for(;target<this.filteredItems.length&&this.filteredItems[target].type!=="item";)target++;target<this.filteredItems.length&&(this.selectedIndex=target);return}if(kb.matches(data,"tui.select.pageDown")){let target=Math.min(this.filteredItems.length-1,this.selectedIndex+this.maxVisible);for(;target>=0&&this.filteredItems[target].type!=="item";)target--;target>=0&&(this.selectedIndex=target);return}if(kb.matches(data,"tui.select.cancel")){this.onCancel?.();return}if(matchesKey(data,"ctrl+c")){this.onExit?.();return}if(kb.matches(data,"tui.input.tab")){this.onSwitchMode?.();return}if(data===" "||kb.matches(data,"tui.select.confirm")){let entry=this.filteredItems[this.selectedIndex];if(entry?.type==="item"&&(this.writeScope==="project"||this.getItemScope(entry.item)==="user")){let newEnabled=this.toggleResource(entry.item);newEnabled!==void 0&&(this.updateItem(entry.item,newEnabled),this.onToggle?.(entry.item,newEnabled))}return}this.searchInput.handleInput(data),this.filterItems(this.searchInput.getValue())}toggleResource(item){if(this.writeScope==="project"){let state=this.getNextOverrideState(item);return this.setProjectResourceOverride(item,state)?state==="inherit"?this.getInheritedEnabled(item):state==="load":void 0}let enabled=!item.enabled;return item.metadata.origin==="top-level"?this.toggleTopLevelResource(item,enabled):this.togglePackageResource(item,enabled),enabled}toggleTopLevelResource(item,enabled){let scope=item.metadata.scope,settings=scope==="project"?this.settingsManager.getProjectSettings():this.settingsManager.getGlobalSettings(),arrayKey=item.resourceType,current=settings[arrayKey]??[],pattern=this.getResourcePattern(item),disablePattern=`-${pattern}`,enablePattern=`+${pattern}`,updated=current.filter(p=>(p.startsWith("!")||p.startsWith("+")||p.startsWith("-")?p.slice(1):p)!==pattern);enabled?updated.push(enablePattern):updated.push(disablePattern),scope==="project"?arrayKey==="extensions"?this.settingsManager.setProjectExtensionPaths(updated):arrayKey==="skills"?this.settingsManager.setProjectSkillPaths(updated):arrayKey==="prompts"?this.settingsManager.setProjectPromptTemplatePaths(updated):arrayKey==="themes"&&this.settingsManager.setProjectThemePaths(updated):arrayKey==="extensions"?this.settingsManager.setExtensionPaths(updated):arrayKey==="skills"?this.settingsManager.setSkillPaths(updated):arrayKey==="prompts"?this.settingsManager.setPromptTemplatePaths(updated):arrayKey==="themes"&&this.settingsManager.setThemePaths(updated)}togglePackageResource(item,enabled){let scope=item.metadata.scope,packages=[...(scope==="project"?this.settingsManager.getProjectSettings():this.settingsManager.getGlobalSettings()).packages??[]],pkgIndex=packages.findIndex(pkg2=>(typeof pkg2=="string"?pkg2:pkg2.source)===item.metadata.source);if(pkgIndex===-1)return;let pkg=packages[pkgIndex];typeof pkg=="string"&&(pkg={source:pkg},packages[pkgIndex]=pkg);let arrayKey=item.resourceType,current=pkg[arrayKey]??[],pattern=this.getPackageResourcePattern(item),disablePattern=`-${pattern}`,enablePattern=`+${pattern}`,updated=current.filter(p=>(p.startsWith("!")||p.startsWith("+")||p.startsWith("-")?p.slice(1):p)!==pattern);enabled?updated.push(enablePattern):updated.push(disablePattern),pkg[arrayKey]=updated.length>0?updated:void 0,["extensions","skills","prompts","themes"].some(k=>pkg[k]!==void 0)||(packages[pkgIndex]=pkg.source),scope==="project"?this.settingsManager.setProjectPackages(packages):this.settingsManager.setPackages(packages)}renderCheckbox(item){if(this.writeScope==="project"){let state=this.getProjectOverrideState(item);return state==="load"?theme.fg("success","[+]"):state==="unload"?theme.fg("warning","[-]"):theme.fg("dim",item.enabled?"[x]":"[ ]")}return item.enabled?theme.fg("success","[x]"):theme.fg("dim","[ ]")}getItemSuffix(item){if(this.writeScope!=="project")return"";let state=this.getProjectOverrideState(item);return state==="load"?theme.fg("muted"," project load"):state==="unload"?theme.fg("muted"," project unload"):this.isInheritedGlobalItem(item)?theme.fg("dim"," inherited global"):""}isDimmedItem(item){return this.writeScope==="project"&&this.isInheritedGlobalItem(item)&&this.getProjectOverrideState(item)==="inherit"}setProjectResourceOverride(item,state){return item.metadata.origin==="top-level"?this.setProjectTopLevelOverride(item,state):this.setProjectPackageOverride(item,state)}setProjectTopLevelOverride(item,state){let current=this.settingsManager.getProjectSettings()[item.resourceType]??[],pattern=this.isInheritedGlobalItem(item)?item.path:this.getResourcePatternForScope(item,"project"),patterns=this.getTopLevelOverridePatterns(item,"project"),updated=current.filter(entry=>{let target=this.getPatternEntryTarget(entry);return(entry.startsWith("!")||entry.startsWith("+")||entry.startsWith("-"))&&patterns.has(target)?!1:!(state==="inherit"&&this.isInheritedGlobalItem(item)&&target===pattern)});return state!=="inherit"&&(this.isInheritedGlobalItem(item)&&item.metadata.source!=="builtin"&&!updated.includes(pattern)&&updated.push(pattern),updated.push(`${state==="load"?"+":"-"}${pattern}`)),this.setProjectTopLevelPaths(item.resourceType,updated),!0}setProjectTopLevelPaths(key,paths){key==="extensions"?this.settingsManager.setProjectExtensionPaths(paths):key==="skills"?this.settingsManager.setProjectSkillPaths(paths):key==="prompts"?this.settingsManager.setProjectPromptTemplatePaths(paths):this.settingsManager.setProjectThemePaths(paths)}setProjectPackageOverride(item,state){let packages=[...this.settingsManager.getProjectSettings().packages??[]],pkgIndex=packages.findIndex(pkg2=>this.packageSourceStringMatches(item.metadata.source,this.getItemScope(item),typeof pkg2=="string"?pkg2:pkg2.source,"project"));if(pkgIndex===-1){if(state==="inherit")return!1;packages.push(this.createPackageOverrideSource(item)),pkgIndex=packages.length-1}let pkg=packages[pkgIndex];if(pkg===void 0)return!1;typeof pkg=="string"&&(pkg={source:pkg},packages[pkgIndex]=pkg);let pattern=this.getPackageResourcePattern(item),updated=(pkg[item.resourceType]??[]).filter(entry=>this.getPatternEntryTarget(entry)!==pattern);return state!=="inherit"&&updated.push(`${state==="load"?"+":"-"}${pattern}`),pkg[item.resourceType]=updated.length>0?updated:void 0,RESOURCE_TYPES.some(key=>pkg[key]!==void 0)||(pkg.autoload===!1?packages.splice(pkgIndex,1):packages[pkgIndex]=pkg.source),this.settingsManager.setProjectPackages(packages),!0}getNextOverrideState(item){let state=this.getProjectOverrideState(item),inheritedEnabled=this.getInheritedEnabled(item);return state==="inherit"?inheritedEnabled?"unload":"load":state==="unload"?inheritedEnabled?"load":"inherit":inheritedEnabled?"inherit":"unload"}getProjectOverrideState(item){if(this.writeScope!=="project")return"inherit";if(item.metadata.origin==="top-level")return this.getOverrideStateFromEntries(this.settingsManager.getProjectSettings()[item.resourceType]??[],this.getTopLevelOverridePatterns(item,"project"),!1);let pkg=this.findMatchingPackageSource(item,"project");if(typeof pkg!="object")return"inherit";let entries=pkg[item.resourceType];return entries===void 0?"inherit":this.getOverrideStateFromEntries(entries,new Set([this.getPackageResourcePattern(item)]),pkg.autoload!==!1)}getOverrideStateFromEntries(entries,patterns,emptyArrayIsUnload){if(entries.length===0&&emptyArrayIsUnload)return"unload";let state="inherit";for(let entry of entries)patterns.has(this.getPatternEntryTarget(entry))&&(entry.startsWith("!")||entry.startsWith("-")?state="unload":state="load");return state}getInheritedEnabled(item){return this.inheritedEnabledByKey.get(this.getResourceItemKey(item))??(this.getItemScope(item)==="user"?item.enabled:!0)}isInheritedGlobalItem(item){return this.getItemScope(item)==="user"||this.inheritedEnabledByKey.has(this.getResourceItemKey(item))}getTopLevelOverridePatterns(item,scope){let baseDir=this.getTopLevelBaseDir(scope),patterns=new Set([this.getResourcePatternForScope(item,scope),item.path,relative3(baseDir,item.path)]);return item.metadata.baseDir&&patterns.add(relative3(item.metadata.baseDir,item.path)),patterns}getResourcePatternForScope(item,scope){let sourceScope=this.getItemScope(item);if(scope!==sourceScope||item.metadata.source==="builtin")return item.path;let baseDir=item.metadata.baseDir??this.getTopLevelBaseDir(sourceScope);return relative3(baseDir,item.path)}createPackageOverrideSource(item){let source=item.metadata.source;if(!isLocalPath(source))return{source,autoload:!1};let sourcePath=resolvePath(source,this.getTopLevelBaseDir(this.getItemScope(item)),{trim:!0});return{source:relative3(this.getTopLevelBaseDir("project"),sourcePath)||".",autoload:!1}}packageSourceStringMatches(leftSource,leftScope,rightSource,rightScope){if(leftSource===rightSource)return!0;if(!isLocalPath(leftSource)||!isLocalPath(rightSource))return!1;let left=resolvePath(leftSource,this.getTopLevelBaseDir(leftScope),{trim:!0}),right=resolvePath(rightSource,this.getTopLevelBaseDir(rightScope),{trim:!0});return left===right}findMatchingPackageSource(item,targetScope){return((targetScope==="project"?this.settingsManager.getProjectSettings():this.settingsManager.getGlobalSettings()).packages??[]).find(pkg=>this.packageSourceStringMatches(item.metadata.source,this.getItemScope(item),typeof pkg=="string"?pkg:pkg.source,targetScope))}getPatternEntryTarget(entry){return entry.startsWith("!")||entry.startsWith("+")||entry.startsWith("-")?entry.slice(1):entry}getResourceItemKey(item){return`${item.resourceType}:${canonicalizePath(item.path)}`}getItemScope(item){return item.metadata.scope==="project"?"project":"user"}getTopLevelBaseDir(scope){return scope==="project"?join4(this.cwd,CONFIG_DIR_NAME):this.agentDir}getResourcePattern(item){if(item.metadata.source==="builtin")return item.path;let scope=item.metadata.scope,baseDir=item.metadata.baseDir??this.getTopLevelBaseDir(scope);return relative3(baseDir,item.path)}getPackageResourcePattern(item){let baseDir=item.metadata.baseDir??dirname3(item.path);return relative3(baseDir,item.path)}},ConfigSelectorComponent=class extends Container{get focused(){return this._focused}set focused(value){this._focused=value,this.resourceList.focused=value}constructor(resolvedPaths,settingsManager,cwd,agentDir,onClose,onExit,requestRender,terminalHeight,writeScope="global",projectModeAvailable=!0){super(),this._focused=!1,this.writeScope=writeScope;let groupsByScope={global:buildGroups(resolvedPaths.global,agentDir),project:buildGroups(resolvedPaths.project,agentDir)};this.addChild(new Spacer(1)),this.addChild(new DynamicBorder),this.addChild(new Spacer(1)),this.header=new ConfigSelectorHeader(this.writeScope,projectModeAvailable),this.addChild(this.header),this.addChild(new Spacer(1)),this.resourceList=new ResourceList(groupsByScope,settingsManager,cwd,agentDir,terminalHeight,this.writeScope),this.resourceList.onCancel=onClose,this.resourceList.onExit=onExit,this.resourceList.onToggle=()=>requestRender(),projectModeAvailable&&(this.resourceList.onSwitchMode=()=>{this.switchWriteScope(),requestRender()}),this.addChild(this.resourceList),this.addChild(new Spacer(1)),this.addChild(new DynamicBorder)}switchWriteScope(){this.writeScope=this.writeScope==="global"?"project":"global",this.header.setWriteScope(this.writeScope),this.resourceList.setWriteScope(this.writeScope)}getResourceList(){return this.resourceList}};async function selectConfig(options){return initTheme(options.settingsManager.getTheme(),!0),new Promise(resolve4=>{let ui=new TUI(new ProcessTerminal({onExternalStdoutWrite:appendHiddenTuiStdout}),options.settingsManager.getShowHardwareCursor());ui.setClearOnShrink(options.settingsManager.getClearOnShrink());let resolved=!1,selector=new ConfigSelectorComponent(options.resolvedPaths,options.settingsManager,options.cwd,options.agentDir,()=>{resolved||(resolved=!0,ui.stop(),stopThemeWatcher(),resolve4())},()=>{ui.stop(),stopThemeWatcher(),process.exit(0)},()=>ui.requestRender(),ui.terminal.rows,options.writeScope,options.projectModeAvailable);ui.addChild(selector),ui.setFocus(selector.getResourceList()),ui.start()})}var DEFAULT_INSTALLER_API_BASE="https://pi.dev/api/installer/releases",MANAGED_INSTALL_MARKER="managed-install.json",MANAGED_RELEASE_VERSION_RE=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;function getActiveManagedInstallRoot(){let configuredRoot=process.env.PI_MANAGED_INSTALL_ROOT?.trim();if(!configuredRoot)return;let managedRoot=resolve3(configuredRoot),releasesDir=canonicalizePath(join5(managedRoot,"releases"));if(getCwdRelativePath(canonicalizePath(getInstallPackageDir()),releasesDir)===void 0)return;let markerPath=join5(managedRoot,MANAGED_INSTALL_MARKER);try{let marker=JSON.parse(readFileSync2(markerPath,"utf8"));if(marker.kind!=="pi-managed-install"||marker.schemaVersion!==1||marker.layout!=="releases-v1")throw new Error}catch{throw new Error(`Managed install marker is missing or invalid: ${markerPath}`)}return managedRoot}async function fetchInstallerArtifact(url,label){let response=await fetch(url,{headers:{"User-Agent":getPiUserAgent(VERSION)}});if(!response.ok)throw new Error(`Could not download managed installer ${label} from ${url}: HTTP ${response.status}`);return await response.text()}async function runManagedNpmCi(stageDir){let args=["ci","--ignore-scripts","--min-release-age=0","--omit=dev","--include=optional","--no-fund","--no-audit","--loglevel=error","--progress=false"],code=await waitForChildProcess(spawnProcess("npm",args,{cwd:stageDir,stdio:"inherit"}));if(code!==0)throw new Error(`npm ${args.join(" ")} exited with code ${code??"unknown"}`)}function verifyManagedRelease(releaseDir,expectedVersion){let binPath=join5(releaseDir,"node_modules",".bin",process.platform==="win32"?`${APP_NAME}.cmd`:APP_NAME),result=spawnProcessSync(binPath,["--version"],{encoding:"utf8",stdio:["ignore","pipe","pipe"]});if(result.error||result.status!==0){let reason=result.error?.message||result.stderr.trim()||`exit code ${result.status??"unknown"}`;throw new Error(`Could not verify managed Pi ${expectedVersion}: ${reason}`)}let installedVersion=result.stdout.trim();if(installedVersion!==expectedVersion)throw new Error(`Managed Pi smoke test returned version ${installedVersion}; expected ${expectedVersion}.`)}function activateManagedRelease(managedRoot,version){let currentPath=join5(managedRoot,"current-version"),temporaryPath=join5(managedRoot,`current-version.tmp.${process.pid}-${Date.now()}`);try{writeFileSync2(temporaryPath,`${version}
`),renameSync2(temporaryPath,currentPath)}finally{rmSync2(temporaryPath,{force:!0})}}function cleanupManagedStaging(managedRoot){let stagingRoot=join5(managedRoot,"staging");try{for(let entry of readdirSync2(stagingRoot))entry.startsWith("update-")&&rmSync2(join5(stagingRoot,entry),{force:!0,recursive:!0})}catch{}}function cleanupManagedInstall(){let managedRoot;try{managedRoot=getActiveManagedInstallRoot()}catch{return}if(managedRoot)try{let releaseLock=import_proper_lockfile.default.lockSync(join5(managedRoot,"update"),{realpath:!1});try{cleanupManagedStaging(managedRoot)}finally{releaseLock()}}catch{}}async function runManagedSelfUpdate(managedRoot,version){if(!MANAGED_RELEASE_VERSION_RE.test(version))throw new Error(`Invalid managed release version: ${version}`);let updateLock;try{updateLock=await lockWithLossHandling(join5(managedRoot,"update"),{realpath:!1})}catch(error){throw error instanceof Error&&"code"in error&&error.code==="ELOCKED"?new Error("Another managed Pi update is already running."):error}let stageDir;try{cleanupManagedStaging(managedRoot);let releaseUrl=`${(process.env.PI_INSTALLER_API_BASE?.trim()||DEFAULT_INSTALLER_API_BASE).replace(/\/+$/,"")}/${encodeURIComponent(version)}`,stagingRoot=join5(managedRoot,"staging"),releasesRoot=join5(managedRoot,"releases");mkdirSync3(releasesRoot,{recursive:!0});let releaseDir=join5(releasesRoot,version);if(existsSync3(releaseDir)){verifyManagedRelease(releaseDir,version),updateLock.assertHeld(),activateManagedRelease(managedRoot,version);return}mkdirSync3(stagingRoot,{recursive:!0}),stageDir=mkdtempSync(join5(stagingRoot,"update-"));let[packageJsonContent,packageLockContent]=await Promise.all([fetchInstallerArtifact(`${releaseUrl}/package.json`,"package.json"),fetchInstallerArtifact(`${releaseUrl}/package-lock.json`,"package-lock.json")]);writeFileSync2(join5(stageDir,"package.json"),packageJsonContent),writeFileSync2(join5(stageDir,"package-lock.json"),packageLockContent),await runManagedNpmCi(stageDir),verifyManagedRelease(stageDir,version),updateLock.assertHeld(),renameSync2(stageDir,releaseDir),updateLock.assertHeld(),activateManagedRelease(managedRoot,version)}finally{stageDir&&rmSync2(stageDir,{force:!0,recursive:!0}),await updateLock.release()}}var SELF_UPDATE_NOTE_MARKDOWN_THEME={heading:text=>source_default.bold(source_default.yellow(text)),link:text=>source_default.cyan(text),linkUrl:text=>source_default.dim(text),code:text=>source_default.yellow(text),codeBlock:text=>source_default.dim(text),codeBlockBorder:text=>source_default.dim(text),quote:text=>source_default.dim(text),quoteBorder:text=>source_default.dim(text),hr:text=>source_default.dim(text),listBullet:text=>source_default.yellow(text),bold:text=>source_default.bold(text),italic:text=>source_default.italic(text),strikethrough:text=>source_default.strikethrough(text),underline:text=>source_default.underline(text)};function reportSettingsErrors(settingsManager,context){let errors=settingsManager.drainErrors();for(let{scope,error}of errors)console.error(source_default.yellow(`Warning (${context}, ${scope} settings): ${error.message}`)),error.stack&&console.error(source_default.dim(error.stack))}function getPackageCommandUsage(command){switch(command){case"install":return`${APP_NAME} install <source> [-l] [--approve|--no-approve]`;case"remove":return`${APP_NAME} remove <source> [-l] [--approve|--no-approve]`;case"update":return`${APP_NAME} update [source|self|${APP_NAME}] [--self|--extensions|--models|--all] [--extension <source>] [--approve|--no-approve] [--force]`;case"list":return`${APP_NAME} list [--approve|--no-approve]`}}function printPackageCommandHelp(command){switch(command){case"install":console.log(`${source_default.bold("Usage:")}
${getPackageCommandUsage("install")}
Install a package and add it to settings.
Options:
-l, --local Install project-locally (${CONFIG_DIR_NAME}/settings.json)
-a, --approve Trust project-local files for this command
-na, --no-approve Ignore project-local files for this command
Examples:
${APP_NAME} install npm:@foo/bar
${APP_NAME} install git:github.com/user/repo
${APP_NAME} install git:git@github.com:user/repo
${APP_NAME} install https://github.com/user/repo
${APP_NAME} install ssh://git@github.com/user/repo
${APP_NAME} install ./local/path
`);return;case"remove":console.log(`${source_default.bold("Usage:")}
${getPackageCommandUsage("remove")}
Remove a package and its source from settings.
Alias: ${APP_NAME} uninstall <source> [-l]
Options:
-l, --local Remove from project settings (${CONFIG_DIR_NAME}/settings.json)
-a, --approve Trust project-local files for this command
-na, --no-approve Ignore project-local files for this command
Examples:
${APP_NAME} remove npm:@foo/bar
${APP_NAME} uninstall npm:@foo/bar
`);return;case"update":console.log(`${source_default.bold("Usage:")}
${getPackageCommandUsage("update")}
Update ${APP_NAME}, installed packages, or model catalogs.
Options:
--self Update ${APP_NAME} only (default when no target is given)
--extensions Update installed packages only
--models Refresh model catalogs only
--all Update ${APP_NAME} and installed packages
--extension <source> Update one package only
-a, --approve Trust project-local files for this command
-na, --no-approve Ignore project-local files for this command
--force Reinstall ${APP_NAME} even if the current version is latest
Short forms:
${APP_NAME} update Update ${APP_NAME} only
${APP_NAME} update --all Update ${APP_NAME} and all extensions
${APP_NAME} update --models Refresh model catalogs only
${APP_NAME} update <source> Update one package
${APP_NAME} update ${APP_NAME} Update ${APP_NAME} only (self and pi work as aliases)
`);return;case"list":console.log(`${source_default.bold("Usage:")}
${getPackageCommandUsage("list")}
List installed packages from user and project settings.
Options:
-a, --approve Trust project-local files for this command
-na, --no-approve Ignore project-local files for this command
`);return}}function parsePackageCommand(args){let[rawCommand,...rest]=args,command;if(rawCommand==="uninstall"?command="remove":(rawCommand==="install"||rawCommand==="remove"||rawCommand==="update"||rawCommand==="list")&&(command=rawCommand),!command)return;let local=!1,force=!1,omoLocalUpdateWorker=!1,projectTrustOverride,help=!1,invalidOption,invalidArgument,missingOptionValue,conflictingOptions,source,selfFlag=!1,extensionsFlag=!1,modelsFlag=!1,allFlag=!1,extensionFlagSource;for(let index=0;index<rest.length;index++){let arg=rest[index];if(arg==="-h"||arg==="--help"){help=!0;continue}if(arg==="-l"||arg==="--local"){command==="install"||command==="remove"?local=!0:invalidOption=invalidOption??arg;continue}if(arg==="--self"){command==="update"?selfFlag=!0:invalidOption=invalidOption??arg;continue}if(arg==="--extensions"){command==="update"?extensionsFlag=!0:invalidOption=invalidOption??arg;continue}if(arg==="--models"){command==="update"?modelsFlag=!0:invalidOption=invalidOption??arg;continue}if(arg==="--all"){command==="update"?allFlag=!0:invalidOption=invalidOption??arg;continue}if(arg==="--approve"||arg==="-a"){projectTrustOverride=!0;continue}if(arg==="--no-approve"||arg==="-na"){projectTrustOverride=!1;continue}if(arg==="--force"){command==="update"?force=!0:invalidOption=invalidOption??arg;continue}if(arg==="--omo-local-update-worker"){command==="update"?omoLocalUpdateWorker=!0:invalidOption=invalidOption??arg;continue}if(arg==="--extension"){if(command!=="update"){invalidOption=invalidOption??arg;continue}let value=rest[index+1];!value||value.startsWith("-")?missingOptionValue=missingOptionValue??arg:extensionFlagSource?(conflictingOptions=conflictingOptions??"--extension can only be provided once",index++):(extensionFlagSource=value,index++);continue}if(arg.startsWith("-")){invalidOption=invalidOption??arg;continue}source?invalidArgument=invalidArgument??arg:source=arg}let updateTarget,showExtensionsSkippedNote=!1;return command==="update"&&(allFlag&&(selfFlag||extensionsFlag||modelsFlag||extensionFlagSource)&&(conflictingOptions=conflictingOptions??"--all cannot be combined with --self, --extensions, --models, or --extension"),allFlag&&source&&(conflictingOptions=conflictingOptions??"--all cannot be combined with a positional source"),modelsFlag?((selfFlag||extensionsFlag||allFlag||extensionFlagSource)&&(conflictingOptions=conflictingOptions??"--models cannot be combined with --self, --extensions, --all, or --extension"),source&&(conflictingOptions=conflictingOptions??"--models cannot be combined with a positional source"),updateTarget={type:"models"}):extensionFlagSource?((selfFlag||extensionsFlag||allFlag)&&(conflictingOptions=conflictingOptions??"--extension cannot be combined with --self, --extensions, or --all"),source&&(conflictingOptions=conflictingOptions??"--extension cannot be combined with a positional source"),updateTarget={type:"extensions",source:extensionFlagSource}):source?source==="self"||source==="pi"||source===APP_NAME?updateTarget=extensionsFlag?{type:"all"}:{type:"self"}:((extensionsFlag||selfFlag||allFlag)&&(conflictingOptions=conflictingOptions??"positional update targets cannot be combined with --self, --extensions, or --all"),updateTarget={type:"extensions",source}):allFlag?updateTarget={type:"all"}:selfFlag&&extensionsFlag?updateTarget={type:"all"}:selfFlag?updateTarget={type:"self"}:extensionsFlag?updateTarget={type:"extensions"}:(updateTarget={type:"self"},showExtensionsSkippedNote=!0)),{command,source,updateTarget,showExtensionsSkippedNote,omoLocalUpdateWorker,local,force,projectTrustOverride,help,invalidOption,invalidArgument,missingOptionValue,conflictingOptions}}function updateTargetIncludesSelf(target){return target.type==="all"||target.type==="self"}function updateTargetIncludesExtensions(target){return target.type==="all"||target.type==="extensions"}async function refreshModelCatalogs(agentDir){let controller=new AbortController,timeout=setTimeout(()=>controller.abort(),15e3);try{let result=await(await ModelRuntime.create({authPath:join5(agentDir,"auth.json"),modelsPath:join5(agentDir,"models.json"),allowModelNetwork:!1,signal:controller.signal})).refresh({allowNetwork:!0,force:!0,signal:controller.signal});if(result.aborted)throw new Error("Model catalog refresh timed out.");if(result.errors.size>0){let details=Array.from(result.errors,([provider,error])=>`${provider}: ${error.message}`).join("; ");throw new Error(`Could not refresh model catalogs: ${details}`)}}finally{clearTimeout(timeout)}console.log(source_default.green("Model catalogs refreshed"))}function printSelfUpdateUnavailable(npmCommand,updatePackageTarget=PACKAGE_NAME){console.error(`error: ${APP_NAME} cannot self-update this installation.`),console.error(getSelfUpdateUnavailableInstruction(PACKAGE_NAME,npmCommand,updatePackageTarget));let entrypoint=process.argv[1];entrypoint&&(console.error(""),console.error(`Location of ${APP_NAME} executable: ${entrypoint}`))}function printSelfUpdateFallback(command){console.error(source_default.dim(`If this keeps failing, run this command yourself: ${command.display}`))}function printPnpmSelfUpdateMetadataHint(){console.error(source_default.yellow("If pnpm reports missing package versions, its cached registry metadata may be stale.")),console.error(source_default.yellow(`Run \`pnpm store prune\` and retry \`${APP_NAME} update --self\`.`))}function printSelfUpdateNote(note){let trimmedNote=note.trim();if(trimmedNote){console.log(),console.log(source_default.bold(source_default.yellow("Update note")));try{let width=Math.max(20,process.stdout.columns??80),renderedLines=new Markdown(trimmedNote,0,0,SELF_UPDATE_NOTE_MARKDOWN_THEME).render(width).map(line=>line.trimEnd());console.log(renderedLines.join(`
`))}catch{console.log(trimmedNote)}console.log()}}function selfUpdatePlanAfterLookupFailure(installMethod,reason){if(installMethod!=="bun-binary")throw new Error(`Could not determine latest ${APP_NAME} version${reason?`: ${reason}`:"."}`);return console.log(source_default.yellow(`Could not check the latest ${APP_NAME} release${reason?` (${reason})`:""}.`)),console.log(source_default.cyan("Download from: https://github.com/code-yeongyu/senpi/releases/latest")),{packageName:PACKAGE_NAME,installSpec:PACKAGE_NAME,version:VERSION,shouldRun:!1}}async function getSelfUpdatePlan(force){let brandUpdate=brandProfile()?.update;if(brandUpdate)return console.log(source_default.yellow(`${APP_NAME} ships inside ${brandUpdate.packageName}. Update it with:`)),console.log(source_default.cyan(` ${brandUpdate.command}`)),{packageName:brandUpdate.packageName,installSpec:brandUpdate.command,version:DISPLAY_VERSION,shouldRun:!1};let latestRelease;try{latestRelease=await getLatestPiRelease(VERSION,{retry:!0})}catch(error){try{return selfUpdatePlanAfterLookupFailure(detectInstallMethod(),formatVersionCheckError(error))}catch(planError){throw planError instanceof Error?Object.assign(planError,{cause:error}):planError}}if(!latestRelease)return selfUpdatePlanAfterLookupFailure(detectInstallMethod(),"");let packageName=latestRelease.packageName??PACKAGE_NAME,installSpec=`${packageName}@${latestRelease.version}`;return force||packageName!==PACKAGE_NAME||isNewerPackageVersion(latestRelease.version,VERSION)?{packageName,installSpec,version:latestRelease.version,...latestRelease.note?{note:latestRelease.note}:{},shouldRun:!0}:(console.log(source_default.green(`${APP_NAME} is already up to date (v${VERSION})`)),{packageName,installSpec,version:latestRelease.version,shouldRun:!1})}async function runSelfUpdate(command){console.log(source_default.dim(`Updating ${APP_NAME} with ${command.display}...`));for(let step of command.steps??[command])await new Promise((resolve4,reject)=>{let child=spawnProcess(step.command,step.args,{stdio:"inherit"});child.on("error",error=>{reject(error)}),child.on("close",(code,signal)=>{code===0?resolve4():reject(signal?new Error(`${step.display} terminated by signal ${signal}`):new Error(`${step.display} exited with code ${code??"unknown"}`))})})}function prepareWindowsNpmSelfUpdate(){if(process.platform!=="win32")return;let packageDir=getInstallPackageDir();cleanupWindowsSelfUpdateQuarantine(packageDir),quarantineWindowsNativeDependencies(packageDir)}function getCommandAppMode(){return process.stdin.isTTY&&process.stdout.isTTY?"interactive":"print"}function reportProjectTrustWarnings(warnings){for(let warning of warnings)console.error(source_default.yellow(`Warning: ${warning}`))}async function createCommandSettingsManager(options){let settingsManager=SettingsManager.create(options.cwd,options.agentDir,{projectTrusted:!1}),projectTrustWarnings=[],trustStore=new ProjectTrustStore(options.agentDir);if(options.useSavedProjectTrustOnly){let savedProjectTrusted=trustStore.get(options.cwd)===!0;return settingsManager.setProjectTrusted(options.projectTrustOverride??savedProjectTrusted),{settingsManager,projectTrustWarnings}}let appMode=getCommandAppMode(),extensionsResult=options.projectTrustOverride===void 0&&hasTrustRequiringProjectResources(options.cwd)?await new DefaultResourceLoader({cwd:options.cwd,agentDir:options.agentDir,settingsManager,extensionFactories:options.extensionFactories}).loadProjectTrustExtensions():void 0;for(let error of extensionsResult?.errors??[])projectTrustWarnings.push(`Failed to load extension "${error.path}": ${error.error}`);let projectTrusted=await resolveProjectTrusted({cwd:options.cwd,trustStore,trustOverride:options.projectTrustOverride,defaultProjectTrust:settingsManager.getDefaultProjectTrust(),extensionsResult,projectTrustContext:createProjectTrustContext({cwd:options.cwd,mode:appMode,settingsManager,hasUI:appMode==="interactive"}),onExtensionError:message=>projectTrustWarnings.push(message)});return settingsManager.setProjectTrusted(projectTrusted),{settingsManager,projectTrustWarnings}}async function handleConfigCommand(args,runtimeOptions={}){let[command,...rest]=args;if(command!=="config")return!1;if(rest.includes("-h")||rest.includes("--help"))return printConfigCommandHelp(),!0;if(rest[0]===CONFIG_IMPORT_PI_ARGV)return runConfigImportPi(rest.slice(1)),!0;let local=!1,projectTrustOverride;for(let arg of rest)if(arg==="-l"||arg==="--local")local=!0;else if(arg==="-a"||arg==="--approve")projectTrustOverride=!0;else if(arg==="-na"||arg==="--no-approve")projectTrustOverride=!1;else return arg.startsWith("-")?(console.error(source_default.red(`Unknown option ${arg} for "config".`)),console.error(source_default.dim(`Use "${APP_NAME} --help" or "${CONFIG_COMMAND_USAGE}".`)),process.exitCode=1,!0):(console.error(source_default.red(`Unexpected argument ${arg}.`)),console.error(source_default.dim(`Usage: ${CONFIG_COMMAND_USAGE}`)),process.exitCode=1,!0);let cwd=process.cwd(),agentDir=getAgentDir(),{settingsManager,projectTrustWarnings}=await createCommandSettingsManager({cwd,agentDir,projectTrustOverride,extensionFactories:runtimeOptions.extensionFactories});if(reportProjectTrustWarnings(projectTrustWarnings),local&&!settingsManager.isProjectTrusted())return console.error(source_default.red("Project is not trusted. Use --approve to modify local resource config.")),process.exitCode=1,!0;reportSettingsErrors(settingsManager,"config command");let builtinExtensions=(runtimeOptions.extensionFactories??[]).filter(isBuiltinExtension).map(input=>input.name),globalSettingsManager=SettingsManager.create(cwd,agentDir,{projectTrusted:!1}),globalResolvedPaths=await new DefaultPackageManager({cwd,agentDir,settingsManager:globalSettingsManager,builtinExtensions}).resolve(),projectResolvedPaths=settingsManager.isProjectTrusted()?await new DefaultPackageManager({cwd,agentDir,settingsManager,builtinExtensions}).resolve():globalResolvedPaths;await selectConfig({resolvedPaths:{global:globalResolvedPaths,project:projectResolvedPaths},settingsManager,cwd,agentDir,writeScope:local?"project":"global",projectModeAvailable:settingsManager.isProjectTrusted()}),process.exit(0)}async function handlePackageCommand(args,runtimeOptions={}){let options=parsePackageCommand(args);if(!options)return!1;if(options.help)return printPackageCommandHelp(options.command),!0;if(options.invalidOption)return console.error(source_default.red(`Unknown option ${options.invalidOption} for "${options.command}".`)),console.error(source_default.dim(`Use "${APP_NAME} --help" or "${getPackageCommandUsage(options.command)}".`)),process.exitCode=1,!0;if(options.missingOptionValue)return console.error(source_default.red(`Missing value for ${options.missingOptionValue}.`)),console.error(source_default.dim(`Usage: ${getPackageCommandUsage(options.command)}`)),process.exitCode=1,!0;if(options.invalidArgument)return console.error(source_default.red(`Unexpected argument ${options.invalidArgument}.`)),console.error(source_default.dim(`Usage: ${getPackageCommandUsage(options.command)}`)),process.exitCode=1,!0;if(options.conflictingOptions)return console.error(source_default.red(options.conflictingOptions)),console.error(source_default.dim(`Usage: ${getPackageCommandUsage(options.command)}`)),process.exitCode=1,!0;let source=options.source;if((options.command==="install"||options.command==="remove")&&!source)return console.error(source_default.red(`Missing ${options.command} source.`)),console.error(source_default.dim(`Usage: ${getPackageCommandUsage(options.command)}`)),process.exitCode=1,!0;if(options.command==="update"&&options.updateTarget?.type==="models"){try{await refreshModelCatalogs(getAgentDir())}catch(error){let message=error instanceof Error?error.message:"Unknown model catalog refresh error";console.error(source_default.red(`Error: ${message}`)),process.exitCode=1}return!0}let cwd=process.cwd(),agentDir=getAgentDir(),writesProjectPackageConfig=(options.command==="install"||options.command==="remove")&&options.local,{settingsManager,projectTrustWarnings}=await createCommandSettingsManager({cwd,agentDir,projectTrustOverride:options.projectTrustOverride,useSavedProjectTrustOnly:options.command==="update",extensionFactories:runtimeOptions.extensionFactories});if(reportProjectTrustWarnings(projectTrustWarnings),!settingsManager.isProjectTrusted()&&writesProjectPackageConfig)return console.error(source_default.red("Project is not trusted. Use --approve to modify local package config.")),process.exitCode=1,!0;reportSettingsErrors(settingsManager,"package command");let selfUpdateNpmCommand=settingsManager.getGlobalSettings().npmCommand,packageManager=new DefaultPackageManager({cwd,agentDir,settingsManager});packageManager.setProgressCallback(event=>{event.type==="start"&&process.stdout.write(source_default.dim(`${event.message}
`))});try{switch(options.command){case"install":return await packageManager.installAndPersist(source,{local:options.local}),console.log(source_default.green(`Installed ${source}`)),!0;case"remove":return await packageManager.removeAndPersist(source,{local:options.local})?(console.log(source_default.green(`Removed ${source}`)),!0):(console.error(source_default.red(`No matching package found for ${source}`)),process.exitCode=1,!0);case"list":{let configuredPackages=packageManager.listConfiguredPackages(),userPackages=configuredPackages.filter(pkg=>pkg.scope==="user"),projectPackages=configuredPackages.filter(pkg=>pkg.scope==="project");if(configuredPackages.length===0)return console.log(source_default.dim("No packages installed.")),!0;let formatPackage=pkg=>{let display=pkg.filtered?`${pkg.source} (filtered)`:pkg.source;console.log(` ${display}`),pkg.installedPath&&console.log(source_default.dim(` ${pkg.installedPath}`))};if(userPackages.length>0){console.log(source_default.bold("User packages:"));for(let pkg of userPackages)formatPackage(pkg)}if(projectPackages.length>0){userPackages.length>0&&console.log(),console.log(source_default.bold("Project packages:"));for(let pkg of projectPackages)formatPackage(pkg)}return!0}case"update":{let target=options.updateTarget??{type:"self"};if(options.omoLocalUpdateWorker)return await runOmoLocalUpdateBeta({env:process.env,agentDir,settings:settingsManager.getGlobalSettings(),force:options.force,mode:"build"}),!0;if(options.showExtensionsSkippedNote&&await runOmoLocalUpdateBeta({env:process.env,agentDir,settings:settingsManager.getGlobalSettings(),force:options.force,mode:"dispatch"}),options.showExtensionsSkippedNote&&console.log(source_default.dim(`Extensions are skipped. Run ${APP_NAME} update --extensions to update extensions.`)),updateTargetIncludesExtensions(target)){let updateSource=target.type==="extensions"?target.source:void 0;await packageManager.update(updateSource),console.log(updateSource?source_default.green(`Updated ${updateSource}`):source_default.green("Updated packages"))}if(updateTargetIncludesSelf(target)){let managedInstallRoot=getActiveManagedInstallRoot();if(managedInstallRoot&&options.force)return console.error(source_default.red(`Managed ${APP_NAME} installations do not support --force; rerun the installer to repair this installation.`)),process.exitCode=1,!0;let selfUpdatePlan=await getSelfUpdatePlan(options.force);if(!selfUpdatePlan.shouldRun)return!0;if(managedInstallRoot){selfUpdatePlan.note&&printSelfUpdateNote(selfUpdatePlan.note);try{console.log(source_default.dim(`Updating managed ${APP_NAME} installation...`)),await runManagedSelfUpdate(managedInstallRoot,selfUpdatePlan.version)}catch(error){let message=error instanceof Error?error.message:"Unknown managed update error";return console.error(source_default.red(`Error: ${message}`)),process.exitCode=1,!0}return console.log(source_default.green(`Updated ${APP_NAME} from ${VERSION} to ${selfUpdatePlan.version}`)),!0}let installMethod=detectInstallMethod();if(process.platform==="win32"&&installMethod!=="npm"&&installMethod!=="pnpm")return console.error(source_default.red(`${APP_NAME} self-update on Windows is only supported for npm and pnpm installs.`)),console.error(source_default.dim(`Detected install method: ${installMethod}. Update ${APP_NAME} manually.`)),process.exitCode=1,!0;let selfUpdateTarget={packageName:selfUpdatePlan.packageName,installSpec:selfUpdatePlan.installSpec},selfUpdateCommand=getSelfUpdateCommand(PACKAGE_NAME,selfUpdateNpmCommand,selfUpdateTarget);if(!selfUpdateCommand)return printSelfUpdateUnavailable(selfUpdateNpmCommand,selfUpdateTarget),process.exitCode=1,!0;selfUpdatePlan.note&&printSelfUpdateNote(selfUpdatePlan.note);try{installMethod==="npm"&&prepareWindowsNpmSelfUpdate(),await runSelfUpdate(selfUpdateCommand)}catch(error){let message=error instanceof Error?error.message:"Unknown package command error";return console.error(source_default.red(`Error: ${message}`)),installMethod==="pnpm"&&printPnpmSelfUpdateMetadataHint(),printSelfUpdateFallback(selfUpdateCommand),process.exitCode=1,!0}console.log(source_default.green(`Updated ${APP_NAME} from ${VERSION} to ${selfUpdatePlan.version}`))}return!0}}}catch(error){let message=error instanceof Error?error.message:"Unknown package command error";return console.error(source_default.red(`Error: ${message}`)),process.exitCode=1,!0}}export{cleanupManagedInstall,handleConfigCommand,handlePackageCommand,selfUpdatePlanAfterLookupFailure};