@vibecontrols/agent 2026.814.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-gx1yqwjk.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-zye1vz1y.js → bridge-client-bgkr7bcn.js} +1 -1
- package/dist/cli.js +1 -1
- package/dist/daemon-profile-j2wt35x8.js +2 -0
- package/dist/esm-n9r8p5n2.js +2 -0
- package/dist/{finalize-retry-handle-registry-kzfqhvwv.js → finalize-retry-handle-registry-fvm4gm8s.js} +1 -1
- package/dist/{finalize-retry-worker-74wxbdsh.js → finalize-retry-worker-wb8wj1yw.js} +1 -1
- package/dist/gateway-client-6dqagbg4.js +2 -0
- package/dist/{getMachineId-bsd-65jabrgp.js → getMachineId-bsd-fgatzdd7.js} +1 -1
- package/dist/{getMachineId-darwin-yykv9khr.js → getMachineId-darwin-gt8j2jw2.js} +1 -1
- package/dist/{getMachineId-linux-w09acg2n.js → getMachineId-linux-bcz4rr1x.js} +1 -1
- package/dist/{getMachineId-unsupported-dwr7bb60.js → getMachineId-unsupported-079qwwb4.js} +1 -1
- package/dist/{getMachineId-win-0wkw4jek.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-gx53t38f.js → index-06es0fmw.js} +1 -1
- package/dist/{index-wndzw5pk.js → index-0d4wfjbt.js} +2 -2
- package/dist/{index-2gwc485c.js → index-29fmptfn.js} +2 -2
- package/dist/index-2q2jadag.js +11 -0
- package/dist/{index-16czz4df.js → index-2sn36kaj.js} +1 -1
- package/dist/{index-m2kkd6t6.js → index-3p4n7nwg.js} +2 -2
- package/dist/{index-qzhvhyvq.js → index-3tf12pw3.js} +1 -1
- package/dist/index-4gsn3d9r.js +26 -0
- package/dist/{index-e1bw1bwr.js → index-54mmh1eb.js} +1 -1
- package/dist/{index-5wsfsj88.js → index-7wejfjj9.js} +4 -4
- package/dist/{index-g9fthh7a.js → index-8q19ryt2.js} +2 -2
- package/dist/{index-c975k3pk.js → index-8xh8m2z7.js} +3 -3
- package/dist/index-a8n6s2ae.js +2 -0
- package/dist/{index-2bjqvapr.js → index-b16y8wyz.js} +1 -1
- package/dist/{index-5dysvvjv.js → index-bv1z3fxw.js} +1 -1
- package/dist/{index-nj7bvgws.js → index-df19rrbe.js} +1 -1
- package/dist/{index-jrxbbb7p.js → index-dx9hjdp4.js} +2 -2
- package/dist/{index-0ckffygp.js → index-ea42kfvk.js} +1 -1
- package/dist/{index-52cp759f.js → index-ekr40gvh.js} +1 -1
- package/dist/{index-13xxbf03.js → index-evnbrmdf.js} +2 -2
- package/dist/{index-7vwefvxd.js → index-ggxs7nwz.js} +1 -1
- package/dist/{index-q9dp55wv.js → index-gz5t0vvc.js} +1 -1
- package/dist/{index-4wgjx8bf.js → index-hey6w5m0.js} +1 -1
- package/dist/{index-1ptfacy9.js → index-hp8jrj6j.js} +1 -1
- package/dist/{index-zabjc8f2.js → index-hrfkzecw.js} +1 -1
- package/dist/{index-b5dhmybd.js → index-hwpmdq5z.js} +1 -1
- package/dist/{index-r49hb09r.js → index-hz5cy6vz.js} +2 -2
- package/dist/{index-zaw78sxw.js → index-jbxh0ffn.js} +3 -3
- package/dist/{index-0s81cfpe.js → index-js2r0men.js} +2 -2
- package/dist/{index-jb3v3b39.js → index-k3jkzj3k.js} +1 -1
- package/dist/{index-e2dqz3tw.js → index-kteawn2b.js} +2 -2
- package/dist/{index-ntj6ymk8.js → index-mbhq916m.js} +1 -1
- package/dist/index-pnk33bjw.js +116 -0
- package/dist/{index-4gt22c81.js → index-qdbxvcwr.js} +2 -2
- package/dist/{index-c4p1qcnn.js → index-qqq9qyy6.js} +3 -3
- package/dist/{index-rc79x8fw.js → index-rmh8pff5.js} +1 -1
- package/dist/{index-wd2ak0q4.js → index-sspydg85.js} +1 -1
- package/dist/{index-5s2zc91f.js → index-tk81f249.js} +1 -1
- package/dist/{index-8k78bp4w.js → index-vjdg5qb2.js} +1 -1
- package/dist/{index-c0fgge10.js → index-vkrf8kzp.js} +2 -2
- package/dist/{index-9g3vxhby.js → index-vnxqna70.js} +2 -2
- package/dist/index-w2j4ttsx.js +130 -0
- package/dist/{index-pc05r6fd.js → index-w7gctzhm.js} +2 -2
- package/dist/{index-8nqp3a4d.js → index-wj5hx7gq.js} +1 -1
- package/dist/{index-53qthjhb.js → index-x4eaagvr.js} +2 -2
- package/dist/{index-gb5bnx7a.js → index-xjr60th0.js} +1 -1
- package/dist/{index-zb7nfmts.js → index-xtbppqnv.js} +2 -2
- package/dist/{index-jqfsvf8f.js → index-zr9rmjyp.js} +2 -2
- package/dist/index.js +3 -3
- 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-cg1gsy4m.js → path-utils-g449hqvm.js} +1 -1
- package/dist/plugin-system-gpzcch00.js +2 -0
- 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-hzzh97dn.js +0 -2
- package/dist/app-k3dex7x4.js +0 -2
- package/dist/bootstrap-workspace-dg1e3fp6.js +0 -2
- package/dist/bootstrap.service-nbhhd4pa.js +0 -2
- package/dist/daemon-profile-ryakpcbx.js +0 -2
- package/dist/esm-cg5tnbkd.js +0 -2
- package/dist/gateway-client-8y9yd0ch.js +0 -2
- package/dist/highlights-5wfvq2xq.js +0 -2
- package/dist/highlights-fdyzf5xj.js +0 -2
- package/dist/highlights-g5bek66n.js +0 -2
- package/dist/highlights-scv26t06.js +0 -2
- package/dist/highlights-tx5ed845.js +0 -2
- package/dist/index-2jxqpj7r.js +0 -26
- package/dist/index-nwh7j7ap.js +0 -2
- package/dist/index-sv4rzv3f.js +0 -11
- package/dist/index-tcwmw7ed.js +0 -231
- package/dist/injections-agpjxatz.js +0 -2
- package/dist/interactive-ewe5szk5.js +0 -2
- package/dist/key.cmd-xefsd8p4.js +0 -2
- package/dist/log-shipper-4h1k4kp6.js +0 -2
- package/dist/plugin-system-ksatnqp4.js +0 -2
- package/dist/prereqs-runner-6yf1e5e3.js +0 -2
- package/dist/profile-mount-13qvjqbg.js +0 -2
- package/dist/prune-stale-shims-t6kdd2an.js +0 -2
- package/dist/register-core-9k4zxnsg.js +0 -2
- package/dist/secondary-profile-attach-42x68g0c.js +0 -2
- package/dist/subprocess-6m8bja6s.js +0 -2
- package/dist/telemetry-mq37zapd.js +0 -2
- package/dist/tree-sitter-javascript-emqv64wx.js +0 -2
- package/dist/tree-sitter-markdown-v98rp3y1.js +0 -2
- package/dist/tree-sitter-markdown_inline-5gq03gn2.js +0 -2
- package/dist/tree-sitter-typescript-gr7ymg9w.js +0 -2
- package/dist/tree-sitter-zig-59q80fch.js +0 -2
- package/dist/tunnel-bootstrap-50fm2wt8.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{Zd as c,_d as i,ae as l,de as n}from"./index-q9dp55wv.js";import{fe 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,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
2
|
var o=new Set(["static-api-key","plugin-state:external-config"]),s=["gateway-auth:"],c=[/(^|[-_:])secret($|[-_:])/i,/(^|[-_:])token($|[-_:])/i,/(^|[-_:])password($|[-_:])/i,/(^|[-_:])api[-_]?key($|[-_:])/i,/^static-api-key$/i,/^gateway-auth:/i,/^clientSecret$/i,/^plugin-state:external-config$/i],E="[redacted]";function g(t){return o.has(t)||s.some((n)=>t.startsWith(n))}function i(t){return c.some((n)=>n.test(t))}function a(t,n){return i(t)&&n!==void 0?"[redacted]":n}function f(t){return Object.fromEntries(Object.entries(t).map(([n,e])=>[n,a(n,e)]))}function r(t){if(Array.isArray(t))return t.map((n)=>r(n));if(!t||typeof t!=="object")return t;return Object.fromEntries(Object.entries(t).map(([n,e])=>[n,i(n)?"[redacted]":r(e)]))}
|
|
3
|
-
export{E as
|
|
3
|
+
export{E as ab,g as bb,a as cb,f as db,r as eb};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
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{
|
|
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{
|
|
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-7vwefvxd.js";import{z as c}from"./index-jrxbbb7p.js";import"./index-13xxbf03.js";import"./index-pc05r6fd.js";import"./index-4wgjx8bf.js";import{Ja as Z2,Ka as $2,La as z2,Na as W2,Ta as d}from"./index-5wsfsj88.js";import"./index-0ckffygp.js";import"./index-m2kkd6t6.js";import"./index-9g3vxhby.js";import{Rb as X2,Sb as Y2}from"./index-5dysvvjv.js";import{Ub as J,Vb as V2}from"./index-zaw78sxw.js";import{jc as l,kc as t,lc as R}from"./index-8nqp3a4d.js";import{oc as k,qc as q,rc as O,sc as S,tc as I,uc as _,vc as u,wc as A,yc as i}from"./index-c975k3pk.js";import{Gc as s,Hc as G2}from"./index-0s81cfpe.js";import{Lc as U,Nc as E,Oc as n,Pc as h}from"./index-e2dqz3tw.js";import"./index-sv4rzv3f.js";import{Pd as y}from"./index-c4p1qcnn.js";import"./index-q9dp55wv.js";import"./index-ntj6ymk8.js";import{je as L}from"./index-gb5bnx7a.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-ksatnqp4.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{
|
|
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
|
|
@@ -13,4 +13,4 @@ ${$}`).digest("hex")}function aY(Y,Z=u){if(!SY(Y))throw Error("invalid sid");let
|
|
|
13
13
|
${Y}
|
|
14
14
|
${Z}
|
|
15
15
|
${$}`).digest("hex")}function eY(Y,Z=f){if(!gY(Y))throw Error("invalid plugin name");let $=Math.min(Math.max(1,Math.floor(Z||f)||f),_Y),Q=new Date(Date.now()+$*1000).toISOString(),W=K(16).toString("hex"),z=$Y(Y,Q,W);return{token:`${x}${Q}|${Y}|${W}|${z}`,expiresAt:Q}}function YZ(Y,Z){if(!Y||typeof Y!=="string")return!1;if(!Y.startsWith(x))return!1;let Q=Y.slice(x.length).split("|");if(Q.length!==4)return!1;let[W,z,J,j]=Q;if(!W||!z||!J||!j)return!1;if(z!==Z)return!1;if(!C(W))return!1;let G=$Y(z,W,J);return L(G,j)}function AY(Y,Z){let $;if(Y instanceof Headers)$=Y.get("cookie")??Y.get("Cookie")??void 0;else $=Y.cookie??Y.Cookie??void 0;if(!$)return null;let Q=`vt_ui_${Z}`;for(let W of $.split(";")){let z=W.indexOf("=");if(z===-1)continue;if(W.slice(0,z).trim()!==Q)continue;return W.slice(z+1).trim()||null}return null}function ZZ(Y,Z){return AY(Y.headers,Z)}import{timingSafeEqual as PY}from"crypto";var lY=["/health","/ui","/code-server","/terminal","/plan","/git","/api/agent/status","/api/agent/version","/api/agent/identity","/api/agent/terminal-exchange","/api/agent/ui-exchange","/api/agent/ui-exchange-plugin","/metrics"];function QY(Y,Z){if(!Z||Z==="/")return!1;let $=Z.endsWith("/")?Z.slice(0,-1):Z;return Y===$||Y.startsWith(`${$}/`)}function uY(Y){let Z=Y.replace(/^\/api\/profiles\/[^/]+/,"/api");return Z==="/api"?"/":Z}function fY(Y){let Z=/^\/api\/profiles\/([^/]+)(?:\/|$)/.exec(Y);if(!Z)return null;let $=Z[1];if(!$)return null;return $}function WY(Y,Z){let $=[Y],Q=uY(Y);if(Q!==Y)$.push(Q);for(let W of $){if(lY.some((z)=>QY(W,z)))return!0;if(Z.some((z)=>QY(W,z)))return!0}return!1}function VY(){let Y=new Uint8Array(32);return crypto.getRandomValues(Y),`vcak_${Buffer.from(Y).toString("base64url")}`}var U=null;function n(){return`${P()}:static-api-key`}async function vZ(){let Y=process.env.AGENT_API_KEY;if(Y)return U=Y,Y;let Z=n(),$=await jY(Z);if($)return U=$,$;let Q=l({dir:V().dataDir})["static-api-key"];if(Q){try{await k(Z,Q)}catch(z){V().logger.warn("auth","could not persist legacy api key into secrets backend",{error:String(z)})}return U=Q,Q}let W=VY();return await k(Z,W),U=W,V().logger.info("auth","Generated and persisted new agent API key"),V().audit.emit("agent","apikey.minted",{profile:P(),via:"loadAgentApiKey"}),W}function q(){let Y=process.env.AGENT_API_KEY;if(Y)return Y;if(U!==null)return U;let Z=l()["static-api-key"];if(Z)return U=Z,Z;let $=VY();U=$;try{d({"static-api-key":$},{dir:V().dataDir,scope:V().name})}catch{}return k(n(),$).catch(()=>{}),$}async function UZ(Y){if(process.env.AGENT_API_KEY)throw Error("AGENT_API_KEY is pinned via the environment \u2014 cannot rotate the key at runtime. Update the env var and restart.");let Z=(Y??"").trim();if(!/^vcak_[A-Za-z0-9_-]{16,}$/.test(Z))throw Error("Invalid agent API key format (expected vcak_<base64url>).");U=Z,await k(n(),Z);try{d({"static-api-key":Z},{dir:V().dataDir,scope:V().name})}catch{}V().audit.emit("agent","apikey.rotated",{profile:P(),via:"reset-key"})}function mY(Y){let Z=Y["x-agent-api-key"]??Y["X-Agent-Api-Key"];if(Z)return Z;let $=Y.authorization??Y.Authorization;if($?.startsWith("Bearer "))return $.slice(7);return null}function xY(Y){return!1}function hY(Y,Z){let $=mY(Object.fromEntries(Y.headers.entries()));if($)return $;if(!xY(Z))return null;try{let Q=new URL(Y.url).searchParams.get("apiKey");if(Q)return Q}catch{}return null}function F(Y,Z){let $=Buffer.from(Y),Q=Buffer.from(Z);if($.length!==Q.length)return!1;try{return PY($,Q)}catch{return!1}}function wZ(Y){if(!Y)return!1;return F(Y,q())}async function cY(Y,Z){if(!Y)return!1;let $=fY(Z);if($){let Q=BY.get($);if(Q){try{if(await Q.keyVault.match(Y))return!0}catch{}if($===V().name){try{if(await V().keyVault.match(Y))return!0}catch{}return F(Y,q())}return!1}}try{if(await V().keyVault.match(Y))return!0}catch{}if(F(Y,q()))return!0;if(oY(Y)!==null)return!0;return!1}function oY(Y){if(!Y)return null;if(F(Y,q()))return{name:"default",scopes:new Set(["admin"])};let Z=HY()??V(),$=l({dir:Z.dataDir}),Q=Date.now();for(let W of $.apiKeys??[]){if(!F(Y,W.key))continue;if(W.notBefore){let z=Date.parse(W.notBefore);if(Number.isFinite(z)&&Q<z)return null}if(W.expiresAt){let z=Date.parse(W.expiresAt);if(Number.isFinite(z)&&Q>=z)return null}return{name:W.name,scopes:new Set(W.scopes)}}return null}function XZ(Y,Z){if(!Y)return!1;if(Y.scopes.has("admin"))return!0;return Z.some(($)=>Y.scopes.has($))}var X=null;function p(Y,Z){try{V().audit.emit("auth",Y,Z)}catch{V().logger.warn("auth.audit",Y,Z)}}function pY(Y){let Z=new Set(Y());if(X===null)for(let $ of Z)p("plugin.public_path.declared",{path:$});else{for(let $ of Z)if(!X.has($))p("plugin.public_path.added",{path:$});for(let $ of X)if(!Z.has($))p("plugin.public_path.removed",{path:$})}return X=Z,Z}function NZ(){X=null}function zY(Y){if(!Y)return[];if(X===null)return[...pY(Y)];return[...X]}function bZ(Y){let Z=q();return V().logger.info("auth",`Agent API key: ${Z.substring(0,8)}****${Z.substring(Z.length-4)}`),new JY({name:"plugin/auth"}).decorate("apiKey",Z).derive(async({request:$,path:Q})=>{let W=zY(Y),z;if(WY(Q,W))z=!0;else if(GY($.headers))z=!0;else{let J=o($,Q);if(J&&YY(J,Q,$.method))z=!0;else{let j=hY($,Q);z=await cY(j,Q)}}return{isAuthenticated:z}}).onBeforeHandle(({isAuthenticated:$,request:Q,path:W,set:z})=>{let J=zY(Y);if(!$&&!WY(W,J)){if(o(Q,W))return z.status=401,{error:"invalid iframe token"};return z.status=401,{error:"Unauthorized",message:"Invalid or missing API key"}}}).as("global")}
|
|
16
|
-
export{SY as
|
|
16
|
+
export{SY as xb,nY as yb,sY as zb,YY as Ab,FY as Bb,rY as Cb,o as Db,aY as Eb,iY as Fb,IY as Gb,tY as Hb,gY as Ib,eY as Jb,YZ as Kb,ZZ as Lb,vZ as Mb,q as Nb,UZ as Ob,mY as Pb,wZ as Qb,oY as Rb,XZ as Sb,NZ as Tb,bZ as Ub};
|
|
@@ -0,0 +1,130 @@
|
|
|
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-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
|
+
Description=VibeControls Agent (${q.name})
|
|
4
|
+
After=network.target
|
|
5
|
+
|
|
6
|
+
[Service]
|
|
7
|
+
Type=simple
|
|
8
|
+
ExecStart=${X(q.bunPath)} run ${X(q.entryPoint)}
|
|
9
|
+
Environment=${X(`PORT=${q.port}`)}
|
|
10
|
+
Environment=${X(`DB_PATH=${q.dbPath}`)}
|
|
11
|
+
Environment=NODE_ENV=production${q.profile?`
|
|
12
|
+
Environment=${X(`VIBECONTROLS_PROFILE=${q.profile}`)}`:""}${q.profiles?`
|
|
13
|
+
Environment=${X(`VIBECONTROLS_PROFILES=${q.profiles}`)}`:""}${q.home?`
|
|
14
|
+
Environment=${X(`VIBECONTROLS_HOME=${q.home}`)}`:""}${q.isolatePlugins?`
|
|
15
|
+
Environment=${X(`VIBE_ISOLATE_PLUGINS=${q.isolatePlugins}`)}`:""}
|
|
16
|
+
Environment=${X(`AGENT_LOG_FILE=${q.logFile}`)}
|
|
17
|
+
Environment=${X(`HOME=${W()}`)}
|
|
18
|
+
Environment=${X(`PATH=${process.env.PATH??""}`)}
|
|
19
|
+
WorkingDirectory=${X(W())}
|
|
20
|
+
Restart=always
|
|
21
|
+
RestartSec=5
|
|
22
|
+
StandardOutput=append:${q.logFile}
|
|
23
|
+
StandardError=append:${q.logFile}
|
|
24
|
+
|
|
25
|
+
[Install]
|
|
26
|
+
WantedBy=default.target
|
|
27
|
+
`}async function qq(q,z,G,H={}){L(q),E(G,"dbPath");let K=N(),Y=S(),$=J(A(),`${q}.log`),_=b(q),B=`vibecontrols-agent-${q}.service`;F(A(),{recursive:!0});let R=r({name:q,port:z,dbPath:G,bunPath:K,entryPoint:Y,logFile:$,profile:H.profile,profiles:H.profiles,home:H.home,isolatePlugins:H.isolatePlugins});y(_,R),V(`Wrote systemd unit: ${_}`);let I=[["systemctl","--user","daemon-reload"],["systemctl","--user","enable",B],...H.skipStart?[]:[["systemctl","--user","start",B]]];for(let u of I){let h=Bun.spawnSync(u);if(h.exitCode!==0){let c=h.stderr.toString().trim();j(`Command failed: ${u.join(" ")}${c?` \u2014 ${c}`:""}`)}}if(Bun.spawnSync(["loginctl","enable-linger",process.env.USER||""]).exitCode===0)V("Enabled user linger (service survives logout)");O(`Autostart installed for agent '${q}' on port ${z}`),Z("Service",B),Z("Unit file",_),Z("Log file",$),T(),V(`Check status: systemctl --user status ${B}`)}async function zq(q){let z=`vibecontrols-agent-${q}.service`,G=b(q),H=[["systemctl","--user","stop",z],["systemctl","--user","disable",z]];for(let K of H)Bun.spawnSync(K);if(Q(G))g(G),V(`Removed unit file: ${G}`);Bun.spawnSync(["systemctl","--user","daemon-reload"]),O(`Autostart removed for agent '${q}'`)}async function Gq(q){let z=`vibecontrols-agent-${q}.service`,G=b(q);if(!Q(G)){V(`Autostart is NOT configured for agent '${q}'`),Z("Expected unit",G);return}U(`Autostart Status \u2014 ${q}`),Z("Unit file",G),Z("Service",z),T();let K=Bun.spawnSync(["systemctl","--user","status",z]).stdout.toString().trim();if(K)console.log(K);else V("Service status unavailable")}function f(q){let z=J(W(),"Library","LaunchAgents");return F(z,{recursive:!0}),J(z,`com.boff.vibecontrols.agent.${q}.plist`)}function p(q){return`<?xml version="1.0" encoding="UTF-8"?>
|
|
28
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
29
|
+
<plist version="1.0">
|
|
30
|
+
<dict>
|
|
31
|
+
<key>Label</key>
|
|
32
|
+
<string>com.boff.vibecontrols.agent.${M(q.name)}</string>
|
|
33
|
+
<key>ProgramArguments</key>
|
|
34
|
+
<array>
|
|
35
|
+
<string>${M(q.bunPath)}</string>
|
|
36
|
+
<string>run</string>
|
|
37
|
+
<string>${M(q.entryPoint)}</string>
|
|
38
|
+
</array>
|
|
39
|
+
<key>EnvironmentVariables</key>
|
|
40
|
+
<dict>
|
|
41
|
+
<key>PORT</key>
|
|
42
|
+
<string>${M(q.port)}</string>
|
|
43
|
+
<key>DB_PATH</key>
|
|
44
|
+
<string>${M(q.dbPath)}</string>
|
|
45
|
+
<key>NODE_ENV</key>
|
|
46
|
+
<string>production</string>${q.profile?`
|
|
47
|
+
<key>VIBECONTROLS_PROFILE</key>
|
|
48
|
+
<string>${M(q.profile)}</string>`:""}${q.profiles?`
|
|
49
|
+
<key>VIBECONTROLS_PROFILES</key>
|
|
50
|
+
<string>${M(q.profiles)}</string>`:""}${q.home?`
|
|
51
|
+
<key>VIBECONTROLS_HOME</key>
|
|
52
|
+
<string>${M(q.home)}</string>`:""}${q.isolatePlugins?`
|
|
53
|
+
<key>VIBE_ISOLATE_PLUGINS</key>
|
|
54
|
+
<string>${M(q.isolatePlugins)}</string>`:""}
|
|
55
|
+
<key>AGENT_LOG_FILE</key>
|
|
56
|
+
<string>${M(q.logFile)}</string>
|
|
57
|
+
<key>HOME</key>
|
|
58
|
+
<string>${M(W())}</string>
|
|
59
|
+
<key>PATH</key>
|
|
60
|
+
<string>${M(process.env.PATH??"")}</string>
|
|
61
|
+
</dict>
|
|
62
|
+
<key>WorkingDirectory</key>
|
|
63
|
+
<string>${M(W())}</string>
|
|
64
|
+
<key>RunAtLoad</key>
|
|
65
|
+
<true/>
|
|
66
|
+
<key>KeepAlive</key>
|
|
67
|
+
<dict>
|
|
68
|
+
<key>SuccessfulExit</key>
|
|
69
|
+
<false/>
|
|
70
|
+
</dict>
|
|
71
|
+
<key>StandardOutPath</key>
|
|
72
|
+
<string>${M(q.logFile)}</string>
|
|
73
|
+
<key>StandardErrorPath</key>
|
|
74
|
+
<string>${M(q.logFile)}</string>
|
|
75
|
+
<key>ProcessType</key>
|
|
76
|
+
<string>Background</string>
|
|
77
|
+
</dict>
|
|
78
|
+
</plist>
|
|
79
|
+
`}async function Hq(q,z,G,H={}){L(q),E(G,"dbPath");let K=N(),Y=S(),$=J(A(),`${q}.log`),_=f(q);F(A(),{recursive:!0});let B=p({name:q,port:z,dbPath:G,bunPath:K,entryPoint:Y,logFile:$,profile:H.profile,profiles:H.profiles,home:H.home,isolatePlugins:H.isolatePlugins});if(y(_,B),V(`Wrote launchd plist: ${_}`),H.skipStart){O(`Autostart configured for agent '${q}' on port ${z}`),Z("Plist",_),Z("Log file",$);return}let R=Bun.spawnSync(["launchctl","load",_]);if(R.exitCode!==0){let I=R.stderr.toString().trim();j(`launchctl load failed: ${I}`),V("Trying bootstrap method...");let x=Bun.spawnSync(["id","-u"]).stdout.toString().trim();Bun.spawnSync(["launchctl","bootstrap",`gui/${x}`,_])}O(`Autostart installed for agent '${q}' on port ${z}`),Z("Plist",_),Z("Log file",$)}async function Kq(q){let z=f(q),G=`com.boff.vibecontrols.agent.${q}`;Bun.spawnSync(["launchctl","unload",z]);let H=Bun.spawnSync(["id","-u"]).stdout.toString().trim();if(Bun.spawnSync(["launchctl","bootout",`gui/${H}/${G}`]),Q(z))g(z),V(`Removed plist: ${z}`);O(`Autostart removed for agent '${q}'`)}async function Mq(q){let z=f(q),G=`com.boff.vibecontrols.agent.${q}`;if(!Q(z)){V(`Autostart is NOT configured for agent '${q}'`),Z("Expected plist",z);return}U(`Autostart Status \u2014 ${q}`),Z("Plist",z),Z("Label",G),T();let Y=Bun.spawnSync(["launchctl","list"]).stdout.toString().split(`
|
|
80
|
+
`).filter(($)=>$.includes("vibecontrols"));if(Y.length>0)console.log(Y.join(`
|
|
81
|
+
`));else V("Service not currently loaded")}function P(q){return`VibeControlsAgent_${q}`}function n(q){return J(v(),`autostart-${q}.xml`)}function Yq(q){let z=[`<Variable><Name>VIBECONTROLS_PROFILE</Name><Value>${M(q.name)}</Value></Variable>`,`<Variable><Name>PORT</Name><Value>${M(q.port)}</Value></Variable>`,`<Variable><Name>VIBECONTROLS_HOME</Name><Value>${M(q.configDir)}</Value></Variable>`];if(q.dbPath)z.push(`<Variable><Name>DB_PATH</Name><Value>${M(q.dbPath)}</Value></Variable>`);let G=process.env.USERNAME??process.env.USER??"User";return`<?xml version="1.0" encoding="UTF-16"?>
|
|
82
|
+
<Task version="1.4" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
|
|
83
|
+
<RegistrationInfo>
|
|
84
|
+
<Description>VibeControls Agent (${M(q.name)}) \u2014 auto-start on logon, restart on crash</Description>
|
|
85
|
+
</RegistrationInfo>
|
|
86
|
+
<Triggers>
|
|
87
|
+
<LogonTrigger>
|
|
88
|
+
<Enabled>true</Enabled>
|
|
89
|
+
<UserId>${M(G)}</UserId>
|
|
90
|
+
</LogonTrigger>
|
|
91
|
+
</Triggers>
|
|
92
|
+
<Principals>
|
|
93
|
+
<Principal id="Author">
|
|
94
|
+
<UserId>${M(G)}</UserId>
|
|
95
|
+
<LogonType>InteractiveToken</LogonType>
|
|
96
|
+
<RunLevel>LeastPrivilege</RunLevel>
|
|
97
|
+
</Principal>
|
|
98
|
+
</Principals>
|
|
99
|
+
<Settings>
|
|
100
|
+
<MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
|
|
101
|
+
<DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
|
|
102
|
+
<StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
|
|
103
|
+
<AllowHardTerminate>true</AllowHardTerminate>
|
|
104
|
+
<StartWhenAvailable>true</StartWhenAvailable>
|
|
105
|
+
<RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
|
|
106
|
+
<IdleSettings>
|
|
107
|
+
<StopOnIdleEnd>false</StopOnIdleEnd>
|
|
108
|
+
<RestartOnIdle>false</RestartOnIdle>
|
|
109
|
+
</IdleSettings>
|
|
110
|
+
<AllowStartOnDemand>true</AllowStartOnDemand>
|
|
111
|
+
<Enabled>true</Enabled>
|
|
112
|
+
<Hidden>true</Hidden>
|
|
113
|
+
<RunOnlyIfIdle>false</RunOnlyIfIdle>
|
|
114
|
+
<WakeToRun>false</WakeToRun>
|
|
115
|
+
<ExecutionTimeLimit>PT0S</ExecutionTimeLimit>
|
|
116
|
+
<Priority>7</Priority>
|
|
117
|
+
<RestartOnFailure>
|
|
118
|
+
<Interval>PT1M</Interval>
|
|
119
|
+
<Count>3</Count>
|
|
120
|
+
</RestartOnFailure>
|
|
121
|
+
</Settings>
|
|
122
|
+
<Actions Context="Author">
|
|
123
|
+
<Exec>
|
|
124
|
+
<Command>${M(q.bunPath)}</Command>
|
|
125
|
+
<Arguments>${M(q.entryPoint)} start --foreground --port ${M(q.port)} --name ${M(q.name)}</Arguments>
|
|
126
|
+
<WorkingDirectory>${M(q.configDir)}</WorkingDirectory>
|
|
127
|
+
</Exec>
|
|
128
|
+
</Actions>
|
|
129
|
+
</Task>`}async function Zq(q,z,G){let H=P(q),K=n(q),Y=v(),$=A();F(Y,{recursive:!0}),F($,{recursive:!0});let _=N(),B=S(),R=Yq({name:q,port:z,dbPath:G,bunPath:_,entryPoint:B,configDir:Y,logsDir:$}),I=Buffer.concat([Buffer.from([255,254]),Buffer.from(R,"utf16le")]);if(y(K,I),Z("Task XML",K),Bun.spawnSync(["schtasks","/Create","/TN",H,"/XML",K,"/F"],{stdout:"inherit",stderr:"inherit"}).exitCode!==0)throw Error("schtasks /Create failed. Run from an elevated shell if your user lacks scheduler permission.");T(),O(`Autostart installed for agent '${q}' (Task: ${H})`),V("To start now without rebooting:"),V(` schtasks /Run /TN ${H}`)}async function _q(q){let z=P(q),G=n(q),H=Bun.spawnSync(["schtasks","/Delete","/TN",z,"/F"],{stdout:"pipe",stderr:"pipe"});if(H.exitCode!==0)j(`schtasks /Delete returned non-zero (${H.exitCode}). Task may not have existed.`);else O(`Removed scheduled task ${z}`);if(Q(G))try{g(G)}catch{}}async function $q(q){let z=P(q),G=Bun.spawnSync(["schtasks","/Query","/TN",z,"/V","/FO","LIST"],{stdout:"pipe",stderr:"pipe"});if(G.exitCode!==0){V(`Autostart is NOT configured for agent '${q}'`),Z("Expected task",z);return}U(`Autostart Status \u2014 ${q}`),Z("Task",z),T(),console.log(G.stdout.toString())}function d(q,z,G){if(!Q(z))return!1;try{let H=G({bunPath:N(),entryPoint:S(),logFile:J(A(),`${q.name}.log`)});return a(z,"utf8")===H}catch{return!0}}function Vq(q){try{let z=Bun.spawnSync(["systemctl","--user","is-enabled",`vibecontrols-agent-${q}.service`]);if(z.exitCode===0)return!0;let G=z.stdout.toString().trim();return!["disabled","masked","linked",""].includes(G)}catch{return!0}}var o={linux:{label:"systemd",install:(q,z,G,H)=>qq(q,z,G??"./agent-db",H),uninstall:zq,status:Gq,isCurrent:(q)=>d(q,b(q.name),(z)=>r({...q,...z}))&&Vq(q.name),autoConfigurable:!0},darwin:{label:"launchd",install:(q,z,G,H)=>Hq(q,z,G??"./agent-db",H),uninstall:Kq,status:Mq,isCurrent:(q)=>d(q,f(q.name),(z)=>p({...q,...z})),autoConfigurable:!0},win32:{label:"Task Scheduler",install:Zq,uninstall:_q,status:$q,isCurrent:()=>!0,autoConfigurable:!1}};function k(){let q=o[w()];if(!q)throw Error(`Autostart is not supported on ${w()}. Supported: linux (systemd), darwin (launchd), win32 (Task Scheduler).`);return q}async function Uq(q){let z=process.env.VIBECONTROLS_PROFILES||void 0,G=process.env.VIBECONTROLS_HOME||void 0,H=process.env.VIBE_ISOLATE_PLUGINS||void 0;if(process.env.VIBE_NO_AUTOSTART==="1"||process.env.VIBE_AUTOSTART==="0")return{installed:!1,reason:"opted out via env"};let K=o[w()];if(!K)return{installed:!1,reason:`unsupported platform ${w()}`};if(!K.autoConfigurable)return{installed:!1,reason:`${K.label} must be configured manually \u2014 run \`vibe autostart install\``};try{let Y={name:q.name,port:q.port,dbPath:q.dbPath??"./agent-db",profile:q.profile,profiles:z,home:G,isolatePlugins:H};if(K.isCurrent(Y))return{installed:!1,reason:"already configured"};return await K.install(q.name,q.port,q.dbPath,{skipStart:!0,profile:q.profile,profiles:z,home:G,isolatePlugins:H}),{installed:!0,serviceLabel:K.label}}catch(Y){return{installed:!1,reason:Y instanceof Error?Y.message:String(Y)}}}function Fq(q){let z=q.command("autostart").description("Configure agent to auto-start on system boot");z.command("install").description("Generate and enable system service for auto-start on reboot").option("-n, --name <name>","Agent instance name","default").option("-p, --port <port>","Port to listen on","3005").option("--db-path <path>","Agent storage directory (absolute path; default: ~/.boff/vibecontrols/agents/<profile>/agent-db)").option("--json","Emit JSON").action(async function(G){let H={...q.opts(),...G};try{let K=k(),Y=L(G.name),$=t(G.port),_=G.dbPath??null,B=m(),R=(()=>{if(!_)return B;if(s(_))return _;let I=e(B,"..",_);return j(`--db-path is relative; resolved to ${I}. Pass an absolute path to silence this warning.`),I})();if(!H.json)U("Installing Autostart"),Z("Platform",`${w()} (${K.label})`),Z("Agent",Y),Z("Port",String($)),Z("Database",R),T();await K.install(Y,$,R),C(H,{ok:!0,enabled:!0,name:Y,port:$})}catch(K){if(H.json)C(H,{ok:!1,error:String(K)}),process.exit(1);D(`Failed to install autostart: ${K}`),process.exit(1)}}),z.command("uninstall").description("Stop and remove the system service").option("-n, --name <name>","Agent instance name","default").option("--json","Emit JSON").action(async function(G){let H={...q.opts(),...G};try{let K=k(),Y=L(G.name);if(!H.json)U("Removing Autostart");await K.uninstall(Y),C(H,{ok:!0,enabled:!1,name:Y})}catch(K){if(H.json)C(H,{ok:!1,error:String(K)}),process.exit(1);D(`Failed to uninstall autostart: ${K}`),process.exit(1)}}),z.command("status").description("Check if autostart is configured and running").option("-n, --name <name>","Agent instance name","default").action(async(G)=>{try{let H=k(),K=L(G.name);await H.status(K)}catch(H){D(`Failed to check autostart status: ${H}`),process.exit(1)}})}
|
|
130
|
+
export{r as K,p as L,Uq as M,Fq as N};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
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);
|
|
@@ -80,4 +80,4 @@ window.__VIBE_AUTH__={apiKey:null};
|
|
|
80
80
|
${z.length>0?`<ul>${J}</ul>`:'<p class="empty">No plugins with UIs installed.</p>'}
|
|
81
81
|
</body>
|
|
82
82
|
</html>`}function Zz(z){return new P({prefix:"/ui"}).onAfterHandle(({set:J})=>{J.headers["Content-Security-Policy"]=w()}).get("/",()=>{let J=z.getAllPlugins().filter((Q)=>Q.ui).map((Q)=>({name:Q.name,title:Q.ui?.title??Q.name,tags:Q.tags}));return j(new Response(a(J),{headers:{"Content-Type":"text/html; charset=utf-8"}}))}).get("/*",async({params:J,request:Q,set:W})=>{let X=(J["*"]||"").split("/").filter(Boolean);if(X.length===0)return W.status=404,{error:"Plugin not specified"};let $=X[0];if(!F($))return W.status=404,{error:`Invalid plugin name '${$}'`};let x=X.length===1||X.length===2&&!X[1],A=Q.headers.get("sec-fetch-mode"),d=x&&(A==="navigate"||A===null),C=q(Q,$);if(!(!!C&&S(C,$))){if(d)return W.status=200,W.headers["content-type"]="text/html; charset=utf-8",W.headers["Content-Security-Policy"]=w(),i($);return W.status=401,{error:"Unauthorized: UI plugin cookie required"}}let L=z.getPluginByKey($),I=X.slice(1).join("/");if(L&&X.length>=2){let G=z.getPluginByKey(X[1]);if(G?.ui)L=G,I=X.slice(2).join("/")}if(!L?.ui)return W.status=404,{error:`No UI available for plugin '${$}'`};if(L.ui.devUrl){if(!r(L.ui.devUrl))return W.status=403,{error:"Plugin UI dev proxy is disabled for this URL"};try{let G=new URL(L.ui.devUrl);G.pathname=`/${I}`.replace(/\/+/g,"/");let B=await fetch(G,{redirect:"manual"}),O=await B.arrayBuffer(),Y=new Headers;return B.headers.forEach((K,H)=>Y.set(H,K)),j(new Response(O,{status:B.status,headers:Y}))}catch{return W.status=502,{error:`Failed to proxy to dev server at ${L.ui.devUrl}`}}}if(L.ui.staticDir){let G=L.ui.staticDir,O=await v(L,G,I||"index.html");if(!O)return W.status=403,{error:"Access denied"};let Y=Bun.file(O);if(await Y.exists()){let _=s(O);if(_==="text/html"){let y=await Y.text();return j(new Response(R(y),{headers:{"Content-Type":"text/html; charset=utf-8"}}))}return j(new Response(Y,{headers:{"Content-Type":_}}))}let K=await v(L,G,"index.html"),H=K?Bun.file(K):null;if(H&&await H.exists()){let _=await H.text();return j(new Response(R(_),{headers:{"Content-Type":"text/html; charset=utf-8"}}))}return W.status=404,{error:"File not found"}}return W.status=404,{error:"No UI configuration (neither staticDir nor devUrl)"}})}function Vz(){return{getAgentApiKey:()=>N(),verifyIframeToken:(z,J)=>f(z,J),verifyUiCookieToken:(z,J)=>S(z,J),issueUiCookieToken:(z,J)=>{let Q=h(z,J);return{token:Q.token,expiresAt:Date.parse(Q.expiresAt)}},getIframeTokenFromRequest:(z,J)=>c(z,J),getUiCookieFromRequest:(z,J)=>q(z,J),isValidUiPluginName:(z)=>F(z),frameAncestorsCsp:()=>w()}}
|
|
83
|
-
export{m as
|
|
83
|
+
export{m as Aa,i as Ba,Zz as Ca,Vz as Da};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
2
|
function O(){return!!process.stdout.isTTY&&!!process.stdin.isTTY}async function E(x,A=!1){if(!O())return A;let D=A?"[Y/n]":"[y/N]";return process.stdout.write(` ${x} ${D} `),new Promise((B)=>{let b=process.stdin;b.setRawMode?.(!0),b.resume(),b.setEncoding("utf8");let K=(N)=>{b.removeListener("data",K),b.setRawMode?.(!1),b.pause();let U=N.trim().toLowerCase();if(console.log(U||(A?"y":"n")),U==="")B(A);else B(U==="y")};b.on("data",K)})}function L(x){if(x.json)return"json";if(x.plain)return"plain";if(x.interactive)return"interactive";return"auto"}function P(){return!!process.env.CI||!!process.env.NO_COLOR||process.env.TERM==="dumb"}async function M(x){let A=await x.fetchData(),D=x.mode??"auto";if(D==="json"){let b=x.json?x.json(A):A;process.stdout.write(`${JSON.stringify(b,null,2)}
|
|
3
3
|
`);return}if(D==="plain"){await x.plain(A);return}if((D==="interactive"||O()&&!P())&&!!x.interactive&&x.interactive)try{await x.interactive(A);return}catch{}await x.plain(A)}function S(x,A){if(!x.json)return!1;return process.stdout.write(`${JSON.stringify(A,null,2)}
|
|
4
|
-
`),!0}async function y(x,A,D=!1){if(x.yes===!0||x.json===!0||!O())return!0;return E(A,D)}export{O as
|
|
4
|
+
`),!0}async function y(x,A,D=!1){if(x.yes===!0||x.json===!0||!O())return!0;return E(A,D)}export{O as lc,E as mc,L as nc,M as oc,S as pc,y as qc};
|