@vibecontrols/agent 2026.531.7 → 2026.531.9

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.
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{createApp}from"./index-ar7addvy.js";import"./index-926vt87h.js";import"./index-5krr8y92.js";import"./index-skmkfyzb.js";import"./index-95nmejfd.js";import"./index-34syaqa8.js";import"./index-y5q0m3cx.js";import"./index-yke24mr4.js";import"./index-kf5tas0g.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};
2
+ import{createApp}from"./index-her974n1.js";import"./index-926vt87h.js";import"./index-g9h64dn9.js";import"./index-skmkfyzb.js";import"./index-95nmejfd.js";import"./index-34syaqa8.js";import"./index-y5q0m3cx.js";import"./index-n3y918j2.js";import"./index-h6a1kkfk.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};
package/dist/cli.js CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
- import{pruneStaleBunBinShims}from"./index-6xb3dqrh.js";import{listInstalledPrereqs}from"./index-23rdsqea.js";import{runAliasInherit}from"./index-9e1fgxea.js";import{checkDependencies,installDependencies}from"./index-fg47j98r.js";import{clearTunnelState,getBootstrapTunnelUrl,isProcessAlive,listPersistedTunnels,readTunnelState}from"./index-95nmejfd.js";import{ServiceManager}from"./index-34syaqa8.js";import{REDACTED_VALUE,redactUnknownSecrets}from"./index-y5q0m3cx.js";import{CliContributorRegistry,createIframeBridge,getActiveContributorRegistry,setActiveContributorRegistry}from"./index-yke24mr4.js";import{ABILITIES,PLUGIN_CATALOG,PluginManager,ServiceRegistry,collectPluginBinaries,getDefaultPluginsForAbilities,resolvePluginByShortName}from"./index-kf5tas0g.js";import{getOsAdapter}from"./index-srbb2214.js";import{telemetryService}from"./index-sfjbh6fa.js";import{validateEvent}from"./index-3jez1q8j.js";import{loadAgentApiKey}from"./index-b4wy3jrt.js";import"./index-d3mz9vws.js";import"./index-rnk0kny8.js";import{Command}from"./index-qbvtba0e.js";import{apiDelete,apiGet,apiPost,apiPut,getAgentUrl,isInteractive,maybePrintJson,pickOutputMode,promptConfirm,resolveApiKey,resolveProfileName,runMultimode}from"./index-wvabz3xh.js";import{blank,colors,errMsg,fail,formatStatus,formatTable,header,icons,info,kv,printAgentDetails,setColorsEnabled,shortId,success,timeAgo,warn}from"./index-r0qezdp7.js";import{interactiveDetail,interactiveTable,stripAnsi}from"./index-campp0wv.js";import{BUILTIN_PROFILE_SEEDS,NAMED_ENV_PRESETS,applyAgentConfigToEnv,assertValidProfileName,buildProfileSeed,clearAllSecrets,deleteProfile,ensureProfilesInitialized,getAgentConfigDefaults,getAgentConfigPath,getProfilePath,getSecret,listProfileNames,previewClearAllSecrets,readActiveProfileName,readAgentConfig,readProfile,writeActiveProfileName,writeAgentConfig,writeProfile}from"./index-2pqv0bya.js";import{assertAllowedGatewayUrl,gatewayClient,getDaemonProfile}from"./index-7pdmqbj8.js";import{getPluginRegistry,getProfileDataDir,getVibecontrolsDir,getVibecontrolsProductDir,getVibecontrolsProfile,getVibecontrolsProfilesDir}from"./index-bysm7taq.js";import"./index-zs58d1hc.js";import{__require}from"./index-e9rt4m94.js";import{join as join14}from"path";import{existsSync as existsSync2}from"fs";import{join as join2}from"path";import{createServer}from"net";function isPortAvailable(port,host="0.0.0.0"){return new Promise((resolve)=>{let server=createServer();server.once("error",()=>resolve(!1)),server.once("listening",()=>{server.close(()=>resolve(!0))}),server.listen({host,port,exclusive:!0})})}async function findFreePortFrom(startPort,host="0.0.0.0"){let port=startPort;while(!await isPortAvailable(port,host))if(port++,port>65535)throw Error(`No free port found starting from ${startPort}`);return port}import{existsSync,readFileSync,unlinkSync,writeFileSync}from"fs";import{join}from"path";var CONSENT_FILENAME=".consent.json";function readConsentAbilities(productDir){try{let raw=readFileSync(consentPath(productDir),"utf8"),rec=JSON.parse(raw);if(Array.isArray(rec.abilities)&&rec.abilities.length>0)return new Set(rec.abilities)}catch{}return null}function consentPath(productDir){return join(productDir,CONSENT_FILENAME)}function hasConsent(productDir){return existsSync(consentPath(productDir))}function getPlannedInstall(options,selectedAbilities){let abilities=selectedAbilities??new Set(ABILITIES.filter((a)=>a.defaultSelected||a.mandatory).map((a)=>a.key)),plugins=options.skipPluginInstall?[]:getDefaultPluginsForAbilities(process.platform,abilities).filter((p)=>!options.skipPlugins.includes(p.packageName)&&!options.skipPlugins.includes(p.pluginName)).map((p)=>({packageName:p.packageName,pluginName:p.pluginName,reason:p.description}));return{tools:[],plugins}}async function promptAbilitySelection(){let defaults=new Set(ABILITIES.filter((a)=>a.defaultSelected||a.mandatory).map((a)=>a.key));for(let a of ABILITIES)if(a.mandatory)defaults.add(a.key);if(!(Boolean(process.stdin.isTTY)&&process.env.VIBE_AUTO_ACCEPT!=="1"))return defaults;try{let{interactiveCheckboxes}=await import("./interactive-v8zwz6wf.js"),result=await interactiveCheckboxes("Select the agent abilities to install",ABILITIES.map((a)=>({key:a.key,label:a.label,description:a.description,mandatory:a.mandatory})),defaults);if(result){for(let a of ABILITIES)if(a.mandatory)result.add(a.key);return result}return defaults}catch{return defaults}}function parseAbilityKeys(csv){let valid=new Set(ABILITIES.map((a)=>a.key)),out=new Set;for(let tok of csv.split(",").map((s)=>s.trim().toLowerCase()))if(valid.has(tok))out.add(tok);for(let a of ABILITIES)if(a.mandatory)out.add(a.key);return out}function defaultAbilityKeys(){return new Set(ABILITIES.filter((a)=>a.defaultSelected||a.mandatory).map((a)=>a.key))}function persistConsent(productDir,plan,selectedAbilities,agentVersion){let record={acceptedAt:new Date().toISOString(),agentVersion,abilities:[...selectedAbilities],tools:plan.tools.map((t)=>({name:t.name,reason:t.reason})),plugins:plan.plugins.map((p)=>({packageName:p.packageName,reason:p.reason}))};writeFileSync(consentPath(productDir),JSON.stringify(record,null,2))}function register(program){program.command("start").description("Start a VibeControls agent instance").option("-p, --port <port>","Port to listen on. Default: 3005 for the 'default' profile, deterministic 3100-3399 for any other profile (FNV-1a hash) so multiple profiles run side-by-side without EADDRINUSE.").option("-n, --name <name>","Agent instance name","default").option("-f, --foreground","Run in foreground mode (default: daemon)",!1).option("--db-path <path>","Path to the agent storage directory").option("--profile <profile>","Profile name for isolated config (env: VIBECONTROLS_PROFILE)").option("--host <host>","Host to bind to","0.0.0.0").option("--skip-plugin-install","Skip automatic installation of default plugins",!1).option("--skip-plugin <name>","Skip a specific default plugin (repeatable). Accepts the short pluginName or the full package name.",(value,prev=[])=>[...prev,value],[]).option("--no-install-deps","Skip auto-installing missing tools (installed by their plugins on start by default)").option("-y, --yes","Skip the first-run install consent prompt. Equivalent to VIBE_AUTO_ACCEPT=1; useful for CI / Docker / nohup contexts.",!1).option("--client-id <id>","Gateway OAuth client ID (env: VIBE_CLIENT_ID)").option("--client-secret <secret>","Gateway OAuth client secret (env: VIBE_CLIENT_SECRET)").option("--global-gateway-url <url>","Global gateway URL (env: VIBE_GLOBAL_GATEWAY_URL)").option("--workspace-gateway-url <url>","Workspace gateway URL (env: VIBE_WORKSPACE_GATEWAY_URL)").option("--workspace-id <id>","Workspace ID for auto-report (env: VIBE_WORKSPACE_ID)").option("--isolate <plugins>","Comma-separated list of plugin names to force into worker_threads isolation (Phase 4 hostile-plugin mode). Sets VIBE_ISOLATE_PLUGINS in the daemon env.").option("--profiles <names>","Comma-separated list of profiles to host in this daemon (multi-profile boot). When unset, the daemon hosts a single profile resolved via --profile / VIBECONTROLS_PROFILE / 'default'. Sets VIBECONTROLS_PROFILES in the daemon env so app boot can spin up additional ProfileContexts via the in-process registry.").option("--strict-key-fetch","Refuse to boot if any profile's encryption-key fetch fails. Default lenient: a failed profile is marked degraded and the daemon stays up. Sets VIBE_STRICT_KEY_FETCH=1 in the daemon env.",!1).option("--json","Emit JSON").option("--plain","Plain text output (no interactive TUI). Implied for non-TTY / CI.").option("--abilities <list>","Comma-separated ability keys to install non-interactively (e.g. session,ai,gitops). Storage/tunnel/backup are always included.").option("--wait-ready [seconds]","Block until the agent is fully ready (or fails). Polls /health/ready and renders phase transitions live. Without a value, defaults to 60s. Exits non-zero if the agent ends up degraded or times out. Useful for scripts/CI.").option("--no-wait","Skip the phase tracker entirely after spawning the daemon. Restores the old fire-and-print behavior \u2014 for users who want the previous quick-return UX.").action(async function(opts){let merged={...program.opts(),...opts};try{let defaultPortForProfile=function(profileName){if(profileName==="default")return 3005;let h=2166136261;for(let i=0;i<profileName.length;i++)h=Math.imul(h^profileName.charCodeAt(i),16777619);return 3100+Math.abs(h)%300},serviceManager=new ServiceManager,profile=opts.profile||process.env.VIBECONTROLS_PROFILE||"default";if(process.env.VIBECONTROLS_PROFILE=profile,typeof opts.isolate==="string"&&opts.isolate.length>0)process.env.VIBE_ISOLATE_PLUGINS=opts.isolate;if(typeof opts.profiles==="string"&&opts.profiles.length>0){let names=opts.profiles.split(",").map((s)=>s.trim()).filter(Boolean);if(names.length>0){if(process.env.VIBECONTROLS_PROFILES=names.join(","),process.env.VIBECONTROLS_PROFILE=names[0],names.length>1)warn(`--profiles received ${names.length} entries; daemon boots with '${names[0]}'. Remaining (${names.slice(1).join(", ")}) will be attached via /api/profiles after listen.`)}}if(opts.strictKeyFetch===!0)process.env.VIBE_STRICT_KEY_FETCH="1";applyAgentConfigToEnv();let dbPath=opts.dbPath||getProfileDataDir(),productDir=getVibecontrolsProductDir(),firstRun=!existsSync2(dbPath)&&!existsSync2(join2(productDir,"agents.json")),outputMode=pickOutputMode(merged),canPromptInteractively=outputMode!=="json"&&outputMode!=="plain"&&isInteractive()&&opts.yes!==!0,selectedAbilities;if(typeof merged.abilities==="string"&&merged.abilities.trim()!=="")selectedAbilities=parseAbilityKeys(merged.abilities);else if(hasConsent(productDir))selectedAbilities=readConsentAbilities(productDir)??defaultAbilityKeys();else if(canPromptInteractively)selectedAbilities=await promptAbilitySelection();else selectedAbilities=defaultAbilityKeys();if(!hasConsent(productDir)){let plan=getPlannedInstall({installDeps:opts.installDeps===!0,skipPluginInstall:opts.skipPluginInstall===!0,skipPlugins:Array.isArray(opts.skipPlugin)?opts.skipPlugin:[]},selectedAbilities);if(firstRun&&plan.plugins.length>0)blank(),info(`Installing ${plan.plugins.length} plugin(s) for the selected abilities.`),blank();persistConsent(productDir,plan,selectedAbilities,process.env.VIBE_AGENT_VERSION)}if(firstRun){info("First run detected \u2014 running setup..."),blank();let skipPlugins=Array.isArray(opts.skipPlugin)?opts.skipPlugin:[],plannedPlugins=opts.skipPluginInstall?[]:getDefaultPluginsForAbilities(process.platform,selectedAbilities).filter((p)=>!skipPlugins.includes(p.packageName)&&!skipPlugins.includes(p.pluginName)).map((p)=>p.packageName),pluginBinaries=collectPluginBinaries(plannedPlugins),missing=checkDependencies(pluginBinaries).filter((d)=>!d.installed);if(missing.length>0)if(warn(`Missing tools: ${missing.map((d)=>d.name).join(", ")}`),opts.installDeps)info("Their plugins will install them automatically on startup.");else info("Auto-install skipped (`--no-install-deps`) \u2014 install them yourself or drop the flag.");else success("All plugin tools present.");blank()}if(!opts.skipPluginInstall){let skipPlugins=Array.isArray(opts.skipPlugin)?opts.skipPlugin:[],pluginManager=new PluginManager;await pluginManager.loadCorePlugins(),await pluginManager.loadAll();let installed=await pluginManager.ensureDefaultPlugins((message)=>{if(message.startsWith("No "))warn(message);else if(message.startsWith("Installed "))success(message);else if(message.startsWith("Failed "))warn(message);else info(message)},skipPlugins,selectedAbilities);if(installed.length>0)success(`Auto-installed ${installed.length} default plugin${installed.length>1?"s":""}.`),blank()}let resolvedProfile=opts.profile||process.env.VIBECONTROLS_PROFILE||opts.name||"default",port=opts.port?parseInt(opts.port,10):defaultPortForProfile(resolvedProfile);if(isNaN(port)||port<1||port>65535)fail("Invalid port number. Must be between 1 and 65535.");let availablePort=await findFreePortFrom(port);if(availablePort!==port)warn(`Port ${port} is in use. Auto-selecting port ${colors.bold(String(availablePort))} instead.`),port=availablePort;let host=opts.host,agentUrl=`http://${host==="0.0.0.0"?"localhost":host}:${port}`,clientId=opts.clientId||process.env.VIBE_CLIENT_ID,clientSecret=opts.clientSecret||process.env.VIBE_CLIENT_SECRET,globalGatewayUrl=opts.globalGatewayUrl||process.env.VIBE_GLOBAL_GATEWAY_URL,workspaceGatewayUrl=opts.workspaceGatewayUrl||process.env.VIBE_WORKSPACE_GATEWAY_URL,workspaceId=opts.workspaceId||process.env.VIBE_WORKSPACE_ID;if(clientId&&!clientSecret)fail("--client-secret is required when --client-id is provided.");if(clientSecret&&!clientId)fail("--client-id is required when --client-secret is provided.");if(clientId&&clientSecret){if(!globalGatewayUrl&&!process.env.VIBE_GLOBAL_GATEWAY_URL)fail("--global-gateway-url is required when providing client credentials (none set in env).");if(process.env.VIBE_CLIENT_ID=clientId,process.env.VIBE_CLIENT_SECRET=clientSecret,globalGatewayUrl)process.env.VIBE_GLOBAL_GATEWAY_URL=globalGatewayUrl;let{writeAgentConfig:writeAgentConfig2}=await import("./agent-config-y63ddxgy.js");if(writeAgentConfig2({clientId,clientSecret,workspaceId,globalGatewayUrl,workspaceGatewayUrl}),workspaceGatewayUrl)process.env.VIBE_WORKSPACE_GATEWAY_URL=workspaceGatewayUrl;if(workspaceId)process.env.VIBE_WORKSPACE_ID=workspaceId;success("Gateway credentials staged in env. Agent will authenticate and persist them on startup."),blank()}else if(workspaceGatewayUrl||workspaceId||globalGatewayUrl){if(warn("Workspace options provided without --client-id / --client-secret \u2014 they will be staged in env but unused until credentials are configured."),workspaceGatewayUrl)process.env.VIBE_WORKSPACE_GATEWAY_URL=workspaceGatewayUrl;if(workspaceId)process.env.VIBE_WORKSPACE_ID=workspaceId;if(globalGatewayUrl)process.env.VIBE_GLOBAL_GATEWAY_URL=globalGatewayUrl;blank()}if(opts.foreground){if(!merged.json)header("Starting agent in foreground"),kv("Name",opts.name),kv("Port",String(port)),kv("Host",host),kv("Database",dbPath),blank();let{bootstrapWorkspace}=await import("./bootstrap-workspace-qwed8tfg.js");bootstrapWorkspace();let{createApp}=await import("./app-fk5c313e.js"),appInstance=await createApp({port,host,dbPath});if(await appInstance.start(),clientId&&clientSecret&&workspaceId&&globalGatewayUrl&&workspaceGatewayUrl){let result=await appInstance.finalize({clientId,clientSecret,workspaceId,globalGatewayUrl,workspaceGatewayUrl});if(!result.ok)warn(`Finalize failed \u2014 agent remains in awaiting-config state: ${result.error}`)}if(maybePrintJson(merged,{ok:!0,name:opts.name,port,host,pid:process.pid,url:agentUrl}));else await printAgentDetails(agentUrl);let shutdown=async()=>{await appInstance.stop(),process.exit(0)};process.on("SIGTERM",shutdown),process.on("SIGINT",shutdown)}else{if(!merged.json)header("Starting agent in daemon mode"),kv("Name",opts.name),kv("Port",String(port)),kv("Host",host),kv("Database",dbPath),blank();if(opts.installDeps===!1)process.env.VIBE_SKIP_PREREQ_INSTALL="1";await serviceManager.startDaemon({port,name:opts.name,daemon:!0,dbPath,host,profile});let actualPort=(await serviceManager.getStatus(opts.name))?.port??port,actualAgentUrl=`http://${host==="0.0.0.0"?"localhost":host}:${actualPort}`,waitReady=opts.waitReady,noWait=opts.wait===!1,requestedBlocking=waitReady!==void 0;if(noWait&&requestedBlocking)warn("--wait-ready is ignored because --no-wait was also passed.");let blocking=!noWait&&requestedBlocking,shouldRunTracker=!noWait&&(blocking||!merged.json),timeoutMs=(()=>{let fromFlag=typeof waitReady==="string"?Number.parseInt(waitReady,10):NaN;if(Number.isInteger(fromFlag)&&fromFlag>0)return fromFlag*1000;return blocking?60000:25000})();if(merged.json){if(shouldRunTracker){let{trackAgentReady}=await import("./agent-ready-tracker-5yq97296.js"),result=await trackAgentReady(actualAgentUrl,{timeoutMs,verbose:!1});if(blocking&&(result.outcome==="degraded"||result.outcome==="timeout"))process.exitCode=1;maybePrintJson(merged,{ok:result.outcome==="ready"||result.outcome==="awaiting-config",name:opts.name,port:actualPort,host,url:actualAgentUrl,abilities:[...selectedAbilities],outcome:result.outcome,bootState:result.bootState,degradedReasons:result.degradedReasons,summary:result.summary})}else maybePrintJson(merged,{ok:!0,name:opts.name,port:actualPort,host,url:actualAgentUrl});return}if(await printAgentDetails(actualAgentUrl),shouldRunTracker){let{trackAgentReady}=await import("./agent-ready-tracker-5yq97296.js");blank();let result=await trackAgentReady(actualAgentUrl,{timeoutMs,verbose:!0});if(blocking&&(result.outcome==="degraded"||result.outcome==="timeout"))process.exitCode=1}}}catch(err){let message=err instanceof Error?errMsg(err):String(err);if(merged.json){maybePrintJson(merged,{ok:!1,error:message});return}fail(`Failed to start agent: ${message}`)}})}function register2(program){program.command("stop").description("Stop a running VibeControls agent instance").option("-n, --name <name>","Agent instance name","default").option("--all","Stop all running agent instances",!1).option("--json","Emit JSON").action(async function(opts){let merged={...program.opts(),...opts};try{let serviceManager=new ServiceManager;if(opts.all){let instances=await serviceManager.listInstances();if(!instances||instances.length===0){if(maybePrintJson(merged,{ok:!0,stopped:[]}))return;header("Stopping all agent instances"),blank(),info(`${icons.info} No running agent instances found.`);return}let stoppedNames=[];if(!merged.json)header("Stopping all agent instances"),blank();for(let instance of instances)try{if(await serviceManager.stop(instance.name),stoppedNames.push(instance.name),!merged.json)success(`${icons.success} Stopped ${colors.bold(instance.name)}`)}catch{if(!merged.json)fail(`Failed to stop ${colors.bold(instance.name)}`)}if(maybePrintJson(merged,{ok:!0,stopped:stoppedNames,total:instances.length}))return;blank(),success(`${icons.success} Stopped ${stoppedNames.length}/${instances.length} instance(s).`)}else{if(await serviceManager.stop(opts.name),maybePrintJson(merged,{ok:!0,name:opts.name}))return;header(`Stopping agent: ${opts.name}`),blank(),success(`${icons.success} Agent ${colors.bold(opts.name)} stopped.`)}}catch(err){if(merged.json){maybePrintJson(merged,{ok:!1,error:errMsg(err)});return}fail(`Failed to stop agent: ${errMsg(err)}`)}})}function register3(program){program.command("restart").description("Restart a running VibeControls agent instance").option("-n, --name <name>","Agent instance name","default").option("-p, --port <port>","Port to listen on","3005").option("--db-path <path>","Path to the agent storage directory","./agent-db").option("--json","Emit JSON").action(async function(opts){let merged={...program.opts(),...opts};try{let serviceManager=new ServiceManager;if(!merged.json)header(`Restarting agent: ${opts.name}`),blank(),info(`${icons.info} Stopping agent ${colors.bold(opts.name)}...`);try{if(await serviceManager.stop(opts.name),!merged.json)success(`${icons.success} Agent stopped.`)}catch{if(!merged.json)info(`${icons.info} Agent was not running.`)}let port=parseInt(opts.port,10);if(isNaN(port)||port<1||port>65535){if(merged.json){maybePrintJson(merged,{ok:!1,error:"Invalid port number"});return}fail("Invalid port number. Must be between 1 and 65535.");return}let config={port,name:opts.name,daemon:!0,dbPath:opts.dbPath};if(!merged.json)blank(),info(`${icons.info} Starting agent ${colors.bold(opts.name)}...`);await serviceManager.startDaemon(config);let agentUrl=`http://localhost:${port}`;if(maybePrintJson(merged,{ok:!0,name:opts.name,port,url:agentUrl}))return;blank(),success(`${icons.success} Agent ${colors.bold(opts.name)} restarted.`),blank(),kv("Port",String(port)),kv("Database",opts.dbPath),blank(),printAgentDetails(agentUrl)}catch(err){if(merged.json){maybePrintJson(merged,{ok:!1,error:errMsg(err)});return}fail(`Failed to restart agent: ${errMsg(err)}`)}})}import{existsSync as existsSync3,readFileSync as readFileSync2,unlinkSync as unlinkSync2}from"fs";import{join as join3}from"path";function readProfileRuntime(profileName){let runtimePath=join3(getVibecontrolsProfilesDir(),profileName,"runtime.json");if(!existsSync3(runtimePath))return null;try{let data=JSON.parse(readFileSync2(runtimePath,"utf8"));if(typeof data.pid!=="number")return null;return{...data,pid:data.pid,path:runtimePath}}catch{return null}}async function killAgentProfile(profileName){let rt=readProfileRuntime(profileName);if(!rt)return null;if(!isProcessAlive(rt.pid)){try{unlinkSync2(rt.path)}catch{}return`agent pid=${rt.pid} (${profileName}) already gone (cleaned runtime.json).`}let osAdapter=getOsAdapter();if(!osAdapter.killProcessTree(rt.pid,"SIGTERM"))return`failed to SIGTERM agent pid=${rt.pid}.`;if(await new Promise((r)=>setTimeout(r,3000)),isProcessAlive(rt.pid))osAdapter.killProcessTree(rt.pid,"SIGKILL");try{unlinkSync2(rt.path)}catch{}return`agent ${profileName} pid=${rt.pid}${rt.port?` (port ${rt.port})`:""} killed.`}async function killProfileTunnel(profileName){let dir=join3(getVibecontrolsProfilesDir(),profileName),state=readTunnelState(dir);if(!state)return null;if(!isProcessAlive(state.pid))return clearTunnelState(dir),`tunnel pid=${state.pid} already gone (cleaned state).`;let osAdapter=getOsAdapter();if(!osAdapter.killProcessTree(state.pid,"SIGTERM"))return`failed to SIGTERM tunnel pid=${state.pid}.`;if(await new Promise((r)=>setTimeout(r,3000)),isProcessAlive(state.pid))osAdapter.killProcessTree(state.pid,"SIGKILL");return clearTunnelState(dir),`tunnel ${state.provider} pid=${state.pid} (${state.url??"no url"}) killed.`}function register4(program){program.command("kill").description("Force-kill an agent instance and its tunnel. Defaults to active profile.").option("-n, --name <name>","Agent instance name (alias of --profile, kept for back-compat)").option("--profile <name>","Kill a specific profile (overrides --name and VIBECONTROLS_PROFILE)").option("--all","Kill every agent instance and every profile's tunnel",!1).option("--json","Emit JSON").action(async function(opts){let merged={...program.opts(),...opts},killedAll=[];try{let serviceManager=new ServiceManager;if(opts.all){if(!merged.json)header("Force killing all agent instances + tunnels"),blank();let instances=await serviceManager.listInstances()??[],killedAgents=0,seenProfiles=new Set;for(let instance2 of instances)try{if(await serviceManager.kill(instance2.name),!merged.json)success(`${icons.success} agent ${colors.bold(instance2.name)} (pid=${instance2.pid||"?"}) killed.`);killedAll.push(instance2.name),killedAgents++,seenProfiles.add(instance2.name)}catch{if(!merged.json)warn(`${icons.warning} could not kill agent ${instance2.name}.`)}try{let fs=await import("fs"),agentsDir=getVibecontrolsProfilesDir(),entries=fs.existsSync(agentsDir)?fs.readdirSync(agentsDir):[];for(let profile of entries){if(seenProfiles.has(profile))continue;let rtResult=await killAgentProfile(profile);if(rtResult)success(`${icons.success} ${rtResult}`),killedAgents++}}catch(err){warn(`${icons.warning} runtime.json sweep failed: ${err instanceof Error?errMsg(err):String(err)}`)}let tunnels=listPersistedTunnels({allProfiles:!0}),killedTunnels=0;for(let t of tunnels){if(!t.alive){clearTunnelState(t.profileDir);continue}let osAdapter=getOsAdapter();if(osAdapter.killProcessTree(t.pid,"SIGTERM"),await new Promise((r)=>setTimeout(r,3000)),isProcessAlive(t.pid))osAdapter.killProcessTree(t.pid,"SIGKILL");clearTunnelState(t.profileDir),success(`${icons.success} tunnel ${t.provider} pid=${t.pid} (${t.url??"no url"}, ${t.profileDir.split("/").pop()}) killed.`),killedTunnels++}if(maybePrintJson(merged,{ok:!0,killed:killedAll,tunnels:killedTunnels}))return;blank(),success(`${icons.success} killed ${killedAgents} agent(s) and ${killedTunnels} tunnel(s).`);return}let profileName=opts.profile||opts.name||getVibecontrolsProfile();if(!merged.json)header(`Force killing profile: ${profileName}`),blank();let instance=await serviceManager.getStatus(profileName);if(instance){if(await serviceManager.kill(profileName),killedAll.push(profileName),!merged.json)success(`${icons.success} agent ${colors.bold(profileName)} pid=${instance.pid||"?"} killed.`)}else{let rtResult=await killAgentProfile(profileName);if(rtResult){if(killedAll.push(profileName),!merged.json)success(`${icons.success} ${rtResult}`)}else if(!merged.json)info(`${icons.info} no running agent service for profile ${profileName}.`)}let tunnelResult=await killProfileTunnel(profileName);if(tunnelResult){if(!merged.json)success(`${icons.success} ${tunnelResult}`)}else if(!merged.json)info(`${icons.info} no tunnel recorded for profile ${profileName}.`);maybePrintJson(merged,{ok:!0,killed:killedAll})}catch(err){if(merged.json){maybePrintJson(merged,{ok:!1,error:errMsg(err)});return}fail(`Failed to kill: ${errMsg(err)}`)}})}function register5(program){program.command("list").alias("ls").description("List all VibeControls agent instances").option("--json","Emit JSON").option("--plain","Force plain text output").action(async function(opts){try{let merged={...program.opts(),...opts},sm=new ServiceManager;await runMultimode({mode:pickOutputMode(merged),fetchData:()=>sm.listInstances(),plain:(instances)=>{if(header("Agent Instances"),blank(),!instances||instances.length===0){info(`${icons.info} No agent instances found.`),info(`Run ${colors.bold("vibe start")} to start an agent.`);return}let rows=instances.map((inst)=>({Name:inst.name,Status:formatStatus(inst.status),PID:inst.pid||"-",Port:inst.port||"-",Host:inst.config?.host||"-",Database:inst.config?.dbPath||"-",Started:inst.startTime?timeAgo(inst.startTime):"-"}));formatTable(rows),blank();let running=instances.filter((i)=>i.status==="running").length,stopped=instances.length-running;info(`${icons.info} ${instances.length} instance(s): ${colors.green(String(running))} running, ${colors.dim(String(stopped))} stopped`)},interactive:async(instances)=>{if(!instances||instances.length===0){header("Agent Instances"),blank(),info(`${icons.info} No agent instances found.`),info(`Run ${colors.bold("vibe start")} to start an agent.`);return}let rows=instances.map((inst)=>{let lines=[`${colors.bold(inst.name)} ${formatStatus(inst.status)}`,"",` PID: ${inst.pid??"-"}`,` Port: ${inst.port??"-"}`,` Host: ${inst.config?.host??"-"}`,` Database: ${inst.config?.dbPath??"-"}`,` Started: ${inst.startTime?timeAgo(inst.startTime):"-"}`];return{id:inst.name,label:inst.name,hint:inst.status==="running"?"running":"stopped",detail:lines.join(`
3
+ import{pruneStaleBunBinShims}from"./index-6xb3dqrh.js";import{listInstalledPrereqs}from"./index-23rdsqea.js";import{runAliasInherit}from"./index-9e1fgxea.js";import{checkDependencies,installDependencies}from"./index-fg47j98r.js";import{clearTunnelState,getBootstrapTunnelUrl,isProcessAlive,listPersistedTunnels,readTunnelState}from"./index-95nmejfd.js";import{ServiceManager}from"./index-34syaqa8.js";import{REDACTED_VALUE,redactUnknownSecrets}from"./index-y5q0m3cx.js";import{CliContributorRegistry,createIframeBridge,getActiveContributorRegistry,setActiveContributorRegistry}from"./index-n3y918j2.js";import{ABILITIES,PLUGIN_CATALOG,PluginManager,ServiceRegistry,collectPluginBinaries,getDefaultPluginsForAbilities,resolvePluginByShortName}from"./index-h6a1kkfk.js";import{getOsAdapter}from"./index-srbb2214.js";import{telemetryService}from"./index-sfjbh6fa.js";import{validateEvent}from"./index-3jez1q8j.js";import{loadAgentApiKey}from"./index-b4wy3jrt.js";import"./index-d3mz9vws.js";import"./index-rnk0kny8.js";import{Command}from"./index-qbvtba0e.js";import{apiDelete,apiGet,apiPost,apiPut,getAgentUrl,isInteractive,maybePrintJson,pickOutputMode,promptConfirm,resolveApiKey,resolveProfileName,runMultimode}from"./index-wvabz3xh.js";import{blank,colors,errMsg,fail,formatStatus,formatTable,header,icons,info,kv,printAgentDetails,setColorsEnabled,shortId,success,timeAgo,warn}from"./index-r0qezdp7.js";import{interactiveDetail,interactiveTable,stripAnsi}from"./index-campp0wv.js";import{BUILTIN_PROFILE_SEEDS,NAMED_ENV_PRESETS,applyAgentConfigToEnv,assertValidProfileName,buildProfileSeed,clearAllSecrets,deleteProfile,ensureProfilesInitialized,getAgentConfigDefaults,getAgentConfigPath,getProfilePath,getSecret,listProfileNames,previewClearAllSecrets,readActiveProfileName,readAgentConfig,readProfile,writeActiveProfileName,writeAgentConfig,writeProfile}from"./index-2pqv0bya.js";import{assertAllowedGatewayUrl,gatewayClient,getDaemonProfile}from"./index-7pdmqbj8.js";import{getPluginRegistry,getProfileDataDir,getVibecontrolsDir,getVibecontrolsProductDir,getVibecontrolsProfile,getVibecontrolsProfilesDir}from"./index-bysm7taq.js";import"./index-zs58d1hc.js";import{__require}from"./index-e9rt4m94.js";import{join as join14}from"path";import{existsSync as existsSync2}from"fs";import{join as join2}from"path";import{createServer}from"net";function isPortAvailable(port,host="0.0.0.0"){return new Promise((resolve)=>{let server=createServer();server.once("error",()=>resolve(!1)),server.once("listening",()=>{server.close(()=>resolve(!0))}),server.listen({host,port,exclusive:!0})})}async function findFreePortFrom(startPort,host="0.0.0.0"){let port=startPort;while(!await isPortAvailable(port,host))if(port++,port>65535)throw Error(`No free port found starting from ${startPort}`);return port}import{existsSync,readFileSync,unlinkSync,writeFileSync}from"fs";import{join}from"path";var CONSENT_FILENAME=".consent.json";function readConsentAbilities(productDir){try{let raw=readFileSync(consentPath(productDir),"utf8"),rec=JSON.parse(raw);if(Array.isArray(rec.abilities)&&rec.abilities.length>0)return new Set(rec.abilities)}catch{}return null}function consentPath(productDir){return join(productDir,CONSENT_FILENAME)}function hasConsent(productDir){return existsSync(consentPath(productDir))}function getPlannedInstall(options,selectedAbilities){let abilities=selectedAbilities??new Set(ABILITIES.filter((a)=>a.defaultSelected||a.mandatory).map((a)=>a.key)),plugins=options.skipPluginInstall?[]:getDefaultPluginsForAbilities(process.platform,abilities).filter((p)=>!options.skipPlugins.includes(p.packageName)&&!options.skipPlugins.includes(p.pluginName)).map((p)=>({packageName:p.packageName,pluginName:p.pluginName,reason:p.description}));return{tools:[],plugins}}async function promptAbilitySelection(){let defaults=new Set(ABILITIES.filter((a)=>a.defaultSelected||a.mandatory).map((a)=>a.key));for(let a of ABILITIES)if(a.mandatory)defaults.add(a.key);if(!(Boolean(process.stdin.isTTY)&&process.env.VIBE_AUTO_ACCEPT!=="1"))return defaults;try{let{interactiveCheckboxes}=await import("./interactive-v8zwz6wf.js"),result=await interactiveCheckboxes("Select the agent abilities to install",ABILITIES.map((a)=>({key:a.key,label:a.label,description:a.description,mandatory:a.mandatory})),defaults);if(result){for(let a of ABILITIES)if(a.mandatory)result.add(a.key);return result}return defaults}catch{return defaults}}function parseAbilityKeys(csv){let valid=new Set(ABILITIES.map((a)=>a.key)),out=new Set;for(let tok of csv.split(",").map((s)=>s.trim().toLowerCase()))if(valid.has(tok))out.add(tok);for(let a of ABILITIES)if(a.mandatory)out.add(a.key);return out}function defaultAbilityKeys(){return new Set(ABILITIES.filter((a)=>a.defaultSelected||a.mandatory).map((a)=>a.key))}function persistConsent(productDir,plan,selectedAbilities,agentVersion){let record={acceptedAt:new Date().toISOString(),agentVersion,abilities:[...selectedAbilities],tools:plan.tools.map((t)=>({name:t.name,reason:t.reason})),plugins:plan.plugins.map((p)=>({packageName:p.packageName,reason:p.reason}))};writeFileSync(consentPath(productDir),JSON.stringify(record,null,2))}function register(program){program.command("start").description("Start a VibeControls agent instance").option("-p, --port <port>","Port to listen on. Default: 3005 for the 'default' profile, deterministic 3100-3399 for any other profile (FNV-1a hash) so multiple profiles run side-by-side without EADDRINUSE.").option("-n, --name <name>","Agent instance name","default").option("-f, --foreground","Run in foreground mode (default: daemon)",!1).option("--db-path <path>","Path to the agent storage directory").option("--profile <profile>","Profile name for isolated config (env: VIBECONTROLS_PROFILE)").option("--host <host>","Host to bind to","0.0.0.0").option("--skip-plugin-install","Skip automatic installation of default plugins",!1).option("--skip-plugin <name>","Skip a specific default plugin (repeatable). Accepts the short pluginName or the full package name.",(value,prev=[])=>[...prev,value],[]).option("--no-install-deps","Skip auto-installing missing tools (installed by their plugins on start by default)").option("-y, --yes","Skip the first-run install consent prompt. Equivalent to VIBE_AUTO_ACCEPT=1; useful for CI / Docker / nohup contexts.",!1).option("--client-id <id>","Gateway OAuth client ID (env: VIBE_CLIENT_ID)").option("--client-secret <secret>","Gateway OAuth client secret (env: VIBE_CLIENT_SECRET)").option("--global-gateway-url <url>","Global gateway URL (env: VIBE_GLOBAL_GATEWAY_URL)").option("--workspace-gateway-url <url>","Workspace gateway URL (env: VIBE_WORKSPACE_GATEWAY_URL)").option("--workspace-id <id>","Workspace ID for auto-report (env: VIBE_WORKSPACE_ID)").option("--isolate <plugins>","Comma-separated list of plugin names to force into worker_threads isolation (Phase 4 hostile-plugin mode). Sets VIBE_ISOLATE_PLUGINS in the daemon env.").option("--profiles <names>","Comma-separated list of profiles to host in this daemon (multi-profile boot). When unset, the daemon hosts a single profile resolved via --profile / VIBECONTROLS_PROFILE / 'default'. Sets VIBECONTROLS_PROFILES in the daemon env so app boot can spin up additional ProfileContexts via the in-process registry.").option("--strict-key-fetch","Refuse to boot if any profile's encryption-key fetch fails. Default lenient: a failed profile is marked degraded and the daemon stays up. Sets VIBE_STRICT_KEY_FETCH=1 in the daemon env.",!1).option("--json","Emit JSON").option("--plain","Plain text output (no interactive TUI). Implied for non-TTY / CI.").option("--abilities <list>","Comma-separated ability keys to install non-interactively (e.g. session,ai,gitops). Storage/tunnel/backup are always included.").option("--wait-ready [seconds]","Block until the agent is fully ready (or fails). Polls /health/ready and renders phase transitions live. Without a value, defaults to 60s. Exits non-zero if the agent ends up degraded or times out. Useful for scripts/CI.").option("--no-wait","Skip the phase tracker entirely after spawning the daemon. Restores the old fire-and-print behavior \u2014 for users who want the previous quick-return UX.").action(async function(opts){let merged={...program.opts(),...opts};try{let defaultPortForProfile=function(profileName){if(profileName==="default")return 3005;let h=2166136261;for(let i=0;i<profileName.length;i++)h=Math.imul(h^profileName.charCodeAt(i),16777619);return 3100+Math.abs(h)%300},serviceManager=new ServiceManager,profile=opts.profile||process.env.VIBECONTROLS_PROFILE||"default";if(process.env.VIBECONTROLS_PROFILE=profile,typeof opts.isolate==="string"&&opts.isolate.length>0)process.env.VIBE_ISOLATE_PLUGINS=opts.isolate;if(typeof opts.profiles==="string"&&opts.profiles.length>0){let names=opts.profiles.split(",").map((s)=>s.trim()).filter(Boolean);if(names.length>0){if(process.env.VIBECONTROLS_PROFILES=names.join(","),process.env.VIBECONTROLS_PROFILE=names[0],names.length>1)warn(`--profiles received ${names.length} entries; daemon boots with '${names[0]}'. Remaining (${names.slice(1).join(", ")}) will be attached via /api/profiles after listen.`)}}if(opts.strictKeyFetch===!0)process.env.VIBE_STRICT_KEY_FETCH="1";applyAgentConfigToEnv();let dbPath=opts.dbPath||getProfileDataDir(),productDir=getVibecontrolsProductDir(),firstRun=!existsSync2(dbPath)&&!existsSync2(join2(productDir,"agents.json")),outputMode=pickOutputMode(merged),canPromptInteractively=outputMode!=="json"&&outputMode!=="plain"&&isInteractive()&&opts.yes!==!0,selectedAbilities;if(typeof merged.abilities==="string"&&merged.abilities.trim()!=="")selectedAbilities=parseAbilityKeys(merged.abilities);else if(hasConsent(productDir))selectedAbilities=readConsentAbilities(productDir)??defaultAbilityKeys();else if(canPromptInteractively)selectedAbilities=await promptAbilitySelection();else selectedAbilities=defaultAbilityKeys();if(!hasConsent(productDir)){let plan=getPlannedInstall({installDeps:opts.installDeps===!0,skipPluginInstall:opts.skipPluginInstall===!0,skipPlugins:Array.isArray(opts.skipPlugin)?opts.skipPlugin:[]},selectedAbilities);if(firstRun&&plan.plugins.length>0)blank(),info(`Installing ${plan.plugins.length} plugin(s) for the selected abilities.`),blank();persistConsent(productDir,plan,selectedAbilities,process.env.VIBE_AGENT_VERSION)}if(firstRun){info("First run detected \u2014 running setup..."),blank();let skipPlugins=Array.isArray(opts.skipPlugin)?opts.skipPlugin:[],plannedPlugins=opts.skipPluginInstall?[]:getDefaultPluginsForAbilities(process.platform,selectedAbilities).filter((p)=>!skipPlugins.includes(p.packageName)&&!skipPlugins.includes(p.pluginName)).map((p)=>p.packageName),pluginBinaries=collectPluginBinaries(plannedPlugins),missing=checkDependencies(pluginBinaries).filter((d)=>!d.installed);if(missing.length>0)if(warn(`Missing tools: ${missing.map((d)=>d.name).join(", ")}`),opts.installDeps)info("Their plugins will install them automatically on startup.");else info("Auto-install skipped (`--no-install-deps`) \u2014 install them yourself or drop the flag.");else success("All plugin tools present.");blank()}if(!opts.skipPluginInstall){let skipPlugins=Array.isArray(opts.skipPlugin)?opts.skipPlugin:[],pluginManager=new PluginManager;await pluginManager.loadCorePlugins(),await pluginManager.loadAll();let installed=await pluginManager.ensureDefaultPlugins((message)=>{if(message.startsWith("No "))warn(message);else if(message.startsWith("Installed "))success(message);else if(message.startsWith("Failed "))warn(message);else info(message)},skipPlugins,selectedAbilities);if(installed.length>0)success(`Auto-installed ${installed.length} default plugin${installed.length>1?"s":""}.`),blank()}let resolvedProfile=opts.profile||process.env.VIBECONTROLS_PROFILE||opts.name||"default",port=opts.port?parseInt(opts.port,10):defaultPortForProfile(resolvedProfile);if(isNaN(port)||port<1||port>65535)fail("Invalid port number. Must be between 1 and 65535.");let availablePort=await findFreePortFrom(port);if(availablePort!==port)warn(`Port ${port} is in use. Auto-selecting port ${colors.bold(String(availablePort))} instead.`),port=availablePort;let host=opts.host,agentUrl=`http://${host==="0.0.0.0"?"localhost":host}:${port}`,clientId=opts.clientId||process.env.VIBE_CLIENT_ID,clientSecret=opts.clientSecret||process.env.VIBE_CLIENT_SECRET,globalGatewayUrl=opts.globalGatewayUrl||process.env.VIBE_GLOBAL_GATEWAY_URL,workspaceGatewayUrl=opts.workspaceGatewayUrl||process.env.VIBE_WORKSPACE_GATEWAY_URL,workspaceId=opts.workspaceId||process.env.VIBE_WORKSPACE_ID;if(clientId&&!clientSecret)fail("--client-secret is required when --client-id is provided.");if(clientSecret&&!clientId)fail("--client-id is required when --client-secret is provided.");if(clientId&&clientSecret){if(!globalGatewayUrl&&!process.env.VIBE_GLOBAL_GATEWAY_URL)fail("--global-gateway-url is required when providing client credentials (none set in env).");if(process.env.VIBE_CLIENT_ID=clientId,process.env.VIBE_CLIENT_SECRET=clientSecret,globalGatewayUrl)process.env.VIBE_GLOBAL_GATEWAY_URL=globalGatewayUrl;let{writeAgentConfig:writeAgentConfig2}=await import("./agent-config-y63ddxgy.js");if(writeAgentConfig2({clientId,clientSecret,workspaceId,globalGatewayUrl,workspaceGatewayUrl}),workspaceGatewayUrl)process.env.VIBE_WORKSPACE_GATEWAY_URL=workspaceGatewayUrl;if(workspaceId)process.env.VIBE_WORKSPACE_ID=workspaceId;success("Gateway credentials staged in env. Agent will authenticate and persist them on startup."),blank()}else if(workspaceGatewayUrl||workspaceId||globalGatewayUrl){if(warn("Workspace options provided without --client-id / --client-secret \u2014 they will be staged in env but unused until credentials are configured."),workspaceGatewayUrl)process.env.VIBE_WORKSPACE_GATEWAY_URL=workspaceGatewayUrl;if(workspaceId)process.env.VIBE_WORKSPACE_ID=workspaceId;if(globalGatewayUrl)process.env.VIBE_GLOBAL_GATEWAY_URL=globalGatewayUrl;blank()}if(opts.foreground){if(!merged.json)header("Starting agent in foreground"),kv("Name",opts.name),kv("Port",String(port)),kv("Host",host),kv("Database",dbPath),blank();let{bootstrapWorkspace}=await import("./bootstrap-workspace-qwed8tfg.js");bootstrapWorkspace();let{createApp}=await import("./app-zcb5a9pn.js"),appInstance=await createApp({port,host,dbPath});if(await appInstance.start(),clientId&&clientSecret&&workspaceId&&globalGatewayUrl&&workspaceGatewayUrl){let result=await appInstance.finalize({clientId,clientSecret,workspaceId,globalGatewayUrl,workspaceGatewayUrl});if(!result.ok)warn(`Finalize failed \u2014 agent remains in awaiting-config state: ${result.error}`)}if(maybePrintJson(merged,{ok:!0,name:opts.name,port,host,pid:process.pid,url:agentUrl}));else await printAgentDetails(agentUrl);let shutdown=async()=>{await appInstance.stop(),process.exit(0)};process.on("SIGTERM",shutdown),process.on("SIGINT",shutdown)}else{if(!merged.json)header("Starting agent in daemon mode"),kv("Name",opts.name),kv("Port",String(port)),kv("Host",host),kv("Database",dbPath),blank();if(opts.installDeps===!1)process.env.VIBE_SKIP_PREREQ_INSTALL="1";await serviceManager.startDaemon({port,name:opts.name,daemon:!0,dbPath,host,profile});let actualPort=(await serviceManager.getStatus(opts.name))?.port??port,actualAgentUrl=`http://${host==="0.0.0.0"?"localhost":host}:${actualPort}`,waitReady=opts.waitReady,noWait=opts.wait===!1,requestedBlocking=waitReady!==void 0;if(noWait&&requestedBlocking)warn("--wait-ready is ignored because --no-wait was also passed.");let blocking=!noWait&&requestedBlocking,shouldRunTracker=!noWait&&(blocking||!merged.json),timeoutMs=(()=>{let fromFlag=typeof waitReady==="string"?Number.parseInt(waitReady,10):NaN;if(Number.isInteger(fromFlag)&&fromFlag>0)return fromFlag*1000;return blocking?60000:25000})();if(merged.json){if(shouldRunTracker){let{trackAgentReady}=await import("./agent-ready-tracker-5yq97296.js"),result=await trackAgentReady(actualAgentUrl,{timeoutMs,verbose:!1});if(blocking&&(result.outcome==="degraded"||result.outcome==="timeout"))process.exitCode=1;maybePrintJson(merged,{ok:result.outcome==="ready"||result.outcome==="awaiting-config",name:opts.name,port:actualPort,host,url:actualAgentUrl,abilities:[...selectedAbilities],outcome:result.outcome,bootState:result.bootState,degradedReasons:result.degradedReasons,summary:result.summary})}else maybePrintJson(merged,{ok:!0,name:opts.name,port:actualPort,host,url:actualAgentUrl});return}if(await printAgentDetails(actualAgentUrl),shouldRunTracker){let{trackAgentReady}=await import("./agent-ready-tracker-5yq97296.js");blank();let result=await trackAgentReady(actualAgentUrl,{timeoutMs,verbose:!0});if(blocking&&(result.outcome==="degraded"||result.outcome==="timeout"))process.exitCode=1}}}catch(err){let message=err instanceof Error?errMsg(err):String(err);if(merged.json){maybePrintJson(merged,{ok:!1,error:message});return}fail(`Failed to start agent: ${message}`)}})}function register2(program){program.command("stop").description("Stop a running VibeControls agent instance").option("-n, --name <name>","Agent instance name","default").option("--all","Stop all running agent instances",!1).option("--json","Emit JSON").action(async function(opts){let merged={...program.opts(),...opts};try{let serviceManager=new ServiceManager;if(opts.all){let instances=await serviceManager.listInstances();if(!instances||instances.length===0){if(maybePrintJson(merged,{ok:!0,stopped:[]}))return;header("Stopping all agent instances"),blank(),info(`${icons.info} No running agent instances found.`);return}let stoppedNames=[];if(!merged.json)header("Stopping all agent instances"),blank();for(let instance of instances)try{if(await serviceManager.stop(instance.name),stoppedNames.push(instance.name),!merged.json)success(`${icons.success} Stopped ${colors.bold(instance.name)}`)}catch{if(!merged.json)fail(`Failed to stop ${colors.bold(instance.name)}`)}if(maybePrintJson(merged,{ok:!0,stopped:stoppedNames,total:instances.length}))return;blank(),success(`${icons.success} Stopped ${stoppedNames.length}/${instances.length} instance(s).`)}else{if(await serviceManager.stop(opts.name),maybePrintJson(merged,{ok:!0,name:opts.name}))return;header(`Stopping agent: ${opts.name}`),blank(),success(`${icons.success} Agent ${colors.bold(opts.name)} stopped.`)}}catch(err){if(merged.json){maybePrintJson(merged,{ok:!1,error:errMsg(err)});return}fail(`Failed to stop agent: ${errMsg(err)}`)}})}function register3(program){program.command("restart").description("Restart a running VibeControls agent instance").option("-n, --name <name>","Agent instance name","default").option("-p, --port <port>","Port to listen on","3005").option("--db-path <path>","Path to the agent storage directory","./agent-db").option("--json","Emit JSON").action(async function(opts){let merged={...program.opts(),...opts};try{let serviceManager=new ServiceManager;if(!merged.json)header(`Restarting agent: ${opts.name}`),blank(),info(`${icons.info} Stopping agent ${colors.bold(opts.name)}...`);try{if(await serviceManager.stop(opts.name),!merged.json)success(`${icons.success} Agent stopped.`)}catch{if(!merged.json)info(`${icons.info} Agent was not running.`)}let port=parseInt(opts.port,10);if(isNaN(port)||port<1||port>65535){if(merged.json){maybePrintJson(merged,{ok:!1,error:"Invalid port number"});return}fail("Invalid port number. Must be between 1 and 65535.");return}let config={port,name:opts.name,daemon:!0,dbPath:opts.dbPath};if(!merged.json)blank(),info(`${icons.info} Starting agent ${colors.bold(opts.name)}...`);await serviceManager.startDaemon(config);let agentUrl=`http://localhost:${port}`;if(maybePrintJson(merged,{ok:!0,name:opts.name,port,url:agentUrl}))return;blank(),success(`${icons.success} Agent ${colors.bold(opts.name)} restarted.`),blank(),kv("Port",String(port)),kv("Database",opts.dbPath),blank(),printAgentDetails(agentUrl)}catch(err){if(merged.json){maybePrintJson(merged,{ok:!1,error:errMsg(err)});return}fail(`Failed to restart agent: ${errMsg(err)}`)}})}import{existsSync as existsSync3,readFileSync as readFileSync2,unlinkSync as unlinkSync2}from"fs";import{join as join3}from"path";function readProfileRuntime(profileName){let runtimePath=join3(getVibecontrolsProfilesDir(),profileName,"runtime.json");if(!existsSync3(runtimePath))return null;try{let data=JSON.parse(readFileSync2(runtimePath,"utf8"));if(typeof data.pid!=="number")return null;return{...data,pid:data.pid,path:runtimePath}}catch{return null}}async function killAgentProfile(profileName){let rt=readProfileRuntime(profileName);if(!rt)return null;if(!isProcessAlive(rt.pid)){try{unlinkSync2(rt.path)}catch{}return`agent pid=${rt.pid} (${profileName}) already gone (cleaned runtime.json).`}let osAdapter=getOsAdapter();if(!osAdapter.killProcessTree(rt.pid,"SIGTERM"))return`failed to SIGTERM agent pid=${rt.pid}.`;if(await new Promise((r)=>setTimeout(r,3000)),isProcessAlive(rt.pid))osAdapter.killProcessTree(rt.pid,"SIGKILL");try{unlinkSync2(rt.path)}catch{}return`agent ${profileName} pid=${rt.pid}${rt.port?` (port ${rt.port})`:""} killed.`}async function killProfileTunnel(profileName){let dir=join3(getVibecontrolsProfilesDir(),profileName),state=readTunnelState(dir);if(!state)return null;if(!isProcessAlive(state.pid))return clearTunnelState(dir),`tunnel pid=${state.pid} already gone (cleaned state).`;let osAdapter=getOsAdapter();if(!osAdapter.killProcessTree(state.pid,"SIGTERM"))return`failed to SIGTERM tunnel pid=${state.pid}.`;if(await new Promise((r)=>setTimeout(r,3000)),isProcessAlive(state.pid))osAdapter.killProcessTree(state.pid,"SIGKILL");return clearTunnelState(dir),`tunnel ${state.provider} pid=${state.pid} (${state.url??"no url"}) killed.`}function register4(program){program.command("kill").description("Force-kill an agent instance and its tunnel. Defaults to active profile.").option("-n, --name <name>","Agent instance name (alias of --profile, kept for back-compat)").option("--profile <name>","Kill a specific profile (overrides --name and VIBECONTROLS_PROFILE)").option("--all","Kill every agent instance and every profile's tunnel",!1).option("--json","Emit JSON").action(async function(opts){let merged={...program.opts(),...opts},killedAll=[];try{let serviceManager=new ServiceManager;if(opts.all){if(!merged.json)header("Force killing all agent instances + tunnels"),blank();let instances=await serviceManager.listInstances()??[],killedAgents=0,seenProfiles=new Set;for(let instance2 of instances)try{if(await serviceManager.kill(instance2.name),!merged.json)success(`${icons.success} agent ${colors.bold(instance2.name)} (pid=${instance2.pid||"?"}) killed.`);killedAll.push(instance2.name),killedAgents++,seenProfiles.add(instance2.name)}catch{if(!merged.json)warn(`${icons.warning} could not kill agent ${instance2.name}.`)}try{let fs=await import("fs"),agentsDir=getVibecontrolsProfilesDir(),entries=fs.existsSync(agentsDir)?fs.readdirSync(agentsDir):[];for(let profile of entries){if(seenProfiles.has(profile))continue;let rtResult=await killAgentProfile(profile);if(rtResult)success(`${icons.success} ${rtResult}`),killedAgents++}}catch(err){warn(`${icons.warning} runtime.json sweep failed: ${err instanceof Error?errMsg(err):String(err)}`)}let tunnels=listPersistedTunnels({allProfiles:!0}),killedTunnels=0;for(let t of tunnels){if(!t.alive){clearTunnelState(t.profileDir);continue}let osAdapter=getOsAdapter();if(osAdapter.killProcessTree(t.pid,"SIGTERM"),await new Promise((r)=>setTimeout(r,3000)),isProcessAlive(t.pid))osAdapter.killProcessTree(t.pid,"SIGKILL");clearTunnelState(t.profileDir),success(`${icons.success} tunnel ${t.provider} pid=${t.pid} (${t.url??"no url"}, ${t.profileDir.split("/").pop()}) killed.`),killedTunnels++}if(maybePrintJson(merged,{ok:!0,killed:killedAll,tunnels:killedTunnels}))return;blank(),success(`${icons.success} killed ${killedAgents} agent(s) and ${killedTunnels} tunnel(s).`);return}let profileName=opts.profile||opts.name||getVibecontrolsProfile();if(!merged.json)header(`Force killing profile: ${profileName}`),blank();let instance=await serviceManager.getStatus(profileName);if(instance){if(await serviceManager.kill(profileName),killedAll.push(profileName),!merged.json)success(`${icons.success} agent ${colors.bold(profileName)} pid=${instance.pid||"?"} killed.`)}else{let rtResult=await killAgentProfile(profileName);if(rtResult){if(killedAll.push(profileName),!merged.json)success(`${icons.success} ${rtResult}`)}else if(!merged.json)info(`${icons.info} no running agent service for profile ${profileName}.`)}let tunnelResult=await killProfileTunnel(profileName);if(tunnelResult){if(!merged.json)success(`${icons.success} ${tunnelResult}`)}else if(!merged.json)info(`${icons.info} no tunnel recorded for profile ${profileName}.`);maybePrintJson(merged,{ok:!0,killed:killedAll})}catch(err){if(merged.json){maybePrintJson(merged,{ok:!1,error:errMsg(err)});return}fail(`Failed to kill: ${errMsg(err)}`)}})}function register5(program){program.command("list").alias("ls").description("List all VibeControls agent instances").option("--json","Emit JSON").option("--plain","Force plain text output").action(async function(opts){try{let merged={...program.opts(),...opts},sm=new ServiceManager;await runMultimode({mode:pickOutputMode(merged),fetchData:()=>sm.listInstances(),plain:(instances)=>{if(header("Agent Instances"),blank(),!instances||instances.length===0){info(`${icons.info} No agent instances found.`),info(`Run ${colors.bold("vibe start")} to start an agent.`);return}let rows=instances.map((inst)=>({Name:inst.name,Status:formatStatus(inst.status),PID:inst.pid||"-",Port:inst.port||"-",Host:inst.config?.host||"-",Database:inst.config?.dbPath||"-",Started:inst.startTime?timeAgo(inst.startTime):"-"}));formatTable(rows),blank();let running=instances.filter((i)=>i.status==="running").length,stopped=instances.length-running;info(`${icons.info} ${instances.length} instance(s): ${colors.green(String(running))} running, ${colors.dim(String(stopped))} stopped`)},interactive:async(instances)=>{if(!instances||instances.length===0){header("Agent Instances"),blank(),info(`${icons.info} No agent instances found.`),info(`Run ${colors.bold("vibe start")} to start an agent.`);return}let rows=instances.map((inst)=>{let lines=[`${colors.bold(inst.name)} ${formatStatus(inst.status)}`,"",` PID: ${inst.pid??"-"}`,` Port: ${inst.port??"-"}`,` Host: ${inst.config?.host??"-"}`,` Database: ${inst.config?.dbPath??"-"}`,` Started: ${inst.startTime?timeAgo(inst.startTime):"-"}`];return{id:inst.name,label:inst.name,hint:inst.status==="running"?"running":"stopped",detail:lines.join(`
4
4
  `)}});await interactiveTable({title:`vibe list \u2014 ${instances.length} instance(s)`,rows,footer:"\u2191/\u2193 navigate \xB7 q to quit"})},json:(instances)=>instances.map((inst)=>({name:inst.name,status:inst.status,pid:inst.pid??null,port:inst.port??null,host:inst.config?.host??null,database:inst.config?.dbPath??null,startTime:inst.startTime??null}))})}catch(err){fail(`Failed to list instances: ${err.message}`)}})}var MAX_TAIL_LINES=5000;function register6(program){program.command("logs").description("View logs for a VibeControls agent instance").option("-n, --name <name>","Agent instance name","default").option("-f, --follow","Follow log output",!1).option("--tail <lines>","Number of lines to show from the end","100").option("--json","Emit JSON (one object per line, banners suppressed)").option("--plain","Force plain text output").action(async function(opts){try{let merged={...program.opts(),...opts},serviceManager=new ServiceManager,tail=parseInt(merged.tail??"100",10);if(isNaN(tail)||tail<1||tail>MAX_TAIL_LINES){fail(`Invalid tail value. Must be between 1 and ${MAX_TAIL_LINES}.`);return}let name=merged.name??"default";if(!await serviceManager.getStatus(name)){fail(`Agent instance ${colors.bold(name)} not found.`);return}if(!merged.json){if(merged.follow)header(`Following logs: ${name}`),info(`${icons.info} Press Ctrl+C to stop following.`);else header(`Logs: ${name}`);blank()}await serviceManager.showLogs(name,{follow:!!merged.follow,tail})}catch(err){fail(`Failed to get logs: ${errMsg(err)}`)}})}function register7(program){program.command("setup").description("Install system dependencies and (optionally) write gateway auth config").option("--check","Only check dependencies without installing",!1).option("--client-id <id>","OAuth app client ID (for backend authentication)").option("--client-secret <secret>","OAuth app client secret").option("--workspace-id <id>","Workspace UUID this agent belongs to").option("--global-gateway-url <url>","Global public gateway URL (default: http://localhost:4000/global/graphql)").option("--workspace-gateway-url <url>","Workspace gateway URL (default: http://localhost:4001/workspaces/graphql)").option("--storage-adapter <name>","Named storage adapter (default: skalex, or custom:<path>)").option("--json","Emit JSON").action(async function(options){let merged={...program.opts(),...options},configured=[];try{if(!merged.json)header("VibeControls Agent Setup");let update={};if(options.clientId)update.clientId=options.clientId;if(options.clientSecret)update.clientSecret=options.clientSecret;if(options.workspaceId)update.workspaceId=options.workspaceId;if(options.globalGatewayUrl)update.globalGatewayUrl=assertAllowedGatewayUrl(options.globalGatewayUrl,"globalGatewayUrl");if(options.workspaceGatewayUrl)update.workspaceGatewayUrl=assertAllowedGatewayUrl(options.workspaceGatewayUrl,"workspaceGatewayUrl");if(options.storageAdapter)update.storageAdapter=options.storageAdapter;if(Object.keys(update).length>0){let written=writeAgentConfig(update);if(configured.push(...Object.keys(update)),!merged.json){success(`Agent config written to ${getAgentConfigPath()}`),kv("clientId",written.clientId?colors.dim("(set)"):colors.dim("(unset)")),kv("clientSecret",written.clientSecret?colors.dim("(set)"):colors.dim("(unset)")),kv("workspaceId",written.workspaceId??colors.dim("(unset)"));let defaults=getAgentConfigDefaults();if(kv("globalGatewayUrl",written.globalGatewayUrl??defaults.globalGatewayUrl),kv("workspaceGatewayUrl",written.workspaceGatewayUrl??defaults.workspaceGatewayUrl),written.storageAdapter)kv("storageAdapter",written.storageAdapter);blank()}}else{let existing=readAgentConfig();if((existing.clientId||existing.clientSecret||existing.workspaceId)&&!merged.json)info(`Using existing agent config at ${getAgentConfigPath()} (pass --client-id/--client-secret/--workspace-id to update).`),blank()}if(!merged.json)info("Checking dependencies..."),blank();let deps=checkDependencies(),missing=[],installed=[];for(let dep of deps){if(dep.installed)installed.push(dep.name);if(!merged.json){let icon=dep.installed?icons.success:icons.error,version=dep.version?colors.dim(` (${dep.version})`):"",required=dep.required?"":colors.dim(" [optional]");kv(`${icon} ${dep.name}`,`${dep.installed?colors.green("installed"):colors.red("missing")}${version}${required}`)}if(!dep.installed)missing.push(dep.name)}if(!merged.json)blank();if(missing.length===0){if(maybePrintJson(merged,{ok:!0,installed,configured}))return;success("All dependencies are installed.");return}if(options.check){if(merged.json){maybePrintJson(merged,{ok:!1,installed,missing,configured});return}warn(`Missing: ${missing.join(", ")}`),info(`Run ${colors.bold("vibe setup")} to install them.`),process.exit(1)}if(!merged.json)info(`Installing missing dependencies: ${missing.join(", ")}...`),blank();let result=await installDependencies(missing),newlyInstalled=missing.filter((n)=>!result.failed.includes(n));if(result.failed.length>0){if(merged.json){maybePrintJson(merged,{ok:!1,installed:[...installed,...newlyInstalled],failed:result.failed,configured});return}warn(`${result.failed.length} tool(s) failed: ${result.failed.join(", ")}`),info("You may need to install manually or use sudo."),process.exit(1)}else{if(maybePrintJson(merged,{ok:!0,installed:[...installed,...newlyInstalled],configured}))return;success("All dependencies installed successfully.")}}catch(err){let message=err instanceof Error?errMsg(err):String(err);if(merged.json){maybePrintJson(merged,{ok:!1,error:message});return}fail(`Setup failed: ${message}`)}})}import{join as join4}from"path";async function getPackageMetadata(){let depths=["..","../..","../../.."];for(let depth of depths)try{let pkgPath=join4(import.meta.dir,depth,"package.json"),data=await Bun.file(pkgPath).json(),name=data.name,version=data.version;if(name&&version){let publishConfig=data.publishConfig;return{name,version,registry:publishConfig?.registry??getPluginRegistry()}}}catch{}throw Error("package.json not found")}async function fetchRemoteManifest(pkg,version,registry){try{let result=Bun.spawnSync([process.platform==="win32"?"npm.cmd":"npm","view",`${pkg}@${version}`,"--json",`--registry=${registry}`],{stdout:"pipe",stderr:"pipe"});if(result.exitCode!==0)return null;let parsed=JSON.parse(result.stdout.toString());return Array.isArray(parsed)?parsed[0]??null:parsed}catch{return null}}function compareSemver(a,b){let parse=(v)=>v.replace(/^[\^~>=<v]+/,"").split(/[.+-]/).map((p)=>Number(p)||0),aa=parse(a),bb=parse(b);for(let i=0;i<Math.max(aa.length,bb.length);i++){let ai=aa[i]??0,bi=bb[i]??0;if(ai!==bi)return ai-bi}return 0}function checkBunCompat(required,current){if(!required)return{ok:!0,message:""};let cleaned=required.replace(/^[\^~]/,"").replace(/^>=?\s*/,"");if(compareSemver(current,cleaned)>=0)return{ok:!0,message:`bun ${current} >= ${cleaned}`};return{ok:!1,message:`requires bun ${required}, this process is bun ${current}`}}function getInstalledPath(pkg){try{let npmCmd=process.platform==="win32"?"npm.cmd":"npm",r=Bun.spawnSync([npmCmd,"root","-g"],{stdout:"pipe",stderr:"pipe"});if(r.exitCode!==0)return null;return`${r.stdout.toString().trim()}/${pkg}`}catch{return null}}function smokeTestInstalled(pkg){let root=getInstalledPath(pkg);if(!root)return{ok:!0,step:"(skipped, install root unknown)"};let cli=`${root}/dist/cli.js`,run=(args,step,timeoutMs)=>{try{let runtime=process.platform==="win32"?"bun.exe":"bun",r=Bun.spawnSync([runtime,cli,...args],{stdout:"pipe",stderr:"pipe",timeout:timeoutMs});if(r.exitCode===0)return{ok:!0,step};return{ok:!1,step,detail:r.stderr.toString().slice(0,300)||`exit ${r.exitCode}`}}catch(err){return{ok:!1,step,detail:String(err)}}},v=run(["--version"],"vibe --version",1e4);if(!v.ok)return v;let i=run(["info"],"vibe info",15000);if(!i.ok)return i;let p=run(["plugin","list","--json"],"vibe plugin list",30000);if(!p.ok)return p;return{ok:!0,step:"all checks passed"}}async function maybeAutoRestart(name){try{let sm=new ServiceManager,status=await sm.getStatus(name);if(!status||status.status!=="running")return{kind:"not-running"};let agentUrl=`http://localhost:${status.port}`,apiKey;try{apiKey=await resolveApiKey(agentUrl)}catch{}let headers={};if(apiKey)headers["x-agent-api-key"]=apiKey;let POLL_MS=1000,MAX_MS=60000,started=Date.now();while(Date.now()-started<MAX_MS){try{let res=await fetch(`${agentUrl}/api/profiles/${encodeURIComponent(name)}/stats/inflight`,{headers,signal:AbortSignal.timeout(2000)});if(res.ok){let body=await res.json();if(typeof body.inflight==="number"&&body.inflight===0){let cfg=status.config;return await sm.restart(name,cfg),{kind:"restarted"}}}}catch{}await new Promise((r)=>setTimeout(r,POLL_MS))}return{kind:"still-busy"}}catch(err){return{kind:"error",message:err instanceof Error?errMsg(err):String(err)}}}function register8(program){program.command("update").description("Check for and install VibeControls agent updates").option("--check","Only check for updates without installing",!1).option("--allow-incompatible","Override engines.bun compatibility check (use with care)",!1).option("--no-restart","Skip the post-install idle-aware restart of any running agent").option("-n, --name <name>","Agent profile name to restart after update","default").option("--json","Emit JSON").action(async function(opts){let merged={...program.opts(),...opts};try{if(!merged.json)header("VibeControls Agent Update"),blank();let metadata;try{metadata=await getPackageMetadata()}catch{fail("Could not read package metadata.");return}if(!merged.json)info(`${icons.info} Checking for updates...`),blank();let latestVersion;try{let result=Bun.spawnSync([process.platform==="win32"?"npm.cmd":"npm","view",metadata.name,"version",`--registry=${metadata.registry}`],{stdout:"pipe",stderr:"pipe"});if(result.exitCode!==0)throw Error("npm view failed");latestVersion=result.stdout.toString().trim()}catch{fail("Could not check for updates. Ensure you have internet connectivity and npm is available.");return}if(!merged.json)kv("Package",colors.bold(metadata.name)),kv("Registry",colors.bold(metadata.registry)),kv("Current version",colors.bold(metadata.version)),kv("Latest version",colors.bold(latestVersion)),blank();if(metadata.version===latestVersion){if(maybePrintJson(merged,{ok:!0,current:metadata.version,latest:latestVersion,upToDate:!0}))return;success(`${icons.success} You are running the latest version.`);return}if(opts.check){if(maybePrintJson(merged,{ok:!0,current:metadata.version,latest:latestVersion,upToDate:!1}))return;warn(`${icons.warning} A new version is available: ${colors.green(latestVersion)}`),info(`${icons.info} Run ${colors.bold("vibe update")} to install the update.`);return}let remoteManifest=await fetchRemoteManifest(metadata.name,latestVersion,metadata.registry);if(!remoteManifest)warn(`${icons.warning} Could not fetch remote manifest; skipping engine compat check.`);else{let bunVersion=typeof Bun<"u"?Bun.version:"0.0.0",compat=checkBunCompat(remoteManifest.engines?.bun,bunVersion);if(!compat.ok){if(!opts.allowIncompatible){fail(`${icons.error} Refusing to upgrade: ${compat.message}. Pass --allow-incompatible to override.`);return}warn(`${icons.warning} Engine mismatch (${compat.message}); proceeding due to --allow-incompatible.`)}else kv("Engine check",colors.bold(compat.message))}let installRoot=getInstalledPath(metadata.name),previousVersion=metadata.version;info(`${icons.info} Updating to ${colors.bold(latestVersion)}...`),blank();try{if(Bun.spawnSync([process.platform==="win32"?"npm.cmd":"npm","install","-g",`${metadata.name}@${latestVersion}`,`--registry=${metadata.registry}`],{stdout:"inherit",stderr:"inherit"}).exitCode!==0)throw Error("install failed")}catch{fail(`Failed to install update. Try running with sudo: ${colors.bold(`sudo npm install -g ${metadata.name}@${latestVersion} --registry=${metadata.registry}`)}`);return}let smoke=smokeTestInstalled(metadata.name);if(!smoke.ok){if(warn(`${icons.warning} Post-install smoke test failed at "${smoke.step}". Rolling back to ${previousVersion}\u2026`),smoke.detail)warn(`${icons.warning} Details: ${smoke.detail}`);try{if(Bun.spawnSync([process.platform==="win32"?"npm.cmd":"npm","install","-g",`${metadata.name}@${previousVersion}`,`--registry=${metadata.registry}`],{stdout:"inherit",stderr:"inherit"}).exitCode!==0)throw Error("rollback npm install failed");warn(`${icons.warning} Rolled back to ${previousVersion}. Investigate the new version before retrying.`)}catch{fail(`${icons.error} Rollback failed. Manually run: ${colors.bold(`npm install -g ${metadata.name}@${previousVersion}`)}`)}return}let shouldAutoRestart=opts.restart!==!1,restartOutcome={kind:"skipped"};if(shouldAutoRestart){if(!merged.json)blank(),info(`${icons.info} Waiting for agent ${colors.bold(opts.name)} to become idle before restart\u2026`);if(restartOutcome=await maybeAutoRestart(opts.name),!merged.json)switch(restartOutcome.kind){case"restarted":success(`${icons.success} Restarted agent ${colors.bold(opts.name)} on the new version.`);break;case"not-running":info(`${icons.info} No running agent for profile ${colors.bold(opts.name)}; nothing to restart.`);break;case"still-busy":warn(`${icons.warning} Agent still serving requests after 60s \u2014 run ${colors.bold("vibe restart")} when it's quiet.`);break;case"error":warn(`${icons.warning} Auto-restart failed: ${restartOutcome.message}. Run ${colors.bold("vibe restart")} manually.`);break}}if(maybePrintJson(merged,{ok:!0,current:latestVersion,previous:previousVersion,latest:latestVersion,restart:restartOutcome.kind,...restartOutcome.kind==="error"?{restartError:restartOutcome.message}:{}}))return;if(blank(),success(`${icons.success} Updated to ${colors.bold(latestVersion)} (smoke: ${smoke.step}).`),installRoot)info(`${icons.info} Installed at ${installRoot}.`);if(!shouldAutoRestart)info(`${icons.info} --no-restart set \u2014 restart running agents manually for the update to take effect.`)}catch(err){let message=err instanceof Error?errMsg(err):String(err);if(merged.json){maybePrintJson(merged,{ok:!1,error:message});return}fail(`Update failed: ${message}`)}}),program.command("rollback").description("Roll the global agent install back to a specific version").argument("<version>","Target CalVer version (e.g. 2026.428.3)").action(async(version)=>{try{header("VibeControls Agent Rollback");let metadata=await getPackageMetadata();if(kv("Package",colors.bold(metadata.name)),kv("Current version",colors.bold(metadata.version)),kv("Target version",colors.bold(version)),blank(),info(`${icons.info} Rolling back\u2026`),Bun.spawnSync([process.platform==="win32"?"npm.cmd":"npm","install","-g",`${metadata.name}@${version}`,`--registry=${metadata.registry}`],{stdout:"inherit",stderr:"inherit"}).exitCode!==0){fail("Rollback failed.");return}success(`${icons.success} Rolled back to ${colors.bold(version)}.`)}catch(err){fail(`Rollback failed: ${err instanceof Error?errMsg(err):String(err)}`)}})}import{existsSync as existsSync4,mkdirSync,writeFileSync as writeFileSync2,unlinkSync as unlinkSync3,readFileSync as readFileSync3}from"fs";import{join as join5}from"path";import{homedir}from"os";var SAFE_COMPLETION_NAME_RE=/^[A-Za-z0-9][A-Za-z0-9:_-]{0,63}$/,SAFE_COMPLETION_OPTION_RE=/^--[A-Za-z0-9][A-Za-z0-9-]{0,63}$/;function safeCompletionName(name){return SAFE_COMPLETION_NAME_RE.test(name)?name:null}function safeCompletionWords(words){return words.filter((word)=>safeCompletionName(word))}function safeCompletionOptions(options){return options.filter((option)=>SAFE_COMPLETION_OPTION_RE.test(option))}function collectCommands(cmd){return cmd.commands.flatMap((sub)=>{let name=safeCompletionName(sub.name());if(!name)return[];return[{name,description:sub.description()||"",options:sub.options.map((opt)=>({flags:opt.flags,description:opt.description||""})),subcommands:collectCommands(sub)}]})}function topLevelNames(cmds){return safeCompletionWords(cmds.map((c)=>c.name))}function longOptions(cmds,name){let cmd=cmds.find((c)=>c.name===name);if(!cmd)return[];let opts=[];for(let o of cmd.options){let match=o.flags.match(/--([\w-]+)/);if(match)opts.push(`--${match[1]}`)}return safeCompletionOptions(opts)}function generateBash(cmds){let top=topLevelNames(cmds),caseArms=cmds.filter((c)=>c.subcommands.length>0).map((c)=>({name:c.name,subs:safeCompletionWords(c.subcommands.map((s)=>s.name))})).map((g)=>` ${g.name})
5
5
  COMPREPLY=($(compgen -W "${g.subs.join(" ")}" -- "\${cur}"))
6
6
  return 0
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{denyNonLocalMutation,isLikelyLocalRequest}from"./index-49a60qjr.js";import{autoReportToBackend,stopProfileReconciler,stopTunnelSync}from"./index-5krr8y92.js";import{runAliasCaptured}from"./index-9e1fgxea.js";import{checkDependencies,installDependencies}from"./index-fg47j98r.js";import{ServiceManager}from"./index-34syaqa8.js";import{redactUnknownSecrets}from"./index-y5q0m3cx.js";import{getActiveContributorRegistry}from"./index-yke24mr4.js";import"./index-kf5tas0g.js";import"./index-srbb2214.js";import{validateEvent}from"./index-3jez1q8j.js";import"./index-brtw3j8x.js";import{getAgentApiKey}from"./index-b4wy3jrt.js";import"./index-d3mz9vws.js";import{Elysia,t}from"./index-rnk0kny8.js";import{register}from"./index-njg2sn7v.js";import"./index-qbvtba0e.js";import{apiGet,apiPost,getAgentUrl,maybePrintJson,pickOutputMode,resolveProfileName,runMultimode}from"./index-wvabz3xh.js";import{blank,colors,errMsg,fail,formatBytes,formatDuration,formatStatus,formatTable,header,icons,info,kv,success,timeAgo}from"./index-r0qezdp7.js";import{interactiveDetail}from"./index-campp0wv.js";import{writeAgentConfig}from"./index-2pqv0bya.js";import{currentProfileOrNull,gatewayClient,getDaemonProfile}from"./index-7pdmqbj8.js";import{getVibecontrolsDir,getVibecontrolsProfile,getVibecontrolsProfilesDir,isPathInside}from"./index-bysm7taq.js";import"./index-zs58d1hc.js";import{__require}from"./index-e9rt4m94.js";function createLifecycleHooks(spec){let{name,onInit,onShutdown,onNuke,telemetryEventName,skipPlatforms}=spec;return{onServerStart:async(_app,hostServices)=>{if(skipPlatforms&&skipPlatforms.includes(process.platform)){process.stderr.write(`[${name}] skipping init on unsupported platform '${process.platform}'
2
+ import{denyNonLocalMutation,isLikelyLocalRequest}from"./index-49a60qjr.js";import{autoReportToBackend,stopProfileReconciler,stopTunnelSync}from"./index-g9h64dn9.js";import{runAliasCaptured}from"./index-9e1fgxea.js";import{checkDependencies,installDependencies}from"./index-fg47j98r.js";import{ServiceManager}from"./index-34syaqa8.js";import{redactUnknownSecrets}from"./index-y5q0m3cx.js";import{getActiveContributorRegistry}from"./index-n3y918j2.js";import"./index-h6a1kkfk.js";import"./index-srbb2214.js";import{validateEvent}from"./index-3jez1q8j.js";import"./index-brtw3j8x.js";import{getAgentApiKey}from"./index-b4wy3jrt.js";import"./index-d3mz9vws.js";import{Elysia,t}from"./index-rnk0kny8.js";import{register}from"./index-njg2sn7v.js";import"./index-qbvtba0e.js";import{apiGet,apiPost,getAgentUrl,maybePrintJson,pickOutputMode,resolveProfileName,runMultimode}from"./index-wvabz3xh.js";import{blank,colors,errMsg,fail,formatBytes,formatDuration,formatStatus,formatTable,header,icons,info,kv,success,timeAgo}from"./index-r0qezdp7.js";import{interactiveDetail}from"./index-campp0wv.js";import{writeAgentConfig}from"./index-2pqv0bya.js";import{currentProfileOrNull,gatewayClient,getDaemonProfile}from"./index-7pdmqbj8.js";import{getVibecontrolsDir,getVibecontrolsProfile,getVibecontrolsProfilesDir,isPathInside}from"./index-bysm7taq.js";import"./index-zs58d1hc.js";import{__require}from"./index-e9rt4m94.js";function createLifecycleHooks(spec){let{name,onInit,onShutdown,onNuke,telemetryEventName,skipPlatforms}=spec;return{onServerStart:async(_app,hostServices)=>{if(skipPlatforms&&skipPlatforms.includes(process.platform)){process.stderr.write(`[${name}] skipping init on unsupported platform '${process.platform}'
3
3
  `);return}if(onInit)await onInit(hostServices);if(telemetryEventName)hostServices.telemetry?.emit(telemetryEventName,{plugin:name})},onServerStop:async(hostServices)=>{if(onShutdown)await onShutdown(hostServices)},onNuke:async(hostServices,ctx)=>{if(onNuke)return onNuke(hostServices,ctx)}}}var BoundLogger=class{constructor(logger,source){this.logger=logger,this.source=source}logger;source;info(message,meta){this.logger?.info?.(this.source,message,meta)}warn(message,meta){this.logger?.warn?.(this.source,message,meta)}error(message,meta){this.logger?.error?.(this.source,message,meta)}debug(message,meta){this.logger?.debug?.(this.source,message,meta)}};import{existsSync,rmSync,statSync}from"fs";import{resolve}from"path";function wipeAgentDir(agentDir=getVibecontrolsDir()){let removed=[],safeAgentDir=resolve(agentDir),agentsDir=getVibecontrolsProfilesDir();if(!isPathInside(agentsDir,safeAgentDir))throw Error("Refusing to reset a path outside the agents directory");if(existsSync(safeAgentDir)&&statSync(safeAgentDir).isDirectory())rmSync(safeAgentDir,{recursive:!0,force:!0}),removed.push(safeAgentDir);return{removed,agentDir:safeAgentDir}}var ALIAS_PLUGIN_NAMESPACE="alias",ALIAS_NAME_RE=/^[a-zA-Z0-9_-]{1,64}$/,ALIAS_COMMAND_MAX=16384,ALIAS_DESCRIPTION_MAX=256,ALIAS_CWD_MAX=1024,RESERVED_ALIAS_NAMES=new Set(["help","start","stop","restart","kill","list","status","setup","update","completion","autostart","export","import","diagnostics","nuke","doctor","log-level","gc","deploy","network","profile","peer-bootstrap","gateway-auth","info","key","system","url","health","notify","tunnel","session","git","config","log","plugin","ai","audit","alias","run"]);class AliasValidationError extends Error{code;constructor(code,message){super(message);this.code=code,this.name="AliasValidationError"}}class AliasConflictError extends Error{constructor(name){super(`alias '${name}' already exists`);this.name="AliasConflictError"}}class AliasNotFoundError extends Error{constructor(name){super(`alias '${name}' not found`);this.name="AliasNotFoundError"}}function validateAliasName(name){if(typeof name!=="string"||!ALIAS_NAME_RE.test(name))throw new AliasValidationError("invalid_name",`alias name must match ${ALIAS_NAME_RE} (got '${name}')`);if(RESERVED_ALIAS_NAMES.has(name))throw new AliasValidationError("reserved_name",`alias name '${name}' is reserved`)}function validateAliasCommand(command){if(typeof command!=="string"||command.length===0)throw new AliasValidationError("invalid_command","alias command must be a non-empty string");if(command.length>ALIAS_COMMAND_MAX)throw new AliasValidationError("command_too_long",`alias command exceeds ${ALIAS_COMMAND_MAX} bytes`)}function validateAliasDescription(description){if(description===void 0)return;if(typeof description!=="string")throw new AliasValidationError("invalid_description","alias description must be a string");if(description.length>ALIAS_DESCRIPTION_MAX)throw new AliasValidationError("description_too_long",`alias description exceeds ${ALIAS_DESCRIPTION_MAX} chars`)}function validateAliasCwd(cwd){if(cwd===void 0||cwd===null||cwd==="")return;if(typeof cwd!=="string")throw new AliasValidationError("invalid_cwd","alias cwd must be a string");if(cwd.length>ALIAS_CWD_MAX)throw new AliasValidationError("cwd_too_long",`alias cwd exceeds ${ALIAS_CWD_MAX} chars`);if(cwd.includes("\x00"))throw new AliasValidationError("invalid_cwd","alias cwd must not contain NUL bytes")}function safeParse(value){if(!value)return;try{return JSON.parse(value)}catch{return}}async function listAliases(db){let rows=await db.getAllPluginState(ALIAS_PLUGIN_NAMESPACE),out=[];for(let row of rows){let parsed=safeParse(row.value);if(parsed)out.push(parsed)}return out.sort((a,b)=>a.name.localeCompare(b.name)),out}async function getAliasByName(db,name){return(await listAliases(db)).find((a)=>a.name===name)}function normalizeCwd(cwd){if(cwd===void 0||cwd===null)return null;let trimmed=cwd.trim();return trimmed===""?null:trimmed}async function createAlias(db,input){if(validateAliasName(input.name),validateAliasCommand(input.command),validateAliasDescription(input.description),validateAliasCwd(input.cwd),await getAliasByName(db,input.name))throw new AliasConflictError(input.name);let now=new Date().toISOString(),row={id:crypto.randomUUID(),name:input.name,command:input.command,description:input.description,cwd:normalizeCwd(input.cwd),profile:getVibecontrolsProfile(),createdAt:now,updatedAt:now};return await db.setPluginState(ALIAS_PLUGIN_NAMESPACE,row.id,JSON.stringify(row)),row}async function updateAlias(db,name,patch){let current=await getAliasByName(db,name);if(!current)throw new AliasNotFoundError(name);if(patch.command!==void 0)validateAliasCommand(patch.command);if(patch.description!==void 0)validateAliasDescription(patch.description);if(patch.cwd!==void 0)validateAliasCwd(patch.cwd);let next={...current,command:patch.command??current.command,description:patch.description!==void 0?patch.description:current.description,cwd:patch.cwd!==void 0?normalizeCwd(patch.cwd):current.cwd,updatedAt:new Date().toISOString()};return await db.setPluginState(ALIAS_PLUGIN_NAMESPACE,next.id,JSON.stringify(next)),next}async function deleteAlias(db,name){let current=await getAliasByName(db,name);if(!current)throw new AliasNotFoundError(name);await db.deletePluginState(ALIAS_PLUGIN_NAMESPACE,current.id)}function activeProfileConfigOpts(){let ctx=currentProfileOrNull()??getDaemonProfile();return{dir:ctx.dataDir,scope:ctx.name}}function createRoutes(deps){let{serviceRegistry,db}=deps;return new Elysia().get("/api-key",()=>({apiKey:getAgentApiKey()})).get("/audit",({query})=>{let q=query,limit=q.limit?Math.min(5000,Math.max(1,Number.parseInt(q.limit,10)||100)):100,events=getDaemonProfile().audit.listEvents({since:q.since,limit,event:q.event});return{events,count:events.length}},{query:t.Object({since:t.Optional(t.String()),limit:t.Optional(t.String()),event:t.Optional(t.String())})}).get("/setup/check",()=>{let deps2=checkDependencies();return{ready:deps2.filter((d)=>d.required).every((d)=>d.installed),dependencies:deps2}}).post("/setup/install",async({request,server,set})=>{let denied=denyNonLocalMutation(request,"VIBECONTROLS_ALLOW_REMOTE_SETUP_INSTALL",server);if(denied)return set.status=403,{error:"Forbidden",message:denied};return await installDependencies()}).get("/url",async()=>{let tunnelProvider=serviceRegistry.getProvider("tunnel"),tunnelUrl=tunnelProvider&&tunnelProvider.getActiveTunnelUrl?await tunnelProvider.getActiveTunnelUrl():null,localUrl=`http://localhost:${process.env.PORT||3005}`;return{url:tunnelUrl||localUrl,tunnelUrl,localUrl,source:tunnelUrl?"tunnel":"local"}}).get("/lifecycle/state",()=>{return{state:serviceRegistry.getService("agent","lifecycle")?.getState()??"running"}}).post("/lifecycle/stop",async({set})=>{let lifecycle=serviceRegistry.getService("agent","lifecycle");if(!lifecycle)return set.status=500,{error:"Lifecycle manager not initialized"};return await lifecycle.stop(),{state:"stopped"}}).post("/lifecycle/start",async({set})=>{let lifecycle=serviceRegistry.getService("agent","lifecycle");if(!lifecycle)return set.status=500,{error:"Lifecycle manager not initialized"};return await lifecycle.start(),{state:"running"}}).post("/lifecycle/kill",async({set})=>{let lifecycle=serviceRegistry.getService("agent","lifecycle");if(!lifecycle)return set.status=500,{error:"Lifecycle manager not initialized"};return setTimeout(()=>lifecycle.kill(),100),{state:"killing"}}).post("/log-level",async({body,request,server,set})=>{let denied=denyNonLocalMutation(request,"VIBECONTROLS_ALLOW_REMOTE_LOG_LEVEL",server);if(denied)return set.status=403,{error:"Forbidden",message:denied};let next=String(body.level??"").toLowerCase();if(!["debug","info","warn","error"].includes(next))return set.status=400,{error:"Invalid level",message:"level must be debug | info | warn | error"};return getDaemonProfile().logger.setLevel(next),getDaemonProfile().logger.info("agent",`Log level set to ${next} via API`),{ok:!0,level:next}},{body:t.Object({level:t.String()})}).post("/reset",async({body,request,server,set})=>{if(!body.confirm)return set.status=400,{error:"Reset confirmation required",message:"Send { confirm: true } to reset local agent state."};let denied=denyNonLocalMutation(request,"VIBECONTROLS_ALLOW_REMOTE_RESET",server);if(denied)return set.status=403,{error:"Forbidden",message:denied};let lifecycle=serviceRegistry.getService("agent","lifecycle");try{if(lifecycle)await lifecycle.prepareForReset()}catch(err){getDaemonProfile().logger.warn("agent","prepareForReset failed during reset \u2014 proceeding to wipe anyway",{error:String(err)})}try{gatewayClient.configure({globalGatewayUrl:"",workspaceGatewayUrl:void 0,clientId:"",clientSecret:"",workspaceId:void 0})}catch{}await db.close();let{removed,agentDir}=wipeAgentDir();getDaemonProfile().logger.info("agent","Reset wiped local agent state",{agentDir,removed});let bytes=new Uint8Array(32);crypto.getRandomValues(bytes);let newApiKey=`vcak_${Buffer.from(bytes).toString("base64url")}`;return writeAgentConfig({"static-api-key":newApiKey},activeProfileConfigOpts()),getDaemonProfile().setBootState("awaiting-config"),set.status=200,{success:!0,state:"awaiting-config",...isLikelyLocalRequest(request,server)||process.env.VIBECONTROLS_RETURN_RESET_API_KEY==="1"?{newApiKey}:{},agentDir,removed}},{body:t.Object({confirm:t.Boolean()})}).post("/sessions/:sessionId/share",async({params,body,server,request,set})=>{if(!isLikelyLocalRequest(request,server)&&process.env.VIBECONTROLS_ALLOW_REMOTE_SESSION_SHARE!=="1")return set.status=403,{error:"Forbidden",message:"Session-share mint must come from a local request unless VIBECONTROLS_ALLOW_REMOTE_SESSION_SHARE=1."};let ttlMs=parseTtl(body?.expiresIn)??1800000,id=crypto.randomUUID(),bytes=new Uint8Array(32);crypto.getRandomValues(bytes);let key=`vcak_${Buffer.from(bytes).toString("base64url")}`,expiresAt=new Date(Date.now()+ttlMs).toISOString(),apiKeys=[...(await import("./agent-config-y63ddxgy.js")).readAgentConfig({dir:activeProfileConfigOpts().dir}).apiKeys??[],{id,name:`session-share:${params.sessionId}:${body?.label??"viewer"}`,key,scopes:["read"],expiresAt,createdAt:new Date().toISOString()}];(await import("./agent-config-y63ddxgy.js")).writeAgentConfig({apiKeys},activeProfileConfigOpts());let tunnelProvider=serviceRegistry.getProvider("tunnel"),joinUrl=`${((tunnelProvider&&tunnelProvider.getActiveTunnelUrl?await tunnelProvider.getActiveTunnelUrl():null)??`http://localhost:${process.env.PORT||3005}`).replace(/\/$/,"")}/ws/terminal?sessionId=${encodeURIComponent(params.sessionId)}&apiKey=${encodeURIComponent(key)}`;return getDaemonProfile().logger.info("session-share","Minted share credential",{sessionId:params.sessionId,keyId:id,expiresAt}),{ok:!0,keyId:id,apiKey:key,joinUrl,sessionId:params.sessionId,expiresAt}},{params:t.Object({sessionId:t.String()}),body:t.Optional(t.Object({permissions:t.Optional(t.Array(t.String())),expiresIn:t.Optional(t.String()),label:t.Optional(t.String())}))}).get("/aliases",async()=>{return{aliases:await listAliases(db)}}).get("/aliases/:name",async({params,set})=>{let alias=await getAliasByName(db,params.name);if(!alias)return set.status=404,{error:"Alias not found"};return alias},{params:t.Object({name:t.String()})}).post("/aliases",async({body,set})=>{try{let alias=await createAlias(db,body);return set.status=201,alias}catch(err){if(err instanceof AliasConflictError)return set.status=409,{error:"Alias already exists",message:err.message};if(err instanceof AliasValidationError)return set.status=400,{error:err.code,message:err.message};throw err}},{body:t.Object({name:t.String(),command:t.String(),description:t.Optional(t.String()),cwd:t.Optional(t.Union([t.String(),t.Null()]))})}).put("/aliases/:name",async({params,body,set})=>{try{return await updateAlias(db,params.name,body)}catch(err){if(err instanceof AliasNotFoundError)return set.status=404,{error:"Alias not found"};if(err instanceof AliasValidationError)return set.status=400,{error:err.code,message:err.message};throw err}},{params:t.Object({name:t.String()}),body:t.Object({command:t.Optional(t.String()),description:t.Optional(t.String()),cwd:t.Optional(t.Union([t.String(),t.Null()]))})}).delete("/aliases/:name",async({params,set})=>{try{return await deleteAlias(db,params.name),set.status=204,null}catch(err){if(err instanceof AliasNotFoundError)return set.status=404,{error:"Alias not found"};throw err}},{params:t.Object({name:t.String()})}).post("/aliases/:name/execute",async({params,body,set})=>{let alias=await getAliasByName(db,params.name);if(!alias)return set.status=404,{error:"Alias not found"};let args=body?.args??[],result=await runAliasCaptured(alias,args);getDaemonProfile().audit.emit("agent","alias.executed",{exit_code:result.exit_code});let telemetry=validateEvent("alias.executed",{exit_code:result.exit_code});if(!telemetry.ok)getDaemonProfile().logger.debug("alias",`telemetry validate failed: ${telemetry.reason}`);if(result.timed_out)set.status=408;return{exit_code:result.exit_code,stdout:result.stdout,stderr:result.stderr,duration_ms:result.duration_ms,truncated:result.truncated,cwd:result.cwd}},{params:t.Object({name:t.String()}),body:t.Optional(t.Object({args:t.Optional(t.Array(t.String()))}))}).post("/sessions/share/:keyId/revoke",async({params,server,request,set})=>{if(!isLikelyLocalRequest(request,server)&&process.env.VIBECONTROLS_ALLOW_REMOTE_SESSION_SHARE!=="1")return set.status=403,{error:"Forbidden"};let cfgMod=await import("./agent-config-y63ddxgy.js"),cfgOpts=activeProfileConfigOpts(),cfg=cfgMod.readAgentConfig({dir:cfgOpts.dir}),before=(cfg.apiKeys??[]).length,apiKeys=(cfg.apiKeys??[]).filter((k)=>k.id!==params.keyId);if(apiKeys.length===before)return set.status=404,{error:"No such share key"};return cfgMod.writeAgentConfig({apiKeys},cfgOpts),{ok:!0,revoked:params.keyId}},{params:t.Object({keyId:t.String()})})}function parseTtl(input){if(!input)return null;let m=/^(\d+)([smhdw]?)$/.exec(input.trim());if(!m)return null;let n=Number(m[1]),unit=m[2]||"m";return unit==="s"?n*1000:unit==="m"?n*60000:unit==="h"?n*3600000:unit==="d"?n*86400000:n*7*86400000}var DEFAULT_AGENT_URL="http://localhost:3005";function register2(program){program.command("health").description("Check health of a VibeControls agent instance").option("-n, --name <name>","Agent instance name").option("--agent-url <url>","Agent URL",DEFAULT_AGENT_URL).option("--json","Emit JSON").option("--plain","Force plain text output").action(async function(opts){try{let merged={...program.opts(),...opts};await runMultimode({mode:pickOutputMode(merged),fetchData:async()=>{if(merged.name){let result=await new ServiceManager().checkHealth(merged.name);return{mode:"named",agentUrl:getAgentUrl(merged),name:merged.name,healthy:result.healthy,details:result.details??{}}}let agentUrl=getAgentUrl(merged);try{let data=await apiGet(agentUrl,"/health");return{mode:"url",agentUrl,healthy:!0,details:data}}catch(err){return{mode:"url",agentUrl,healthy:!1,details:{status:"unhealthy",...err instanceof Error?{error:errMsg(err)}:{}}}}},plain:(data)=>{if(header("Agent Health"),blank(),data.mode==="named"){if(!data.healthy){fail(`Agent instance ${colors.bold(data.name??"")} is not responding.`);return}let details=data.details;if(kv("Instance",data.name??""),kv("Status",formatStatus(details.status??"healthy")),details.uptime!==void 0)kv("Uptime",`${details.uptime}s`);if(details.checks){blank(),info(`${icons.info} Health checks:`);for(let[name,check]of Object.entries(details.checks)){let icon=check.status==="healthy"?icons.success:icons.error;kv(` ${icon} ${name}`,formatStatus(check.status))}}}else{if(kv("URL",data.agentUrl),kv("Status",formatStatus(data.details.status??"unhealthy")),data.details.version)kv("Version",data.details.version);if(data.details.uptime!==void 0)kv("Uptime",`${data.details.uptime}s`);if(data.details.timestamp)kv("Timestamp",data.details.timestamp);if(data.details.checks){blank(),info(`${icons.info} Health checks:`);for(let[name,check]of Object.entries(data.details.checks)){let icon=check.status==="healthy"?icons.success:icons.error;kv(` ${icon} ${name}`,formatStatus(check.status))}}}if(blank(),data.healthy)success(`${icons.success} Agent is healthy.`)},interactive:async(data)=>{let lines=[];if(data.mode==="named")lines.push(`Instance: ${data.name??""}`);else lines.push(`URL: ${data.agentUrl}`);if(lines.push(`Status: ${formatStatus(data.details.status??(data.healthy?"healthy":"unhealthy"))}`),data.details.version)lines.push(`Version: ${data.details.version}`);if(data.details.uptime!==void 0)lines.push(`Uptime: ${data.details.uptime}s`);if(data.details.timestamp)lines.push(`Time: ${data.details.timestamp}`);if(data.details.checks){lines.push(""),lines.push("Checks:");for(let[name,check]of Object.entries(data.details.checks))lines.push(` ${name}: ${check.status}`)}await interactiveDetail({title:"Agent Health",body:lines.join(`
4
4
  `),footer:"press q to exit"})},json:(data)=>({mode:data.mode,agentUrl:data.agentUrl,name:data.name??null,healthy:data.healthy,details:data.details})})}catch(err){fail(`Health check failed: ${errMsg(err)}`)}})}import{platform,arch,release,hostname,cpus,totalmem}from"os";var DEFAULT_AGENT_URL2="http://localhost:3005";function register3(program){program.command("info").description("Show local and remote VibeControls agent information").option("--agent-url <url>","Agent URL",DEFAULT_AGENT_URL2).option("--json","Emit JSON").option("--plain","Force plain text output").action(async function(opts){try{let merged={...program.opts(),...opts},agentUrl=getAgentUrl(merged),profile=encodeURIComponent(resolveProfileName(merged));await runMultimode({mode:pickOutputMode(merged),fetchData:async()=>{let local={hostname:hostname(),platform:platform(),arch:arch(),release:release(),cpus:cpus().length,totalMemory:totalmem(),nodeVersion:process.version,bunVersion:process.versions.bun};try{let remote=await apiGet(agentUrl,`/api/profiles/${profile}/agent/version`);return{local,agentUrl,remote}}catch(err){return{local,agentUrl,remote:null,remoteError:err instanceof Error?errMsg(err):String(err)}}},plain:(data)=>{if(header("VibeControls Agent Info"),blank(),info(`${icons.info} Local System`),kv("Hostname",data.local.hostname),kv("Platform",`${data.local.platform} ${data.local.arch}`),kv("OS Release",data.local.release),kv("CPUs",String(data.local.cpus)),kv("Total Memory",formatBytes(data.local.totalMemory)),kv("Node.js",data.local.nodeVersion),data.local.bunVersion)kv("Bun",data.local.bunVersion);if(blank(),info(`${icons.info} Remote Agent`),kv("URL",data.agentUrl),data.remote){if(kv("Version",colors.bold(data.remote.version)),data.remote.build)kv("Build",data.remote.build);if(data.remote.commit)kv("Commit",data.remote.commit);if(data.remote.nodeVersion)kv("Node.js (remote)",data.remote.nodeVersion);if(data.remote.bunVersion)kv("Bun (remote)",data.remote.bunVersion)}else kv("Status",colors.dim("not reachable"));blank()},interactive:async(data)=>{let lines=[];if(lines.push("Local System"),lines.push(` Hostname: ${data.local.hostname}`),lines.push(` Platform: ${data.local.platform} ${data.local.arch}`),lines.push(` OS Release: ${data.local.release}`),lines.push(` CPUs: ${data.local.cpus}`),lines.push(` Total Memory: ${formatBytes(data.local.totalMemory)}`),lines.push(` Node.js: ${data.local.nodeVersion}`),data.local.bunVersion)lines.push(` Bun: ${data.local.bunVersion}`);if(lines.push(""),lines.push("Remote Agent"),lines.push(` URL: ${data.agentUrl}`),data.remote){if(lines.push(` Version: ${data.remote.version}`),data.remote.build)lines.push(` Build: ${data.remote.build}`);if(data.remote.commit)lines.push(` Commit: ${data.remote.commit}`);if(data.remote.nodeVersion)lines.push(` Node.js: ${data.remote.nodeVersion} (remote)`);if(data.remote.bunVersion)lines.push(` Bun: ${data.remote.bunVersion} (remote)`)}else lines.push(" Status: not reachable");await interactiveDetail({title:"VibeControls Agent Info",body:lines.join(`
5
5
  `),footer:"press q to exit"})},json:(data)=>({local:data.local,agentUrl:data.agentUrl,remote:data.remote,remoteError:data.remoteError??null})})}catch(err){fail(`Failed to get info: ${errMsg(err)}`)}})}var DEFAULT_AGENT_URL3="http://localhost:3005";function register4(program){program.command("system").description("Show system information for a running VibeControls agent").option("--agent-url <url>","Agent URL",DEFAULT_AGENT_URL3).option("--json","Emit JSON").option("--plain","Force plain text output").action(async function(opts){try{let merged={...program.opts(),...opts},agentUrl=getAgentUrl(merged),profile=encodeURIComponent(resolveProfileName(merged));await runMultimode({mode:pickOutputMode(merged),fetchData:()=>apiGet(agentUrl,`/api/profiles/${profile}/agent/system`),plain:(data)=>{if(header("Agent System Information"),blank(),info(`${icons.info} Agent`),kv("Version",colors.bold(data.agentVersion)),data.bunVersion)kv("Bun",data.bunVersion);if(data.environment)kv("Environment",data.environment);kv("Uptime",formatDuration(data.uptime)),blank(),info(`${icons.info} Platform`),kv("OS",`${data.platform} ${data.arch}`),kv("Hostname",data.hostname),kv("Release",data.release),blank(),info(`${icons.info} Resources`),kv("CPUs",String(data.cpus)),kv("Total Memory",formatBytes(data.totalMemory)),kv("Free Memory",formatBytes(data.freeMemory)),blank(),info(`${icons.info} Paths`),kv("Home",data.homeDir),kv("CWD",data.cwd),blank()},interactive:async(data)=>{let lines=["Agent",` Version: ${data.agentVersion}`,...data.bunVersion?[` Bun: ${data.bunVersion}`]:[],...data.environment?[` Environment: ${data.environment}`]:[],` Uptime: ${formatDuration(data.uptime)}`,"","Platform",` OS: ${data.platform} ${data.arch}`,` Hostname: ${data.hostname}`,` Release: ${data.release}`,"","Resources",` CPUs: ${data.cpus}`,` Total Mem: ${formatBytes(data.totalMemory)}`,` Free Mem: ${formatBytes(data.freeMemory)}`,"","Paths",` Home: ${data.homeDir}`,` CWD: ${data.cwd}`];await interactiveDetail({title:"Agent System Information",body:lines.join(`
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{CliContributorRegistry,createIframeBridge}from"./index-yke24mr4.js";import{PluginManager,ServiceRegistry}from"./index-kf5tas0g.js";import{getOsAdapter}from"./index-srbb2214.js";import{mountProfileRoutes}from"./index-brtw3j8x.js";import{getAgentApiKey}from"./index-b4wy3jrt.js";import{readAgentConfigWithSecrets,writeAgentConfig}from"./index-2pqv0bya.js";import{assertAllowedGatewayUrl,gatewayClient,getDaemonProfile,getOrCreateProfile,profileRegistry,sanitizeOperatorTunnelUrl,sanitizeTunnelUrl}from"./index-7pdmqbj8.js";import{getVibecontrolsProductDir,validateAgentName}from"./index-bysm7taq.js";import{__require}from"./index-e9rt4m94.js";var RETRY_BACKOFFS_MS=[0,5000,15000,30000,60000],RATE_LIMIT_BUFFER_MS=2000,RATE_LIMIT_MIN_WAIT_MS=5000,RATE_LIMIT_MAX_WAIT_MS=120000,RATE_LIMIT_MAX_RETRIES=10,MAX_GATEWAY_RESPONSE_BYTES=1048576;class RateLimitError extends Error{resetAt;resource;constructor(message,resource,resetAt){super(message);this.name="RateLimitError",this.resource=resource,this.resetAt=resetAt}}function detectRateLimit(errors,resource){if(!errors?.length)return null;let hit=errors.find((e)=>e.extensions?.code==="RATE_LIMITED");if(!hit)return null;let resetRaw=hit.extensions?.resetAt,resetAt=null;if(resetRaw){let parsed=new Date(resetRaw);if(!Number.isNaN(parsed.getTime()))resetAt=parsed}return new RateLimitError(`${resource} rate limited${resetAt?` until ${resetAt.toISOString()}`:""}`,resource,resetAt)}function computeRateLimitDelay(err){if(!err.resetAt)return 60000;let waitMs=err.resetAt.getTime()-Date.now()+RATE_LIMIT_BUFFER_MS;return Math.min(Math.max(waitMs,RATE_LIMIT_MIN_WAIT_MS),RATE_LIMIT_MAX_WAIT_MS)}async function readResponseTextCapped(response,maxBytes){let contentLength=response.headers.get("content-length");if(contentLength){let parsed=Number.parseInt(contentLength,10);if(Number.isInteger(parsed)&&parsed>maxBytes)throw Error(`Gateway response is too large (${parsed} bytes)`)}if(!response.body)return"";let reader=response.body.getReader(),chunks=[],total=0;try{while(!0){let{done,value}=await reader.read();if(done)break;if(!value)continue;if(total+=value.byteLength,total>maxBytes)throw await reader.cancel().catch(()=>{return}),Error(`Gateway response exceeds ${maxBytes} bytes`);chunks.push(value)}}finally{reader.releaseLock()}let merged=new Uint8Array(total),offset=0;for(let chunk of chunks)merged.set(chunk,offset),offset+=chunk.byteLength;return new TextDecoder().decode(merged)}async function readGraphqlJson(response,resource){let raw=await readResponseTextCapped(response,MAX_GATEWAY_RESPONSE_BYTES),data;try{data=raw?JSON.parse(raw):{}}catch(err){let preview=raw.slice(0,240).replace(/\s+/g," ");throw Error(`${resource} returned non-JSON response (${response.status} ${response.statusText})${preview?`: ${preview}`:""}`,{cause:err})}if(!response.ok){let preview=raw.slice(0,240).replace(/\s+/g," ");throw Error(`${resource} failed (${response.status} ${response.statusText})${preview?`: ${preview}`:""}`)}return data}function ensureGraphqlSuffix(url){return url.endsWith("/graphql")?url:`${url}/graphql`}function isLocalDevGatewayHost(url){let host;try{host=new URL(url).hostname.toLowerCase().replace(/^\[|\]$/g,"")}catch{return!1}if(host==="localhost"||host==="127.0.0.1"||host==="::1"||host==="0.0.0.0"||host==="host.docker.internal")return!0;return host.endsWith(".localhost")||host.endsWith(".local")||host.endsWith(".local.burdenoff.com")}function devTlsFetchInit(url){if(!(process.env.VIBE_DEV_INSECURE_TLS==="1"||process.env.NODE_TLS_REJECT_UNAUTHORIZED==="0")&&!isLocalDevGatewayHost(url))return{};return{tls:{rejectUnauthorized:!1}}}async function authenticateApp(globalGatewayUrl,clientId,clientSecret){let res=await fetch(ensureGraphqlSuffix(globalGatewayUrl),{method:"POST",...devTlsFetchInit(globalGatewayUrl),headers:{"Content-Type":"application/json"},body:JSON.stringify({query:`mutation AuthenticateApp($input: AuthenticateAppInput!) {
2
+ import{CliContributorRegistry,createIframeBridge}from"./index-n3y918j2.js";import{PluginManager,ServiceRegistry}from"./index-h6a1kkfk.js";import{getOsAdapter}from"./index-srbb2214.js";import{mountProfileRoutes}from"./index-brtw3j8x.js";import{getAgentApiKey}from"./index-b4wy3jrt.js";import{readAgentConfigWithSecrets,writeAgentConfig}from"./index-2pqv0bya.js";import{assertAllowedGatewayUrl,gatewayClient,getDaemonProfile,getOrCreateProfile,profileRegistry,sanitizeOperatorTunnelUrl,sanitizeTunnelUrl}from"./index-7pdmqbj8.js";import{getVibecontrolsProductDir,validateAgentName}from"./index-bysm7taq.js";import{__require}from"./index-e9rt4m94.js";var RETRY_BACKOFFS_MS=[0,5000,15000,30000,60000],RATE_LIMIT_BUFFER_MS=2000,RATE_LIMIT_MIN_WAIT_MS=5000,RATE_LIMIT_MAX_WAIT_MS=120000,RATE_LIMIT_MAX_RETRIES=10,MAX_GATEWAY_RESPONSE_BYTES=1048576;class RateLimitError extends Error{resetAt;resource;constructor(message,resource,resetAt){super(message);this.name="RateLimitError",this.resource=resource,this.resetAt=resetAt}}function detectRateLimit(errors,resource){if(!errors?.length)return null;let hit=errors.find((e)=>e.extensions?.code==="RATE_LIMITED");if(!hit)return null;let resetRaw=hit.extensions?.resetAt,resetAt=null;if(resetRaw){let parsed=new Date(resetRaw);if(!Number.isNaN(parsed.getTime()))resetAt=parsed}return new RateLimitError(`${resource} rate limited${resetAt?` until ${resetAt.toISOString()}`:""}`,resource,resetAt)}function computeRateLimitDelay(err){if(!err.resetAt)return 60000;let waitMs=err.resetAt.getTime()-Date.now()+RATE_LIMIT_BUFFER_MS;return Math.min(Math.max(waitMs,RATE_LIMIT_MIN_WAIT_MS),RATE_LIMIT_MAX_WAIT_MS)}async function readResponseTextCapped(response,maxBytes){let contentLength=response.headers.get("content-length");if(contentLength){let parsed=Number.parseInt(contentLength,10);if(Number.isInteger(parsed)&&parsed>maxBytes)throw Error(`Gateway response is too large (${parsed} bytes)`)}if(!response.body)return"";let reader=response.body.getReader(),chunks=[],total=0;try{while(!0){let{done,value}=await reader.read();if(done)break;if(!value)continue;if(total+=value.byteLength,total>maxBytes)throw await reader.cancel().catch(()=>{return}),Error(`Gateway response exceeds ${maxBytes} bytes`);chunks.push(value)}}finally{reader.releaseLock()}let merged=new Uint8Array(total),offset=0;for(let chunk of chunks)merged.set(chunk,offset),offset+=chunk.byteLength;return new TextDecoder().decode(merged)}async function readGraphqlJson(response,resource){let raw=await readResponseTextCapped(response,MAX_GATEWAY_RESPONSE_BYTES),data;try{data=raw?JSON.parse(raw):{}}catch(err){let preview=raw.slice(0,240).replace(/\s+/g," ");throw Error(`${resource} returned non-JSON response (${response.status} ${response.statusText})${preview?`: ${preview}`:""}`,{cause:err})}if(!response.ok){let preview=raw.slice(0,240).replace(/\s+/g," ");throw Error(`${resource} failed (${response.status} ${response.statusText})${preview?`: ${preview}`:""}`)}return data}function ensureGraphqlSuffix(url){return url.endsWith("/graphql")?url:`${url}/graphql`}function isLocalDevGatewayHost(url){let host;try{host=new URL(url).hostname.toLowerCase().replace(/^\[|\]$/g,"")}catch{return!1}if(host==="localhost"||host==="127.0.0.1"||host==="::1"||host==="0.0.0.0"||host==="host.docker.internal")return!0;return host.endsWith(".localhost")||host.endsWith(".local")||host.endsWith(".local.burdenoff.com")}function devTlsFetchInit(url){if(!(process.env.VIBE_DEV_INSECURE_TLS==="1"||process.env.NODE_TLS_REJECT_UNAUTHORIZED==="0")&&!isLocalDevGatewayHost(url))return{};return{tls:{rejectUnauthorized:!1}}}async function authenticateApp(globalGatewayUrl,clientId,clientSecret){let res=await fetch(ensureGraphqlSuffix(globalGatewayUrl),{method:"POST",...devTlsFetchInit(globalGatewayUrl),headers:{"Content-Type":"application/json"},body:JSON.stringify({query:`mutation AuthenticateApp($input: AuthenticateAppInput!) {
3
3
  authenticateApp(input: $input) { accessToken expiresIn }
4
4
  }`,variables:{input:{clientId,clientSecret,scopes:[]}}}),signal:AbortSignal.timeout(15000)}),data=await readGraphqlJson(res,"authenticateApp"),rl=detectRateLimit(data.errors,"authenticateApp");if(rl)throw rl;if(data.errors?.length){let codes=data.errors.map((e)=>e.extensions?.code??"UNKNOWN").join(",");throw Error(`authenticateApp errors [${codes}]: ${data.errors.map((e)=>e.message).join("; ")}`)}let token=data.data?.authenticateApp?.accessToken;if(!token)throw Error("authenticateApp returned no token");return token}async function issueWorkspaceToken(workspaceGatewayUrl,appToken,workspaceId,organizationId){let res=await fetch(ensureGraphqlSuffix(workspaceGatewayUrl),{method:"POST",...devTlsFetchInit(workspaceGatewayUrl),headers:{"Content-Type":"application/json",Authorization:`Bearer ${appToken}`},body:JSON.stringify({query:`mutation IssueAgentWorkspaceToken($input: IssueWorkspaceTokenInput!) {
5
5
  issueWorkspaceToken(input: $input) {
@@ -170,9 +170,9 @@ data: /message
170
170
  isActive
171
171
  }
172
172
  }
173
- `;function getAgentVersion(){try{let __dirname2=dirname(fileURLToPath(import.meta.url)),pkgPath=join7(__dirname2,"..","..","..","package.json");return JSON.parse(readFileSync5(pkgPath,"utf8")).version||"0.0.0"}catch{return"0.0.0"}}async function waitForTunnelUrl(serviceRegistry){if(process.env.AGENT_TUNNEL_URL){let safeUrl=sanitizeOperatorTunnelUrl(process.env.AGENT_TUNNEL_URL);if(!safeUrl)return getDaemonProfile().logger.warn(LOG_SOURCE2,"Ignoring invalid AGENT_TUNNEL_URL"),null;return getDaemonProfile().logger.debug(LOG_SOURCE2,`Using AGENT_TUNNEL_URL from environment: ${safeUrl}`),safeUrl}for(let attempt=1;attempt<=MAX_RETRIES;attempt++){let providers=[],defaultProvider=serviceRegistry.getProvider("tunnel");if(defaultProvider)providers.push(defaultProvider);for(let entry of serviceRegistry.listProvidersForType("tunnel")){let provider=serviceRegistry.getProviderByName("tunnel",entry.pluginName);if(provider&&!providers.includes(provider))providers.push(provider)}for(let tunnelProvider of providers){if(!tunnelProvider.getActiveTunnelUrl)continue;let url=await tunnelProvider.getActiveTunnelUrl(),safeUrl=sanitizeTunnelUrl(url);if(safeUrl)return getDaemonProfile().logger.debug(LOG_SOURCE2,`Tunnel URL available on attempt ${attempt}: ${safeUrl}`),safeUrl;if(url)getDaemonProfile().logger.warn(LOG_SOURCE2,"Tunnel provider returned invalid URL",{url})}if(attempt<MAX_RETRIES)getDaemonProfile().logger.debug(LOG_SOURCE2,`Tunnel URL not ready, retrying in ${RETRY_INTERVAL_MS/1000}s (attempt ${attempt}/${MAX_RETRIES})`),await new Promise((resolve)=>setTimeout(resolve,RETRY_INTERVAL_MS))}return getDaemonProfile().logger.warn(LOG_SOURCE2,`Tunnel URL not available after ${MAX_RETRIES} attempts`),null}async function getOrDiscoverAgentRecordId(db,hostname){let cachedAgentRecordId=await db.getConfig("gateway-auth:agentRecordId");if(cachedAgentRecordId)return cachedAgentRecordId;let workspaceId=await db.getConfig("gateway-auth:workspaceId");if(!workspaceId)return null;let result=await gatewayClient.workspaceQuery(FIND_EXISTING_AGENT_QUERY,{workspaceId});if(result.errors?.length)return getDaemonProfile().logger.warn(LOG_SOURCE2,"Failed to discover existing agent record",{errors:result.errors.map((error3)=>error3.message)}),null;let normalizedHostname=hostname.toLowerCase(),match=result.data?.vibecontrolsAgents?.find((agent)=>agent.hostname.toLowerCase()===normalizedHostname);if(!match)return null;return await db.setConfig("gateway-auth:agentRecordId",match.id),getDaemonProfile().logger.info(LOG_SOURCE2,"Recovered existing agent record ID",{agentRecordId:match.id,hostname}),match.id}async function reportLifecycleState(db,state){if(!gatewayClient.isConfigured())return;let agentRecordId=await getOrDiscoverAgentRecordId(db,process.env.VIBE_AGENT_NAME||os.hostname());if(!agentRecordId)return;if(state!=="killed"){getDaemonProfile().logger.debug(LOG_SOURCE2,`Skipping '${state}' lifecycle sync \u2014 startup auto-report already refreshes the live agent record and the current backend schema has no dedicated lifecycle field.`);return}let result=await gatewayClient.workspaceQuery(DEACTIVATE_AGENT_MUTATION,{id:agentRecordId});if(result.errors?.length)getDaemonProfile().logger.warn(LOG_SOURCE2,`Failed to report lifecycle state '${state}'`,{errors:result.errors.map((e)=>e.message)});else getDaemonProfile().logger.info(LOG_SOURCE2,`Reported lifecycle state: ${state}`)}async function verifyAndRetryUpdate(agentRecordId,tunnelUrl,apiKey,workspaceId){let wsId=workspaceId||gatewayClient.getConfig()?.workspaceId||"";for(let attempt=1;attempt<=3;attempt++){await new Promise((r)=>setTimeout(r,1500));let backendUrl=(await gatewayClient.workspaceQuery(FIND_EXISTING_AGENT_QUERY,{workspaceId:wsId})).data?.vibecontrolsAgents?.find((a)=>a.id===agentRecordId)?.tunnelUrl??null;if(backendUrl===tunnelUrl)return getDaemonProfile().logger.info(LOG_SOURCE2,`Verified: backend tunnelUrl matches (attempt ${attempt})`),!0;getDaemonProfile().logger.warn(LOG_SOURCE2,`Verification failed (attempt ${attempt}/3): backend has '${backendUrl}', expected '${tunnelUrl}' \u2014 retrying update`),await gatewayClient.workspaceQuery(UPDATE_AGENT_MUTATION,{id:agentRecordId,input:{tunnelUrl:tunnelUrl||null,tunnelStatus:tunnelUrl?"CONNECTED":"DISCONNECTED",agentApiKey:apiKey}})}return getDaemonProfile().logger.error(LOG_SOURCE2,"Failed to verify tunnel URL update after 3 attempts"),!1}async function sendHeartbeat(agentRecordId){try{let result=await gatewayClient.workspaceQuery(HEARTBEAT_MUTATION,{id:agentRecordId});if(result.errors?.length)getDaemonProfile().logger.debug(LOG_SOURCE2,"Heartbeat returned errors",{errors:result.errors.map((e)=>e.message)});else getDaemonProfile().logger.debug(LOG_SOURCE2,"Heartbeat sent successfully")}catch(err){getDaemonProfile().logger.debug(LOG_SOURCE2,`Heartbeat failed: ${err instanceof Error?err.message:String(err)}`)}}var NOTIFY_PLUGIN_CHANGE_MUTATION=`
173
+ `;function getAgentVersion(){try{let __dirname2=dirname(fileURLToPath(import.meta.url)),pkgPath=join7(__dirname2,"..","..","..","package.json");return JSON.parse(readFileSync5(pkgPath,"utf8")).version||"0.0.0"}catch{return"0.0.0"}}async function waitForTunnelUrl(serviceRegistry){if(process.env.AGENT_TUNNEL_URL){let safeUrl=sanitizeOperatorTunnelUrl(process.env.AGENT_TUNNEL_URL);if(!safeUrl)return getDaemonProfile().logger.warn(LOG_SOURCE2,"Ignoring invalid AGENT_TUNNEL_URL"),null;return getDaemonProfile().logger.debug(LOG_SOURCE2,`Using AGENT_TUNNEL_URL from environment: ${safeUrl}`),safeUrl}for(let attempt=1;attempt<=MAX_RETRIES;attempt++){let providers=[],defaultProvider=serviceRegistry.getProvider("tunnel");if(defaultProvider)providers.push(defaultProvider);for(let entry of serviceRegistry.listProvidersForType("tunnel")){let provider=serviceRegistry.getProviderByName("tunnel",entry.pluginName);if(provider&&!providers.includes(provider))providers.push(provider)}for(let tunnelProvider of providers){if(!tunnelProvider.getActiveTunnelUrl)continue;let url=await tunnelProvider.getActiveTunnelUrl(),safeUrl=sanitizeTunnelUrl(url);if(safeUrl)return getDaemonProfile().logger.debug(LOG_SOURCE2,`Tunnel URL available on attempt ${attempt}: ${safeUrl}`),safeUrl;if(url)getDaemonProfile().logger.warn(LOG_SOURCE2,"Tunnel provider returned invalid URL",{url})}if(attempt<MAX_RETRIES)getDaemonProfile().logger.debug(LOG_SOURCE2,`Tunnel URL not ready, retrying in ${RETRY_INTERVAL_MS/1000}s (attempt ${attempt}/${MAX_RETRIES})`),await new Promise((resolve)=>setTimeout(resolve,RETRY_INTERVAL_MS))}return getDaemonProfile().logger.warn(LOG_SOURCE2,`Tunnel URL not available after ${MAX_RETRIES} attempts`),null}async function getOrDiscoverAgentRecordId(db,hostname){let cachedAgentRecordId=await db.getConfig("gateway-auth:agentRecordId");if(cachedAgentRecordId)return cachedAgentRecordId;let workspaceId=await db.getConfig("gateway-auth:workspaceId");if(!workspaceId)return null;let result=await gatewayClient.workspaceQuery(FIND_EXISTING_AGENT_QUERY,{workspaceId});if(result.errors?.length)return getDaemonProfile().logger.warn(LOG_SOURCE2,"Failed to discover existing agent record",{errors:result.errors.map((error3)=>error3.message)}),null;let normalizedHostname=hostname.toLowerCase(),match=result.data?.vibecontrolsAgents?.find((agent)=>agent.hostname.toLowerCase()===normalizedHostname);if(!match)return null;return await db.setConfig("gateway-auth:agentRecordId",match.id),getDaemonProfile().logger.info(LOG_SOURCE2,"Recovered existing agent record ID",{agentRecordId:match.id,hostname}),match.id}async function agentRecordExists(workspaceId,agentRecordId){try{let result=await gatewayClient.workspaceQuery(FIND_EXISTING_AGENT_QUERY,{workspaceId});if(result.errors?.length)return!0;let agents=result.data?.vibecontrolsAgents;if(!agents)return!0;return agents.some((a)=>a.id===agentRecordId)}catch{return!0}}async function reportLifecycleState(db,state){if(!gatewayClient.isConfigured())return;let agentRecordId=await getOrDiscoverAgentRecordId(db,process.env.VIBE_AGENT_NAME||os.hostname());if(!agentRecordId)return;if(state!=="killed"){getDaemonProfile().logger.debug(LOG_SOURCE2,`Skipping '${state}' lifecycle sync \u2014 startup auto-report already refreshes the live agent record and the current backend schema has no dedicated lifecycle field.`);return}let result=await gatewayClient.workspaceQuery(DEACTIVATE_AGENT_MUTATION,{id:agentRecordId});if(result.errors?.length)getDaemonProfile().logger.warn(LOG_SOURCE2,`Failed to report lifecycle state '${state}'`,{errors:result.errors.map((e)=>e.message)});else getDaemonProfile().logger.info(LOG_SOURCE2,`Reported lifecycle state: ${state}`)}async function verifyAndRetryUpdate(agentRecordId,tunnelUrl,apiKey,workspaceId){let wsId=workspaceId||gatewayClient.getConfig()?.workspaceId||"";for(let attempt=1;attempt<=3;attempt++){await new Promise((r)=>setTimeout(r,1500));let backendUrl=(await gatewayClient.workspaceQuery(FIND_EXISTING_AGENT_QUERY,{workspaceId:wsId})).data?.vibecontrolsAgents?.find((a)=>a.id===agentRecordId)?.tunnelUrl??null;if(backendUrl===tunnelUrl)return getDaemonProfile().logger.info(LOG_SOURCE2,`Verified: backend tunnelUrl matches (attempt ${attempt})`),!0;getDaemonProfile().logger.warn(LOG_SOURCE2,`Verification failed (attempt ${attempt}/3): backend has '${backendUrl}', expected '${tunnelUrl}' \u2014 retrying update`),await gatewayClient.workspaceQuery(UPDATE_AGENT_MUTATION,{id:agentRecordId,input:{tunnelUrl:tunnelUrl||null,tunnelStatus:tunnelUrl?"CONNECTED":"DISCONNECTED",agentApiKey:apiKey}})}return getDaemonProfile().logger.error(LOG_SOURCE2,"Failed to verify tunnel URL update after 3 attempts"),!1}async function sendHeartbeat(agentRecordId){try{let result=await gatewayClient.workspaceQuery(HEARTBEAT_MUTATION,{id:agentRecordId});if(result.errors?.length)getDaemonProfile().logger.debug(LOG_SOURCE2,"Heartbeat returned errors",{errors:result.errors.map((e)=>e.message)});else getDaemonProfile().logger.debug(LOG_SOURCE2,"Heartbeat sent successfully")}catch(err){getDaemonProfile().logger.debug(LOG_SOURCE2,`Heartbeat failed: ${err instanceof Error?err.message:String(err)}`)}}var NOTIFY_PLUGIN_CHANGE_MUTATION=`
174
174
  mutation NotifyVibecontrolsAgentPluginChange($agentId: ID!) {
175
175
  notifyVibecontrolsAgentPluginChange(agentId: $agentId)
176
176
  }
177
- `;async function notifyBackendPluginChange(db){try{if(!gatewayClient.isConfigured())return;let agentRecordId=await db.getConfig("gateway-auth:agentRecordId");if(!agentRecordId)return;let result=await gatewayClient.workspaceQuery(NOTIFY_PLUGIN_CHANGE_MUTATION,{agentId:agentRecordId});if(result.errors?.length)getDaemonProfile().logger.debug(LOG_SOURCE2,"Plugin-change notify returned errors",{errors:result.errors.map((e)=>e.message)})}catch(err){getDaemonProfile().logger.debug(LOG_SOURCE2,`Plugin-change notify failed: ${err instanceof Error?err.message:String(err)}`)}}var tunnelSyncInterval=null,lastReportedTunnelUrl=null;function startTunnelSync(db,serviceRegistry,apiKey,intervalMs){if(tunnelSyncInterval)return;let envOverride=Number(process.env.VIBE_TUNNEL_SYNC_MS),period=Number.isFinite(envOverride)&&envOverride>0?envOverride:intervalMs??60000;tunnelSyncInterval=setInterval(async()=>{if(!gatewayClient.isConfigured())return;try{let tunnelProvider=serviceRegistry.getProvider("tunnel");if(!tunnelProvider||!tunnelProvider.getActiveTunnelUrl)return;let currentUrl=sanitizeTunnelUrl(await tunnelProvider.getActiveTunnelUrl()),agentRecordId=await db.getConfig("gateway-auth:agentRecordId");if(!agentRecordId)return;if(await sendHeartbeat(agentRecordId),!currentUrl)return;let wsId=gatewayClient.getConfig()?.workspaceId||"",backendUrl;if(wsId)backendUrl=(await gatewayClient.workspaceQuery(FIND_EXISTING_AGENT_QUERY,{workspaceId:wsId})).data?.vibecontrolsAgents?.find((a)=>a.id===agentRecordId)?.tunnelUrl??null;let localChanged=currentUrl!==lastReportedTunnelUrl,backendDrifted=backendUrl!==void 0&&backendUrl!==currentUrl;if(!localChanged&&!backendDrifted)return;getDaemonProfile().logger.info(LOG_SOURCE2,"Re-publishing tunnel URL",{reason:backendDrifted?"backend-drift":"local-change",backend:backendUrl,local:currentUrl,lastReported:lastReportedTunnelUrl});let result=await gatewayClient.workspaceQuery(UPDATE_AGENT_MUTATION,{id:agentRecordId,input:{tunnelUrl:currentUrl,tunnelStatus:"CONNECTED",agentApiKey:apiKey}});if(!result.errors?.length)lastReportedTunnelUrl=currentUrl,getDaemonProfile().logger.info(LOG_SOURCE2,"Tunnel URL synced to backend",{tunnelUrl:currentUrl});else getDaemonProfile().logger.warn(LOG_SOURCE2,"Tunnel URL sync returned errors",{errors:result.errors.map((e)=>e.message)})}catch(err){getDaemonProfile().logger.debug(LOG_SOURCE2,`Tunnel sync check failed: ${err instanceof Error?err.message:String(err)}`)}},period),tunnelSyncInterval.unref?.()}function stopTunnelSync(){if(tunnelSyncInterval)clearInterval(tunnelSyncInterval),tunnelSyncInterval=null}async function autoReportToBackend(db,serviceRegistry,apiKey){if(!gatewayClient.isConfigured()){getDaemonProfile().logger.debug(LOG_SOURCE2,"Gateway auth not configured \u2014 skipping auto-report");return}let workspaceId=await db.getConfig("gateway-auth:workspaceId");if(!workspaceId){getDaemonProfile().logger.warn(LOG_SOURCE2,"No workspaceId configured \u2014 skipping auto-report. "+"Configure via POST /api/agent/gateway-auth with workspaceId.");return}getDaemonProfile().logger.info(LOG_SOURCE2,"Starting auto-report to backend...");try{let hostname=process.env.VIBE_AGENT_NAME||os.hostname(),platform=os.platform(),arch=os.arch(),version=getAgentVersion(),tunnelUrl=await waitForTunnelUrl(serviceRegistry),agentRecordId=await getOrDiscoverAgentRecordId(db,hostname);if(agentRecordId){getDaemonProfile().logger.info(LOG_SOURCE2,`Updating agent record ${agentRecordId} via workspace gateway`);let result2=await gatewayClient.workspaceQuery(UPDATE_AGENT_MUTATION,{id:agentRecordId,input:{tunnelUrl:tunnelUrl||null,tunnelStatus:tunnelUrl?"CONNECTED":"DISCONNECTED",agentApiKey:apiKey}});if(result2.errors?.length)getDaemonProfile().logger.warn(LOG_SOURCE2,"Update mutation returned errors",{errors:result2.errors.map((e)=>e.message)});else{getDaemonProfile().logger.info(LOG_SOURCE2,"Agent record updated successfully",{agentRecordId,tunnelUrl}),await verifyAndRetryUpdate(agentRecordId,tunnelUrl,apiKey,workspaceId),await sendHeartbeat(agentRecordId),lastReportedTunnelUrl=tunnelUrl,startTunnelSync(db,serviceRegistry,apiKey),startProfileReconciler(db);return}}getDaemonProfile().logger.info(LOG_SOURCE2,`Registering installed agent via workspace gateway (hostname: ${hostname})`);let result=await gatewayClient.workspaceQuery(REGISTER_INSTALLED_AGENT_MUTATION,{workspaceId,input:{name:hostname,hostname,platform,architecture:arch,tunnelUrl:tunnelUrl||null,agentApiKey:apiKey}});if(result.errors?.length){getDaemonProfile().logger.error(LOG_SOURCE2,"Register installed agent mutation failed",{errors:result.errors.map((e)=>e.message)});return}let registeredId=result.data?.registerInstalledAgent?.id;if(registeredId)await db.setConfig("gateway-auth:agentRecordId",registeredId),agentRecordId=registeredId,getDaemonProfile().logger.info(LOG_SOURCE2,"Agent registered successfully",{agentRecordId:registeredId,name:result.data?.registerInstalledAgent?.name,tunnelUrl,version});if(!agentRecordId)return;let updateResult=await gatewayClient.workspaceQuery(UPDATE_AGENT_MUTATION,{id:agentRecordId,input:{tunnelUrl:tunnelUrl||null,tunnelStatus:tunnelUrl?"CONNECTED":"DISCONNECTED",agentApiKey:apiKey}});if(updateResult.errors?.length)getDaemonProfile().logger.warn(LOG_SOURCE2,"Post-registration agent update returned errors",{errors:updateResult.errors.map((error3)=>error3.message)});else getDaemonProfile().logger.info(LOG_SOURCE2,"Post-registration agent sync completed",{agentRecordId,tunnelUrl});if(await verifyAndRetryUpdate(agentRecordId,tunnelUrl,apiKey,workspaceId),await sendHeartbeat(agentRecordId),lastReportedTunnelUrl=tunnelUrl,startTunnelSync(db,serviceRegistry,apiKey),startProfileReconciler(db),process.env.VIBE_BRIDGE_DISABLED!=="1")try{let{bridgeClient}=await import("./bridge-client-nsed8aw4.js"),profile=process.env.VIBECONTROLS_PROFILE||"default";bridgeClient.start(agentRecordId,profile)}catch(err){getDaemonProfile().logger.warn(LOG_SOURCE2,`bridge-client start failed: ${err instanceof Error?err.message:String(err)}`)}}catch(err){getDaemonProfile().logger.error(LOG_SOURCE2,`Auto-report failed: ${err instanceof Error?err.message:String(err)}`);try{startTunnelSync(db,serviceRegistry,apiKey),startProfileReconciler(db)}catch{}}}var LOG_SOURCE3="lifecycle";class LifecycleManager{serviceRegistry;pluginManager;db;app;hostServices;appStopFn;state="running";transition=Promise.resolve();constructor(serviceRegistry,pluginManager,db,app,hostServices,appStopFn){this.serviceRegistry=serviceRegistry;this.pluginManager=pluginManager;this.db=db;this.app=app;this.hostServices=hostServices;this.appStopFn=appStopFn}getState(){return this.state}enqueueTransition(name,fn){let run=this.transition.then(fn,fn);return this.transition=run.catch((err)=>{getDaemonProfile().logger.warn(LOG_SOURCE3,`Lifecycle transition '${name}' failed`,{error:String(err)})}),run}async stop(){return this.enqueueTransition("stop",async()=>{if(this.state==="stopped"){getDaemonProfile().logger.warn(LOG_SOURCE3,"Agent is already stopped");return}getDaemonProfile().logger.info(LOG_SOURCE3,"Stopping agent..."),this.state="stopped";let sessionProvider=this.serviceRegistry.getProvider("session");if(sessionProvider)try{let sessions=await sessionProvider.list();for(let session of sessions)if(session.status==="active")try{await sessionProvider.kill(session.id),getDaemonProfile().logger.debug(LOG_SOURCE3,`Killed session ${session.id}`)}catch(err){getDaemonProfile().logger.warn(LOG_SOURCE3,`Failed to kill session ${session.id}`,{error:String(err)})}}catch(err){getDaemonProfile().logger.warn(LOG_SOURCE3,"Failed to list/stop sessions",{error:String(err)})}try{await this.pluginManager.dispatchServerStop()}catch(err){getDaemonProfile().logger.warn(LOG_SOURCE3,"Error during plugin stop dispatch",{error:String(err)})}getDaemonProfile().logger.info(LOG_SOURCE3,"Agent stopped (tunnel + HTTP still alive)");try{await reportLifecycleState(this.db,"stopped")}catch(err){getDaemonProfile().logger.warn(LOG_SOURCE3,"Failed to report stopped state to backend",{error:String(err)})}})}async start(){return this.enqueueTransition("start",async()=>{if(this.state==="running"){getDaemonProfile().logger.warn(LOG_SOURCE3,"Agent is already running");return}getDaemonProfile().logger.info(LOG_SOURCE3,"Starting agent..."),this.state="running";try{await this.pluginManager.dispatchServerStart(this.app,this.hostServices),await this.pluginManager.dispatchServerReady(this.app,this.hostServices)}catch(err){getDaemonProfile().logger.warn(LOG_SOURCE3,"Error during plugin start dispatch",{error:String(err)})}getDaemonProfile().logger.info(LOG_SOURCE3,"Agent started");try{await reportLifecycleState(this.db,"running")}catch(err){getDaemonProfile().logger.warn(LOG_SOURCE3,"Failed to report running state to backend",{error:String(err)})}})}async softStop(){return this.enqueueTransition("softStop",async()=>{getDaemonProfile().logger.info(LOG_SOURCE3,"Soft-stopping agent (hot-reload)...");try{await this.pluginManager.dispatchServerStop({reason:"reload"})}catch(err){getDaemonProfile().logger.warn(LOG_SOURCE3,"Error during plugin soft-stop dispatch",{error:String(err)})}try{await this.appStopFn({reason:"reload"})}catch{}getDaemonProfile().logger.info(LOG_SOURCE3,"Agent soft-stopped \u2014 exiting for reload"),process.exit(0)})}async prepareForReset(){return this.enqueueTransition("prepareForReset",async()=>{getDaemonProfile().logger.info(LOG_SOURCE3,"Preparing agent for reset..."),this.state="stopped";try{await this.pluginManager.dispatchServerStop({reason:"shutdown"})}catch(err){getDaemonProfile().logger.warn(LOG_SOURCE3,"Error during reset stop dispatch",{error:String(err)})}})}async kill(){return this.enqueueTransition("kill",async()=>{getDaemonProfile().logger.info(LOG_SOURCE3,"Killing agent...");try{await Promise.race([reportLifecycleState(this.db,"killed"),new Promise((_,reject)=>setTimeout(()=>reject(Error("Timeout")),5000))])}catch(err){getDaemonProfile().logger.warn(LOG_SOURCE3,"Failed to report killed state to backend",{error:String(err)})}let tunnelProvider=this.serviceRegistry.getProvider("tunnel");if(tunnelProvider)try{let tunnels=await tunnelProvider.list();for(let tunnel of tunnels)try{await tunnelProvider.stop(tunnel.id)}catch{}}catch(err){getDaemonProfile().logger.warn(LOG_SOURCE3,"Failed to stop tunnels",{error:String(err)})}try{await this.appStopFn()}catch{}getDaemonProfile().logger.info(LOG_SOURCE3,"Agent killed \u2014 exiting process"),process.exit(0)})}}async function credsForSecondaryProfile(ctx){let fromConfig=await credsFromConfig(ctx);if(fromConfig)return fromConfig;return credsFromEnv(ctx.name)}async function credsFromConfig(ctx){let cfg;try{cfg=await readAgentConfigWithSecrets({dir:ctx.dataDir,scope:ctx.name})}catch{return null}if(!cfg.clientId||!cfg.clientSecret||!cfg.globalGatewayUrl||!cfg.workspaceGatewayUrl||!cfg.workspaceId)return null;return{clientId:cfg.clientId,clientSecret:cfg.clientSecret,globalGatewayUrl:cfg.globalGatewayUrl,workspaceGatewayUrl:cfg.workspaceGatewayUrl,workspaceId:cfg.workspaceId,organizationId:cfg.organizationId}}function credsFromEnv(profile){let upper=profile.replace(/[^A-Za-z0-9_]/g,"_").toUpperCase(),get=(suffix)=>process.env[`VIBE_${upper}_${suffix}`],clientId=get("CLIENT_ID"),clientSecret=get("CLIENT_SECRET"),globalGatewayUrl=get("GLOBAL_GATEWAY_URL"),workspaceGatewayUrl=get("WORKSPACE_GATEWAY_URL"),workspaceId=get("WORKSPACE_ID");if(!clientId||!clientSecret||!globalGatewayUrl||!workspaceGatewayUrl||!workspaceId)return null;return{clientId,clientSecret,globalGatewayUrl,workspaceGatewayUrl,workspaceId,organizationId:get("ORGANIZATION_ID")}}async function attachSecondaryProfile(ctx){let creds=await credsForSecondaryProfile(ctx);if(!creds)return{ok:!1,error:`no creds for profile '${ctx.name}' (run gateway-auth against this profile or set VIBE_${ctx.name.toUpperCase()}_* env vars)`};ctx.setBootState("initializing");let db;try{let encryptionKey=await fetchEncryptionKey(creds);db=await createAgentDatabase({dbPath:ctx.dataDir,encryptionKey})}catch(err){return ctx.setBootState("awaiting-config"),{ok:!1,error:err instanceof Error?err.message:String(err)}}let serviceRegistry=new ServiceRegistry(db);await serviceRegistry.hydrateDefaultsFromDb();let pluginManager=new PluginManager(db);await pluginManager.loadCorePlugins();try{await pluginManager.loadAll()}catch(err){ctx.logger.warn("secondary-profile-attach","failed to load some external plugins for secondary profile",{error:err instanceof Error?err.message:String(err)})}let hostServices={storage:{async get(namespace,key){return await db.getPluginState(namespace,key)??null},async set(namespace,key,value){await db.setPluginState(namespace,key,value)},async delete(namespace,key){return db.deletePluginState(namespace,key)},async list(namespace){return await db.getAllPluginState(namespace)},async deleteAll(namespace){return db.deleteAllPluginState(namespace)}},logger:ctx.logger,serviceRegistry,getProvider:(type)=>serviceRegistry.getProvider(type),getAgentBaseUrl:()=>process.env.AGENT_URL||"http://localhost:0",getAgentVersion:()=>"0.0.0",broadcast:()=>{},workspaceQuery:async()=>({}),isGatewayConfigured:()=>!0,getAgentRecordId:async()=>await db.getConfig("gateway-auth:agentRecordId")??null,getWorkspaceId:async()=>await db.getConfig("gateway-auth:workspaceId")??null,getConfig:async(key)=>await db.getConfig(key)??void 0,getPluginRegistry:()=>"",getDataDir:()=>ctx.dataDir,cliContributors:new CliContributorRegistry,audit:{emit:(event,payload)=>ctx.audit.emit("agent",event,payload??{})},telemetry:{emit:()=>{}},os:getOsAdapter(),iframeBridge:createIframeBridge()},lifecycle=new LifecycleManager(serviceRegistry,pluginManager,db,{},hostServices,async()=>{});serviceRegistry.registerService("agent","lifecycle",lifecycle),ctx.attachServices({db,serviceRegistry,pluginManager,lifecycle,hostServices});try{mountProfileRoutes(ctx)}catch(err){ctx.logger.warn("secondary-profile-attach","failed to mount per-profile plugin routes",{error:err instanceof Error?err.message:String(err)})}try{await ctx.keyVault.bindApiKey(getAgentApiKey())}catch{}return ctx.setBootState("ready"),{ok:!0}}
177
+ `;async function notifyBackendPluginChange(db){try{if(!gatewayClient.isConfigured())return;let agentRecordId=await db.getConfig("gateway-auth:agentRecordId");if(!agentRecordId)return;let result=await gatewayClient.workspaceQuery(NOTIFY_PLUGIN_CHANGE_MUTATION,{agentId:agentRecordId});if(result.errors?.length)getDaemonProfile().logger.debug(LOG_SOURCE2,"Plugin-change notify returned errors",{errors:result.errors.map((e)=>e.message)})}catch(err){getDaemonProfile().logger.debug(LOG_SOURCE2,`Plugin-change notify failed: ${err instanceof Error?err.message:String(err)}`)}}var tunnelSyncInterval=null,lastReportedTunnelUrl=null;function startTunnelSync(db,serviceRegistry,apiKey,intervalMs){if(tunnelSyncInterval)return;let envOverride=Number(process.env.VIBE_TUNNEL_SYNC_MS),period=Number.isFinite(envOverride)&&envOverride>0?envOverride:intervalMs??60000;tunnelSyncInterval=setInterval(async()=>{if(!gatewayClient.isConfigured())return;try{let tunnelProvider=serviceRegistry.getProvider("tunnel");if(!tunnelProvider||!tunnelProvider.getActiveTunnelUrl)return;let currentUrl=sanitizeTunnelUrl(await tunnelProvider.getActiveTunnelUrl()),agentRecordId=await db.getConfig("gateway-auth:agentRecordId");if(!agentRecordId)return;if(await sendHeartbeat(agentRecordId),!currentUrl)return;let wsId=gatewayClient.getConfig()?.workspaceId||"",backendUrl;if(wsId)backendUrl=(await gatewayClient.workspaceQuery(FIND_EXISTING_AGENT_QUERY,{workspaceId:wsId})).data?.vibecontrolsAgents?.find((a)=>a.id===agentRecordId)?.tunnelUrl??null;let localChanged=currentUrl!==lastReportedTunnelUrl,backendDrifted=backendUrl!==void 0&&backendUrl!==currentUrl;if(!localChanged&&!backendDrifted)return;getDaemonProfile().logger.info(LOG_SOURCE2,"Re-publishing tunnel URL",{reason:backendDrifted?"backend-drift":"local-change",backend:backendUrl,local:currentUrl,lastReported:lastReportedTunnelUrl});let result=await gatewayClient.workspaceQuery(UPDATE_AGENT_MUTATION,{id:agentRecordId,input:{tunnelUrl:currentUrl,tunnelStatus:"CONNECTED",agentApiKey:apiKey}});if(!result.errors?.length)lastReportedTunnelUrl=currentUrl,getDaemonProfile().logger.info(LOG_SOURCE2,"Tunnel URL synced to backend",{tunnelUrl:currentUrl});else getDaemonProfile().logger.warn(LOG_SOURCE2,"Tunnel URL sync returned errors",{errors:result.errors.map((e)=>e.message)})}catch(err){getDaemonProfile().logger.debug(LOG_SOURCE2,`Tunnel sync check failed: ${err instanceof Error?err.message:String(err)}`)}},period),tunnelSyncInterval.unref?.()}function stopTunnelSync(){if(tunnelSyncInterval)clearInterval(tunnelSyncInterval),tunnelSyncInterval=null}async function autoReportToBackend(db,serviceRegistry,apiKey){if(!gatewayClient.isConfigured()){getDaemonProfile().logger.debug(LOG_SOURCE2,"Gateway auth not configured \u2014 skipping auto-report");return}let workspaceId=await db.getConfig("gateway-auth:workspaceId");if(!workspaceId){getDaemonProfile().logger.warn(LOG_SOURCE2,"No workspaceId configured \u2014 skipping auto-report. "+"Configure via POST /api/agent/gateway-auth with workspaceId.");return}getDaemonProfile().logger.info(LOG_SOURCE2,"Starting auto-report to backend...");try{let hostname=process.env.VIBE_AGENT_NAME||os.hostname(),platform=os.platform(),arch=os.arch(),version=getAgentVersion(),tunnelUrl=await waitForTunnelUrl(serviceRegistry),agentRecordId=await getOrDiscoverAgentRecordId(db,hostname);if(agentRecordId){getDaemonProfile().logger.info(LOG_SOURCE2,`Updating agent record ${agentRecordId} via workspace gateway`);let result2=await gatewayClient.workspaceQuery(UPDATE_AGENT_MUTATION,{id:agentRecordId,input:{tunnelUrl:tunnelUrl||null,tunnelStatus:tunnelUrl?"CONNECTED":"DISCONNECTED",agentApiKey:apiKey}});if(result2.errors?.length){if(getDaemonProfile().logger.warn(LOG_SOURCE2,"Update mutation returned errors",{errors:result2.errors.map((e)=>e.message)}),await agentRecordExists(workspaceId,agentRecordId)){getDaemonProfile().logger.warn(LOG_SOURCE2,"Agent record still exists \u2014 treating update failure as transient; will retry on next sync (NOT registering a duplicate)",{agentRecordId}),await sendHeartbeat(agentRecordId),lastReportedTunnelUrl=tunnelUrl,startTunnelSync(db,serviceRegistry,apiKey),startProfileReconciler(db);return}getDaemonProfile().logger.info(LOG_SOURCE2,"Cached agent record no longer exists \u2014 clearing cache and registering fresh",{agentRecordId}),await db.setConfig("gateway-auth:agentRecordId",""),agentRecordId=null}else{getDaemonProfile().logger.info(LOG_SOURCE2,"Agent record updated successfully",{agentRecordId,tunnelUrl}),await verifyAndRetryUpdate(agentRecordId,tunnelUrl,apiKey,workspaceId),await sendHeartbeat(agentRecordId),lastReportedTunnelUrl=tunnelUrl,startTunnelSync(db,serviceRegistry,apiKey),startProfileReconciler(db);return}}getDaemonProfile().logger.info(LOG_SOURCE2,`Registering installed agent via workspace gateway (hostname: ${hostname})`);let result=await gatewayClient.workspaceQuery(REGISTER_INSTALLED_AGENT_MUTATION,{workspaceId,input:{name:hostname,hostname,platform,architecture:arch,tunnelUrl:tunnelUrl||null,agentApiKey:apiKey}});if(result.errors?.length){getDaemonProfile().logger.error(LOG_SOURCE2,"Register installed agent mutation failed",{errors:result.errors.map((e)=>e.message)});return}let registeredId=result.data?.registerInstalledAgent?.id;if(registeredId)await db.setConfig("gateway-auth:agentRecordId",registeredId),agentRecordId=registeredId,getDaemonProfile().logger.info(LOG_SOURCE2,"Agent registered successfully",{agentRecordId:registeredId,name:result.data?.registerInstalledAgent?.name,tunnelUrl,version});if(!agentRecordId)return;let updateResult=await gatewayClient.workspaceQuery(UPDATE_AGENT_MUTATION,{id:agentRecordId,input:{tunnelUrl:tunnelUrl||null,tunnelStatus:tunnelUrl?"CONNECTED":"DISCONNECTED",agentApiKey:apiKey}});if(updateResult.errors?.length)getDaemonProfile().logger.warn(LOG_SOURCE2,"Post-registration agent update returned errors",{errors:updateResult.errors.map((error3)=>error3.message)});else getDaemonProfile().logger.info(LOG_SOURCE2,"Post-registration agent sync completed",{agentRecordId,tunnelUrl});if(await verifyAndRetryUpdate(agentRecordId,tunnelUrl,apiKey,workspaceId),await sendHeartbeat(agentRecordId),lastReportedTunnelUrl=tunnelUrl,startTunnelSync(db,serviceRegistry,apiKey),startProfileReconciler(db),process.env.VIBE_BRIDGE_DISABLED!=="1")try{let{bridgeClient}=await import("./bridge-client-nsed8aw4.js"),profile=process.env.VIBECONTROLS_PROFILE||"default";bridgeClient.start(agentRecordId,profile)}catch(err){getDaemonProfile().logger.warn(LOG_SOURCE2,`bridge-client start failed: ${err instanceof Error?err.message:String(err)}`)}}catch(err){getDaemonProfile().logger.error(LOG_SOURCE2,`Auto-report failed: ${err instanceof Error?err.message:String(err)}`);try{startTunnelSync(db,serviceRegistry,apiKey),startProfileReconciler(db)}catch{}}}var LOG_SOURCE3="lifecycle";class LifecycleManager{serviceRegistry;pluginManager;db;app;hostServices;appStopFn;state="running";transition=Promise.resolve();constructor(serviceRegistry,pluginManager,db,app,hostServices,appStopFn){this.serviceRegistry=serviceRegistry;this.pluginManager=pluginManager;this.db=db;this.app=app;this.hostServices=hostServices;this.appStopFn=appStopFn}getState(){return this.state}enqueueTransition(name,fn){let run=this.transition.then(fn,fn);return this.transition=run.catch((err)=>{getDaemonProfile().logger.warn(LOG_SOURCE3,`Lifecycle transition '${name}' failed`,{error:String(err)})}),run}async stop(){return this.enqueueTransition("stop",async()=>{if(this.state==="stopped"){getDaemonProfile().logger.warn(LOG_SOURCE3,"Agent is already stopped");return}getDaemonProfile().logger.info(LOG_SOURCE3,"Stopping agent..."),this.state="stopped";let sessionProvider=this.serviceRegistry.getProvider("session");if(sessionProvider)try{let sessions=await sessionProvider.list();for(let session of sessions)if(session.status==="active")try{await sessionProvider.kill(session.id),getDaemonProfile().logger.debug(LOG_SOURCE3,`Killed session ${session.id}`)}catch(err){getDaemonProfile().logger.warn(LOG_SOURCE3,`Failed to kill session ${session.id}`,{error:String(err)})}}catch(err){getDaemonProfile().logger.warn(LOG_SOURCE3,"Failed to list/stop sessions",{error:String(err)})}try{await this.pluginManager.dispatchServerStop()}catch(err){getDaemonProfile().logger.warn(LOG_SOURCE3,"Error during plugin stop dispatch",{error:String(err)})}getDaemonProfile().logger.info(LOG_SOURCE3,"Agent stopped (tunnel + HTTP still alive)");try{await reportLifecycleState(this.db,"stopped")}catch(err){getDaemonProfile().logger.warn(LOG_SOURCE3,"Failed to report stopped state to backend",{error:String(err)})}})}async start(){return this.enqueueTransition("start",async()=>{if(this.state==="running"){getDaemonProfile().logger.warn(LOG_SOURCE3,"Agent is already running");return}getDaemonProfile().logger.info(LOG_SOURCE3,"Starting agent..."),this.state="running";try{await this.pluginManager.dispatchServerStart(this.app,this.hostServices),await this.pluginManager.dispatchServerReady(this.app,this.hostServices)}catch(err){getDaemonProfile().logger.warn(LOG_SOURCE3,"Error during plugin start dispatch",{error:String(err)})}getDaemonProfile().logger.info(LOG_SOURCE3,"Agent started");try{await reportLifecycleState(this.db,"running")}catch(err){getDaemonProfile().logger.warn(LOG_SOURCE3,"Failed to report running state to backend",{error:String(err)})}})}async softStop(){return this.enqueueTransition("softStop",async()=>{getDaemonProfile().logger.info(LOG_SOURCE3,"Soft-stopping agent (hot-reload)...");try{await this.pluginManager.dispatchServerStop({reason:"reload"})}catch(err){getDaemonProfile().logger.warn(LOG_SOURCE3,"Error during plugin soft-stop dispatch",{error:String(err)})}try{await this.appStopFn({reason:"reload"})}catch{}getDaemonProfile().logger.info(LOG_SOURCE3,"Agent soft-stopped \u2014 exiting for reload"),process.exit(0)})}async prepareForReset(){return this.enqueueTransition("prepareForReset",async()=>{getDaemonProfile().logger.info(LOG_SOURCE3,"Preparing agent for reset..."),this.state="stopped";try{await this.pluginManager.dispatchServerStop({reason:"shutdown"})}catch(err){getDaemonProfile().logger.warn(LOG_SOURCE3,"Error during reset stop dispatch",{error:String(err)})}})}async kill(){return this.enqueueTransition("kill",async()=>{getDaemonProfile().logger.info(LOG_SOURCE3,"Killing agent...");try{await Promise.race([reportLifecycleState(this.db,"killed"),new Promise((_,reject)=>setTimeout(()=>reject(Error("Timeout")),5000))])}catch(err){getDaemonProfile().logger.warn(LOG_SOURCE3,"Failed to report killed state to backend",{error:String(err)})}let tunnelProvider=this.serviceRegistry.getProvider("tunnel");if(tunnelProvider)try{let tunnels=await tunnelProvider.list();for(let tunnel of tunnels)try{await tunnelProvider.stop(tunnel.id)}catch{}}catch(err){getDaemonProfile().logger.warn(LOG_SOURCE3,"Failed to stop tunnels",{error:String(err)})}try{await this.appStopFn()}catch{}getDaemonProfile().logger.info(LOG_SOURCE3,"Agent killed \u2014 exiting process"),process.exit(0)})}}async function credsForSecondaryProfile(ctx){let fromConfig=await credsFromConfig(ctx);if(fromConfig)return fromConfig;return credsFromEnv(ctx.name)}async function credsFromConfig(ctx){let cfg;try{cfg=await readAgentConfigWithSecrets({dir:ctx.dataDir,scope:ctx.name})}catch{return null}if(!cfg.clientId||!cfg.clientSecret||!cfg.globalGatewayUrl||!cfg.workspaceGatewayUrl||!cfg.workspaceId)return null;return{clientId:cfg.clientId,clientSecret:cfg.clientSecret,globalGatewayUrl:cfg.globalGatewayUrl,workspaceGatewayUrl:cfg.workspaceGatewayUrl,workspaceId:cfg.workspaceId,organizationId:cfg.organizationId}}function credsFromEnv(profile){let upper=profile.replace(/[^A-Za-z0-9_]/g,"_").toUpperCase(),get=(suffix)=>process.env[`VIBE_${upper}_${suffix}`],clientId=get("CLIENT_ID"),clientSecret=get("CLIENT_SECRET"),globalGatewayUrl=get("GLOBAL_GATEWAY_URL"),workspaceGatewayUrl=get("WORKSPACE_GATEWAY_URL"),workspaceId=get("WORKSPACE_ID");if(!clientId||!clientSecret||!globalGatewayUrl||!workspaceGatewayUrl||!workspaceId)return null;return{clientId,clientSecret,globalGatewayUrl,workspaceGatewayUrl,workspaceId,organizationId:get("ORGANIZATION_ID")}}async function attachSecondaryProfile(ctx){let creds=await credsForSecondaryProfile(ctx);if(!creds)return{ok:!1,error:`no creds for profile '${ctx.name}' (run gateway-auth against this profile or set VIBE_${ctx.name.toUpperCase()}_* env vars)`};ctx.setBootState("initializing");let db;try{let encryptionKey=await fetchEncryptionKey(creds);db=await createAgentDatabase({dbPath:ctx.dataDir,encryptionKey})}catch(err){return ctx.setBootState("awaiting-config"),{ok:!1,error:err instanceof Error?err.message:String(err)}}let serviceRegistry=new ServiceRegistry(db);await serviceRegistry.hydrateDefaultsFromDb();let pluginManager=new PluginManager(db);await pluginManager.loadCorePlugins();try{await pluginManager.loadAll()}catch(err){ctx.logger.warn("secondary-profile-attach","failed to load some external plugins for secondary profile",{error:err instanceof Error?err.message:String(err)})}let hostServices={storage:{async get(namespace,key){return await db.getPluginState(namespace,key)??null},async set(namespace,key,value){await db.setPluginState(namespace,key,value)},async delete(namespace,key){return db.deletePluginState(namespace,key)},async list(namespace){return await db.getAllPluginState(namespace)},async deleteAll(namespace){return db.deleteAllPluginState(namespace)}},logger:ctx.logger,serviceRegistry,getProvider:(type)=>serviceRegistry.getProvider(type),getAgentBaseUrl:()=>process.env.AGENT_URL||"http://localhost:0",getAgentVersion:()=>"0.0.0",broadcast:()=>{},workspaceQuery:async()=>({}),isGatewayConfigured:()=>!0,getAgentRecordId:async()=>await db.getConfig("gateway-auth:agentRecordId")??null,getWorkspaceId:async()=>await db.getConfig("gateway-auth:workspaceId")??null,getConfig:async(key)=>await db.getConfig(key)??void 0,getPluginRegistry:()=>"",getDataDir:()=>ctx.dataDir,cliContributors:new CliContributorRegistry,audit:{emit:(event,payload)=>ctx.audit.emit("agent",event,payload??{})},telemetry:{emit:()=>{}},os:getOsAdapter(),iframeBridge:createIframeBridge()},lifecycle=new LifecycleManager(serviceRegistry,pluginManager,db,{},hostServices,async()=>{});serviceRegistry.registerService("agent","lifecycle",lifecycle),ctx.attachServices({db,serviceRegistry,pluginManager,lifecycle,hostServices});try{mountProfileRoutes(ctx)}catch(err){ctx.logger.warn("secondary-profile-attach","failed to mount per-profile plugin routes",{error:err instanceof Error?err.message:String(err)})}try{await ctx.keyVault.bindApiKey(getAgentApiKey())}catch{}return ctx.setBootState("ready"),{ok:!0}}
178
178
  export{createAgentDatabase,fetchEncryptionKey,LifecycleManager,attachSecondaryProfile,stopProfileReconciler,notifyBackendPluginChange,stopTunnelSync,autoReportToBackend};
@@ -0,0 +1,5 @@
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,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-ftx08bfa.js"),import("./index-fwd90spw.js"),import("./index-m483e746.js"),import("./index-e875a6zy.js"),import("./index-pne5682j.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(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.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()}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};