@vibecontrols/agent 2026.820.1 → 2026.824.1
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.
- package/dist/agent-config-5b0avmy6.js +2 -0
- package/dist/{agent-ready-tracker-y9wbqt6y.js → agent-ready-tracker-ez6r9djg.js} +1 -1
- package/dist/app-hkt10ta3.js +2 -0
- package/dist/autostart.cmd-fdcdqrr2.js +2 -0
- package/dist/bootstrap-workspace-t5fyq07m.js +2 -0
- package/dist/bootstrap.service-nxhkrsf1.js +2 -0
- package/dist/{bridge-client-emc7mttx.js → bridge-client-bgkr7bcn.js} +1 -1
- package/dist/cli.js +1 -1
- package/dist/daemon-profile-j2wt35x8.js +2 -0
- package/dist/{esm-br6epktf.js → esm-n9r8p5n2.js} +1 -1
- package/dist/{finalize-retry-handle-registry-ndbsa6a3.js → finalize-retry-handle-registry-fvm4gm8s.js} +1 -1
- package/dist/{finalize-retry-worker-mfj115ek.js → finalize-retry-worker-wb8wj1yw.js} +1 -1
- package/dist/gateway-client-6dqagbg4.js +2 -0
- package/dist/{getMachineId-bsd-gvxzt2gm.js → getMachineId-bsd-fgatzdd7.js} +1 -1
- package/dist/{getMachineId-darwin-g66tx8f2.js → getMachineId-darwin-gt8j2jw2.js} +1 -1
- package/dist/{getMachineId-linux-f0mt4jq9.js → getMachineId-linux-bcz4rr1x.js} +1 -1
- package/dist/{getMachineId-unsupported-bsmqnjcv.js → getMachineId-unsupported-079qwwb4.js} +1 -1
- package/dist/{getMachineId-win-172fq57c.js → getMachineId-win-2hk4e8bg.js} +1 -1
- package/dist/highlights-0gfz787m.js +2 -0
- package/dist/highlights-86sbx76f.js +2 -0
- package/dist/highlights-n55f5jnk.js +2 -0
- package/dist/highlights-tbmszdr7.js +2 -0
- package/dist/highlights-wm2cs773.js +2 -0
- package/dist/{index-m1bteh0j.js → index-06es0fmw.js} +1 -1
- package/dist/{index-4f3ac5nf.js → index-0d4wfjbt.js} +2 -2
- package/dist/{index-ff8acg43.js → index-29fmptfn.js} +1 -1
- package/dist/index-2q2jadag.js +11 -0
- package/dist/{index-1hfchgm5.js → index-2sn36kaj.js} +1 -1
- package/dist/{index-jnrqbhew.js → index-3p4n7nwg.js} +1 -1
- package/dist/{index-hym4bq94.js → index-3tf12pw3.js} +1 -1
- package/dist/index-4gsn3d9r.js +26 -0
- package/dist/{index-2244sbdx.js → index-7wejfjj9.js} +3 -3
- package/dist/{index-tcew34xr.js → index-8q19ryt2.js} +1 -1
- package/dist/{index-6nz3c1ys.js → index-8xh8m2z7.js} +2 -2
- package/dist/index-a8n6s2ae.js +2 -0
- package/dist/{index-najxwhng.js → index-b16y8wyz.js} +1 -1
- package/dist/{index-1xw2wxyf.js → index-df19rrbe.js} +1 -1
- package/dist/{index-xyfcpfec.js → index-dx9hjdp4.js} +2 -2
- package/dist/{index-97r6ekww.js → index-evnbrmdf.js} +1 -1
- package/dist/{index-r1v6p7vc.js → index-ggxs7nwz.js} +1 -1
- package/dist/{index-c4zn91z3.js → index-gz5t0vvc.js} +1 -1
- package/dist/{index-426ddch6.js → index-hp8jrj6j.js} +1 -1
- package/dist/{index-ywv7amgf.js → index-hrfkzecw.js} +1 -1
- package/dist/{index-4beawmtx.js → index-hz5cy6vz.js} +2 -2
- package/dist/{index-e0jbxcn1.js → index-jbxh0ffn.js} +2 -2
- package/dist/{index-sj39bx7y.js → index-js2r0men.js} +1 -1
- package/dist/{index-paxfq5k4.js → index-k3jkzj3k.js} +1 -1
- package/dist/{index-svtmb9t1.js → index-kteawn2b.js} +1 -1
- package/dist/{index-73qwyf9q.js → index-mbhq916m.js} +1 -1
- package/dist/{index-vd3njzs5.js → index-pnk33bjw.js} +5 -5
- package/dist/{index-34g3tenj.js → index-qdbxvcwr.js} +1 -1
- package/dist/{index-axgp7ryd.js → index-qqq9qyy6.js} +3 -3
- package/dist/{index-jq7vqe4a.js → index-sspydg85.js} +1 -1
- package/dist/{index-81gn264d.js → index-tk81f249.js} +1 -1
- package/dist/{index-sasygg1e.js → index-vjdg5qb2.js} +1 -1
- package/dist/{index-wqwzfy0e.js → index-vkrf8kzp.js} +2 -2
- package/dist/{index-d384edvr.js → index-vnxqna70.js} +1 -1
- package/dist/{index-w893wd2g.js → index-w2j4ttsx.js} +1 -1
- package/dist/{index-rhcsaqc0.js → index-w7gctzhm.js} +1 -1
- package/dist/{index-at6z8tds.js → index-x4eaagvr.js} +1 -1
- package/dist/{index-149rjxa5.js → index-xjr60th0.js} +1 -1
- package/dist/{index-a3mwtteb.js → index-xtbppqnv.js} +1 -1
- package/dist/{index-gmwpaz2a.js → index-zr9rmjyp.js} +1 -1
- package/dist/index.js +2 -2
- package/dist/injections-2g0zh0bq.js +2 -0
- package/dist/interactive-08vyaapn.js +2 -0
- package/dist/key.cmd-642xcxb4.js +2 -0
- package/dist/log-shipper-9xfnjwr6.js +2 -0
- package/dist/{path-utils-rzsac4g6.js → path-utils-g449hqvm.js} +1 -1
- package/dist/{plugin-system-jww7bh2a.js → plugin-system-gpzcch00.js} +1 -1
- package/dist/prereqs-runner-re9f51fp.js +2 -0
- package/dist/profile-mount-txvgkaz8.js +2 -0
- package/dist/prune-stale-shims-vs6a07tb.js +2 -0
- package/dist/register-core-e0ha52yw.js +2 -0
- package/dist/secondary-profile-attach-m9x9e7py.js +2 -0
- package/dist/subprocess-zcgpccp1.js +2 -0
- package/dist/telemetry-k6em3vy2.js +2 -0
- package/dist/tree-sitter-javascript-qh90w7td.js +2 -0
- package/dist/tree-sitter-markdown-favzteb6.js +2 -0
- package/dist/tree-sitter-markdown_inline-x2726t9j.js +2 -0
- package/dist/tree-sitter-typescript-m7ep8z1h.js +2 -0
- package/dist/tree-sitter-zig-3vsxg5wh.js +2 -0
- package/dist/tunnel-bootstrap-y8dczezc.js +2 -0
- package/package.json +1 -1
- package/dist/agent-config-t242qh84.js +0 -2
- package/dist/app-7rmybh7z.js +0 -2
- package/dist/autostart.cmd-arjjfy8k.js +0 -2
- package/dist/bootstrap-workspace-dvxqq79t.js +0 -2
- package/dist/bootstrap.service-3zpbgsg0.js +0 -2
- package/dist/daemon-profile-nbe3pww8.js +0 -2
- package/dist/gateway-client-dnjxwbnj.js +0 -2
- package/dist/highlights-3g7x1wxx.js +0 -2
- package/dist/highlights-66pe672g.js +0 -2
- package/dist/highlights-78tmcgkr.js +0 -2
- package/dist/highlights-dhv8z6p7.js +0 -2
- package/dist/highlights-j95xsvt4.js +0 -2
- package/dist/index-014sfc8c.js +0 -2
- package/dist/index-a9x5swye.js +0 -11
- package/dist/index-dpyv0pqb.js +0 -26
- package/dist/injections-2pt7wmtk.js +0 -2
- package/dist/interactive-svpgqn7v.js +0 -2
- package/dist/key.cmd-m0zst9pm.js +0 -2
- package/dist/log-shipper-m9h3jxem.js +0 -2
- package/dist/prereqs-runner-fhjjgzhw.js +0 -2
- package/dist/profile-mount-xchr4y5e.js +0 -2
- package/dist/prune-stale-shims-wttq2y0f.js +0 -2
- package/dist/register-core-n2kb3mhq.js +0 -2
- package/dist/secondary-profile-attach-yzwncw4f.js +0 -2
- package/dist/subprocess-chzm6zj2.js +0 -2
- package/dist/telemetry-h9pa43c9.js +0 -2
- package/dist/tree-sitter-javascript-jre8s337.js +0 -2
- package/dist/tree-sitter-markdown-3as64nwe.js +0 -2
- package/dist/tree-sitter-markdown_inline-rs74pnzp.js +0 -2
- package/dist/tree-sitter-typescript-dgsjhgb0.js +0 -2
- package/dist/tree-sitter-zig-p8cc70k0.js +0 -2
- package/dist/tunnel-bootstrap-6xm4w7dm.js +0 -2
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
2
|
+
import{ke as c,le as i,ne as l,qe as n}from"./index-gz5t0vvc.js";import{se as g}from"./index-mbhq916m.js";import{we as p}from"./index-xjr60th0.js";import{join as xJ}from"path";import{AsyncLocalStorage as IJ}from"async_hooks";import{mkdirSync as _J}from"fs";import{join as u}from"path";import{appendFileSync as r,existsSync as O,mkdirSync as e,readFileSync as JJ,readdirSync as ZJ,statSync as $J,unlinkSync as w}from"fs";import{join as F}from"path";var QJ=30,XJ=104857600,WJ=/secret|password|token|key|email/i,h=/^audit-(\d{4}-\d{2}-\d{2})\.log$/;function y(J=new Date){let Z=J.getUTCFullYear(),$=String(J.getUTCMonth()+1).padStart(2,"0"),Q=String(J.getUTCDate()).padStart(2,"0");return`${Z}-${$}-${Q}`}function k(J){if(Array.isArray(J))return J.map(k);if(J&&typeof J==="object"){let Z={};for(let[$,Q]of Object.entries(J)){if(WJ.test($)){Z[$]="[redacted]";continue}Z[$]=k(Q)}return Z}return J}function KJ(J,Z){if(!Z)return!0;if(Z.includes("*"))return new RegExp(`^${Z.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*")}$`).test(J);return J.includes(Z)}class I{profile;auditDir;constructor(J,Z){this.profile=J,this.auditDir=F(Z,"audit")}ensureDir(){if(!O(this.auditDir))e(this.auditDir,{recursive:!0});return this.auditDir}activeFilePath(){return F(this.ensureDir(),`audit-${y()}.log`)}emit(J,Z,$={}){let Q=k($),X={timestamp:new Date().toISOString(),source:J,event:Z,payload:{...Q,profile:this.profile}};try{r(this.activeFilePath(),`${JSON.stringify(X)}
|
|
3
3
|
`,{mode:384})}catch{}}listLogFiles(){if(!O(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(!O(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){w(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{w(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 oJ(){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 sJ(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 aJ(J){f.enterWith(J)}function G(){return f.getStore()?.requestId}var bJ=10485760,m=7,PJ=60000,b={debug:0,info:1,warn:2,error:3},OJ={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(),PJ),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=OJ[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},x=new IJ;function B2(J){x.enterWith(J)}class A{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 x.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-
|
|
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},x=new IJ;function B2(J){x.enterWith(J)}class A{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 x.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-k6em3vy2.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-txvgkaz8.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 x.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 T{profiles=new Map;create(J){if(this.profiles.has(J.name))throw Error(`profile already registered: ${J.name}`);let Z=new A(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 T,D=null;function AJ(){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 AJ()}function G2(J){let Z=i(J),$=j.get(Z);if($)return $;return j.create({name:Z,dataDir:xJ(n(),"agents",Z)})}async function b2(){D=null,await j.destroyAll()}var P=new Set(["localhost","127.0.0.1","0.0.0.0","::1","[::1]","host.docker.internal"]),TJ=new Set(["4000","4001","4002","4003"]),UJ=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(!P.has(Z))return!1;if(process.env.VIBECONTROLS_ALLOW_UNTRUSTED_GATEWAYS==="1")return!0;return TJ.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(UJ.has($))return Z.protocol==="https:";if(Z.protocol!=="https:")return!1;return EJ.has($)}catch{return!1}}function U(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 O2(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(P.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 vJ(J){if(!J)return null;let Z=J.trim().replace(/\/+$/,"");return SJ(Z)?Z:null}function k2(J){if(!J)return null;let Z=vJ(J);if(Z)return Z;let $=process.env.AGENT_TUNNEL_URL;if($&&J.trim().replace(/\/+$/,"")===$.trim().replace(/\/+$/,""))return fJ(J);return null}var wJ=new Set([".trycloudflare.com"]);function hJ(J){try{let Z=new URL(J.trim()),$=C(Z.hostname);if(P.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 I2(J){if(!J)return null;let Z=J.trim().replace(/\/+$/,"");return hJ(Z)?Z:null}function yJ(J){try{let Z=new URL(J.trim()),$=C(Z.hostname);if(P.has($))return Z.protocol==="http:"||Z.protocol==="https:";return Z.protocol==="https:"}catch{return!1}}function fJ(J){if(!J)return null;let Z=J.trim().replace(/\/+$/,"");return yJ(Z)?Z:null}function _2(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 mJ=/(?:\/(?:global|workspaces))?\/graphql$/i,gJ=1048576;function v(J){return J.trim().replace(/\/+$/,"").replace(mJ,"")}function a(J,Z){return`${v(J)}/${Z}/graphql`}function t(J){return J instanceof Error?J.message:String(J)}async function pJ(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=v(U(J.globalGatewayUrl,"globalGatewayUrl")),$=J.workspaceGatewayUrl?v(U(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
|
|
@@ -18,4 +18,4 @@ import{ee as c,fe as i,he as l,ke as n}from"./index-c4zn91z3.js";import{me as g}
|
|
|
18
18
|
}
|
|
19
19
|
}
|
|
20
20
|
`,variables:{input:{clientId:J.clientId,clientSecret:J.clientSecret,scopes:J.scopes??[]}}});if(Q.errors?.length||!Q.data?.authenticateApp){let K=Q.errors?.[0]?.message??"Authentication failed";throw B().logger.error("gateway-client",`Authentication failed: ${K}`),Error(`Gateway authentication failed: ${K}`)}let X=Q.data.authenticateApp,W={accessToken:X.accessToken,expiresAt:Date.now()+X.expiresIn*1000,scopes:X.scopes};if(Z!==this.configGeneration||J!==this.config)throw Error("Gateway configuration changed during authentication");return this.token=W,B().logger.info("gateway-client","Authenticated successfully",{expiresIn:X.expiresIn,scopes:X.scopes}),W.accessToken}async postGraphQL(J,Z,$){let Q;try{Q=await fetch(J,{method:"POST",headers:Z,body:JSON.stringify($),signal:AbortSignal.timeout(15000)})}catch(X){throw Error(`Could not reach gateway at ${J}: ${t(X)}`,{cause:X})}try{let X=await pJ(Q,gJ),W={};if(X)try{W=JSON.parse(X)}catch{let K=X.slice(0,240).replace(/\s+/g," ");throw Error(`Gateway returned a non-JSON response (${Q.status} ${Q.statusText}) from ${J}${K?`: ${K}`:""}`)}if(!Q.ok){let K=W.errors?.[0]?.message??`${Q.status} ${Q.statusText}`;throw Error(`Gateway request failed at ${J}: ${K} (${Q.status})`)}return W}catch(X){if(X instanceof Error)throw X;throw Error(`Failed to process gateway response from ${J}: ${t(X)}`,{cause:X})}}}function S(){let J=d();if(J)return J.gatewayClient;return B().gatewayClient}var uJ=new Proxy({},{get(J,Z,$){let Q=S(),X=Q[Z];return typeof X==="function"?X.bind(Q):X},set(J,Z,$){let Q=S();return Q[Z]=$,!0},has(J,Z){return Z in S()}}),E2=uJ;
|
|
21
|
-
export{oJ as
|
|
21
|
+
export{oJ as Jd,sJ as Kd,aJ as Ld,G as Md,U as Nd,O2 as Od,vJ as Pd,k2 as Qd,I2 as Rd,fJ as Sd,_2 as Td,v as Ud,R as Vd,uJ as Wd,E2 as Xd,B2 as Yd,d as Zd,j as _d,AJ as $d,B as ae,G2 as be,b2 as ce};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Zb as U}from"./index-
|
|
2
|
+
import{Zb as U}from"./index-jbxh0ffn.js";import"./index-wj5hx7gq.js";import{Bc as G,Dc as J,sc as i,uc as w,vc as C,yc as b,zc as v}from"./index-8xh8m2z7.js";import"./index-js2r0men.js";import{Pc as y,Qc as M,Rc as h,Sc as T}from"./index-kteawn2b.js";import"./index-2q2jadag.js";import{ae as $}from"./index-qqq9qyy6.js";import"./index-gz5t0vvc.js";import"./index-mbhq916m.js";import"./index-xjr60th0.js";var x={debug:0,info:1,warn:2,error:3};function j(o){if(!o)return;return o==="debug"||o==="info"||o==="warn"||o==="error"?o:void 0}function A(o,n,e,t){if(!o)return n;let r=parseInt(o,10);if(!Number.isInteger(r))return n;return Math.min(t,Math.max(e,r))}function L(o){return new U().get("/",async({query:n,set:e})=>{let t=n,r=j(t.level);if(t.level&&!r)return e.status=400,{error:"Invalid log level"};let m=await $().logger.readHistory({level:r,source:t.source,from:t.from,to:t.to,limit:A(t.limit,200,1,1000),offset:A(t.offset,0,0,1e5)});return{entries:m,count:m.length}}).get("/stream",({query:n,set:e})=>{let t=n,r=j(t.level);if(t.level&&!r)return e.status=400,{error:"Invalid log level"};let m=r??"info",a=t.source??"";return e.headers["Content-Type"]="text/event-stream",e.headers["Cache-Control"]="no-cache",e.headers.Connection="keep-alive",e.headers["X-Accel-Buffering"]="no",new ReadableStream({start(u){let c=new TextEncoder;u.enqueue(c.encode(`: connected
|
|
3
3
|
|
|
4
4
|
`));let s=(g)=>{if(x[g.level]<x[m])return;if(a&&!g.source.includes(a))return;try{u.enqueue(c.encode(`event: log
|
|
5
5
|
data: ${JSON.stringify(g)}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{E as A,G as N}from"./index-6jzsthh9.js";import{Yb as l,Zb as T}from"./index-
|
|
2
|
+
import{E as A,G as N}from"./index-6jzsthh9.js";import{Yb as l,Zb as T}from"./index-jbxh0ffn.js";import{nc as G,oc as D,pc as f}from"./index-wj5hx7gq.js";import{Ac as w,Cc as P,Dc as v,Hc as y,uc as d,vc as r,wc as j,yc as J,zc as U}from"./index-8xh8m2z7.js";import{Kc as E}from"./index-js2r0men.js";import{Pc as p,Rc as g,Sc as L,Tc as x,Uc as S,Vc as O}from"./index-kteawn2b.js";import"./index-2q2jadag.js";import"./index-qqq9qyy6.js";import"./index-gz5t0vvc.js";import"./index-mbhq916m.js";import"./index-xjr60th0.js";import{promises as R}from"fs";import C from"path";async function M(a){try{let n=await R.readdir(a);if(n.includes("package.json")){try{let i=JSON.parse(await R.readFile(C.join(a,"package.json"),"utf8")),o={...i.dependencies,...i.devDependencies};if(o.react||o["@types/react"])return"react";if(o.vue||o["@vue/cli"])return"vue";if(o.angular||o["@angular/core"])return"angular";if(o.next||o["@types/next"])return"nextjs";if(o.nuxt||o["@nuxt/core"])return"nuxtjs";if(o.svelte||o["@sveltejs/kit"])return"svelte";if(o.express||o.fastify||o.koa)return"nodejs-backend";if(o.electron)return"electron";if(o.vite)return"vite"}catch{}return"nodejs"}if(n.includes("setup.py")||n.includes("requirements.txt")||n.includes("pyproject.toml")||n.includes("Pipfile")){if(n.includes("manage.py"))return"django";if(n.includes("app.py"))return"flask";return"python"}if(n.includes("go.mod"))return"go";if(n.includes("Cargo.toml"))return"rust";if(n.includes("pom.xml"))return"maven";if(n.includes("build.gradle")||n.includes("build.gradle.kts"))return"gradle";if(n.includes("Gemfile"))return"ruby";if(n.includes("composer.json"))return"php";if(n.some((i)=>i.endsWith(".csproj")||i.endsWith(".sln")))return"dotnet";if(n.includes("CMakeLists.txt")||n.includes("Makefile"))return"cpp";if(n.includes("Package.swift"))return"swift";if(n.includes("pubspec.yaml"))return"flutter";if(n.some((i)=>i.endsWith(".tf")))return"terraform";if(n.includes("Dockerfile"))return"docker"}catch{}return}async function V(a){try{let n=["vite.config.ts","vite.config.js"];for(let i of n)try{let t=(await R.readFile(C.join(a,i),"utf-8")).match(/port:\s*(\d+)/);if(t)return parseInt(t[1],10)}catch{}}catch{}return}var Y=new Set([".git","node_modules","__pycache__",".venv","venv","dist","build"]),F=parseInt(process.env.VIBECONTROLS_GIT_SCAN_MAX_DEPTH??"8",10),z=parseInt(process.env.VIBECONTROLS_GIT_SCAN_MAX_DIRECTORIES??"5000",10);async function k(a,n,i,o={visited:0},t=0){let u=[];if(t>F||o.visited>=z)return u;o.visited+=1;try{let e=await N(a);if(e.some((c)=>c.name===".git"&&c.isDirectory())){if(u.push({path:a,name:C.basename(a),parentPath:i,isSubmodule:!!i,projectType:await M(a),vitePort:await V(a)}),!n)return u;i=a}for(let c of e)if(c.isDirectory()&&!c.isSymbolicLink()&&!Y.has(c.name)&&!c.name.startsWith(".")){let s=C.join(a,c.name),$=await k(s,n,i,o,t+1);u.push(...$)}}catch{}return u}function I(a){let{db:n}=a;return new T().get("/",async()=>{return{repositories:await n.getAllGitRepositories()}}).get("/:id",async({params:i,set:o})=>{let t=await n.getGitRepository(i.id);if(!t)return o.status=404,{error:"Repository not found"};return{repository:t}}).post("/scan",async({body:i,set:o})=>{try{let t=(await A(i.directory,{mustExist:!0})).path;if(!(await R.stat(t)).isDirectory())return o.status=400,{error:"Path is not a directory"};let e=await k(t,i.includeSubmodules??!0),m=[];for(let c of e){let s=await n.getGitRepositoryByPath(c.path);if(s)await n.updateGitRepository(s.id,c),m.push({...s,...c});else{let $=await n.createGitRepository({id:globalThis.crypto.randomUUID(),...c});m.push($)}}return{repositories:m,scannedPath:t,totalFound:m.length}}catch(t){return o.status=500,{error:"Failed to scan directory",details:String(t)}}},{body:l.Object({directory:l.String(),includeSubmodules:l.Optional(l.Boolean())})}).put("/:id",async({params:i,body:o,set:t})=>{if(!await n.getGitRepository(i.id))return t.status=404,{error:"Repository not found"};try{return await n.updateGitRepository(i.id,o),{success:!0}}catch(e){return t.status=500,{error:"Failed to update repository",details:String(e)}}},{body:l.Object({name:l.Optional(l.String()),projectType:l.Optional(l.String()),vitePort:l.Optional(l.Number())})}).delete("/:id",async({params:i,set:o})=>{if(!await n.getGitRepository(i.id))return o.status=404,{error:"Repository not found"};try{return await n.deleteGitRepository(i.id),{success:!0}}catch(u){return o.status=500,{error:"Failed to delete repository",details:String(u)}}}).post("/fix-hierarchy",async({set:i})=>{try{let o=await n.fixGitHierarchy(),t=await n.getAllGitRepositories();return{success:!0,fixed:o.fixed,total:t.length}}catch(o){return i.status=500,{error:"Failed to fix hierarchy",details:String(o)}}})}var h="http://localhost:3005";function q(a){let n=a.command("git").description("Manage git repositories");n.command("list").description("List discovered git repositories").option("--agent-url <url>","Agent URL",h).option("--json","Emit JSON").option("--plain","Force plain text output").action(async function(i){let o={...a.opts(),...i};try{let t=p(i),u=encodeURIComponent(g(o));await D({mode:G(o),fetchData:async()=>{return(await L(t,`/api/profiles/${u}/git`)).repositories||[]},plain:(e)=>{if(!e||e.length===0){J("No git repositories found.");return}U("Git Repositories"),P(e.map((m)=>({ID:y(m.id),Name:m.name||"-",Path:m.path||"-",Type:m.type||m.projectType||"-",Submodule:m.isSubmodule?"Yes":"No",Scanned:m.scannedAt?v(m.scannedAt):"-"})))},interactive:async(e)=>{if(!e||e.length===0){U("Git Repositories"),J("No git repositories found.");return}let m=e.map((c)=>({id:String(c.id),label:c.name||y(c.id),hint:c.type||c.projectType||"",detail:[`ID: ${c.id}`,`Name: ${c.name??"-"}`,`Path: ${c.path??"-"}`,`Type: ${c.type??c.projectType??"-"}`,`Submodule: ${c.isSubmodule?"Yes":"No"}`,`Scanned: ${c.scannedAt?v(c.scannedAt):"-"}`].join(`
|
|
3
3
|
`)}));await E({title:`vibe git list \u2014 ${e.length} repo(s)`,rows:m})},json:(e)=>e.map((m)=>({id:m.id,name:m.name??null,path:m.path??null,type:m.type??m.projectType??null,isSubmodule:!!m.isSubmodule,scannedAt:m.scannedAt??null}))})}catch(t){d(r(t))}}),n.command("scan").description("Scan a directory for git repositories").requiredOption("--dir <directory>","Directory to scan").option("--depth <depth>","Scan depth","3").option("--agent-url <url>","Agent URL",h).option("--json","Emit JSON").action(async function(i){let o={...a.opts(),...i};try{let t=p(i),u=encodeURIComponent(g(o)),e=await x(t,`/api/profiles/${u}/git/scan`,{directory:i.dir,depth:parseInt(i.depth,10)});if(f(o,{ok:!0,found:e?.found??e?.repositories?.length??0}))return;if(j("Git scan completed."),e?.found!==void 0)w("Repositories found",e.found);if(e?.repositories)w("Repositories found",e.repositories.length)}catch(t){if(o.json){f(o,{ok:!1,error:r(t)});return}d(r(t))}}),n.command("update").description("Update a git repository entry").requiredOption("-i, --id <id>","Repository ID").option("--vite-port <port>","Vite dev server port").option("--project-type <type>","Project type").option("--agent-url <url>","Agent URL",h).option("--json","Emit JSON").action(async function(i){let o={...a.opts(),...i};try{let t=p(i),u=encodeURIComponent(g(o)),e={};if(i.vitePort)e.vitePort=parseInt(i.vitePort,10);if(i.projectType)e.projectType=i.projectType;if(await S(t,`/api/profiles/${u}/git/${i.id}`,e),f(o,{ok:!0,id:i.id}))return;j(`Repository ${y(i.id)} updated.`)}catch(t){if(o.json){f(o,{ok:!1,error:r(t)});return}d(r(t))}}),n.command("delete").description("Delete a git repository entry").requiredOption("-i, --id <id>","Repository ID").option("--agent-url <url>","Agent URL",h).option("--json","Emit JSON").action(async function(i){let o={...a.opts(),...i};try{let t=p(i),u=encodeURIComponent(g(o));if(await O(t,`/api/profiles/${u}/git/${i.id}`),f(o,{ok:!0,id:i.id}))return;j(`Repository ${y(i.id)} deleted.`)}catch(t){if(o.json){f(o,{ok:!1,error:r(t)});return}d(r(t))}}),n.command("fix-hierarchy").description("Fix repository parent-child hierarchy").option("--agent-url <url>","Agent URL",h).option("--json","Emit JSON").action(async function(i){let o={...a.opts(),...i};try{let t=p(i),u=encodeURIComponent(g(o)),e=await x(t,`/api/profiles/${u}/git/fix-hierarchy`,{});if(f(o,{ok:!0,fixed:e?.fixed??null}))return;if(j("Hierarchy fix completed."),e?.fixed!==void 0)w("Fixed",e.fixed)}catch(t){if(o.json){f(o,{ok:!1,error:r(t)});return}d(r(t))}})}function H(a,n){q(a)}function eo(a){return{name:"git",version:"2.2.0",description:"Git repository scanning, tracking, and hierarchy management",capabilities:{storage:"rw",subprocess:!0,audit:!0,telemetry:!0},tags:["backend","cli"],cliCommand:"git",apiPrefix:"/api/git",createRoutes:(n)=>I(n),onCliSetup:async(n,i)=>{H(n,i)}}}export{eo as createPlugin};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{bb as h,cb as Z,db as S}from"./index-rmh8pff5.js";import{fb as K}from"./index-
|
|
2
|
+
import{bb as h,cb as Z,db as S}from"./index-rmh8pff5.js";import{fb as K}from"./index-x4eaagvr.js";import"./index-ekr40gvh.js";import{Yb as X,Zb as R}from"./index-jbxh0ffn.js";import{nc as N,oc as O,pc as D}from"./index-wj5hx7gq.js";import{Ac as U,Bc as j,Cc as C,sc as W,tc as _,uc as F,vc as A,wc as G,yc as $,zc as I}from"./index-8xh8m2z7.js";import"./index-js2r0men.js";import{Pc as V,Rc as M,Sc as q,Uc as E,Vc as J}from"./index-kteawn2b.js";import"./index-2q2jadag.js";import"./index-qqq9qyy6.js";import"./index-gz5t0vvc.js";import"./index-mbhq916m.js";import"./index-xjr60th0.js";function L(Q,w){if(Q==="telemetry.enabled")K.setEnabled(w==="true")}function v(Q){return Object.entries(Q).map(([w,x])=>({key:w,value:x}))}function T(Q){let{db:w}=Q;return new R().get("/",async()=>{let x=await w.getAllConfig(),B=S(x);return{config:B,configs:v(B)}}).get("/status",async()=>{return await w.getConfigStatus()}).get("/:key",async({params:x,set:B})=>{let H=await w.getConfig(x.key);if(H===void 0)return B.status=404,{error:"Configuration key not found"};return{key:x.key,value:Z(x.key,H)}}).put("/:key",async({params:x,body:B,set:H})=>{if(h(x.key))return H.status=403,{error:"Configuration key is managed by a dedicated endpoint"};try{return await w.setConfig(x.key,B.value),L(x.key,B.value),{success:!0}}catch(z){return H.status=500,{error:"Failed to set configuration",details:String(z)}}},{body:X.Object({value:X.String()})}).delete("/:key",async({params:x,set:B})=>{if(h(x.key))return B.status=403,{error:"Configuration key is managed by a dedicated endpoint"};if(await w.getConfig(x.key)===void 0)return B.status=404,{error:"Configuration key not found"};try{return await w.deleteConfig(x.key),{success:!0}}catch(z){return B.status=500,{error:"Failed to delete configuration",details:String(z)}}}).post("/",async({body:x,set:B})=>{if(h(x.key))return B.status=403,{error:"Configuration key is managed by a dedicated endpoint"};try{return await w.setConfig(x.key,x.value),L(x.key,x.value),{success:!0,key:x.key}}catch(H){return B.status=500,{error:"Failed to set configuration",details:String(H)}}},{body:X.Object({key:X.String(),value:X.String()})}).post("/bulk",async({body:x,set:B})=>{let H=Object.keys(x.configs).filter(h);if(H.length>0)return B.status=403,{error:"One or more configuration keys are managed by dedicated endpoints",keys:H};try{await w.bulkSetConfig(x.configs);for(let[z,P]of Object.entries(x.configs))L(z,P);return{success:!0}}catch(z){return B.status=500,{error:"Failed to set configuration",details:String(z)}}},{body:X.Object({configs:X.Record(X.String(),X.String())})})}var f="http://localhost:3005";function u(Q){Q.command("config").description("Manage VibeControls agent configuration").option("--set <key=value>","Set a configuration value").option("--get <key>","Get a configuration value").option("--delete <key>","Delete a configuration value").option("--list","List all configuration values",!1).option("--value <value>","Value used with `--set <key>` (alternative to `--set key=value`)").option("--agent-url <url>","Agent URL",f).option("--json","Emit JSON").option("--plain","Force plain text output").action(async function(w){let x={...Q.opts(),...w};try{let B=V(w),H=encodeURIComponent(M(x));if(w.set){let z=w.set.indexOf("="),P,Y;if(z===-1){if(w.value===void 0){if(x.json){D(x,{ok:!1,error:"Invalid format: use key=value or --set key --value v"});return}F(`Invalid format. Use ${W.bold("--set key=value")} or ${W.bold("--set key --value value")}`);return}P=w.set.trim(),Y=String(w.value).trim()}else P=w.set.slice(0,z).trim(),Y=w.set.slice(z+1).trim();if(!P){if(x.json){D(x,{ok:!1,error:"Configuration key cannot be empty"});return}F("Configuration key cannot be empty.");return}if(await E(B,`/api/profiles/${H}/config/${encodeURIComponent(P)}`,{value:Y}),D(x,{ok:!0,key:P}))return;G(`${_.success} Set ${W.bold(P)} = ${W.cyan(String(Z(P,Y)))}`)}else if(w.get)await O({mode:N(x),fetchData:()=>q(B,`/api/profiles/${H}/config/${encodeURIComponent(w.get)}`),plain:(z)=>{I("Configuration"),j(),U(z.key,W.bold(String(Z(z.key,z.value)))),j()},json:(z)=>({key:z.key,value:Z(z.key,z.value)})});else if(w.delete){if(await J(B,`/api/profiles/${H}/config/${encodeURIComponent(w.delete)}`),D(x,{ok:!0,key:w.delete}))return;G(`${_.success} Deleted configuration key: ${W.bold(w.delete)}`)}else if(w.list)await O({mode:N(x),fetchData:()=>q(B,`/api/profiles/${H}/config/`),plain:(z)=>{if(I("Agent Configuration"),j(),!z.configs||z.configs.length===0){$(`${_.info} No configuration entries found.`);return}let P=z.configs.map((Y)=>({Key:Y.key,Value:String(Z(Y.key,Y.value))}));C(P),j(),$(`${_.info} ${z.configs.length} configuration(s) found.`)},json:(z)=>(z.configs??[]).map((P)=>({key:P.key,value:Z(P.key,P.value)}))});else{if(x.json){D(x,{ok:!1,error:"No operation specified"});return}$(`${_.info} Usage:`),$(` ${W.bold("vibe config --list")} List all config values`),$(` ${W.bold("vibe config --get <key>")} Get a config value`),$(` ${W.bold("vibe config --set <key=value>")} Set a config value`),$(` ${W.bold("vibe config --delete <key>")} Delete a config value`)}}catch(B){if(x.json){D(x,{ok:!1,error:A(B)});return}F(`Config operation failed: ${A(B)}`)}})}function k(Q,w){u(Q)}function d(Q){return{name:"config",version:"2.2.0",description:"Agent configuration key-value store",capabilities:{storage:"rw",audit:!0},tags:["backend","cli"],cliCommand:"config",apiPrefix:"/api/config",createRoutes:(w)=>T(w),onCliSetup:async(w,x)=>{k(w,x)}}}export{d as createPlugin};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{d as m,e as H2}from"./index-r1v6p7vc.js";import{z as c}from"./index-xyfcpfec.js";import"./index-97r6ekww.js";import"./index-rhcsaqc0.js";import"./index-hey6w5m0.js";import{Na as Z2,Oa as $2,Pa as z2,Ra as W2,Xa as d}from"./index-2244sbdx.js";import"./index-ea42kfvk.js";import"./index-jnrqbhew.js";import"./index-d384edvr.js";import{Vb as X2,Wb as Y2}from"./index-bv1z3fxw.js";import{Yb as J,Zb as V2}from"./index-e0jbxcn1.js";import{nc as l,oc as t,pc as R}from"./index-wj5hx7gq.js";import{Ac as A,Cc as i,sc as k,uc as q,vc as O,wc as S,xc as I,yc as _,zc as u}from"./index-6nz3c1ys.js";import{Kc as s,Lc as G2}from"./index-sj39bx7y.js";import{Pc as U,Rc as E,Sc as n,Tc as h}from"./index-svtmb9t1.js";import"./index-a9x5swye.js";import{Wd as y}from"./index-axgp7ryd.js";import"./index-c4zn91z3.js";import"./index-73qwyf9q.js";import{qe as L}from"./index-149rjxa5.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-jww7bh2a.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-
|
|
2
|
+
import{d as m,e as H2}from"./index-ggxs7nwz.js";import{z as c}from"./index-dx9hjdp4.js";import"./index-evnbrmdf.js";import"./index-w7gctzhm.js";import"./index-hey6w5m0.js";import{Na as Z2,Oa as $2,Pa as z2,Ra as W2,Xa as d}from"./index-7wejfjj9.js";import"./index-ea42kfvk.js";import"./index-3p4n7nwg.js";import"./index-vnxqna70.js";import{Vb as X2,Wb as Y2}from"./index-bv1z3fxw.js";import{Yb as J,Zb as V2}from"./index-jbxh0ffn.js";import{nc as l,oc as t,pc as R}from"./index-wj5hx7gq.js";import{Ac as A,Cc as i,sc as k,uc as q,vc as O,wc as S,xc as I,yc as _,zc as u}from"./index-8xh8m2z7.js";import{Kc as s,Lc as G2}from"./index-js2r0men.js";import{Pc as U,Rc as E,Sc as n,Tc as h}from"./index-kteawn2b.js";import"./index-2q2jadag.js";import{ae as y}from"./index-qqq9qyy6.js";import"./index-gz5t0vvc.js";import"./index-mbhq916m.js";import{we as L}from"./index-xjr60th0.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-gpzcch00.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-gpzcch00.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-gpzcch00.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-gpzcch00.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-gpzcch00.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-gpzcch00.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-gpzcch00.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
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
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
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)+`
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Xb as GY}from"./index-bv1z3fxw.js";import{Zb as JY}from"./index-
|
|
2
|
+
import{Xb as GY}from"./index-bv1z3fxw.js";import{Zb as JY}from"./index-jbxh0ffn.js";import{Wc as jY,Xc as k,td as l,vd as d}from"./index-2q2jadag.js";import{Zd as HY,_d as BY,ae as V}from"./index-qqq9qyy6.js";import{ke as P}from"./index-gz5t0vvc.js";import{randomBytes as K,createHmac as g,timingSafeEqual as UY}from"crypto";var T=600,r=600,A=K(32),M="p2.";function S(Y){if(!Y.startsWith("/"))return`/${Y}`;return Y.length>1&&Y.endsWith("/")?Y.slice(0,-1):Y}var wY=/^\/terminal\/[A-Za-z0-9_-]{1,128}(?:\/.*)?$/,XY=/^\/ui\/[a-z0-9-]{1,64}(?:\/.*)?$/,NY=/^\/plan\/[A-Za-z0-9_-]{1,128}(?:\/.*)?$/,bY=/^\/git(?:\/.*)?$/,OY="/ws/logs",LY=/^\/code-server(?:\/.*)?$/,CY=/^\/api\/plugins\/[a-z0-9-]{1,64}\/ui(?:\/.*)?$/;function a(Y){if(typeof Y!=="string"||Y.length===0)return!1;if(Y.includes("\x00")||Y.includes(`
|
|
3
3
|
`)||Y.includes("|"))return!1;if(Y.includes(".."))return!1;if(new Set(["/","/api","/api/agent","/api/plugins","/api/profiles","/health","/metrics","/ws","/api/ai","/api/logs"]).has(Y))return!1;if(wY.test(Y))return!0;if(XY.test(Y))return!0;if(NY.test(Y))return!0;if(bY.test(Y))return!0;if(Y===OY)return!0;if(LY.test(Y))return!0;if(CY.test(Y))return!0;return!1}var DY=new Set(["*","GET","HEAD","POST","PUT","PATCH","DELETE","OPTIONS"]);function MY(Y){if(!Y||Y.length===0)return["*"];let Z=new Set,$=[];for(let Q of Y){if(typeof Q!=="string")continue;let W=Q.toUpperCase();if(!DY.has(W))throw Error(`invalid method: ${Q}`);if(!Z.has(W))Z.add(W),$.push(W)}if($.length===0)return["*"];return $.sort()}function i(Y,Z){if(Y.includes("*"))return!0;return Y.includes(Z.toUpperCase())}var KY=/^[A-Za-z0-9_-]{1,128}$/;function SY(Y){return typeof Y==="string"&&KY.test(Y)}function h(Y,Z,$){return g("sha256",A).update(`${Y}
|
|
4
4
|
${Z}
|
|
5
5
|
${$}`).digest("hex")}var y=new Map;function kY(Y){for(let[Z,$]of y)if($<=Y)y.delete(Z)}function t(Y,Z){let $=Date.parse(Z);if(!Number.isFinite($))return;y.set(Y,$)}function e(Y){return kY(Date.now()),y.has(Y)}function c(Y,Z,$,Q){return g("sha256",A).update(`v2
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{$a as l}from"./index-ea42kfvk.js";import{pc as C}from"./index-wj5hx7gq.js";import{Ac as Z,Bc as T,uc as D,wc as O,xc as j,yc as V,zc as U}from"./index-
|
|
2
|
+
import{$a as l}from"./index-ea42kfvk.js";import{pc as C}from"./index-wj5hx7gq.js";import{Ac as Z,Bc as T,uc as D,wc as O,xc as j,yc as V,zc as U}from"./index-8xh8m2z7.js";import{ne as i,pe as m}from"./index-gz5t0vvc.js";import{existsSync as Q,mkdirSync as F,writeFileSync as y,unlinkSync as g,readFileSync as a}from"fs";import{join as J}from"path";import{homedir as W,platform as w}from"os";import{isAbsolute as s,resolve as e}from"path";function v(){return i()}function A(){return J(v(),"logs")}function N(){if(process.execPath&&process.execPath.includes("bun"))return process.execPath;let q=l().which("bun");if(q)return q;throw Error("Could not find bun binary. Ensure bun is installed and in PATH.")}function S(){return import.meta.dir.endsWith("/dist")||import.meta.dir.includes("/dist/")?J(import.meta.dir,"index.js"):J(import.meta.dir,"..","..","index.ts")}function E(q,z){if(/[\0\r\n]/.test(q))throw Error(`${z} contains invalid control characters`)}function L(q){if(!/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(q))throw Error("Agent name must use 1-64 characters: letters, numbers, dot, underscore, or dash.");return q}function t(q){let z=parseInt(q,10);if(!Number.isInteger(z)||z<1||z>65535)throw Error("Port must be an integer between 1 and 65535");return z}function X(q){return E(q,"systemd value"),`"${q.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`}function M(q){let z=String(q);return E(z,"plist value"),z.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function b(q){let z=J(W(),".config","systemd","user");return F(z,{recursive:!0}),J(z,`vibecontrols-agent-${q}.service`)}function r(q){return`[Unit]
|
|
3
3
|
Description=VibeControls Agent (${q.name})
|
|
4
4
|
After=network.target
|
|
5
5
|
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Wa as k}from"./index-
|
|
2
|
+
import{Wa as k}from"./index-7wejfjj9.js";import{Ab as f,Db as c,Ib as F,Jb as h,Kb as S,Lb as q,Nb as N}from"./index-vnxqna70.js";import{Zb as P}from"./index-jbxh0ffn.js";import{ae as V}from"./index-qqq9qyy6.js";var U=["tunnel","session","ai","plan","gitops","security"];class m{providers=new Map;providerOrder=new Map;defaults=new Map;services=new Map;db;constructor(z){this.db=z}getDb(){return this.db}setProviderDefault(z,J){this.defaults.set(z,J)}clearProviderDefault(z,J){if(!J||this.defaults.get(z)===J)this.defaults.delete(z)}async hydrateDefaultsFromDb(){if(!this.db)return;for(let z of U)try{let J=await this.db.getConfig(`provider:default:${z}`);if(J)this.defaults.set(z,J)}catch{}}registerProvider(z,J,Q){if(!this.providers.has(z))this.providers.set(z,new Map),this.providerOrder.set(z,[]);let W=this.providers.get(z),Z=this.providerOrder.get(z);if(W.has(Q))V().logger.info("service-registry",`Updating ${z} provider from plugin '${Q}'`);else V().logger.info("service-registry",`Registered ${z} provider from plugin '${Q}'`);if(W.set(Q,{provider:J,pluginName:Q,registeredAt:new Date}),!Z.includes(Q))Z.push(Q)}getProvider(z){let J=this.providers.get(z);if(!J||J.size===0)return;let Q=this.defaults.get(z);if(Q&&J.has(Q))return J.get(Q).provider;let W=this.providerOrder.get(z);if(W&&W.length>0){let Z=W[0];return J.get(Z)?.provider}return}getProviderByName(z,J){let Q=this.providers.get(z);if(!Q)return;return Q.get(J)?.provider}hasProvider(z){let J=this.providers.get(z);return!!J&&J.size>0}unregisterProvider(z,J){let Q=this.providers.get(z);if(!Q)return!1;let W=Q.delete(J);if(W){let Z=this.providerOrder.get(z);if(Z){let X=Z.indexOf(J);if(X!==-1)Z.splice(X,1)}this.clearProviderDefault(z,J),V().logger.info("service-registry",`Unregistered ${z} provider from plugin '${J}'`)}return W}unregisterPlugin(z){for(let J of U)this.unregisterProvider(J,z);this.unregisterServices(z)}listProvidersForType(z){let J=this.providers.get(z);if(!J)return[];let Q=this.defaults.get(z);if(!Q||!J.has(Q)){let W=this.providerOrder.get(z);Q=W&&W.length>0?W[0]:void 0}return Array.from(J.keys()).map((W)=>({pluginName:W,isDefault:W===Q}))}registerService(z,J,Q){let W=`${z}:${J}`;this.services.set(W,{service:Q,pluginName:z}),V().logger.debug("service-registry",`Registered service '${W}'`)}getService(z,J){let Q=`${z}:${J}`;return this.services.get(Q)?.service}unregisterServices(z){let J=[];for(let[Q,W]of this.services)if(W.pluginName===z)J.push(Q);for(let Q of J)this.services.delete(Q);if(J.length>0)V().logger.info("service-registry",`Unregistered ${J.length} services from ${z}`)}listProviders(){let z=[];for(let[J,Q]of this.providers)for(let[W,Z]of Q)z.push({type:J,name:W,pluginName:Z.pluginName});return z}listServices(){return Array.from(this.services.entries()).map(([z,J])=>({pluginName:J.pluginName,serviceName:z.split(":").slice(1).join(":")}))}clear(){this.providers.clear(),this.providerOrder.clear(),this.defaults.clear(),this.services.clear()}}import{extname as g,relative as o,resolve as u}from"path";import{realpath as E}from"fs/promises";var n=["'self'","http://localhost:*","http://127.0.0.1:*","https://localhost:*","https://127.0.0.1:*","https://*.local.burdenoff.com","https://vibecontrols.com","https://*.vibecontrols.com","https://burdenoff.com","https://app.burdenoff.com","https://alphaapp.burdenoff.com"],D=!1;function w(){let z=process.env.VIBE_UI_FRAME_ANCESTORS?.trim(),J=z?z.split(/[\s,]+/).filter(Boolean):n;if(z&&!D&&(J.includes("*")||!J.includes("'self'")))D=!0,console.warn(`[ui-server] VIBE_UI_FRAME_ANCESTORS override does not include "'self'" or contains "*". This significantly weakens CSP frame-ancestors and is almost never intended. Override: ${z}`);return`frame-ancestors ${J.join(" ")}`}var l={".html":"text/html",".js":"application/javascript",".mjs":"application/javascript",".css":"text/css",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".map":"application/json",".wasm":"application/wasm"};function s(z){return l[g(z).toLowerCase()]||"application/octet-stream"}var b=`<script>
|
|
3
3
|
window.__VIBE_AUTH__={apiKey:null};
|
|
4
4
|
(function(){
|
|
5
5
|
var p=new URLSearchParams(window.location.search);
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{gb as Y,hb as k}from"./index-ekr40gvh.js";import{
|
|
2
|
+
import{gb as Y,hb as k}from"./index-ekr40gvh.js";import{ae as W}from"./index-qqq9qyy6.js";import{qe as V}from"./index-gz5t0vvc.js";import{createHash as g,randomUUID as x}from"crypto";import{existsSync as $,mkdirSync as L,readFileSync as O,writeFileSync as j}from"fs";import{join as K}from"path";import*as X from"os";var A="https://analytics.burdenoff.com/api/track",H="cd7d5ccc3667",w=200,f=10,B=30000,R=5000;function C(q){if(process.env.DO_NOT_TRACK==="1")return!1;let z=process.env.VIBECONTROLS_TELEMETRY?.toLowerCase();if(z==="on"||z==="true"||z==="1")return!0;if(z==="off"||z==="false"||z==="0")return!1;return q}class M{enabled=!1;persisted=!1;buffer=[];flushTimer=null;cachedAnonymousId=null;overflowWarned=!1;postFailureWarned=!1;initialized=!1;init(q){if(q?.persisted!==void 0)this.persisted=q.persisted;if(this.enabled=C(this.persisted),!this.initialized)this.initialized=!0,this.startFlushTimer()}setEnabled(q){let z=this.enabled;if(this.persisted=q,this.enabled=C(this.persisted),z&&!this.enabled)this.buffer=[],this.enqueueRaw("telemetry.disabled",{reason:"user_opt_out"}),this.flush()}emit(q,z={}){if(!this.enabled)return;let G={},J=!1;for(let[Z,N]of Object.entries(z)){if(Y(Z)){J=!0;continue}G[Z]=N}let Q=k(q,G);if(!Q.ok||!Q.sanitized){W().logger.warn("telemetry",`dropping event '${q}': ${Q.reason??"invalid"}`);return}this.enqueue(q,Q.sanitized)}enqueueRaw(q,z){this.enqueue(q,z)}enqueue(q,z){let G={site_id:H,event_name:q,properties:z,anonymous_id:this.getAnonymousId(),timestamp:new Date().toISOString()};if(this.buffer.length>=w){if(this.buffer.shift(),!this.overflowWarned)this.overflowWarned=!0,W().logger.warn("telemetry",`buffer overflow (cap=${w}) \u2014 dropping oldest events`)}if(this.buffer.push(G),this.buffer.length>=f)this.flush()}async flush(){if(this.buffer.length===0)return;let q=this.buffer.splice(0,this.buffer.length),z=new AbortController,G=setTimeout(()=>z.abort(),R);try{await fetch(A,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({events:q}),signal:z.signal})}catch(J){if(!this.postFailureWarned)this.postFailureWarned=!0,W().logger.warn("telemetry","shipper POST failed; dropping batch",{error:String(J)})}finally{clearTimeout(G)}}stop(){if(this.flushTimer)clearInterval(this.flushTimer),this.flushTimer=null;this.initialized=!1}_resetForTest(){this.stop(),this.enabled=!1,this.persisted=!1,this.buffer=[],this.cachedAnonymousId=null,this.overflowWarned=!1,this.postFailureWarned=!1}_bufferLength(){return this.buffer.length}_isEnabled(){return this.enabled}startFlushTimer(){if(this.flushTimer)return;if(this.flushTimer=setInterval(()=>{this.flush()},B),typeof this.flushTimer.unref==="function")this.flushTimer.unref()}getAnonymousId(){if(this.cachedAnonymousId)return this.cachedAnonymousId;let q=`${X.hostname()}${X.platform()}`,z=this.readOrCreateInstallId(),G=g("sha256").update(q+z).digest("hex");return this.cachedAnonymousId=G.slice(0,16),this.cachedAnonymousId}readOrCreateInstallId(){let q;try{q=V()}catch{q=K(process.cwd(),".boff","vibecontrols")}if(!$(q))try{L(q,{recursive:!0,mode:448})}catch{}let z=K(q,".install-id");if($(z))try{let J=O(z,"utf-8").trim();if(J)return J}catch{}let G=x();try{j(z,G,{mode:384})}catch{}return G}}var b=new M;
|
|
3
3
|
export{b as fb};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
2
|
var j=Object.create;var{getPrototypeOf:k,defineProperty:f,getOwnPropertyNames:l}=Object;var m=Object.prototype.hasOwnProperty;function n(a){return this[a]}var o,p,s=(a,b,c)=>{var g=a!=null&&typeof a==="object";if(g){var h=b?o??=new WeakMap:p??=new WeakMap,i=h.get(a);if(i)return i}c=a!=null?j(k(a)):{};let d=b||!a||!a.__esModule?f(c,"default",{value:a,enumerable:!0}):c;for(let e of l(a))if(!m.call(d,e))f(d,e,{get:n.bind(a,e),enumerable:!0});if(g)h.set(a,d);return d};var t=(a,b)=>()=>(b||a((b={exports:{}}).exports,b),b.exports);var q=(a)=>a;function r(a,b){this[a]=q.bind(null,b)}var u=(a,b)=>{for(var c in b)f(a,c,{get:b[c],enumerable:!0,configurable:!0,set:r.bind(b,c)})};var v=import.meta.require;
|
|
3
|
-
export{s as
|
|
3
|
+
export{s as te,t as ue,u as ve,v as we};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{$a as R}from"./index-ea42kfvk.js";import{fb as j}from"./index-
|
|
2
|
+
import{$a as R}from"./index-ea42kfvk.js";import{fb as j}from"./index-x4eaagvr.js";import{Od as D,Sd as P,Zd as g,ae as M}from"./index-qqq9qyy6.js";import{ke as y,ne as x,oe as A}from"./index-gz5t0vvc.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 pa,F as qa,C as ra,xG as sa,HG as ta,AG as ua,bG as va,SG as wa,vG as xa,KG as ya};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{nc as O,oc as L,pc as Y}from"./index-wj5hx7gq.js";import{Ac as X,Bc as I,Cc as K,sc as D,uc as R,vc as U,wc as W,yc as C,zc as E}from"./index-
|
|
2
|
+
import{nc as O,oc as L,pc as Y}from"./index-wj5hx7gq.js";import{Ac as X,Bc as I,Cc as K,sc as D,uc as R,vc as U,wc as W,yc as C,zc as E}from"./index-8xh8m2z7.js";import{Wc as J,td as T,vd as V,xd as w}from"./index-2q2jadag.js";import{ke as h}from"./index-gz5t0vvc.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 _b,f as $b};
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
3
|
-
import{j as e,k as QQ,l as XQ,m as ZQ,n as HQ}from"./index-
|
|
3
|
+
import{j as e,k as QQ,l as XQ,m as ZQ,n as HQ}from"./index-4gsn3d9r.js";import"./index-hrfkzecw.js";import{t as $Q}from"./index-2sn36kaj.js";import"./index-dx9hjdp4.js";import"./index-6jzsthh9.js";import"./index-qdbxvcwr.js";import"./index-xtbppqnv.js";import"./index-29fmptfn.js";import"./index-w7gctzhm.js";import"./index-hey6w5m0.js";import{Ha as t}from"./index-7wejfjj9.js";import"./index-ea42kfvk.js";import"./index-rmh8pff5.js";import{fb as T}from"./index-x4eaagvr.js";import"./index-ekr40gvh.js";import"./index-3p4n7nwg.js";import{Mb as o,Nb as r}from"./index-vnxqna70.js";import"./index-bv1z3fxw.js";import"./index-jbxh0ffn.js";import"./index-kteawn2b.js";import{Hd as s,Id as a,Wc as i,Xc as m,td as E,xd as y}from"./index-2q2jadag.js";import{ae as q}from"./index-qqq9qyy6.js";import{ke as k,ne as S,pe as n,qe as U}from"./index-gz5t0vvc.js";import"./index-mbhq916m.js";import{we as B}from"./index-xjr60th0.js";async function P(Q,H={}){let X=H.readConfig??(async()=>{let Z=await y();return{clientId:Z.clientId,clientSecret:Z.clientSecret,workspaceId:Z.workspaceId,organizationId:Z.organizationId,globalGatewayUrl:Z.globalGatewayUrl,workspaceGatewayUrl:Z.workspaceGatewayUrl}});try{let Z=H.pinned?.clientId&&H.pinned?.clientSecret?{clientId:H.pinned.clientId,clientSecret:H.pinned.clientSecret}:null,Y=await X();if(!Y.clientId||!Y.clientSecret)return Q;return{clientId:Z?.clientId??Y.clientId,clientSecret:Z?.clientSecret??Y.clientSecret,workspaceId:Y.workspaceId??Q.workspaceId,organizationId:Y.organizationId??Q.organizationId,globalGatewayUrl:Y.globalGatewayUrl??Q.globalGatewayUrl,workspaceGatewayUrl:Y.workspaceGatewayUrl??Q.workspaceGatewayUrl}}catch(Z){let Y=Z instanceof Error?Z.message:String(Z);if(H.onReadError)H.onReadError(Y);else q().logger.warn("finalize-retry","Could not re-read stored credentials; retrying with the boot-time pair",{error:Y});return Q}}import{isAbsolute as EQ}from"path";import{existsSync as V,mkdirSync as d,readFileSync as IQ,readdirSync as f,renameSync as TQ,unlinkSync as yQ,writeFileSync as g}from"fs";import{dirname as c,join as F}from"path";var WQ=".secrets-migrated-v1",JQ=["static-api-key","clientId","clientSecret"];function VQ(Q,H){return`${Q}:${H}`}function p(){return F(U(),WQ)}function FQ(){let Q=p();d(c(Q),{recursive:!0}),g(Q,`${new Date().toISOString()}
|
|
4
4
|
`,{mode:384})}function KQ(Q){if(!V(Q))return null;try{let H=IQ(Q,"utf8"),X=JSON.parse(H);if(X&&typeof X==="object"&&!Array.isArray(X))return X}catch{}return null}function MQ(Q,H){d(c(Q),{recursive:!0});let X=`${Q}.${process.pid}.tmp`;g(X,`${JSON.stringify(H,null,2)}
|
|
5
|
-
`,{mode:384}),TQ(X,Q)}function UQ(){let Q=U(),H=F(Q,"agents");if(!V(H))return[];let X=[],Z;try{Z=f(H)}catch{return[]}for(let Y of Z){let z=F(H,Y,"config.json");if(!V(z))continue;X.push({path:z,scope:Y})}return X}function RQ(){let Q=U(),H=F(Q,"profiles");if(!V(H))return[];let X=[],Z;try{Z=f(H)}catch{return[]}for(let Y of Z){if(!Y.endsWith(".json"))continue;X.push({path:F(H,Y),scope:Y.slice(0,-5)})}return X}async function jQ(Q,H){let X=KQ(Q);if(!X)return 0;let Z=0;for(let Y of JQ){let z=X[Y];if(typeof z!=="string"||z.length===0)continue;let _=VQ(H,Y);try{await m(_,z),delete X[Y],Z++,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(Z>0)MQ(Q,X);return Z}async function l(){let Q={alreadyMigrated:!1,fieldsMoved:0,filesUpdated:0};if(V(p()))return Q.alreadyMigrated=!0,Q;let H=[...UQ(),...RQ()];for(let X of H){let Z;try{Z=await jQ(X.path,X.scope)}catch(Y){q().logger.warn("secrets-migrator","skipping target after error",{path:X.path,error:String(Y)});continue}if(Z>0)Q.fieldsMoved+=Z,Q.filesUpdated++}try{FQ()}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=(Z,Y)=>{try{return Q(Z,Y)}catch(z){if(typeof Z==="string"&&Z.endsWith("}}"))try{return Q(Z.slice(0,-1),Y)}catch{}throw z}};let X=globalThis.Request?.prototype;if(X&&typeof X.json==="function"){let Z=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 Z.call(_)}}}}$Q();s();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 wQ(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 w=(()=>{try{return k()}catch{return"default"}})(),x=Number.parseInt(process.env.PORT||String(wQ(w)),10),R=Number.isInteger(x)&&x>0?x:3005,j=process.env.HOST||"0.0.0.0",CQ=(()=>{let Q=process.env.DB_PATH;if(!Q)return;if(EQ(Q))return Q;console.warn(`[boot] Ignoring relative DB_PATH=${Q} (cwd=${process.cwd()}). Use an absolute path or unset to fall back to ${n()}.`);return})(),D=process.env.AGENT_API_KEY||void 0,AQ=process.env.LOG_LEVEL||"info",xQ=process.env.CORS_ORIGIN||void 0;async function DQ(){try{await l()}catch(L){q().logger.warn("server","secrets migration encountered an error",{error:String(L)})}let Q=E()["static-api-key"],H=(()=>{try{return k()}catch{return"default"}})(),X=Q??await i(`${H}:static-api-key`),Z=!D&&!X;await o();let Y={clientId:process.env.VIBE_CLIENT_ID,clientSecret:process.env.VIBE_CLIENT_SECRET};await a();let z=process.env.VIBE_CLIENT_ID,_=process.env.VIBE_CLIENT_SECRET,G=process.env.VIBE_GLOBAL_GATEWAY_URL,u=process.env.VIBE_WORKSPACE_GATEWAY_URL,h=process.env.VIBE_WORKSPACE_ID,YQ=!!z&&!!_&&!!G&&!!u&&!!h;q().logger.info("server","Starting VibeControls Agent...",{runtime:"bun",bunVersion:Bun.version,port:R,host:j,env:"production"});try{let L=E(),$=L["telemetry.enabled"]===!0||L["telemetry.enabled"]==="true";T.init({persisted:$});let N=Date.now();T.emit("agent.started",{version:process.env.npm_package_version??"unknown",profile:w,platform:process.platform}),process.__vibe_started_at=N}catch{}let K=Math.max(1,Number.parseInt(process.env.VIBECONTROLS_AGENT_BOOT_RETRIES??"10",10)||10),LQ=(L)=>{let $=String(L?.message??L).toLowerCase();return $.includes("syntax")||$.includes("cannot find module")||$.includes("module not found")||$.includes("typeerror")||$.includes("config schema")||$.includes("invalid config")||$.includes("corrupt")||$.includes("eaccess")||$.includes("eperm")},O=null,I=0;while(!O){I++;try{O=await HQ({port:R,host:j,dbPath:CQ,apiKey:D,logLevel:AQ,corsOrigin:xQ}),await O.start();try{let L=await import("fs"),$=`${S()}/runtime.json`;L.writeFileSync($,JSON.stringify({pid:process.pid,port:R,host:j,profile:w,startedAt:new Date().toISOString(),version:t()},null,2));let N=()=>{try{if(L.existsSync($))L.unlinkSync($)}catch{}};process.once("SIGTERM",N),process.once("SIGINT",N),process.once("exit",N)}catch(L){q().logger.warn("server","Could not write runtime.json",{error:String(L)})}}catch(L){let $=LQ(L);if(q().logger.error("server","Failed to start agent server",{attempt:I,maxBootAttempts:K,fatal:$,error:String(L)}),$||I>=K)console.error(`\u274C Failed to start VibeControls Agent (attempt ${I}/${K}, fatal=${$}):`,L),process.exit(1);let N=Math.min(30000,1000*2**Math.min(5,I-1)),J=Math.floor(Math.random()*500),M=N+J;console.warn(`\u26A0\uFE0F Agent boot attempt ${I}/${K} failed (transient), retrying in ${Math.round(M/1000)}s...`),await new Promise((A)=>setTimeout(A,M)),O=null}}let b=O.getServiceRegistry().getProvider("tunnel"),W=null;if(b?.getActiveTunnelUrl)for(let L=0;L<30;L++){if(W=await b.getActiveTunnelUrl(),W)break;await new Promise(($)=>setTimeout($,1000))}if(!W){let{sanitizeEnvSuffix:L}=await import("./tunnel-bootstrap-
|
|
5
|
+
`,{mode:384}),TQ(X,Q)}function UQ(){let Q=U(),H=F(Q,"agents");if(!V(H))return[];let X=[],Z;try{Z=f(H)}catch{return[]}for(let Y of Z){let z=F(H,Y,"config.json");if(!V(z))continue;X.push({path:z,scope:Y})}return X}function RQ(){let Q=U(),H=F(Q,"profiles");if(!V(H))return[];let X=[],Z;try{Z=f(H)}catch{return[]}for(let Y of Z){if(!Y.endsWith(".json"))continue;X.push({path:F(H,Y),scope:Y.slice(0,-5)})}return X}async function jQ(Q,H){let X=KQ(Q);if(!X)return 0;let Z=0;for(let Y of JQ){let z=X[Y];if(typeof z!=="string"||z.length===0)continue;let _=VQ(H,Y);try{await m(_,z),delete X[Y],Z++,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(Z>0)MQ(Q,X);return Z}async function l(){let Q={alreadyMigrated:!1,fieldsMoved:0,filesUpdated:0};if(V(p()))return Q.alreadyMigrated=!0,Q;let H=[...UQ(),...RQ()];for(let X of H){let Z;try{Z=await jQ(X.path,X.scope)}catch(Y){q().logger.warn("secrets-migrator","skipping target after error",{path:X.path,error:String(Y)});continue}if(Z>0)Q.fieldsMoved+=Z,Q.filesUpdated++}try{FQ()}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=(Z,Y)=>{try{return Q(Z,Y)}catch(z){if(typeof Z==="string"&&Z.endsWith("}}"))try{return Q(Z.slice(0,-1),Y)}catch{}throw z}};let X=globalThis.Request?.prototype;if(X&&typeof X.json==="function"){let Z=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 Z.call(_)}}}}$Q();s();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 wQ(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 w=(()=>{try{return k()}catch{return"default"}})(),x=Number.parseInt(process.env.PORT||String(wQ(w)),10),R=Number.isInteger(x)&&x>0?x:3005,j=process.env.HOST||"0.0.0.0",CQ=(()=>{let Q=process.env.DB_PATH;if(!Q)return;if(EQ(Q))return Q;console.warn(`[boot] Ignoring relative DB_PATH=${Q} (cwd=${process.cwd()}). Use an absolute path or unset to fall back to ${n()}.`);return})(),D=process.env.AGENT_API_KEY||void 0,AQ=process.env.LOG_LEVEL||"info",xQ=process.env.CORS_ORIGIN||void 0;async function DQ(){try{await l()}catch(L){q().logger.warn("server","secrets migration encountered an error",{error:String(L)})}let Q=E()["static-api-key"],H=(()=>{try{return k()}catch{return"default"}})(),X=Q??await i(`${H}:static-api-key`),Z=!D&&!X;await o();let Y={clientId:process.env.VIBE_CLIENT_ID,clientSecret:process.env.VIBE_CLIENT_SECRET};await a();let z=process.env.VIBE_CLIENT_ID,_=process.env.VIBE_CLIENT_SECRET,G=process.env.VIBE_GLOBAL_GATEWAY_URL,u=process.env.VIBE_WORKSPACE_GATEWAY_URL,h=process.env.VIBE_WORKSPACE_ID,YQ=!!z&&!!_&&!!G&&!!u&&!!h;q().logger.info("server","Starting VibeControls Agent...",{runtime:"bun",bunVersion:Bun.version,port:R,host:j,env:"production"});try{let L=E(),$=L["telemetry.enabled"]===!0||L["telemetry.enabled"]==="true";T.init({persisted:$});let N=Date.now();T.emit("agent.started",{version:process.env.npm_package_version??"unknown",profile:w,platform:process.platform}),process.__vibe_started_at=N}catch{}let K=Math.max(1,Number.parseInt(process.env.VIBECONTROLS_AGENT_BOOT_RETRIES??"10",10)||10),LQ=(L)=>{let $=String(L?.message??L).toLowerCase();return $.includes("syntax")||$.includes("cannot find module")||$.includes("module not found")||$.includes("typeerror")||$.includes("config schema")||$.includes("invalid config")||$.includes("corrupt")||$.includes("eaccess")||$.includes("eperm")},O=null,I=0;while(!O){I++;try{O=await HQ({port:R,host:j,dbPath:CQ,apiKey:D,logLevel:AQ,corsOrigin:xQ}),await O.start();try{let L=await import("fs"),$=`${S()}/runtime.json`;L.writeFileSync($,JSON.stringify({pid:process.pid,port:R,host:j,profile:w,startedAt:new Date().toISOString(),version:t()},null,2));let N=()=>{try{if(L.existsSync($))L.unlinkSync($)}catch{}};process.once("SIGTERM",N),process.once("SIGINT",N),process.once("exit",N)}catch(L){q().logger.warn("server","Could not write runtime.json",{error:String(L)})}}catch(L){let $=LQ(L);if(q().logger.error("server","Failed to start agent server",{attempt:I,maxBootAttempts:K,fatal:$,error:String(L)}),$||I>=K)console.error(`\u274C Failed to start VibeControls Agent (attempt ${I}/${K}, fatal=${$}):`,L),process.exit(1);let N=Math.min(30000,1000*2**Math.min(5,I-1)),J=Math.floor(Math.random()*500),M=N+J;console.warn(`\u26A0\uFE0F Agent boot attempt ${I}/${K} failed (transient), retrying in ${Math.round(M/1000)}s...`),await new Promise((A)=>setTimeout(A,M)),O=null}}let b=O.getServiceRegistry().getProvider("tunnel"),W=null;if(b?.getActiveTunnelUrl)for(let L=0;L<30;L++){if(W=await b.getActiveTunnelUrl(),W)break;await new Promise(($)=>setTimeout($,1000))}if(!W){let{sanitizeEnvSuffix:L}=await import("./tunnel-bootstrap-y8dczezc.js"),{getVibecontrolsProfile:$}=await import("./path-utils-g449hqvm.js"),N=L($());W=process.env[`AGENT_TUNNEL_URL_${N}`]??process.env.AGENT_TUNNEL_URL??null}let NQ=E(),qQ=D||r()||NQ["static-api-key"]||"",C=q().getBootState(),zQ=C==="ready"?null:e();if(C==="ready")QQ();kQ({port:R,host:j,tunnelUrl:W,apiKey:qQ,revealApiKey:Z||process.env.AGENT_PRINT_API_KEY==="1",state:C,pairingToken:zQ});try{XQ({profile:w})}catch(L){q().logger.warn("server","Could not start autoupdate",{error:String(L)})}let{existsSync:OQ,unlinkSync:_Q}=await import("fs"),{tmpdir:BQ}=await import("os"),{join:GQ}=await import("path"),v=async(L)=>{q().logger.info("server",`Received ${L}, shutting down...`),ZQ();try{let N=process.__vibe_started_at??Date.now();T.emit("agent.stopped",{uptime_s:Math.round((Date.now()-N)/1000),reason:L}),await T.flush(),T.stop()}catch{}let $=O.getLifecycle();if(L==="SIGTERM"){let N=GQ(BQ(),`.boff-vibecontrols-kill-${process.pid}`);if(OQ(N)){try{_Q(N)}catch{}if(q().logger.info("server","Kill-intent flag detected \u2014 full shutdown"),$)await $.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)"),$)await $.softStop();else await O.stop({reason:"reload"})}else if($)await $.kill();else await O.stop({reason:"shutdown"}),process.exit(0)};if(process.on("SIGINT",()=>v("SIGINT")),process.on("SIGTERM",()=>v("SIGTERM")),YQ){let L=(()=>{let $=process.env.VIBECONTROLS_FINALIZE_TIMEOUT_MS,N=$?Number.parseInt($,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(L/1000)}s)`),(async()=>{let $={clientId:z,clientSecret:_,workspaceId:h,globalGatewayUrl:G,workspaceGatewayUrl:u};try{let N=await Promise.race([O.finalize($),new Promise((J)=>setTimeout(()=>J({ok:!1,error:`inline finalize timed out after ${Math.round(L/1000)}s`}),L))]);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-wb8wj1yw.js"),{setFinalizeRetryHandle:M}=await import("./finalize-retry-handle-registry-fvm4gm8s.js"),A=J({trigger:async()=>O.finalize(await P($,{pinned:Y}))});M(A)}}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",Z="\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(Z),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(Z),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("")}DQ();
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{$b as b,_b as a}from"./index-zr9rmjyp.js";import"./index-8q19ryt2.js";import"./index-wj5hx7gq.js";import"./index-8xh8m2z7.js";import"./index-js2r0men.js";import"./index-kteawn2b.js";import"./index-2q2jadag.js";import"./index-qqq9qyy6.js";import"./index-gz5t0vvc.js";import"./index-mbhq916m.js";import"./index-xjr60th0.js";export{a as resolveDefaultApiKey,b as register};
|