@vibecontrols/agent 2026.531.11 → 2026.531.13

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

Potentially problematic release.


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

@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{listTrackedByOwner,spawnTracked}from"./index-926vt87h.js";import{LifecycleManager,createAgentDatabase,fetchEncryptionKey}from"./index-8xr7ewxg.js";import{resolveSafePath}from"./index-skmkfyzb.js";import{readTunnelState,startBootstrapTunnel,stopBootstrapTunnel}from"./index-95nmejfd.js";import{ServiceManager}from"./index-34syaqa8.js";import{redactUnknownSecrets}from"./index-y5q0m3cx.js";import{CliContributorRegistry,createIframeBridge,createUIServer,renderUiBootstrapHtml}from"./index-1atc02se.js";import{PluginManager,ServiceRegistry,isCriticalPlugin}from"./index-7qj1swrk.js";import{getOsAdapter}from"./index-srbb2214.js";import{broadcast,createEventsWs,createLogWs,createPluginRouter,createTerminalProxy,dispatchProfileRequest,mountProfileRoutes,rateLimitPlugin}from"./index-brtw3j8x.js";import{createAuthPlugin,getAgentApiKey,getApiKeyFromHeaders,getUiCookieFromRequest,isValidAgentApiKey,isValidUiPluginName,issueIframeToken,issueScopedIframeToken,issueTerminalCookieToken,issueUiCookieToken,markPluginPublicPathsDirty,verifyIframeToken,verifyIframeTokenWithReason,verifyUiCookieToken}from"./index-b4wy3jrt.js";import{Elysia,t}from"./index-rnk0kny8.js";import{getAgentConfigSeed,readAgentConfig,writeAgentConfig,writeAgentConfigAwaitSecrets}from"./index-2pqv0bya.js";import{assertAllowedGatewayUrl,currentProfileOrNull,enterProfileContext,enterRequestContext,extractRequestId,gatewayClient,generateRequestId,getDaemonProfile,getOrCreateProfile,getRequestId,profileRegistry}from"./index-7pdmqbj8.js";import{getDefaultProfile,getInstances,getPluginRegistry,getProfileDataDir,getVibecontrolsDir,getVibecontrolsProductDir,getVibecontrolsProfile,setDefaultProfile,validateAgentName}from"./index-bysm7taq.js";import{__require,__toESM}from"./index-e9rt4m94.js";var isBun=typeof new Headers()?.toJSON==="function",processHeaders=(headers)=>{if(isBun)return Object.keys(headers.toJSON()).join(", ");let keys="",i=0;return headers.forEach((_,key)=>{if(i)keys=keys+", "+key;else keys=key;i++}),keys},cors=(config)=>{let{aot=!0,origin=!0,methods=!0,allowedHeaders=!0,exposeHeaders=!0,credentials=!0,maxAge=5,preflight=!0}=config??{};if(Array.isArray(allowedHeaders))allowedHeaders=allowedHeaders.join(", ");if(Array.isArray(exposeHeaders))exposeHeaders=exposeHeaders.join(", ");let origins=typeof origin==="boolean"?void 0:Array.isArray(origin)?origin:[origin],app=new Elysia({name:"@elysiajs/cors",seed:config,aot}),anyOrigin=origins?.some((o)=>o==="*"),originMap={};if(origins){for(let origin2 of origins)if(typeof origin2==="string")originMap[origin2]=!0}let processOrigin=(origin2,request,from)=>{if(Array.isArray(origin2))return origin2.some((o)=>processOrigin(o,request,from));switch(typeof origin2){case"string":if(from in originMap)return!0;let fromProtocol=from.indexOf("://");if(fromProtocol!==-1)from=from.slice(fromProtocol+3);return origin2===from;case"function":return origin2(request)===!0;case"object":if(origin2 instanceof RegExp)return origin2.test(from)}return!1},handleOrigin=(set,request)=>{if(origin===!0){set.headers.vary="*",set.headers["access-control-allow-origin"]=request.headers.get("Origin")||"*";return}if(anyOrigin){set.headers.vary="*",set.headers["access-control-allow-origin"]="*";return}if(!origins?.length)return;if(origins.length){let from=request.headers.get("Origin")??"";for(let i=0;i<origins.length;i++)if(processOrigin(origins[i],request,from)===!0){set.headers.vary=origin?"Origin":"*",set.headers["access-control-allow-origin"]=from||"*";return}}set.headers.vary="Origin"},handleMethod=(set,method)=>{if(!method)return;if(methods===!0)return set.headers["access-control-allow-methods"]=method??"*";if(methods===!1||!methods?.length)return;if(methods==="*")return set.headers["access-control-allow-methods"]="*";if(!Array.isArray(methods))return set.headers["access-control-allow-methods"]=methods;set.headers["access-control-allow-methods"]=methods.join(", ")},defaultHeaders={};if(typeof exposeHeaders==="string")defaultHeaders["access-control-expose-headers"]=exposeHeaders;if(typeof allowedHeaders==="string")defaultHeaders["access-control-allow-headers"]=allowedHeaders;if(credentials===!0)defaultHeaders["access-control-allow-credentials"]="true";app.headers(defaultHeaders);function handleOption({set,request,headers}){if(handleOrigin(set,request),handleMethod(set,request.headers.get("access-control-request-method")),allowedHeaders===!0||exposeHeaders===!0){if(allowedHeaders===!0)set.headers["access-control-allow-headers"]=headers["access-control-request-headers"];if(exposeHeaders===!0)set.headers["access-control-expose-headers"]=Object.keys(headers).join(",")}if(maxAge)set.headers["access-control-max-age"]=maxAge.toString();return new Response(null,{status:204})}if(preflight)app.options("/",handleOption).options("/*",handleOption);return app.onRequest(function({set,request}){if(handleOrigin(set,request),preflight&&request.method==="OPTIONS")return handleOption({set,request,headers:isBun?request.headers.toJSON():Object.fromEntries(request.headers.entries())});if(handleMethod(set,request.method),allowedHeaders===!0||exposeHeaders===!0){let headers=processHeaders(request.headers);if(allowedHeaders===!0)set.headers["access-control-allow-headers"]=headers;if(exposeHeaders===!0)set.headers["access-control-expose-headers"]=headers}})};import{createHash}from"crypto";var NS="idempotency",TTL_MS=300000,MAX_ENTRIES=1e4;function cacheKey(method,path,rawKey,bodyHash){return createHash("sha256").update(`${method}|${path}|${rawKey}|${bodyHash}`).digest("hex")}async function readCached(db,key){let raw=await db.getPluginState(NS,key);if(!raw)return null;try{let entry=JSON.parse(raw);if(entry.expiresAt<Date.now())return await db.deletePluginState(NS,key),null;return entry}catch{return null}}async function writeCached(db,key,entry){await db.setPluginState(NS,key,JSON.stringify(entry))}async function sweepIdempotency(db){let all=await db.getAllPluginState(NS),now=Date.now(),removed=0,live=[];for(let e of all)try{if(JSON.parse(e.value).expiresAt<now)await db.deletePluginState(NS,e.key),removed+=1;else live.push({key:e.key,updatedAt:e.updatedAt})}catch{await db.deletePluginState(NS,e.key),removed+=1}if(live.length>MAX_ENTRIES){live.sort((a,b)=>(a.updatedAt??"").localeCompare(b.updatedAt??""));let overage=live.slice(0,live.length-MAX_ENTRIES);for(let entry of overage)await db.deletePluginState(NS,entry.key),removed+=1}if(removed>0)getDaemonProfile().logger.info("idempotency",`Swept ${removed} expired/over-cap entries`)}var sweepTimer=null,SWEEP_INTERVAL_MS=600000;function startSweepIfNeeded(deps){if(sweepTimer)return;sweepTimer=setInterval(()=>{let db=deps.getDb();if(!db)return;sweepIdempotency(db).catch((err)=>{getDaemonProfile().logger.warn("idempotency","Sweep failed",{error:String(err)})})},SWEEP_INTERVAL_MS),sweepTimer.unref?.()}function idempotencyPlugin(deps){return startSweepIfNeeded(deps),new Elysia({name:"plugin/idempotency"}).onBeforeHandle(async({request,path,set,store})=>{if(request.method!=="POST"&&request.method!=="PUT")return;let rawKey=request.headers.get("x-idempotency-key")??request.headers.get("X-Idempotency-Key");if(!rawKey)return;if(rawKey.length<8||rawKey.length>200)return set.status=400,{error:"X-Idempotency-Key must be 8\u2013200 chars",code:"BAD_REQUEST"};let db=deps.getDb();if(!db)return;let bodyHash="no-body";try{let text=await request.clone().text();bodyHash=createHash("sha256").update(text).digest("hex")}catch{}let key=cacheKey(request.method,path,rawKey,bodyHash),cached=await readCached(db,key);if(cached){set.status=cached.status;let headers=set.headers??={};headers["Content-Type"]=cached.contentType,headers["X-Idempotency-Replay"]="true",store.__idemReplay=cached.body;try{return JSON.parse(cached.body)}catch{return cached.body}}store.__idemKey=key}).onAfterHandle(async({response,set,store})=>{let key=store.__idemKey;if(!key)return;let db=deps.getDb();if(!db)return;let status=set.status??200;if(status<200||status>=300)return;let body=typeof response==="string"?response:JSON.stringify(response),contentType=set.headers?.["Content-Type"]??"application/json";try{await writeCached(db,key,{status,body,contentType,expiresAt:Date.now()+TTL_MS})}catch(err){getDaemonProfile().logger.warn("idempotency","Failed to persist response",{error:String(err)})}}).as("global")}import os from"os";import{readFileSync as readFileSync2}from"fs";import{join as join2}from"path";var DISABLED_REGISTRY={enabled:!1,async scrape(){return`# vibecontrols agent metrics disabled (OTel SDK not initialised)
2
+ import{listTrackedByOwner,spawnTracked}from"./index-926vt87h.js";import{LifecycleManager,createAgentDatabase,fetchEncryptionKey}from"./index-q96eskyn.js";import{resolveSafePath}from"./index-skmkfyzb.js";import{readTunnelState,startBootstrapTunnel,stopBootstrapTunnel}from"./index-95nmejfd.js";import{ServiceManager}from"./index-vfwervz9.js";import{redactUnknownSecrets}from"./index-y5q0m3cx.js";import{CliContributorRegistry,createIframeBridge,createUIServer,renderUiBootstrapHtml}from"./index-ttafzcs7.js";import{PluginManager,ServiceRegistry,isCriticalPlugin}from"./index-1x89a7r1.js";import{getOsAdapter}from"./index-srbb2214.js";import{broadcast,createEventsWs,createLogWs,createPluginRouter,createTerminalProxy,dispatchProfileRequest,mountProfileRoutes,rateLimitPlugin}from"./index-brtw3j8x.js";import{createAuthPlugin,getAgentApiKey,getApiKeyFromHeaders,getUiCookieFromRequest,isValidAgentApiKey,isValidUiPluginName,issueIframeToken,issueScopedIframeToken,issueTerminalCookieToken,issueUiCookieToken,markPluginPublicPathsDirty,verifyIframeToken,verifyIframeTokenWithReason,verifyUiCookieToken}from"./index-b4wy3jrt.js";import{Elysia,t}from"./index-rnk0kny8.js";import{getAgentConfigSeed,readAgentConfig,writeAgentConfig,writeAgentConfigAwaitSecrets}from"./index-2pqv0bya.js";import{assertAllowedGatewayUrl,currentProfileOrNull,enterProfileContext,enterRequestContext,extractRequestId,gatewayClient,generateRequestId,getDaemonProfile,getOrCreateProfile,getRequestId,profileRegistry}from"./index-7pdmqbj8.js";import{getDefaultProfile,getInstances,getPluginRegistry,getProfileDataDir,getVibecontrolsDir,getVibecontrolsProductDir,getVibecontrolsProfile,setDefaultProfile,validateAgentName}from"./index-bysm7taq.js";import{__require,__toESM}from"./index-e9rt4m94.js";var isBun=typeof new Headers()?.toJSON==="function",processHeaders=(headers)=>{if(isBun)return Object.keys(headers.toJSON()).join(", ");let keys="",i=0;return headers.forEach((_,key)=>{if(i)keys=keys+", "+key;else keys=key;i++}),keys},cors=(config)=>{let{aot=!0,origin=!0,methods=!0,allowedHeaders=!0,exposeHeaders=!0,credentials=!0,maxAge=5,preflight=!0}=config??{};if(Array.isArray(allowedHeaders))allowedHeaders=allowedHeaders.join(", ");if(Array.isArray(exposeHeaders))exposeHeaders=exposeHeaders.join(", ");let origins=typeof origin==="boolean"?void 0:Array.isArray(origin)?origin:[origin],app=new Elysia({name:"@elysiajs/cors",seed:config,aot}),anyOrigin=origins?.some((o)=>o==="*"),originMap={};if(origins){for(let origin2 of origins)if(typeof origin2==="string")originMap[origin2]=!0}let processOrigin=(origin2,request,from)=>{if(Array.isArray(origin2))return origin2.some((o)=>processOrigin(o,request,from));switch(typeof origin2){case"string":if(from in originMap)return!0;let fromProtocol=from.indexOf("://");if(fromProtocol!==-1)from=from.slice(fromProtocol+3);return origin2===from;case"function":return origin2(request)===!0;case"object":if(origin2 instanceof RegExp)return origin2.test(from)}return!1},handleOrigin=(set,request)=>{if(origin===!0){set.headers.vary="*",set.headers["access-control-allow-origin"]=request.headers.get("Origin")||"*";return}if(anyOrigin){set.headers.vary="*",set.headers["access-control-allow-origin"]="*";return}if(!origins?.length)return;if(origins.length){let from=request.headers.get("Origin")??"";for(let i=0;i<origins.length;i++)if(processOrigin(origins[i],request,from)===!0){set.headers.vary=origin?"Origin":"*",set.headers["access-control-allow-origin"]=from||"*";return}}set.headers.vary="Origin"},handleMethod=(set,method)=>{if(!method)return;if(methods===!0)return set.headers["access-control-allow-methods"]=method??"*";if(methods===!1||!methods?.length)return;if(methods==="*")return set.headers["access-control-allow-methods"]="*";if(!Array.isArray(methods))return set.headers["access-control-allow-methods"]=methods;set.headers["access-control-allow-methods"]=methods.join(", ")},defaultHeaders={};if(typeof exposeHeaders==="string")defaultHeaders["access-control-expose-headers"]=exposeHeaders;if(typeof allowedHeaders==="string")defaultHeaders["access-control-allow-headers"]=allowedHeaders;if(credentials===!0)defaultHeaders["access-control-allow-credentials"]="true";app.headers(defaultHeaders);function handleOption({set,request,headers}){if(handleOrigin(set,request),handleMethod(set,request.headers.get("access-control-request-method")),allowedHeaders===!0||exposeHeaders===!0){if(allowedHeaders===!0)set.headers["access-control-allow-headers"]=headers["access-control-request-headers"];if(exposeHeaders===!0)set.headers["access-control-expose-headers"]=Object.keys(headers).join(",")}if(maxAge)set.headers["access-control-max-age"]=maxAge.toString();return new Response(null,{status:204})}if(preflight)app.options("/",handleOption).options("/*",handleOption);return app.onRequest(function({set,request}){if(handleOrigin(set,request),preflight&&request.method==="OPTIONS")return handleOption({set,request,headers:isBun?request.headers.toJSON():Object.fromEntries(request.headers.entries())});if(handleMethod(set,request.method),allowedHeaders===!0||exposeHeaders===!0){let headers=processHeaders(request.headers);if(allowedHeaders===!0)set.headers["access-control-allow-headers"]=headers;if(exposeHeaders===!0)set.headers["access-control-expose-headers"]=headers}})};import{createHash}from"crypto";var NS="idempotency",TTL_MS=300000,MAX_ENTRIES=1e4;function cacheKey(method,path,rawKey,bodyHash){return createHash("sha256").update(`${method}|${path}|${rawKey}|${bodyHash}`).digest("hex")}async function readCached(db,key){let raw=await db.getPluginState(NS,key);if(!raw)return null;try{let entry=JSON.parse(raw);if(entry.expiresAt<Date.now())return await db.deletePluginState(NS,key),null;return entry}catch{return null}}async function writeCached(db,key,entry){await db.setPluginState(NS,key,JSON.stringify(entry))}async function sweepIdempotency(db){let all=await db.getAllPluginState(NS),now=Date.now(),removed=0,live=[];for(let e of all)try{if(JSON.parse(e.value).expiresAt<now)await db.deletePluginState(NS,e.key),removed+=1;else live.push({key:e.key,updatedAt:e.updatedAt})}catch{await db.deletePluginState(NS,e.key),removed+=1}if(live.length>MAX_ENTRIES){live.sort((a,b)=>(a.updatedAt??"").localeCompare(b.updatedAt??""));let overage=live.slice(0,live.length-MAX_ENTRIES);for(let entry of overage)await db.deletePluginState(NS,entry.key),removed+=1}if(removed>0)getDaemonProfile().logger.info("idempotency",`Swept ${removed} expired/over-cap entries`)}var sweepTimer=null,SWEEP_INTERVAL_MS=600000;function startSweepIfNeeded(deps){if(sweepTimer)return;sweepTimer=setInterval(()=>{let db=deps.getDb();if(!db)return;sweepIdempotency(db).catch((err)=>{getDaemonProfile().logger.warn("idempotency","Sweep failed",{error:String(err)})})},SWEEP_INTERVAL_MS),sweepTimer.unref?.()}function idempotencyPlugin(deps){return startSweepIfNeeded(deps),new Elysia({name:"plugin/idempotency"}).onBeforeHandle(async({request,path,set,store})=>{if(request.method!=="POST"&&request.method!=="PUT")return;let rawKey=request.headers.get("x-idempotency-key")??request.headers.get("X-Idempotency-Key");if(!rawKey)return;if(rawKey.length<8||rawKey.length>200)return set.status=400,{error:"X-Idempotency-Key must be 8\u2013200 chars",code:"BAD_REQUEST"};let db=deps.getDb();if(!db)return;let bodyHash="no-body";try{let text=await request.clone().text();bodyHash=createHash("sha256").update(text).digest("hex")}catch{}let key=cacheKey(request.method,path,rawKey,bodyHash),cached=await readCached(db,key);if(cached){set.status=cached.status;let headers=set.headers??={};headers["Content-Type"]=cached.contentType,headers["X-Idempotency-Replay"]="true",store.__idemReplay=cached.body;try{return JSON.parse(cached.body)}catch{return cached.body}}store.__idemKey=key}).onAfterHandle(async({response,set,store})=>{let key=store.__idemKey;if(!key)return;let db=deps.getDb();if(!db)return;let status=set.status??200;if(status<200||status>=300)return;let body=typeof response==="string"?response:JSON.stringify(response),contentType=set.headers?.["Content-Type"]??"application/json";try{await writeCached(db,key,{status,body,contentType,expiresAt:Date.now()+TTL_MS})}catch(err){getDaemonProfile().logger.warn("idempotency","Failed to persist response",{error:String(err)})}}).as("global")}import os from"os";import{readFileSync as readFileSync2}from"fs";import{join as join2}from"path";var DISABLED_REGISTRY={enabled:!1,async scrape(){return`# vibecontrols agent metrics disabled (OTel SDK not initialised)
3
3
  `},recordHttpRequest(){},setPluginsLoaded(){}},cached=null,initPromise=null;async function getMetricsRegistry(opts){if(cached)return cached;if(initPromise)return initPromise;return initPromise=(async()=>{try{let{MeterProvider}=await import("./index-7t06bbkg.js").then((m)=>__toESM(m.default,1)),{PrometheusExporter,PrometheusSerializer}=await import("./index-q7zah1sn.js").then((m)=>__toESM(m.default,1)),reader=new PrometheusExporter({preventServerStart:!0}),serializer=new PrometheusSerializer,meter=new MeterProvider({readers:[reader]}).getMeter("vibecontrols-agent"),infoGauge=meter.createGauge("vibecontrols_agent_info",{description:"Static info about the agent process; value is always 1."});meter.createObservableGauge("vibecontrols_agent_uptime_seconds",{description:"Process uptime in seconds."}).addCallback((res)=>{res.observe(process.uptime())});let httpCounter=meter.createCounter("vibecontrols_http_requests_total",{description:"Total HTTP requests handled by the agent, labelled by method, route, status."}),pluginsLoadedSnapshot={};meter.createObservableGauge("vibecontrols_plugins_loaded",{description:"Plugins loaded by the agent, broken down by status (loaded, failed, etc.)."}).addCallback((res)=>{for(let[status,count]of Object.entries(pluginsLoadedSnapshot))res.observe(count,{status})}),infoGauge.record(1,{version:opts?.version??"unknown",profile:opts?.profile??"default"});let handle={enabled:!0,async scrape(){let collected=await reader.collect();if(!collected.resourceMetrics)return"";return serializer.serialize(collected.resourceMetrics)},recordHttpRequest(method,route,status){httpCounter.add(1,{method,route,status:String(status)})},setPluginsLoaded(byStatus){pluginsLoadedSnapshot={...byStatus}}};return cached=handle,getDaemonProfile().logger.info("metrics","OTel Prometheus registry initialised"),handle}catch(err){return getDaemonProfile().logger.warn("metrics","Failed to initialise OTel metrics; /metrics will return a stub body",{error:err instanceof Error?err.message:String(err)}),cached=DISABLED_REGISTRY,DISABLED_REGISTRY}})(),initPromise}function recordHttpRequest(method,route,status){if(!cached)return;cached.recordHttpRequest(method,route,status)}function setPluginsLoaded(byStatus){if(!cached)return;cached.setPluginsLoaded(byStatus)}var LOOPBACK_ADDRS=new Set(["127.0.0.1","::1"]),warnedAnonEnv=!1;function maybeWarnAnonEnv(){if(warnedAnonEnv)return;if(process.env.METRICS_ANONYMOUS_LOCALHOST==="true")warnedAnonEnv=!0,getDaemonProfile().logger.warn("metrics","METRICS_ANONYMOUS_LOCALHOST=true \u2014 /metrics is open to TCP loopback peers without an API key. Prefer issuing a scoped API key for your scraper.")}function normalizeAddr(addr){let cleaned=addr.replace(/^\[|\]$/g,"");if(cleaned.startsWith("::ffff:"))return cleaned.slice(7);return cleaned}function isLoopbackPeer(request,server){let peer=server?.requestIP(request)?.address;if(!peer)return!1;return LOOPBACK_ADDRS.has(normalizeAddr(peer))}function createMetricsRoutes(){return maybeWarnAnonEnv(),new Elysia({name:"routes/metrics"}).get("/metrics",async({request,server,set})=>{if(!(process.env.METRICS_ANONYMOUS_LOCALHOST==="true"&&isLoopbackPeer(request,server))){let provided=getApiKeyFromHeaders(Object.fromEntries(request.headers.entries()));if(!isValidAgentApiKey(provided))return set.status=401,set.headers["content-type"]="application/json",JSON.stringify({error:"Unauthorized",message:"Invalid or missing API key"})}let body=await(await getMetricsRegistry()).scrape();return set.headers["content-type"]="text/plain; version=0.0.4; charset=utf-8",body})}import{randomBytes,timingSafeEqual}from"crypto";import{chmodSync,existsSync,mkdirSync,readFileSync,unlinkSync,writeFileSync}from"fs";import{dirname,join}from"path";var inMemoryToken=null;function pairingTokenPath(){return join(getVibecontrolsDir(),"pairing-token")}function generateToken(){return randomBytes(32).toString("base64url")}function constantTimeMatch(a,b){let aBuf=Buffer.from(a),bBuf=Buffer.from(b);if(aBuf.length!==bBuf.length)return!1;try{return timingSafeEqual(aBuf,bBuf)}catch{return!1}}function mintPairingToken(){if(inMemoryToken)return inMemoryToken;let path=pairingTokenPath();try{if(existsSync(path)){let existing=readFileSync(path,"utf8").trim();if(existing.length>=32)return inMemoryToken=existing,existing}}catch{}let token=generateToken();try{mkdirSync(dirname(path),{recursive:!0}),writeFileSync(path,token,{encoding:"utf8"});try{chmodSync(path,384)}catch{}}catch(err){}return inMemoryToken=token,token}function isValidPairingToken(candidate){if(!candidate)return!1;if(!inMemoryToken)return!1;return constantTimeMatch(candidate,inMemoryToken)}function invalidatePairingToken(){inMemoryToken=null;try{let path=pairingTokenPath();if(existsSync(path))unlinkSync(path)}catch{}}function getPairingTokenFromHeaders(headers){return headers["x-pairing-token"]??headers["X-Pairing-Token"]??null}function getMachineId(){let hostname=os.hostname(),platform=os.platform(),arch=os.arch(),hasher=new Bun.CryptoHasher("sha256");return hasher.update(`${hostname}-${platform}-${arch}`),hasher.digest("hex").substring(0,16)}function getAgentVersion(){for(let depth of["..","../.."])try{let pkgPath=join2(import.meta.dir,depth,"package.json"),v=JSON.parse(readFileSync2(pkgPath,"utf8")).version;if(v)return v}catch{}return"0.0.0"}async function getActiveTunnelUrl(serviceRegistry){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 provider of providers){if(!provider.getActiveTunnelUrl)continue;let url=await provider.getActiveTunnelUrl();if(url)return url}return null}function createPreConfigRoutes({serviceRegistry,runFinalize,getDb}){let version=getAgentVersion(),machineId=getMachineId();return new Elysia({prefix:"/api/agent"}).get("/identity",()=>({machineId,hostname:os.hostname(),platform:os.platform(),arch:os.arch(),version,uptime:process.uptime()})).get("/version",()=>({version,runtime:"bun",runtimeVersion:typeof Bun<"u"?Bun.version:"unknown"})).get("/api-key",({request,server,set})=>{if(!isLoopbackPeer(request,server)){let provided=getApiKeyFromHeaders(Object.fromEntries(request.headers.entries()));if(!isValidAgentApiKey(provided))return set.status=401,{error:"Unauthorized",message:"Invalid or missing API key"}}return{apiKey:getAgentApiKey()}}).post("/iframe-token",({body,request,set})=>{let provided=getApiKeyFromHeaders(Object.fromEntries(request.headers.entries()));if(!isValidAgentApiKey(provided))return set.status=401,{error:"Unauthorized",message:"Invalid or missing API key"};try{if(Array.isArray(body.pathPrefixes)&&body.pathPrefixes.length>0)return issueScopedIframeToken({pathPrefixes:body.pathPrefixes},body.ttlSeconds??void 0);if(!body.pathPrefix)return set.status=400,{error:"BadRequest",message:"Provide either pathPrefix (string) or pathPrefixes (string[])"};return issueIframeToken(body.pathPrefix,body.ttlSeconds??void 0)}catch(err){return set.status=400,{error:"BadRequest",message:err instanceof Error?err.message:String(err)}}},{body:t.Object({pathPrefix:t.Optional(t.String({minLength:1})),pathPrefixes:t.Optional(t.Array(t.String({minLength:1}),{minItems:1,maxItems:16})),ttlSeconds:t.Optional(t.Number())})}).post("/terminal-exchange",({body,set})=>{let{sid,token}=body;if(!sid||!token)return set.status=400,{error:"BadRequest",message:"sid and token required"};if(sid.includes("/")||sid.includes("\x00")||sid.includes(`
4
- `)||sid.includes("|"))return set.status=400,{error:"BadRequest",message:"invalid sid"};let expectedPath=`/terminal/${sid}`,verifyResult=verifyIframeTokenWithReason(token,expectedPath);if(!verifyResult.ok)return getDaemonProfile().logger.warn("terminal-exchange","iframe token rejected",{sid,reason:verifyResult.reason}),set.status=401,{error:"Unauthorized",message:"invalid iframe token",code:verifyResult.reason==="expired"?"expired":verifyResult.reason==="replayed"?"replayed":"invalid"};let cookie=issueTerminalCookieToken(sid,600),cookieName=`vt_term_${sid}`;return set.headers["set-cookie"]=`${cookieName}=${cookie.token}; HttpOnly; Secure; SameSite=None; Path=/terminal/${sid}; Max-Age=600`,set.status=204,null},{body:t.Object({sid:t.String({minLength:1}),token:t.String({minLength:1})})}).post("/ui-exchange",({body,set})=>{let{plugin,token}=body;if(!plugin||!token)return set.status=400,{error:"BadRequest",message:"plugin and token required"};if(!isValidUiPluginName(plugin))return set.status=400,{error:"BadRequest",message:"invalid plugin name"};let expectedPath=`/ui/${plugin}`;if(!verifyIframeToken(token,expectedPath))return set.status=401,{error:"Unauthorized",message:"invalid iframe token"};let cookie=issueUiCookieToken(plugin,600),cookieName=`vt_ui_${plugin}`;return set.headers["set-cookie"]=`${cookieName}=${cookie.token}; HttpOnly; Secure; SameSite=None; Path=/ui/${plugin}/; Max-Age=600`,set.status=204,null},{body:t.Object({plugin:t.String({minLength:1}),token:t.String({minLength:1})})}).post("/ui-exchange-plugin",({body,set})=>{let{plugin,token}=body;if(!plugin||!token)return set.status=400,{error:"BadRequest",message:"plugin and token required"};if(!isValidUiPluginName(plugin))return set.status=400,{error:"BadRequest",message:"invalid plugin name"};if(![`/api/plugins/${plugin}/ui`,`/${plugin}`].find((p)=>verifyIframeToken(token,p)))return set.status=401,{error:"Unauthorized",message:"invalid iframe token"};let cookie=issueUiCookieToken(plugin,600),cookieName=`vt_ui_${plugin}`;return set.headers["set-cookie"]=`${cookieName}=${cookie.token}; HttpOnly; Secure; SameSite=None; Path=/api/plugins/${plugin}/ui/; Max-Age=600`,set.status=204,null},{body:t.Object({plugin:t.String({minLength:1}),token:t.String({minLength:1})})}).get("/system",()=>({hostname:os.hostname(),platform:os.platform(),arch:os.arch(),release:os.release(),cpus:os.cpus().length,totalMemory:os.totalmem(),freeMemory:os.freemem(),uptime:os.uptime(),bunVersion:typeof Bun<"u"?Bun.version:void 0,agentVersion:version,homeDir:os.homedir(),cwd:process.cwd(),environment:"production"})).get("/tunnel",async()=>{let url=await getActiveTunnelUrl(serviceRegistry);if(!url)return{tunnelUrl:null,message:"No tunnel provider registered"};return{tunnelUrl:url}}).get("/status",()=>{let providers=["tunnel","session","ai"].filter((type)=>serviceRegistry.hasProvider(type));return{state:getDaemonProfile().getBootState(),status:getDaemonProfile().getBootState(),version,providers,timestamp:new Date().toISOString()}}).get("/gateway-auth",()=>({configured:gatewayClient.isConfigured(),config:redactUnknownSecrets(gatewayClient.getConfig()),state:getDaemonProfile().getBootState()})).post("/retry-config",async({set})=>{let{getFinalizeRetryHandle}=await import("./finalize-retry-handle-registry-vbq5qhj1.js"),handle=getFinalizeRetryHandle();if(!handle)return set.status=409,{ok:!1,error:"No finalize retry worker is active. The agent either never had cached credentials to retry with, or it already reached the ready state."};let result=await handle.forceRetryNow();if(!result.ok)set.status=503;return{ok:result.ok,error:result.ok?void 0:result.error,state:getDaemonProfile().getBootState(),worker:handle.getState()}}).post("/gateway-auth",async({body,request,set})=>{let stateForAuth=getDaemonProfile().getBootState(),headerMap=Object.fromEntries(request.headers.entries());if(stateForAuth==="ready"){let provided=getApiKeyFromHeaders(headerMap);if(!isValidAgentApiKey(provided))return set.status=401,{success:!1,state:stateForAuth,error:"Unauthorized: API key required to reconfigure"}}else{let apiKey=getApiKeyFromHeaders(headerMap),pairing=getPairingTokenFromHeaders(headerMap),apiKeyOk=isValidAgentApiKey(apiKey),pairingOk=isValidPairingToken(pairing);if(!apiKeyOk&&!pairingOk)return set.status=401,{success:!1,state:stateForAuth,error:"Unauthorized: provide x-agent-api-key OR x-pairing-token for bootstrap"}}let{clientId,clientSecret,workspaceId,globalGatewayUrl,workspaceGatewayUrl}=body;if(!clientId||!clientSecret||!workspaceId||!globalGatewayUrl||!workspaceGatewayUrl)return set.status=400,{success:!1,state:getDaemonProfile().getBootState(),error:"clientId, clientSecret, workspaceId, globalGatewayUrl, and workspaceGatewayUrl are required"};let safeGlobalGatewayUrl,safeWorkspaceGatewayUrl;try{safeGlobalGatewayUrl=assertAllowedGatewayUrl(globalGatewayUrl,"globalGatewayUrl"),safeWorkspaceGatewayUrl=assertAllowedGatewayUrl(workspaceGatewayUrl,"workspaceGatewayUrl")}catch(err){return set.status=400,{success:!1,state:getDaemonProfile().getBootState(),error:err instanceof Error?err.message:String(err)}}{let ctx=currentProfileOrNull()??getDaemonProfile();try{await writeAgentConfigAwaitSecrets({clientId,clientSecret,workspaceId,organizationId:body.organizationId,globalGatewayUrl:safeGlobalGatewayUrl,workspaceGatewayUrl:safeWorkspaceGatewayUrl,agentRecordId:body.agentRecordId,scopes:body.scopes},{dir:ctx.dataDir,scope:ctx.name})}catch(err){return set.status=500,{success:!1,state:getDaemonProfile().getBootState(),error:`Failed to persist gateway credentials to secrets backend: ${err instanceof Error?err.message:String(err)}`}}}let state=getDaemonProfile().getBootState();if(state==="ready"){let db=getDb();if(db){if(await db.setConfig("gateway-auth:clientId",clientId),await db.setConfig("gateway-auth:clientSecret",clientSecret),await db.setConfig("gateway-auth:workspaceId",workspaceId),body.organizationId)await db.setConfig("gateway-auth:organizationId",body.organizationId);if(await db.setConfig("gateway-auth:globalGatewayUrl",safeGlobalGatewayUrl),await db.setConfig("gateway-auth:workspaceGatewayUrl",safeWorkspaceGatewayUrl),body.agentRecordId)await db.setConfig("gateway-auth:agentRecordId",body.agentRecordId)}return gatewayClient.configure({globalGatewayUrl:safeGlobalGatewayUrl,workspaceGatewayUrl:safeWorkspaceGatewayUrl,clientId,clientSecret,workspaceId,organizationId:body.organizationId}),getDaemonProfile().logger.info("preconfig","Gateway credentials re-configured (agent was already ready)"),{success:!0,state,message:"Gateway auth re-configured"}}return getDaemonProfile().logger.info("preconfig","Gateway credentials received \u2014 beginning finalize (background)"),invalidatePairingToken(),runFinalize({clientId,clientSecret,workspaceId,organizationId:body.organizationId,globalGatewayUrl:safeGlobalGatewayUrl,workspaceGatewayUrl:safeWorkspaceGatewayUrl},{agentRecordId:body.agentRecordId,scopes:body.scopes}).catch((err)=>{getDaemonProfile().logger.error("preconfig","Background finalize threw",{error:err instanceof Error?err.message:String(err)})}),set.status=202,{success:!0,state:getDaemonProfile().getBootState(),agentRecordId:body.agentRecordId,message:"Gateway credentials accepted; finalize is running in the background. Poll /health/ready for completion."}},{body:t.Object({clientId:t.Optional(t.String()),clientSecret:t.Optional(t.String()),workspaceId:t.Optional(t.String()),organizationId:t.Optional(t.String()),globalGatewayUrl:t.Optional(t.String()),workspaceGatewayUrl:t.Optional(t.String()),scopes:t.Optional(t.Array(t.String())),agentRecordId:t.Optional(t.String())})})}import{existsSync as existsSync2,mkdirSync as mkdirSync2,rmSync,readdirSync}from"fs";import{join as join3}from"path";function profileDir(name){return join3(getVibecontrolsProductDir(),"agents",validateAgentName(name))}function listProfileNames(){let dir=join3(getVibecontrolsProductDir(),"agents");if(!existsSync2(dir))return[];return readdirSync(dir,{withFileTypes:!0}).filter((entry)=>entry.isDirectory()).map((entry)=>entry.name).filter((name)=>/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(name))}function profileDataDir(name){return join3(getVibecontrolsProductDir(),"agents",validateAgentName(name))}function readConfigForProfile(name){return readAgentConfig({dir:profileDataDir(name)})}function writeConfigForProfile(name,cfg){return writeAgentConfig(cfg,{dir:profileDataDir(name),scope:validateAgentName(name)})}function summarize(name){let defaultName=getDefaultProfile(),instance=getInstances().find((p)=>p.name===name),ctx=profileRegistry.get(name),summary={name,isDefault:name===defaultName,isRunning:instance?.status==="running",attached:ctx!==void 0,bootState:ctx?ctx.getBootState():null,dataDir:ctx?ctx.dataDir:null};if(instance)summary.port=instance.port,summary.pid=instance.pid,summary.startTime=instance.startTime;if(existsSync2(profileDir(name)))summary.config=redactUnknownSecrets(readConfigForProfile(name));return summary}function createProfileManagementRoutes(deps={}){let sm=deps.serviceManagerFactory?deps.serviceManagerFactory():new ServiceManager;return new Elysia({prefix:"/api/profiles"}).get("/",()=>{let onDisk=listProfileNames(),defaultName=getDefaultProfile(),names=new Set(onDisk);return names.add(defaultName),[...names].sort().map((n)=>summarize(n))}).post("/",async({body,set})=>{try{let name=validateAgentName(body.name),dir=profileDir(name);if(existsSync2(dir))return set.status=409,{error:"exists",message:`Profile '${name}' already exists.`};let seed;if(body.copyFrom){let src=validateAgentName(body.copyFrom);if(!existsSync2(profileDir(src)))return set.status=400,{error:"copy-source-missing",message:`Profile '${src}' does not exist.`};seed=readConfigForProfile(src),delete seed["static-api-key"],delete seed.agentRecordId,delete seed.apiKeys}else seed=getAgentConfigSeed();if(body.gatewayUrl)seed.globalGatewayUrl=body.gatewayUrl;if(body.workspaceGatewayUrl)seed.workspaceGatewayUrl=body.workspaceGatewayUrl;if(body.clientId)seed.clientId=body.clientId;if(body.clientSecret)seed.clientSecret=body.clientSecret;if(body.workspaceId)seed.workspaceId=body.workspaceId;if(body.organizationId)seed.organizationId=body.organizationId;mkdirSync2(dir,{recursive:!0}),writeConfigForProfile(name,seed);try{getOrCreateProfile(name)}catch(err){getDaemonProfile().logger.warn("profile-mgmt",`In-process attach failed for '${name}'`,{error:String(err)})}if(getDaemonProfile().logger.info("profile-mgmt",`Created profile '${name}' at ${dir}`),body.start){let startCfg={name,port:body.port??0,daemon:!0,dbPath:getProfileDataDir(),profile:name};await sm.startDaemon(startCfg)}return set.status=201,summarize(name)}catch(err){return set.status=400,{error:"create-failed",message:err instanceof Error?err.message:String(err)}}},{body:t.Object({name:t.String(),gatewayUrl:t.Optional(t.String()),workspaceGatewayUrl:t.Optional(t.String()),clientId:t.Optional(t.String()),clientSecret:t.Optional(t.String()),workspaceId:t.Optional(t.String()),organizationId:t.Optional(t.String()),copyFrom:t.Optional(t.String()),start:t.Optional(t.Boolean()),port:t.Optional(t.Number())})}).get("/:name",({params,set})=>{try{let name=validateAgentName(params.name);if(!existsSync2(profileDir(name)))return set.status=404,{error:"not-found",message:`No profile '${name}'.`};return summarize(name)}catch(err){return set.status=400,{error:"bad-request",message:err instanceof Error?err.message:String(err)}}},{params:t.Object({name:t.String()})}).put("/:name",({params,body,set})=>{try{let name=validateAgentName(params.name);if(!existsSync2(profileDir(name)))return set.status=404,{error:"not-found",message:`No profile '${name}'.`};let forbidden=["static-api-key","apiKeys","agentRecordId"];for(let key of forbidden)if(key in body)return set.status=400,{error:"forbidden-field",message:`Field '${key}' is managed via dedicated commands (vibe key rotate / vibe profile create). It cannot be patched here.`};let next={...readConfigForProfile(name),...body};return writeConfigForProfile(name,next),summarize(name)}catch(err){return set.status=400,{error:"update-failed",message:err instanceof Error?err.message:String(err)}}},{params:t.Object({name:t.String()}),body:t.Record(t.String(),t.Any())}).delete("/:name",async({params,body,query,set})=>{try{let name=validateAgentName(params.name);if(name===getDefaultProfile())return set.status=409,{error:"is-default",message:`Cannot delete active default profile '${name}'. Switch to another profile first.`};let purge=query?.purge==="true"||query?.purge==="1",hasDir=existsSync2(profileDir(name)),inRegistry=profileRegistry.has(name);if(!hasDir&&!inRegistry)return set.status=404,{error:"not-found",message:`No profile '${name}'.`};if(hasDir&&!purge&&!body?.confirm)return set.status=400,{error:"confirm-required",message:"Pass { confirm: true } in the body or `?purge=true` in the query to delete the on-disk dataDir (destructive)."};try{await sm.stop(name)}catch{}try{await profileRegistry.destroy(name)}catch(err){getDaemonProfile().logger.warn("profile-mgmt",`In-process detach failed for '${name}'`,{error:String(err)})}if(hasDir)if(body?.keepConfig)for(let entry of readdirSync(profileDir(name))){if(entry==="config.json")continue;rmSync(join3(profileDir(name),entry),{recursive:!0,force:!0})}else rmSync(profileDir(name),{recursive:!0,force:!0});return getDaemonProfile().logger.info("profile-mgmt",`Deleted profile '${name}'`),{ok:!0,deleted:name,keptConfig:!!body?.keepConfig,detached:inRegistry,purged:hasDir}}catch(err){return set.status=400,{error:"delete-failed",message:err instanceof Error?err.message:String(err)}}},{params:t.Object({name:t.String()}),query:t.Optional(t.Object({purge:t.Optional(t.String())})),body:t.Optional(t.Object({confirm:t.Optional(t.Boolean()),keepConfig:t.Optional(t.Boolean())}))}).post("/:name/switch",({params,set})=>{try{let name=validateAgentName(params.name);if(!existsSync2(profileDir(name)))return set.status=404,{error:"not-found",message:`No profile '${name}'.`};return setDefaultProfile(name),getDaemonProfile().logger.info("profile-mgmt",`Default profile switched to '${name}'`),{ok:!0,defaultProfile:name}}catch(err){return set.status=400,{error:"switch-failed",message:err instanceof Error?err.message:String(err)}}},{params:t.Object({name:t.String()})}).post("/:name/start",async({params,body,set})=>{try{let name=validateAgentName(params.name);if(!existsSync2(profileDir(name)))return set.status=404,{error:"not-found",message:`No profile '${name}'.`};try{getOrCreateProfile(name)}catch(err){getDaemonProfile().logger.warn("profile-mgmt",`In-process attach failed for '${name}'`,{error:String(err)})}if(!getInstances().some((p)=>p.name===name&&p.status==="running")){let startCfg={name,port:body?.port??0,daemon:!0,dbPath:getProfileDataDir(),profile:name};await sm.startDaemon(startCfg)}return summarize(name)}catch(err){return set.status=500,{error:"start-failed",message:err instanceof Error?err.message:String(err)}}},{params:t.Object({name:t.String()}),body:t.Optional(t.Object({port:t.Optional(t.Number())}))}).post("/:name/stop",async({params,set})=>{try{let name=validateAgentName(params.name);try{await sm.stop(name)}catch{}try{await profileRegistry.destroy(name)}catch(err){getDaemonProfile().logger.warn("profile-mgmt",`In-process detach failed for '${name}'`,{error:String(err)})}return summarize(name)}catch(err){return set.status=500,{error:"stop-failed",message:err instanceof Error?err.message:String(err)}}},{params:t.Object({name:t.String()})})}function buildProfileStats(){let rss=process.memoryUsage(),ru=process.resourceUsage(),totalCpuUserMs=ru.userCPUTime/1000,totalCpuSystemMs=ru.systemCPUTime/1000,totalCpuMs=totalCpuUserMs+totalCpuSystemMs,profiles=profileRegistry.list().map((ctx)=>{let childPidCount;try{childPidCount=listTrackedByOwner(ctx.spawnOwnerKey).length}catch{childPidCount=0}return{name:ctx.name,status:ctx.getBootState(),childPidCount,cpuMs:totalCpuMs,heapBytes:rss.heapUsed,dataDir:ctx.dataDir}});return{process:{pid:process.pid,uptimeSeconds:process.uptime(),cpuUserMs:totalCpuUserMs,cpuSystemMs:totalCpuSystemMs,heapUsedBytes:rss.heapUsed,heapTotalBytes:rss.heapTotal,rssBytes:rss.rss},profiles,notes:{perProfileCpu:"deferred",perProfileHeap:"deferred"}}}function createProfileStatsRoutes(){return new Elysia({prefix:"/api/profile-stats"}).get("/",()=>buildProfileStats())}function withTimeout(p,ms){return Promise.race([p,new Promise((_,reject)=>setTimeout(()=>reject(Error(`timeout after ${ms}ms`)),ms))])}function isEnoent(err){let msg=err instanceof Error?err.message:String(err);return/ENOENT/.test(msg)||/no such file or directory/i.test(msg)}async function runDbProbe(db){let probeKey=`__health__:probe:${typeof crypto<"u"&&typeof crypto.randomUUID==="function"?crypto.randomUUID():`${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`}`,value=String(Date.now());if(await withTimeout(db.setConfig(probeKey,value),2000),await withTimeout(db.getConfig(probeKey),2000)!==value)throw Error("round-trip mismatch");try{await withTimeout(db.deleteConfig(probeKey),500)}catch{}}async function checkDb(db,dbPath){if(!db)return{ok:!1,message:"database not opened"};let start=performance.now();try{return await runDbProbe(db),{ok:!0,durationMs:performance.now()-start}}catch(err){if(dbPath&&isEnoent(err))try{return(await import("fs")).mkdirSync(dbPath,{recursive:!0}),await runDbProbe(db),{ok:!0,message:`recovered: dbPath ${dbPath} was missing \u2014 recreated`,durationMs:performance.now()-start}}catch(retryErr){return{ok:!1,message:`ENOENT on dbPath ${dbPath}: ${retryErr instanceof Error?retryErr.message:String(retryErr)}`,durationMs:performance.now()-start}}return{ok:!1,message:err instanceof Error?err.message:String(err),durationMs:performance.now()-start}}}function checkProvider(registry,type){if(!registry)return{ok:!1,message:"no service registry"};let awaiting=getDaemonProfile().getBootState()==="awaiting-config";if(type==="tunnel"){let p=registry.getProvider("tunnel");if(!p&&process.env.AGENT_TUNNEL==="false")return{ok:!0,message:"tunnel disabled via AGENT_TUNNEL=false"};if(p)return{ok:!0,message:`provider: ${p.name}`};return{ok:!1,message:awaiting?"agent is awaiting-config \u2014 POST OAuth credentials to /api/agent/gateway-auth to register tunnel provider":"no tunnel provider registered"}}if(type==="session"){let p=registry.getProvider("session");if(p)return{ok:!0,message:`provider: ${p.name}`};return{ok:!1,message:awaiting?"agent is awaiting-config \u2014 POST OAuth credentials to /api/agent/gateway-auth to register session provider":"no session provider registered"}}return{ok:!0}}async function checkPluginHealth(pm){if(!pm)return{};let results={};for(let plugin of pm.getAllPlugins()){let fn=plugin.getHealth;if(typeof fn!=="function")continue;let start=performance.now();try{let out=await withTimeout(Promise.resolve(fn.call(plugin)),2000);results[plugin.name]={ok:out?.ok!==!1,message:out?.message,durationMs:performance.now()-start}}catch(err){results[plugin.name]={ok:!1,message:err instanceof Error?err.message:String(err),durationMs:performance.now()-start}}}return results}function createHealthRoutes(depsOrRegistry){let deps=depsOrRegistry&&"serviceRegistry"in depsOrRegistry?depsOrRegistry:{serviceRegistry:depsOrRegistry};return new Elysia({prefix:"/health"}).get("/",()=>{return{status:"ok",lifecycleState:deps.serviceRegistry?.getService("agent","lifecycle")?.getState()??"running",bootState:getDaemonProfile().getBootState(),timestamp:new Date().toISOString(),uptime:process.uptime()}}).get("/live",()=>({status:"ok"})).get("/ready",async({set})=>{let lifecycleState=deps.serviceRegistry?.getService("agent","lifecycle")?.getState()??"running",bootState=getDaemonProfile().getBootState(),components={};components.boot={ok:bootState==="ready",message:bootState==="ready"?void 0:`boot state ${bootState}`},components.lifecycle={ok:lifecycleState==="running",message:lifecycleState==="running"?void 0:`lifecycle ${lifecycleState}`},components.db=await checkDb(deps.getDb?.()??null,deps.getDbPath?.()??null),components.tunnel=checkProvider(deps.serviceRegistry,"tunnel"),components.session=checkProvider(deps.serviceRegistry,"session");let plugins=await checkPluginHealth(deps.getPluginManager?.()??null),allOk=Object.values(components).every((r)=>r.ok)&&Object.values(plugins).every((r)=>r.ok);if(!allOk)set.status=503;let reasons=bootState==="degraded"?getDaemonProfile().getDegradedReasons():[],daemonName=getDaemonProfile().name,profilesMap={};for(let ctx of profileRegistry.list())profilesMap[ctx.name]={bootState:ctx.getBootState(),ok:ctx.getBootState()==="ready",degradedReasons:ctx.getDegradedReasons()};let lastFinalizeError=getDaemonProfile().getLastFinalizeError(),body={status:allOk?"ok":"degraded",lifecycleState,bootState,daemon:{profile:daemonName,bootState,ok:bootState==="ready"},profiles:profilesMap,components,plugins,degradedReasons:reasons,lastFinalizeError,timestamp:new Date().toISOString()};if(!allOk)getDaemonProfile().logger.warn("health","Readiness probe failed",{components,plugins,bootState});return body})}var inflight=0,totalServed=0;function createInflightTracker(){return new Elysia({name:"inflight-tracker"}).onRequest(()=>{inflight+=1}).onAfterResponse(()=>{inflight=Math.max(0,inflight-1),totalServed+=1})}function createStatsRoutes(){return new Elysia({prefix:"/api/stats"}).get("/inflight",()=>({inflight:Math.max(0,inflight-1),totalServed}))}var ALLOWED_COMMANDS=Object.freeze(["code","code-insiders","codium","cursor","idea","pycharm","webstorm","goland","phpstorm","rubymine","clion","rider","zed","subl","vim","nvim","emacs","neovide","fleet","helix"]),ALLOWED_SET=new Set(ALLOWED_COMMANDS),ALLOWED_ARG_FLAGS=new Set(["--new-window","-n","--reuse-window","-r","--wait","-w","--add","--goto"]);function which(cmd){try{return Bun.which(cmd)??null}catch{return null}}function createEditorRoutes(){return new Elysia({prefix:"/api/editor"}).get("/allowlist",()=>({commands:[...ALLOWED_COMMANDS]})).get("/detect",async()=>{let results=ALLOWED_COMMANDS.map((cmd)=>[cmd,which(cmd)]),available=[],paths={};for(let[cmd,p]of results)if(p)available.push(cmd),paths[cmd]=p;return{available,paths}}).post("/open",async({body,set})=>{let{command,path:rawPath,args=[]}=body;if(!ALLOWED_SET.has(command))return set.status=400,{ok:!1,error:`Command '${command}' is not in the IDE allowlist`};for(let a of args)if(typeof a!=="string"||!ALLOWED_ARG_FLAGS.has(a))return set.status=400,{ok:!1,error:`Argument '${a}' is not in the flag allowlist`};let resolvedPath;try{resolvedPath=(await resolveSafePath(rawPath,{mustExist:!0})).realPath}catch(err){return set.status=400,{ok:!1,error:`Invalid path: ${err instanceof Error?err.message:String(err)}`}}let resolvedCmd=which(command);if(!resolvedCmd)return set.status=404,{ok:!1,error:`'${command}' is not installed or not on PATH on this agent`};try{let child=spawnTracked({owner:`editor:${command}`,cmd:[resolvedCmd,...args,resolvedPath],env:process.env,stdout:"ignore",stderr:"ignore",stdin:"ignore",meta:{command,path:resolvedPath}});return getDaemonProfile().logger.info("editor",`Launched ${command} on ${resolvedPath}`,{pid:child.pid}),getDaemonProfile().audit.emit("agent","editor.open",{command,path:resolvedPath,pid:child.pid}),{ok:!0,command,resolvedPath,pid:child.pid}}catch(err){return set.status=500,{ok:!1,error:`Failed to spawn editor: ${err instanceof Error?err.message:String(err)}`}}},{body:t.Object({command:t.String({minLength:1,maxLength:40}),path:t.String({minLength:1,maxLength:4096}),args:t.Optional(t.Array(t.String({maxLength:32})))})})}var REGISTRY_KEY=Symbol.for("@vibecontrols/plugin-sdk:contextProviders@1");function getRegistry(){let slots=globalThis,existing=slots[REGISTRY_KEY];if(existing)return existing;let created=new Map;return slots[REGISTRY_KEY]=created,created}function listContextProviders(){return Array.from(getRegistry().values())}function safeHost(maybeUrl){if(!maybeUrl)return null;try{return new URL(maybeUrl).host}catch{return null}}async function buildAgentSelfContext(deps,args){let pm=deps.getPluginManager(),loadedPlugins=pm?pm.getPluginDetails().map((p)=>({pluginName:p.pluginName,packageName:p.packageName,version:p.version,tags:p.tags??[]})):[],mem=process.memoryUsage(),tunnelHost=safeHost(deps.getTunnelHost?.()??null);return{pluginName:"agent",description:"vibecontrols-agent runtime self-report",generatedAt:new Date().toISOString(),data:{profile:args.profile,vibeId:args.vibeId??null,runtime:{bunVersion:typeof Bun<"u"?Bun.version:null,nodeVersion:process.versions.node??null,platform:process.platform,arch:process.arch,pid:process.pid,uptimeSeconds:Math.round(process.uptime()),memory:{rssMB:Math.round(mem.rss/1048576),heapUsedMB:Math.round(mem.heapUsed/1048576)}},agent:{version:deps.getAgentVersion?.()??null,profileRegistered:getVibecontrolsProfile(),tunnelHost},plugins:{count:loadedPlugins.length,items:loadedPlugins}}}}var DEFAULT_PROVIDER_TIMEOUT_MS=2000,SINGLE_FLIGHT_TTL_MS=1000;async function withTimeout2(promise,timeoutMs){let timer,timeout=new Promise((_,reject)=>{timer=setTimeout(()=>reject(Error(`timeout after ${timeoutMs}ms`)),timeoutMs)});try{return await Promise.race([promise,timeout])}finally{if(timer)clearTimeout(timer)}}async function runOne(provider,args){let start=performance.now(),timeoutMs=provider.timeoutMs??DEFAULT_PROVIDER_TIMEOUT_MS;try{let data=await withTimeout2(provider.getContext(args),timeoutMs);if(!data.generatedAt)data.generatedAt=new Date().toISOString();return{ok:!0,data,durationMs:Math.round(performance.now()-start)}}catch(err){return{ok:!1,error:err.message??String(err),durationMs:Math.round(performance.now()-start)}}}class ContextAggregator{deps;inflight=new Map;constructor(deps){this.deps=deps}async aggregate(args){let key=`${args.profile}::${args.vibeId??""}`,existing=this.inflight.get(key);if(existing&&Date.now()-existing.ts<SINGLE_FLIGHT_TTL_MS)return existing.promise;let promise=this.doAggregate(args).finally(()=>{setTimeout(()=>{let entry=this.inflight.get(key);if(entry&&entry.promise===promise)this.inflight.delete(key)},SINGLE_FLIGHT_TTL_MS).unref?.()});return this.inflight.set(key,{ts:Date.now(),promise}),promise}async selfContext(args){return buildAgentSelfContext(this.deps,args)}async pluginContext(name,args){let provider=listContextProviders().find((p)=>p.name===name);if(!provider)return null;return runOne(provider,args)}async pluginsContext(args){let providers=listContextProviders(),settled=await Promise.allSettled(providers.map((p)=>runOne(p,args))),out={};return providers.forEach((p,i)=>{let r=settled[i];if(r&&r.status==="fulfilled")out[p.name]=r.value;else if(r&&r.status==="rejected")out[p.name]={ok:!1,error:r.reason instanceof Error?r.reason.message:String(r.reason),durationMs:0}}),out}async doAggregate(args){let[agent,plugins]=await Promise.all([this.selfContext(args),this.pluginsContext(args)]);return{agent,plugins}}}function parseVibeId(query){let raw=query.vibeId;if(typeof raw!=="string")return;let v=raw.trim();return v.length>0&&v.length<=128?v:void 0}function createContextRoutes(deps){let aggregator=new ContextAggregator(deps);return new Elysia({prefix:"/api/agent/context"}).get("/",async({params,query})=>{let profile=params?.profile??"default",vibeId=parseVibeId(query);return aggregator.aggregate({profile,vibeId})},{query:t.Object({vibeId:t.Optional(t.String())})}).get("/agent",async({params,query})=>{let profile=params?.profile??"default",vibeId=parseVibeId(query);return aggregator.selfContext({profile,vibeId})},{query:t.Object({vibeId:t.Optional(t.String())})}).get("/plugins",async({params,query})=>{let profile=params?.profile??"default",vibeId=parseVibeId(query);return aggregator.pluginsContext({profile,vibeId})},{query:t.Object({vibeId:t.Optional(t.String())})}).get("/plugins/:name",async({params,query,set})=>{let profile=params?.profile??"default",name=params?.name;if(!name)return set.status=400,{error:"missing plugin name"};let vibeId=parseVibeId(query),entry=await aggregator.pluginContext(name,{profile,vibeId});if(!entry)return set.status=404,{error:`no context provider registered under name "${name}"`};return entry},{params:t.Object({name:t.String()}),query:t.Object({vibeId:t.Optional(t.String())})})}var FINALIZE_EXEMPT_PREFIXES=["/health","/api/agent/status","/api/agent/version","/api/agent/identity","/api/agent/api-key","/api/agent/tunnel","/api/agent/system","/api/agent/gateway-auth","/api/stats","/metrics","/api/profiles","/api/profile-stats"];function isFinalizeExempt(path){return FINALIZE_EXEMPT_PREFIXES.some((p)=>path.startsWith(p))}var UUID_RE=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function normalizeRouteLabel(path){return path.split("/").map((seg)=>{if(!seg)return seg;if(/^\d+$/.test(seg))return":id";if(UUID_RE.test(seg))return":id";if(seg.length>=24&&/^[A-Za-z0-9_-]+$/.test(seg))return":id";return seg}).join("/")}async function createApp(options){let{port,host,dbPath,logLevel,corsOrigin}=options,effectiveDbPath=dbPath??getProfileDataDir();try{(await import("fs")).mkdirSync(effectiveDbPath,{recursive:!0})}catch(err){throw getDaemonProfile().logger.error("app","Failed to create dbPath dir at boot",{dbPath:effectiveDbPath,error:String(err)}),Error(`Cannot create dbPath ${effectiveDbPath}: ${err instanceof Error?err.message:String(err)}`,{cause:err})}if(logLevel)getDaemonProfile().logger.setLevel(logLevel);(async()=>{let{logShipper}=await import("./log-shipper-9rtt4y1s.js");logShipper.init()})(),(async()=>{let version=await getPackageVersion();await getMetricsRegistry({version,profile:getVibecontrolsProfile()})})();try{let{checkDependencies}=await import("./bootstrap.service-fknk5beq.js"),deps=checkDependencies(),missingRequired=deps.filter((d)=>d.required&&!d.installed),missingOptional=deps.filter((d)=>!d.required&&!d.installed);if(missingRequired.length>0)getDaemonProfile().logger.error("app",`Missing required system deps: ${missingRequired.map((d)=>d.name).join(", ")}. Run \`vibe setup\` to install.`);if(missingOptional.length>0)getDaemonProfile().logger.warn("app",`Missing optional system deps: ${missingOptional.map((d)=>d.name).join(", ")}. Some plugins may fail their prereqs check.`)}catch(err){getDaemonProfile().logger.warn("app","Boot-time dependency check failed",{error:String(err)})}try{getDaemonProfile().audit.runRetention()}catch(err){getDaemonProfile().logger.warn("app","Audit-log retention sweep failed",{error:String(err)})}let serviceRegistry=new ServiceRegistry;startBootstrapTunnel(serviceRegistry,{port});let CORS_METHODS="GET, POST, PUT, PATCH, DELETE, OPTIONS",CORS_HEADERS="Content-Type, x-agent-api-key, Authorization, x-requested-with",configuredCorsOrigins=Array.isArray(corsOrigin)?corsOrigin:(corsOrigin??"").split(",").map((origin)=>origin.trim()).filter(Boolean),trustedProductionOrigins=new Set(["https://vibecontrols.com","https://app.vibecontrols.com","https://alphaapp.vibecontrols.com","https://burdenoff.com","https://app.burdenoff.com","https://alphaapp.burdenoff.com"]),isAllowedOrigin=(origin)=>{try{let url=new URL(origin);if(configuredCorsOrigins.includes(origin))return!0;if(configuredCorsOrigins.includes("*"))return!1;return url.hostname==="localhost"||url.hostname==="127.0.0.1"||url.hostname==="0.0.0.0"||url.hostname.endsWith(".local.burdenoff.com")||trustedProductionOrigins.has(url.origin)}catch{return!1}},db=null,pluginManager=null,hostServices=null,lifecycle=null,pluginPublicPaths=()=>[],pluginRoutesApp=null,uiServerApp=null,finalizeInFlight=null,SHUTDOWN_PHASE_MS=5000,runPhase=async(name,fn)=>{let started=Date.now();try{await Promise.race([Promise.resolve(fn()),new Promise((_,reject)=>setTimeout(()=>reject(Error(`shutdown phase ${name} exceeded ${SHUTDOWN_PHASE_MS}ms`)),SHUTDOWN_PHASE_MS))]),getDaemonProfile().logger.info("app",`shutdown.phase ${name} complete`,{ms:Date.now()-started})}catch(err){getDaemonProfile().logger.warn("app",`shutdown.phase ${name} failed`,{error:String(err),ms:Date.now()-started})}},stopFn=async(context)=>{if(getDaemonProfile().logger.info("app","Agent shutdown starting",{reason:context?.reason??"shutdown"}),await runPhase("plugins",async()=>{if(pluginManager)await pluginManager.dispatchServerStop(context)}),await runPhase("bootstrap-tunnel",()=>stopBootstrapTunnel()),await runPhase("tracked-subprocesses",async()=>{let{killAllTracked}=await import("./subprocess-vks78xmn.js");await killAllTracked()}),context?.reason!=="reload")await runPhase("db-close",async()=>{if(db)await db.close()});getDaemonProfile().logger.close(),getDaemonProfile().logger.info("app","Agent server stopped")},finalize=async(creds,opts)=>{if(getDaemonProfile().getBootState()==="ready")return{ok:!0};if(finalizeInFlight)return finalizeInFlight;return finalizeInFlight=(async()=>{getDaemonProfile().setBootState("initializing");try{let safeCreds={...creds,globalGatewayUrl:assertAllowedGatewayUrl(creds.globalGatewayUrl,"globalGatewayUrl"),workspaceGatewayUrl:assertAllowedGatewayUrl(creds.workspaceGatewayUrl,"workspaceGatewayUrl")},encryptionKey=await fetchEncryptionKey(safeCreds),resolvedDbPath=effectiveDbPath,cfgForStorage=readAgentConfig({dir:getDaemonProfile().dataDir}),storageAdapterName=cfgForStorage.storageAdapter??process.env.VIBE_STORAGE_ADAPTER??void 0,storageAdapterOptions=cfgForStorage.storageOptions;try{db=await createAgentDatabase({dbPath:resolvedDbPath,encryptionKey,adapterName:storageAdapterName,adapterOptions:storageAdapterOptions})}catch(openErr){let message=openErr instanceof Error?openErr.message:String(openErr);getDaemonProfile().logger.error("app","Storage open failed; quarantining and retrying once",{error:message,path:resolvedDbPath});try{let fs=await import("fs");if(fs.existsSync(resolvedDbPath)){let ts=new Date().toISOString().replace(/[:.]/g,"-"),broken=`${resolvedDbPath}.broken-${ts}`;fs.renameSync(resolvedDbPath,broken),getDaemonProfile().logger.warn("app",`Quarantined storage to ${broken} \u2014 fresh DB will be created`)}db=await createAgentDatabase({dbPath:resolvedDbPath,encryptionKey,adapterName:storageAdapterName,adapterOptions:storageAdapterOptions})}catch(retryErr){let retryMsg=retryErr instanceof Error?retryErr.message:String(retryErr);throw getDaemonProfile().recordDegradedReason("storage",retryMsg),Error(`Storage open failed twice; agent is degraded: ${retryMsg}`,{cause:retryErr})}}if(await writeAgentConfigAwaitSecrets({clientId:safeCreds.clientId,clientSecret:safeCreds.clientSecret,workspaceId:safeCreds.workspaceId,organizationId:safeCreds.organizationId,globalGatewayUrl:safeCreds.globalGatewayUrl,workspaceGatewayUrl:safeCreds.workspaceGatewayUrl,agentRecordId:opts?.agentRecordId,scopes:opts?.scopes},{dir:getDaemonProfile().dataDir,scope:getDaemonProfile().name}),await db.setConfig("gateway-auth:clientId",safeCreds.clientId),await db.setConfig("gateway-auth:clientSecret",safeCreds.clientSecret),await db.setConfig("gateway-auth:globalGatewayUrl",safeCreds.globalGatewayUrl),await db.setConfig("gateway-auth:workspaceGatewayUrl",safeCreds.workspaceGatewayUrl),await db.setConfig("gateway-auth:workspaceId",safeCreds.workspaceId),safeCreds.organizationId)await db.setConfig("gateway-auth:organizationId",safeCreds.organizationId);if(opts?.agentRecordId)await db.setConfig("gateway-auth:agentRecordId",opts.agentRecordId);serviceRegistry.db=db,await serviceRegistry.hydrateDefaultsFromDb(),pluginManager=new PluginManager(db),await pluginManager.loadCorePlugins();try{await pluginManager.loadAll()}catch(err){getDaemonProfile().logger.warn("app","Failed to load some external plugins",{error:String(err)})}let autoInstallDisabled=process.env.VIBE_SKIP_AUTO_INSTALL==="1"||await db.getConfig("plugins:auto-install-disabled");if(autoInstallDisabled!=="true"&&autoInstallDisabled!==!0)try{let installed=await pluginManager.ensureDefaultPlugins((message)=>getDaemonProfile().logger.info("app",`[auto-install] ${message}`));if(installed.length>0)getDaemonProfile().logger.info("app",`Auto-installed ${installed.length} default plugin(s): ${installed.map((p)=>p.packageName).join(", ")}`)}catch(err){getDaemonProfile().logger.warn("app","Failed to auto-install default plugins",{error:String(err)})}getDaemonProfile().logger.info("app",`Plugins loaded: ${pluginManager.getPluginDetails().length} total (${pluginManager.getPluginDetails().filter((p)=>p.isCore).length} core)`);try{let details=pluginManager.getPluginDetails(),byStatus={loaded:details.filter((p)=>p.loaded).length,failed:details.filter((p)=>!p.loaded).length};setPluginsLoaded(byStatus)}catch{}let storageProvider={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)}},packageVersion=await getPackageVersion();hostServices={storage:storageProvider,logger:getDaemonProfile().logger,serviceRegistry,getProvider:(type)=>serviceRegistry.getProvider(type),getAgentBaseUrl:()=>process.env.AGENT_URL||`http://localhost:${port}`,getAgentVersion:()=>packageVersion,validateApiKey:(key)=>isValidAgentApiKey(key),setCodeServerSessionValidator:(fn)=>{codeServerSessionValidator=fn},broadcast,workspaceQuery:async(query,variables)=>gatewayClient.workspaceQuery(query,variables),isGatewayConfigured:()=>gatewayClient.isConfigured(),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:()=>getPluginRegistry(),getDataDir:()=>getVibecontrolsDir(),cliContributors:new CliContributorRegistry,audit:{emit:(event,payload)=>getDaemonProfile().audit.emit("agent",event,payload??{})},telemetry:{emit:(event,payload)=>{import("./telemetry-rew0mtj2.js").then(({telemetryService})=>telemetryService.emit(event,payload??{})).catch(()=>{})}},os:getOsAdapter(),iframeBridge:createIframeBridge()},gatewayClient.configure({globalGatewayUrl:safeCreds.globalGatewayUrl,workspaceGatewayUrl:safeCreds.workspaceGatewayUrl,clientId:safeCreds.clientId,clientSecret:safeCreds.clientSecret,workspaceId:safeCreds.workspaceId,organizationId:safeCreds.organizationId});let routeDeps={db,serviceRegistry,pluginManager,broadcast,hostServices};routeDeps.app=app;let pluginRoutesAppInitialized=!1,rebuildPluginSurfaces=()=>{let{routes:pluginRoutes,getPublicPaths,mountPlugin}=createPluginRouter(pluginManager,routeDeps);if(routeDeps.mountPlugin=mountPlugin,pluginPublicPaths=getPublicPaths,markPluginPublicPathsDirty(),pluginRoutesApp=pluginRoutes,uiServerApp=createUIServer(pluginManager),pluginManager&&pluginRoutesAppInitialized&&hostServices)pluginManager.dispatchServerStart(pluginRoutesApp,hostServices).catch((err)=>getDaemonProfile().logger.warn("app","Re-dispatch of onServerStart after plugin reload failed",{error:String(err)}));pluginRoutesAppInitialized=!0};routeDeps.rebuildPluginSurfaces=rebuildPluginSurfaces,rebuildPluginSurfaces(),lifecycle=new LifecycleManager(serviceRegistry,pluginManager,db,app,hostServices,stopFn),serviceRegistry.registerService("agent","lifecycle",lifecycle),getDaemonProfile().attachServices({db,serviceRegistry,pluginManager,lifecycle,hostServices}),mountProfileRoutes(getDaemonProfile(),{rebuildPluginSurfaces,mountPlugin:routeDeps.mountPlugin});try{await getDaemonProfile().keyVault.bindApiKey(getAgentApiKey())}catch(err){getDaemonProfile().logger.warn("app","Failed to bind api key into daemon keyVault",{error:String(err)})}let criticalFailures=[];try{let{failures}=await pluginManager.dispatchServerStart(pluginRoutesApp,hostServices);for(let f of failures)if(isCriticalPlugin(f.plugin)||(f.packageName?isCriticalPlugin(f.packageName):!1))criticalFailures.push(f),getDaemonProfile().recordDegradedReason(f.plugin,f.error);else getDaemonProfile().logger.warn("app",`Non-critical plugin ${f.plugin} failed onServerStart; continuing`,{error:f.error})}catch(err){getDaemonProfile().logger.warn("app","Error during plugin onServerStart dispatch",{error:String(err)})}try{await pluginManager.dispatchServerReady(app,hostServices)}catch(err){getDaemonProfile().logger.warn("app","Error during plugin onServerReady dispatch",{error:String(err)})}if(getDaemonProfile().clearFinalizeError(),criticalFailures.length>0)getDaemonProfile().setBootState("degraded"),getDaemonProfile().logger.error("app","Agent finalized but degraded \u2014 critical plugins failed",{failures:criticalFailures.map((f)=>`${f.plugin}: ${f.error}`)});else getDaemonProfile().setBootState("ready"),getDaemonProfile().logger.info("app","Agent finalized \u2014 state=ready"),getDaemonProfile().audit.emit("agent","gateway-auth.configured",{workspaceId:safeCreds.workspaceId,organizationId:safeCreds.organizationId,agentRecordId:opts?.agentRecordId});return(async()=>{try{if(await pluginManager.provisionDefaultPrereqs(app,hostServices),getDaemonProfile().logger.info("app","Default provider prerequisites provisioned"),(serviceRegistry.listProvidersForType("tunnel")??[]).some((p)=>p.pluginName!=="bootstrap")){let{tryHandoverBootstrapTunnel}=await import("./tunnel-bootstrap-x82wcnt8.js");if(!tryHandoverBootstrapTunnel())stopBootstrapTunnel();serviceRegistry.unregisterProvider("tunnel","bootstrap"),getDaemonProfile().logger.info("app","Bootstrap tunnel handed over to the real tunnel provider")}}catch(err){getDaemonProfile().logger.warn("app","Plugin prerequisite provisioning failed",{error:String(err)})}})(),{ok:!0}}catch(err){getDaemonProfile().setBootState("awaiting-config");let msg=err instanceof Error?err.message:String(err);if(getDaemonProfile().recordFinalizeError(msg),getDaemonProfile().logger.error("app","Finalize failed",{error:msg}),process.env.VIBE_STRICT_KEY_FETCH==="1")getDaemonProfile().logger.error("app","VIBE_STRICT_KEY_FETCH=1 \u2192 aborting daemon (strict mode)",{error:msg}),setTimeout(()=>process.exit(1),50);return{ok:!1,error:msg}}finally{finalizeInFlight=null}})(),finalizeInFlight},corsPlugin=cors({origin:(request)=>{let origin=request.headers.get("origin");return!!origin&&isAllowedOrigin(origin)},credentials:!0,allowedHeaders:CORS_HEADERS.split(",").map((s)=>s.trim()),methods:CORS_METHODS.split(",").map((s)=>s.trim()),exposeHeaders:["content-type","content-length"],maxAge:86400,preflight:!0}),DEFAULT_MAX_BODY_BYTES=10485760,maxBodyEnv=process.env.VIBECONTROLS_MAX_BODY_BYTES,parsedMaxBody=maxBodyEnv?Number.parseInt(maxBodyEnv,10):NaN,maxBodySize=Number.isFinite(parsedMaxBody)&&parsedMaxBody>0?parsedMaxBody:DEFAULT_MAX_BODY_BYTES,appRef={current:null},app=new Elysia({serve:{maxRequestBodySize:maxBodySize}}).onRequest(({request,set})=>{let requestId=extractRequestId(request.headers)??generateRequestId();enterRequestContext({requestId,startedAt:new Date().toISOString()});let headers=set.headers??={};headers["X-Request-Id"]=requestId}).onRequest(({request})=>{try{let url=new URL(request.url).pathname,name=/^\/api\/profiles\/([^/]+)(?:\/|$)/.exec(url)?.[1],ctx=name?profileRegistry.get(name):null;enterProfileContext(ctx??getDaemonProfile())}catch{enterProfileContext(getDaemonProfile())}}).onRequest(({request,set})=>{let url=new URL(request.url).pathname;if(!url.startsWith("/api/"))return;if(url==="/api/profiles"||url.startsWith("/api/profiles/"))return;if(url==="/api/profile-stats"||url.startsWith("/api/profile-stats/"))return;let defaultProfileUrl=new URL(request.url);defaultProfileUrl.pathname=`/api/profiles/default${url.slice(4)}`;try{request.headers.set("x-vc-profile-rewrite","1"),request.headers.set("x-vc-profile-rewrite-target",defaultProfileUrl.pathname)}catch{}return}).derive(()=>({requestId:getRequestId()??generateRequestId()})).use(corsPlugin).use(rateLimitPlugin()).use(createAuthPlugin(()=>pluginPublicPaths())).use(idempotencyPlugin({getDb:()=>currentProfileOrNull()?.db??db})).onBeforeHandle(({request,set})=>{let state=getDaemonProfile().getBootState();if(state==="ready")return;let url=new URL(request.url).pathname;if(isFinalizeExempt(url))return;return set.status=503,{error:"Agent not yet configured",message:"Agent is in '"+state+"' state. POST credentials to /api/agent/gateway-auth to finalize.",state}}).onAfterHandle(({request,set})=>{let url=new URL(request.url).pathname,isNoisy=url==="/health"||url.startsWith("/api/logs/stream")||url.startsWith("/ui/")||url==="/ws/events"||url==="/api/sessions/health-check"||url.startsWith("/terminal/"),status=typeof set.status==="number"?set.status:200,level=isNoisy?"debug":status>=400?"warn":"info";getDaemonProfile().logger[level]("http",`${request.method} ${url} \u2192 ${status}`,{method:request.method,path:url,statusCode:status});try{recordHttpRequest(request.method,normalizeRouteLabel(url),status)}catch{}}).use(createHealthRoutes({serviceRegistry,getDb:()=>currentProfileOrNull()?.db??db,getDbPath:()=>effectiveDbPath,getPluginManager:()=>currentProfileOrNull()?.pluginManager??pluginManager})).use(createMetricsRoutes()).use(createPreConfigRoutes({serviceRegistry,runFinalize:(creds,opts)=>finalize(creds,opts),getDb:()=>currentProfileOrNull()?.db??db})).use(createInflightTracker()).use(createStatsRoutes()).use(createEditorRoutes()).use(createContextRoutes({getPluginManager:()=>currentProfileOrNull()?.pluginManager??pluginManager,getTunnelHost:()=>readTunnelState()?.url??null})).use(createProfileManagementRoutes()).use(createProfileStatsRoutes()).use(createEventsWs()).use(createLogWs()).use(createTerminalProxy(serviceRegistry)).ws("/code-server/*",buildCodeServerBridge(port)).all("/api/profiles/:name/*",async({params,request,set})=>{let hasReqBody=request.method!=="GET"&&request.method!=="HEAD",bodyBytes=hasReqBody?await request.arrayBuffer():void 0,dispatched=await dispatchProfileRequest(params.name,request,bodyBytes);if(dispatched&&dispatched.status!==404)return dispatched;let running=getVibecontrolsProfile(),requested=params.name;if(requested!==running)return set.status=404,{error:"profile-mismatch",running,requested,hint:"This daemon serves a different profile. Call GET /api/profiles to discover the right tunnel."};let u=new URL(request.url),stripped=u.pathname.replace(/^\/api\/profiles\/[^/]+/,"/api"),headers=new Headers(request.headers);headers.set("x-vc-profile-rewrite","1");let init={method:request.method,headers};if(hasReqBody&&bodyBytes!==void 0)init.body=bodyBytes;let rewritten=new Request(`${u.origin}${stripped}${u.search}`,init),target=appRef.current;if(!target)return new Response(JSON.stringify({error:"agent-not-ready"}),{status:503,headers:{"content-type":"application/json"}});return target.handle(rewritten)}).all("/api/*",async({request})=>{if(getDaemonProfile().getBootState()!=="ready"||!pluginRoutesApp)return new Response(JSON.stringify({error:"Agent not yet configured",state:getDaemonProfile().getBootState(),message:"Plugin routes are unavailable until the agent reaches state=ready. POST credentials to /api/agent/gateway-auth to finalize."}),{status:503,headers:{"content-type":"application/json"}});try{let apiUiUrl=new URL(request.url),apiUiMatch=/^\/api\/plugins\/([a-z0-9-]{1,64})\/ui(?:\/.*)?$/.exec(apiUiUrl.pathname);if(apiUiMatch&&request.method==="GET"){let plugin=apiUiMatch[1];if(isValidUiPluginName(plugin)){let restAfterUi=apiUiUrl.pathname.slice(`/api/plugins/${plugin}/ui`.length),isBareDoc=restAfterUi===""||restAfterUi==="/",looksLikeNavigation=request.headers.get("sec-fetch-mode")==="navigate";if(isBareDoc||looksLikeNavigation){let cookie=getUiCookieFromRequest(request,plugin);if(!cookie||!verifyUiCookieToken(cookie,plugin))return new Response(renderUiBootstrapHtml(plugin,"/api/profiles/default/agent/ui-exchange-plugin"),{status:200,headers:{"content-type":"text/html; charset=utf-8","Content-Security-Policy":"frame-ancestors 'self' http://localhost:* http://127.0.0.1:* https://localhost:* https://127.0.0.1:* https://*.local.burdenoff.com https://vibecontrols.com https://*.vibecontrols.com https://burdenoff.com https://app.burdenoff.com https://alphaapp.burdenoff.com"}})}}}}catch{}return pluginRoutesApp.handle(request)}).all("/ui/*",async({request})=>{if(getDaemonProfile().getBootState()!=="ready"||!uiServerApp)return new Response("Plugin UI not yet available",{status:503});return uiServerApp.handle(request)}).all("/code-server/*",async({request})=>{if(getDaemonProfile().getBootState()!=="ready"||!pluginRoutesApp)return new Response("code-server not yet available",{status:503});return pluginRoutesApp.handle(request)}).all("/plan/*",async({request})=>{if(getDaemonProfile().getBootState()!=="ready"||!pluginRoutesApp)return new Response("plan provider not yet available",{status:503});return pluginRoutesApp.handle(request)});return appRef.current=app,{app,async start(){app.listen({port,hostname:host}),getDaemonProfile().logger.info("app",`Agent server listening on ${host}:${port}`);try{let list=(process.env.VIBECONTROLS_PROFILES??"").split(",").map((s)=>s.trim()).filter(Boolean),bootName=getDaemonProfile().name,{getOrCreateProfile:getOrCreateProfile2}=await import("./daemon-profile-c7zt62gk.js"),{attachSecondaryProfile}=await import("./secondary-profile-attach-n597amqv.js"),strict=process.env.VIBE_STRICT_KEY_FETCH==="1";for(let name of list){if(name===bootName)continue;try{let ctx=getOrCreateProfile2(name),result=await attachSecondaryProfile(ctx);if(result.ok)getDaemonProfile().logger.info("app",`Secondary profile '${name}' attached (db+services online)`);else if(strict)throw Error(`attachServices for secondary profile '${name}' failed: ${result.error}`);else ctx.recordDegradedReason("attach",result.error??"unknown"),getDaemonProfile().logger.warn("app",`Secondary profile '${name}' is degraded (no creds / attach failed)`,{error:result.error})}catch(err){if(strict)throw getDaemonProfile().logger.error("app",`--strict-key-fetch: secondary profile '${name}' attach failed; aborting`,{error:String(err)}),setTimeout(()=>process.exit(1),50),err;getDaemonProfile().logger.warn("app",`Failed to attach secondary profile '${name}'`,{error:String(err)})}}}catch{}return app},stop:stopFn,finalize,getState:()=>getDaemonProfile().getBootState(),getLifecycle:()=>currentProfileOrNull()?.lifecycle??lifecycle,getDb:()=>currentProfileOrNull()?.db??db,getServiceRegistry:()=>currentProfileOrNull()?.serviceRegistry??serviceRegistry,getPluginManager:()=>currentProfileOrNull()?.pluginManager??pluginManager,getHostServices:()=>currentProfileOrNull()?.hostServices??hostServices}}var codeServerSessionValidator=null;function getCookieValue(cookieHeader,name){if(!cookieHeader)return null;let m=cookieHeader.match(new RegExp(`(?:^|;\\s*)${name}=([^;]*)`));return m?m[1]:null}function buildCodeServerBridge(port){let payloadBytes=(payload)=>typeof payload==="string"?Buffer.byteLength(payload):payload.byteLength;return{open(ws){let wsData=ws.data,apiKey=wsData.query?.apiKey??getApiKeyFromHeaders(wsData.headers??{})??getApiKeyFromHeaders(wsData.request?Object.fromEntries(wsData.request.headers.entries()):{});if(!isValidAgentApiKey(apiKey)){let cookieHeader=wsData.headers?.cookie??wsData.request?.headers.get("cookie")??null,sessionToken=getCookieValue(cookieHeader,"__vibe_cs_session");if(!sessionToken||!codeServerSessionValidator?.(sessionToken)){ws.close(1008,"Unauthorized");return}}let bridgeProfile=getDaemonProfile().name;fetch(`http://127.0.0.1:${port}/api/profiles/${encodeURIComponent(bridgeProfile)}/code-server/status`,{headers:{"x-agent-api-key":getAgentApiKey()}}).then((r)=>r.json()).then((raw)=>{if(wsData._csClosed)return;let status=raw;if(!status.running||!status.port){ws.close(1011,"code-server not running");return}let requestUrl=wsData.request?.url??"/code-server/",upstreamPath;try{let url=new URL(requestUrl,`http://127.0.0.1:${status.port}`);upstreamPath=(url.pathname.replace(/^\/code-server\/?/,"/")||"/")+url.search}catch{upstreamPath="/"}let upstreamWs=new WebSocket(`ws://127.0.0.1:${status.port}${upstreamPath}`),state={upstream:upstreamWs,ready:!1,buffer:[],bufferBytes:0,openTimer:setTimeout(()=>{try{upstreamWs.close(1011,"upstream open timeout")}catch{}try{ws.close(1011,"upstream open timeout")}catch{}},1e4)};wsData._csBridge=state,upstreamWs.addEventListener("open",()=>{clearTimeout(state.openTimer),state.ready=!0;for(let msg of state.buffer)upstreamWs.send(msg);state.buffer.length=0,state.bufferBytes=0}),upstreamWs.addEventListener("message",(event)=>{try{let d=event.data;if(d instanceof ArrayBuffer)ws.send(new Uint8Array(d));else if(d instanceof Blob)d.arrayBuffer().then((ab)=>{try{ws.send(new Uint8Array(ab))}catch{}});else ws.send(d)}catch{}}),upstreamWs.addEventListener("close",(event)=>{clearTimeout(state.openTimer);try{ws.close(event.code||1000,event.reason||"upstream closed")}catch{}}),upstreamWs.addEventListener("error",()=>{clearTimeout(state.openTimer);try{ws.close(1011,"upstream error")}catch{}})}).catch(()=>{ws.close(1011,"Failed to query code-server status")})},message(ws,message){let state=ws.data?._csBridge;if(!state)return;let payload;if(typeof message==="string")payload=message;else if(message instanceof ArrayBuffer)payload=message;else if(message instanceof Uint8Array||Buffer.isBuffer(message)){let copy=new ArrayBuffer(message.byteLength);new Uint8Array(copy).set(new Uint8Array(message.buffer,message.byteOffset,message.byteLength)),payload=copy}else if(typeof message==="object"&&message!==null)payload=JSON.stringify(message);else payload=String(message);if(state.upstream&&state.ready&&state.upstream.readyState===WebSocket.OPEN)try{state.upstream.send(payload)}catch{}else{let nextBytes=payloadBytes(payload);if(state.buffer.length>=256||state.bufferBytes+nextBytes>1048576){try{state.upstream.close(1013,"buffer limit exceeded")}catch{}try{ws.close(1013,"buffer limit exceeded")}catch{}return}state.buffer.push(payload),state.bufferBytes+=nextBytes}},close(ws){ws.data._csClosed=!0;let state=ws.data?._csBridge;if(state?.openTimer)clearTimeout(state.openTimer);if(state?.upstream&&state.upstream.readyState===WebSocket.OPEN)state.upstream.close(1000,"client disconnected")}}}async function getPackageVersion(){try{let{readFileSync:readFileSync3}=await import("fs"),{join:join4,dirname:dirname2}=await import("path"),{fileURLToPath}=await import("url"),__dirname2=dirname2(fileURLToPath(import.meta.url));return JSON.parse(readFileSync3(join4(__dirname2,"..","package.json"),"utf8")).version||"1.0.0"}catch{return"1.0.0"}}
4
+ `)||sid.includes("|"))return set.status=400,{error:"BadRequest",message:"invalid sid"};let expectedPath=`/terminal/${sid}`,verifyResult=verifyIframeTokenWithReason(token,expectedPath);if(!verifyResult.ok)return getDaemonProfile().logger.warn("terminal-exchange","iframe token rejected",{sid,reason:verifyResult.reason}),set.status=401,{error:"Unauthorized",message:"invalid iframe token",code:verifyResult.reason==="expired"?"expired":verifyResult.reason==="replayed"?"replayed":"invalid"};let cookie=issueTerminalCookieToken(sid,600),cookieName=`vt_term_${sid}`;return set.headers["set-cookie"]=`${cookieName}=${cookie.token}; HttpOnly; Secure; SameSite=None; Path=/terminal/${sid}; Max-Age=600`,set.status=204,null},{body:t.Object({sid:t.String({minLength:1}),token:t.String({minLength:1})})}).post("/ui-exchange",({body,set})=>{let{plugin,token}=body;if(!plugin||!token)return set.status=400,{error:"BadRequest",message:"plugin and token required"};if(!isValidUiPluginName(plugin))return set.status=400,{error:"BadRequest",message:"invalid plugin name"};let expectedPath=`/ui/${plugin}`;if(!verifyIframeToken(token,expectedPath))return set.status=401,{error:"Unauthorized",message:"invalid iframe token"};let cookie=issueUiCookieToken(plugin,600),cookieName=`vt_ui_${plugin}`;return set.headers["set-cookie"]=`${cookieName}=${cookie.token}; HttpOnly; Secure; SameSite=None; Path=/ui/${plugin}/; Max-Age=600`,set.status=204,null},{body:t.Object({plugin:t.String({minLength:1}),token:t.String({minLength:1})})}).post("/ui-exchange-plugin",({body,set})=>{let{plugin,token}=body;if(!plugin||!token)return set.status=400,{error:"BadRequest",message:"plugin and token required"};if(!isValidUiPluginName(plugin))return set.status=400,{error:"BadRequest",message:"invalid plugin name"};if(![`/api/plugins/${plugin}/ui`,`/${plugin}`].find((p)=>verifyIframeToken(token,p)))return set.status=401,{error:"Unauthorized",message:"invalid iframe token"};let cookie=issueUiCookieToken(plugin,600),cookieName=`vt_ui_${plugin}`;return set.headers["set-cookie"]=`${cookieName}=${cookie.token}; HttpOnly; Secure; SameSite=None; Path=/api/plugins/${plugin}/ui/; Max-Age=600`,set.status=204,null},{body:t.Object({plugin:t.String({minLength:1}),token:t.String({minLength:1})})}).get("/system",()=>({hostname:os.hostname(),platform:os.platform(),arch:os.arch(),release:os.release(),cpus:os.cpus().length,totalMemory:os.totalmem(),freeMemory:os.freemem(),uptime:os.uptime(),bunVersion:typeof Bun<"u"?Bun.version:void 0,agentVersion:version,homeDir:os.homedir(),cwd:process.cwd(),environment:"production"})).get("/tunnel",async()=>{let url=await getActiveTunnelUrl(serviceRegistry);if(!url)return{tunnelUrl:null,message:"No tunnel provider registered"};return{tunnelUrl:url}}).get("/status",()=>{let providers=["tunnel","session","ai"].filter((type)=>serviceRegistry.hasProvider(type));return{state:getDaemonProfile().getBootState(),status:getDaemonProfile().getBootState(),version,providers,timestamp:new Date().toISOString()}}).get("/gateway-auth",()=>({configured:gatewayClient.isConfigured(),config:redactUnknownSecrets(gatewayClient.getConfig()),state:getDaemonProfile().getBootState()})).post("/retry-config",async({set})=>{let{getFinalizeRetryHandle}=await import("./finalize-retry-handle-registry-vbq5qhj1.js"),handle=getFinalizeRetryHandle();if(!handle)return set.status=409,{ok:!1,error:"No finalize retry worker is active. The agent either never had cached credentials to retry with, or it already reached the ready state."};let result=await handle.forceRetryNow();if(!result.ok)set.status=503;return{ok:result.ok,error:result.ok?void 0:result.error,state:getDaemonProfile().getBootState(),worker:handle.getState()}}).post("/gateway-auth",async({body,request,set})=>{let stateForAuth=getDaemonProfile().getBootState(),headerMap=Object.fromEntries(request.headers.entries());if(stateForAuth==="ready"){let provided=getApiKeyFromHeaders(headerMap);if(!isValidAgentApiKey(provided))return set.status=401,{success:!1,state:stateForAuth,error:"Unauthorized: API key required to reconfigure"}}else{let apiKey=getApiKeyFromHeaders(headerMap),pairing=getPairingTokenFromHeaders(headerMap),apiKeyOk=isValidAgentApiKey(apiKey),pairingOk=isValidPairingToken(pairing);if(!apiKeyOk&&!pairingOk)return set.status=401,{success:!1,state:stateForAuth,error:"Unauthorized: provide x-agent-api-key OR x-pairing-token for bootstrap"}}let{clientId,clientSecret,workspaceId,globalGatewayUrl,workspaceGatewayUrl}=body;if(!clientId||!clientSecret||!workspaceId||!globalGatewayUrl||!workspaceGatewayUrl)return set.status=400,{success:!1,state:getDaemonProfile().getBootState(),error:"clientId, clientSecret, workspaceId, globalGatewayUrl, and workspaceGatewayUrl are required"};let safeGlobalGatewayUrl,safeWorkspaceGatewayUrl;try{safeGlobalGatewayUrl=assertAllowedGatewayUrl(globalGatewayUrl,"globalGatewayUrl"),safeWorkspaceGatewayUrl=assertAllowedGatewayUrl(workspaceGatewayUrl,"workspaceGatewayUrl")}catch(err){return set.status=400,{success:!1,state:getDaemonProfile().getBootState(),error:err instanceof Error?err.message:String(err)}}{let ctx=currentProfileOrNull()??getDaemonProfile();try{await writeAgentConfigAwaitSecrets({clientId,clientSecret,workspaceId,organizationId:body.organizationId,globalGatewayUrl:safeGlobalGatewayUrl,workspaceGatewayUrl:safeWorkspaceGatewayUrl,agentRecordId:body.agentRecordId,scopes:body.scopes},{dir:ctx.dataDir,scope:ctx.name})}catch(err){return set.status=500,{success:!1,state:getDaemonProfile().getBootState(),error:`Failed to persist gateway credentials to secrets backend: ${err instanceof Error?err.message:String(err)}`}}}let state=getDaemonProfile().getBootState();if(state==="ready"){let db=getDb();if(db){if(await db.setConfig("gateway-auth:clientId",clientId),await db.setConfig("gateway-auth:clientSecret",clientSecret),await db.setConfig("gateway-auth:workspaceId",workspaceId),body.organizationId)await db.setConfig("gateway-auth:organizationId",body.organizationId);if(await db.setConfig("gateway-auth:globalGatewayUrl",safeGlobalGatewayUrl),await db.setConfig("gateway-auth:workspaceGatewayUrl",safeWorkspaceGatewayUrl),body.agentRecordId)await db.setConfig("gateway-auth:agentRecordId",body.agentRecordId)}return gatewayClient.configure({globalGatewayUrl:safeGlobalGatewayUrl,workspaceGatewayUrl:safeWorkspaceGatewayUrl,clientId,clientSecret,workspaceId,organizationId:body.organizationId}),getDaemonProfile().logger.info("preconfig","Gateway credentials re-configured (agent was already ready)"),{success:!0,state,message:"Gateway auth re-configured"}}return getDaemonProfile().logger.info("preconfig","Gateway credentials received \u2014 beginning finalize (background)"),invalidatePairingToken(),runFinalize({clientId,clientSecret,workspaceId,organizationId:body.organizationId,globalGatewayUrl:safeGlobalGatewayUrl,workspaceGatewayUrl:safeWorkspaceGatewayUrl},{agentRecordId:body.agentRecordId,scopes:body.scopes}).catch((err)=>{getDaemonProfile().logger.error("preconfig","Background finalize threw",{error:err instanceof Error?err.message:String(err)})}),set.status=202,{success:!0,state:getDaemonProfile().getBootState(),agentRecordId:body.agentRecordId,message:"Gateway credentials accepted; finalize is running in the background. Poll /health/ready for completion."}},{body:t.Object({clientId:t.Optional(t.String()),clientSecret:t.Optional(t.String()),workspaceId:t.Optional(t.String()),organizationId:t.Optional(t.String()),globalGatewayUrl:t.Optional(t.String()),workspaceGatewayUrl:t.Optional(t.String()),scopes:t.Optional(t.Array(t.String())),agentRecordId:t.Optional(t.String())})})}import{existsSync as existsSync2,mkdirSync as mkdirSync2,rmSync,readdirSync}from"fs";import{join as join3}from"path";function profileDir(name){return join3(getVibecontrolsProductDir(),"agents",validateAgentName(name))}function listProfileNames(){let dir=join3(getVibecontrolsProductDir(),"agents");if(!existsSync2(dir))return[];return readdirSync(dir,{withFileTypes:!0}).filter((entry)=>entry.isDirectory()).map((entry)=>entry.name).filter((name)=>/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(name))}function profileDataDir(name){return join3(getVibecontrolsProductDir(),"agents",validateAgentName(name))}function readConfigForProfile(name){return readAgentConfig({dir:profileDataDir(name)})}function writeConfigForProfile(name,cfg){return writeAgentConfig(cfg,{dir:profileDataDir(name),scope:validateAgentName(name)})}function summarize(name){let defaultName=getDefaultProfile(),instance=getInstances().find((p)=>p.name===name),ctx=profileRegistry.get(name),summary={name,isDefault:name===defaultName,isRunning:instance?.status==="running",attached:ctx!==void 0,bootState:ctx?ctx.getBootState():null,dataDir:ctx?ctx.dataDir:null};if(instance)summary.port=instance.port,summary.pid=instance.pid,summary.startTime=instance.startTime;if(existsSync2(profileDir(name)))summary.config=redactUnknownSecrets(readConfigForProfile(name));return summary}function createProfileManagementRoutes(deps={}){let sm=deps.serviceManagerFactory?deps.serviceManagerFactory():new ServiceManager;return new Elysia({prefix:"/api/profiles"}).get("/",()=>{let onDisk=listProfileNames(),defaultName=getDefaultProfile(),names=new Set(onDisk);return names.add(defaultName),[...names].sort().map((n)=>summarize(n))}).post("/",async({body,set})=>{try{let name=validateAgentName(body.name),dir=profileDir(name);if(existsSync2(dir))return set.status=409,{error:"exists",message:`Profile '${name}' already exists.`};let seed;if(body.copyFrom){let src=validateAgentName(body.copyFrom);if(!existsSync2(profileDir(src)))return set.status=400,{error:"copy-source-missing",message:`Profile '${src}' does not exist.`};seed=readConfigForProfile(src),delete seed["static-api-key"],delete seed.agentRecordId,delete seed.apiKeys}else seed=getAgentConfigSeed();if(body.gatewayUrl)seed.globalGatewayUrl=body.gatewayUrl;if(body.workspaceGatewayUrl)seed.workspaceGatewayUrl=body.workspaceGatewayUrl;if(body.clientId)seed.clientId=body.clientId;if(body.clientSecret)seed.clientSecret=body.clientSecret;if(body.workspaceId)seed.workspaceId=body.workspaceId;if(body.organizationId)seed.organizationId=body.organizationId;mkdirSync2(dir,{recursive:!0}),writeConfigForProfile(name,seed);try{getOrCreateProfile(name)}catch(err){getDaemonProfile().logger.warn("profile-mgmt",`In-process attach failed for '${name}'`,{error:String(err)})}if(getDaemonProfile().logger.info("profile-mgmt",`Created profile '${name}' at ${dir}`),body.start){let startCfg={name,port:body.port??0,daemon:!0,dbPath:getProfileDataDir(),profile:name};await sm.startDaemon(startCfg)}return set.status=201,summarize(name)}catch(err){return set.status=400,{error:"create-failed",message:err instanceof Error?err.message:String(err)}}},{body:t.Object({name:t.String(),gatewayUrl:t.Optional(t.String()),workspaceGatewayUrl:t.Optional(t.String()),clientId:t.Optional(t.String()),clientSecret:t.Optional(t.String()),workspaceId:t.Optional(t.String()),organizationId:t.Optional(t.String()),copyFrom:t.Optional(t.String()),start:t.Optional(t.Boolean()),port:t.Optional(t.Number())})}).get("/:name",({params,set})=>{try{let name=validateAgentName(params.name);if(!existsSync2(profileDir(name)))return set.status=404,{error:"not-found",message:`No profile '${name}'.`};return summarize(name)}catch(err){return set.status=400,{error:"bad-request",message:err instanceof Error?err.message:String(err)}}},{params:t.Object({name:t.String()})}).put("/:name",({params,body,set})=>{try{let name=validateAgentName(params.name);if(!existsSync2(profileDir(name)))return set.status=404,{error:"not-found",message:`No profile '${name}'.`};let forbidden=["static-api-key","apiKeys","agentRecordId"];for(let key of forbidden)if(key in body)return set.status=400,{error:"forbidden-field",message:`Field '${key}' is managed via dedicated commands (vibe key rotate / vibe profile create). It cannot be patched here.`};let next={...readConfigForProfile(name),...body};return writeConfigForProfile(name,next),summarize(name)}catch(err){return set.status=400,{error:"update-failed",message:err instanceof Error?err.message:String(err)}}},{params:t.Object({name:t.String()}),body:t.Record(t.String(),t.Any())}).delete("/:name",async({params,body,query,set})=>{try{let name=validateAgentName(params.name);if(name===getDefaultProfile())return set.status=409,{error:"is-default",message:`Cannot delete active default profile '${name}'. Switch to another profile first.`};let purge=query?.purge==="true"||query?.purge==="1",hasDir=existsSync2(profileDir(name)),inRegistry=profileRegistry.has(name);if(!hasDir&&!inRegistry)return set.status=404,{error:"not-found",message:`No profile '${name}'.`};if(hasDir&&!purge&&!body?.confirm)return set.status=400,{error:"confirm-required",message:"Pass { confirm: true } in the body or `?purge=true` in the query to delete the on-disk dataDir (destructive)."};try{await sm.stop(name)}catch{}try{await profileRegistry.destroy(name)}catch(err){getDaemonProfile().logger.warn("profile-mgmt",`In-process detach failed for '${name}'`,{error:String(err)})}if(hasDir)if(body?.keepConfig)for(let entry of readdirSync(profileDir(name))){if(entry==="config.json")continue;rmSync(join3(profileDir(name),entry),{recursive:!0,force:!0})}else rmSync(profileDir(name),{recursive:!0,force:!0});return getDaemonProfile().logger.info("profile-mgmt",`Deleted profile '${name}'`),{ok:!0,deleted:name,keptConfig:!!body?.keepConfig,detached:inRegistry,purged:hasDir}}catch(err){return set.status=400,{error:"delete-failed",message:err instanceof Error?err.message:String(err)}}},{params:t.Object({name:t.String()}),query:t.Optional(t.Object({purge:t.Optional(t.String())})),body:t.Optional(t.Object({confirm:t.Optional(t.Boolean()),keepConfig:t.Optional(t.Boolean())}))}).post("/:name/switch",({params,set})=>{try{let name=validateAgentName(params.name);if(!existsSync2(profileDir(name)))return set.status=404,{error:"not-found",message:`No profile '${name}'.`};return setDefaultProfile(name),getDaemonProfile().logger.info("profile-mgmt",`Default profile switched to '${name}'`),{ok:!0,defaultProfile:name}}catch(err){return set.status=400,{error:"switch-failed",message:err instanceof Error?err.message:String(err)}}},{params:t.Object({name:t.String()})}).post("/:name/start",async({params,body,set})=>{try{let name=validateAgentName(params.name);if(!existsSync2(profileDir(name)))return set.status=404,{error:"not-found",message:`No profile '${name}'.`};try{getOrCreateProfile(name)}catch(err){getDaemonProfile().logger.warn("profile-mgmt",`In-process attach failed for '${name}'`,{error:String(err)})}if(!getInstances().some((p)=>p.name===name&&p.status==="running")){let startCfg={name,port:body?.port??0,daemon:!0,dbPath:getProfileDataDir(),profile:name};await sm.startDaemon(startCfg)}return summarize(name)}catch(err){return set.status=500,{error:"start-failed",message:err instanceof Error?err.message:String(err)}}},{params:t.Object({name:t.String()}),body:t.Optional(t.Object({port:t.Optional(t.Number())}))}).post("/:name/stop",async({params,set})=>{try{let name=validateAgentName(params.name);try{await sm.stop(name)}catch{}try{await profileRegistry.destroy(name)}catch(err){getDaemonProfile().logger.warn("profile-mgmt",`In-process detach failed for '${name}'`,{error:String(err)})}return summarize(name)}catch(err){return set.status=500,{error:"stop-failed",message:err instanceof Error?err.message:String(err)}}},{params:t.Object({name:t.String()})})}function buildProfileStats(){let rss=process.memoryUsage(),ru=process.resourceUsage(),totalCpuUserMs=ru.userCPUTime/1000,totalCpuSystemMs=ru.systemCPUTime/1000,totalCpuMs=totalCpuUserMs+totalCpuSystemMs,profiles=profileRegistry.list().map((ctx)=>{let childPidCount;try{childPidCount=listTrackedByOwner(ctx.spawnOwnerKey).length}catch{childPidCount=0}return{name:ctx.name,status:ctx.getBootState(),childPidCount,cpuMs:totalCpuMs,heapBytes:rss.heapUsed,dataDir:ctx.dataDir}});return{process:{pid:process.pid,uptimeSeconds:process.uptime(),cpuUserMs:totalCpuUserMs,cpuSystemMs:totalCpuSystemMs,heapUsedBytes:rss.heapUsed,heapTotalBytes:rss.heapTotal,rssBytes:rss.rss},profiles,notes:{perProfileCpu:"deferred",perProfileHeap:"deferred"}}}function createProfileStatsRoutes(){return new Elysia({prefix:"/api/profile-stats"}).get("/",()=>buildProfileStats())}function withTimeout(p,ms){return Promise.race([p,new Promise((_,reject)=>setTimeout(()=>reject(Error(`timeout after ${ms}ms`)),ms))])}function isEnoent(err){let msg=err instanceof Error?err.message:String(err);return/ENOENT/.test(msg)||/no such file or directory/i.test(msg)}async function runDbProbe(db){let probeKey=`__health__:probe:${typeof crypto<"u"&&typeof crypto.randomUUID==="function"?crypto.randomUUID():`${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`}`,value=String(Date.now());if(await withTimeout(db.setConfig(probeKey,value),2000),await withTimeout(db.getConfig(probeKey),2000)!==value)throw Error("round-trip mismatch");try{await withTimeout(db.deleteConfig(probeKey),500)}catch{}}async function checkDb(db,dbPath){if(!db)return{ok:!1,message:"database not opened"};let start=performance.now();try{return await runDbProbe(db),{ok:!0,durationMs:performance.now()-start}}catch(err){if(dbPath&&isEnoent(err))try{return(await import("fs")).mkdirSync(dbPath,{recursive:!0}),await runDbProbe(db),{ok:!0,message:`recovered: dbPath ${dbPath} was missing \u2014 recreated`,durationMs:performance.now()-start}}catch(retryErr){return{ok:!1,message:`ENOENT on dbPath ${dbPath}: ${retryErr instanceof Error?retryErr.message:String(retryErr)}`,durationMs:performance.now()-start}}return{ok:!1,message:err instanceof Error?err.message:String(err),durationMs:performance.now()-start}}}function checkProvider(registry,type){if(!registry)return{ok:!1,message:"no service registry"};let awaiting=getDaemonProfile().getBootState()==="awaiting-config";if(type==="tunnel"){let p=registry.getProvider("tunnel");if(!p&&process.env.AGENT_TUNNEL==="false")return{ok:!0,message:"tunnel disabled via AGENT_TUNNEL=false"};if(p)return{ok:!0,message:`provider: ${p.name}`};return{ok:!1,message:awaiting?"agent is awaiting-config \u2014 POST OAuth credentials to /api/agent/gateway-auth to register tunnel provider":"no tunnel provider registered"}}if(type==="session"){let p=registry.getProvider("session");if(p)return{ok:!0,message:`provider: ${p.name}`};return{ok:!1,message:awaiting?"agent is awaiting-config \u2014 POST OAuth credentials to /api/agent/gateway-auth to register session provider":"no session provider registered"}}return{ok:!0}}async function checkPluginHealth(pm){if(!pm)return{};let results={};for(let plugin of pm.getAllPlugins()){let fn=plugin.getHealth;if(typeof fn!=="function")continue;let start=performance.now();try{let out=await withTimeout(Promise.resolve(fn.call(plugin)),2000);results[plugin.name]={ok:out?.ok!==!1,message:out?.message,durationMs:performance.now()-start}}catch(err){results[plugin.name]={ok:!1,message:err instanceof Error?err.message:String(err),durationMs:performance.now()-start}}}return results}function createHealthRoutes(depsOrRegistry){let deps=depsOrRegistry&&"serviceRegistry"in depsOrRegistry?depsOrRegistry:{serviceRegistry:depsOrRegistry};return new Elysia({prefix:"/health"}).get("/",()=>{return{status:"ok",lifecycleState:deps.serviceRegistry?.getService("agent","lifecycle")?.getState()??"running",bootState:getDaemonProfile().getBootState(),timestamp:new Date().toISOString(),uptime:process.uptime()}}).get("/live",()=>({status:"ok"})).get("/ready",async({set})=>{let lifecycleState=deps.serviceRegistry?.getService("agent","lifecycle")?.getState()??"running",bootState=getDaemonProfile().getBootState(),components={};components.boot={ok:bootState==="ready",message:bootState==="ready"?void 0:`boot state ${bootState}`},components.lifecycle={ok:lifecycleState==="running",message:lifecycleState==="running"?void 0:`lifecycle ${lifecycleState}`},components.db=await checkDb(deps.getDb?.()??null,deps.getDbPath?.()??null),components.tunnel=checkProvider(deps.serviceRegistry,"tunnel"),components.session=checkProvider(deps.serviceRegistry,"session");let plugins=await checkPluginHealth(deps.getPluginManager?.()??null),allOk=Object.values(components).every((r)=>r.ok)&&Object.values(plugins).every((r)=>r.ok);if(!allOk)set.status=503;let reasons=bootState==="degraded"?getDaemonProfile().getDegradedReasons():[],daemonName=getDaemonProfile().name,profilesMap={};for(let ctx of profileRegistry.list())profilesMap[ctx.name]={bootState:ctx.getBootState(),ok:ctx.getBootState()==="ready",degradedReasons:ctx.getDegradedReasons()};let lastFinalizeError=getDaemonProfile().getLastFinalizeError(),body={status:allOk?"ok":"degraded",lifecycleState,bootState,daemon:{profile:daemonName,bootState,ok:bootState==="ready"},profiles:profilesMap,components,plugins,degradedReasons:reasons,lastFinalizeError,timestamp:new Date().toISOString()};if(!allOk)getDaemonProfile().logger.warn("health","Readiness probe failed",{components,plugins,bootState});return body})}var inflight=0,totalServed=0;function createInflightTracker(){return new Elysia({name:"inflight-tracker"}).onRequest(()=>{inflight+=1}).onAfterResponse(()=>{inflight=Math.max(0,inflight-1),totalServed+=1})}function createStatsRoutes(){return new Elysia({prefix:"/api/stats"}).get("/inflight",()=>({inflight:Math.max(0,inflight-1),totalServed}))}var ALLOWED_COMMANDS=Object.freeze(["code","code-insiders","codium","cursor","idea","pycharm","webstorm","goland","phpstorm","rubymine","clion","rider","zed","subl","vim","nvim","emacs","neovide","fleet","helix"]),ALLOWED_SET=new Set(ALLOWED_COMMANDS),ALLOWED_ARG_FLAGS=new Set(["--new-window","-n","--reuse-window","-r","--wait","-w","--add","--goto"]);function which(cmd){try{return Bun.which(cmd)??null}catch{return null}}function createEditorRoutes(){return new Elysia({prefix:"/api/editor"}).get("/allowlist",()=>({commands:[...ALLOWED_COMMANDS]})).get("/detect",async()=>{let results=ALLOWED_COMMANDS.map((cmd)=>[cmd,which(cmd)]),available=[],paths={};for(let[cmd,p]of results)if(p)available.push(cmd),paths[cmd]=p;return{available,paths}}).post("/open",async({body,set})=>{let{command,path:rawPath,args=[]}=body;if(!ALLOWED_SET.has(command))return set.status=400,{ok:!1,error:`Command '${command}' is not in the IDE allowlist`};for(let a of args)if(typeof a!=="string"||!ALLOWED_ARG_FLAGS.has(a))return set.status=400,{ok:!1,error:`Argument '${a}' is not in the flag allowlist`};let resolvedPath;try{resolvedPath=(await resolveSafePath(rawPath,{mustExist:!0})).realPath}catch(err){return set.status=400,{ok:!1,error:`Invalid path: ${err instanceof Error?err.message:String(err)}`}}let resolvedCmd=which(command);if(!resolvedCmd)return set.status=404,{ok:!1,error:`'${command}' is not installed or not on PATH on this agent`};try{let child=spawnTracked({owner:`editor:${command}`,cmd:[resolvedCmd,...args,resolvedPath],env:process.env,stdout:"ignore",stderr:"ignore",stdin:"ignore",meta:{command,path:resolvedPath}});return getDaemonProfile().logger.info("editor",`Launched ${command} on ${resolvedPath}`,{pid:child.pid}),getDaemonProfile().audit.emit("agent","editor.open",{command,path:resolvedPath,pid:child.pid}),{ok:!0,command,resolvedPath,pid:child.pid}}catch(err){return set.status=500,{ok:!1,error:`Failed to spawn editor: ${err instanceof Error?err.message:String(err)}`}}},{body:t.Object({command:t.String({minLength:1,maxLength:40}),path:t.String({minLength:1,maxLength:4096}),args:t.Optional(t.Array(t.String({maxLength:32})))})})}var REGISTRY_KEY=Symbol.for("@vibecontrols/plugin-sdk:contextProviders@1");function getRegistry(){let slots=globalThis,existing=slots[REGISTRY_KEY];if(existing)return existing;let created=new Map;return slots[REGISTRY_KEY]=created,created}function listContextProviders(){return Array.from(getRegistry().values())}function safeHost(maybeUrl){if(!maybeUrl)return null;try{return new URL(maybeUrl).host}catch{return null}}async function buildAgentSelfContext(deps,args){let pm=deps.getPluginManager(),loadedPlugins=pm?pm.getPluginDetails().map((p)=>({pluginName:p.pluginName,packageName:p.packageName,version:p.version,tags:p.tags??[]})):[],mem=process.memoryUsage(),tunnelHost=safeHost(deps.getTunnelHost?.()??null);return{pluginName:"agent",description:"vibecontrols-agent runtime self-report",generatedAt:new Date().toISOString(),data:{profile:args.profile,vibeId:args.vibeId??null,runtime:{bunVersion:typeof Bun<"u"?Bun.version:null,nodeVersion:process.versions.node??null,platform:process.platform,arch:process.arch,pid:process.pid,uptimeSeconds:Math.round(process.uptime()),memory:{rssMB:Math.round(mem.rss/1048576),heapUsedMB:Math.round(mem.heapUsed/1048576)}},agent:{version:deps.getAgentVersion?.()??null,profileRegistered:getVibecontrolsProfile(),tunnelHost},plugins:{count:loadedPlugins.length,items:loadedPlugins}}}}var DEFAULT_PROVIDER_TIMEOUT_MS=2000,SINGLE_FLIGHT_TTL_MS=1000;async function withTimeout2(promise,timeoutMs){let timer,timeout=new Promise((_,reject)=>{timer=setTimeout(()=>reject(Error(`timeout after ${timeoutMs}ms`)),timeoutMs)});try{return await Promise.race([promise,timeout])}finally{if(timer)clearTimeout(timer)}}async function runOne(provider,args){let start=performance.now(),timeoutMs=provider.timeoutMs??DEFAULT_PROVIDER_TIMEOUT_MS;try{let data=await withTimeout2(provider.getContext(args),timeoutMs);if(!data.generatedAt)data.generatedAt=new Date().toISOString();return{ok:!0,data,durationMs:Math.round(performance.now()-start)}}catch(err){return{ok:!1,error:err.message??String(err),durationMs:Math.round(performance.now()-start)}}}class ContextAggregator{deps;inflight=new Map;constructor(deps){this.deps=deps}async aggregate(args){let key=`${args.profile}::${args.vibeId??""}`,existing=this.inflight.get(key);if(existing&&Date.now()-existing.ts<SINGLE_FLIGHT_TTL_MS)return existing.promise;let promise=this.doAggregate(args).finally(()=>{setTimeout(()=>{let entry=this.inflight.get(key);if(entry&&entry.promise===promise)this.inflight.delete(key)},SINGLE_FLIGHT_TTL_MS).unref?.()});return this.inflight.set(key,{ts:Date.now(),promise}),promise}async selfContext(args){return buildAgentSelfContext(this.deps,args)}async pluginContext(name,args){let provider=listContextProviders().find((p)=>p.name===name);if(!provider)return null;return runOne(provider,args)}async pluginsContext(args){let providers=listContextProviders(),settled=await Promise.allSettled(providers.map((p)=>runOne(p,args))),out={};return providers.forEach((p,i)=>{let r=settled[i];if(r&&r.status==="fulfilled")out[p.name]=r.value;else if(r&&r.status==="rejected")out[p.name]={ok:!1,error:r.reason instanceof Error?r.reason.message:String(r.reason),durationMs:0}}),out}async doAggregate(args){let[agent,plugins]=await Promise.all([this.selfContext(args),this.pluginsContext(args)]);return{agent,plugins}}}function parseVibeId(query){let raw=query.vibeId;if(typeof raw!=="string")return;let v=raw.trim();return v.length>0&&v.length<=128?v:void 0}function createContextRoutes(deps){let aggregator=new ContextAggregator(deps);return new Elysia({prefix:"/api/agent/context"}).get("/",async({params,query})=>{let profile=params?.profile??"default",vibeId=parseVibeId(query);return aggregator.aggregate({profile,vibeId})},{query:t.Object({vibeId:t.Optional(t.String())})}).get("/agent",async({params,query})=>{let profile=params?.profile??"default",vibeId=parseVibeId(query);return aggregator.selfContext({profile,vibeId})},{query:t.Object({vibeId:t.Optional(t.String())})}).get("/plugins",async({params,query})=>{let profile=params?.profile??"default",vibeId=parseVibeId(query);return aggregator.pluginsContext({profile,vibeId})},{query:t.Object({vibeId:t.Optional(t.String())})}).get("/plugins/:name",async({params,query,set})=>{let profile=params?.profile??"default",name=params?.name;if(!name)return set.status=400,{error:"missing plugin name"};let vibeId=parseVibeId(query),entry=await aggregator.pluginContext(name,{profile,vibeId});if(!entry)return set.status=404,{error:`no context provider registered under name "${name}"`};return entry},{params:t.Object({name:t.String()}),query:t.Object({vibeId:t.Optional(t.String())})})}var FINALIZE_EXEMPT_PREFIXES=["/health","/api/agent/status","/api/agent/version","/api/agent/identity","/api/agent/api-key","/api/agent/tunnel","/api/agent/system","/api/agent/gateway-auth","/api/stats","/metrics","/api/profiles","/api/profile-stats"];function isFinalizeExempt(path){return FINALIZE_EXEMPT_PREFIXES.some((p)=>path.startsWith(p))}var UUID_RE=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function normalizeRouteLabel(path){return path.split("/").map((seg)=>{if(!seg)return seg;if(/^\d+$/.test(seg))return":id";if(UUID_RE.test(seg))return":id";if(seg.length>=24&&/^[A-Za-z0-9_-]+$/.test(seg))return":id";return seg}).join("/")}async function createApp(options){let{port,host,dbPath,logLevel,corsOrigin}=options,effectiveDbPath=dbPath??getProfileDataDir();try{(await import("fs")).mkdirSync(effectiveDbPath,{recursive:!0})}catch(err){throw getDaemonProfile().logger.error("app","Failed to create dbPath dir at boot",{dbPath:effectiveDbPath,error:String(err)}),Error(`Cannot create dbPath ${effectiveDbPath}: ${err instanceof Error?err.message:String(err)}`,{cause:err})}if(logLevel)getDaemonProfile().logger.setLevel(logLevel);(async()=>{let{logShipper}=await import("./log-shipper-9rtt4y1s.js");logShipper.init()})(),(async()=>{let version=await getPackageVersion();await getMetricsRegistry({version,profile:getVibecontrolsProfile()})})();try{let{checkDependencies}=await import("./bootstrap.service-fknk5beq.js"),deps=checkDependencies(),missingRequired=deps.filter((d)=>d.required&&!d.installed),missingOptional=deps.filter((d)=>!d.required&&!d.installed);if(missingRequired.length>0)getDaemonProfile().logger.error("app",`Missing required system deps: ${missingRequired.map((d)=>d.name).join(", ")}. Run \`vibe setup\` to install.`);if(missingOptional.length>0)getDaemonProfile().logger.warn("app",`Missing optional system deps: ${missingOptional.map((d)=>d.name).join(", ")}. Some plugins may fail their prereqs check.`)}catch(err){getDaemonProfile().logger.warn("app","Boot-time dependency check failed",{error:String(err)})}try{getDaemonProfile().audit.runRetention()}catch(err){getDaemonProfile().logger.warn("app","Audit-log retention sweep failed",{error:String(err)})}let serviceRegistry=new ServiceRegistry;startBootstrapTunnel(serviceRegistry,{port});let CORS_METHODS="GET, POST, PUT, PATCH, DELETE, OPTIONS",CORS_HEADERS="Content-Type, x-agent-api-key, Authorization, x-requested-with",configuredCorsOrigins=Array.isArray(corsOrigin)?corsOrigin:(corsOrigin??"").split(",").map((origin)=>origin.trim()).filter(Boolean),trustedProductionOrigins=new Set(["https://vibecontrols.com","https://app.vibecontrols.com","https://alphaapp.vibecontrols.com","https://burdenoff.com","https://app.burdenoff.com","https://alphaapp.burdenoff.com"]),isAllowedOrigin=(origin)=>{try{let url=new URL(origin);if(configuredCorsOrigins.includes(origin))return!0;if(configuredCorsOrigins.includes("*"))return!1;return url.hostname==="localhost"||url.hostname==="127.0.0.1"||url.hostname==="0.0.0.0"||url.hostname.endsWith(".local.burdenoff.com")||trustedProductionOrigins.has(url.origin)}catch{return!1}},db=null,pluginManager=null,hostServices=null,lifecycle=null,pluginPublicPaths=()=>[],pluginRoutesApp=null,uiServerApp=null,finalizeInFlight=null,SHUTDOWN_PHASE_MS=5000,runPhase=async(name,fn)=>{let started=Date.now();try{await Promise.race([Promise.resolve(fn()),new Promise((_,reject)=>setTimeout(()=>reject(Error(`shutdown phase ${name} exceeded ${SHUTDOWN_PHASE_MS}ms`)),SHUTDOWN_PHASE_MS))]),getDaemonProfile().logger.info("app",`shutdown.phase ${name} complete`,{ms:Date.now()-started})}catch(err){getDaemonProfile().logger.warn("app",`shutdown.phase ${name} failed`,{error:String(err),ms:Date.now()-started})}},stopFn=async(context)=>{if(getDaemonProfile().logger.info("app","Agent shutdown starting",{reason:context?.reason??"shutdown"}),await runPhase("plugins",async()=>{if(pluginManager)await pluginManager.dispatchServerStop(context)}),await runPhase("bootstrap-tunnel",()=>stopBootstrapTunnel()),await runPhase("tracked-subprocesses",async()=>{let{killAllTracked}=await import("./subprocess-vks78xmn.js");await killAllTracked()}),context?.reason!=="reload")await runPhase("db-close",async()=>{if(db)await db.close()});getDaemonProfile().logger.close(),getDaemonProfile().logger.info("app","Agent server stopped")},finalize=async(creds,opts)=>{if(getDaemonProfile().getBootState()==="ready")return{ok:!0};if(finalizeInFlight)return finalizeInFlight;return finalizeInFlight=(async()=>{getDaemonProfile().setBootState("initializing");try{let safeCreds={...creds,globalGatewayUrl:assertAllowedGatewayUrl(creds.globalGatewayUrl,"globalGatewayUrl"),workspaceGatewayUrl:assertAllowedGatewayUrl(creds.workspaceGatewayUrl,"workspaceGatewayUrl")},encryptionKey=await fetchEncryptionKey(safeCreds),resolvedDbPath=effectiveDbPath,cfgForStorage=readAgentConfig({dir:getDaemonProfile().dataDir}),storageAdapterName=cfgForStorage.storageAdapter??process.env.VIBE_STORAGE_ADAPTER??void 0,storageAdapterOptions=cfgForStorage.storageOptions;try{db=await createAgentDatabase({dbPath:resolvedDbPath,encryptionKey,adapterName:storageAdapterName,adapterOptions:storageAdapterOptions})}catch(openErr){let message=openErr instanceof Error?openErr.message:String(openErr);getDaemonProfile().logger.error("app","Storage open failed; quarantining and retrying once",{error:message,path:resolvedDbPath});try{let fs=await import("fs");if(fs.existsSync(resolvedDbPath)){let ts=new Date().toISOString().replace(/[:.]/g,"-"),broken=`${resolvedDbPath}.broken-${ts}`;fs.renameSync(resolvedDbPath,broken),getDaemonProfile().logger.warn("app",`Quarantined storage to ${broken} \u2014 fresh DB will be created`)}db=await createAgentDatabase({dbPath:resolvedDbPath,encryptionKey,adapterName:storageAdapterName,adapterOptions:storageAdapterOptions})}catch(retryErr){let retryMsg=retryErr instanceof Error?retryErr.message:String(retryErr);throw getDaemonProfile().recordDegradedReason("storage",retryMsg),Error(`Storage open failed twice; agent is degraded: ${retryMsg}`,{cause:retryErr})}}if(await writeAgentConfigAwaitSecrets({clientId:safeCreds.clientId,clientSecret:safeCreds.clientSecret,workspaceId:safeCreds.workspaceId,organizationId:safeCreds.organizationId,globalGatewayUrl:safeCreds.globalGatewayUrl,workspaceGatewayUrl:safeCreds.workspaceGatewayUrl,agentRecordId:opts?.agentRecordId,scopes:opts?.scopes},{dir:getDaemonProfile().dataDir,scope:getDaemonProfile().name}),await db.setConfig("gateway-auth:clientId",safeCreds.clientId),await db.setConfig("gateway-auth:clientSecret",safeCreds.clientSecret),await db.setConfig("gateway-auth:globalGatewayUrl",safeCreds.globalGatewayUrl),await db.setConfig("gateway-auth:workspaceGatewayUrl",safeCreds.workspaceGatewayUrl),await db.setConfig("gateway-auth:workspaceId",safeCreds.workspaceId),safeCreds.organizationId)await db.setConfig("gateway-auth:organizationId",safeCreds.organizationId);if(opts?.agentRecordId)await db.setConfig("gateway-auth:agentRecordId",opts.agentRecordId);serviceRegistry.db=db,await serviceRegistry.hydrateDefaultsFromDb(),pluginManager=new PluginManager(db),await pluginManager.loadCorePlugins();try{await pluginManager.loadAll()}catch(err){getDaemonProfile().logger.warn("app","Failed to load some external plugins",{error:String(err)})}let autoInstallDisabled=process.env.VIBE_SKIP_AUTO_INSTALL==="1"||await db.getConfig("plugins:auto-install-disabled");if(autoInstallDisabled!=="true"&&autoInstallDisabled!==!0)try{let installed=await pluginManager.ensureDefaultPlugins((message)=>getDaemonProfile().logger.info("app",`[auto-install] ${message}`));if(installed.length>0)getDaemonProfile().logger.info("app",`Auto-installed ${installed.length} default plugin(s): ${installed.map((p)=>p.packageName).join(", ")}`)}catch(err){getDaemonProfile().logger.warn("app","Failed to auto-install default plugins",{error:String(err)})}getDaemonProfile().logger.info("app",`Plugins loaded: ${pluginManager.getPluginDetails().length} total (${pluginManager.getPluginDetails().filter((p)=>p.isCore).length} core)`);try{let details=pluginManager.getPluginDetails(),byStatus={loaded:details.filter((p)=>p.loaded).length,failed:details.filter((p)=>!p.loaded).length};setPluginsLoaded(byStatus)}catch{}let storageProvider={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)}},packageVersion=await getPackageVersion();hostServices={storage:storageProvider,logger:getDaemonProfile().logger,serviceRegistry,getProvider:(type)=>serviceRegistry.getProvider(type),getAgentBaseUrl:()=>process.env.AGENT_URL||`http://localhost:${port}`,getAgentVersion:()=>packageVersion,validateApiKey:(key)=>isValidAgentApiKey(key),setCodeServerSessionValidator:(fn)=>{codeServerSessionValidator=fn},broadcast,workspaceQuery:async(query,variables)=>gatewayClient.workspaceQuery(query,variables),isGatewayConfigured:()=>gatewayClient.isConfigured(),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:()=>getPluginRegistry(),getDataDir:()=>getVibecontrolsDir(),cliContributors:new CliContributorRegistry,audit:{emit:(event,payload)=>getDaemonProfile().audit.emit("agent",event,payload??{})},telemetry:{emit:(event,payload)=>{import("./telemetry-rew0mtj2.js").then(({telemetryService})=>telemetryService.emit(event,payload??{})).catch(()=>{})}},os:getOsAdapter(),iframeBridge:createIframeBridge()},gatewayClient.configure({globalGatewayUrl:safeCreds.globalGatewayUrl,workspaceGatewayUrl:safeCreds.workspaceGatewayUrl,clientId:safeCreds.clientId,clientSecret:safeCreds.clientSecret,workspaceId:safeCreds.workspaceId,organizationId:safeCreds.organizationId});let routeDeps={db,serviceRegistry,pluginManager,broadcast,hostServices};routeDeps.app=app;let pluginRoutesAppInitialized=!1,rebuildPluginSurfaces=()=>{let{routes:pluginRoutes,getPublicPaths,mountPlugin}=createPluginRouter(pluginManager,routeDeps);if(routeDeps.mountPlugin=mountPlugin,pluginPublicPaths=getPublicPaths,markPluginPublicPathsDirty(),pluginRoutesApp=pluginRoutes,uiServerApp=createUIServer(pluginManager),pluginManager&&pluginRoutesAppInitialized&&hostServices)pluginManager.dispatchServerStart(pluginRoutesApp,hostServices).catch((err)=>getDaemonProfile().logger.warn("app","Re-dispatch of onServerStart after plugin reload failed",{error:String(err)}));pluginRoutesAppInitialized=!0};routeDeps.rebuildPluginSurfaces=rebuildPluginSurfaces,rebuildPluginSurfaces(),lifecycle=new LifecycleManager(serviceRegistry,pluginManager,db,app,hostServices,stopFn),serviceRegistry.registerService("agent","lifecycle",lifecycle),getDaemonProfile().attachServices({db,serviceRegistry,pluginManager,lifecycle,hostServices}),mountProfileRoutes(getDaemonProfile(),{rebuildPluginSurfaces,mountPlugin:routeDeps.mountPlugin});try{await getDaemonProfile().keyVault.bindApiKey(getAgentApiKey())}catch(err){getDaemonProfile().logger.warn("app","Failed to bind api key into daemon keyVault",{error:String(err)})}let criticalFailures=[];try{let{failures}=await pluginManager.dispatchServerStart(pluginRoutesApp,hostServices);for(let f of failures)if(isCriticalPlugin(f.plugin)||(f.packageName?isCriticalPlugin(f.packageName):!1))criticalFailures.push(f),getDaemonProfile().recordDegradedReason(f.plugin,f.error);else getDaemonProfile().logger.warn("app",`Non-critical plugin ${f.plugin} failed onServerStart; continuing`,{error:f.error})}catch(err){getDaemonProfile().logger.warn("app","Error during plugin onServerStart dispatch",{error:String(err)})}try{await pluginManager.dispatchServerReady(app,hostServices)}catch(err){getDaemonProfile().logger.warn("app","Error during plugin onServerReady dispatch",{error:String(err)})}if(getDaemonProfile().clearFinalizeError(),criticalFailures.length>0)getDaemonProfile().setBootState("degraded"),getDaemonProfile().logger.error("app","Agent finalized but degraded \u2014 critical plugins failed",{failures:criticalFailures.map((f)=>`${f.plugin}: ${f.error}`)});else getDaemonProfile().setBootState("ready"),getDaemonProfile().logger.info("app","Agent finalized \u2014 state=ready"),getDaemonProfile().audit.emit("agent","gateway-auth.configured",{workspaceId:safeCreds.workspaceId,organizationId:safeCreds.organizationId,agentRecordId:opts?.agentRecordId});return(async()=>{try{if(await pluginManager.provisionDefaultPrereqs(app,hostServices),getDaemonProfile().logger.info("app","Default provider prerequisites provisioned"),(serviceRegistry.listProvidersForType("tunnel")??[]).some((p)=>p.pluginName!=="bootstrap")){let{tryHandoverBootstrapTunnel}=await import("./tunnel-bootstrap-x82wcnt8.js");if(!tryHandoverBootstrapTunnel())stopBootstrapTunnel();serviceRegistry.unregisterProvider("tunnel","bootstrap"),getDaemonProfile().logger.info("app","Bootstrap tunnel handed over to the real tunnel provider")}}catch(err){getDaemonProfile().logger.warn("app","Plugin prerequisite provisioning failed",{error:String(err)})}})(),{ok:!0}}catch(err){getDaemonProfile().setBootState("awaiting-config");let msg=err instanceof Error?err.message:String(err);if(getDaemonProfile().recordFinalizeError(msg),getDaemonProfile().logger.error("app","Finalize failed",{error:msg}),process.env.VIBE_STRICT_KEY_FETCH==="1")getDaemonProfile().logger.error("app","VIBE_STRICT_KEY_FETCH=1 \u2192 aborting daemon (strict mode)",{error:msg}),setTimeout(()=>process.exit(1),50);return{ok:!1,error:msg}}finally{finalizeInFlight=null}})(),finalizeInFlight},corsPlugin=cors({origin:(request)=>{let origin=request.headers.get("origin");return!!origin&&isAllowedOrigin(origin)},credentials:!0,allowedHeaders:CORS_HEADERS.split(",").map((s)=>s.trim()),methods:CORS_METHODS.split(",").map((s)=>s.trim()),exposeHeaders:["content-type","content-length"],maxAge:86400,preflight:!0}),DEFAULT_MAX_BODY_BYTES=10485760,maxBodyEnv=process.env.VIBECONTROLS_MAX_BODY_BYTES,parsedMaxBody=maxBodyEnv?Number.parseInt(maxBodyEnv,10):NaN,maxBodySize=Number.isFinite(parsedMaxBody)&&parsedMaxBody>0?parsedMaxBody:DEFAULT_MAX_BODY_BYTES,appRef={current:null},app=new Elysia({serve:{maxRequestBodySize:maxBodySize}}).onRequest(({request,set})=>{let requestId=extractRequestId(request.headers)??generateRequestId();enterRequestContext({requestId,startedAt:new Date().toISOString()});let headers=set.headers??={};headers["X-Request-Id"]=requestId}).onRequest(({request})=>{try{let url=new URL(request.url).pathname,name=/^\/api\/profiles\/([^/]+)(?:\/|$)/.exec(url)?.[1],ctx=name?profileRegistry.get(name):null;enterProfileContext(ctx??getDaemonProfile())}catch{enterProfileContext(getDaemonProfile())}}).onRequest(({request,set})=>{let url=new URL(request.url).pathname;if(!url.startsWith("/api/"))return;if(url==="/api/profiles"||url.startsWith("/api/profiles/"))return;if(url==="/api/profile-stats"||url.startsWith("/api/profile-stats/"))return;let defaultProfileUrl=new URL(request.url);defaultProfileUrl.pathname=`/api/profiles/default${url.slice(4)}`;try{request.headers.set("x-vc-profile-rewrite","1"),request.headers.set("x-vc-profile-rewrite-target",defaultProfileUrl.pathname)}catch{}return}).derive(()=>({requestId:getRequestId()??generateRequestId()})).use(corsPlugin).use(rateLimitPlugin()).use(createAuthPlugin(()=>pluginPublicPaths())).use(idempotencyPlugin({getDb:()=>currentProfileOrNull()?.db??db})).onBeforeHandle(({request,set})=>{let state=getDaemonProfile().getBootState();if(state==="ready")return;let url=new URL(request.url).pathname;if(isFinalizeExempt(url))return;return set.status=503,{error:"Agent not yet configured",message:"Agent is in '"+state+"' state. POST credentials to /api/agent/gateway-auth to finalize.",state}}).onAfterHandle(({request,set})=>{let url=new URL(request.url).pathname,isNoisy=url==="/health"||url.startsWith("/api/logs/stream")||url.startsWith("/ui/")||url==="/ws/events"||url==="/api/sessions/health-check"||url.startsWith("/terminal/"),status=typeof set.status==="number"?set.status:200,level=isNoisy?"debug":status>=400?"warn":"info";getDaemonProfile().logger[level]("http",`${request.method} ${url} \u2192 ${status}`,{method:request.method,path:url,statusCode:status});try{recordHttpRequest(request.method,normalizeRouteLabel(url),status)}catch{}}).use(createHealthRoutes({serviceRegistry,getDb:()=>currentProfileOrNull()?.db??db,getDbPath:()=>effectiveDbPath,getPluginManager:()=>currentProfileOrNull()?.pluginManager??pluginManager})).use(createMetricsRoutes()).use(createPreConfigRoutes({serviceRegistry,runFinalize:(creds,opts)=>finalize(creds,opts),getDb:()=>currentProfileOrNull()?.db??db})).use(createInflightTracker()).use(createStatsRoutes()).use(createEditorRoutes()).use(createContextRoutes({getPluginManager:()=>currentProfileOrNull()?.pluginManager??pluginManager,getTunnelHost:()=>readTunnelState()?.url??null})).use(createProfileManagementRoutes()).use(createProfileStatsRoutes()).use(createEventsWs()).use(createLogWs()).use(createTerminalProxy(serviceRegistry)).ws("/code-server/*",buildCodeServerBridge(port)).all("/api/profiles/:name/*",async({params,request,set})=>{let hasReqBody=request.method!=="GET"&&request.method!=="HEAD",bodyBytes=hasReqBody?await request.arrayBuffer():void 0,dispatched=await dispatchProfileRequest(params.name,request,bodyBytes);if(dispatched&&dispatched.status!==404)return dispatched;let running=getVibecontrolsProfile(),requested=params.name;if(requested!==running)return set.status=404,{error:"profile-mismatch",running,requested,hint:"This daemon serves a different profile. Call GET /api/profiles to discover the right tunnel."};let u=new URL(request.url),stripped=u.pathname.replace(/^\/api\/profiles\/[^/]+/,"/api"),headers=new Headers(request.headers);headers.set("x-vc-profile-rewrite","1");let init={method:request.method,headers};if(hasReqBody&&bodyBytes!==void 0)init.body=bodyBytes;let rewritten=new Request(`${u.origin}${stripped}${u.search}`,init),target=appRef.current;if(!target)return new Response(JSON.stringify({error:"agent-not-ready"}),{status:503,headers:{"content-type":"application/json"}});return target.handle(rewritten)}).all("/api/*",async({request})=>{if(getDaemonProfile().getBootState()!=="ready"||!pluginRoutesApp)return new Response(JSON.stringify({error:"Agent not yet configured",state:getDaemonProfile().getBootState(),message:"Plugin routes are unavailable until the agent reaches state=ready. POST credentials to /api/agent/gateway-auth to finalize."}),{status:503,headers:{"content-type":"application/json"}});try{let apiUiUrl=new URL(request.url),apiUiMatch=/^\/api\/plugins\/([a-z0-9-]{1,64})\/ui(?:\/.*)?$/.exec(apiUiUrl.pathname);if(apiUiMatch&&request.method==="GET"){let plugin=apiUiMatch[1];if(isValidUiPluginName(plugin)){let restAfterUi=apiUiUrl.pathname.slice(`/api/plugins/${plugin}/ui`.length),isBareDoc=restAfterUi===""||restAfterUi==="/",looksLikeNavigation=request.headers.get("sec-fetch-mode")==="navigate";if(isBareDoc||looksLikeNavigation){let cookie=getUiCookieFromRequest(request,plugin);if(!cookie||!verifyUiCookieToken(cookie,plugin))return new Response(renderUiBootstrapHtml(plugin,"/api/profiles/default/agent/ui-exchange-plugin"),{status:200,headers:{"content-type":"text/html; charset=utf-8","Content-Security-Policy":"frame-ancestors 'self' http://localhost:* http://127.0.0.1:* https://localhost:* https://127.0.0.1:* https://*.local.burdenoff.com https://vibecontrols.com https://*.vibecontrols.com https://burdenoff.com https://app.burdenoff.com https://alphaapp.burdenoff.com"}})}}}}catch{}return pluginRoutesApp.handle(request)}).all("/ui/*",async({request})=>{if(getDaemonProfile().getBootState()!=="ready"||!uiServerApp)return new Response("Plugin UI not yet available",{status:503});return uiServerApp.handle(request)}).all("/code-server/*",async({request})=>{if(getDaemonProfile().getBootState()!=="ready"||!pluginRoutesApp)return new Response("code-server not yet available",{status:503});return pluginRoutesApp.handle(request)}).all("/plan/*",async({request})=>{if(getDaemonProfile().getBootState()!=="ready"||!pluginRoutesApp)return new Response("plan provider not yet available",{status:503});return pluginRoutesApp.handle(request)});return appRef.current=app,{app,async start(){app.listen({port,hostname:host}),getDaemonProfile().logger.info("app",`Agent server listening on ${host}:${port}`);try{let list=(process.env.VIBECONTROLS_PROFILES??"").split(",").map((s)=>s.trim()).filter(Boolean),bootName=getDaemonProfile().name,{getOrCreateProfile:getOrCreateProfile2}=await import("./daemon-profile-c7zt62gk.js"),{attachSecondaryProfile}=await import("./secondary-profile-attach-9c1rp4y7.js"),strict=process.env.VIBE_STRICT_KEY_FETCH==="1";for(let name of list){if(name===bootName)continue;try{let ctx=getOrCreateProfile2(name),result=await attachSecondaryProfile(ctx);if(result.ok)getDaemonProfile().logger.info("app",`Secondary profile '${name}' attached (db+services online)`);else if(strict)throw Error(`attachServices for secondary profile '${name}' failed: ${result.error}`);else ctx.recordDegradedReason("attach",result.error??"unknown"),getDaemonProfile().logger.warn("app",`Secondary profile '${name}' is degraded (no creds / attach failed)`,{error:result.error})}catch(err){if(strict)throw getDaemonProfile().logger.error("app",`--strict-key-fetch: secondary profile '${name}' attach failed; aborting`,{error:String(err)}),setTimeout(()=>process.exit(1),50),err;getDaemonProfile().logger.warn("app",`Failed to attach secondary profile '${name}'`,{error:String(err)})}}}catch{}return app},stop:stopFn,finalize,getState:()=>getDaemonProfile().getBootState(),getLifecycle:()=>currentProfileOrNull()?.lifecycle??lifecycle,getDb:()=>currentProfileOrNull()?.db??db,getServiceRegistry:()=>currentProfileOrNull()?.serviceRegistry??serviceRegistry,getPluginManager:()=>currentProfileOrNull()?.pluginManager??pluginManager,getHostServices:()=>currentProfileOrNull()?.hostServices??hostServices}}var codeServerSessionValidator=null;function getCookieValue(cookieHeader,name){if(!cookieHeader)return null;let m=cookieHeader.match(new RegExp(`(?:^|;\\s*)${name}=([^;]*)`));return m?m[1]:null}function buildCodeServerBridge(port){let payloadBytes=(payload)=>typeof payload==="string"?Buffer.byteLength(payload):payload.byteLength;return{open(ws){let wsData=ws.data,apiKey=wsData.query?.apiKey??getApiKeyFromHeaders(wsData.headers??{})??getApiKeyFromHeaders(wsData.request?Object.fromEntries(wsData.request.headers.entries()):{});if(!isValidAgentApiKey(apiKey)){let cookieHeader=wsData.headers?.cookie??wsData.request?.headers.get("cookie")??null,sessionToken=getCookieValue(cookieHeader,"__vibe_cs_session");if(!sessionToken||!codeServerSessionValidator?.(sessionToken)){ws.close(1008,"Unauthorized");return}}let bridgeProfile=getDaemonProfile().name;fetch(`http://127.0.0.1:${port}/api/profiles/${encodeURIComponent(bridgeProfile)}/code-server/status`,{headers:{"x-agent-api-key":getAgentApiKey()}}).then((r)=>r.json()).then((raw)=>{if(wsData._csClosed)return;let status=raw;if(!status.running||!status.port){ws.close(1011,"code-server not running");return}let requestUrl=wsData.request?.url??"/code-server/",upstreamPath;try{let url=new URL(requestUrl,`http://127.0.0.1:${status.port}`);upstreamPath=(url.pathname.replace(/^\/code-server\/?/,"/")||"/")+url.search}catch{upstreamPath="/"}let upstreamWs=new WebSocket(`ws://127.0.0.1:${status.port}${upstreamPath}`),state={upstream:upstreamWs,ready:!1,buffer:[],bufferBytes:0,openTimer:setTimeout(()=>{try{upstreamWs.close(1011,"upstream open timeout")}catch{}try{ws.close(1011,"upstream open timeout")}catch{}},1e4)};wsData._csBridge=state,upstreamWs.addEventListener("open",()=>{clearTimeout(state.openTimer),state.ready=!0;for(let msg of state.buffer)upstreamWs.send(msg);state.buffer.length=0,state.bufferBytes=0}),upstreamWs.addEventListener("message",(event)=>{try{let d=event.data;if(d instanceof ArrayBuffer)ws.send(new Uint8Array(d));else if(d instanceof Blob)d.arrayBuffer().then((ab)=>{try{ws.send(new Uint8Array(ab))}catch{}});else ws.send(d)}catch{}}),upstreamWs.addEventListener("close",(event)=>{clearTimeout(state.openTimer);try{ws.close(event.code||1000,event.reason||"upstream closed")}catch{}}),upstreamWs.addEventListener("error",()=>{clearTimeout(state.openTimer);try{ws.close(1011,"upstream error")}catch{}})}).catch(()=>{ws.close(1011,"Failed to query code-server status")})},message(ws,message){let state=ws.data?._csBridge;if(!state)return;let payload;if(typeof message==="string")payload=message;else if(message instanceof ArrayBuffer)payload=message;else if(message instanceof Uint8Array||Buffer.isBuffer(message)){let copy=new ArrayBuffer(message.byteLength);new Uint8Array(copy).set(new Uint8Array(message.buffer,message.byteOffset,message.byteLength)),payload=copy}else if(typeof message==="object"&&message!==null)payload=JSON.stringify(message);else payload=String(message);if(state.upstream&&state.ready&&state.upstream.readyState===WebSocket.OPEN)try{state.upstream.send(payload)}catch{}else{let nextBytes=payloadBytes(payload);if(state.buffer.length>=256||state.bufferBytes+nextBytes>1048576){try{state.upstream.close(1013,"buffer limit exceeded")}catch{}try{ws.close(1013,"buffer limit exceeded")}catch{}return}state.buffer.push(payload),state.bufferBytes+=nextBytes}},close(ws){ws.data._csClosed=!0;let state=ws.data?._csBridge;if(state?.openTimer)clearTimeout(state.openTimer);if(state?.upstream&&state.upstream.readyState===WebSocket.OPEN)state.upstream.close(1000,"client disconnected")}}}async function getPackageVersion(){try{let{readFileSync:readFileSync3}=await import("fs"),{join:join4,dirname:dirname2}=await import("path"),{fileURLToPath}=await import("url"),__dirname2=dirname2(fileURLToPath(import.meta.url));return JSON.parse(readFileSync3(join4(__dirname2,"..","package.json"),"utf8")).version||"1.0.0"}catch{return"1.0.0"}}
5
5
  export{mintPairingToken,invalidatePairingToken,createApp};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{denyNonLocalMutation,isLikelyLocalRequest}from"./index-49a60qjr.js";import{autoReportToBackend,stopProfileReconciler,stopTunnelSync}from"./index-8xr7ewxg.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-1atc02se.js";import"./index-7qj1swrk.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-q96eskyn.js";import{runAliasCaptured}from"./index-9e1fgxea.js";import{checkDependencies,installDependencies}from"./index-fg47j98r.js";import{ServiceManager}from"./index-vfwervz9.js";import{redactUnknownSecrets}from"./index-y5q0m3cx.js";import{getActiveContributorRegistry}from"./index-ttafzcs7.js";import"./index-1x89a7r1.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(`