@vibecontrols/agent 2026.531.12 → 2026.531.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of @vibecontrols/agent might be problematic. Click here for more details.

@@ -0,0 +1,13 @@
1
+ // @bun
2
+ import{getAgentVersion}from"./index-1x89a7r1.js";import{getOsAdapter}from"./index-srbb2214.js";import{getDefaultProfile,getInstances,getVibecontrolsDir,getVibecontrolsProductDir,setDefaultProfile,setInstances,validateAgentName}from"./index-bysm7taq.js";import{__require}from"./index-e9rt4m94.js";import{existsSync,readdirSync,readFileSync,writeFileSync,mkdirSync,openSync,closeSync,unlinkSync}from"fs";import{join}from"path";import{tmpdir}from"os";import{spawn as spawnDaemon}from"child_process";class ServiceManager{registryPath;logsDir;productDir;constructor(){let productDir=getVibecontrolsProductDir();this.productDir=productDir,this.registryPath=join(productDir,"agents.json");let agentDir=getVibecontrolsDir();this.logsDir=join(agentDir,"logs"),mkdirSync(productDir,{recursive:!0}),mkdirSync(agentDir,{recursive:!0}),mkdirSync(this.logsDir,{recursive:!0})}async startDaemon(config){return validateAgentName(config.name),this.withInstanceLock(config.name,async()=>{let existing=await this.findProcessByName(config.name);if(existing&&existing.status==="running"){let runningVersion=existing.version,installedVersion=getAgentVersion();if(runningVersion===installedVersion){console.log(`\u26A0\uFE0F Agent '${config.name}' is already running on port ${existing.port}`);return}console.log(`\uD83D\uDD04 Agent '${config.name}' is running an older build (${runningVersion??"unknown"} \u2192 ${installedVersion}) \u2014 restarting to apply the update`);try{await this.stopInternal(config.name)}catch(err){console.log(`\u26A0\uFE0F Could not cleanly stop the stale daemon (${err instanceof Error?err.message:String(err)}); proceeding to start the new build`)}}let logFile=join(this.logsDir,`${config.name}.log`),logFd=openSync(logFile,"a"),distEntry=join(import.meta.dir,"index.js"),devEntry=join(import.meta.dir,"..","index.ts"),indexPath=existsSync(distEntry)?distEntry:devEntry,child=spawnDaemon(process.execPath,["run",indexPath],{detached:!0,windowsHide:!0,stdio:["ignore",logFd,logFd],env:{...process.env,VIBECONTROLS_PROFILE:config.profile||"default",PORT:config.port.toString(),DB_PATH:config.dbPath,NODE_ENV:"production",AGENT_LOG_FILE:logFile}});child.on("error",()=>{}),closeSync(logFd),await new Promise((resolve)=>setTimeout(resolve,2000));let pid=child.pid;if(!(pid!==void 0&&await this.isProcessRunning(pid))){let tail="";try{tail=readFileSync(logFile,"utf8").split(/\r?\n/).filter((l)=>l.trim()).slice(-25).join(`
3
+ `)}catch{}let where=`See ${logFile}`;throw Error(tail?`Failed to start agent '${config.name}'. ${where}
4
+ --- last log lines ---
5
+ ${tail}`:`Failed to start agent '${config.name}'. ${where}`)}child.unref(),await this.saveProcessInfo(config.name,pid,config),console.log(`\uD83D\uDE80 Agent '${config.name}' started (PID: ${pid}, Port: ${config.port})`)})}async stop(name){return validateAgentName(name),this.withInstanceLock(name,()=>this.stopInternal(name))}async stopInternal(name){let agentProcess=await this.findProcessByName(name);if(!agentProcess||agentProcess.status!=="running"){console.log(`\u26A0\uFE0F Agent '${name}' is not running`);return}try{if(process.kill(agentProcess.pid,"SIGTERM"),await new Promise((resolve)=>setTimeout(resolve,3000)),await this.isProcessRunning(agentProcess.pid))process.kill(agentProcess.pid,"SIGKILL");await this.updateProcessStatus(name,"stopped"),console.log(`\u2705 Agent '${name}' stopped (tunnel + API key preserved)`)}catch(err){throw Error(`Failed to stop agent '${name}': ${err}`,{cause:err})}}async restart(name,config){validateAgentName(name),validateAgentName(config.name);let existing=await this.findProcessByName(name);if(existing&&existing.status==="running")await this.stop(name);await this.startDaemon(config),console.log(`\uD83D\uDD04 Agent '${name}' restarted (tunnel + API key preserved)`)}async kill(name){return validateAgentName(name),this.withInstanceLock(name,async()=>{let agentProcess=await this.findProcessByName(name);if(!agentProcess||agentProcess.status!=="running"){console.log(`\u26A0\uFE0F Agent '${name}' is not running`);return}let flagPath=join(tmpdir(),`.boff-vibecontrols-kill-${agentProcess.pid}`);try{await Bun.write(flagPath,"kill")}catch{}try{process.kill(agentProcess.pid,"SIGTERM"),await new Promise((resolve)=>setTimeout(resolve,5000))}catch{}if(await this.isProcessRunning(agentProcess.pid))await this.killProcessTree(agentProcess.pid);await this.updateProcessStatus(name,"stopped"),console.log(`\uD83D\uDC80 Agent '${name}' killed (tunnel + state torn down)`)})}async getStatus(name){return validateAgentName(name),this.findProcessByName(name)}discoverRuntimeInstances(){let agentsDir=join(this.productDir,"agents");if(!existsSync(agentsDir))return[];let profileDirs;try{profileDirs=readdirSync(agentsDir,{withFileTypes:!0}).filter((entry)=>entry.isDirectory()).map((entry)=>entry.name)}catch{return[]}let discovered=[];for(let profile of profileDirs){let runtimePath=join(agentsDir,profile,"runtime.json");if(!existsSync(runtimePath))continue;try{let rt=JSON.parse(readFileSync(runtimePath,"utf8"));if(typeof rt.pid!=="number"||typeof rt.port!=="number")continue;let name=rt.profile||profile;try{validateAgentName(name)}catch{continue}discovered.push({name,pid:rt.pid,port:rt.port,config:{name,port:rt.port,daemon:!0,dbPath:join(agentsDir,profile,"agent-db"),host:rt.host,profile:name},startTime:rt.startedAt??new Date(0).toISOString(),status:"unknown",version:rt.version})}catch{}}return discovered}async getStatusAll(){let registry=this.loadRegistry(),registryNames=new Set(registry.map((p)=>p.name)),candidates=[...registry];for(let disc of this.discoverRuntimeInstances())if(!registryNames.has(disc.name))candidates.push(disc);let processes=[];for(let candidate of candidates){let isRunning=await this.isManagedProcessRunning(candidate);if(!registryNames.has(candidate.name)&&!isRunning)continue;processes.push({...candidate,status:isRunning?"running":"stopped"})}let adopt=processes.filter((p)=>p.status==="running"&&!registryNames.has(p.name));if(adopt.length>0)try{let fresh=this.loadRegistry(),freshNames=new Set(fresh.map((p)=>p.name)),toAdd=adopt.filter((p)=>!freshNames.has(p.name));if(toAdd.length>0)this.saveRegistry([...fresh,...toAdd.map((p)=>({...p,status:"running"}))])}catch{}return processes}async listInstances(){return this.getStatusAll()}getDefaultProfile(){return getDefaultProfile()}setDefaultProfile(name){setDefaultProfile(validateAgentName(name))}async showLogs(name,options){validateAgentName(name);let logFile=join(this.logsDir,`${name}.log`);if(!existsSync(logFile)){console.log(`No logs found for agent '${name}'`);return}if(options.follow)try{let printTail=async(initial)=>{let contents=await Bun.file(logFile).text(),trail=contents.split(`
6
+ `).slice(-options.tail).join(`
7
+ `);if(process.stdout.write(initial?trail:trail),initial&&!trail.endsWith(`
8
+ `))process.stdout.write(`
9
+ `);return contents.length},cursor=await printTail(!0),stopped=!1,interval=setInterval(async()=>{if(stopped)return;try{let fs=await import("fs"),stat=fs.statSync(logFile);if(stat.size>cursor){let fd=fs.openSync(logFile,"r"),length=stat.size-cursor,buf=Buffer.alloc(length);fs.readSync(fd,buf,0,length,cursor),fs.closeSync(fd),process.stdout.write(buf),cursor=stat.size}else if(stat.size<cursor)cursor=await printTail(!1)}catch{}},500),cleanup=()=>{if(stopped)return;stopped=!0,clearInterval(interval)};process.on("SIGINT",()=>{cleanup(),process.exit(0)}),process.on("SIGTERM",()=>{cleanup(),process.exit(0)}),process.on("SIGHUP",()=>{cleanup(),process.exit(0)}),process.on("exit",cleanup)}catch(err){console.error("Failed to follow logs:",err)}else try{let trail=(await Bun.file(logFile).text()).split(`
10
+ `).slice(-options.tail).join(`
11
+ `);console.log(trail)}catch(err){console.error("Failed to read logs:",err)}}async checkHealth(name){let proc=await this.findProcessByName(name);if(!proc||proc.status!=="running")return{healthy:!1,details:{error:"Process not running"}};try{let response=await fetch(`http://localhost:${proc.port}/health`),data=await response.json();return{healthy:response.ok,details:data}}catch(err){return{healthy:!1,details:{error:"Health check failed",message:err.message}}}}async setConfig(key,value){let configFile=join(getVibecontrolsProductDir(),"config.json"),config={};if(existsSync(configFile))config=JSON.parse(readFileSync(configFile,"utf8"));config[key]=value,writeFileSync(configFile,JSON.stringify(config,null,2))}async getConfig(key){let configFile=join(getVibecontrolsProductDir(),"config.json");if(!existsSync(configFile))return key?void 0:{};let config=JSON.parse(readFileSync(configFile,"utf8"));return key?config[key]:config}loadRegistry(){return getInstances()}saveRegistry(processes){setInstances(processes)}async withInstanceLock(name,fn){let safeName=validateAgentName(name),lockPath=join(this.productDir,`.agent-${safeName}.lock`),fd;try{fd=openSync(lockPath,"wx",384),writeFileSync(fd,`${process.pid}
12
+ `)}catch(err){if(err.code==="EEXIST"){let lockPid=parseInt(readFileSync(lockPath,"utf8"),10);if(!lockPid||!await this.isProcessRunning(lockPid)){try{unlinkSync(lockPath)}catch{}return this.withInstanceLock(name,fn)}throw Error(`Agent '${name}' is already being modified`,{cause:err})}throw err}try{return await fn()}finally{try{closeSync(fd)}catch{}try{unlinkSync(lockPath)}catch{}}}async saveProcessInfo(name,pid,config){let filtered=this.loadRegistry().filter((p)=>p.name!==name);filtered.push({name,pid,port:config.port,config,startTime:new Date().toISOString(),status:"running"}),this.saveRegistry(filtered)}async updateProcessStatus(name,status){let registry=this.loadRegistry(),proc=registry.find((p)=>p.name===name);if(proc)proc.status=status,this.saveRegistry(registry)}async findProcessByName(name){validateAgentName(name);let proc=this.loadRegistry().find((p)=>p.name===name);if(!proc)return null;let isRunning=await this.isManagedProcessRunning(proc);return proc.status=isRunning?"running":"stopped",proc}async isManagedProcessRunning(proc){if(!await this.isProcessRunning(proc.pid))return!1;try{return(await fetch(`http://127.0.0.1:${proc.port}/health/live`,{signal:AbortSignal.timeout(1000)})).ok}catch{return!1}}async isProcessRunning(pid){try{return process.kill(pid,0),!0}catch{return!1}}async killProcessTree(pid){if(process.platform==="win32"){try{getOsAdapter().killProcessTree(pid,"SIGKILL")}catch{}return}let children=this.getChildPids(pid);for(let childPid of children)await this.killProcessTree(childPid);try{process.kill(-pid,"SIGKILL")}catch{try{process.kill(pid,"SIGKILL")}catch{}}}getChildPids(pid){try{return getOsAdapter().listChildPids(pid)}catch{return[]}}}
13
+ export{ServiceManager};
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
- import{createApp,invalidatePairingToken,mintPairingToken}from"./index-dsfy42e8.js";import"./index-926vt87h.js";import{bootstrapWorkspace}from"./index-ns2dd8nx.js";import"./index-8xr7ewxg.js";import"./index-skmkfyzb.js";import"./index-95nmejfd.js";import"./index-34syaqa8.js";import"./index-y5q0m3cx.js";import"./index-1atc02se.js";import"./index-7qj1swrk.js";import"./index-srbb2214.js";import{telemetryService}from"./index-sfjbh6fa.js";import"./index-3jez1q8j.js";import"./index-brtw3j8x.js";import{getAgentApiKey,loadAgentApiKey}from"./index-b4wy3jrt.js";import"./index-d3mz9vws.js";import"./index-rnk0kny8.js";import{applyAgentConfigToEnv,applyAgentSecretsToEnv,getSecret,readAgentConfig,setSecret}from"./index-2pqv0bya.js";import{getDaemonProfile}from"./index-7pdmqbj8.js";import{getProfileDataDir,getVibecontrolsDir,getVibecontrolsProductDir,getVibecontrolsProfile}from"./index-bysm7taq.js";import"./index-zs58d1hc.js";import{__require}from"./index-e9rt4m94.js";import{isAbsolute}from"path";import{existsSync,mkdirSync,readFileSync,readdirSync,renameSync,unlinkSync,writeFileSync}from"fs";import{dirname,join}from"path";var MIGRATION_MARKER=".secrets-migrated-v1",SECRET_KEYS=["static-api-key","clientId","clientSecret"];function composeName(scope,key){return`${scope}:${key}`}function getMarkerPath(){return join(getVibecontrolsProductDir(),MIGRATION_MARKER)}function writeMarker(){let path=getMarkerPath();mkdirSync(dirname(path),{recursive:!0}),writeFileSync(path,`${new Date().toISOString()}
3
+ import{createApp,invalidatePairingToken,mintPairingToken}from"./index-h2n00ae3.js";import"./index-926vt87h.js";import{bootstrapWorkspace}from"./index-ns2dd8nx.js";import"./index-q96eskyn.js";import"./index-skmkfyzb.js";import"./index-95nmejfd.js";import"./index-vfwervz9.js";import"./index-y5q0m3cx.js";import"./index-ttafzcs7.js";import{getAgentVersion}from"./index-1x89a7r1.js";import"./index-srbb2214.js";import{telemetryService}from"./index-sfjbh6fa.js";import"./index-3jez1q8j.js";import"./index-brtw3j8x.js";import{getAgentApiKey,loadAgentApiKey}from"./index-b4wy3jrt.js";import"./index-d3mz9vws.js";import"./index-rnk0kny8.js";import{applyAgentConfigToEnv,applyAgentSecretsToEnv,getSecret,readAgentConfig,setSecret}from"./index-2pqv0bya.js";import{getDaemonProfile}from"./index-7pdmqbj8.js";import{getProfileDataDir,getVibecontrolsDir,getVibecontrolsProductDir,getVibecontrolsProfile}from"./index-bysm7taq.js";import"./index-zs58d1hc.js";import{__require}from"./index-e9rt4m94.js";import{isAbsolute}from"path";import{existsSync,mkdirSync,readFileSync,readdirSync,renameSync,unlinkSync,writeFileSync}from"fs";import{dirname,join}from"path";var MIGRATION_MARKER=".secrets-migrated-v1",SECRET_KEYS=["static-api-key","clientId","clientSecret"];function composeName(scope,key){return`${scope}:${key}`}function getMarkerPath(){return join(getVibecontrolsProductDir(),MIGRATION_MARKER)}function writeMarker(){let path=getMarkerPath();mkdirSync(dirname(path),{recursive:!0}),writeFileSync(path,`${new Date().toISOString()}
4
4
  `,{mode:384})}function parseJsonFile(path){if(!existsSync(path))return null;try{let raw=readFileSync(path,"utf8"),parsed=JSON.parse(raw);if(parsed&&typeof parsed==="object"&&!Array.isArray(parsed))return parsed}catch{}return null}function atomicWriteJson(path,data){mkdirSync(dirname(path),{recursive:!0});let tmp=`${path}.${process.pid}.tmp`;writeFileSync(tmp,`${JSON.stringify(data,null,2)}
5
- `,{mode:384}),renameSync(tmp,path)}function listAgentConfigs(){let productDir=getVibecontrolsProductDir(),agentsDir=join(productDir,"agents");if(!existsSync(agentsDir))return[];let entries=[],names;try{names=readdirSync(agentsDir)}catch{return[]}for(let name of names){let cfgPath=join(agentsDir,name,"config.json");if(!existsSync(cfgPath))continue;entries.push({path:cfgPath,scope:name})}return entries}function listProfileFiles(){let productDir=getVibecontrolsProductDir(),profilesDir=join(productDir,"profiles");if(!existsSync(profilesDir))return[];let entries=[],names;try{names=readdirSync(profilesDir)}catch{return[]}for(let name of names){if(!name.endsWith(".json"))continue;entries.push({path:join(profilesDir,name),scope:name.slice(0,-5)})}return entries}async function migrateOneJson(path,scope){let data=parseJsonFile(path);if(!data)return 0;let moved=0;for(let key of SECRET_KEYS){let v=data[key];if(typeof v!=="string"||v.length===0)continue;let composed=composeName(scope,key);try{await setSecret(composed,v),delete data[key],moved++,getDaemonProfile().logger.info("secrets-migrator","migrated field",{path,scope,key})}catch(err){getDaemonProfile().logger.warn("secrets-migrator","failed to migrate field",{path,scope,key,error:String(err)})}}if(moved>0)atomicWriteJson(path,data);return moved}async function runSecretsMigrationOnce(){let result={alreadyMigrated:!1,fieldsMoved:0,filesUpdated:0};if(existsSync(getMarkerPath()))return result.alreadyMigrated=!0,result;let targets=[...listAgentConfigs(),...listProfileFiles()];for(let t of targets){let moved;try{moved=await migrateOneJson(t.path,t.scope)}catch(err){getDaemonProfile().logger.warn("secrets-migrator","skipping target after error",{path:t.path,error:String(err)});continue}if(moved>0)result.fieldsMoved+=moved,result.filesUpdated++}try{writeMarker()}catch(err){getDaemonProfile().logger.warn("secrets-migrator","failed to drop migration marker",{error:String(err)})}if(result.fieldsMoved>0)getDaemonProfile().logger.info("secrets-migrator","migration complete",{fieldsMoved:result.fieldsMoved,filesUpdated:result.filesUpdated});return result}{let originalJsonParse=JSON.parse.bind(JSON);JSON.parse=(text,reviver)=>{try{return originalJsonParse(text,reviver)}catch(err){if(typeof text==="string"&&text.endsWith("}}"))try{return originalJsonParse(text.slice(0,-1),reviver)}catch{}throw err}};let RequestProto=globalThis.Request?.prototype;if(RequestProto&&typeof RequestProto.json==="function"){let originalJson=RequestProto.json;RequestProto.json=async function(){let text=await this.text();if(!text)return;try{return originalJsonParse(text)}catch{if(text.endsWith("}}"))try{return originalJsonParse(text.slice(0,-1))}catch{}let fresh=new Request("http://shim/",{method:"POST",body:text});return originalJson.call(fresh)}}}}bootstrapWorkspace();applyAgentConfigToEnv();if(!process.env.VIBECONTROLS_DATA_DIR)process.env.VIBECONTROLS_DATA_DIR=getVibecontrolsDir();if(typeof Bun>"u")console.error("ERROR: VibeControls Agent requires Bun runtime."),console.error("Install Bun: https://bun.sh"),process.exit(1);function defaultPortForProfile(profile){if(profile==="default")return 3005;let h=2166136261;for(let i=0;i<profile.length;i++)h=Math.imul(h^profile.charCodeAt(i),16777619);return 3100+Math.abs(h)%300}var _resolvedProfile=(()=>{try{return getVibecontrolsProfile()}catch{return"default"}})(),parsedPort=Number.parseInt(process.env.PORT||String(defaultPortForProfile(_resolvedProfile)),10),port=Number.isInteger(parsedPort)&&parsedPort>0?parsedPort:3005,host=process.env.HOST||"0.0.0.0",dbPath=(()=>{let fromEnv=process.env.DB_PATH;if(!fromEnv)return;if(isAbsolute(fromEnv))return fromEnv;console.warn(`[boot] Ignoring relative DB_PATH=${fromEnv} (cwd=${process.cwd()}). Use an absolute path or unset to fall back to ${getProfileDataDir()}.`);return})(),apiKey=process.env.AGENT_API_KEY||void 0,logLevel=process.env.LOG_LEVEL||"info",corsOrigin=process.env.CORS_ORIGIN||void 0;async function main(){try{await runSecretsMigrationOnce()}catch(err){getDaemonProfile().logger.warn("server","secrets migration encountered an error",{error:String(err)})}let legacyJsonKey=readAgentConfig()["static-api-key"],profile=(()=>{try{return getVibecontrolsProfile()}catch{return"default"}})(),preExistingApiKey=legacyJsonKey??await getSecret(`${profile}:static-api-key`),isFirstBoot=!apiKey&&!preExistingApiKey;await loadAgentApiKey(),await applyAgentSecretsToEnv();let vibeClientId=process.env.VIBE_CLIENT_ID,vibeClientSecret=process.env.VIBE_CLIENT_SECRET,vibeGlobalGatewayUrl=process.env.VIBE_GLOBAL_GATEWAY_URL,vibeWorkspaceGatewayUrl=process.env.VIBE_WORKSPACE_GATEWAY_URL,vibeWorkspaceId=process.env.VIBE_WORKSPACE_ID,hasInlineCreds=!!vibeClientId&&!!vibeClientSecret&&!!vibeGlobalGatewayUrl&&!!vibeWorkspaceGatewayUrl&&!!vibeWorkspaceId;getDaemonProfile().logger.info("server","Starting VibeControls Agent...",{runtime:"bun",bunVersion:Bun.version,port,host,env:"production"});try{let cfgRaw=readAgentConfig(),persisted=cfgRaw["telemetry.enabled"]===!0||cfgRaw["telemetry.enabled"]==="true";telemetryService.init({persisted});let startedAt=Date.now();telemetryService.emit("agent.started",{version:process.env.npm_package_version??"unknown",profile:_resolvedProfile,platform:process.platform}),process.__vibe_started_at=startedAt}catch{}let maxBootAttempts=Math.max(1,Number.parseInt(process.env.VIBECONTROLS_AGENT_BOOT_RETRIES??"10",10)||10),isFatalBootError=(err)=>{let msg=String(err?.message??err).toLowerCase();return msg.includes("syntax")||msg.includes("cannot find module")||msg.includes("module not found")||msg.includes("typeerror")||msg.includes("config schema")||msg.includes("invalid config")||msg.includes("corrupt")||msg.includes("eaccess")||msg.includes("eperm")},bootstrap=null,attempt=0;while(!bootstrap){attempt++;try{bootstrap=await createApp({port,host,dbPath,apiKey,logLevel,corsOrigin}),await bootstrap.start();try{let fs=await import("fs"),runtimePath=`${getVibecontrolsDir()}/runtime.json`;fs.writeFileSync(runtimePath,JSON.stringify({pid:process.pid,port,host,profile:_resolvedProfile,startedAt:new Date().toISOString()},null,2));let cleanup=()=>{try{if(fs.existsSync(runtimePath))fs.unlinkSync(runtimePath)}catch{}};process.once("SIGTERM",cleanup),process.once("SIGINT",cleanup),process.once("exit",cleanup)}catch(err){getDaemonProfile().logger.warn("server","Could not write runtime.json",{error:String(err)})}}catch(err){let fatal=isFatalBootError(err);if(getDaemonProfile().logger.error("server","Failed to start agent server",{attempt,maxBootAttempts,fatal,error:String(err)}),fatal||attempt>=maxBootAttempts)console.error(`\u274C Failed to start VibeControls Agent (attempt ${attempt}/${maxBootAttempts}, fatal=${fatal}):`,err),process.exit(1);let delayMs=Math.min(30000,1000*2**Math.min(5,attempt-1)),jitter=Math.floor(Math.random()*500),wait=delayMs+jitter;console.warn(`\u26A0\uFE0F Agent boot attempt ${attempt}/${maxBootAttempts} failed (transient), retrying in ${Math.round(wait/1000)}s...`),await new Promise((r)=>setTimeout(r,wait)),bootstrap=null}}let tunnelProvider=bootstrap.getServiceRegistry().getProvider("tunnel"),tunnelUrl=null;if(tunnelProvider?.getActiveTunnelUrl)for(let i=0;i<30;i++){if(tunnelUrl=await tunnelProvider.getActiveTunnelUrl(),tunnelUrl)break;await new Promise((r)=>setTimeout(r,1000))}if(!tunnelUrl){let{sanitizeEnvSuffix}=await import("./tunnel-bootstrap-x82wcnt8.js"),{getVibecontrolsProfile:getVibecontrolsProfile2}=await import("./path-utils-y2ba2951.js"),profileSuffix=sanitizeEnvSuffix(getVibecontrolsProfile2());tunnelUrl=process.env[`AGENT_TUNNEL_URL_${profileSuffix}`]??process.env.AGENT_TUNNEL_URL??null}let cfg=readAgentConfig(),resolvedApiKey=apiKey||getAgentApiKey()||cfg["static-api-key"]||"",bootState=getDaemonProfile().getBootState(),pairingToken=bootState==="ready"?null:mintPairingToken();if(bootState==="ready")invalidatePairingToken();printBanner({port,host,tunnelUrl,apiKey:resolvedApiKey,revealApiKey:isFirstBoot||process.env.AGENT_PRINT_API_KEY==="1",state:bootState,pairingToken});let{existsSync:existsSync2,unlinkSync:unlinkSync2}=await import("fs"),{tmpdir}=await import("os"),{join:joinPath}=await import("path"),shutdown=async(signal)=>{getDaemonProfile().logger.info("server",`Received ${signal}, shutting down...`);try{let startedAt=process.__vibe_started_at??Date.now();telemetryService.emit("agent.stopped",{uptime_s:Math.round((Date.now()-startedAt)/1000),reason:signal}),await telemetryService.flush(),telemetryService.stop()}catch{}let lifecycle=bootstrap.getLifecycle();if(signal==="SIGTERM"){let flagPath=joinPath(tmpdir(),`.boff-vibecontrols-kill-${process.pid}`);if(existsSync2(flagPath)){try{unlinkSync2(flagPath)}catch{}if(getDaemonProfile().logger.info("server","Kill-intent flag detected \u2014 full shutdown"),lifecycle)await lifecycle.kill();else await bootstrap.stop({reason:"shutdown"}),process.exit(0)}else if(getDaemonProfile().logger.info("server","No kill flag \u2014 treating as hot-reload (soft stop)"),lifecycle)await lifecycle.softStop();else await bootstrap.stop({reason:"reload"})}else if(lifecycle)await lifecycle.kill();else await bootstrap.stop({reason:"shutdown"}),process.exit(0)};if(process.on("SIGINT",()=>shutdown("SIGINT")),process.on("SIGTERM",()=>shutdown("SIGTERM")),hasInlineCreds){let timeoutMs=(()=>{let raw=process.env.VIBECONTROLS_FINALIZE_TIMEOUT_MS,n=raw?Number.parseInt(raw,10):NaN;return Number.isFinite(n)&&n>0?n:300000})();getDaemonProfile().logger.info("server",`VIBE_* env vars detected \u2014 running inline finalize (timeout ${Math.round(timeoutMs/1000)}s)`),(async()=>{let inlineCreds={clientId:vibeClientId,clientSecret:vibeClientSecret,workspaceId:vibeWorkspaceId,globalGatewayUrl:vibeGlobalGatewayUrl,workspaceGatewayUrl:vibeWorkspaceGatewayUrl};try{let result=await Promise.race([bootstrap.finalize(inlineCreds),new Promise((resolve)=>setTimeout(()=>resolve({ok:!1,error:`inline finalize timed out after ${Math.round(timeoutMs/1000)}s`}),timeoutMs))]);if(!result.ok){getDaemonProfile().logger.warn("server","Inline finalize failed \u2014 agent stays awaiting-config. Background retry worker will keep trying.",{error:result.error});let{startFinalizeRetryWorker}=await import("./finalize-retry-worker-3q4xc65x.js"),{setFinalizeRetryHandle}=await import("./finalize-retry-handle-registry-vbq5qhj1.js"),handle=startFinalizeRetryWorker({trigger:()=>bootstrap.finalize(inlineCreds)});setFinalizeRetryHandle(handle)}}catch(err){getDaemonProfile().logger.error("server","Inline finalize threw",{error:String(err)})}})()}else getDaemonProfile().logger.info("server","Agent is awaiting gateway credentials. Add it on the VibeControls platform using the tunnel URL and API key shown above.")}function printBanner(opts){let pad=(s)=>("\u2551 "+s).padEnd(65)+"\u2551",line="\u2560"+"\u2550".repeat(64)+"\u2563",top="\u2554"+"\u2550".repeat(64)+"\u2557",bot="\u255A"+"\u2550".repeat(64)+"\u255D",displayKey=opts.revealApiKey?opts.apiKey:opts.apiKey?`${opts.apiKey.substring(0,8)}****${opts.apiKey.substring(opts.apiKey.length-4)}`:"(none)";if(console.log(""),console.log(top),console.log(pad("VibeControls Agent")),console.log(line),console.log(pad(`State: ${opts.state}`)),console.log(pad(`Agent URL: http://${opts.host}:${opts.port}`)),console.log(pad(`API Key: ${displayKey}`)),console.log(pad(`Tunnel URL: ${opts.tunnelUrl??"(none)"}`)),opts.pairingToken)console.log(pad(`Pairing: ${opts.pairingToken}`)),console.log(pad(" (send as x-pairing-token on bootstrap)"));if(console.log(line),console.log(pad(`Health: http://localhost:${opts.port}/health`)),console.log(pad(`Status: http://localhost:${opts.port}/api/agent/status`)),console.log(bot),!opts.revealApiKey)console.log(" (Set AGENT_PRINT_API_KEY=1 to print the API key in full.)");console.log("")}main();
5
+ `,{mode:384}),renameSync(tmp,path)}function listAgentConfigs(){let productDir=getVibecontrolsProductDir(),agentsDir=join(productDir,"agents");if(!existsSync(agentsDir))return[];let entries=[],names;try{names=readdirSync(agentsDir)}catch{return[]}for(let name of names){let cfgPath=join(agentsDir,name,"config.json");if(!existsSync(cfgPath))continue;entries.push({path:cfgPath,scope:name})}return entries}function listProfileFiles(){let productDir=getVibecontrolsProductDir(),profilesDir=join(productDir,"profiles");if(!existsSync(profilesDir))return[];let entries=[],names;try{names=readdirSync(profilesDir)}catch{return[]}for(let name of names){if(!name.endsWith(".json"))continue;entries.push({path:join(profilesDir,name),scope:name.slice(0,-5)})}return entries}async function migrateOneJson(path,scope){let data=parseJsonFile(path);if(!data)return 0;let moved=0;for(let key of SECRET_KEYS){let v=data[key];if(typeof v!=="string"||v.length===0)continue;let composed=composeName(scope,key);try{await setSecret(composed,v),delete data[key],moved++,getDaemonProfile().logger.info("secrets-migrator","migrated field",{path,scope,key})}catch(err){getDaemonProfile().logger.warn("secrets-migrator","failed to migrate field",{path,scope,key,error:String(err)})}}if(moved>0)atomicWriteJson(path,data);return moved}async function runSecretsMigrationOnce(){let result={alreadyMigrated:!1,fieldsMoved:0,filesUpdated:0};if(existsSync(getMarkerPath()))return result.alreadyMigrated=!0,result;let targets=[...listAgentConfigs(),...listProfileFiles()];for(let t of targets){let moved;try{moved=await migrateOneJson(t.path,t.scope)}catch(err){getDaemonProfile().logger.warn("secrets-migrator","skipping target after error",{path:t.path,error:String(err)});continue}if(moved>0)result.fieldsMoved+=moved,result.filesUpdated++}try{writeMarker()}catch(err){getDaemonProfile().logger.warn("secrets-migrator","failed to drop migration marker",{error:String(err)})}if(result.fieldsMoved>0)getDaemonProfile().logger.info("secrets-migrator","migration complete",{fieldsMoved:result.fieldsMoved,filesUpdated:result.filesUpdated});return result}{let originalJsonParse=JSON.parse.bind(JSON);JSON.parse=(text,reviver)=>{try{return originalJsonParse(text,reviver)}catch(err){if(typeof text==="string"&&text.endsWith("}}"))try{return originalJsonParse(text.slice(0,-1),reviver)}catch{}throw err}};let RequestProto=globalThis.Request?.prototype;if(RequestProto&&typeof RequestProto.json==="function"){let originalJson=RequestProto.json;RequestProto.json=async function(){let text=await this.text();if(!text)return;try{return originalJsonParse(text)}catch{if(text.endsWith("}}"))try{return originalJsonParse(text.slice(0,-1))}catch{}let fresh=new Request("http://shim/",{method:"POST",body:text});return originalJson.call(fresh)}}}}bootstrapWorkspace();applyAgentConfigToEnv();if(!process.env.VIBECONTROLS_DATA_DIR)process.env.VIBECONTROLS_DATA_DIR=getVibecontrolsDir();if(typeof Bun>"u")console.error("ERROR: VibeControls Agent requires Bun runtime."),console.error("Install Bun: https://bun.sh"),process.exit(1);function defaultPortForProfile(profile){if(profile==="default")return 3005;let h=2166136261;for(let i=0;i<profile.length;i++)h=Math.imul(h^profile.charCodeAt(i),16777619);return 3100+Math.abs(h)%300}var _resolvedProfile=(()=>{try{return getVibecontrolsProfile()}catch{return"default"}})(),parsedPort=Number.parseInt(process.env.PORT||String(defaultPortForProfile(_resolvedProfile)),10),port=Number.isInteger(parsedPort)&&parsedPort>0?parsedPort:3005,host=process.env.HOST||"0.0.0.0",dbPath=(()=>{let fromEnv=process.env.DB_PATH;if(!fromEnv)return;if(isAbsolute(fromEnv))return fromEnv;console.warn(`[boot] Ignoring relative DB_PATH=${fromEnv} (cwd=${process.cwd()}). Use an absolute path or unset to fall back to ${getProfileDataDir()}.`);return})(),apiKey=process.env.AGENT_API_KEY||void 0,logLevel=process.env.LOG_LEVEL||"info",corsOrigin=process.env.CORS_ORIGIN||void 0;async function main(){try{await runSecretsMigrationOnce()}catch(err){getDaemonProfile().logger.warn("server","secrets migration encountered an error",{error:String(err)})}let legacyJsonKey=readAgentConfig()["static-api-key"],profile=(()=>{try{return getVibecontrolsProfile()}catch{return"default"}})(),preExistingApiKey=legacyJsonKey??await getSecret(`${profile}:static-api-key`),isFirstBoot=!apiKey&&!preExistingApiKey;await loadAgentApiKey(),await applyAgentSecretsToEnv();let vibeClientId=process.env.VIBE_CLIENT_ID,vibeClientSecret=process.env.VIBE_CLIENT_SECRET,vibeGlobalGatewayUrl=process.env.VIBE_GLOBAL_GATEWAY_URL,vibeWorkspaceGatewayUrl=process.env.VIBE_WORKSPACE_GATEWAY_URL,vibeWorkspaceId=process.env.VIBE_WORKSPACE_ID,hasInlineCreds=!!vibeClientId&&!!vibeClientSecret&&!!vibeGlobalGatewayUrl&&!!vibeWorkspaceGatewayUrl&&!!vibeWorkspaceId;getDaemonProfile().logger.info("server","Starting VibeControls Agent...",{runtime:"bun",bunVersion:Bun.version,port,host,env:"production"});try{let cfgRaw=readAgentConfig(),persisted=cfgRaw["telemetry.enabled"]===!0||cfgRaw["telemetry.enabled"]==="true";telemetryService.init({persisted});let startedAt=Date.now();telemetryService.emit("agent.started",{version:process.env.npm_package_version??"unknown",profile:_resolvedProfile,platform:process.platform}),process.__vibe_started_at=startedAt}catch{}let maxBootAttempts=Math.max(1,Number.parseInt(process.env.VIBECONTROLS_AGENT_BOOT_RETRIES??"10",10)||10),isFatalBootError=(err)=>{let msg=String(err?.message??err).toLowerCase();return msg.includes("syntax")||msg.includes("cannot find module")||msg.includes("module not found")||msg.includes("typeerror")||msg.includes("config schema")||msg.includes("invalid config")||msg.includes("corrupt")||msg.includes("eaccess")||msg.includes("eperm")},bootstrap=null,attempt=0;while(!bootstrap){attempt++;try{bootstrap=await createApp({port,host,dbPath,apiKey,logLevel,corsOrigin}),await bootstrap.start();try{let fs=await import("fs"),runtimePath=`${getVibecontrolsDir()}/runtime.json`;fs.writeFileSync(runtimePath,JSON.stringify({pid:process.pid,port,host,profile:_resolvedProfile,startedAt:new Date().toISOString(),version:getAgentVersion()},null,2));let cleanup=()=>{try{if(fs.existsSync(runtimePath))fs.unlinkSync(runtimePath)}catch{}};process.once("SIGTERM",cleanup),process.once("SIGINT",cleanup),process.once("exit",cleanup)}catch(err){getDaemonProfile().logger.warn("server","Could not write runtime.json",{error:String(err)})}}catch(err){let fatal=isFatalBootError(err);if(getDaemonProfile().logger.error("server","Failed to start agent server",{attempt,maxBootAttempts,fatal,error:String(err)}),fatal||attempt>=maxBootAttempts)console.error(`\u274C Failed to start VibeControls Agent (attempt ${attempt}/${maxBootAttempts}, fatal=${fatal}):`,err),process.exit(1);let delayMs=Math.min(30000,1000*2**Math.min(5,attempt-1)),jitter=Math.floor(Math.random()*500),wait=delayMs+jitter;console.warn(`\u26A0\uFE0F Agent boot attempt ${attempt}/${maxBootAttempts} failed (transient), retrying in ${Math.round(wait/1000)}s...`),await new Promise((r)=>setTimeout(r,wait)),bootstrap=null}}let tunnelProvider=bootstrap.getServiceRegistry().getProvider("tunnel"),tunnelUrl=null;if(tunnelProvider?.getActiveTunnelUrl)for(let i=0;i<30;i++){if(tunnelUrl=await tunnelProvider.getActiveTunnelUrl(),tunnelUrl)break;await new Promise((r)=>setTimeout(r,1000))}if(!tunnelUrl){let{sanitizeEnvSuffix}=await import("./tunnel-bootstrap-x82wcnt8.js"),{getVibecontrolsProfile:getVibecontrolsProfile2}=await import("./path-utils-y2ba2951.js"),profileSuffix=sanitizeEnvSuffix(getVibecontrolsProfile2());tunnelUrl=process.env[`AGENT_TUNNEL_URL_${profileSuffix}`]??process.env.AGENT_TUNNEL_URL??null}let cfg=readAgentConfig(),resolvedApiKey=apiKey||getAgentApiKey()||cfg["static-api-key"]||"",bootState=getDaemonProfile().getBootState(),pairingToken=bootState==="ready"?null:mintPairingToken();if(bootState==="ready")invalidatePairingToken();printBanner({port,host,tunnelUrl,apiKey:resolvedApiKey,revealApiKey:isFirstBoot||process.env.AGENT_PRINT_API_KEY==="1",state:bootState,pairingToken});let{existsSync:existsSync2,unlinkSync:unlinkSync2}=await import("fs"),{tmpdir}=await import("os"),{join:joinPath}=await import("path"),shutdown=async(signal)=>{getDaemonProfile().logger.info("server",`Received ${signal}, shutting down...`);try{let startedAt=process.__vibe_started_at??Date.now();telemetryService.emit("agent.stopped",{uptime_s:Math.round((Date.now()-startedAt)/1000),reason:signal}),await telemetryService.flush(),telemetryService.stop()}catch{}let lifecycle=bootstrap.getLifecycle();if(signal==="SIGTERM"){let flagPath=joinPath(tmpdir(),`.boff-vibecontrols-kill-${process.pid}`);if(existsSync2(flagPath)){try{unlinkSync2(flagPath)}catch{}if(getDaemonProfile().logger.info("server","Kill-intent flag detected \u2014 full shutdown"),lifecycle)await lifecycle.kill();else await bootstrap.stop({reason:"shutdown"}),process.exit(0)}else if(getDaemonProfile().logger.info("server","No kill flag \u2014 treating as hot-reload (soft stop)"),lifecycle)await lifecycle.softStop();else await bootstrap.stop({reason:"reload"})}else if(lifecycle)await lifecycle.kill();else await bootstrap.stop({reason:"shutdown"}),process.exit(0)};if(process.on("SIGINT",()=>shutdown("SIGINT")),process.on("SIGTERM",()=>shutdown("SIGTERM")),hasInlineCreds){let timeoutMs=(()=>{let raw=process.env.VIBECONTROLS_FINALIZE_TIMEOUT_MS,n=raw?Number.parseInt(raw,10):NaN;return Number.isFinite(n)&&n>0?n:300000})();getDaemonProfile().logger.info("server",`VIBE_* env vars detected \u2014 running inline finalize (timeout ${Math.round(timeoutMs/1000)}s)`),(async()=>{let inlineCreds={clientId:vibeClientId,clientSecret:vibeClientSecret,workspaceId:vibeWorkspaceId,globalGatewayUrl:vibeGlobalGatewayUrl,workspaceGatewayUrl:vibeWorkspaceGatewayUrl};try{let result=await Promise.race([bootstrap.finalize(inlineCreds),new Promise((resolve)=>setTimeout(()=>resolve({ok:!1,error:`inline finalize timed out after ${Math.round(timeoutMs/1000)}s`}),timeoutMs))]);if(!result.ok){getDaemonProfile().logger.warn("server","Inline finalize failed \u2014 agent stays awaiting-config. Background retry worker will keep trying.",{error:result.error});let{startFinalizeRetryWorker}=await import("./finalize-retry-worker-3q4xc65x.js"),{setFinalizeRetryHandle}=await import("./finalize-retry-handle-registry-vbq5qhj1.js"),handle=startFinalizeRetryWorker({trigger:()=>bootstrap.finalize(inlineCreds)});setFinalizeRetryHandle(handle)}}catch(err){getDaemonProfile().logger.error("server","Inline finalize threw",{error:String(err)})}})()}else getDaemonProfile().logger.info("server","Agent is awaiting gateway credentials. Add it on the VibeControls platform using the tunnel URL and API key shown above.")}function printBanner(opts){let pad=(s)=>("\u2551 "+s).padEnd(65)+"\u2551",line="\u2560"+"\u2550".repeat(64)+"\u2563",top="\u2554"+"\u2550".repeat(64)+"\u2557",bot="\u255A"+"\u2550".repeat(64)+"\u255D",displayKey=opts.revealApiKey?opts.apiKey:opts.apiKey?`${opts.apiKey.substring(0,8)}****${opts.apiKey.substring(opts.apiKey.length-4)}`:"(none)";if(console.log(""),console.log(top),console.log(pad("VibeControls Agent")),console.log(line),console.log(pad(`State: ${opts.state}`)),console.log(pad(`Agent URL: http://${opts.host}:${opts.port}`)),console.log(pad(`API Key: ${displayKey}`)),console.log(pad(`Tunnel URL: ${opts.tunnelUrl??"(none)"}`)),opts.pairingToken)console.log(pad(`Pairing: ${opts.pairingToken}`)),console.log(pad(" (send as x-pairing-token on bootstrap)"));if(console.log(line),console.log(pad(`Health: http://localhost:${opts.port}/health`)),console.log(pad(`Status: http://localhost:${opts.port}/api/agent/status`)),console.log(bot),!opts.revealApiKey)console.log(" (Set AGENT_PRINT_API_KEY=1 to print the API key in full.)");console.log("")}main();
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{CORE_PLUGIN_NAMES,DEFAULT_PLUGINS,PluginManager,TRUSTED_PACKAGES,getPluginPackageRoot,validatePluginPackageName}from"./index-7qj1swrk.js";import"./index-7pdmqbj8.js";import"./index-bysm7taq.js";import"./index-zs58d1hc.js";import"./index-e9rt4m94.js";export{validatePluginPackageName,getPluginPackageRoot,TRUSTED_PACKAGES,PluginManager,DEFAULT_PLUGINS,CORE_PLUGIN_NAMES};
2
+ import{CORE_PLUGIN_NAMES,DEFAULT_PLUGINS,PluginManager,TRUSTED_PACKAGES,getPluginPackageRoot,validatePluginPackageName}from"./index-1x89a7r1.js";import"./index-7pdmqbj8.js";import"./index-bysm7taq.js";import"./index-zs58d1hc.js";import"./index-e9rt4m94.js";export{validatePluginPackageName,getPluginPackageRoot,TRUSTED_PACKAGES,PluginManager,DEFAULT_PLUGINS,CORE_PLUGIN_NAMES};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{attachSecondaryProfile}from"./index-8xr7ewxg.js";import"./index-1atc02se.js";import"./index-7qj1swrk.js";import"./index-srbb2214.js";import"./index-brtw3j8x.js";import"./index-b4wy3jrt.js";import"./index-d3mz9vws.js";import"./index-rnk0kny8.js";import"./index-2pqv0bya.js";import"./index-7pdmqbj8.js";import"./index-bysm7taq.js";import"./index-zs58d1hc.js";import"./index-e9rt4m94.js";export{attachSecondaryProfile};
2
+ import{attachSecondaryProfile}from"./index-q96eskyn.js";import"./index-ttafzcs7.js";import"./index-1x89a7r1.js";import"./index-srbb2214.js";import"./index-brtw3j8x.js";import"./index-b4wy3jrt.js";import"./index-d3mz9vws.js";import"./index-rnk0kny8.js";import"./index-2pqv0bya.js";import"./index-7pdmqbj8.js";import"./index-bysm7taq.js";import"./index-zs58d1hc.js";import"./index-e9rt4m94.js";export{attachSecondaryProfile};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vibecontrols/agent",
3
- "version": "2026.531.12",
3
+ "version": "2026.531.13",
4
4
  "main": "./dist/index.js",
5
5
  "type": "module",
6
6
  "bin": {
@@ -1,2 +0,0 @@
1
- // @bun
2
- import{createApp}from"./index-dsfy42e8.js";import"./index-926vt87h.js";import"./index-8xr7ewxg.js";import"./index-skmkfyzb.js";import"./index-95nmejfd.js";import"./index-34syaqa8.js";import"./index-y5q0m3cx.js";import"./index-1atc02se.js";import"./index-7qj1swrk.js";import"./index-srbb2214.js";import"./index-sfjbh6fa.js";import"./index-3jez1q8j.js";import"./index-brtw3j8x.js";import"./index-b4wy3jrt.js";import"./index-d3mz9vws.js";import"./index-rnk0kny8.js";import"./index-2pqv0bya.js";import"./index-7pdmqbj8.js";import"./index-bysm7taq.js";import"./index-zs58d1hc.js";import"./index-e9rt4m94.js";export{createApp};
@@ -1,13 +0,0 @@
1
- // @bun
2
- import{getOsAdapter}from"./index-srbb2214.js";import{getDefaultProfile,getInstances,getVibecontrolsDir,getVibecontrolsProductDir,setDefaultProfile,setInstances,validateAgentName}from"./index-bysm7taq.js";import{__require}from"./index-e9rt4m94.js";import{existsSync,readdirSync,readFileSync,writeFileSync,mkdirSync,openSync,closeSync,unlinkSync}from"fs";import{join}from"path";import{tmpdir}from"os";import{spawn as spawnDaemon}from"child_process";class ServiceManager{registryPath;logsDir;productDir;constructor(){let productDir=getVibecontrolsProductDir();this.productDir=productDir,this.registryPath=join(productDir,"agents.json");let agentDir=getVibecontrolsDir();this.logsDir=join(agentDir,"logs"),mkdirSync(productDir,{recursive:!0}),mkdirSync(agentDir,{recursive:!0}),mkdirSync(this.logsDir,{recursive:!0})}async startDaemon(config){return validateAgentName(config.name),this.withInstanceLock(config.name,async()=>{let existing=await this.findProcessByName(config.name);if(existing&&existing.status==="running"){console.log(`\u26A0\uFE0F Agent '${config.name}' is already running on port ${existing.port}`);return}let logFile=join(this.logsDir,`${config.name}.log`),logFd=openSync(logFile,"a"),distEntry=join(import.meta.dir,"index.js"),devEntry=join(import.meta.dir,"..","index.ts"),indexPath=existsSync(distEntry)?distEntry:devEntry,child=spawnDaemon(process.execPath,["run",indexPath],{detached:!0,windowsHide:!0,stdio:["ignore",logFd,logFd],env:{...process.env,VIBECONTROLS_PROFILE:config.profile||"default",PORT:config.port.toString(),DB_PATH:config.dbPath,NODE_ENV:"production",AGENT_LOG_FILE:logFile}});child.on("error",()=>{}),closeSync(logFd),await new Promise((resolve)=>setTimeout(resolve,2000));let pid=child.pid;if(!(pid!==void 0&&await this.isProcessRunning(pid))){let tail="";try{tail=readFileSync(logFile,"utf8").split(/\r?\n/).filter((l)=>l.trim()).slice(-25).join(`
3
- `)}catch{}let where=`See ${logFile}`;throw Error(tail?`Failed to start agent '${config.name}'. ${where}
4
- --- last log lines ---
5
- ${tail}`:`Failed to start agent '${config.name}'. ${where}`)}child.unref(),await this.saveProcessInfo(config.name,pid,config),console.log(`\uD83D\uDE80 Agent '${config.name}' started (PID: ${pid}, Port: ${config.port})`)})}async stop(name){return validateAgentName(name),this.withInstanceLock(name,async()=>{let agentProcess=await this.findProcessByName(name);if(!agentProcess||agentProcess.status!=="running"){console.log(`\u26A0\uFE0F Agent '${name}' is not running`);return}try{if(process.kill(agentProcess.pid,"SIGTERM"),await new Promise((resolve)=>setTimeout(resolve,3000)),await this.isProcessRunning(agentProcess.pid))process.kill(agentProcess.pid,"SIGKILL");await this.updateProcessStatus(name,"stopped"),console.log(`\u2705 Agent '${name}' stopped (tunnel + API key preserved)`)}catch(err){throw Error(`Failed to stop agent '${name}': ${err}`,{cause:err})}})}async restart(name,config){validateAgentName(name),validateAgentName(config.name);let existing=await this.findProcessByName(name);if(existing&&existing.status==="running")await this.stop(name);await this.startDaemon(config),console.log(`\uD83D\uDD04 Agent '${name}' restarted (tunnel + API key preserved)`)}async kill(name){return validateAgentName(name),this.withInstanceLock(name,async()=>{let agentProcess=await this.findProcessByName(name);if(!agentProcess||agentProcess.status!=="running"){console.log(`\u26A0\uFE0F Agent '${name}' is not running`);return}let flagPath=join(tmpdir(),`.boff-vibecontrols-kill-${agentProcess.pid}`);try{await Bun.write(flagPath,"kill")}catch{}try{process.kill(agentProcess.pid,"SIGTERM"),await new Promise((resolve)=>setTimeout(resolve,5000))}catch{}if(await this.isProcessRunning(agentProcess.pid))await this.killProcessTree(agentProcess.pid);await this.updateProcessStatus(name,"stopped"),console.log(`\uD83D\uDC80 Agent '${name}' killed (tunnel + state torn down)`)})}async getStatus(name){return validateAgentName(name),this.findProcessByName(name)}discoverRuntimeInstances(){let agentsDir=join(this.productDir,"agents");if(!existsSync(agentsDir))return[];let profileDirs;try{profileDirs=readdirSync(agentsDir,{withFileTypes:!0}).filter((entry)=>entry.isDirectory()).map((entry)=>entry.name)}catch{return[]}let discovered=[];for(let profile of profileDirs){let runtimePath=join(agentsDir,profile,"runtime.json");if(!existsSync(runtimePath))continue;try{let rt=JSON.parse(readFileSync(runtimePath,"utf8"));if(typeof rt.pid!=="number"||typeof rt.port!=="number")continue;let name=rt.profile||profile;try{validateAgentName(name)}catch{continue}discovered.push({name,pid:rt.pid,port:rt.port,config:{name,port:rt.port,daemon:!0,dbPath:join(agentsDir,profile,"agent-db"),host:rt.host,profile:name},startTime:rt.startedAt??new Date(0).toISOString(),status:"unknown"})}catch{}}return discovered}async getStatusAll(){let registry=this.loadRegistry(),registryNames=new Set(registry.map((p)=>p.name)),candidates=[...registry];for(let disc of this.discoverRuntimeInstances())if(!registryNames.has(disc.name))candidates.push(disc);let processes=[];for(let candidate of candidates){let isRunning=await this.isManagedProcessRunning(candidate);if(!registryNames.has(candidate.name)&&!isRunning)continue;processes.push({...candidate,status:isRunning?"running":"stopped"})}let adopt=processes.filter((p)=>p.status==="running"&&!registryNames.has(p.name));if(adopt.length>0)try{let fresh=this.loadRegistry(),freshNames=new Set(fresh.map((p)=>p.name)),toAdd=adopt.filter((p)=>!freshNames.has(p.name));if(toAdd.length>0)this.saveRegistry([...fresh,...toAdd.map((p)=>({...p,status:"running"}))])}catch{}return processes}async listInstances(){return this.getStatusAll()}getDefaultProfile(){return getDefaultProfile()}setDefaultProfile(name){setDefaultProfile(validateAgentName(name))}async showLogs(name,options){validateAgentName(name);let logFile=join(this.logsDir,`${name}.log`);if(!existsSync(logFile)){console.log(`No logs found for agent '${name}'`);return}if(options.follow)try{let printTail=async(initial)=>{let contents=await Bun.file(logFile).text(),trail=contents.split(`
6
- `).slice(-options.tail).join(`
7
- `);if(process.stdout.write(initial?trail:trail),initial&&!trail.endsWith(`
8
- `))process.stdout.write(`
9
- `);return contents.length},cursor=await printTail(!0),stopped=!1,interval=setInterval(async()=>{if(stopped)return;try{let fs=await import("fs"),stat=fs.statSync(logFile);if(stat.size>cursor){let fd=fs.openSync(logFile,"r"),length=stat.size-cursor,buf=Buffer.alloc(length);fs.readSync(fd,buf,0,length,cursor),fs.closeSync(fd),process.stdout.write(buf),cursor=stat.size}else if(stat.size<cursor)cursor=await printTail(!1)}catch{}},500),cleanup=()=>{if(stopped)return;stopped=!0,clearInterval(interval)};process.on("SIGINT",()=>{cleanup(),process.exit(0)}),process.on("SIGTERM",()=>{cleanup(),process.exit(0)}),process.on("SIGHUP",()=>{cleanup(),process.exit(0)}),process.on("exit",cleanup)}catch(err){console.error("Failed to follow logs:",err)}else try{let trail=(await Bun.file(logFile).text()).split(`
10
- `).slice(-options.tail).join(`
11
- `);console.log(trail)}catch(err){console.error("Failed to read logs:",err)}}async checkHealth(name){let proc=await this.findProcessByName(name);if(!proc||proc.status!=="running")return{healthy:!1,details:{error:"Process not running"}};try{let response=await fetch(`http://localhost:${proc.port}/health`),data=await response.json();return{healthy:response.ok,details:data}}catch(err){return{healthy:!1,details:{error:"Health check failed",message:err.message}}}}async setConfig(key,value){let configFile=join(getVibecontrolsProductDir(),"config.json"),config={};if(existsSync(configFile))config=JSON.parse(readFileSync(configFile,"utf8"));config[key]=value,writeFileSync(configFile,JSON.stringify(config,null,2))}async getConfig(key){let configFile=join(getVibecontrolsProductDir(),"config.json");if(!existsSync(configFile))return key?void 0:{};let config=JSON.parse(readFileSync(configFile,"utf8"));return key?config[key]:config}loadRegistry(){return getInstances()}saveRegistry(processes){setInstances(processes)}async withInstanceLock(name,fn){let safeName=validateAgentName(name),lockPath=join(this.productDir,`.agent-${safeName}.lock`),fd;try{fd=openSync(lockPath,"wx",384),writeFileSync(fd,`${process.pid}
12
- `)}catch(err){if(err.code==="EEXIST"){let lockPid=parseInt(readFileSync(lockPath,"utf8"),10);if(!lockPid||!await this.isProcessRunning(lockPid)){try{unlinkSync(lockPath)}catch{}return this.withInstanceLock(name,fn)}throw Error(`Agent '${name}' is already being modified`,{cause:err})}throw err}try{return await fn()}finally{try{closeSync(fd)}catch{}try{unlinkSync(lockPath)}catch{}}}async saveProcessInfo(name,pid,config){let filtered=this.loadRegistry().filter((p)=>p.name!==name);filtered.push({name,pid,port:config.port,config,startTime:new Date().toISOString(),status:"running"}),this.saveRegistry(filtered)}async updateProcessStatus(name,status){let registry=this.loadRegistry(),proc=registry.find((p)=>p.name===name);if(proc)proc.status=status,this.saveRegistry(registry)}async findProcessByName(name){validateAgentName(name);let proc=this.loadRegistry().find((p)=>p.name===name);if(!proc)return null;let isRunning=await this.isManagedProcessRunning(proc);return proc.status=isRunning?"running":"stopped",proc}async isManagedProcessRunning(proc){if(!await this.isProcessRunning(proc.pid))return!1;try{return(await fetch(`http://127.0.0.1:${proc.port}/health/live`,{signal:AbortSignal.timeout(1000)})).ok}catch{return!1}}async isProcessRunning(pid){try{return process.kill(pid,0),!0}catch{return!1}}async killProcessTree(pid){if(process.platform==="win32"){try{getOsAdapter().killProcessTree(pid,"SIGKILL")}catch{}return}let children=this.getChildPids(pid);for(let childPid of children)await this.killProcessTree(childPid);try{process.kill(-pid,"SIGKILL")}catch{try{process.kill(pid,"SIGKILL")}catch{}}}getChildPids(pid){try{return getOsAdapter().listChildPids(pid)}catch{return[]}}}
13
- export{ServiceManager};
@@ -1,5 +0,0 @@
1
- // @bun
2
- import{getDaemonProfile,profileRegistry,registerAllowedTunnelSuffix}from"./index-7pdmqbj8.js";import{getPluginRegistry,getVibecontrolsDir}from"./index-bysm7taq.js";import{__require}from"./index-e9rt4m94.js";import{existsSync,mkdirSync,readFileSync,renameSync,realpathSync,rmSync,statSync,writeFileSync}from"fs";import{homedir as osHomedir}from"os";import{dirname,isAbsolute,join,relative}from"path";import{fileURLToPath as fileURLToPath2}from"url";var PROVIDER_TYPES=["tunnel","session","ai","plan"];class ServiceRegistry{providers=new Map;providerOrder=new Map;defaults=new Map;services=new Map;db;constructor(db){this.db=db}getDb(){return this.db}setProviderDefault(type,pluginName){this.defaults.set(type,pluginName)}clearProviderDefault(type,pluginName){if(!pluginName||this.defaults.get(type)===pluginName)this.defaults.delete(type)}async hydrateDefaultsFromDb(){if(!this.db)return;for(let type of PROVIDER_TYPES)try{let name=await this.db.getConfig(`provider:default:${type}`);if(name)this.defaults.set(type,name)}catch{}}registerProvider(type,provider,pluginName){if(!this.providers.has(type))this.providers.set(type,new Map),this.providerOrder.set(type,[]);let typeMap=this.providers.get(type),order=this.providerOrder.get(type);if(typeMap.has(pluginName))getDaemonProfile().logger.info("service-registry",`Updating ${type} provider from plugin '${pluginName}'`);else getDaemonProfile().logger.info("service-registry",`Registered ${type} provider from plugin '${pluginName}'`);if(typeMap.set(pluginName,{provider,pluginName,registeredAt:new Date}),!order.includes(pluginName))order.push(pluginName)}getProvider(type){let typeMap=this.providers.get(type);if(!typeMap||typeMap.size===0)return;let defaultName=this.defaults.get(type);if(defaultName&&typeMap.has(defaultName))return typeMap.get(defaultName).provider;let order=this.providerOrder.get(type);if(order&&order.length>0){let firstPluginName=order[0];return typeMap.get(firstPluginName)?.provider}return}getProviderByName(type,pluginName){let typeMap=this.providers.get(type);if(!typeMap)return;return typeMap.get(pluginName)?.provider}hasProvider(type){let typeMap=this.providers.get(type);return!!typeMap&&typeMap.size>0}unregisterProvider(type,pluginName){let typeMap=this.providers.get(type);if(!typeMap)return!1;let removed=typeMap.delete(pluginName);if(removed){let order=this.providerOrder.get(type);if(order){let idx=order.indexOf(pluginName);if(idx!==-1)order.splice(idx,1)}this.clearProviderDefault(type,pluginName),getDaemonProfile().logger.info("service-registry",`Unregistered ${type} provider from plugin '${pluginName}'`)}return removed}unregisterPlugin(pluginName){for(let type of PROVIDER_TYPES)this.unregisterProvider(type,pluginName);this.unregisterServices(pluginName)}listProvidersForType(type){let typeMap=this.providers.get(type);if(!typeMap)return[];let defaultName=this.defaults.get(type);if(!defaultName||!typeMap.has(defaultName)){let order=this.providerOrder.get(type);defaultName=order&&order.length>0?order[0]:void 0}return Array.from(typeMap.keys()).map((name)=>({pluginName:name,isDefault:name===defaultName}))}registerService(pluginName,serviceName,service){let key=`${pluginName}:${serviceName}`;this.services.set(key,{service,pluginName}),getDaemonProfile().logger.debug("service-registry",`Registered service '${key}'`)}getService(pluginName,serviceName){let key=`${pluginName}:${serviceName}`;return this.services.get(key)?.service}unregisterServices(pluginName){let keysToDelete=[];for(let[key,entry]of this.services)if(entry.pluginName===pluginName)keysToDelete.push(key);for(let key of keysToDelete)this.services.delete(key);if(keysToDelete.length>0)getDaemonProfile().logger.info("service-registry",`Unregistered ${keysToDelete.length} services from ${pluginName}`)}listProviders(){let result=[];for(let[type,typeMap]of this.providers)for(let[pluginName,entry]of typeMap)result.push({type,name:pluginName,pluginName:entry.pluginName});return result}listServices(){return Array.from(this.services.entries()).map(([key,entry])=>({pluginName:entry.pluginName,serviceName:key.split(":").slice(1).join(":")}))}clear(){this.providers.clear(),this.providerOrder.clear(),this.defaults.clear(),this.services.clear()}}function pluginContractV2EnforceMode(){let v=process.env.VIBECONTROLS_PLUGIN_CONTRACT_V2_ENFORCE;return v==="1"||v==="true"||v==="on"}var FULL_TRUST_CAPS={storage:"rw",secrets:"rw",gateway:!0,broadcast:!0,subprocess:!0,audit:!0,telemetry:!0,singletonOnly:!1,requiresIsolation:!1},EMPTY_CAPS={storage:"none",secrets:"none",gateway:!1,broadcast:!1,subprocess:!1,audit:!1,telemetry:!1,singletonOnly:!1,requiresIsolation:!1};function strictCapsMode(){let v=process.env.VIBECONTROLS_STRICT_PLUGIN_CAPS;return v==="1"||v==="true"||v==="on"}function buildCapabilityProxy(hostServices,pluginName,caps,audit){return new Proxy(hostServices,{get(target,prop,receiver){if(prop==="storage")return guardedStorage(target.storage,caps.storage??"none",pluginName,audit);if(prop==="broadcast"&&!caps.broadcast)return refusalFn(pluginName,"broadcast",audit);if(prop==="workspaceQuery"&&!caps.gateway)return refusalFn(pluginName,"workspaceQuery",audit);if(prop==="getAgentRecordId"&&!caps.gateway)return refusalFn(pluginName,"getAgentRecordId",audit);if(prop==="getWorkspaceId"&&!caps.gateway)return refusalFn(pluginName,"getWorkspaceId",audit);if(prop==="telemetry"){if(!caps.telemetry)return;return Reflect.get(target,prop,receiver)}return Reflect.get(target,prop,receiver)}})}function guardedStorage(storage,mode,pluginName,audit){if(mode==="rw")return storage;return new Proxy(storage,{get(target,op,receiver){let opName=String(op),isWriter=opName==="set"||opName==="delete"||opName==="deleteAll";if(mode==="none"||mode==="read"&&isWriter)return(..._args)=>{throw audit("plugin.capability.denied",{pluginName,surface:"storage",op:opName,mode}),Error(`plugin '${pluginName}' lacks storage:${isWriter?"rw":"read"} capability (op=${opName})`)};return Reflect.get(target,op,receiver)}})}function refusalFn(pluginName,what,audit){return(..._args)=>{throw audit("plugin.capability.denied",{pluginName,op:what}),Error(`plugin '${pluginName}' lacks capability for ${what}`)}}import{Worker}from"worker_threads";import{fileURLToPath}from"url";import{randomUUID}from"crypto";function resolveRuntimeEntry(){let here=fileURLToPath(import.meta.url),sep=here.lastIndexOf("/"),dir=sep>=0?here.slice(0,sep):here,tsPath=`${dir}/plugin-worker-runtime.ts`,jsPath=`${dir}/plugin-worker-runtime.js`;if(here.endsWith(".ts"))return tsPath;return jsPath}class PluginWorkerHost{worker;pending=new Map;spec;initPromise;terminated=!1;constructor(spec){this.spec=spec}async start(){if(this.initPromise)return this.initPromise;return this.initPromise=this.spawn(),this.initPromise}async spawn(){let entry=this.spec.runtimeEntry??resolveRuntimeEntry(),worker=new Worker(entry,{env:process.env});this.worker=worker,worker.on("message",(msg)=>this.onMessage(msg)),worker.on("error",(err)=>this.onWorkerError(err instanceof Error?err:Error(String(err)))),worker.on("exit",(code)=>this.onWorkerExit(code)),await this.call("init",{modulePath:this.spec.modulePath,ctxStub:{name:this.spec.ctx.name,dataDir:this.spec.ctx.dataDir}})}async dispatch(method,params=[]){if(this.terminated)throw Error("PluginWorkerHost terminated");if(!this.worker)await this.start();return this.call("dispatch",{method,params})}call(op,args){if(!this.worker)return Promise.reject(Error("worker not spawned"));let id=randomUUID();return new Promise((resolve,reject)=>{this.pending.set(id,{resolve,reject});try{this.worker?.postMessage({id,op,args})}catch(err){this.pending.delete(id),reject(err instanceof Error?err:Error(String(err)))}})}onMessage(msg){let pending=this.pending.get(msg.id);if(!pending)return;if(this.pending.delete(msg.id),msg.ok)pending.resolve(msg.result);else{let err=Error(msg.error?.message??"worker error");if(msg.error?.stack)err.stack=msg.error.stack;pending.reject(err)}}onWorkerError(err){for(let[,p]of this.pending)p.reject(err);this.pending.clear()}onWorkerExit(code){if(this.pending.size>0){let err=Error(`worker exited (code=${code}) with pending calls`);for(let[,p]of this.pending)p.reject(err);this.pending.clear()}this.terminated=!0}async terminate(){if(this.terminated=!0,!this.worker)return;try{await this.worker.terminate()}catch{}this.worker=void 0}}var CORE_PLUGINS=[{packageName:"@vibecontrols/vibe-plugin-storage",pluginName:"storage",label:"Storage facade",description:"Storage provider registry \u2014 owns AgentDatabase contract. Bundled with the agent; the storage meta lazy-loads the configured provider by name.",category:"storage",trusted:!0,isCore:!0,isDefault:!0,isCritical:!0,removable:!1},...["agent","task","config","git","plugin-mgr","log"].map((name)=>({packageName:`@vibecontrols/vibe-plugin-${name}`,pluginName:name,label:`${name} (built-in)`,description:`Built-in ${name} plugin bundled with the agent.`,category:"core",trusted:!0,isCore:!0,removable:!1}))],META_PLUGINS=[{packageName:"@vibecontrols/vibe-plugin-tunnel",pluginName:"tunnel",label:"Tunnel manager",description:"Owns TunnelProvider interface. Routes to a registered tunnel provider.",category:"tunnel",trusted:!0,isDefault:!0,isCritical:!0,cliCommand:"tunnel",apiPrefix:"/api/tunnel"},{packageName:"@vibecontrols/vibe-plugin-session-manager",pluginName:"session-manager",label:"Session manager",description:"Owns SessionProvider interface. Routes to a registered session backend.",category:"session",trusted:!0,isCore:!0,isDefault:!0,isCritical:!0,cliCommand:"session",apiPrefix:"/api/sessions"},{packageName:"@vibecontrols/vibe-plugin-ai",pluginName:"ai",label:"AI orchestration",description:"Owns AIAgentProvider interface. Prompts, contexts, sessions, dispatch, logs.",category:"ai",trusted:!0,isDefault:!0,isCritical:!0,cliCommand:"ai",apiPrefix:"/api/ai"},{packageName:"@vibecontrols/vibe-plugin-plan",pluginName:"plan",label:"Plan orchestration",description:"Owns PlanProvider interface. Routes plan sessions to a registered provider.",category:"plan",trusted:!0,isDefault:!0,cliCommand:"plan",apiPrefix:"/api/plan"},{packageName:"@vibecontrols/vibe-plugin-gitops",pluginName:"gitops",label:"GitOps orchestrator",description:"Owns GitOpsProvider interface. Routes repo / PR / CI / security queries to a registered provider.",category:"gitops",trusted:!0,isDefault:!0,cliCommand:"gitops",apiPrefix:"/api/gitops"},{packageName:"@vibecontrols/vibe-plugin-security",pluginName:"security",label:"Security lifecycle",description:"Security lifecycle orchestrator \u2014 owns /api/security and dispatches to per-stage providers.",category:"security",trusted:!0,isDefault:!0,cliCommand:"security",apiPrefix:"/api/security"}],AGENT_PLUGINS=[{packageName:"@vibecontrols/vibe-plugin-agent-backup",pluginName:"agent-backup",label:"Agent backup",description:"Backup and restore agent state.",category:"agent",trusted:!0,isDefault:!0}],PLUGIN_CATALOG=[...CORE_PLUGINS,...META_PLUGINS,...AGENT_PLUGINS],ABILITIES=[{key:"storage",label:"Storage",description:"Encrypted local state for the agent.",categories:["storage"],mandatory:!0,defaultSelected:!0},{key:"tunnel",label:"Tunnels",description:"Expose the agent for remote access + share links.",categories:["tunnel"],mandatory:!0,defaultSelected:!0},{key:"backup",label:"Backup",description:"Backup + restore agent state.",categories:["agent"],mandatory:!0,defaultSelected:!0},{key:"session",label:"Terminal sessions",description:"Long-lived terminal / AI agent sessions.",categories:["session"],mandatory:!1,defaultSelected:!0},{key:"ai",label:"AI orchestration",description:"AI agent harnesses, prompts + dispatch.",categories:["ai"],mandatory:!1,defaultSelected:!0},{key:"plan",label:"Plan review",description:"Review / approve AI-proposed plans.",categories:["plan"],mandatory:!1,defaultSelected:!0},{key:"gitops",label:"GitOps",description:"Repo / PR / CI / security integration.",categories:["gitops"],mandatory:!1,defaultSelected:!0},{key:"security",label:"Security",description:"Security scanning lifecycle.",categories:["security"],mandatory:!1,defaultSelected:!0}],CORE_PLUGIN_NAMES=PLUGIN_CATALOG.filter((p)=>p.isCore&&p.category==="core").map((p)=>p.pluginName),DEFAULT_PLUGINS=PLUGIN_CATALOG.filter((p)=>p.isDefault===!0);function getDefaultPluginsForPlatform(_platform){return DEFAULT_PLUGINS}function getDefaultPluginsForAbilities(platform,selectedAbilityKeys){let selected=selectedAbilityKeys instanceof Set?selectedAbilityKeys:new Set(selectedAbilityKeys),activeCategories=new Set;for(let ability of ABILITIES)if(ability.mandatory||selected.has(ability.key))for(let c of ability.categories)activeCategories.add(c);return getDefaultPluginsForPlatform(platform).filter((p)=>activeCategories.has(p.category))}var TRUSTED_PACKAGES=new Set(PLUGIN_CATALOG.filter((p)=>p.trusted).map((p)=>p.packageName));function getCriticalPluginNames(){let fromCatalog=PLUGIN_CATALOG.filter((p)=>p.isCritical).flatMap((p)=>[p.packageName,p.pluginName]),override=process.env.VIBECONTROLS_CRITICAL_PLUGINS;if(override){let parts=override.split(",").map((s)=>s.trim()).filter(Boolean);return new Set([...fromCatalog,...parts])}return new Set(fromCatalog)}function isCriticalPlugin(packageOrName){return getCriticalPluginNames().has(packageOrName)}var AVAILABLE_PLUGINS=PLUGIN_CATALOG.filter((p)=>!p.isCore||p.category!=="core");function getCatalogEntry(packageName){return PLUGIN_CATALOG.find((p)=>p.packageName===packageName)}function collectPluginBinaries(_pluginIdentifiers){return new Set}function isTrustedPackage(packageName){return packageName.startsWith("@vibecontrols/vibe-plugin-")||TRUSTED_PACKAGES.has(packageName)}function resolvePluginByShortName(input){let raw=input.trim();if(!raw)return;if(raw.startsWith("@vibecontrols/"))return PLUGIN_CATALOG.find((p)=>p.packageName===raw);if(raw.startsWith("vibe-plugin-"))return PLUGIN_CATALOG.find((p)=>p.packageName===`@vibecontrols/${raw}`);let byPluginName=PLUGIN_CATALOG.find((p)=>p.pluginName===raw);if(byPluginName)return byPluginName;return PLUGIN_CATALOG.find((p)=>p.packageName===`@vibecontrols/vibe-plugin-${raw}`)}function getCatalogEntry2(pluginName){return PLUGIN_CATALOG.find((entry)=>entry.pluginName===pluginName)}var REGISTRY_FILE_NAME="plugins.json",PLUGIN_PACKAGE_RE=/^@vibecontrols\/vibe-plugin-[a-z0-9][a-z0-9-]{0,80}$/,PLUGIN_NAME_RE=/^[a-z0-9][a-z0-9-]{0,63}$/,PLUGIN_API_PREFIX_RE=/^\/api\/[A-Za-z0-9][A-Za-z0-9/_-]{0,127}$/,PLUGIN_PUBLIC_PATH_RE=/^\/[A-Za-z0-9][A-Za-z0-9/_-]{0,159}$/,PLUGIN_PACKAGE_ROOT=Symbol.for("vibecontrols.pluginPackageRoot");function getPluginPackageRoot(plugin){return plugin[PLUGIN_PACKAGE_ROOT]}function validatePluginPackageName(packageName){let normalized=packageName.trim();if(!PLUGIN_PACKAGE_RE.test(normalized))throw Error("Plugin package must be a @vibecontrols/vibe-plugin-* package name.");if(!isTrustedPackage(normalized)&&process.env.VIBECONTROLS_ALLOW_UNTRUSTED_PLUGINS!=="1")throw Error("Plugin package is not in the trusted VibeControls catalog.");return normalized}function isPathInside(parent,child){let rel=relative(parent,child);return rel===""||!!rel&&!rel.startsWith("..")&&!isAbsolute(rel)}function getInstallMode(){let v=(process.env.VIBECONTROLS_PLUGIN_INSTALL_MODE||"").toLowerCase();if(v==="local")return"local";if(v==="global")return"global";return process.platform==="win32"?"local":"global"}var PROVIDER_DEFAULT_PREFIX="provider:default:";function isPluginEntry(value){if(!value||typeof value!=="object")return!1;let entry=value;return typeof entry.packageName==="string"&&typeof entry.version==="string"&&typeof entry.pluginName==="string"&&typeof entry.installedAt==="string"}var DEFAULT_PLUGINS2=DEFAULT_PLUGINS;class PluginManager{registry=[];loaded=new Map;corePlugins=new Map;db;forcedIsolation=new Set;workerHosts=new Map;constructor(db){this.db=db,this.ensureDir(),this.loadRegistry();let isolateEnv=process.env.VIBE_ISOLATE_PLUGINS;if(typeof isolateEnv==="string"&&isolateEnv.length>0)this.setForcedIsolation(isolateEnv.split(",").map((n)=>n.trim()).filter((n)=>n.length>0))}setForcedIsolation(names){this.forcedIsolation=new Set(names.filter((n)=>n.length>0))}shouldIsolate(plugin){if(this.forcedIsolation.has(plugin.name))return!0;return plugin.capabilities?.requiresIsolation===!0}getWorkerHost(pluginName){return this.workerHosts.get(pluginName)}registerWorkerHost(pluginName,host){this.workerHosts.set(pluginName,host)}auditSink=(event,payload)=>{getDaemonProfile().logger.warn("plugin-capability",event,payload)};static resolveEffectiveCapabilities(plugin,isCore){if(plugin.capabilities)return plugin.capabilities;return isCore?FULL_TRUST_CAPS:EMPTY_CAPS}wrapHostServices(plugin,hostServices){let caps=PluginManager.resolveEffectiveCapabilities(plugin,this.corePlugins.has(plugin.name));return buildCapabilityProxy(hostServices,plugin.name,caps,this.auditSink)}acceptCapabilities(plugin,source){if(plugin.capabilities?.singletonOnly===!0&&profileRegistry.size()>1)return getDaemonProfile().logger.error("plugin-manager",`[plugin] '${plugin.name}' refused to load: singletonOnly capability incompatible with multi-profile daemon (profiles=${profileRegistry.size()}, source=${source})`),!1;if(plugin.capabilities)return!0;if(strictCapsMode())return getDaemonProfile().logger.error("plugin-manager",`[plugin] '${plugin.name}' refused to load: missing required capabilities declaration (source=${source})`),!1;if(source.startsWith("core:"))getDaemonProfile().logger.warn("plugin-manager",`[plugin] '${plugin.name}' loaded without a capabilities declaration \u2014 granting full trust (core plugin). Declare capabilities explicitly. (source=${source})`);else getDaemonProfile().logger.warn("plugin-manager",`[plugin] '${plugin.name}' loaded without a capabilities declaration \u2014 defaulting to EMPTY capability set (deny by default). External plugins MUST declare capabilities explicitly to access host services. (source=${source})`);return!0}ensureDir(){let dir=getVibecontrolsDir();if(!existsSync(dir))mkdirSync(dir,{recursive:!0})}loadRegistry(){let registryFile=join(getVibecontrolsDir(),REGISTRY_FILE_NAME);try{if(existsSync(registryFile)){let raw=readFileSync(registryFile,"utf-8"),parsed=JSON.parse(raw);if(Array.isArray(parsed)&&parsed.every(isPluginEntry))this.registry=parsed.filter((entry)=>{try{return validatePluginPackageName(entry.packageName),!0}catch(err){return getDaemonProfile().logger.warn("plugin-manager","Ignoring invalid plugin entry",{packageName:entry.packageName,error:String(err)}),!1}});else throw Error("plugins.json has an invalid schema")}}catch(err){getDaemonProfile().logger.warn("plugin-manager","Failed to load plugin registry",{path:registryFile,error:String(err)}),this.registry=[]}}saveRegistry(){this.ensureDir();let registryFile=join(getVibecontrolsDir(),REGISTRY_FILE_NAME),tmpFile=`${registryFile}.${process.pid}.tmp`;writeFileSync(tmpFile,`${JSON.stringify(this.registry,null,2)}
3
- `,{encoding:"utf-8",mode:384}),renameSync(tmpFile,registryFile)}async loadCorePlugins(){let coreModules=await Promise.allSettled([import("./index-1p8wr6rq.js"),import("./index-fwd90spw.js"),import("./index-m483e746.js"),import("./index-e875a6zy.js"),import("./index-j0dksk5f.js"),import("./index-4ymjceh1.js")]),ctx=getDaemonProfile();for(let i=0;i<coreModules.length;i++){let result=coreModules[i],expectedName=CORE_PLUGIN_NAMES[i];if(result.status==="fulfilled"){let mod=result.value,plugin;try{plugin=this.extractPlugin(mod,`core:${expectedName}`,ctx)}catch(err){getDaemonProfile().logger.error("plugin-manager",`Core plugin '${expectedName}' refused to load: ${err instanceof Error?err.message:String(err)}`);continue}if(plugin?.name){if(!this.acceptCapabilities(plugin,`core:${expectedName}`))continue;this.corePlugins.set(plugin.name,plugin),getDaemonProfile().logger.info("plugin-manager",`Core plugin loaded: ${plugin.name} v${plugin.version}`)}else getDaemonProfile().logger.warn("plugin-manager",`Core plugin '${expectedName}' did not export a valid createPlugin(ctx) factory`)}else getDaemonProfile().logger.warn("plugin-manager",`Failed to load core plugin '${expectedName}': ${result.reason}`)}getDaemonProfile().logger.info("plugin-manager",`Core plugins loaded: ${this.corePlugins.size}/${CORE_PLUGIN_NAMES.length}`)}async resolveConcreteLatest(packageName,registry){try{let url=`${registry.replace(/\/+$/,"")}/${packageName.replace("/","%2F")}`,res=await fetch(url,{headers:{accept:"application/json"},signal:AbortSignal.timeout(20000)});if(!res.ok)return;let latest=(await res.json())["dist-tags"]?.latest;if(typeof latest==="string"&&/^\d+\.\d+\.\d+/.test(latest))return latest}catch{}return}async install(packageName,opts={}){packageName=validatePluginPackageName(packageName);let refreshLatest=opts.refreshLatest===!0;if(getDaemonProfile().logger.info("plugin-manager",`Installing ${packageName}${refreshLatest?"@latest (refresh)":""}...`),!refreshLatest)try{await import(packageName),getDaemonProfile().logger.info("plugin-manager",`${packageName} already resolvable \u2014 skipping global install`);let plugin2=await this.importPlugin(packageName),entry2={packageName,version:plugin2.version,pluginName:plugin2.name,installedAt:new Date().toISOString()};return this.registry=this.registry.filter((e)=>e.packageName!==packageName),this.registry.push(entry2),this.saveRegistry(),entry2}catch{}let registry=getPluginRegistry(),installMode=getInstallMode(),concreteLatest=refreshLatest?await this.resolveConcreteLatest(packageName,registry):void 0,installSpec=refreshLatest?`${packageName}@${concreteLatest??"latest"}`:packageName;try{if(installMode==="local"){let localDir=join(getVibecontrolsDir(),"agent-plugins");if(!existsSync(localDir))mkdirSync(localDir,{recursive:!0});let pkgJsonPath=join(localDir,"package.json");if(!existsSync(pkgJsonPath))writeFileSync(pkgJsonPath,JSON.stringify({name:"vibecontrols-agent-plugins",private:!0,version:"0.0.0",dependencies:{}},null,2)+`
4
- `);if(refreshLatest&&concreteLatest){let installedVer=this.readInstalledVersion(join(localDir,"node_modules"),packageName);if(installedVer&&installedVer!==concreteLatest){getDaemonProfile().logger.info("plugin-manager",`Pre-clean ${packageName}: on-disk v${installedVer} != target v${concreteLatest} \u2014 removing stale copy + lockfile to force fresh resolve`);try{rmSync(join(localDir,"node_modules",packageName),{recursive:!0,force:!0})}catch{}try{rmSync(join(localDir,"bun.lock"),{force:!0})}catch{}}}if(Bun.spawnSync(["bun","add",installSpec,"--registry",registry],{cwd:localDir,timeout:120000,stdout:"pipe",stderr:"pipe"}).exitCode!==0){let npmResult=Bun.spawnSync(["npm","install",installSpec,"--registry",registry],{cwd:localDir,timeout:120000,stdout:"pipe",stderr:"pipe"});if(npmResult.exitCode!==0)throw Error(npmResult.stderr.toString().trim())}}else if(Bun.spawnSync(["bun","install","-g",installSpec,"--registry",registry],{timeout:120000,stdout:"pipe",stderr:"pipe"}).exitCode!==0){let npmResult=Bun.spawnSync(["npm","install","-g",installSpec,"--registry",registry],{timeout:120000,stdout:"pipe",stderr:"pipe"});if(npmResult.exitCode!==0)throw Error(npmResult.stderr.toString().trim())}this.pluginRoots=void 0}catch(err){let message=err instanceof Error?err.message:String(err);if(refreshLatest)try{await import(packageName),getDaemonProfile().logger.warn("plugin-manager",`Could not refresh ${packageName} to @latest (${message}); using the already-installed copy`),this.pluginRoots=void 0;let plugin2=await this.importPlugin(packageName),entry2={packageName,version:plugin2.version,pluginName:plugin2.name,installedAt:new Date().toISOString()};return this.registry=this.registry.filter((e)=>e.packageName!==packageName),this.registry.push(entry2),this.saveRegistry(),entry2}catch{}throw Error(`Failed to install ${packageName}: ${message}`,{cause:err})}let plugin=await this.importPlugin(packageName);if(refreshLatest&&concreteLatest&&plugin.version!==concreteLatest)getDaemonProfile().logger.warn("plugin-manager",`${packageName} refreshed to ${plugin.version} but registry latest is ${concreteLatest} \u2014 a stale resolver/cache may still be in play`);if(this.corePlugins.has(plugin.name))getDaemonProfile().logger.info("plugin-manager",`External plugin '${packageName}' overrides core plugin '${plugin.name}'`);let entry={packageName,version:plugin.version,pluginName:plugin.name,installedAt:new Date().toISOString()};return this.registry=this.registry.filter((e)=>e.packageName!==packageName),this.registry.push(entry),this.saveRegistry(),getDaemonProfile().logger.info("plugin-manager",`Installed ${packageName}@${plugin.version} (${plugin.name})`),entry}async ensureDefaultPlugins(onStatus,skipPlugins=[],selectedAbilities){let installed=[],skipSet=new Set(skipPlugins),entries=selectedAbilities?getDefaultPluginsForAbilities(process.platform,selectedAbilities):getDefaultPluginsForPlatform(process.platform);for(let entry of entries){if(skipSet.has(entry.packageName)||skipSet.has(entry.pluginName)){getDaemonProfile().logger.info("plugin-manager",`${entry.packageName} skipped by --skip-plugin`);continue}if(entry.isCore){getDaemonProfile().logger.info("plugin-manager",`${entry.packageName} is bundled with the agent \u2014 skipping auto-install`);continue}if(this.registry.some((r)=>r.packageName===entry.packageName)){getDaemonProfile().logger.info("plugin-manager",`${entry.packageName} already installed, skipping auto-install`);continue}onStatus?.(`Installing ${entry.label} (${entry.packageName})...`);try{await this.install(entry.packageName),installed.push(entry),onStatus?.(`Installed ${entry.label} (${entry.packageName})`)}catch(err){let message=err instanceof Error?err.message:String(err);getDaemonProfile().logger.error("plugin-manager",`Failed to auto-install ${entry.packageName}: ${message}`),onStatus?.(`Failed to install ${entry.label}: ${message}`)}}if(installed.length>0)this.loadRegistry();return installed}async installAndLoad(packageName,app,hostServices){let entry=await this.install(packageName),plugin=this.loaded.get(entry.packageName);if(plugin){this.registerPluginProviders(plugin,hostServices);let wrapped=this.wrapHostServices(plugin,hostServices);if(plugin.onServerStart)await plugin.onServerStart(app,wrapped);if(plugin.onServerReady)await plugin.onServerReady(app,wrapped)}return entry}async update(packageName){packageName=validatePluginPackageName(packageName),getDaemonProfile().logger.info("plugin-manager",`Updating ${packageName}...`);let existing=this.registry.find((e)=>e.packageName===packageName);if(!existing)throw Error(`Plugin ${packageName} is not installed. Use 'install' first.`);let registry=getPluginRegistry();try{if(Bun.spawnSync(["bun","install","-g",`${packageName}@latest`,"--registry",registry],{timeout:120000,stdout:"pipe",stderr:"pipe"}).exitCode!==0){let npmResult=Bun.spawnSync(["npm","install","-g",`${packageName}@latest`,"--registry",registry],{timeout:120000,stdout:"pipe",stderr:"pipe"});if(npmResult.exitCode!==0)throw Error(npmResult.stderr.toString().trim())}}catch(err){let message=err instanceof Error?err.message:String(err);throw Error(`Failed to update ${packageName}: ${message}`,{cause:err})}this.loaded.delete(packageName);let plugin=await this.importPlugin(packageName),entry={packageName,version:plugin.version,pluginName:plugin.name,installedAt:existing.installedAt};return this.registry=this.registry.filter((e)=>e.packageName!==packageName),this.registry.push(entry),this.saveRegistry(),getDaemonProfile().logger.info("plugin-manager",`Updated ${packageName} to v${plugin.version}`),entry}async updateAll(){let results=[];for(let entry of[...this.registry])try{let updated=await this.update(entry.packageName);results.push({packageName:entry.packageName,success:!0,version:updated.version})}catch(err){results.push({packageName:entry.packageName,success:!1,error:err instanceof Error?err.message:String(err)})}return results}async removeAll(hostServices){let results=[],toRemove=[...this.registry];for(let entry of toRemove)try{await this.remove(entry.packageName,hostServices),results.push({packageName:entry.packageName,success:!0})}catch(err){results.push({packageName:entry.packageName,success:!1,error:err instanceof Error?err.message:String(err)})}return results}async remove(packageName,hostServices){packageName=validatePluginPackageName(packageName),getDaemonProfile().logger.info("plugin-manager",`Removing ${packageName}...`);let plugin=this.loaded.get(packageName);if(plugin?.onServerStop)try{await plugin.onServerStop()}catch(err){getDaemonProfile().logger.warn("plugin-manager",`Error stopping ${packageName}: ${err}`)}if(plugin)hostServices?.serviceRegistry.unregisterPlugin(plugin.name),this.loaded.delete(packageName);let registryEntry=this.registry.find((e)=>e.packageName===packageName);if(!plugin&&registryEntry)hostServices?.serviceRegistry.unregisterPlugin(registryEntry.pluginName);let localDir=join(getVibecontrolsDir(),"agent-plugins");try{if(existsSync(join(localDir,"package.json")))Bun.spawnSync(["bun","remove",packageName],{cwd:localDir,timeout:60000,stdout:"pipe",stderr:"pipe"})}catch{}try{Bun.spawnSync(["bun","remove","-g",packageName],{timeout:60000,stdout:"pipe",stderr:"pipe"})}catch{try{Bun.spawnSync(["npm","uninstall","-g",packageName],{timeout:60000,stdout:"pipe",stderr:"pipe"})}catch{}}this.pluginRoots=void 0,this.registry=this.registry.filter((e)=>e.packageName!==packageName),this.saveRegistry(),getDaemonProfile().logger.info("plugin-manager",`Removed ${packageName}`)}async loadAll(){this.loaded.clear();let stale=[];for(let entry of this.registry)try{validatePluginPackageName(entry.packageName),await this.importPlugin(entry.packageName),getDaemonProfile().logger.info("plugin-manager",`Loaded ${entry.packageName} (${entry.pluginName})`)}catch(err){let code=err.code;if(code==="ENOENT_PLUGIN")getDaemonProfile().logger.info("plugin-manager",`${entry.packageName} not present on disk \u2014 dropping from registry`),stale.push(entry.packageName);else if(code==="EPLUGIN_LEGACY_SINGLETON")getDaemonProfile().logger.warn("plugin-manager",`Skipping ${entry.packageName}: ${err instanceof Error?err.message:String(err)}`);else getDaemonProfile().logger.warn("plugin-manager",`Failed to load ${entry.packageName} \u2014 dropping from registry: ${err}`),stale.push(entry.packageName)}if(stale.length>0){this.registry=this.registry.filter((e)=>!stale.includes(e.packageName));try{this.saveRegistry()}catch(err){getDaemonProfile().logger.warn("plugin-manager",`Failed to persist pruned registry: ${err}`)}}}async importPlugin(packageName){packageName=validatePluginPackageName(packageName);let mod={},packageRoot;{let roots=this.getGlobalRoots(),loaded=!1,attempts=[],allMissing=!0;for(let root of roots){let absolutePath=join(root,packageName);if(!existsSync(absolutePath)){attempts.push({path:absolutePath,error:"directory missing"});continue}allMissing=!1;try{packageRoot=absolutePath,mod=await import(absolutePath),loaded=!0;break}catch(err){attempts.push({path:absolutePath,error:err instanceof Error?err.message:String(err)})}try{let pkgJsonPath=join(absolutePath,"package.json");if(!existsSync(pkgJsonPath)){attempts.push({path:pkgJsonPath,error:"package.json missing"});continue}let pkgJson=JSON.parse(readFileSync(pkgJsonPath,"utf8")),entry=pkgJson.module??pkgJson.main??"./index.js",filePath=join(absolutePath,entry);packageRoot=absolutePath,mod=await import(filePath),loaded=!0;break}catch(err){attempts.push({path:absolutePath,error:err instanceof Error?err.message:String(err)})}}if(!loaded)try{packageRoot=this.resolvePackageRoot(packageName)??packageRoot,mod=await import(packageName),loaded=!0}catch(err){attempts.push({path:`bare:${packageName}`,error:err instanceof Error?err.message:String(err)})}if(!loaded){let detail=attempts.map((a)=>`${a.path} (${a.error})`).join("; "),err=Error(`Cannot find module '${packageName}': explicit root attempts and bare import failed: ${detail||"(no roots probed)"}`);if(allMissing&&roots.length>0)err.code="ENOENT_PLUGIN";throw err}}let plugin=this.extractPlugin(mod,`external:${packageName}`,getDaemonProfile());if(!plugin){if(this.hasLegacySingleton(mod)){let err=Error(`${packageName} uses removed singleton contract; upgrade to createPlugin(ctx) factory (set VIBECONTROLS_PLUGIN_CONTRACT_V2_ENFORCE=1 to refuse strictly)`);throw err.code="EPLUGIN_LEGACY_SINGLETON",err}throw Error(`${packageName} does not export a valid createPlugin(ctx) factory`)}if(this.validatePluginExport(plugin,packageName,packageRoot),!this.acceptCapabilities(plugin,`external:${packageName}`))throw Error(`${packageName} refused to load: missing required capabilities declaration`);if(packageRoot)Object.defineProperty(plugin,PLUGIN_PACKAGE_ROOT,{value:packageRoot,enumerable:!1,configurable:!1});if(this.logResolvedPlugin(packageName,plugin.version,packageRoot),this.loaded.set(packageName,plugin),this.shouldIsolate(plugin))try{let ctx=getDaemonProfile(),host=new PluginWorkerHost({modulePath:packageName,pluginName:plugin.name,ctx:{name:ctx.name,dataDir:ctx.dataDir}});await host.start(),this.workerHosts.set(plugin.name,host),ctx.logger.info("plugin-manager",`Isolated plugin '${plugin.name}' running in worker_threads`)}catch(err){getDaemonProfile().logger.warn("plugin-manager",`Failed to isolate plugin '${plugin.name}'; falling back to in-host: ${err instanceof Error?err.message:String(err)}`)}return plugin}resolvePackageRoot(packageName){let meta=import.meta;if(typeof meta.resolve!=="function")return;try{let resolved=meta.resolve(packageName);if(!resolved.startsWith("file:"))return;let current=dirname(fileURLToPath2(resolved));while(current&&current!==dirname(current)){if(existsSync(join(current,"package.json")))return current;current=dirname(current)}}catch{return}return}validatePluginExport(plugin,packageName,packageRoot){if(!PLUGIN_NAME_RE.test(plugin.name))throw Error(`${packageName} exports an invalid plugin name`);if(!plugin.version||plugin.version.length>64)throw Error(`${packageName} exports an invalid plugin version`);if(plugin.description&&plugin.description.length>500)throw Error(`${packageName} description is too long`);if(plugin.cliCommand&&!PLUGIN_NAME_RE.test(plugin.cliCommand))throw Error(`${packageName} exports an invalid CLI command`);if(plugin.apiPrefix){if(!PLUGIN_API_PREFIX_RE.test(plugin.apiPrefix)||plugin.apiPrefix.includes("..")||plugin.apiPrefix.includes("//"))throw Error(`${packageName} exports an invalid API prefix`)}if(plugin.publicPaths){if(plugin.publicPaths.length>20)throw Error(`${packageName} exports too many public paths`);for(let publicPath of plugin.publicPaths)if(!PLUGIN_PUBLIC_PATH_RE.test(publicPath)||publicPath.includes("..")||publicPath.includes("//"))throw Error(`${packageName} exports an invalid public path`)}if(plugin.dependencies&&plugin.dependencies.length>20)throw Error(`${packageName} exports too many dependencies`);if(plugin.tags){let allowedTags=new Set(["backend","frontend","cli","provider","adapter","integration"]);if(plugin.tags.length>allowedTags.size)throw Error(`${packageName} exports too many tags`);for(let tag of plugin.tags)if(!allowedTags.has(tag))throw Error(`${packageName} exports an invalid tag`)}if(plugin.ui){if(plugin.ui.title&&plugin.ui.title.length>120)throw Error(`${packageName} UI title is too long`);if(plugin.ui.staticDir){if(!packageRoot)throw Error(`${packageName} UI staticDir requires a package root`);let rootReal=realpathSync(packageRoot),staticReal=realpathSync(plugin.ui.staticDir);if(!statSync(staticReal).isDirectory()||!isPathInside(rootReal,staticReal))throw Error(`${packageName} UI staticDir must be inside the plugin package`)}}}pluginRoots;getPluginRoots(){if(this.pluginRoots!==void 0)return this.pluginRoots;let roots=[],seen=new Set,push=(p)=>{if(!p)return;if(seen.has(p))return;if(!existsSync(p))return;seen.add(p),roots.push(p)};try{let localDir=join(getVibecontrolsDir(),"agent-plugins","node_modules");push(localDir)}catch{}let extra=process.env.VIBECONTROLS_PLUGIN_ROOTS;if(extra){let rootsDelimiter=process.platform==="win32"?";":":";for(let p of extra.split(rootsDelimiter).map((s)=>s.trim()).filter(Boolean))push(p)}try{let dir=process.cwd(),root=dirname(dir)===dir?dir:"/";while(dir&&dir!==root&&dir!==dirname(dir))push(join(dir,"node_modules")),dir=dirname(dir)}catch{}try{let dir=dirname(fileURLToPath2(import.meta.url)),stop=dirname(dir)===dir?dir:"/";while(dir&&dir!==stop&&dir!==dirname(dir)){if(existsSync(join(dir,"package.json"))){push(join(dir,"node_modules"));break}dir=dirname(dir)}}catch{}try{push(join(osHomedir(),".bun","install","global","node_modules"))}catch{}try{let result=Bun.spawnSync(["npm","root","-g"],{stdout:"pipe",stderr:"pipe",timeout:1e4});if(result.exitCode===0)push(result.stdout.toString().trim())}catch{}return this.pluginRoots=roots,roots}getGlobalRoots(){return this.getPluginRoots()}readInstalledVersion(root,packageName){try{let pkgJsonPath=join(root,packageName,"package.json");if(!existsSync(pkgJsonPath))return;let pkg=JSON.parse(readFileSync(pkgJsonPath,"utf8"));return typeof pkg.version==="string"?pkg.version:void 0}catch{return}}logResolvedPlugin(packageName,loadedVersion,loadedDir){let logger=getDaemonProfile().logger;logger.debug("plugin-manager",`Resolved ${packageName}@${loadedVersion}`,{from:loadedDir??"(bare import)"});try{let shadows=[];for(let root of this.getPluginRoots()){let dir=join(root,packageName);if(loadedDir&&dir===loadedDir)continue;let ver=this.readInstalledVersion(root,packageName);if(ver&&ver!==loadedVersion)shadows.push(`${dir} (v${ver})`)}if(shadows.length>0)logger.warn("plugin-manager",`${packageName}: loaded v${loadedVersion} but stale duplicate copy(ies) exist at a different version \u2014 these shadow the active copy across reinstalls. Run \`vibe nuke --all\` to purge them.`,{loadedVersion,loadedFrom:loadedDir??"(bare import)",shadows})}catch{}}getNpmGlobalRoot(){let roots=this.getPluginRoots();return roots.length>0?roots[0]:null}extractPlugin(mod,label,ctx){let factory=this.findFactory(mod);if(factory){let plugin=factory(ctx);if(!this.isVibePlugin(plugin))throw Error(`plugin '${label}' createPlugin(ctx) factory returned an invalid VibePlugin`);return plugin}if(this.hasLegacySingleton(mod)){let message=`plugin '${label}' uses removed singleton contract; upgrade to createPlugin(ctx) factory`;if(pluginContractV2EnforceMode())throw Error(message);getDaemonProfile().logger.warn("plugin-manager",message);return}return}findFactory(mod){if(typeof mod.createPlugin==="function")return mod.createPlugin;let defaultExport=mod.default;if(defaultExport&&typeof defaultExport.createPlugin==="function")return defaultExport.createPlugin;return}hasLegacySingleton(mod){if(this.isVibePlugin(mod.vibePlugin))return!0;let defaultExport=mod.default;if(defaultExport&&this.isVibePlugin(defaultExport.vibePlugin))return!0;if(this.isVibePlugin(defaultExport))return!0;return!1}isVibePlugin(value){if(!value||typeof value!=="object")return!1;let candidate=value;return typeof candidate.name==="string"&&typeof candidate.version==="string"}registerProviders(plugin,hostServices){this.registerPluginProviders(plugin,hostServices)}registerPluginProviders(plugin,hostServices){let isDefault=getCatalogEntry2(plugin.name)?.isDefault===!0,pinDefault=(type)=>{if(!isDefault)return;hostServices.serviceRegistry.setProviderDefault(type,plugin.name)};if(plugin.providers?.tunnel){if(hostServices.serviceRegistry.registerProvider("tunnel",plugin.providers.tunnel,plugin.name),pinDefault("tunnel"),plugin.tunnelDomainSuffixes)for(let suffix of plugin.tunnelDomainSuffixes)registerAllowedTunnelSuffix(suffix)}if(plugin.providers?.session)hostServices.serviceRegistry.registerProvider("session",plugin.providers.session,plugin.name),pinDefault("session");if(plugin.providers?.ai)hostServices.serviceRegistry.registerProvider("ai",plugin.providers.ai,plugin.name),pinDefault("ai")}async dispatchCliSetup(program,hostServices){for(let plugin of this.getAllPlugins())if(plugin.onCliSetup)try{await plugin.onCliSetup(program,this.wrapHostServices(plugin,hostServices))}catch(err){getDaemonProfile().logger.warn("plugin-manager",`onCliSetup failed for ${plugin.name}: ${err}`)}}async dispatchServerStart(app,hostServices){let sorted=this.sortAllByDependencies(),failures=[];for(let plugin of sorted){if(this.registerPluginProviders(plugin,hostServices),plugin.onServerStart){let startedAt=Date.now();try{await plugin.onServerStart(app,this.wrapHostServices(plugin,hostServices)),(async()=>{try{let{telemetryService}=await import("./telemetry-rew0mtj2.js");telemetryService.emit("plugin.activated",{plugin_name:plugin.name,version:plugin.version,duration_ms:Date.now()-startedAt})}catch{}})()}catch(err){let message=err instanceof Error?err.message:String(err);getDaemonProfile().logger.error("plugin-manager",`onServerStart failed for ${plugin.name}: ${message}`),(async()=>{try{let{telemetryService}=await import("./telemetry-rew0mtj2.js");telemetryService.emit("plugin.failed",{plugin_name:plugin.name,error_class:err instanceof Error?err.constructor.name:"Error"})}catch{}})();let entry=this.registry.find((e)=>e.pluginName===plugin.name);failures.push({plugin:plugin.name,packageName:entry?.packageName,error:message})}}this.registerPluginProviders(plugin,hostServices)}return{failures}}async dispatchServerReady(app,hostServices){for(let plugin of this.getAllPlugins())if(plugin.onServerReady)try{await plugin.onServerReady(app,this.wrapHostServices(plugin,hostServices))}catch(err){getDaemonProfile().logger.warn("plugin-manager",`onServerReady failed for ${plugin.name}: ${err}`)}}async provisionDefaultPrereqs(app,hostServices){let{runPluginPrereqs}=await import("./prereqs-runner-k85knvak.js"),skipInstall=process.env.VIBE_SKIP_PREREQ_INSTALL==="1",platform=process.platform,newlyInstalled=[],metaPkgs=getDefaultPluginsForPlatform(process.platform).map((p)=>p.packageName);if(!skipInstall)for(let pkg of metaPkgs){if(this.loaded.has(pkg))continue;try{getDaemonProfile().logger.info("plugin-manager",`Installing default meta ${pkg}`),await this.install(pkg,{refreshLatest:!0}),newlyInstalled.push(pkg)}catch(err){getDaemonProfile().logger.warn("plugin-manager",`Failed to install default meta ${pkg}: ${err}`)}}let providerPkgs=new Set;for(let[metaPkg,metaPlugin]of this.getAllLoaded()){let mps=metaPlugin.metaProviders??[];if(mps.length>0)getDaemonProfile().logger.info("plugin-manager",`Meta ${metaPkg} declares ${mps.length} provider(s) (platform=${platform})`);for(let prov of mps)if(prov.defaultOn?.includes(platform))providerPkgs.add(prov.packageName)}if(getDaemonProfile().logger.info("plugin-manager",`Default providers for ${platform}: ${[...providerPkgs].join(", ")||"(none)"}`),!skipInstall)for(let pkg of providerPkgs){if(this.loaded.has(pkg))continue;try{getDaemonProfile().logger.info("plugin-manager",`Installing default provider ${pkg} (declared by a meta plugin)`),await this.install(pkg,{refreshLatest:!0}),newlyInstalled.push(pkg)}catch(err){getDaemonProfile().logger.warn("plugin-manager",`Failed to install default provider ${pkg}: ${err}`)}}let defaults=new Set([...metaPkgs,...providerPkgs]);for(let[packageName,plugin]of this.getAllLoaded()){if(!defaults.has(packageName))continue;try{let r=await runPluginPrereqs(plugin,packageName,app,this.db??null,{skipInstall});if(!r.noProtocol&&!r.satisfied){let pending=r.pendingSudo.map((p)=>p.name).join(", ")||"none";getDaemonProfile().logger.warn("plugin-manager",`${packageName}: prerequisites still unsatisfied after install (pendingSudo: ${pending})`)}}catch(err){getDaemonProfile().logger.warn("plugin-manager",`${packageName}: prereq provisioning failed: ${err}`)}}for(let pkg of newlyInstalled){let plugin=this.loaded.get(pkg);if(!plugin)continue;try{this.registerPluginProviders(plugin,hostServices);let wrapped=this.wrapHostServices(plugin,hostServices);if(plugin.onServerStart)await plugin.onServerStart(app,wrapped);if(plugin.onServerReady)await plugin.onServerReady(app,wrapped)}catch(err){getDaemonProfile().logger.warn("plugin-manager",`${pkg}: provider start failed: ${err}`)}}await this.electPlatformDefaultProviders(hostServices,platform)}inferProviderTypeForPlugin(hostServices,pluginName){for(let type of PROVIDER_TYPES)if(hostServices.serviceRegistry.listProvidersForType(type).some((e)=>e.pluginName===pluginName))return type;return}async electPlatformDefaultProviders(hostServices,platform){for(let[,metaPlugin]of this.getAllLoaded())for(let prov of metaPlugin.metaProviders??[]){if(!prov.pluginName)continue;if(!prov.defaultOn?.includes(platform))continue;let type=prov.providerType??this.inferProviderTypeForPlugin(hostServices,prov.pluginName);if(!type)continue;if(!hostServices.serviceRegistry.listProvidersForType(type).some((e)=>e.pluginName===prov.pluginName))continue;try{let existing=await this.getDefaultProvider(type);if(existing&&existing!==prov.pluginName)continue;if(hostServices.serviceRegistry.setProviderDefault(type,prov.pluginName),!existing)await this.setDefaultProvider(type,prov.pluginName).catch(()=>{});getDaemonProfile().logger.info("plugin-manager",`Elected platform-default '${type}' provider '${prov.pluginName}' for ${platform}`)}catch(err){getDaemonProfile().logger.warn("plugin-manager",`Failed to elect default '${type}' provider '${prov.pluginName}': ${err}`)}}}async dispatchServerStop(context){for(let plugin of this.getAllPlugins())if(plugin.onServerStop)try{await plugin.onServerStop(context)}catch(err){getDaemonProfile().logger.warn("plugin-manager",`onServerStop failed for ${plugin.name}: ${err}`)}}async runPluginNuke(packageName,hostServices,ctx){let targets=packageName?this.loaded.has(packageName)?[[packageName,this.loaded.get(packageName)]]:[]:Array.from(this.loaded.entries()),results=[];for(let[pkg,plugin]of targets){if(!plugin.onNuke)continue;try{let wrapped=this.wrapHostServices(plugin,hostServices),out=await plugin.onNuke(wrapped,ctx);results.push({plugin:pkg,ok:!0,reaped:out?.reaped??[],notes:out?.notes??[]}),getDaemonProfile().logger.info("plugin-manager",`onNuke ${ctx.dryRun?"(dry-run) ":""}completed for ${pkg}`,{reaped:out?.reaped??[]})}catch(err){let msg=err instanceof Error?err.message:String(err);results.push({plugin:pkg,ok:!1,reaped:[],notes:[],error:msg}),getDaemonProfile().logger.warn("plugin-manager",`onNuke failed for ${pkg}: ${msg}`)}}return{results}}async reloadAll(app,hostServices){await this.dispatchServerStop({reason:"reload"});for(let plugin of this.loaded.values())hostServices.serviceRegistry.unregisterPlugin(plugin.name);this.loaded.clear(),this.corePlugins.clear(),this.loadRegistry(),await this.loadCorePlugins(),await this.loadAll(),await this.dispatchServerStart(app,hostServices),await this.dispatchServerReady(app,hostServices)}sortAllByDependencies(){let allPlugins=this.getAllPlugins(),pluginMap=new Map;for(let plugin of allPlugins)pluginMap.set(plugin.name,plugin);let visited=new Set,visiting=new Set,sorted=[],visit=(name)=>{if(visited.has(name))return;if(visiting.has(name))throw Error(`Plugin dependency cycle detected at '${name}'`);let plugin=pluginMap.get(name);if(!plugin)return;if(visiting.add(name),plugin.dependencies)for(let dep of plugin.dependencies){if(!pluginMap.has(dep)){getDaemonProfile().logger.warn("plugin-manager",`Plugin '${plugin.name}' depends on missing plugin '${dep}'`);continue}visit(dep)}visiting.delete(name),visited.add(name),sorted.push(plugin)};for(let plugin of allPlugins)visit(plugin.name);return sorted}sortByDependencies(){let entries=Array.from(this.loaded.entries()),nameToPackage=new Map;for(let[pkg,plugin]of entries)nameToPackage.set(plugin.name,pkg);let visited=new Set,sorted=[],visit=(pkg)=>{if(visited.has(pkg))return;visited.add(pkg);let plugin=this.loaded.get(pkg);if(plugin?.dependencies)for(let dep of plugin.dependencies){let depPkg=nameToPackage.get(dep);if(depPkg&&this.loaded.has(depPkg))visit(depPkg)}let loadedPlugin=this.loaded.get(pkg);if(loadedPlugin)sorted.push([pkg,loadedPlugin])};for(let[pkg]of entries)visit(pkg);return sorted}getPluginByKey(key){for(let[,plugin]of this.loaded)if(plugin.name===key)return plugin;return this.corePlugins.get(key)}getAllPlugins(){let merged=new Map;for(let[key,plugin]of this.corePlugins)merged.set(key,plugin);for(let[,plugin]of this.loaded)merged.set(plugin.name,plugin);return Array.from(merged.values())}getAllPluginsByTag(tag){return this.getAllPlugins().filter((plugin)=>plugin.tags?.includes(tag)??!1)}resolvePluginChain(tokens){let allKeys=new Set;for(let p of this.getAllPlugins())allKeys.add(p.name);let chain=[],commandIdx=-1;for(let i=0;i<tokens.length;i++){if(tokens[i].startsWith("-")){commandIdx=i;break}if(allKeys.has(tokens[i]))chain.push(tokens[i]);else{commandIdx=i;break}}if(commandIdx===-1)return{chain,command:"",args:[]};return{chain,command:tokens[commandIdx],args:tokens.slice(commandIdx+1)}}async getDefaultProvider(type){if(!this.db)return null;return await this.db.getConfig(`${PROVIDER_DEFAULT_PREFIX}${type}`)??null}async setDefaultProvider(type,pluginName){if(!this.db)throw Error("Cannot set default provider: PluginManager was constructed without a database reference");if(!this.getPluginByKey(pluginName))throw Error(`Plugin '${pluginName}' not found`);await this.db.setConfig(`${PROVIDER_DEFAULT_PREFIX}${type}`,pluginName),getDaemonProfile().logger.info("plugin-manager",`Set default '${type}' provider to '${pluginName}'`)}getPluginDetails(){let coreInfos=this.getCorePluginDetails(),externalInfos=this.getExternalPluginDetails(),merged=new Map;for(let info of coreInfos)merged.set(info.pluginName,info);for(let info of externalInfos)merged.set(info.pluginName,info);return Array.from(merged.values())}getCorePluginDetails(){let infos=[];for(let[name,plugin]of this.corePlugins)infos.push({packageName:`@vibecontrols/plugin-${name}`,pluginName:name,version:plugin.version,description:plugin.description,tags:plugin.tags,cliCommand:plugin.cliCommand,apiPrefix:plugin.apiPrefix,dependencies:plugin.dependencies,installedAt:"",loaded:!0,isCore:!0,hasUI:!!plugin.ui,uiUrl:plugin.ui?`/ui/${name}`:void 0,hasCliSetup:!!plugin.onCliSetup,hasServerStart:!!plugin.onServerStart,hasServerStop:!!plugin.onServerStop,hasServerReady:!!plugin.onServerReady,hasProviders:!!(plugin.providers?.tunnel||plugin.providers?.session||plugin.providers?.ai)});return infos}getExternalPluginDetails(){return this.registry.map((entry)=>{let plugin=this.loaded.get(entry.packageName),catalogEntry=getCatalogEntry2(entry.pluginName);return{packageName:entry.packageName,pluginName:entry.pluginName,version:plugin?.version??entry.version,description:plugin?.description,tags:plugin?.tags,cliCommand:plugin?.cliCommand,apiPrefix:plugin?.apiPrefix,dependencies:plugin?.dependencies,installedAt:entry.installedAt,loaded:!!plugin,isCore:catalogEntry?.isCore===!0,hasUI:!!plugin?.ui,uiUrl:plugin?.ui?`/ui/${entry.pluginName}`:void 0,hasCliSetup:!!plugin?.onCliSetup,hasServerStart:!!plugin?.onServerStart,hasServerStop:!!plugin?.onServerStop,hasServerReady:!!plugin?.onServerReady,hasProviders:!!(plugin?.providers?.tunnel||plugin?.providers?.session||plugin?.providers?.ai)}})}getRegistry(){return[...this.registry]}getLoaded(packageName){return this.loaded.get(packageName)}getAllLoaded(){return new Map(this.loaded)}isInstalled(packageName){return this.registry.some((e)=>e.packageName===packageName)}isLoaded(packageName){return this.loaded.has(packageName)}}
5
- export{ServiceRegistry,PLUGIN_CATALOG,ABILITIES,CORE_PLUGIN_NAMES,getDefaultPluginsForAbilities,TRUSTED_PACKAGES,isCriticalPlugin,AVAILABLE_PLUGINS,getCatalogEntry,collectPluginBinaries,isTrustedPackage,resolvePluginByShortName,getPluginPackageRoot,validatePluginPackageName,DEFAULT_PLUGINS2 as DEFAULT_PLUGINS,PluginManager};