@vibecontrols/agent 2026.602.5 → 2026.602.7

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.
Files changed (52) hide show
  1. package/dist/{agent-config-4ppenhqp.js → agent-config-pxkfd7ec.js} +1 -1
  2. package/dist/{agent-ready-tracker-kgs7td6t.js → agent-ready-tracker-pyw7zrp0.js} +1 -1
  3. package/dist/app-5asxkthh.js +2 -0
  4. package/dist/{bootstrap-workspace-qgs6d5f0.js → bootstrap-workspace-1ff98st2.js} +1 -1
  5. package/dist/{bridge-client-1fxza4p7.js → bridge-client-73z9c5nm.js} +1 -1
  6. package/dist/cli.js +1 -1
  7. package/dist/{daemon-profile-gwdcqx0q.js → daemon-profile-696722nr.js} +1 -1
  8. package/dist/{finalize-retry-worker-dvykrzed.js → finalize-retry-worker-vfdskqb5.js} +1 -1
  9. package/dist/{gateway-client-9kwnmk89.js → gateway-client-xdy5g715.js} +1 -1
  10. package/dist/{index-0924jp9m.js → index-08y76yzh.js} +1 -1
  11. package/dist/{index-h60rr9ca.js → index-2nq63va3.js} +2 -2
  12. package/dist/{index-cjbfremy.js → index-5mnyfrck.js} +1 -1
  13. package/dist/{index-h74va4wd.js → index-63ba5fb4.js} +1 -1
  14. package/dist/{index-hvjqgb97.js → index-6p3gcnxr.js} +2 -2
  15. package/dist/{index-1mppacnx.js → index-85ke6hng.js} +1 -1
  16. package/dist/{index-btt96dhd.js → index-9bdbnx8f.js} +2 -2
  17. package/dist/{index-rqq0k5fc.js → index-bfeekmyh.js} +1 -1
  18. package/dist/{index-dxtnaa3g.js → index-c6xa5nd4.js} +1 -1
  19. package/dist/{index-kmkhjf1c.js → index-cfa3pgh5.js} +3 -3
  20. package/dist/{index-5wpck4aw.js → index-czrb2yd1.js} +1 -1
  21. package/dist/{index-nrsqzcfc.js → index-eawbdgkb.js} +1 -1
  22. package/dist/{index-9430ndf7.js → index-ekzav1nc.js} +3 -3
  23. package/dist/{index-ydc0tk17.js → index-jrtsdm8f.js} +1 -1
  24. package/dist/{index-ebwwtwwc.js → index-m9dpfyxb.js} +1 -1
  25. package/dist/{index-hwtd3ank.js → index-n1222y6a.js} +4 -4
  26. package/dist/{index-tgrt61qr.js → index-p9cgvp3x.js} +1 -1
  27. package/dist/{index-rv6h14n8.js → index-rjhcmnx0.js} +1 -1
  28. package/dist/{index-b6x6a4xp.js → index-t8tnkqxh.js} +1 -1
  29. package/dist/{index-d1xjj001.js → index-wetsgcyq.js} +1 -1
  30. package/dist/{index-pk3ejfc4.js → index-x0xv3rpa.js} +1 -1
  31. package/dist/{index-js1xn4sq.js → index-xnr6t79p.js} +1 -1
  32. package/dist/{index-rw9x93zb.js → index-yas07mv9.js} +1 -1
  33. package/dist/index-z40ptwv4.js +158 -0
  34. package/dist/{index-z5s398n0.js → index-z73x3sdf.js} +1 -1
  35. package/dist/{index-rzpaqrhx.js → index-zhyxdyk6.js} +1 -1
  36. package/dist/index.js +2 -2
  37. package/dist/key.cmd-q8c7ywwd.js +2 -0
  38. package/dist/{plugin-system-8hfz23sx.js → plugin-system-f47jdx66.js} +1 -1
  39. package/dist/{prereqs-runner-27x3j1md.js → prereqs-runner-t5jhqr7x.js} +1 -1
  40. package/dist/{profile-mount-8dc9jwt5.js → profile-mount-m714p85h.js} +1 -1
  41. package/dist/register-core-2t9dmbnp.js +2 -0
  42. package/dist/secondary-profile-attach-s5z9dppt.js +2 -0
  43. package/dist/{subprocess-1nna3d3x.js → subprocess-q2ky0ptw.js} +1 -1
  44. package/dist/telemetry-jxfgrm61.js +2 -0
  45. package/dist/{tunnel-bootstrap-5wgt9a1h.js → tunnel-bootstrap-zdczwezc.js} +1 -1
  46. package/package.json +1 -1
  47. package/dist/app-bjmh5b5w.js +0 -2
  48. package/dist/index-ngrj0aqp.js +0 -158
  49. package/dist/key.cmd-972133dv.js +0 -2
  50. package/dist/register-core-vv6pbb13.js +0 -2
  51. package/dist/secondary-profile-attach-69zv112x.js +0 -2
  52. package/dist/telemetry-8jfdyt51.js +0 -2
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Da as D}from"./index-kmkhjf1c.js";import{Xa as V}from"./index-0ckffygp.js";import{$d as A,Sd as _,Td as w,Ud as x,Vd as N,Wd as j,Zd as X,ce as I}from"./index-a4854mwz.js";import{ie as S}from"./index-c7554sg7.js";import{existsSync as $,readdirSync as v,readFileSync as O,writeFileSync as M,mkdirSync as E,openSync as T,closeSync as b,unlinkSync as R}from"fs";import{join as Q}from"path";import{tmpdir as F}from"os";import{spawn as h}from"child_process";class P{registryPath;logsDir;productDir;constructor(){let q=I();this.productDir=q,this.registryPath=Q(q,"agents.json");let z=A();this.logsDir=Q(z,"logs"),E(q,{recursive:!0}),E(z,{recursive:!0}),E(this.logsDir,{recursive:!0})}async startDaemon(q){return X(q.name),this.withInstanceLock(q.name,async()=>{let z=await this.findProcessByName(q.name);if(z&&z.status==="running"){let U=z.version,W=D();if(U===W){console.log(`\u26A0\uFE0F Agent '${q.name}' is already running on port ${z.port}`);return}console.log(`\uD83D\uDD04 Agent '${q.name}' is running an older build (${U??"unknown"} \u2192 ${W}) \u2014 restarting to apply the update`);try{await this.stopInternal(q.name)}catch(Z){console.log(`\u26A0\uFE0F Could not cleanly stop the stale daemon (${Z instanceof Error?Z.message:String(Z)}); proceeding to start the new build`)}}let B=Q(this.logsDir,`${q.name}.log`),C=T(B,"a"),H=Q(import.meta.dir,"index.js"),G=Q(import.meta.dir,"..","index.ts"),L=$(H)?H:G,K=h(process.execPath,["run",L],{detached:!0,windowsHide:!0,stdio:["ignore",C,C],env:{...process.env,VIBECONTROLS_PROFILE:q.profile||"default",PORT:q.port.toString(),DB_PATH:q.dbPath,NODE_ENV:"production",AGENT_LOG_FILE:B}});K.on("error",()=>{}),b(C),await new Promise((U)=>setTimeout(U,2000));let J=K.pid;if(!(J!==void 0&&await this.isProcessRunning(J))){let U="";try{U=O(B,"utf8").split(/\r?\n/).filter((k)=>k.trim()).slice(-25).join(`
2
+ import{Da as D}from"./index-cfa3pgh5.js";import{Xa as V}from"./index-0ckffygp.js";import{$d as A,Sd as _,Td as w,Ud as x,Vd as N,Wd as j,Zd as X,ce as I}from"./index-a4854mwz.js";import{ie as S}from"./index-c7554sg7.js";import{existsSync as $,readdirSync as v,readFileSync as O,writeFileSync as M,mkdirSync as E,openSync as T,closeSync as b,unlinkSync as R}from"fs";import{join as Q}from"path";import{tmpdir as F}from"os";import{spawn as h}from"child_process";class P{registryPath;logsDir;productDir;constructor(){let q=I();this.productDir=q,this.registryPath=Q(q,"agents.json");let z=A();this.logsDir=Q(z,"logs"),E(q,{recursive:!0}),E(z,{recursive:!0}),E(this.logsDir,{recursive:!0})}async startDaemon(q){return X(q.name),this.withInstanceLock(q.name,async()=>{let z=await this.findProcessByName(q.name);if(z&&z.status==="running"){let U=z.version,W=D();if(U===W){console.log(`\u26A0\uFE0F Agent '${q.name}' is already running on port ${z.port}`);return}console.log(`\uD83D\uDD04 Agent '${q.name}' is running an older build (${U??"unknown"} \u2192 ${W}) \u2014 restarting to apply the update`);try{await this.stopInternal(q.name)}catch(Z){console.log(`\u26A0\uFE0F Could not cleanly stop the stale daemon (${Z instanceof Error?Z.message:String(Z)}); proceeding to start the new build`)}}let B=Q(this.logsDir,`${q.name}.log`),C=T(B,"a"),H=Q(import.meta.dir,"index.js"),G=Q(import.meta.dir,"..","index.ts"),L=$(H)?H:G,K=h(process.execPath,["run",L],{detached:!0,windowsHide:!0,stdio:["ignore",C,C],env:{...process.env,VIBECONTROLS_PROFILE:q.profile||"default",PORT:q.port.toString(),DB_PATH:q.dbPath,NODE_ENV:"production",AGENT_LOG_FILE:B}});K.on("error",()=>{}),b(C),await new Promise((U)=>setTimeout(U,2000));let J=K.pid;if(!(J!==void 0&&await this.isProcessRunning(J))){let U="";try{U=O(B,"utf8").split(/\r?\n/).filter((k)=>k.trim()).slice(-25).join(`
3
3
  `)}catch{}let W=`See ${B}`;throw Error(U?`Failed to start agent '${q.name}'. ${W}
4
4
  --- last log lines ---
5
5
  ${U}`:`Failed to start agent '${q.name}'. ${W}`)}K.unref(),await this.saveProcessInfo(q.name,J,q),console.log(`\uD83D\uDE80 Agent '${q.name}' started (PID: ${J}, Port: ${q.port})`)})}async stop(q){return X(q),this.withInstanceLock(q,()=>this.stopInternal(q))}async stopInternal(q){let z=await this.findProcessByName(q);if(!z||z.status!=="running"){console.log(`\u26A0\uFE0F Agent '${q}' is not running`);return}try{if(process.kill(z.pid,"SIGTERM"),await new Promise((C)=>setTimeout(C,3000)),await this.isProcessRunning(z.pid))process.kill(z.pid,"SIGKILL");await this.updateProcessStatus(q,"stopped"),console.log(`\u2705 Agent '${q}' stopped (tunnel + API key preserved)`)}catch(B){throw Error(`Failed to stop agent '${q}': ${B}`,{cause:B})}}async restart(q,z){X(q),X(z.name);let B=await this.findProcessByName(q);if(B&&B.status==="running")await this.stop(q);await this.startDaemon(z),console.log(`\uD83D\uDD04 Agent '${q}' restarted (tunnel + API key preserved)`)}async kill(q){return X(q),this.withInstanceLock(q,async()=>{let z=await this.findProcessByName(q);if(!z||z.status!=="running"){console.log(`\u26A0\uFE0F Agent '${q}' is not running`);return}let B=Q(F(),`.boff-vibecontrols-kill-${z.pid}`);try{await Bun.write(B,"kill")}catch{}try{process.kill(z.pid,"SIGTERM"),await new Promise((H)=>setTimeout(H,5000))}catch{}if(await this.isProcessRunning(z.pid))await this.killProcessTree(z.pid);await this.updateProcessStatus(q,"stopped"),console.log(`\uD83D\uDC80 Agent '${q}' killed (tunnel + state torn down)`)})}async getStatus(q){return X(q),this.findProcessByName(q)}discoverRuntimeInstances(){let q=Q(this.productDir,"agents");if(!$(q))return[];let z;try{z=v(q,{withFileTypes:!0}).filter((C)=>C.isDirectory()).map((C)=>C.name)}catch{return[]}let B=[];for(let C of z){let H=Q(q,C,"runtime.json");if(!$(H))continue;try{let G=JSON.parse(O(H,"utf8"));if(typeof G.pid!=="number"||typeof G.port!=="number")continue;let L=G.profile||C;try{X(L)}catch{continue}B.push({name:L,pid:G.pid,port:G.port,config:{name:L,port:G.port,daemon:!0,dbPath:Q(q,C,"agent-db"),host:G.host,profile:L},startTime:G.startedAt??new Date(0).toISOString(),status:"unknown",version:G.version})}catch{}}return B}async getStatusAll(){let q=this.loadRegistry(),z=new Set(q.map((G)=>G.name)),B=[...q];for(let G of this.discoverRuntimeInstances())if(!z.has(G.name))B.push(G);let C=[];for(let G of B){let L=await this.isManagedProcessRunning(G);if(!z.has(G.name)&&!L)continue;C.push({...G,status:L?"running":"stopped"})}let H=C.filter((G)=>G.status==="running"&&!z.has(G.name));if(H.length>0)try{await _(()=>{let G=this.loadRegistry(),L=new Set(G.map((J)=>J.name)),K=H.filter((J)=>!L.has(J.name));if(K.length>0)this.saveRegistry([...G,...K.map((J)=>({...J,status:"running"}))])})}catch{}return C}async listInstances(){return this.getStatusAll()}getDefaultProfile(){return N()}setDefaultProfile(q){j(X(q))}async showLogs(q,z){X(q);let B=Q(this.logsDir,`${q}.log`);if(!$(B)){console.log(`No logs found for agent '${q}'`);return}if(z.follow)try{let C=async(J)=>{let Y=await Bun.file(B).text(),W=Y.split(`
@@ -3,7 +3,7 @@ import{$d as l,Yd as c,Zd as i,ce as n}from"./index-a4854mwz.js";import{ee as g}
3
3
  `,{mode:384})}catch{}}listLogFiles(){if(!P(this.auditDir))return[];return ZJ(this.auditDir).filter((J)=>h.test(J)).sort()}listEvents(J={}){let Z=Math.max(1,Math.min(J.limit??200,5000)),$=J.since?Date.parse(J.since):null,Q=J.event??"",X=this.listLogFiles(),W=[];for(let K=X.length-1;K>=0&&W.length<Z;K--){let V=X[K],z;try{z=JJ(F(this.auditDir,V),"utf8")}catch{continue}let Y=z.split(`
4
4
  `);for(let M=Y.length-1;M>=0&&W.length<Z;M--){let q=Y[M];if(!q)continue;let H;try{H=JSON.parse(q)}catch{continue}if($!==null&&Number.isFinite($)&&Date.parse(H.timestamp)<$)continue;if(!KJ(H.event,Q))continue;W.push(H)}}return W}runRetention(J=new Date){if(!P(this.auditDir))return;let Z=J.getTime()-QJ*24*60*60*1000,$=this.listLogFiles(),Q=[];for(let K of $){let V=h.exec(K);if(!V)continue;let z=Date.parse(`${V[1]}T00:00:00Z`),Y=F(this.auditDir,K);try{let M=$J(Y);if(Number.isFinite(z)&&z<Z){v(Y);continue}Q.push({name:K,size:M.size,mtime:M.mtimeMs})}catch{}}let X=Q.reduce((K,V)=>K+V.size,0),W=`audit-${y(J)}.log`;Q.sort((K,V)=>K.name.localeCompare(V.name));for(let K of Q){if(X<=XJ)break;if(K.name===W)continue;try{v(F(this.auditDir,K.name)),X-=K.size}catch{}}}__getAuditDirForTests(){return this.auditDir}}class _{profile;cryptoKey=null;apiKeyHash=null;constructor(J){this.profile=J}async load(J){if(J.byteLength!==32)throw Error(`KeyVault expects 32-byte key, got ${J.byteLength}`);let Z=new Uint8Array(J);try{this.cryptoKey=await crypto.subtle.importKey("raw",Z,{name:"AES-GCM"},!1,["encrypt","decrypt"])}finally{J.fill(0),Z.fill(0)}}async bindApiKey(J){let Z=new TextEncoder().encode(J);this.apiKeyHash=await crypto.subtle.digest("SHA-256",Z),Z.fill(0)}async match(J){if(!this.apiKeyHash)return!1;let Z=new TextEncoder().encode(J),$=await crypto.subtle.digest("SHA-256",Z);return Z.fill(0),VJ(this.apiKeyHash,$)}hasKey(){return this.cryptoKey!==null}getCryptoKey(){return this.cryptoKey}shutdown(){this.cryptoKey=null,this.apiKeyHash=null}}function VJ(J,Z){if(J.byteLength!==Z.byteLength)return!1;let $=new Uint8Array(J),Q=new Uint8Array(Z),X=0;for(let W=0;W<$.length;W++)X|=($[W]??0)^(Q[W]??0);return X===0}import{existsSync as N,mkdirSync as MJ,statSync as HJ,copyFileSync as BJ,truncateSync as CJ,renameSync as qJ,unlinkSync as NJ,createReadStream as DJ}from"fs";import{join as FJ}from"path";import{EventEmitter as jJ}from"events";import{createInterface as GJ}from"readline";import{AsyncLocalStorage as zJ}from"async_hooks";var f=new zJ,YJ=/^[A-Za-z0-9._:-]{8,128}$/;function lJ(){let J=globalThis.crypto;if(J?.randomUUID)return J.randomUUID();let Z=new Uint8Array(16);return J?.getRandomValues?.(Z),[...Z].map(($)=>$.toString(16).padStart(2,"0")).join("")}function nJ(J){let Z=(Q)=>{if(J instanceof Headers)return J.get(Q)??void 0;return J[Q]??J[Q.toLowerCase()]??J[Q.toUpperCase()]},$=Z("x-request-id")??Z("X-Request-Id");if(!$)return;return YJ.test($)?$:void 0}function oJ(J){f.enterWith(J)}function G(){return f.getStore()?.requestId}var bJ=10485760,m=7,OJ=60000,b={debug:0,info:1,warn:2,error:3},PJ={debug:"\x1B[90m",info:"\x1B[36m",warn:"\x1B[33m",error:"\x1B[31m"},kJ="\x1B[0m";class L extends jJ{logDir;logFile;currentDay="";minLevel;isDaemon;emitOutput;prettyOutput;rotationTimer=null;constructor(J){super();this.setMaxListeners(100),this.logDir=J.logDir;let Z=process.env.AGENT_LOG_FILE;this.logFile=Z&&Z.length>0?Z:J.logFile??FJ(this.logDir,"default.log"),this.minLevel=process.env.LOG_LEVEL??"info",this.isDaemon=Boolean(process.env.AGENT_LOG_FILE);let $=process.env.VIBE_FOREGROUND==="1"||process.argv.some((Q)=>Q==="-f"||Q==="--foreground");if(this.emitOutput=this.isDaemon||$||process.env.LOG_CONSOLE==="true"||!1,this.prettyOutput=this.emitOutput&&!this.isDaemon&&Boolean(process.stdout.isTTY),this.ensureLogDir(),this.currentDay=new Date().toISOString().split("T")[0]??"",this.isDaemon)this.rotationTimer=setInterval(()=>this.checkRotation(),OJ),this.rotationTimer.unref?.()}debug(J,Z,$){this.log("debug",J,Z,$)}info(J,Z,$){this.log("info",J,Z,$)}warn(J,Z,$){this.log("warn",J,Z,$)}error(J,Z,$){this.log("error",J,Z,$)}setLevel(J){this.minLevel=J}async readHistory(J){let{level:Z,source:$,from:Q,to:X,limit:W=200,offset:K=0}=J??{},V=[];if(!N(this.logFile))return V;return new Promise((z)=>{let Y=GJ({input:DJ(this.logFile,"utf8")}),M=0;Y.on("line",(q)=>{if(V.length>=W){Y.close();return}try{let H=JSON.parse(q);if(Z&&b[H.level]<b[Z])return;if($&&!H.source.includes($))return;if(Q&&H.timestamp<Q)return;if(X&&H.timestamp>X)return;if(M<K){M++;return}V.push(H)}catch{}}),Y.on("close",()=>z(V)),Y.on("error",()=>z(V))})}close(){if(this.rotationTimer)clearInterval(this.rotationTimer),this.rotationTimer=null}log(J,Z,$,Q){if(b[J]<b[this.minLevel])return;let X=G(),W=X!==void 0?{requestId:X,...Q??{}}:Q,K={timestamp:new Date().toISOString(),level:J,source:Z,message:$,...W&&Object.keys(W).length>0?{metadata:W}:{}};if(this.emitOutput)if(this.prettyOutput){let V=PJ[J],z=J.toUpperCase().padEnd(5),Y=Z?` [${Z}]`:"",M=W&&Object.keys(W).length>0?` ${JSON.stringify(W)}`:"",q=K.timestamp.split("T")[1]?.slice(0,12)??K.timestamp;process.stdout.write(`${V}${q} ${z}${kJ}${Y} ${$}${M}
5
5
  `)}else process.stdout.write(JSON.stringify(K)+`
6
- `);this.emit("log",K),g.enqueue(K)}checkRotation(){let J=new Date().toISOString().split("T")[0];if(this.currentDay&&this.currentDay!==J){this.rotate(),this.currentDay=J;return}this.currentDay=J;try{if(N(this.logFile)){if(HJ(this.logFile).size>=bJ)this.rotate()}}catch{}}rotate(){try{for(let J=m-1;J>=1;J--){let Z=`${this.logFile}.${J}`,$=`${this.logFile}.${J+1}`;if(N(Z)){if(J+1>m&&N($))NJ($);qJ(Z,$)}}if(N(this.logFile))BJ(this.logFile,`${this.logFile}.1`),CJ(this.logFile,0)}catch{}}ensureLogDir(){if(!N(this.logDir))MJ(this.logDir,{recursive:!0})}}var LJ={maxFileDescriptors:4096,maxChildProcesses:256,maxMemoryMB:4096},U=new IJ;function M2(J){U.enterWith(J)}class x{name;dataDir;spawnOwnerKey;keyVault;audit;logger;budget;db=null;serviceRegistry=null;pluginManager=null;lifecycle=null;hostServices=null;tunnel={url:null,child:null,externalUrl:!1};_gatewayClient=null;state="awaiting-config";degradedReasons=[];listeners=new Set;lastFinalizeError=null;constructor(J){this.name=J.name,this.dataDir=J.dataDir,this.spawnOwnerKey=`profile/${J.name}`,this.budget=J.budget??LJ,_J(this.dataDir,{recursive:!0}),this.keyVault=new _(J.name),this.audit=new I(J.name,J.dataDir),this.logger=new L({logDir:u(J.dataDir,"logs")})}run(J){return U.run(this,J)}get gatewayClient(){if(!this._gatewayClient)this._gatewayClient=new R;return this._gatewayClient}attachServices(J){this.db=J.db,this.serviceRegistry=J.serviceRegistry,this.pluginManager=J.pluginManager,this.lifecycle=J.lifecycle,this.hostServices=J.hostServices}getBootState(){return this.state}setBootState(J){if(this.state===J)return;if(this.state=J,J!=="degraded")this.degradedReasons.length=0;for(let Z of this.listeners)try{Z(J)}catch{}}recordDegradedReason(J,Z){if(this.degradedReasons.push({plugin:J,message:Z}),this.state==="ready")this.setBootState("degraded");(async()=>{try{let{telemetryService:$}=await import("./telemetry-8jfdyt51.js");$.emit("health.degraded",{reason_class:RJ(Z)})}catch{}})()}getDegradedReasons(){return this.degradedReasons.slice()}recordFinalizeError(J,Z){this.lastFinalizeError={message:J,at:new Date().toISOString(),attempt:Z}}clearFinalizeError(){this.lastFinalizeError=null}getLastFinalizeError(){return this.lastFinalizeError}onBootStateChange(J){return this.listeners.add(J),()=>this.listeners.delete(J)}async shutdown(){this.setBootState("shutting-down");try{let{unmountProfileRoutes:J}=await import("./profile-mount-8dc9jwt5.js");J(this.name)}catch{}try{if(this.pluginManager)await this.pluginManager.dispatchServerStop({reason:"shutdown"})}catch{}try{if(this.db)await this.db.close()}catch{}this.lifecycle=null,this.pluginManager=null,this.hostServices=null,this.serviceRegistry=null,this.db=null,this._gatewayClient=null,this.tunnel={url:null,child:null,externalUrl:!1},this.keyVault.shutdown(),this.listeners.clear()}subdir(J){return u(this.dataDir,J)}}function d(){return U.getStore()??null}function RJ(J){let Z=J.toLowerCase();if(Z.includes("timeout"))return"timeout";if(Z.includes("econn")||Z.includes("network"))return"network";if(Z.includes("permission")||Z.includes("eacces"))return"permission";if(Z.includes("not found")||Z.includes("enoent"))return"not_found";if(Z.includes("plugin"))return"plugin";return"other"}class A{profiles=new Map;create(J){if(this.profiles.has(J.name))throw Error(`profile already registered: ${J.name}`);let Z=new x(J);return this.profiles.set(J.name,Z),this.refreshProcessTitle(),Z}refreshProcessTitle(){try{let Z=[...this.profiles.keys()].sort().join(","),$=Z.length>96?`${Z.slice(0,93)}...`:Z;process.title=`vibe-daemon[${$}]`}catch{}}get(J){return this.profiles.get(J)}list(){return[...this.profiles.values()]}names(){return[...this.profiles.keys()]}has(J){return this.profiles.has(J)}size(){return this.profiles.size}async destroy(J){let Z=this.profiles.get(J);if(!Z)return;await Z.shutdown(),this.profiles.delete(J),this.refreshProcessTitle()}async destroyAll(){let J=[...this.profiles.keys()];for(let Z of J)await this.destroy(Z)}}var j=new A,D=null;function xJ(){if(D)return D;let J=c(),Z=j.get(J);if(Z)return D=Z,Z;return D=j.create({name:J,dataDir:l()}),D}function B(){return xJ()}function F2(J){let Z=i(J),$=j.get(Z);if($)return $;return j.create({name:Z,dataDir:UJ(n(),"agents",Z)})}async function j2(){D=null,await j.destroyAll()}var O=new Set(["localhost","127.0.0.1","0.0.0.0","::1","[::1]","host.docker.internal"]),AJ=new Set(["4000","4001","4002","4003"]),TJ=new Set(["gw-global.local.burdenoff.com","gw-global-int.local.burdenoff.com","gw-wspace.local.burdenoff.com","gw-wspace-int.local.burdenoff.com"]),EJ=new Set(["graphql.burdenoff.com","graphqlworkspaces.burdenoff.com","alphagraphql.burdenoff.com","alphagraphqlworkspaces.burdenoff.com"]);function C(J){return J.toLowerCase().replace(/^\[|\]$/g,"")}function o(J){let Z=C(J.hostname);if(!O.has(Z))return!1;if(process.env.VIBECONTROLS_ALLOW_UNTRUSTED_GATEWAYS==="1")return!0;return AJ.has(J.port)}function s(J){try{let Z=new URL(J.trim());if(Z.protocol!=="https:"&&Z.protocol!=="http:")return!1;if(o(Z))return!0;let $=C(Z.hostname);if(TJ.has($))return Z.protocol==="https:";if(Z.protocol!=="https:")return!1;return EJ.has($)}catch{return!1}}function T(J,Z){let $=J.trim();if(!s($))throw Error(`${Z} is not an allowed gateway URL. Use a trusted Burdenoff gateway, approved gw-*.local.burdenoff.com host, or localhost gateway ports 4000-4003.`);return $.replace(/\/+$/,"")}var E=new Set([".vibecontrols.com"]);function b2(J){let Z=J.trim().toLowerCase();if(!Z)return;E.add(Z.startsWith(".")?Z:`.${Z}`)}function SJ(J){try{let Z=new URL(J.trim()),$=C(Z.hostname);if(O.has($))return Z.protocol==="http:"||Z.protocol==="https:";if(Z.protocol!=="https:")return!1;for(let Q of E)if($.endsWith(Q))return!0;return!1}catch{return!1}}function O2(J){if(!J)return null;let Z=J.trim().replace(/\/+$/,"");return SJ(Z)?Z:null}var wJ=new Set([".trycloudflare.com"]);function vJ(J){try{let Z=new URL(J.trim()),$=C(Z.hostname);if(O.has($))return Z.protocol==="http:"||Z.protocol==="https:";if(Z.protocol!=="https:")return!1;for(let Q of E)if($.endsWith(Q))return!0;for(let Q of wJ)if($.endsWith(Q))return!0;return!1}catch{return!1}}function P2(J){if(!J)return null;let Z=J.trim().replace(/\/+$/,"");return vJ(Z)?Z:null}function hJ(J){try{let Z=new URL(J.trim()),$=C(Z.hostname);if(O.has($))return Z.protocol==="http:"||Z.protocol==="https:";return Z.protocol==="https:"}catch{return!1}}function k2(J){if(!J)return null;let Z=J.trim().replace(/\/+$/,"");return hJ(Z)?Z:null}function I2(J,Z){try{let $=new URL(J.trim());if($.protocol!=="https:"&&!o($))return!1;let Q=C($.hostname);for(let X of Z){if(!X)continue;let W=new URL(X);if(Q===C(W.hostname))return!0}return s(J)}catch{return!1}}var yJ=/(?:\/(?:global|workspaces))?\/graphql$/i,fJ=1048576;function w(J){return J.trim().replace(/\/+$/,"").replace(yJ,"")}function a(J,Z){return`${w(J)}/${Z}/graphql`}function t(J){return J instanceof Error?J.message:String(J)}async function mJ(J,Z){let $=J.headers.get("content-length");if($){let z=Number.parseInt($,10);if(Number.isInteger(z)&&z>Z)throw Error(`Gateway response is too large (${z} bytes)`)}if(!J.body)return"";let Q=J.body.getReader(),X=[],W=0;try{while(!0){let{done:z,value:Y}=await Q.read();if(z)break;if(!Y)continue;if(W+=Y.byteLength,W>Z)throw await Q.cancel().catch(()=>{return}),Error(`Gateway response exceeds ${Z} bytes`);X.push(Y)}}finally{Q.releaseLock()}let K=new Uint8Array(W),V=0;for(let z of X)K.set(z,V),V+=z.byteLength;return new TextDecoder().decode(K)}class R{config=null;token=null;authInFlight=null;configGeneration=0;configure(J){let Z=w(T(J.globalGatewayUrl,"globalGatewayUrl")),$=J.workspaceGatewayUrl?w(T(J.workspaceGatewayUrl,"workspaceGatewayUrl")):void 0,Q=J.clientId.trim(),X=J.clientSecret.trim();if(!Z)throw Error("globalGatewayUrl is required");if(!Q)throw Error("clientId is required");if(!X)throw Error("clientSecret is required");this.configGeneration+=1,this.config={...J,globalGatewayUrl:Z,workspaceGatewayUrl:$,clientId:Q,clientSecret:X,scopes:J.scopes?.map((W)=>W.trim()).filter(Boolean),workspaceId:J.workspaceId?.trim()||void 0,organizationId:J.organizationId?.trim()||void 0},this.token=null,this.authInFlight=null,B().logger.info("gateway-client","Gateway client configured",{globalGatewayUrl:this.config.globalGatewayUrl,workspaceGatewayUrl:this.config.workspaceGatewayUrl,clientId:this.config.clientId})}isConfigured(){return this.config!==null}getConfig(){if(!this.config)return null;let{clientSecret:J,...Z}=this.config;return Z}async getAccessToken(){let{token:J,config:Z}=await this.ensureToken();return{token:J,workspaceGatewayUrl:Z.workspaceGatewayUrl??"",globalGatewayUrl:Z.globalGatewayUrl??"",workspaceId:Z.workspaceId??""}}async globalQuery(J,Z){return this.executeQuery("global",J,Z)}async workspaceQuery(J,Z){return this.executeQuery("workspaces",J,Z)}async lookupPeerAgent(J,Z){if(!this.isConfigured())return null;try{let Q=(await this.workspaceQuery(`query AgentNetworkLookup($targetAgentRecordId: ID!, $operation: String!) {
6
+ `);this.emit("log",K),g.enqueue(K)}checkRotation(){let J=new Date().toISOString().split("T")[0];if(this.currentDay&&this.currentDay!==J){this.rotate(),this.currentDay=J;return}this.currentDay=J;try{if(N(this.logFile)){if(HJ(this.logFile).size>=bJ)this.rotate()}}catch{}}rotate(){try{for(let J=m-1;J>=1;J--){let Z=`${this.logFile}.${J}`,$=`${this.logFile}.${J+1}`;if(N(Z)){if(J+1>m&&N($))NJ($);qJ(Z,$)}}if(N(this.logFile))BJ(this.logFile,`${this.logFile}.1`),CJ(this.logFile,0)}catch{}}ensureLogDir(){if(!N(this.logDir))MJ(this.logDir,{recursive:!0})}}var LJ={maxFileDescriptors:4096,maxChildProcesses:256,maxMemoryMB:4096},U=new IJ;function M2(J){U.enterWith(J)}class x{name;dataDir;spawnOwnerKey;keyVault;audit;logger;budget;db=null;serviceRegistry=null;pluginManager=null;lifecycle=null;hostServices=null;tunnel={url:null,child:null,externalUrl:!1};_gatewayClient=null;state="awaiting-config";degradedReasons=[];listeners=new Set;lastFinalizeError=null;constructor(J){this.name=J.name,this.dataDir=J.dataDir,this.spawnOwnerKey=`profile/${J.name}`,this.budget=J.budget??LJ,_J(this.dataDir,{recursive:!0}),this.keyVault=new _(J.name),this.audit=new I(J.name,J.dataDir),this.logger=new L({logDir:u(J.dataDir,"logs")})}run(J){return U.run(this,J)}get gatewayClient(){if(!this._gatewayClient)this._gatewayClient=new R;return this._gatewayClient}attachServices(J){this.db=J.db,this.serviceRegistry=J.serviceRegistry,this.pluginManager=J.pluginManager,this.lifecycle=J.lifecycle,this.hostServices=J.hostServices}getBootState(){return this.state}setBootState(J){if(this.state===J)return;if(this.state=J,J!=="degraded")this.degradedReasons.length=0;for(let Z of this.listeners)try{Z(J)}catch{}}recordDegradedReason(J,Z){if(this.degradedReasons.push({plugin:J,message:Z}),this.state==="ready")this.setBootState("degraded");(async()=>{try{let{telemetryService:$}=await import("./telemetry-jxfgrm61.js");$.emit("health.degraded",{reason_class:RJ(Z)})}catch{}})()}getDegradedReasons(){return this.degradedReasons.slice()}recordFinalizeError(J,Z){this.lastFinalizeError={message:J,at:new Date().toISOString(),attempt:Z}}clearFinalizeError(){this.lastFinalizeError=null}getLastFinalizeError(){return this.lastFinalizeError}onBootStateChange(J){return this.listeners.add(J),()=>this.listeners.delete(J)}async shutdown(){this.setBootState("shutting-down");try{let{unmountProfileRoutes:J}=await import("./profile-mount-m714p85h.js");J(this.name)}catch{}try{if(this.pluginManager)await this.pluginManager.dispatchServerStop({reason:"shutdown"})}catch{}try{if(this.db)await this.db.close()}catch{}this.lifecycle=null,this.pluginManager=null,this.hostServices=null,this.serviceRegistry=null,this.db=null,this._gatewayClient=null,this.tunnel={url:null,child:null,externalUrl:!1},this.keyVault.shutdown(),this.listeners.clear()}subdir(J){return u(this.dataDir,J)}}function d(){return U.getStore()??null}function RJ(J){let Z=J.toLowerCase();if(Z.includes("timeout"))return"timeout";if(Z.includes("econn")||Z.includes("network"))return"network";if(Z.includes("permission")||Z.includes("eacces"))return"permission";if(Z.includes("not found")||Z.includes("enoent"))return"not_found";if(Z.includes("plugin"))return"plugin";return"other"}class A{profiles=new Map;create(J){if(this.profiles.has(J.name))throw Error(`profile already registered: ${J.name}`);let Z=new x(J);return this.profiles.set(J.name,Z),this.refreshProcessTitle(),Z}refreshProcessTitle(){try{let Z=[...this.profiles.keys()].sort().join(","),$=Z.length>96?`${Z.slice(0,93)}...`:Z;process.title=`vibe-daemon[${$}]`}catch{}}get(J){return this.profiles.get(J)}list(){return[...this.profiles.values()]}names(){return[...this.profiles.keys()]}has(J){return this.profiles.has(J)}size(){return this.profiles.size}async destroy(J){let Z=this.profiles.get(J);if(!Z)return;await Z.shutdown(),this.profiles.delete(J),this.refreshProcessTitle()}async destroyAll(){let J=[...this.profiles.keys()];for(let Z of J)await this.destroy(Z)}}var j=new A,D=null;function xJ(){if(D)return D;let J=c(),Z=j.get(J);if(Z)return D=Z,Z;return D=j.create({name:J,dataDir:l()}),D}function B(){return xJ()}function F2(J){let Z=i(J),$=j.get(Z);if($)return $;return j.create({name:Z,dataDir:UJ(n(),"agents",Z)})}async function j2(){D=null,await j.destroyAll()}var O=new Set(["localhost","127.0.0.1","0.0.0.0","::1","[::1]","host.docker.internal"]),AJ=new Set(["4000","4001","4002","4003"]),TJ=new Set(["gw-global.local.burdenoff.com","gw-global-int.local.burdenoff.com","gw-wspace.local.burdenoff.com","gw-wspace-int.local.burdenoff.com"]),EJ=new Set(["graphql.burdenoff.com","graphqlworkspaces.burdenoff.com","alphagraphql.burdenoff.com","alphagraphqlworkspaces.burdenoff.com"]);function C(J){return J.toLowerCase().replace(/^\[|\]$/g,"")}function o(J){let Z=C(J.hostname);if(!O.has(Z))return!1;if(process.env.VIBECONTROLS_ALLOW_UNTRUSTED_GATEWAYS==="1")return!0;return AJ.has(J.port)}function s(J){try{let Z=new URL(J.trim());if(Z.protocol!=="https:"&&Z.protocol!=="http:")return!1;if(o(Z))return!0;let $=C(Z.hostname);if(TJ.has($))return Z.protocol==="https:";if(Z.protocol!=="https:")return!1;return EJ.has($)}catch{return!1}}function T(J,Z){let $=J.trim();if(!s($))throw Error(`${Z} is not an allowed gateway URL. Use a trusted Burdenoff gateway, approved gw-*.local.burdenoff.com host, or localhost gateway ports 4000-4003.`);return $.replace(/\/+$/,"")}var E=new Set([".vibecontrols.com"]);function b2(J){let Z=J.trim().toLowerCase();if(!Z)return;E.add(Z.startsWith(".")?Z:`.${Z}`)}function SJ(J){try{let Z=new URL(J.trim()),$=C(Z.hostname);if(O.has($))return Z.protocol==="http:"||Z.protocol==="https:";if(Z.protocol!=="https:")return!1;for(let Q of E)if($.endsWith(Q))return!0;return!1}catch{return!1}}function O2(J){if(!J)return null;let Z=J.trim().replace(/\/+$/,"");return SJ(Z)?Z:null}var wJ=new Set([".trycloudflare.com"]);function vJ(J){try{let Z=new URL(J.trim()),$=C(Z.hostname);if(O.has($))return Z.protocol==="http:"||Z.protocol==="https:";if(Z.protocol!=="https:")return!1;for(let Q of E)if($.endsWith(Q))return!0;for(let Q of wJ)if($.endsWith(Q))return!0;return!1}catch{return!1}}function P2(J){if(!J)return null;let Z=J.trim().replace(/\/+$/,"");return vJ(Z)?Z:null}function hJ(J){try{let Z=new URL(J.trim()),$=C(Z.hostname);if(O.has($))return Z.protocol==="http:"||Z.protocol==="https:";return Z.protocol==="https:"}catch{return!1}}function k2(J){if(!J)return null;let Z=J.trim().replace(/\/+$/,"");return hJ(Z)?Z:null}function I2(J,Z){try{let $=new URL(J.trim());if($.protocol!=="https:"&&!o($))return!1;let Q=C($.hostname);for(let X of Z){if(!X)continue;let W=new URL(X);if(Q===C(W.hostname))return!0}return s(J)}catch{return!1}}var yJ=/(?:\/(?:global|workspaces))?\/graphql$/i,fJ=1048576;function w(J){return J.trim().replace(/\/+$/,"").replace(yJ,"")}function a(J,Z){return`${w(J)}/${Z}/graphql`}function t(J){return J instanceof Error?J.message:String(J)}async function mJ(J,Z){let $=J.headers.get("content-length");if($){let z=Number.parseInt($,10);if(Number.isInteger(z)&&z>Z)throw Error(`Gateway response is too large (${z} bytes)`)}if(!J.body)return"";let Q=J.body.getReader(),X=[],W=0;try{while(!0){let{done:z,value:Y}=await Q.read();if(z)break;if(!Y)continue;if(W+=Y.byteLength,W>Z)throw await Q.cancel().catch(()=>{return}),Error(`Gateway response exceeds ${Z} bytes`);X.push(Y)}}finally{Q.releaseLock()}let K=new Uint8Array(W),V=0;for(let z of X)K.set(z,V),V+=z.byteLength;return new TextDecoder().decode(K)}class R{config=null;token=null;authInFlight=null;configGeneration=0;configure(J){let Z=w(T(J.globalGatewayUrl,"globalGatewayUrl")),$=J.workspaceGatewayUrl?w(T(J.workspaceGatewayUrl,"workspaceGatewayUrl")):void 0,Q=J.clientId.trim(),X=J.clientSecret.trim();if(!Z)throw Error("globalGatewayUrl is required");if(!Q)throw Error("clientId is required");if(!X)throw Error("clientSecret is required");this.configGeneration+=1,this.config={...J,globalGatewayUrl:Z,workspaceGatewayUrl:$,clientId:Q,clientSecret:X,scopes:J.scopes?.map((W)=>W.trim()).filter(Boolean),workspaceId:J.workspaceId?.trim()||void 0,organizationId:J.organizationId?.trim()||void 0},this.token=null,this.authInFlight=null,B().logger.info("gateway-client","Gateway client configured",{globalGatewayUrl:this.config.globalGatewayUrl,workspaceGatewayUrl:this.config.workspaceGatewayUrl,clientId:this.config.clientId})}isConfigured(){return this.config!==null}getConfig(){if(!this.config)return null;let{clientSecret:J,...Z}=this.config;return Z}async getAccessToken(){let{token:J,config:Z}=await this.ensureToken();return{token:J,workspaceGatewayUrl:Z.workspaceGatewayUrl??"",globalGatewayUrl:Z.globalGatewayUrl??"",workspaceId:Z.workspaceId??""}}async globalQuery(J,Z){return this.executeQuery("global",J,Z)}async workspaceQuery(J,Z){return this.executeQuery("workspaces",J,Z)}async lookupPeerAgent(J,Z){if(!this.isConfigured())return null;try{let Q=(await this.workspaceQuery(`query AgentNetworkLookup($targetAgentRecordId: ID!, $operation: String!) {
7
7
  vibecontrolsAgentNetworkLookup(targetAgentRecordId: $targetAgentRecordId, operation: $operation) {
8
8
  tunnelUrl
9
9
  peerApiKey
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{Xa as R}from"./index-0ckffygp.js";import{bb as j}from"./index-ydc0tk17.js";import{Bd as D,Ed as P,Ld as g,Od as M}from"./index-js1xn4sq.js";import{$d as x,Yd as y,ae as A}from"./index-a4854mwz.js";import{spawn as _}from"child_process";import{createHash as f}from"crypto";import{existsSync as u,promises as V,createWriteStream as h}from"fs";import{homedir as m,tmpdir as p}from"os";import*as q from"path";import{Readable as d}from"stream";import{pipeline as l}from"stream/promises";function n(){let G=process.arch==="x64"?"x64":"arm64";return`${process.platform==="win32"?"win32":process.platform==="darwin"?"darwin":"linux"}-${G}`}function c(){return q.join(m(),".boff","vibecontrols","tools")}function L(G,J){let X=J??G;if(process.platform==="win32"&&!X.toLowerCase().endsWith(".exe"))return`${X}.exe`;return X}function o(G,J,X){return q.join(X??c(),G,L(G,J))}async function E(G,J){if(!J.versionMatcher)return!0;return new Promise((X)=>{let Y=_(G,J.versionArgs??["--version"],{stdio:["ignore","pipe","pipe"]}),K="";Y.stdout.on("data",(H)=>K+=H.toString()),Y.stderr.on("data",(H)=>K+=H.toString()),Y.on("close",()=>{try{X(new RegExp(J.versionMatcher).test(K))}catch{X(!1)}}),Y.on("error",()=>X(!1))})}async function i(G){let J=G.platform??n(),X=L(G.name,G.binaryName),Y=o(G.name,G.binaryName,G.cacheRoot);if(u(Y)&&await E(Y,G))return Y;try{let H=typeof Bun<"u"&&typeof Bun.which==="function"?Bun.which(G.binaryName??G.name,{PATH:process.env.PATH}):null;if(H&&await E(H,G))return G.log?.info?.(`[install] using PATH binary ${G.name} (${H})`),H}catch{}let K=G.downloads[J];if(!K)throw Error(`[install] no download manifest entry for ${G.name} on ${J}`);return G.log?.info?.(`[install] downloading ${G.name} for ${J}`),await V.mkdir(q.dirname(Y),{recursive:!0}),await a(K,Y,X,G.name),G.log?.info?.(`[install] installed ${G.name} \u2192 ${Y}`),Y}async function a(G,J,X,Y){let K=q.dirname(J),H=q.join(p(),`vibe-install-${Y}-${process.pid}`);await V.mkdir(H,{recursive:!0});let $=q.join(H,"artifact");try{let Z=await fetch(G.url,{redirect:"follow"});if(!Z.ok)throw Error(`download failed (${Z.status}) for ${G.url}`);if(!Z.body)throw Error(`empty response body for ${G.url}`);if(await l(d.fromWeb(Z.body),h($)),G.sha256){let I=f("sha256").update(await V.readFile($)).digest("hex");if(I!==G.sha256)throw Error(`sha256 mismatch for ${Y}: expected ${G.sha256}, got ${I}`)}let z=G.archive??(G.url.endsWith(".tar.gz")||G.url.endsWith(".tgz")?"tar.gz":G.url.endsWith(".zip")?"zip":"raw");if(z==="raw")await V.copyFile($,J);else{if(z==="tar.gz")await w("tar",["-xzf",$,"-C",H]);else await s($,H);let I=G.binaryWithinArchive??X;await V.copyFile(q.join(H,I),J)}if(process.platform!=="win32")await V.chmod(J,493)}finally{await V.rm(H,{recursive:!0,force:!0})}}async function s(G,J){try{await w("unzip",["-q","-o",G,"-d",J]);return}catch(X){if(process.platform!=="win32")throw X;await w("tar",["-xf",G,"-C",J])}}async function w(G,J){return new Promise((X,Y)=>{let K=_(G,J,{stdio:["ignore","ignore","pipe"]}),H="";K.stderr.on("data",($)=>H+=$.toString()),K.on("close",($)=>$===0?X():Y(Error(`${G} exit ${$}: ${H}`))),K.on("error",Y)})}var W="https://github.com/cloudflare/cloudflared/releases/latest/download",r={"linux-x64":{url:`${W}/cloudflared-linux-amd64`,archive:"raw"},"linux-arm64":{url:`${W}/cloudflared-linux-arm64`,archive:"raw"},"darwin-x64":{url:`${W}/cloudflared-darwin-amd64.tgz`,archive:"tar.gz",binaryWithinArchive:"cloudflared"},"darwin-arm64":{url:`${W}/cloudflared-darwin-arm64.tgz`,archive:"tar.gz",binaryWithinArchive:"cloudflared"},"win32-x64":{url:`${W}/cloudflared-windows-amd64.exe`,archive:"raw"},"win32-arm64":{url:`${W}/cloudflared-windows-arm64.exe`,archive:"raw"}},t=/(https:\/\/(?!api\.)[a-zA-Z0-9-]+\.trycloudflare\.com)/;async function N(G,J){let X=J?.log??{},Y;try{Y=await i({name:"cloudflared",downloads:r,versionMatcher:"cloudflared version",log:X})}catch($){return X.warn?.(`quick-tunnel: could not obtain cloudflared: ${String($)}`),null}let K;try{K=_(Y,["tunnel","--url",`http://127.0.0.1:${G}`,"--no-autoupdate"],{stdio:["ignore","pipe","pipe"]})}catch($){return X.warn?.(`quick-tunnel: failed to spawn cloudflared: ${String($)}`),null}let H=await new Promise(($)=>{let Z=!1,z=(Q)=>{if(Z)return;Z=!0,$(Q)},I=setTimeout(()=>{X.warn?.("quick-tunnel: cloudflared did not advertise a URL in time"),z(null)},J?.timeoutMs??30000),O=(Q)=>{let B=Q.toString("utf8").match(t);if(B)clearTimeout(I),z(B[0])};K.stdout?.on("data",O),K.stderr?.on("data",O),K.on("error",(Q)=>{clearTimeout(I),X.warn?.(`quick-tunnel: cloudflared failed to spawn: ${String(Q)}`),z(null)}),K.on("exit",(Q)=>{clearTimeout(I),X.warn?.(`quick-tunnel: cloudflared exited (code=${Q})`),z(null)})});if(!H)return null;return{url:H,child:K}}import{existsSync as b,mkdirSync as e,readFileSync as GG,writeFileSync as JG,unlinkSync as XG}from"fs";import{dirname as YG,join as S}from"path";import{readdirSync as $G}from"fs";function T(G){return S(G??x(),"tunnel.state.json")}function v(G,J){let X=T(J);try{e(YG(X),{recursive:!0}),JG(X,JSON.stringify(G,null,2),"utf8")}catch(Y){M().logger.warn("tunnel-state","Failed to persist tunnel state",{error:String(Y)})}}function k(G){let J=T(G);if(!b(J))return null;try{let X=GG(J,"utf8"),Y=JSON.parse(X);if(typeof Y.pid!=="number")return null;return Y}catch(X){return M().logger.warn("tunnel-state","Failed to read tunnel state",{error:String(X)}),null}}function F(G){let J=T(G);if(!b(J))return;try{XG(J)}catch{}}function C(G){return R().isProcessAlive(G)}function xG(G){let J=[];if(G?.allProfiles){let Y;try{Y=A()}catch{return J}let K;try{K=$G(Y)}catch{return J}for(let H of K){let $=S(Y,H),Z=k($);if(Z)J.push({...Z,alive:C(Z.pid),profileDir:$})}return J}let X=k();if(X)J.push({...X,alive:C(X.pid),profileDir:x()});return J}function HG(G){return G.replace(/[^A-Za-z0-9_]/g,"_")}function U(){return(g()??M()).tunnel}async function AG(G,J){let X=U();MG(G),KG();let Y=process.env.AGENT_TUNNEL_URL;if(Y){let $=P(Y);if(!$)return M().logger.warn("tunnel-bootstrap","Ignoring invalid AGENT_TUNNEL_URL"),null;X.url=$,X.externalUrl=!0,M().logger.info("tunnel-bootstrap",`Using AGENT_TUNNEL_URL=${$}`);try{j.emit("tunnel.url_assigned",{provider:"external"})}catch{}return $}let K=J.port,H=await N(K,{log:{info:($)=>M().logger.info("tunnel-bootstrap",$),warn:($)=>M().logger.warn("tunnel-bootstrap",$)}});if(!H)return M().logger.warn("tunnel-bootstrap","No bootstrap tunnel \u2014 the agent will register once the tunnel provider starts post-config"),null;if(X.child=H.child,X.url=H.url,X.url){M().logger.info("tunnel-bootstrap",`Bootstrap tunnel ready: ${X.url}`);try{let z=new URL(X.url).hostname.split(".");if(z.length>=2)D("."+z.slice(-2).join("."))}catch{}try{j.emit("tunnel.url_assigned",{provider:"bootstrap"})}catch{}let $=HG(y());if(process.env[`AGENT_TUNNEL_URL_${$}`]=X.url,X.child?.pid!==void 0)process.env[`AGENT_TUNNEL_PID_${$}`]=String(X.child.pid),v({pid:X.child.pid,url:X.url,startedAt:new Date().toISOString(),provider:"bootstrap",port:K,cmd:`cloudflared tunnel --url http://127.0.0.1:${K}`})}return X.url}function bG(){let G=U();if(G.externalUrl)return!1;if(!G.child||G.child.killed)return!1;let J=G.child.pid;if(J===void 0)return!1;try{process.kill(J,0)}catch{return!1}return G.child=null,F(),M().logger.info("tunnel-bootstrap",`Handed over bootstrap tunnel (PID ${J}) to plugin \u2014 process kept alive`),!0}function SG(){let G=U();if(G.externalUrl){F();return}let J=G.child;if(G.child=null,F(),!J||J.killed)return;try{J.kill("SIGTERM"),M().logger.info("tunnel-bootstrap","Bootstrap tunnel stopped")}catch{}}function vG(){return U().url}function KG(){let G=k();if(!G)return;if(!C(G.pid)){F();return}try{process.kill(G.pid,"SIGTERM"),M().logger.info("tunnel-bootstrap","Reaped orphan tunnel from prior run",{pid:G.pid,provider:G.provider})}catch{}let J=Date.now();while(Date.now()-J<2000&&C(G.pid))Bun.sleepSync(50);if(C(G.pid))try{process.kill(G.pid,"SIGKILL")}catch{}F()}function MG(G){let J={name:"bootstrap",async getActiveTunnelUrl(){return U().url}};G.registerProvider("tunnel",J,"bootstrap")}
2
+ import{Xa as R}from"./index-0ckffygp.js";import{bb as j}from"./index-jrtsdm8f.js";import{Bd as D,Ed as P,Ld as g,Od as M}from"./index-xnr6t79p.js";import{$d as x,Yd as y,ae as A}from"./index-a4854mwz.js";import{spawn as _}from"child_process";import{createHash as f}from"crypto";import{existsSync as u,promises as V,createWriteStream as h}from"fs";import{homedir as m,tmpdir as p}from"os";import*as q from"path";import{Readable as d}from"stream";import{pipeline as l}from"stream/promises";function n(){let G=process.arch==="x64"?"x64":"arm64";return`${process.platform==="win32"?"win32":process.platform==="darwin"?"darwin":"linux"}-${G}`}function c(){return q.join(m(),".boff","vibecontrols","tools")}function L(G,J){let X=J??G;if(process.platform==="win32"&&!X.toLowerCase().endsWith(".exe"))return`${X}.exe`;return X}function o(G,J,X){return q.join(X??c(),G,L(G,J))}async function E(G,J){if(!J.versionMatcher)return!0;return new Promise((X)=>{let Y=_(G,J.versionArgs??["--version"],{stdio:["ignore","pipe","pipe"]}),K="";Y.stdout.on("data",(H)=>K+=H.toString()),Y.stderr.on("data",(H)=>K+=H.toString()),Y.on("close",()=>{try{X(new RegExp(J.versionMatcher).test(K))}catch{X(!1)}}),Y.on("error",()=>X(!1))})}async function i(G){let J=G.platform??n(),X=L(G.name,G.binaryName),Y=o(G.name,G.binaryName,G.cacheRoot);if(u(Y)&&await E(Y,G))return Y;try{let H=typeof Bun<"u"&&typeof Bun.which==="function"?Bun.which(G.binaryName??G.name,{PATH:process.env.PATH}):null;if(H&&await E(H,G))return G.log?.info?.(`[install] using PATH binary ${G.name} (${H})`),H}catch{}let K=G.downloads[J];if(!K)throw Error(`[install] no download manifest entry for ${G.name} on ${J}`);return G.log?.info?.(`[install] downloading ${G.name} for ${J}`),await V.mkdir(q.dirname(Y),{recursive:!0}),await a(K,Y,X,G.name),G.log?.info?.(`[install] installed ${G.name} \u2192 ${Y}`),Y}async function a(G,J,X,Y){let K=q.dirname(J),H=q.join(p(),`vibe-install-${Y}-${process.pid}`);await V.mkdir(H,{recursive:!0});let $=q.join(H,"artifact");try{let Z=await fetch(G.url,{redirect:"follow"});if(!Z.ok)throw Error(`download failed (${Z.status}) for ${G.url}`);if(!Z.body)throw Error(`empty response body for ${G.url}`);if(await l(d.fromWeb(Z.body),h($)),G.sha256){let I=f("sha256").update(await V.readFile($)).digest("hex");if(I!==G.sha256)throw Error(`sha256 mismatch for ${Y}: expected ${G.sha256}, got ${I}`)}let z=G.archive??(G.url.endsWith(".tar.gz")||G.url.endsWith(".tgz")?"tar.gz":G.url.endsWith(".zip")?"zip":"raw");if(z==="raw")await V.copyFile($,J);else{if(z==="tar.gz")await w("tar",["-xzf",$,"-C",H]);else await s($,H);let I=G.binaryWithinArchive??X;await V.copyFile(q.join(H,I),J)}if(process.platform!=="win32")await V.chmod(J,493)}finally{await V.rm(H,{recursive:!0,force:!0})}}async function s(G,J){try{await w("unzip",["-q","-o",G,"-d",J]);return}catch(X){if(process.platform!=="win32")throw X;await w("tar",["-xf",G,"-C",J])}}async function w(G,J){return new Promise((X,Y)=>{let K=_(G,J,{stdio:["ignore","ignore","pipe"]}),H="";K.stderr.on("data",($)=>H+=$.toString()),K.on("close",($)=>$===0?X():Y(Error(`${G} exit ${$}: ${H}`))),K.on("error",Y)})}var W="https://github.com/cloudflare/cloudflared/releases/latest/download",r={"linux-x64":{url:`${W}/cloudflared-linux-amd64`,archive:"raw"},"linux-arm64":{url:`${W}/cloudflared-linux-arm64`,archive:"raw"},"darwin-x64":{url:`${W}/cloudflared-darwin-amd64.tgz`,archive:"tar.gz",binaryWithinArchive:"cloudflared"},"darwin-arm64":{url:`${W}/cloudflared-darwin-arm64.tgz`,archive:"tar.gz",binaryWithinArchive:"cloudflared"},"win32-x64":{url:`${W}/cloudflared-windows-amd64.exe`,archive:"raw"},"win32-arm64":{url:`${W}/cloudflared-windows-arm64.exe`,archive:"raw"}},t=/(https:\/\/(?!api\.)[a-zA-Z0-9-]+\.trycloudflare\.com)/;async function N(G,J){let X=J?.log??{},Y;try{Y=await i({name:"cloudflared",downloads:r,versionMatcher:"cloudflared version",log:X})}catch($){return X.warn?.(`quick-tunnel: could not obtain cloudflared: ${String($)}`),null}let K;try{K=_(Y,["tunnel","--url",`http://127.0.0.1:${G}`,"--no-autoupdate"],{stdio:["ignore","pipe","pipe"]})}catch($){return X.warn?.(`quick-tunnel: failed to spawn cloudflared: ${String($)}`),null}let H=await new Promise(($)=>{let Z=!1,z=(Q)=>{if(Z)return;Z=!0,$(Q)},I=setTimeout(()=>{X.warn?.("quick-tunnel: cloudflared did not advertise a URL in time"),z(null)},J?.timeoutMs??30000),O=(Q)=>{let B=Q.toString("utf8").match(t);if(B)clearTimeout(I),z(B[0])};K.stdout?.on("data",O),K.stderr?.on("data",O),K.on("error",(Q)=>{clearTimeout(I),X.warn?.(`quick-tunnel: cloudflared failed to spawn: ${String(Q)}`),z(null)}),K.on("exit",(Q)=>{clearTimeout(I),X.warn?.(`quick-tunnel: cloudflared exited (code=${Q})`),z(null)})});if(!H)return null;return{url:H,child:K}}import{existsSync as b,mkdirSync as e,readFileSync as GG,writeFileSync as JG,unlinkSync as XG}from"fs";import{dirname as YG,join as S}from"path";import{readdirSync as $G}from"fs";function T(G){return S(G??x(),"tunnel.state.json")}function v(G,J){let X=T(J);try{e(YG(X),{recursive:!0}),JG(X,JSON.stringify(G,null,2),"utf8")}catch(Y){M().logger.warn("tunnel-state","Failed to persist tunnel state",{error:String(Y)})}}function k(G){let J=T(G);if(!b(J))return null;try{let X=GG(J,"utf8"),Y=JSON.parse(X);if(typeof Y.pid!=="number")return null;return Y}catch(X){return M().logger.warn("tunnel-state","Failed to read tunnel state",{error:String(X)}),null}}function F(G){let J=T(G);if(!b(J))return;try{XG(J)}catch{}}function C(G){return R().isProcessAlive(G)}function xG(G){let J=[];if(G?.allProfiles){let Y;try{Y=A()}catch{return J}let K;try{K=$G(Y)}catch{return J}for(let H of K){let $=S(Y,H),Z=k($);if(Z)J.push({...Z,alive:C(Z.pid),profileDir:$})}return J}let X=k();if(X)J.push({...X,alive:C(X.pid),profileDir:x()});return J}function HG(G){return G.replace(/[^A-Za-z0-9_]/g,"_")}function U(){return(g()??M()).tunnel}async function AG(G,J){let X=U();MG(G),KG();let Y=process.env.AGENT_TUNNEL_URL;if(Y){let $=P(Y);if(!$)return M().logger.warn("tunnel-bootstrap","Ignoring invalid AGENT_TUNNEL_URL"),null;X.url=$,X.externalUrl=!0,M().logger.info("tunnel-bootstrap",`Using AGENT_TUNNEL_URL=${$}`);try{j.emit("tunnel.url_assigned",{provider:"external"})}catch{}return $}let K=J.port,H=await N(K,{log:{info:($)=>M().logger.info("tunnel-bootstrap",$),warn:($)=>M().logger.warn("tunnel-bootstrap",$)}});if(!H)return M().logger.warn("tunnel-bootstrap","No bootstrap tunnel \u2014 the agent will register once the tunnel provider starts post-config"),null;if(X.child=H.child,X.url=H.url,X.url){M().logger.info("tunnel-bootstrap",`Bootstrap tunnel ready: ${X.url}`);try{let z=new URL(X.url).hostname.split(".");if(z.length>=2)D("."+z.slice(-2).join("."))}catch{}try{j.emit("tunnel.url_assigned",{provider:"bootstrap"})}catch{}let $=HG(y());if(process.env[`AGENT_TUNNEL_URL_${$}`]=X.url,X.child?.pid!==void 0)process.env[`AGENT_TUNNEL_PID_${$}`]=String(X.child.pid),v({pid:X.child.pid,url:X.url,startedAt:new Date().toISOString(),provider:"bootstrap",port:K,cmd:`cloudflared tunnel --url http://127.0.0.1:${K}`})}return X.url}function bG(){let G=U();if(G.externalUrl)return!1;if(!G.child||G.child.killed)return!1;let J=G.child.pid;if(J===void 0)return!1;try{process.kill(J,0)}catch{return!1}return G.child=null,F(),M().logger.info("tunnel-bootstrap",`Handed over bootstrap tunnel (PID ${J}) to plugin \u2014 process kept alive`),!0}function SG(){let G=U();if(G.externalUrl){F();return}let J=G.child;if(G.child=null,F(),!J||J.killed)return;try{J.kill("SIGTERM"),M().logger.info("tunnel-bootstrap","Bootstrap tunnel stopped")}catch{}}function vG(){return U().url}function KG(){let G=k();if(!G)return;if(!C(G.pid)){F();return}try{process.kill(G.pid,"SIGTERM"),M().logger.info("tunnel-bootstrap","Reaped orphan tunnel from prior run",{pid:G.pid,provider:G.provider})}catch{}let J=Date.now();while(Date.now()-J<2000&&C(G.pid))Bun.sleepSync(50);if(C(G.pid))try{process.kill(G.pid,"SIGKILL")}catch{}F()}function MG(G){let J={name:"bootstrap",async getActiveTunnelUrl(){return U().url}};G.registerProvider("tunnel",J,"bootstrap")}
3
3
  export{k as la,F as ma,C as na,xG as oa,HG as pa,AG as qa,bG as ra,SG as sa,vG as ta,KG as ua};
@@ -0,0 +1,158 @@
1
+ // @bun
2
+ import{d as m,e as H2}from"./index-z73x3sdf.js";import{z as c}from"./index-9bdbnx8f.js";import"./index-wetsgcyq.js";import"./index-c6xa5nd4.js";import"./index-4wgjx8bf.js";import{Ja as Z2,Ka as $2,La as z2,Na as W2,Ta as d}from"./index-cfa3pgh5.js";import"./index-0ckffygp.js";import"./index-6p3gcnxr.js";import"./index-bfeekmyh.js";import{Rb as X2,Sb as Y2}from"./index-5dysvvjv.js";import{Ub as J,Vb as V2}from"./index-pgew6sge.js";import{jc as l,kc as t,lc as R}from"./index-8nqp3a4d.js";import{oc as k,qc as q,rc as O,sc as S,tc as I,uc as _,vc as u,wc as A,yc as i}from"./index-85ke6hng.js";import{Gc as s,Hc as G2}from"./index-thammzct.js";import{Lc as U,Nc as E,Oc as n,Pc as h}from"./index-t8tnkqxh.js";import"./index-63ba5fb4.js";import{Od as y}from"./index-xnr6t79p.js";import"./index-a4854mwz.js";import"./index-4qq083yd.js";import{ie as L}from"./index-c7554sg7.js";import{timingSafeEqual as j2}from"crypto";function U2(){return(process.env.NPM_CONFIG_REGISTRY||process.env.npm_config_registry||"https://registry.npmjs.org").replace(/\/+$/,"")}async function a(V,B){try{let z=await fetch(`${U2()}/${V}/${B}`,{headers:{accept:"application/json"},signal:AbortSignal.timeout(1e4)});if(z.ok){let Q=(await z.json()).dist?.integrity;if(typeof Q==="string"&&Q.startsWith("sha"))return Q}}catch{}try{let z=Bun.spawn({cmd:["npm","view",`${V}@${B}`,"dist.integrity","--json"],stdout:"pipe",stderr:"pipe"});if(await z.exited!==0)return null;let X=(await new Response(z.stdout).text()).trim();if(!X)return null;if(X.startsWith('"'))try{let $=JSON.parse(X);return typeof $==="string"?$:null}catch{return null}return X}catch{return null}}function e(V,B){let z=Buffer.from(V),K=Buffer.from(B);if(z.length!==K.length)return!1;try{return j2(z,K)}catch{return!1}}var h2=$2.map((V)=>({packageName:V.packageName,name:V.pluginName,description:V.description,cliCommand:V.cliCommand,apiPrefix:V.apiPrefix,installed:!1,category:V.category})),N=new Map;function w(V,B){let K=(N.get(V)??Promise.resolve()).then(B,B),Q=K.then(()=>{return},()=>{return});return N.set(V,Q),Q.finally(()=>{if(N.get(V)===Q)N.delete(V)}),K}function K2(V){return N.has(V)}function Q2(V){let B=V.getPluginDetails(),z=new Set(B.map((K)=>K.packageName));return{plugins:h2.map((K)=>({...K,installed:z.has(K.packageName)}))}}function B2(V){let{pluginManager:B}=V;return new V2().get("/",()=>{let z=B.getPluginDetails();return{plugins:z,count:z.length}}).get("/available",()=>Q2(B)).get("/catalog",()=>Q2(B)).get("/contributions",({query:z})=>{let K=typeof z?.mountPoint==="string"&&z.mountPoint?z.mountPoint:null,Q=[],X=new Map;for(let $ of B.getPluginDetails())X.set($.pluginName,$.packageName);for(let $ of B.getAllPlugins()){let x=$.ui;if(!x||!x.contributions||x.contributions.length===0)continue;let Y=x.capabilities??{restPaths:[],wsTopics:[],rpcMethods:[]};for(let W of x.contributions){if(K&&W.mountPoint!==K)continue;let Z=W.meta,H=Z&&typeof Z.url==="string"?Z.url:null,F=H&&H.startsWith("/")&&!H.startsWith("//")&&!H.includes("\x00")&&!H.includes("..")?H:null;Q.push({pluginKey:$.name,pluginPackageName:X.get($.name),contribution:W,capabilities:W.capabilities??Y,url:F??`/ui/${encodeURIComponent($.name)}`})}}return{contributions:Q,count:Q.length}}).post("/install",async({body:z,set:K})=>{if(!z.packageName||typeof z.packageName!=="string")return K.status=400,{error:"Missing required field: packageName"};if(z.packageName.startsWith("@burdenoff/"))z.packageName=z.packageName.replace(/^@burdenoff\//,"@vibecontrols/");if(!W2(z.packageName))return K.status=403,{error:"Plugin package is not in the trusted VibeControls catalog"};try{let Q=d(z.packageName);if(K2(Q)){let X=Q.split("/").pop()?.replace("vibe-plugin-","");if(B.getAllPlugins().some((x)=>x.name===X))return{success:!0,message:`Plugin ${Q} is already installed`,packageName:Q,alreadyInstalled:!0};return K.status=409,{error:"Install for this package is already in progress. Wait for it to finish.",packageName:Q}}return await w(Q,async()=>{let X=Q.split("/").pop()?.replace("vibe-plugin-",""),$=X?.startsWith("ai-")?X.slice(3):void 0,x=B.getAllPlugins().find((C)=>C.name===X||C.name===$),Y=!!x,W=await B.install(Q),Z=z2(Q);if(Z?.integrity){let C=await a(Q,W.version);if(C&&!e(Z.integrity,C)){try{await B.remove(Q,V.hostServices)}catch(G){console.warn(`[plugin-mgr] integrity rollback uninstall failed for ${Q}:`,G)}return y().audit.emit("agent","plugin.install.rejected",{packageName:Q,version:W.version,reason:"integrity_mismatch",expected:Z.integrity,actual:C}),K.status=400,{error:"integrity mismatch",expected:Z.integrity,actual:C}}if(!C)console.warn(`[plugin-mgr] could not fetch registry integrity for ${Q}@${W.version}; accepting the package-manager-verified tarball (pin present but unverifiable)`),y().audit.emit("agent","plugin.install.integrity_unverified",{packageName:Q,version:W.version,expected:Z.integrity})}else console.warn(`[plugin-mgr] plugin ${Q} has no pinned integrity \u2014 accepting npm registry's hash`);let H=B.getAllPlugins().find((C)=>C.name===W.pluginName);if(H){let C=[];if(V.mountPlugin)V.mountPlugin(H);if(V.hostServices){if(Y&&x?.onServerStop)try{await x.onServerStop()}catch(G){C.push(`onServerStop failed: ${G instanceof Error?G.message:String(G)}`)}if(B.registerProviders(H,V.hostServices),H.onServerStart&&V.app)try{await H.onServerStart(V.app,V.hostServices),B.registerProviders(H,V.hostServices)}catch(G){C.push(`onServerStart failed: ${G instanceof Error?G.message:String(G)}`)}if(H.onServerReady&&V.app)try{await H.onServerReady(V.app,V.hostServices)}catch(G){C.push(`onServerReady failed: ${G instanceof Error?G.message:String(G)}`)}}if(V.rebuildPluginSurfaces?.(),C.length>0)return K.status=500,{success:!1,message:`Plugin ${Q} installed but failed to start`,lifecycleErrors:C,restartRequired:!0}}let F;if(H&&V.app)try{F=await m(H,Q,V.app,V.db,{skipInstall:!!z.skipPrereqs})}catch(C){F=void 0,console.warn(`[plugin-mgr] prereq run failed for ${Q}:`,C)}return c(V.db),y().audit.emit("agent","plugin.installed",{packageName:Q,version:W.version,pluginName:W.pluginName,wasRunning:Y}),{success:!0,message:`Plugin ${Q} installed and loaded successfully`,prereqs:F?{satisfied:F.satisfied,missing:F.status?.missing??[],pendingSudo:F.pendingSudo,skipped:!!z.skipPrereqs}:void 0}})}catch(Q){return K.status=500,{error:"Failed to install plugin",details:String(Q)}}},{body:J.Object({packageName:J.String(),skipPrereqs:J.Optional(J.Boolean())})}).post("/prereqs/status",async({body:z,set:K})=>{if(!z.packageName)return K.status=400,{error:"Missing packageName"};let Q=z.packageName,X=B.getAllPlugins().find(($)=>$.name===Q||B.getLoaded(Q)?.name===$.name);if(!X||!V.app)return await H2(V.db,Q)??{satisfied:!0,missing:[]};try{let $=await m(X,Q,V.app,V.db,{skipInstall:!0});return{satisfied:$.satisfied,missing:$.status?.missing??[],noProtocol:$.noProtocol}}catch($){return K.status=500,{error:String($)}}},{body:J.Object({packageName:J.String()})}).post("/prereqs/install",async({body:z,set:K})=>{if(!z.packageName)return K.status=400,{error:"Missing packageName"};let Q=z.packageName,X=B.getAllPlugins().find(($)=>$.name===Q||B.getLoaded(Q)?.name===$.name);if(!X||!V.app)return K.status=404,{error:"Plugin not loaded"};try{let $=await m(X,Q,V.app,V.db,{skipInstall:!1});return{satisfied:$.satisfied,installed:$.install?.installed??[],pendingSudo:$.pendingSudo,errors:$.install?.errors??[],noProtocol:$.noProtocol}}catch($){return K.status=500,{error:String($)}}},{body:J.Object({packageName:J.String(),approveSudo:J.Optional(J.Boolean())})}).post("/prereqs/uninstall",async({body:z,set:K})=>{if(!z.packageName)return K.status=400,{error:"Missing packageName"};let Q=z.packageName,X=B.getAllPlugins().find((W)=>W.name===Q);if(!X||!X.apiPrefix||!V.app)return K.status=404,{error:"Plugin not loaded"};let $=V.app.handle;if(typeof $!=="function")return K.status=500,{error:"App handle unavailable"};let x=`${X.apiPrefix.replace(/\/+$/,"")}/prereqs/uninstall`,Y=await $.call(V.app,new Request(`http://agent.local${x}`,{method:"POST",headers:{"x-vc-profile-rewrite":"1",[X2]:Y2()}}));if(Y.status===404)return K.status=404,{error:"Plugin has no prereqs/uninstall endpoint"};return Y.json()},{body:J.Object({packageName:J.String()})}).post("/nuke",async({body:z,set:K})=>{if(!V.hostServices)return K.status=503,{error:"hostServices unavailable"};let Q=V.hostServices.getDataDir?.();return{ok:!0,...await B.runPluginNuke(z.packageName,V.hostServices,{agentDir:Q,dryRun:!!z.dryRun})}},{body:J.Object({packageName:J.Optional(J.String()),dryRun:J.Optional(J.Boolean())})}).post("/remove",async({body:z,set:K})=>{if(!z.packageName||typeof z.packageName!=="string")return K.status=400,{error:"Missing required field: packageName"};if(z.packageName.startsWith("@burdenoff/"))z.packageName=z.packageName.replace(/^@burdenoff\//,"@vibecontrols/");if(Z2(z.packageName))return{success:!0,message:`Plugin ${z.packageName} is critical and cannot be removed; treating remove as a no-op.`,skipped:!0};try{let Q=d(z.packageName);return await w(Q,async()=>{return await B.remove(Q,V.hostServices),V.rebuildPluginSurfaces?.(),c(V.db),y().audit.emit("agent","plugin.removed",{packageName:Q}),{success:!0,message:`Plugin ${Q} removed successfully`}})}catch(Q){return K.status=500,{error:"Failed to remove plugin",details:String(Q)}}},{body:J.Object({packageName:J.String()})}).post("/update",async({body:z,set:K})=>{if(!z.packageName||typeof z.packageName!=="string")return K.status=400,{error:"Missing required field: packageName"};let Q=typeof z.version==="string"&&z.version.trim()?z.version.trim():void 0;if(Q&&!/^[0-9][0-9A-Za-z.+-]{0,63}$/.test(Q))return K.status=400,{error:`Invalid version "${Q}"`};try{let X=d(z.packageName);return await w(X,async()=>{let $=B.getLoaded(X);if($?.onServerStop)await $.onServerStop({reason:"reload"});if($&&V.hostServices)V.hostServices.serviceRegistry.unregisterPlugin($.name);let x=await B.update(X,Q),Y=B.getLoaded(X);if(Y&&V.hostServices){if(B.registerProviders(Y,V.hostServices),Y.onServerStart&&V.app)await Y.onServerStart(V.app,V.hostServices),B.registerProviders(Y,V.hostServices);if(Y.onServerReady&&V.app)await Y.onServerReady(V.app,V.hostServices)}return V.rebuildPluginSurfaces?.(),c(V.db),{success:!0,message:`Plugin ${X} updated to v${x.version}`,version:x.version}})}catch(X){return K.status=500,{error:"Failed to update plugin",details:String(X)}}},{body:J.Object({packageName:J.String(),version:J.Optional(J.String())})}).post("/update-all",async({set:z})=>{try{let K=await w("*",()=>B.updateAll());return{success:!0,results:K,message:`Updated ${K.filter((Q)=>Q.success).length}/${K.length} plugin(s)`}}catch(K){return z.status=500,{error:"Failed to update all plugins",details:String(K)}}}).post("/remove-all",async({set:z})=>{try{let K=await w("*",async()=>{let Q=await B.removeAll(V.hostServices);return V.rebuildPluginSurfaces?.(),Q});return{success:!0,results:K,message:`Removed ${K.filter((Q)=>Q.success).length}/${K.length} plugin(s)`}}catch(K){return z.status=500,{error:"Failed to remove all plugins",details:String(K)}}}).post("/reload",async({set:z})=>{try{if(!V.app||!V.hostServices)return z.status=503,{error:"Plugin lifecycle services are not ready"};let K=await w("*",async()=>{return await B.reloadAll(V.app,V.hostServices),V.rebuildPluginSurfaces?.(),B.getPluginDetails()});return{success:!0,plugins:K,message:`Reloaded ${K.length} plugin(s)`}}catch(K){return z.status=500,{error:"Failed to reload plugins",details:String(K)}}}).post("/:name/reload",async({params:z,set:K})=>{if(!V.app||!V.hostServices)return K.status=503,{error:"Plugin lifecycle services are not ready"};let Q=z.name,X=B.getAllPlugins().find((Y)=>Y.name===Q);if(!X)return K.status=404,{error:`Plugin "${Q}" not found`};let x=B.getPluginDetails().find((Y)=>Y.pluginName===Q)?.packageName??`core:${Q}`;if(K2(x))return K.status=409,{error:"Plugin lifecycle in progress; try again shortly",packageName:x};try{return await w(x,async()=>{if(X.onServerStop)try{await X.onServerStop({reason:"reload"})}catch(Y){console.warn(`[plugin-mgr] onServerStop during reload of ${Q}:`,Y)}if(V.hostServices)V.hostServices.serviceRegistry.unregisterPlugin(X.name);if(B.registerProviders(X,V.hostServices),X.onServerStart)await X.onServerStart(V.app,V.hostServices),B.registerProviders(X,V.hostServices);if(X.onServerReady)await X.onServerReady(V.app,V.hostServices);return V.rebuildPluginSurfaces?.(),{success:!0,message:`Plugin ${Q} reloaded`,version:X.version}})}catch(Y){return K.status=500,{error:"Failed to reload plugin",details:String(Y)}}},{params:J.Object({name:J.String()})})}import{mkdirSync as o,writeFileSync as v,existsSync as x2}from"fs";import{isAbsolute as D2,join as T,relative as A2,resolve as g}from"path";var D="http://localhost:3005",v2=/^[a-z0-9][a-z0-9-]{0,63}$/,E2=new Set(["backend","frontend","cli","provider","adapter","integration"]);function C2(V,B){let z=A2(V,B);if(z.startsWith("..")||D2(z))throw Error("Plugin scaffold path escapes the selected directory.")}function M(V){return JSON.stringify(V)}function J2(V){let B=V.command("plugin").description("Manage plugins");B.command("list").description("List installed plugins").option("--agent-url <url>","Agent URL",D).option("--profile <name>","Target a specific profile by name").option("--json","Emit JSON").option("--plain","Force plain text output").action(async(K)=>{try{let Q={...V.opts(),...K},X=U(K),$=encodeURIComponent(E(Q)),x=async()=>{try{return(await n(X,`/api/profiles/${$}/plugins`)).plugins||[]}catch{I("Agent not reachable. Attempting local plugin registry...");let{PluginManager:Z}=await import("./plugin-system-f47jdx66.js");return new Z().getPluginDetails()||[]}},Y=(Z)=>Z.status??(Z.loaded===!0||Z.enabled===!0?"enabled":"disabled"),W=(Z)=>Z.pluginName||Z.name||Z.packageName||Z.package||"-";await t({mode:l(Q),fetchData:x,plain:(Z)=>{if(!Z.length){_("No plugins installed.");return}u("Installed Plugins"),i(Z.map((H)=>({Name:W(H),Version:H.version||"-",Status:Y(H),Description:H.description||"-"})))},interactive:async(Z)=>{if(!Z.length){u("Installed Plugins"),_("No plugins installed.");return}let H=Z.map((F)=>{let C=W(F),G=Y(F),b=[`${k.bold(C)} ${G==="enabled"?k.green(G):k.dim(G)}`,"",` Version: ${F.version||"-"}`,` Description: ${F.description||"-"}`];if(F.tags&&Array.isArray(F.tags))b.push(` Tags: ${F.tags.join(", ")}`);if(F.cliCommand)b.push(` CLI command: vibe ${F.cliCommand}`);return{id:C,label:C,hint:G,detail:b.join(`
3
+ `)}});await s({title:`vibe plugin \u2014 ${Z.length} installed`,rows:H,footer:"\u2191/\u2193 navigate \xB7 q to quit"})},json:(Z)=>Z.map((H)=>({name:W(H),version:H.version??null,status:Y(H),description:H.description??null,tags:H.tags??null,cliCommand:H.cliCommand??null}))})}catch(Q){q(O(Q))}}),B.command("install").description("Install a plugin").argument("<package>","NPM package name to install").option("--agent-url <url>","Agent URL",D).option("--profile <name>","Target a specific profile by name").option("--skip-prereqs","Skip running the plugin's prereqs/install",!1).option("--json","Emit JSON result").action(async(K,Q)=>{try{let X={...V.opts(),...Q},$=U(Q),x=encodeURIComponent(E(X));try{let Y=await h($,`/api/profiles/${x}/plugins/install`,{packageName:K,skipPrereqs:!!Q.skipPrereqs});if(R(X,{ok:!0,action:"install",package:K,version:Y?.version??null,prereqs:Y?.prereqs??null}))return;if(S(`Plugin "${K}" installed.`),Y?.version)A("Version",Y.version);if(Y?.prereqs){let W=Y.prereqs;if(W.skipped)I(`Prerequisite install skipped. Run \`vibe plugin prereqs ${K} install\` later.`);else if(!W.satisfied)I(`Prerequisites not yet satisfied: ${(W.missing||[]).map((Z)=>Z.name).join(", ")||"(unknown)"}`);if((W.pendingSudo||[]).length>0){I(`${W.pendingSudo.length} command(s) need sudo. Run them and re-check with \`vibe plugin prereqs ${K} status\`:`);for(let Z of W.pendingSudo)A(` ${Z.name}`,Z.command)}}}catch{I("Agent not reachable. Attempting local install...");try{let{PluginManager:Y}=await import("./plugin-system-f47jdx66.js");if(await new Y().install(K),R(X,{ok:!0,action:"install",package:K,local:!0}))return;S(`Plugin "${K}" installed locally.`)}catch(Y){q(`Could not install plugin via agent or locally: ${O(Y)}`)}}}catch(X){q(O(X))}}),B.command("remove").description("Remove a plugin").argument("<package>","NPM package name to remove").option("--agent-url <url>","Agent URL",D).option("--profile <name>","Target a specific profile by name").option("--json","Emit JSON result").action(async(K,Q)=>{try{let X={...V.opts(),...Q},$=U(Q),x=encodeURIComponent(E(X));try{if(await h($,`/api/profiles/${x}/plugins/remove`,{packageName:K}),R(X,{ok:!0,action:"remove",package:K}))return;S(`Plugin "${K}" removed.`)}catch{I("Agent not reachable. Attempting local removal...");try{let{PluginManager:Y}=await import("./plugin-system-f47jdx66.js");if(await new Y().remove(K),R(X,{ok:!0,action:"remove",package:K,local:!0}))return;S(`Plugin "${K}" removed locally.`)}catch(Y){q(`Could not remove plugin via agent or locally: ${O(Y)}`)}}}catch(X){q(O(X))}}),B.command("update").description("Update a plugin (or all plugins with --all)").argument("[package]","NPM package name to update").option("--all","Update all installed plugins",!1).option("--agent-url <url>","Agent URL",D).option("--profile <name>","Target a specific profile by name").option("--json","Emit JSON result").action(async(K,Q)=>{try{let X={...V.opts(),...Q},$=U(Q),x=encodeURIComponent(E(X));if(Q.all){_("Updating all plugins...");try{let Y=await h($,`/api/profiles/${x}/plugins/update-all`,{}),W=Y?.results||[];if(R(X,{ok:!0,action:"update-all",results:W}))return;for(let Z of W)if(Z.success)S(`Updated ${Z.packageName}${Z.version?` to v${Z.version}`:""}`);else I(`Failed to update ${Z.packageName}: ${Z.error}`);S(Y?.message||"Done.")}catch{I("Agent not reachable. Attempting local update...");try{let{PluginManager:Y}=await import("./plugin-system-f47jdx66.js"),Z=await new Y().updateAll();if(R(X,{ok:!0,action:"update-all",results:Z,local:!0}))return;for(let H of Z)if(H.success)S(`Updated ${H.packageName}${H.version?` to v${H.version}`:""}`);else I(`Failed to update ${H.packageName}: ${H.error}`)}catch(Y){q(`Could not update plugins: ${O(Y)}`)}}}else if(K){_(`Updating ${K}...`);try{let Y=await h($,`/api/profiles/${x}/plugins/update`,{packageName:K});if(R(X,{ok:!0,action:"update",package:K,version:Y?.version??null,message:Y?.message??null}))return;S(Y?.message||`Plugin "${K}" updated.`)}catch{I("Agent not reachable. Attempting local update...");try{let{PluginManager:Y}=await import("./plugin-system-f47jdx66.js"),Z=await new Y().update(K);if(R(X,{ok:!0,action:"update",package:K,version:Z.version,local:!0}))return;S(`Plugin "${K}" updated to v${Z.version}.`)}catch(Y){q(`Could not update plugin: ${O(Y)}`)}}}else q("Provide a package name to update, or use --all to update all plugins.")}catch(X){q(O(X))}}),B.command("uninstall").description("Uninstall a plugin (or all plugins with --all)").argument("[package]","NPM package name to uninstall").option("--all","Uninstall all external plugins",!1).option("--agent-url <url>","Agent URL",D).option("--profile <name>","Target a specific profile by name").option("--json","Emit JSON result").action(async(K,Q)=>{try{let X={...V.opts(),...Q},$=U(Q),x=encodeURIComponent(E(X));if(Q.all){_("Uninstalling all plugins...");try{let Y=await h($,`/api/profiles/${x}/plugins/remove-all`,{}),W=Y?.results||[];if(R(X,{ok:!0,action:"uninstall-all",results:W}))return;for(let Z of W)if(Z.success)S(`Removed ${Z.packageName}`);else I(`Failed to remove ${Z.packageName}: ${Z.error}`);S(Y?.message||"Done.")}catch{I("Agent not reachable. Attempting local removal...");try{let{PluginManager:Y}=await import("./plugin-system-f47jdx66.js"),Z=await new Y().removeAll();if(R(X,{ok:!0,action:"uninstall-all",results:Z,local:!0}))return;for(let H of Z)if(H.success)S(`Removed ${H.packageName}`);else I(`Failed to remove ${H.packageName}: ${H.error}`)}catch(Y){q(`Could not uninstall plugins: ${O(Y)}`)}}}else if(K)try{if(await h($,`/api/profiles/${x}/plugins/remove`,{packageName:K}),R(X,{ok:!0,action:"uninstall",package:K}))return;S(`Plugin "${K}" uninstalled.`)}catch{I("Agent not reachable. Attempting local removal...");try{let{PluginManager:Y}=await import("./plugin-system-f47jdx66.js");if(await new Y().remove(K),R(X,{ok:!0,action:"uninstall",package:K,local:!0}))return;S(`Plugin "${K}" uninstalled locally.`)}catch(Y){q(`Could not uninstall plugin: ${O(Y)}`)}}else q("Provide a package name to uninstall, or use --all to uninstall all plugins.")}catch(X){q(O(X))}}),B.command("reload").description("Reload all plugins").option("--agent-url <url>","Agent URL",D).option("--profile <name>","Target a specific profile by name").option("--json","Emit JSON result").action(async(K)=>{try{let Q={...V.opts(),...K},X=U(K),$=encodeURIComponent(E(Q));if(await h(X,`/api/profiles/${$}/plugins/reload`,{}),R(Q,{ok:!0,action:"reload"}))return;S("Plugins reloaded.")}catch(Q){q(O(Q))}}),B.command("available").description("Show available plugins").option("--agent-url <url>","Agent URL",D).option("--profile <name>","Target a specific profile by name").option("--json","Emit JSON").option("--plain","Force plain text output").action(async(K)=>{try{let Q={...V.opts(),...K},X=U(K),$=encodeURIComponent(E(Q)),x=async()=>{return(await n(X,`/api/profiles/${$}/plugins/available`)).plugins||[]},Y=(Z)=>Z.name||Z.package||"-",W=(Z)=>Z.version||Z.latestVersion||"-";await t({mode:l(Q),fetchData:x,plain:(Z)=>{if(!Z||Z.length===0){_("No available plugins found.");return}u("Available Plugins"),i(Z.map((H)=>({Name:Y(H),Version:W(H),Description:H.description||"-"})))},interactive:async(Z)=>{if(!Z||Z.length===0){u("Available Plugins"),_("No available plugins found.");return}let H=Z.map((F)=>{let C=Y(F),G=[k.bold(C),"",` Version: ${W(F)}`,` Description: ${F.description||"-"}`];return{id:C,label:C,hint:W(F),detail:G.join(`
4
+ `)}});await s({title:`vibe plugin available \u2014 ${Z.length} plugin(s)`,rows:H,footer:"\u2191/\u2193 navigate \xB7 q to quit"})},json:(Z)=>Z.map((H)=>({name:Y(H),version:W(H),description:H.description??null}))})}catch(Q){q(O(Q))}});let z=B.command("prereqs").description("Inspect or run a plugin's prerequisite-install protocol").argument("<package>","NPM package name (or short plugin name)");z.command("status",{isDefault:!0}).description("Show the plugin's prereq status").option("--agent-url <url>","Agent URL",D).option("--profile <name>","Target a specific profile by name").option("--json","Emit JSON").option("--plain","Force plain text output").action(async(K,Q)=>{let X=Q.parent?.args?.[0];if(!X){q("Missing plugin package argument.");return}try{let $={...V.opts(),...K},x=U(K),Y=async()=>h(x,"/api/plugins/prereqs/status",{packageName:X});await t({mode:l($),fetchData:Y,plain:(W)=>{if(A("Plugin",X),A("Satisfied",W?.satisfied?"yes":"no"),Array.isArray(W?.missing)&&W.missing.length>0)A("Missing",W.missing.map((Z)=>Z.name).join(", "))},interactive:async(W)=>{let Z=[`Plugin: ${X}`,`Satisfied: ${W?.satisfied?"yes":"no"}`];if(Array.isArray(W?.missing)&&W.missing.length>0)Z.push(`Missing: ${W.missing.map((H)=>H.name).join(", ")}`);await G2({title:`Prereqs: ${X}`,body:Z.join(`
5
+ `),footer:"q / Esc to quit"})},json:(W)=>({plugin:X,satisfied:!!W?.satisfied,missing:Array.isArray(W?.missing)?W.missing:[],pendingSudo:Array.isArray(W?.pendingSudo)?W.pendingSudo:[]})})}catch($){q(`Could not read prereq status: ${O($)}`)}}),z.command("install").description("Run the plugin's prerequisite install endpoint").option("--agent-url <url>","Agent URL",D).option("--profile <name>","Target a specific profile by name").option("--approve-sudo","Auto-approve sudo commands the plugin returns",!1).option("--json","Emit JSON result").action(async(K,Q)=>{let X=Q.parent?.args?.[0];if(!X){q("Missing plugin package argument.");return}try{let $={...V.opts(),...K},x=U(K),Y=await h(x,"/api/plugins/prereqs/install",{packageName:X,approveSudo:!!K.approveSudo});if(R($,{ok:!0,action:"prereqs-install",plugin:X,satisfied:!!Y?.satisfied,pendingSudo:Y?.pendingSudo??[]}))return;if(Y?.satisfied)S(`Prerequisites satisfied for ${X}.`);else I(`Prerequisites still missing for ${X}.`);if(Array.isArray(Y?.pendingSudo)&&Y.pendingSudo.length>0){I(`${Y.pendingSudo.length} command(s) require sudo:`);for(let W of Y.pendingSudo)A(` ${W.name}`,W.command)}}catch($){q(`Prereq install failed: ${O($)}`)}}),z.command("uninstall").description("Run the plugin's prerequisite uninstall endpoint (if supported)").option("--agent-url <url>","Agent URL",D).option("--profile <name>","Target a specific profile by name").option("--json","Emit JSON result").action(async(K,Q)=>{let X=Q.parent?.args?.[0];if(!X){q("Missing plugin package argument.");return}try{let $={...V.opts(),...K},x=U(K);if(await h(x,"/api/plugins/prereqs/uninstall",{packageName:X}),R($,{ok:!0,action:"prereqs-uninstall",plugin:X}))return;S(`Prereq uninstall completed for ${X}.`)}catch($){I(`Prereq uninstall not supported or failed: ${O($)}`)}}),B.command("create").description("Scaffold a new plugin project").argument("<name>",'Plugin name (e.g. "docker" \u2192 vibe-plugin-docker)').option("-d, --dir <directory>","Parent directory",".").option("--tag <tag>","Plugin tag (backend, frontend, cli, provider, adapter, integration)","backend").option("--with-ui","Include a companion UI plugin scaffold",!1).option("--json","Emit JSON result").action(async(K,Q)=>{try{let X={...V.opts(),...Q},$=K.startsWith("vibe-plugin-")?K.slice(12):K;if(!v2.test($)){q("Plugin name must use lowercase letters, numbers, and dashes only.");return}let x=Q.tag;if(!E2.has(x)){q("Invalid plugin tag.");return}let Y=`vibe-plugin-${$}`,W=g(Q.dir),Z=g(W,Y);if(C2(W,Z),x2(Z)){q(`Directory "${Z}" already exists.`);return}_(`Scaffolding ${Y}...`),o(T(Z,"src"),{recursive:!0}),o(T(Z,"dist"),{recursive:!0});let H=`VibeControls plugin: ${$}`,F={name:`@vibecontrols/${Y}`,version:"0.1.0",main:"./dist/index.js",type:"module",engines:{bun:">=1.3.0"},scripts:{build:"bun build ./src/index.ts --outdir ./dist --target bun",lint:"eslint ./src",format:"bunx prettier . --write","format:check":"bunx prettier . --check","type:check":"tsc --noEmit",clean:"rimraf dist",prebuild:"bun run clean",prepublishOnly:"bun run build",sanity:"bun run format:check && bun run lint && bun run type:check && bun run build"},keywords:["vibecontrols","vibe","vibe-plugin",$,"bun"],author:{name:"Your Name",email:"you@example.com"},license:"SEE LICENSE IN LICENSE",description:H,devDependencies:{"@types/bun":"^1.2.16","bun-types":"^1.3.9",commander:"^14.0.3",eslint:"^9.30.1",prettier:"^3.6.2",rimraf:"^6.0.1",typescript:"^5.8.3","typescript-eslint":"^8.56.0"},peerDependencies:{"@vibecontrols/agent":">=2.0.0"},peerDependenciesMeta:{"@vibecontrols/agent":{optional:!0}},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},files:["dist/**/*","README.md","LICENSE"]};v(T(Z,"package.json"),JSON.stringify(F,null,2)+`
6
+ `);let C={compilerOptions:{target:"ES2022",module:"ES2022",moduleResolution:"bundler",types:["bun-types"],strict:!0,esModuleInterop:!0,skipLibCheck:!0,outDir:"./dist",rootDir:"./src",declaration:!0,sourceMap:!0},include:["src/**/*.ts"],exclude:["node_modules","dist"]};v(T(Z,"tsconfig.json"),JSON.stringify(C,null,2)+`
7
+ `),v(T(Z,".gitignore"),["node_modules/","dist/","bun.lock",".env",".env.local","*.tgz"].join(`
8
+ `)+`
9
+ `);let G=$,b=M(Y),p=M(H),q2=M(x),r=M(G),S2=`import type { Command } from "commander";
10
+
11
+ /**
12
+ * @vibecontrols/${Y}
13
+ *
14
+ * ${H}
15
+ */
16
+
17
+ // \u2500\u2500 Plugin Interfaces \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
18
+
19
+ export interface HostServices {
20
+ logger?: {
21
+ info: (msg: string) => void;
22
+ warn: (msg: string) => void;
23
+ error: (msg: string) => void;
24
+ debug: (msg: string) => void;
25
+ };
26
+ config?: Record<string, unknown>;
27
+ }
28
+
29
+ export interface VibePlugin {
30
+ name: string;
31
+ version: string;
32
+ description: string;
33
+ tags?: Array<
34
+ "backend" | "frontend" | "cli" | "provider" | "adapter" | "integration"
35
+ >;
36
+ cliCommand: string;
37
+ onCliSetup: (program: Command, hostServices?: HostServices) => void;
38
+ }
39
+
40
+ // \u2500\u2500 Plugin Implementation \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
41
+
42
+ const plugin: VibePlugin = {
43
+ name: ${b},
44
+ version: "0.1.0",
45
+ description: ${p},
46
+ tags: [${q2}],
47
+ cliCommand: ${r},
48
+
49
+ onCliSetup(program: Command, _hostServices?: HostServices): void {
50
+ const cmd = program
51
+ .command(${r})
52
+ .description(${p});
53
+
54
+ cmd
55
+ .command("status")
56
+ .description(`+M(`Show ${$} status`)+`)
57
+ .action(() => {
58
+ console.log(`+M(`${Y} is ready.`)+`);
59
+ });
60
+
61
+ cmd
62
+ .command("info")
63
+ .description("Show plugin info")
64
+ .action(() => {
65
+ console.log(JSON.stringify({
66
+ name: plugin.name,
67
+ version: plugin.version,
68
+ description: plugin.description,
69
+ tags: plugin.tags,
70
+ }, null, 2));
71
+ });
72
+ },
73
+ };
74
+
75
+ export default plugin;
76
+ `;v(T(Z,"src","index.ts"),S2);let I2=`# ${Y}
77
+
78
+ ${H}
79
+
80
+ ## Installation
81
+
82
+ \`\`\`bash
83
+ vibe plugin install @vibecontrols/${Y}
84
+ \`\`\`
85
+
86
+ ## Usage
87
+
88
+ \`\`\`bash
89
+ vibe ${G} status
90
+ vibe ${G} info
91
+ \`\`\`
92
+
93
+ ## Development
94
+
95
+ \`\`\`bash
96
+ bun install
97
+ bun run build
98
+ bun run sanity
99
+ \`\`\`
100
+
101
+ ## Publishing
102
+
103
+ \`\`\`bash
104
+ bun run build
105
+ npm publish
106
+ \`\`\`
107
+ `;v(T(Z,"README.md"),I2);let P={ok:!0,action:"create",plugin:Y,packageName:`@vibecontrols/${Y}`,cliCommand:G,tag:x,dir:Z,withUi:Q.withUi===!0};if(!X.json)S(`Created ${Y} at ${Z}`),A("Plugin Name",`@vibecontrols/${Y}`),A("CLI Command",`vibe ${G}`),A("Tag",x),_(`
108
+ Next steps:`),_(` cd ${Y}`),_(" bun install"),_(" bun run build"),_(` publish @vibecontrols/${Y}, then install from catalog`);if(Q.withUi){let f=`${Y.replace("vibe-plugin-","vibe-plugin-ui-")}`,j=g(W,f);if(C2(W,j),x2(j)){if(!X.json)I(`UI directory "${j}" already exists, skipping.`);P.uiSkipped=!0,P.uiDir=j}else{o(T(j,"src"),{recursive:!0}),o(T(j,"public"),{recursive:!0});let O2={name:`@vibecontrols/${f}`,version:"0.1.0",private:!1,type:"module",scripts:{dev:"vite --port 5180",build:"tsc && vite build",preview:"vite preview",lint:"eslint ./src",format:"bunx prettier . --write","format:check":"bunx prettier . --check","type:check":"tsc --noEmit",sanity:"bun run format:check && bun run lint && bun run type:check && bun run build"},keywords:["vibecontrols","vibe-plugin","ui",$],author:{name:"Your Name",email:"you@example.com"},license:"SEE LICENSE IN LICENSE",description:`UI for ${Y}`,dependencies:{react:"^19.0.0","react-dom":"^19.0.0"},devDependencies:{"@types/react":"^19.0.0","@types/react-dom":"^19.0.0","@vitejs/plugin-react":"^4.5.2",typescript:"^5.8.3",vite:"^7.0.0"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},files:["dist/**/*","README.md"]};v(T(j,"package.json"),JSON.stringify(O2,null,2)+`
109
+ `);let R2=`import React from "react";
110
+ import ReactDOM from "react-dom/client";
111
+ import App from "./App";
112
+
113
+ ReactDOM.createRoot(document.getElementById("root")!).render(
114
+ <React.StrictMode>
115
+ <App />
116
+ </React.StrictMode>
117
+ );
118
+ `;v(T(j,"src","main.tsx"),R2);let _2=`import { useState, useEffect } from "react";
119
+
120
+ const TITLE = ${M(`${$} UI`)};
121
+
122
+ export default function App() {
123
+ const [apiKey, setApiKey] = useState<string | null>(null);
124
+ const [status, setStatus] = useState("loading...");
125
+
126
+ useEffect(() => {
127
+ // Auth via postMessage (iframe) or URL param (new tab)
128
+ const params = new URLSearchParams(window.location.search);
129
+ const key = params.get("apiKey");
130
+ if (key) {
131
+ setApiKey(key);
132
+ setStatus("connected");
133
+ return;
134
+ }
135
+
136
+ const handler = (e: MessageEvent) => {
137
+ if (e.data?.type === "vibe-auth" && e.data.apiKey) {
138
+ setApiKey(e.data.apiKey);
139
+ setStatus("connected");
140
+ }
141
+ };
142
+ window.addEventListener("message", handler);
143
+ return () => window.removeEventListener("message", handler);
144
+ }, []);
145
+
146
+ return (
147
+ <div style={{ background: "var(--vibe-surface, Canvas)", color: "var(--vibe-text, CanvasText)", minHeight: "100vh", padding: 24, fontFamily: "system-ui" }}>
148
+ <h1>{TITLE}</h1>
149
+ <p>Status: {status}</p>
150
+ {apiKey && <p style={{ color: "var(--vibe-success, CanvasText)" }}>Authenticated</p>}
151
+ </div>
152
+ );
153
+ }
154
+ `;v(T(j,"src","App.tsx"),_2);let T2=`<!DOCTYPE html>
155
+ <html lang="en">
156
+ <head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>${$} UI</title></head>
157
+ <body><div id="root"></div><script type="module" src="/src/main.tsx"></script></body>
158
+ </html>`;if(v(T(j,"index.html"),T2),!X.json)S(`Created UI plugin ${f} at ${j}`);P.uiPluginName=f,P.uiPackageName=`@vibecontrols/${f}`,P.uiDir=j}}R(X,P)}catch(X){q(O(X))}})}function F2(V,B){J2(V)}function p2(V){return{name:"plugin-mgr",version:"2.2.0",description:"Plugin lifecycle management \u2014 install, remove, reload, catalog",capabilities:{storage:"rw",subprocess:!0,gateway:!0,audit:!0,telemetry:!0},tags:["backend","cli"],cliCommand:"plugin",apiPrefix:"/api/plugins",createRoutes:(B)=>B2(B),onCliSetup:async(B,z)=>{F2(B,z)}}}export{p2 as createPlugin};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{K as I}from"./index-d1xjj001.js";import{Rb as G,Sb as D}from"./index-5dysvvjv.js";import{Od as H}from"./index-js1xn4sq.js";var j="prereqs-runner",q="plugin-mgr",v={status:null,install:null,satisfied:!0,pendingSudo:[],noProtocol:!0};function w(z,F){if(!z.apiPrefix)return null;return`${(z.apiPrefix.startsWith("/")?z.apiPrefix:`/${z.apiPrefix}`).replace(/\/+$/,"")}/prereqs${F}`}async function M(z,F,J){let Q=z.handle;if(typeof Q!=="function")return null;let Y=new Request(`http://agent.local${F}`,{method:J,headers:{"x-vc-profile-rewrite":"1",[G]:D()}}),K=await Q.call(z,Y);if(K.status===404)return null;if(!K.ok){let $=await K.text().catch(()=>"");throw Error(`prereqs ${J} ${F} \u2192 ${K.status} ${$}`)}return await K.json()}async function A(z,F,J,Q,Y={}){let K=w(z,"/status"),$=w(z,"/install");if(!K||!$)return v;let W=null;try{W=await M(J,K,"GET")}catch(V){H().logger.warn(j,`${z.name}: prereqs/status call failed`,{error:String(V)})}if(W===null)return v;if(W.satisfied||Y.skipInstall)return await x(Q,F,z.version,{status:W,install:null}),{status:W,install:null,satisfied:W.satisfied,pendingSudo:[],noProtocol:!1};let X=null;try{X=await M(J,$,"POST")}catch(V){H().logger.warn(j,`${z.name}: prereqs/install call failed`,{error:String(V)})}let B=W;try{let V=await M(J,K,"GET");if(V)B=V}catch{}if(await x(Q,F,z.version,{status:B,install:X}),X&&X.installed.length>0){let V=new Map;for(let Z of z.prerequisites??[])V.set(Z.name,Z.kind);I(F,X.installed.map((Z)=>({name:Z,kind:V.get(Z)??"binary"})))}return{status:B,install:X,satisfied:B.satisfied,pendingSudo:X?.pendingSudo??[],noProtocol:!1}}async function x(z,F,J,Q){if(!z)return;let Y=JSON.stringify({lastInstallAt:new Date().toISOString(),lastInstallVersion:J,satisfied:Q.status?.satisfied??!1,missing:Q.status?.missing??[],pendingSudo:Q.install?.pendingSudo??[]});try{await z.setPluginState(q,`prereqs:${F}`,Y)}catch(K){H().logger.warn(j,"Failed to persist prereq state",{packageName:F,error:String(K)})}}async function L(z,F){if(!z)return null;try{let J=await z.getPluginState(q,`prereqs:${F}`);return J?JSON.parse(J):null}catch{return null}}
2
+ import{K as I}from"./index-wetsgcyq.js";import{Rb as G,Sb as D}from"./index-5dysvvjv.js";import{Od as H}from"./index-xnr6t79p.js";var j="prereqs-runner",q="plugin-mgr",v={status:null,install:null,satisfied:!0,pendingSudo:[],noProtocol:!0};function w(z,F){if(!z.apiPrefix)return null;return`${(z.apiPrefix.startsWith("/")?z.apiPrefix:`/${z.apiPrefix}`).replace(/\/+$/,"")}/prereqs${F}`}async function M(z,F,J){let Q=z.handle;if(typeof Q!=="function")return null;let Y=new Request(`http://agent.local${F}`,{method:J,headers:{"x-vc-profile-rewrite":"1",[G]:D()}}),K=await Q.call(z,Y);if(K.status===404)return null;if(!K.ok){let $=await K.text().catch(()=>"");throw Error(`prereqs ${J} ${F} \u2192 ${K.status} ${$}`)}return await K.json()}async function A(z,F,J,Q,Y={}){let K=w(z,"/status"),$=w(z,"/install");if(!K||!$)return v;let W=null;try{W=await M(J,K,"GET")}catch(V){H().logger.warn(j,`${z.name}: prereqs/status call failed`,{error:String(V)})}if(W===null)return v;if(W.satisfied||Y.skipInstall)return await x(Q,F,z.version,{status:W,install:null}),{status:W,install:null,satisfied:W.satisfied,pendingSudo:[],noProtocol:!1};let X=null;try{X=await M(J,$,"POST")}catch(V){H().logger.warn(j,`${z.name}: prereqs/install call failed`,{error:String(V)})}let B=W;try{let V=await M(J,K,"GET");if(V)B=V}catch{}if(await x(Q,F,z.version,{status:B,install:X}),X&&X.installed.length>0){let V=new Map;for(let Z of z.prerequisites??[])V.set(Z.name,Z.kind);I(F,X.installed.map((Z)=>({name:Z,kind:V.get(Z)??"binary"})))}return{status:B,install:X,satisfied:B.satisfied,pendingSudo:X?.pendingSudo??[],noProtocol:!1}}async function x(z,F,J,Q){if(!z)return;let Y=JSON.stringify({lastInstallAt:new Date().toISOString(),lastInstallVersion:J,satisfied:Q.status?.satisfied??!1,missing:Q.status?.missing??[],pendingSudo:Q.install?.pendingSudo??[]});try{await z.setPluginState(q,`prereqs:${F}`,Y)}catch(K){H().logger.warn(j,"Failed to persist prereq state",{packageName:F,error:String(K)})}}async function L(z,F){if(!z)return null;try{let J=await z.getPluginState(q,`prereqs:${F}`);return J?JSON.parse(J):null}catch{return null}}
3
3
  export{A as d,L as e};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{jc as O,kc as L,lc as Y}from"./index-8nqp3a4d.js";import{oc as D,qc as R,rc as U,sc as W,uc as C,vc as E,wc as X,xc as I,yc as K}from"./index-1mppacnx.js";import{Sc as J,od as T,qd as V,sd as w}from"./index-h74va4wd.js";import{Yd as h}from"./index-a4854mwz.js";async function P(){if(process.env.AGENT_API_KEY)return process.env.AGENT_API_KEY;let F="default";try{F=h()}catch{}let H=await J(`${F}:static-api-key`);if(H)return H;return T()["static-api-key"]??null}var j=["read","mutate","plugin:install","plugin:remove","update","admin"];function _(F){if(F.length<=12)return"[redacted]";return`${F.slice(0,8)}...${F.slice(-4)}`}function x(){let F=new Uint8Array(32);return crypto.getRandomValues(F),`vcak_${Buffer.from(F).toString("base64url")}`}function b(){return crypto.randomUUID()}function A(F){if(!F)return;let H=/^(\d+)([smhdw]?)$/.exec(F.trim());if(!H)throw Error(`Invalid --expires-in: ${F} (use 30s, 12h, 7d, 4w; bare digits = days)`);let q=Number(H[1]),N=H[2]||"d",z=N==="s"?q*1000:N==="m"?q*60000:N==="h"?q*3600000:N==="w"?q*7*86400000:q*86400000;return new Date(Date.now()+z).toISOString()}function S(F){if(!F)return["read"];let H=F.split(",").map((q)=>q.trim()).filter(Boolean);for(let q of H)if(!j.includes(q))throw Error(`Unknown scope: ${q}. Allowed: ${j.join(", ")}`);return H}function f(F){let H=F.command("key").description("Show or manage VibeControls agent API keys");H.command("show",{isDefault:!0}).description("Show the default agent API key").option("--show-secret","Print the full API key",!1).option("--json","Emit JSON").option("--plain","Force plain text output").action(async function(q){let N={...F.opts(),...q};try{await L({mode:O(N),fetchData:async()=>{return{apiKey:await P()??null}},plain:(z)=>{if(E("Agent API Key"),I(),!z.apiKey){R("No API key found in AGENT_API_KEY or local agent config.");return}if(X("API Key",D.bold(q.showSecret?z.apiKey:_(z.apiKey))),!q.showSecret)X("Full key",D.dim("hidden; rerun with --show-secret"));I()},json:(z)=>({apiKey:z.apiKey?q.showSecret?z.apiKey:"[redacted]":null})})}catch(z){R(`Failed to get API key: ${U(z)}`)}}),H.command("list").description("List all scoped API keys (default + minted)").option("--json","Emit JSON").option("--plain","Force plain text output").option("--show-secret","Include full key values in JSON output",!1).action(async function(q){let N={...F.opts(),...q};try{await L({mode:O(N),fetchData:()=>w(),plain:(z)=>{let B=[],Q=z["static-api-key"];if(Q)B.push({ID:"default",Name:"default",Scopes:"admin",Expires:"never",Key:_(Q)});for(let G of z.apiKeys??[])B.push({ID:G.id??"(legacy)",Name:G.name,Scopes:G.scopes.join(","),Expires:G.expiresAt??"never",Key:_(G.key)});if(B.length===0){C("No keys configured.");return}E("Agent API Keys"),K(B)},json:(z)=>{let B=[],Q=z["static-api-key"];if(Q)B.push({id:"default",name:"default",scopes:["admin"],expiresAt:null,key:q.showSecret?Q:"[redacted]"});for(let G of z.apiKeys??[])B.push({id:G.id??"(legacy)",name:G.name,scopes:G.scopes,expiresAt:G.expiresAt??null,key:q.showSecret?G.key:"[redacted]"});return B}})}catch(z){R(U(z))}}),H.command("add").description("Mint a new scoped API key").requiredOption("--name <name>","Display name (logs only)").option("--scope <scope>",`Comma-separated scope list (default: read). Allowed: ${j.join(",")}`,"read").option("--expires-in <duration>","TTL (e.g. 7d, 12h, 30m). Omit for no expiry.").option("--not-before <iso>","ISO timestamp before which the key is rejected.").option("--json","Emit JSON").action(function(q){let N={...F.opts(),...q};try{let z=S(q.scope),B=A(q.expiresIn),Q=T(),G=b(),Z=x(),$={id:G,name:q.name,key:Z,scopes:z,expiresAt:B,notBefore:q.notBefore,createdAt:new Date().toISOString()},M=[...Q.apiKeys??[],$];if(V({apiKeys:M}),Y(N,{ok:!0,id:G,name:q.name,scopes:z,expiresAt:B??null,key:Z}))return;if(W(`Minted key ${G}`),X("Name",q.name),X("Scopes",z.join(",")),B)X("Expires",B);if(q.notBefore)X("Not before",q.notBefore);I(),X("Key (save now)",D.bold(Z))}catch(z){if(N.json){Y(N,{ok:!1,error:U(z)});return}R(U(z))}}),H.command("revoke <id>").description("Revoke a scoped key by ID").option("--json","Emit JSON").action(function(q,N){let z={...F.opts(),...N};try{let B=T(),Q=(B.apiKeys??[]).length,G=(B.apiKeys??[]).filter((Z)=>Z.id!==q);if(G.length===Q){if(z.json){Y(z,{ok:!1,error:`No key with id ${q}`});return}R(`No key with id ${q}`);return}if(V({apiKeys:G}),Y(z,{ok:!0,id:q}))return;W(`Revoked key ${q}`)}catch(B){if(z.json){Y(z,{ok:!1,error:U(B)});return}R(U(B))}}),H.command("rotate <id>").description("Rotate the secret of an existing scoped key (preserves scopes/expiry)").option("--json","Emit JSON").action(function(q,N){let z={...F.opts(),...N};try{let B=T();if(!(B.apiKeys??[]).find(($)=>$.id===q)){if(z.json){Y(z,{ok:!1,error:`No key with id ${q}`});return}R(`No key with id ${q}`);return}let G=x(),Z=(B.apiKeys??[]).map(($)=>$.id===q?{...$,key:G}:$);if(V({apiKeys:Z}),Y(z,{ok:!0,id:q,key:G}))return;W(`Rotated key ${q}`),X("New key (save now)",D.bold(G))}catch(B){if(z.json){Y(z,{ok:!1,error:U(B)});return}R(U(B))}})}
2
+ import{jc as O,kc as L,lc as Y}from"./index-8nqp3a4d.js";import{oc as D,qc as R,rc as U,sc as W,uc as C,vc as E,wc as X,xc as I,yc as K}from"./index-85ke6hng.js";import{Sc as J,od as T,qd as V,sd as w}from"./index-63ba5fb4.js";import{Yd as h}from"./index-a4854mwz.js";async function P(){if(process.env.AGENT_API_KEY)return process.env.AGENT_API_KEY;let F="default";try{F=h()}catch{}let H=await J(`${F}:static-api-key`);if(H)return H;return T()["static-api-key"]??null}var j=["read","mutate","plugin:install","plugin:remove","update","admin"];function _(F){if(F.length<=12)return"[redacted]";return`${F.slice(0,8)}...${F.slice(-4)}`}function x(){let F=new Uint8Array(32);return crypto.getRandomValues(F),`vcak_${Buffer.from(F).toString("base64url")}`}function b(){return crypto.randomUUID()}function A(F){if(!F)return;let H=/^(\d+)([smhdw]?)$/.exec(F.trim());if(!H)throw Error(`Invalid --expires-in: ${F} (use 30s, 12h, 7d, 4w; bare digits = days)`);let q=Number(H[1]),N=H[2]||"d",z=N==="s"?q*1000:N==="m"?q*60000:N==="h"?q*3600000:N==="w"?q*7*86400000:q*86400000;return new Date(Date.now()+z).toISOString()}function S(F){if(!F)return["read"];let H=F.split(",").map((q)=>q.trim()).filter(Boolean);for(let q of H)if(!j.includes(q))throw Error(`Unknown scope: ${q}. Allowed: ${j.join(", ")}`);return H}function f(F){let H=F.command("key").description("Show or manage VibeControls agent API keys");H.command("show",{isDefault:!0}).description("Show the default agent API key").option("--show-secret","Print the full API key",!1).option("--json","Emit JSON").option("--plain","Force plain text output").action(async function(q){let N={...F.opts(),...q};try{await L({mode:O(N),fetchData:async()=>{return{apiKey:await P()??null}},plain:(z)=>{if(E("Agent API Key"),I(),!z.apiKey){R("No API key found in AGENT_API_KEY or local agent config.");return}if(X("API Key",D.bold(q.showSecret?z.apiKey:_(z.apiKey))),!q.showSecret)X("Full key",D.dim("hidden; rerun with --show-secret"));I()},json:(z)=>({apiKey:z.apiKey?q.showSecret?z.apiKey:"[redacted]":null})})}catch(z){R(`Failed to get API key: ${U(z)}`)}}),H.command("list").description("List all scoped API keys (default + minted)").option("--json","Emit JSON").option("--plain","Force plain text output").option("--show-secret","Include full key values in JSON output",!1).action(async function(q){let N={...F.opts(),...q};try{await L({mode:O(N),fetchData:()=>w(),plain:(z)=>{let B=[],Q=z["static-api-key"];if(Q)B.push({ID:"default",Name:"default",Scopes:"admin",Expires:"never",Key:_(Q)});for(let G of z.apiKeys??[])B.push({ID:G.id??"(legacy)",Name:G.name,Scopes:G.scopes.join(","),Expires:G.expiresAt??"never",Key:_(G.key)});if(B.length===0){C("No keys configured.");return}E("Agent API Keys"),K(B)},json:(z)=>{let B=[],Q=z["static-api-key"];if(Q)B.push({id:"default",name:"default",scopes:["admin"],expiresAt:null,key:q.showSecret?Q:"[redacted]"});for(let G of z.apiKeys??[])B.push({id:G.id??"(legacy)",name:G.name,scopes:G.scopes,expiresAt:G.expiresAt??null,key:q.showSecret?G.key:"[redacted]"});return B}})}catch(z){R(U(z))}}),H.command("add").description("Mint a new scoped API key").requiredOption("--name <name>","Display name (logs only)").option("--scope <scope>",`Comma-separated scope list (default: read). Allowed: ${j.join(",")}`,"read").option("--expires-in <duration>","TTL (e.g. 7d, 12h, 30m). Omit for no expiry.").option("--not-before <iso>","ISO timestamp before which the key is rejected.").option("--json","Emit JSON").action(function(q){let N={...F.opts(),...q};try{let z=S(q.scope),B=A(q.expiresIn),Q=T(),G=b(),Z=x(),$={id:G,name:q.name,key:Z,scopes:z,expiresAt:B,notBefore:q.notBefore,createdAt:new Date().toISOString()},M=[...Q.apiKeys??[],$];if(V({apiKeys:M}),Y(N,{ok:!0,id:G,name:q.name,scopes:z,expiresAt:B??null,key:Z}))return;if(W(`Minted key ${G}`),X("Name",q.name),X("Scopes",z.join(",")),B)X("Expires",B);if(q.notBefore)X("Not before",q.notBefore);I(),X("Key (save now)",D.bold(Z))}catch(z){if(N.json){Y(N,{ok:!1,error:U(z)});return}R(U(z))}}),H.command("revoke <id>").description("Revoke a scoped key by ID").option("--json","Emit JSON").action(function(q,N){let z={...F.opts(),...N};try{let B=T(),Q=(B.apiKeys??[]).length,G=(B.apiKeys??[]).filter((Z)=>Z.id!==q);if(G.length===Q){if(z.json){Y(z,{ok:!1,error:`No key with id ${q}`});return}R(`No key with id ${q}`);return}if(V({apiKeys:G}),Y(z,{ok:!0,id:q}))return;W(`Revoked key ${q}`)}catch(B){if(z.json){Y(z,{ok:!1,error:U(B)});return}R(U(B))}}),H.command("rotate <id>").description("Rotate the secret of an existing scoped key (preserves scopes/expiry)").option("--json","Emit JSON").action(function(q,N){let z={...F.opts(),...N};try{let B=T();if(!(B.apiKeys??[]).find(($)=>$.id===q)){if(z.json){Y(z,{ok:!1,error:`No key with id ${q}`});return}R(`No key with id ${q}`);return}let G=x(),Z=(B.apiKeys??[]).map(($)=>$.id===q?{...$,key:G}:$);if(V({apiKeys:Z}),Y(z,{ok:!0,id:q,key:G}))return;W(`Rotated key ${q}`),X("New key (save now)",D.bold(G))}catch(B){if(z.json){Y(z,{ok:!1,error:U(B)});return}R(U(B))}})}
3
3
  export{P as Wb,f as Xb};
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
- import{j as o,k as r,l as t,m as e,n as XQ}from"./index-hwtd3ank.js";import"./index-5wpck4aw.js";import{t as QQ}from"./index-rv6h14n8.js";import"./index-btt96dhd.js";import"./index-6jzsthh9.js";import"./index-cjbfremy.js";import"./index-rw9x93zb.js";import"./index-pk3ejfc4.js";import"./index-dxtnaa3g.js";import"./index-4wgjx8bf.js";import{Da as a}from"./index-kmkhjf1c.js";import"./index-0ckffygp.js";import"./index-rc79x8fw.js";import{bb as W}from"./index-ydc0tk17.js";import"./index-52cp759f.js";import"./index-hvjqgb97.js";import{Ib as s,Jb as i}from"./index-rqq0k5fc.js";import"./index-5dysvvjv.js";import"./index-pgew6sge.js";import"./index-b6x6a4xp.js";import{Sc as p,Tc as v,od as C,ud as l,vd as n}from"./index-h74va4wd.js";import{Od as q}from"./index-js1xn4sq.js";import{$d as S,Yd as D,be as g,ce as M}from"./index-a4854mwz.js";import"./index-4qq083yd.js";import{ie as B}from"./index-c7554sg7.js";import{isAbsolute as MQ}from"path";import{existsSync as V,mkdirSync as y,readFileSync as _Q,readdirSync as P,renameSync as BQ,unlinkSync as DQ,writeFileSync as f}from"fs";import{dirname as d,join as F}from"path";var GQ=".secrets-migrated-v1",IQ=["static-api-key","clientId","clientSecret"];function WQ(Q,H){return`${Q}:${H}`}function c(){return F(M(),GQ)}function TQ(){let Q=c();y(d(Q),{recursive:!0}),f(Q,`${new Date().toISOString()}
3
+ import{j as o,k as r,l as t,m as e,n as XQ}from"./index-n1222y6a.js";import"./index-czrb2yd1.js";import{t as QQ}from"./index-rjhcmnx0.js";import"./index-9bdbnx8f.js";import"./index-6jzsthh9.js";import"./index-5mnyfrck.js";import"./index-yas07mv9.js";import"./index-x0xv3rpa.js";import"./index-c6xa5nd4.js";import"./index-4wgjx8bf.js";import{Da as a}from"./index-cfa3pgh5.js";import"./index-0ckffygp.js";import"./index-rc79x8fw.js";import{bb as W}from"./index-jrtsdm8f.js";import"./index-52cp759f.js";import"./index-6p3gcnxr.js";import{Ib as s,Jb as i}from"./index-bfeekmyh.js";import"./index-5dysvvjv.js";import"./index-pgew6sge.js";import"./index-t8tnkqxh.js";import{Sc as p,Tc as v,od as C,ud as l,vd as n}from"./index-63ba5fb4.js";import{Od as q}from"./index-xnr6t79p.js";import{$d as S,Yd as D,be as g,ce as M}from"./index-a4854mwz.js";import"./index-4qq083yd.js";import{ie as B}from"./index-c7554sg7.js";import{isAbsolute as MQ}from"path";import{existsSync as V,mkdirSync as y,readFileSync as _Q,readdirSync as P,renameSync as BQ,unlinkSync as DQ,writeFileSync as f}from"fs";import{dirname as d,join as F}from"path";var GQ=".secrets-migrated-v1",IQ=["static-api-key","clientId","clientSecret"];function WQ(Q,H){return`${Q}:${H}`}function c(){return F(M(),GQ)}function TQ(){let Q=c();y(d(Q),{recursive:!0}),f(Q,`${new Date().toISOString()}
4
4
  `,{mode:384})}function JQ(Q){if(!V(Q))return null;try{let H=_Q(Q,"utf8"),X=JSON.parse(H);if(X&&typeof X==="object"&&!Array.isArray(X))return X}catch{}return null}function VQ(Q,H){y(d(Q),{recursive:!0});let X=`${Q}.${process.pid}.tmp`;f(X,`${JSON.stringify(H,null,2)}
5
- `,{mode:384}),BQ(X,Q)}function FQ(){let Q=M(),H=F(Q,"agents");if(!V(H))return[];let X=[],L;try{L=P(H)}catch{return[]}for(let Y of L){let z=F(H,Y,"config.json");if(!V(z))continue;X.push({path:z,scope:Y})}return X}function jQ(){let Q=M(),H=F(Q,"profiles");if(!V(H))return[];let X=[],L;try{L=P(H)}catch{return[]}for(let Y of L){if(!Y.endsWith(".json"))continue;X.push({path:F(H,Y),scope:Y.slice(0,-5)})}return X}async function KQ(Q,H){let X=JQ(Q);if(!X)return 0;let L=0;for(let Y of IQ){let z=X[Y];if(typeof z!=="string"||z.length===0)continue;let _=WQ(H,Y);try{await v(_,z),delete X[Y],L++,q().logger.info("secrets-migrator","migrated field",{path:Q,scope:H,key:Y})}catch(G){q().logger.warn("secrets-migrator","failed to migrate field",{path:Q,scope:H,key:Y,error:String(G)})}}if(L>0)VQ(Q,X);return L}async function m(){let Q={alreadyMigrated:!1,fieldsMoved:0,filesUpdated:0};if(V(c()))return Q.alreadyMigrated=!0,Q;let H=[...FQ(),...jQ()];for(let X of H){let L;try{L=await KQ(X.path,X.scope)}catch(Y){q().logger.warn("secrets-migrator","skipping target after error",{path:X.path,error:String(Y)});continue}if(L>0)Q.fieldsMoved+=L,Q.filesUpdated++}try{TQ()}catch(X){q().logger.warn("secrets-migrator","failed to drop migration marker",{error:String(X)})}if(Q.fieldsMoved>0)q().logger.info("secrets-migrator","migration complete",{fieldsMoved:Q.fieldsMoved,filesUpdated:Q.filesUpdated});return Q}{let Q=JSON.parse.bind(JSON);JSON.parse=(L,Y)=>{try{return Q(L,Y)}catch(z){if(typeof L==="string"&&L.endsWith("}}"))try{return Q(L.slice(0,-1),Y)}catch{}throw z}};let X=globalThis.Request?.prototype;if(X&&typeof X.json==="function"){let L=X.json;X.json=async function(){let z=await this.text();if(!z)return;try{return Q(z)}catch{if(z.endsWith("}}"))try{return Q(z.slice(0,-1))}catch{}let _=new Request("http://shim/",{method:"POST",body:z});return L.call(_)}}}}QQ();l();if(!process.env.VIBECONTROLS_DATA_DIR)process.env.VIBECONTROLS_DATA_DIR=S();if(typeof Bun>"u")console.error("ERROR: VibeControls Agent requires Bun runtime."),console.error("Install Bun: https://bun.sh"),process.exit(1);function UQ(Q){if(Q==="default")return 3005;let H=2166136261;for(let X=0;X<Q.length;X++)H=Math.imul(H^Q.charCodeAt(X),16777619);return 3100+Math.abs(H)%300}var E=(()=>{try{return D()}catch{return"default"}})(),A=Number.parseInt(process.env.PORT||String(UQ(E)),10),U=Number.isInteger(A)&&A>0?A:3005,R=process.env.HOST||"0.0.0.0",RQ=(()=>{let Q=process.env.DB_PATH;if(!Q)return;if(MQ(Q))return Q;console.warn(`[boot] Ignoring relative DB_PATH=${Q} (cwd=${process.cwd()}). Use an absolute path or unset to fall back to ${g()}.`);return})(),x=process.env.AGENT_API_KEY||void 0,CQ=process.env.LOG_LEVEL||"info",EQ=process.env.CORS_ORIGIN||void 0;async function wQ(){try{await m()}catch($){q().logger.warn("server","secrets migration encountered an error",{error:String($)})}let Q=C()["static-api-key"],H=(()=>{try{return D()}catch{return"default"}})(),X=Q??await p(`${H}:static-api-key`),L=!x&&!X;await s(),await n();let Y=process.env.VIBE_CLIENT_ID,z=process.env.VIBE_CLIENT_SECRET,_=process.env.VIBE_GLOBAL_GATEWAY_URL,G=process.env.VIBE_WORKSPACE_GATEWAY_URL,b=process.env.VIBE_WORKSPACE_ID,ZQ=!!Y&&!!z&&!!_&&!!G&&!!b;q().logger.info("server","Starting VibeControls Agent...",{runtime:"bun",bunVersion:Bun.version,port:U,host:R,env:"production"});try{let $=C(),Z=$["telemetry.enabled"]===!0||$["telemetry.enabled"]==="true";W.init({persisted:Z});let N=Date.now();W.emit("agent.started",{version:process.env.npm_package_version??"unknown",profile:E,platform:process.platform}),process.__vibe_started_at=N}catch{}let j=Math.max(1,Number.parseInt(process.env.VIBECONTROLS_AGENT_BOOT_RETRIES??"10",10)||10),$Q=($)=>{let Z=String($?.message??$).toLowerCase();return Z.includes("syntax")||Z.includes("cannot find module")||Z.includes("module not found")||Z.includes("typeerror")||Z.includes("config schema")||Z.includes("invalid config")||Z.includes("corrupt")||Z.includes("eaccess")||Z.includes("eperm")},O=null,I=0;while(!O){I++;try{O=await XQ({port:U,host:R,dbPath:RQ,apiKey:x,logLevel:CQ,corsOrigin:EQ}),await O.start();try{let $=await import("fs"),Z=`${S()}/runtime.json`;$.writeFileSync(Z,JSON.stringify({pid:process.pid,port:U,host:R,profile:E,startedAt:new Date().toISOString(),version:a()},null,2));let N=()=>{try{if($.existsSync(Z))$.unlinkSync(Z)}catch{}};process.once("SIGTERM",N),process.once("SIGINT",N),process.once("exit",N)}catch($){q().logger.warn("server","Could not write runtime.json",{error:String($)})}}catch($){let Z=$Q($);if(q().logger.error("server","Failed to start agent server",{attempt:I,maxBootAttempts:j,fatal:Z,error:String($)}),Z||I>=j)console.error(`\u274C Failed to start VibeControls Agent (attempt ${I}/${j}, fatal=${Z}):`,$),process.exit(1);let N=Math.min(30000,1000*2**Math.min(5,I-1)),J=Math.floor(Math.random()*500),K=N+J;console.warn(`\u26A0\uFE0F Agent boot attempt ${I}/${j} failed (transient), retrying in ${Math.round(K/1000)}s...`),await new Promise((k)=>setTimeout(k,K)),O=null}}let h=O.getServiceRegistry().getProvider("tunnel"),T=null;if(h?.getActiveTunnelUrl)for(let $=0;$<30;$++){if(T=await h.getActiveTunnelUrl(),T)break;await new Promise((Z)=>setTimeout(Z,1000))}if(!T){let{sanitizeEnvSuffix:$}=await import("./tunnel-bootstrap-5wgt9a1h.js"),{getVibecontrolsProfile:Z}=await import("./path-utils-hxdyv2zn.js"),N=$(Z());T=process.env[`AGENT_TUNNEL_URL_${N}`]??process.env.AGENT_TUNNEL_URL??null}let HQ=C(),LQ=x||i()||HQ["static-api-key"]||"",w=q().getBootState(),YQ=w==="ready"?null:o();if(w==="ready")r();kQ({port:U,host:R,tunnelUrl:T,apiKey:LQ,revealApiKey:L||process.env.AGENT_PRINT_API_KEY==="1",state:w,pairingToken:YQ});try{t({profile:E})}catch($){q().logger.warn("server","Could not start autoupdate",{error:String($)})}let{existsSync:NQ,unlinkSync:qQ}=await import("fs"),{tmpdir:zQ}=await import("os"),{join:OQ}=await import("path"),u=async($)=>{q().logger.info("server",`Received ${$}, shutting down...`),e();try{let N=process.__vibe_started_at??Date.now();W.emit("agent.stopped",{uptime_s:Math.round((Date.now()-N)/1000),reason:$}),await W.flush(),W.stop()}catch{}let Z=O.getLifecycle();if($==="SIGTERM"){let N=OQ(zQ(),`.boff-vibecontrols-kill-${process.pid}`);if(NQ(N)){try{qQ(N)}catch{}if(q().logger.info("server","Kill-intent flag detected \u2014 full shutdown"),Z)await Z.kill();else await O.stop({reason:"shutdown"}),process.exit(0)}else if(q().logger.info("server","No kill flag \u2014 treating as hot-reload (soft stop)"),Z)await Z.softStop();else await O.stop({reason:"reload"})}else if(Z)await Z.kill();else await O.stop({reason:"shutdown"}),process.exit(0)};if(process.on("SIGINT",()=>u("SIGINT")),process.on("SIGTERM",()=>u("SIGTERM")),ZQ){let $=(()=>{let Z=process.env.VIBECONTROLS_FINALIZE_TIMEOUT_MS,N=Z?Number.parseInt(Z,10):NaN;return Number.isFinite(N)&&N>0?N:300000})();q().logger.info("server",`VIBE_* env vars detected \u2014 running inline finalize (timeout ${Math.round($/1000)}s)`),(async()=>{let Z={clientId:Y,clientSecret:z,workspaceId:b,globalGatewayUrl:_,workspaceGatewayUrl:G};try{let N=await Promise.race([O.finalize(Z),new Promise((J)=>setTimeout(()=>J({ok:!1,error:`inline finalize timed out after ${Math.round($/1000)}s`}),$))]);if(!N.ok){q().logger.warn("server","Inline finalize failed \u2014 agent stays awaiting-config. Background retry worker will keep trying.",{error:N.error});let{startFinalizeRetryWorker:J}=await import("./finalize-retry-worker-dvykrzed.js"),{setFinalizeRetryHandle:K}=await import("./finalize-retry-handle-registry-xnm9kxry.js"),k=J({trigger:()=>O.finalize(Z)});K(k)}}catch(N){q().logger.error("server","Inline finalize threw",{error:String(N)})}})()}else q().logger.info("server","Agent is awaiting gateway credentials. Add it on the VibeControls platform using the tunnel URL and API key shown above.")}function kQ(Q){let X=(G)=>("\u2551 "+G).padEnd(65)+"\u2551",L="\u2560"+"\u2550".repeat(64)+"\u2563",Y="\u2554"+"\u2550".repeat(64)+"\u2557",z="\u255A"+"\u2550".repeat(64)+"\u255D",_=Q.revealApiKey?Q.apiKey:Q.apiKey?`${Q.apiKey.substring(0,8)}****${Q.apiKey.substring(Q.apiKey.length-4)}`:"(none)";if(console.log(""),console.log(Y),console.log(X("VibeControls Agent")),console.log(L),console.log(X(`State: ${Q.state}`)),console.log(X(`Agent URL: http://${Q.host}:${Q.port}`)),console.log(X(`API Key: ${_}`)),console.log(X(`Tunnel URL: ${Q.tunnelUrl??"(none)"}`)),Q.pairingToken)console.log(X(`Pairing: ${Q.pairingToken}`)),console.log(X(" (send as x-pairing-token on bootstrap)"));if(console.log(L),console.log(X(`Health: http://localhost:${Q.port}/health`)),console.log(X(`Status: http://localhost:${Q.port}/api/agent/status`)),console.log(z),!Q.revealApiKey)console.log(" (Set AGENT_PRINT_API_KEY=1 to print the API key in full.)");console.log("")}wQ();
5
+ `,{mode:384}),BQ(X,Q)}function FQ(){let Q=M(),H=F(Q,"agents");if(!V(H))return[];let X=[],L;try{L=P(H)}catch{return[]}for(let Y of L){let z=F(H,Y,"config.json");if(!V(z))continue;X.push({path:z,scope:Y})}return X}function jQ(){let Q=M(),H=F(Q,"profiles");if(!V(H))return[];let X=[],L;try{L=P(H)}catch{return[]}for(let Y of L){if(!Y.endsWith(".json"))continue;X.push({path:F(H,Y),scope:Y.slice(0,-5)})}return X}async function KQ(Q,H){let X=JQ(Q);if(!X)return 0;let L=0;for(let Y of IQ){let z=X[Y];if(typeof z!=="string"||z.length===0)continue;let _=WQ(H,Y);try{await v(_,z),delete X[Y],L++,q().logger.info("secrets-migrator","migrated field",{path:Q,scope:H,key:Y})}catch(G){q().logger.warn("secrets-migrator","failed to migrate field",{path:Q,scope:H,key:Y,error:String(G)})}}if(L>0)VQ(Q,X);return L}async function m(){let Q={alreadyMigrated:!1,fieldsMoved:0,filesUpdated:0};if(V(c()))return Q.alreadyMigrated=!0,Q;let H=[...FQ(),...jQ()];for(let X of H){let L;try{L=await KQ(X.path,X.scope)}catch(Y){q().logger.warn("secrets-migrator","skipping target after error",{path:X.path,error:String(Y)});continue}if(L>0)Q.fieldsMoved+=L,Q.filesUpdated++}try{TQ()}catch(X){q().logger.warn("secrets-migrator","failed to drop migration marker",{error:String(X)})}if(Q.fieldsMoved>0)q().logger.info("secrets-migrator","migration complete",{fieldsMoved:Q.fieldsMoved,filesUpdated:Q.filesUpdated});return Q}{let Q=JSON.parse.bind(JSON);JSON.parse=(L,Y)=>{try{return Q(L,Y)}catch(z){if(typeof L==="string"&&L.endsWith("}}"))try{return Q(L.slice(0,-1),Y)}catch{}throw z}};let X=globalThis.Request?.prototype;if(X&&typeof X.json==="function"){let L=X.json;X.json=async function(){let z=await this.text();if(!z)return;try{return Q(z)}catch{if(z.endsWith("}}"))try{return Q(z.slice(0,-1))}catch{}let _=new Request("http://shim/",{method:"POST",body:z});return L.call(_)}}}}QQ();l();if(!process.env.VIBECONTROLS_DATA_DIR)process.env.VIBECONTROLS_DATA_DIR=S();if(typeof Bun>"u")console.error("ERROR: VibeControls Agent requires Bun runtime."),console.error("Install Bun: https://bun.sh"),process.exit(1);function UQ(Q){if(Q==="default")return 3005;let H=2166136261;for(let X=0;X<Q.length;X++)H=Math.imul(H^Q.charCodeAt(X),16777619);return 3100+Math.abs(H)%300}var E=(()=>{try{return D()}catch{return"default"}})(),A=Number.parseInt(process.env.PORT||String(UQ(E)),10),U=Number.isInteger(A)&&A>0?A:3005,R=process.env.HOST||"0.0.0.0",RQ=(()=>{let Q=process.env.DB_PATH;if(!Q)return;if(MQ(Q))return Q;console.warn(`[boot] Ignoring relative DB_PATH=${Q} (cwd=${process.cwd()}). Use an absolute path or unset to fall back to ${g()}.`);return})(),x=process.env.AGENT_API_KEY||void 0,CQ=process.env.LOG_LEVEL||"info",EQ=process.env.CORS_ORIGIN||void 0;async function wQ(){try{await m()}catch($){q().logger.warn("server","secrets migration encountered an error",{error:String($)})}let Q=C()["static-api-key"],H=(()=>{try{return D()}catch{return"default"}})(),X=Q??await p(`${H}:static-api-key`),L=!x&&!X;await s(),await n();let Y=process.env.VIBE_CLIENT_ID,z=process.env.VIBE_CLIENT_SECRET,_=process.env.VIBE_GLOBAL_GATEWAY_URL,G=process.env.VIBE_WORKSPACE_GATEWAY_URL,b=process.env.VIBE_WORKSPACE_ID,ZQ=!!Y&&!!z&&!!_&&!!G&&!!b;q().logger.info("server","Starting VibeControls Agent...",{runtime:"bun",bunVersion:Bun.version,port:U,host:R,env:"production"});try{let $=C(),Z=$["telemetry.enabled"]===!0||$["telemetry.enabled"]==="true";W.init({persisted:Z});let N=Date.now();W.emit("agent.started",{version:process.env.npm_package_version??"unknown",profile:E,platform:process.platform}),process.__vibe_started_at=N}catch{}let j=Math.max(1,Number.parseInt(process.env.VIBECONTROLS_AGENT_BOOT_RETRIES??"10",10)||10),$Q=($)=>{let Z=String($?.message??$).toLowerCase();return Z.includes("syntax")||Z.includes("cannot find module")||Z.includes("module not found")||Z.includes("typeerror")||Z.includes("config schema")||Z.includes("invalid config")||Z.includes("corrupt")||Z.includes("eaccess")||Z.includes("eperm")},O=null,I=0;while(!O){I++;try{O=await XQ({port:U,host:R,dbPath:RQ,apiKey:x,logLevel:CQ,corsOrigin:EQ}),await O.start();try{let $=await import("fs"),Z=`${S()}/runtime.json`;$.writeFileSync(Z,JSON.stringify({pid:process.pid,port:U,host:R,profile:E,startedAt:new Date().toISOString(),version:a()},null,2));let N=()=>{try{if($.existsSync(Z))$.unlinkSync(Z)}catch{}};process.once("SIGTERM",N),process.once("SIGINT",N),process.once("exit",N)}catch($){q().logger.warn("server","Could not write runtime.json",{error:String($)})}}catch($){let Z=$Q($);if(q().logger.error("server","Failed to start agent server",{attempt:I,maxBootAttempts:j,fatal:Z,error:String($)}),Z||I>=j)console.error(`\u274C Failed to start VibeControls Agent (attempt ${I}/${j}, fatal=${Z}):`,$),process.exit(1);let N=Math.min(30000,1000*2**Math.min(5,I-1)),J=Math.floor(Math.random()*500),K=N+J;console.warn(`\u26A0\uFE0F Agent boot attempt ${I}/${j} failed (transient), retrying in ${Math.round(K/1000)}s...`),await new Promise((k)=>setTimeout(k,K)),O=null}}let h=O.getServiceRegistry().getProvider("tunnel"),T=null;if(h?.getActiveTunnelUrl)for(let $=0;$<30;$++){if(T=await h.getActiveTunnelUrl(),T)break;await new Promise((Z)=>setTimeout(Z,1000))}if(!T){let{sanitizeEnvSuffix:$}=await import("./tunnel-bootstrap-zdczwezc.js"),{getVibecontrolsProfile:Z}=await import("./path-utils-hxdyv2zn.js"),N=$(Z());T=process.env[`AGENT_TUNNEL_URL_${N}`]??process.env.AGENT_TUNNEL_URL??null}let HQ=C(),LQ=x||i()||HQ["static-api-key"]||"",w=q().getBootState(),YQ=w==="ready"?null:o();if(w==="ready")r();kQ({port:U,host:R,tunnelUrl:T,apiKey:LQ,revealApiKey:L||process.env.AGENT_PRINT_API_KEY==="1",state:w,pairingToken:YQ});try{t({profile:E})}catch($){q().logger.warn("server","Could not start autoupdate",{error:String($)})}let{existsSync:NQ,unlinkSync:qQ}=await import("fs"),{tmpdir:zQ}=await import("os"),{join:OQ}=await import("path"),u=async($)=>{q().logger.info("server",`Received ${$}, shutting down...`),e();try{let N=process.__vibe_started_at??Date.now();W.emit("agent.stopped",{uptime_s:Math.round((Date.now()-N)/1000),reason:$}),await W.flush(),W.stop()}catch{}let Z=O.getLifecycle();if($==="SIGTERM"){let N=OQ(zQ(),`.boff-vibecontrols-kill-${process.pid}`);if(NQ(N)){try{qQ(N)}catch{}if(q().logger.info("server","Kill-intent flag detected \u2014 full shutdown"),Z)await Z.kill();else await O.stop({reason:"shutdown"}),process.exit(0)}else if(q().logger.info("server","No kill flag \u2014 treating as hot-reload (soft stop)"),Z)await Z.softStop();else await O.stop({reason:"reload"})}else if(Z)await Z.kill();else await O.stop({reason:"shutdown"}),process.exit(0)};if(process.on("SIGINT",()=>u("SIGINT")),process.on("SIGTERM",()=>u("SIGTERM")),ZQ){let $=(()=>{let Z=process.env.VIBECONTROLS_FINALIZE_TIMEOUT_MS,N=Z?Number.parseInt(Z,10):NaN;return Number.isFinite(N)&&N>0?N:300000})();q().logger.info("server",`VIBE_* env vars detected \u2014 running inline finalize (timeout ${Math.round($/1000)}s)`),(async()=>{let Z={clientId:Y,clientSecret:z,workspaceId:b,globalGatewayUrl:_,workspaceGatewayUrl:G};try{let N=await Promise.race([O.finalize(Z),new Promise((J)=>setTimeout(()=>J({ok:!1,error:`inline finalize timed out after ${Math.round($/1000)}s`}),$))]);if(!N.ok){q().logger.warn("server","Inline finalize failed \u2014 agent stays awaiting-config. Background retry worker will keep trying.",{error:N.error});let{startFinalizeRetryWorker:J}=await import("./finalize-retry-worker-vfdskqb5.js"),{setFinalizeRetryHandle:K}=await import("./finalize-retry-handle-registry-xnm9kxry.js"),k=J({trigger:()=>O.finalize(Z)});K(k)}}catch(N){q().logger.error("server","Inline finalize threw",{error:String(N)})}})()}else q().logger.info("server","Agent is awaiting gateway credentials. Add it on the VibeControls platform using the tunnel URL and API key shown above.")}function kQ(Q){let X=(G)=>("\u2551 "+G).padEnd(65)+"\u2551",L="\u2560"+"\u2550".repeat(64)+"\u2563",Y="\u2554"+"\u2550".repeat(64)+"\u2557",z="\u255A"+"\u2550".repeat(64)+"\u255D",_=Q.revealApiKey?Q.apiKey:Q.apiKey?`${Q.apiKey.substring(0,8)}****${Q.apiKey.substring(Q.apiKey.length-4)}`:"(none)";if(console.log(""),console.log(Y),console.log(X("VibeControls Agent")),console.log(L),console.log(X(`State: ${Q.state}`)),console.log(X(`Agent URL: http://${Q.host}:${Q.port}`)),console.log(X(`API Key: ${_}`)),console.log(X(`Tunnel URL: ${Q.tunnelUrl??"(none)"}`)),Q.pairingToken)console.log(X(`Pairing: ${Q.pairingToken}`)),console.log(X(" (send as x-pairing-token on bootstrap)"));if(console.log(L),console.log(X(`Health: http://localhost:${Q.port}/health`)),console.log(X(`Status: http://localhost:${Q.port}/api/agent/status`)),console.log(z),!Q.revealApiKey)console.log(" (Set AGENT_PRINT_API_KEY=1 to print the API key in full.)");console.log("")}wQ();
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{Wb as a,Xb as b}from"./index-zhyxdyk6.js";import"./index-8sdrhr3q.js";import"./index-8nqp3a4d.js";import"./index-85ke6hng.js";import"./index-thammzct.js";import"./index-t8tnkqxh.js";import"./index-63ba5fb4.js";import"./index-xnr6t79p.js";import"./index-a4854mwz.js";import"./index-4qq083yd.js";import"./index-c7554sg7.js";export{a as resolveDefaultApiKey,b as register};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{Ga as a,Ia as b,Qa as c,Ra as d,Sa as e,Ta as f,Ua as g,Va as h,Wa as i}from"./index-kmkhjf1c.js";import"./index-0ckffygp.js";import"./index-js1xn4sq.js";import"./index-a4854mwz.js";import"./index-4qq083yd.js";import"./index-c7554sg7.js";export{f as validatePluginPackageName,c as getRegistryAllowlist,e as getPluginPackageRoot,g as getInstallScope,d as assertRegistryAllowed,b as TRUSTED_PACKAGES,i as PluginManager,h as DEFAULT_PLUGINS,a as CORE_PLUGIN_NAMES};
2
+ import{Ga as a,Ia as b,Qa as c,Ra as d,Sa as e,Ta as f,Ua as g,Va as h,Wa as i}from"./index-cfa3pgh5.js";import"./index-0ckffygp.js";import"./index-xnr6t79p.js";import"./index-a4854mwz.js";import"./index-4qq083yd.js";import"./index-c7554sg7.js";export{f as validatePluginPackageName,c as getRegistryAllowlist,e as getPluginPackageRoot,g as getInstallScope,d as assertRegistryAllowed,b as TRUSTED_PACKAGES,i as PluginManager,h as DEFAULT_PLUGINS,a as CORE_PLUGIN_NAMES};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{d as a,e as b}from"./index-z5s398n0.js";import"./index-d1xjj001.js";import"./index-5dysvvjv.js";import"./index-js1xn4sq.js";import"./index-a4854mwz.js";import"./index-4qq083yd.js";import"./index-c7554sg7.js";export{a as runPluginPrereqs,b as readPrereqState};
2
+ import{d as a,e as b}from"./index-z73x3sdf.js";import"./index-wetsgcyq.js";import"./index-5dysvvjv.js";import"./index-xnr6t79p.js";import"./index-a4854mwz.js";import"./index-4qq083yd.js";import"./index-c7554sg7.js";export{a as runPluginPrereqs,b as readPrereqState};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{nb as a,ob as b,pb as c,qb as d,rb as e,sb as f}from"./index-hvjqgb97.js";import"./index-rqq0k5fc.js";import"./index-5dysvvjv.js";import"./index-pgew6sge.js";import"./index-h74va4wd.js";import"./index-js1xn4sq.js";import"./index-a4854mwz.js";import"./index-4qq083yd.js";import"./index-c7554sg7.js";export{b as unmountProfileRoutes,a as mountProfileRoutes,c as dispatchProfileRequest,f as __setMountForTests,e as __resetProfileMountsForTests,d as __listMountedProfilesForTests};
2
+ import{nb as a,ob as b,pb as c,qb as d,rb as e,sb as f}from"./index-6p3gcnxr.js";import"./index-bfeekmyh.js";import"./index-5dysvvjv.js";import"./index-pgew6sge.js";import"./index-63ba5fb4.js";import"./index-xnr6t79p.js";import"./index-a4854mwz.js";import"./index-4qq083yd.js";import"./index-c7554sg7.js";export{b as unmountProfileRoutes,a as mountProfileRoutes,c as dispatchProfileRequest,f as __setMountForTests,e as __resetProfileMountsForTests,d as __listMountedProfilesForTests};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{J as a}from"./index-ekzav1nc.js";import"./index-wetsgcyq.js";import"./index-b5dhmybd.js";import"./index-e1bw1bwr.js";import"./index-5mnyfrck.js";import"./index-yas07mv9.js";import"./index-x0xv3rpa.js";import"./index-4wgjx8bf.js";import"./index-cfa3pgh5.js";import"./index-0ckffygp.js";import"./index-rc79x8fw.js";import"./index-jrtsdm8f.js";import"./index-52cp759f.js";import"./index-bfeekmyh.js";import"./index-5dysvvjv.js";import"./index-pgew6sge.js";import"./index-8nqp3a4d.js";import"./index-85ke6hng.js";import"./index-thammzct.js";import"./index-t8tnkqxh.js";import"./index-63ba5fb4.js";import"./index-xnr6t79p.js";import"./index-a4854mwz.js";import"./index-4qq083yd.js";import"./index-c7554sg7.js";export{a as registerCoreCommands};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{x as a}from"./index-9bdbnx8f.js";import"./index-c6xa5nd4.js";import"./index-4wgjx8bf.js";import"./index-cfa3pgh5.js";import"./index-0ckffygp.js";import"./index-6p3gcnxr.js";import"./index-bfeekmyh.js";import"./index-5dysvvjv.js";import"./index-pgew6sge.js";import"./index-63ba5fb4.js";import"./index-xnr6t79p.js";import"./index-a4854mwz.js";import"./index-4qq083yd.js";import"./index-c7554sg7.js";export{a as attachSecondaryProfile};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{o as a,p as b,q as c,r as d,s as e}from"./index-5wpck4aw.js";import"./index-0ckffygp.js";import"./index-js1xn4sq.js";import"./index-a4854mwz.js";import"./index-4qq083yd.js";import"./index-c7554sg7.js";export{a as spawnTracked,c as listTrackedByOwner,b as listTracked,d as killTracked,e as killAllTracked};
2
+ import{o as a,p as b,q as c,r as d,s as e}from"./index-czrb2yd1.js";import"./index-0ckffygp.js";import"./index-xnr6t79p.js";import"./index-a4854mwz.js";import"./index-4qq083yd.js";import"./index-c7554sg7.js";export{a as spawnTracked,c as listTrackedByOwner,b as listTracked,d as killTracked,e as killAllTracked};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{bb as a}from"./index-jrtsdm8f.js";import"./index-52cp759f.js";import"./index-xnr6t79p.js";import"./index-a4854mwz.js";import"./index-4qq083yd.js";import"./index-c7554sg7.js";export{a as telemetryService};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{pa as a,qa as b,ra as c,sa as d,ta as e,ua as f}from"./index-rw9x93zb.js";import"./index-0ckffygp.js";import"./index-ydc0tk17.js";import"./index-52cp759f.js";import"./index-js1xn4sq.js";import"./index-a4854mwz.js";import"./index-4qq083yd.js";import"./index-c7554sg7.js";export{c as tryHandoverBootstrapTunnel,d as stopBootstrapTunnel,b as startBootstrapTunnel,a as sanitizeEnvSuffix,f as reapOrphanTunnelsForProfile,e as getBootstrapTunnelUrl};
2
+ import{pa as a,qa as b,ra as c,sa as d,ta as e,ua as f}from"./index-yas07mv9.js";import"./index-0ckffygp.js";import"./index-jrtsdm8f.js";import"./index-52cp759f.js";import"./index-xnr6t79p.js";import"./index-a4854mwz.js";import"./index-4qq083yd.js";import"./index-c7554sg7.js";export{c as tryHandoverBootstrapTunnel,d as stopBootstrapTunnel,b as startBootstrapTunnel,a as sanitizeEnvSuffix,f as reapOrphanTunnelsForProfile,e as getBootstrapTunnelUrl};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vibecontrols/agent",
3
- "version": "2026.602.5",
3
+ "version": "2026.602.7",
4
4
  "main": "./dist/index.js",
5
5
  "type": "module",
6
6
  "bin": {
@@ -1,2 +0,0 @@
1
- // @bun
2
- import{n as a}from"./index-hwtd3ank.js";import"./index-5wpck4aw.js";import"./index-btt96dhd.js";import"./index-6jzsthh9.js";import"./index-cjbfremy.js";import"./index-rw9x93zb.js";import"./index-pk3ejfc4.js";import"./index-dxtnaa3g.js";import"./index-4wgjx8bf.js";import"./index-kmkhjf1c.js";import"./index-0ckffygp.js";import"./index-rc79x8fw.js";import"./index-ydc0tk17.js";import"./index-52cp759f.js";import"./index-hvjqgb97.js";import"./index-rqq0k5fc.js";import"./index-5dysvvjv.js";import"./index-pgew6sge.js";import"./index-b6x6a4xp.js";import"./index-h74va4wd.js";import"./index-js1xn4sq.js";import"./index-a4854mwz.js";import"./index-4qq083yd.js";import"./index-c7554sg7.js";export{a as createApp};