@vibecontrols/agent 2026.1125.2 → 2026.1127.2
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-xwvsmn6b.js +2 -0
- package/dist/{agent-ready-tracker-mewxehg9.js → agent-ready-tracker-7ebr09d9.js} +1 -1
- package/dist/app-4t875vbv.js +2 -0
- package/dist/autostart.cmd-mdyv35dn.js +2 -0
- package/dist/bootstrap-workspace-1pt0bwy6.js +2 -0
- package/dist/bootstrap.service-gehm65tt.js +2 -0
- package/dist/bridge-client-9ax1cvj6.js +2 -0
- package/dist/bridge-commands-xhzhghxt.js +2 -0
- package/dist/cli.js +2 -2
- package/dist/daemon-profile-fnhc7pcf.js +2 -0
- package/dist/{finalize-retry-worker-az74f2qv.js → finalize-retry-worker-c38km3mt.js} +1 -1
- package/dist/gateway-client-3zp6kkav.js +2 -0
- package/dist/{getMachineId-bsd-4w1wmcjv.js → getMachineId-bsd-qjqk66se.js} +1 -1
- package/dist/{getMachineId-darwin-kejwz8w5.js → getMachineId-darwin-tqhg8pqb.js} +1 -1
- package/dist/{getMachineId-linux-mpm53wat.js → getMachineId-linux-ygfapc26.js} +1 -1
- package/dist/{getMachineId-unsupported-54seyw5v.js → getMachineId-unsupported-87w3cred.js} +1 -1
- package/dist/{getMachineId-win-cva7ghz9.js → getMachineId-win-jrtkq63e.js} +1 -1
- package/dist/{index-0gmhd3hs.js → index-0rmmrrfh.js} +3 -3
- package/dist/{index-7s7ee1y9.js → index-0vbsve3v.js} +4 -4
- package/dist/{index-7f2k4g6q.js → index-12gb48hg.js} +4 -4
- package/dist/{index-4rasb3ph.js → index-12rehjp4.js} +9 -9
- package/dist/{index-7wben1jx.js → index-164mtd7z.js} +2 -2
- package/dist/index-1smr1csg.js +116 -0
- package/dist/{index-w0m3jm0s.js → index-1t74r13z.js} +2 -2
- package/dist/{index-9xrhb68w.js → index-31ssvzw8.js} +2 -2
- package/dist/{index-652f9scs.js → index-4kf3nr14.js} +2 -2
- package/dist/{index-qe3xpt41.js → index-5s4mtrqb.js} +2 -2
- package/dist/{index-jmx5awkj.js → index-62vfxd90.js} +2 -2
- package/dist/{index-5ccmrpb5.js → index-6b9vh0gq.js} +48 -48
- package/dist/{index-7gk1x74m.js → index-6nv5rdqh.js} +2 -2
- package/dist/{index-er5k6qtr.js → index-6wfd7cv3.js} +4 -4
- package/dist/{index-t6p4szqx.js → index-76vza24h.js} +3 -3
- package/dist/{index-76m37yd8.js → index-7bm1kptr.js} +3 -3
- package/dist/{index-0qjbnyg4.js → index-7wm4bqx5.js} +5 -5
- package/dist/{index-akk3rxnn.js → index-90gn0b6x.js} +3 -3
- package/dist/{index-2r6cmxxz.js → index-axkwyajz.js} +1 -1
- package/dist/index-bk17490n.js +3 -0
- package/dist/{index-2vcxt38h.js → index-bpzk441p.js} +2 -2
- package/dist/{index-4z1y39jt.js → index-cn4p1ks0.js} +2 -2
- package/dist/{index-byerrz46.js → index-damc6cvc.js} +2 -2
- package/dist/{index-xtd0j8ve.js → index-dgbe8jm8.js} +2 -2
- package/dist/index-dtxd2xmg.js +158 -0
- package/dist/index-e5jdx9c1.js +3 -0
- package/dist/{index-tahaxp6n.js → index-ednz6yz2.js} +2 -2
- package/dist/{index-hsrt2v87.js → index-f5nmxa9e.js} +1 -1
- package/dist/{index-thm1bzpj.js → index-j8j1h00a.js} +9 -9
- package/dist/{index-kwhx023z.js → index-j99tkngg.js} +10 -10
- package/dist/{index-fqz9n560.js → index-nz7mhjjn.js} +3 -3
- package/dist/index-p1b10hs1.js +11 -0
- package/dist/{index-qfxwk38p.js → index-p7fbnfwd.js} +2 -2
- package/dist/{index-jnxjjx2y.js → index-ppxayc0x.js} +2 -2
- package/dist/index-qzwbctkv.js +16 -0
- package/dist/{index-a0vx2zyx.js → index-rae5bn1c.js} +2 -2
- package/dist/{index-8rbhm4g8.js → index-rhn7wy1p.js} +2 -2
- package/dist/index-sd5bt3g5.js +2 -0
- package/dist/{index-vtsd74g0.js → index-sq5j8bjn.js} +6 -6
- package/dist/{index-t5cfkz1e.js → index-v77bb0rm.js} +3 -3
- package/dist/{index-v16qz1fa.js → index-vhz1c474.js} +2 -2
- package/dist/{index-ywnfz6nm.js → index-wxb9dgwq.js} +1 -1
- package/dist/index-x4z055t8.js +3 -0
- package/dist/{index-haww9jpq.js → index-xetd52ad.js} +2 -2
- package/dist/{index-d59kp6zr.js → index-yfk0pb00.js} +2 -2
- package/dist/{index-cy97asyh.js → index-zcnfj1q4.js} +3 -3
- package/dist/{index-c4whjk5r.js → index-zn9snqbg.js} +2 -2
- package/dist/index.js +3 -3
- package/dist/interactive-52x9hv6c.js +2 -0
- package/dist/key.cmd-y415ngam.js +2 -0
- package/dist/log-shipper-02rqvtq8.js +2 -0
- package/dist/{path-utils-r4df8d3w.js → path-utils-qgkdkp5j.js} +1 -1
- package/dist/plugin-system-7qjqrq7s.js +2 -0
- package/dist/prereqs-runner-w7z2dwa6.js +2 -0
- package/dist/profile-mount-ga5z1vx9.js +2 -0
- package/dist/prune-stale-shims-vejvb1rj.js +2 -0
- package/dist/register-core-vv5pddxj.js +2 -0
- package/dist/secondary-profile-attach-222s85md.js +2 -0
- package/dist/subprocess-p9bv9nqz.js +2 -0
- package/dist/telemetry-1d3t1mbf.js +2 -0
- package/dist/tunnel-bootstrap-20vwak7q.js +2 -0
- package/package.json +1 -1
- package/dist/agent-config-v9d7gcz0.js +0 -2
- package/dist/app-xc9c1d71.js +0 -2
- package/dist/autostart.cmd-ahet7b1t.js +0 -2
- package/dist/bootstrap-workspace-3pb8qjsh.js +0 -2
- package/dist/bootstrap.service-9m7m1ksa.js +0 -2
- package/dist/bridge-client-xvqy3n15.js +0 -2
- package/dist/daemon-profile-sg8fp50z.js +0 -2
- package/dist/gateway-client-ermpz52n.js +0 -2
- package/dist/index-5021rk8n.js +0 -3
- package/dist/index-b3v08awy.js +0 -3
- package/dist/index-mmx2kp76.js +0 -16
- package/dist/index-ss5gez2p.js +0 -2
- package/dist/index-tts92sdm.js +0 -5
- package/dist/index-x83tcr8f.js +0 -158
- package/dist/index-zcmhy3jv.js +0 -116
- package/dist/interactive-vbz68zh5.js +0 -2
- package/dist/key.cmd-f6rjvjy8.js +0 -2
- package/dist/log-shipper-0erbwn0q.js +0 -2
- package/dist/plugin-system-byzwda4c.js +0 -2
- package/dist/prereqs-runner-gca0bytz.js +0 -2
- package/dist/profile-mount-s4mc1x18.js +0 -2
- package/dist/prune-stale-shims-4nqtv0xt.js +0 -2
- package/dist/register-core-ws2axmcf.js +0 -2
- package/dist/secondary-profile-attach-em1tq7vq.js +0 -2
- package/dist/subprocess-4gg77skg.js +0 -2
- package/dist/telemetry-nmtywcba.js +0 -2
- package/dist/tunnel-bootstrap-tjwz90pb.js +0 -2
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
// @bun
|
|
2
2
|
import{join as Ae}from"path";import{AsyncLocalStorage as Zt}from"async_hooks";import{mkdirSync as te}from"fs";import{join as et}from"path";import{appendFileSync as ct,existsSync as E,mkdirSync as ut,readFileSync as gt,readdirSync as ft,statSync as pt,unlinkSync as V}from"fs";import{join as y}from"path";var dt=30,ht=104857600,mt=/secret|password|token|key|email/i,K=/^audit-(\d{4}-\d{2}-\d{2})\.log$/;function H(t=new Date){let r=t.getUTCFullYear(),n=String(t.getUTCMonth()+1).padStart(2,"0"),i=String(t.getUTCDate()).padStart(2,"0");return`${r}-${n}-${i}`}function L(t){if(Array.isArray(t))return t.map(L);if(t&&typeof t==="object"){let r={};for(let[n,i]of Object.entries(t)){if(mt.test(n)){r[n]="[redacted]";continue}r[n]=L(i)}return r}return t}function yt(t,r){if(!r)return!0;if(r.includes("*"))return new RegExp(`^${r.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*")}$`).test(t);return t.includes(r)}class A{profile;auditDir;constructor(t,r){this.profile=t,this.auditDir=y(r,"audit")}ensureDir(){if(!E(this.auditDir))ut(this.auditDir,{recursive:!0});return this.auditDir}activeFilePath(){return y(this.ensureDir(),`audit-${H()}.log`)}emit(t,r,n={}){let i=L(n),o={timestamp:new Date().toISOString(),source:t,event:r,payload:{...i,profile:this.profile}};try{ct(this.activeFilePath(),`${JSON.stringify(o)}
|
|
3
3
|
`,{mode:384})}catch{}}listLogFiles(){if(!E(this.auditDir))return[];return ft(this.auditDir).filter((t)=>K.test(t)).sort()}listEvents(t={}){let r=Math.max(1,Math.min(t.limit??200,5000)),n=t.since?Date.parse(t.since):null,i=t.event??"",o=this.listLogFiles(),s=[];for(let a=o.length-1;a>=0&&s.length<r;a--){let l=o[a],c;try{c=gt(y(this.auditDir,l),"utf8")}catch{continue}let u=c.split(`
|
|
4
|
-
`);for(let g=u.length-1;g>=0&&s.length<r;g--){let d=u[g];if(!d)continue;let f;try{f=JSON.parse(d)}catch{continue}if(n!==null&&Number.isFinite(n)&&Date.parse(f.timestamp)<n)continue;if(!yt(f.event,i))continue;s.push(f)}}return s}runRetention(t=new Date){if(!E(this.auditDir))return;let r=t.getTime()-dt*24*60*60*1000,n=this.listLogFiles(),i=[];for(let a of n){let l=K.exec(a);if(!l)continue;let c=Date.parse(`${l[1]}T00:00:00Z`),u=y(this.auditDir,a);try{let g=pt(u);if(Number.isFinite(c)&&c<r){V(u);continue}i.push({name:a,size:g.size,mtime:g.mtimeMs})}catch{}}let o=i.reduce((a,l)=>a+l.size,0),s=`audit-${H(t)}.log`;i.sort((a,l)=>a.name.localeCompare(l.name));for(let a of i){if(o<=ht)break;if(a.name===s)continue;try{V(y(this.auditDir,a.name)),o-=a.size}catch{}}}__getAuditDirForTests(){return this.auditDir}}class P{profile;cryptoKey=null;apiKeyHash=null;constructor(t){this.profile=t}async load(t){if(t.byteLength!==32)throw Error(`KeyVault expects 32-byte key, got ${t.byteLength}`);let r=new Uint8Array(t);try{this.cryptoKey=await crypto.subtle.importKey("raw",r,{name:"AES-GCM"},!1,["encrypt","decrypt"])}finally{t.fill(0),r.fill(0)}}async bindApiKey(t){let r=new TextEncoder().encode(t);this.apiKeyHash=await crypto.subtle.digest("SHA-256",r),r.fill(0)}async match(t){if(!this.apiKeyHash)return!1;let r=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",r);return r.fill(0),
|
|
4
|
+
`);for(let g=u.length-1;g>=0&&s.length<r;g--){let d=u[g];if(!d)continue;let f;try{f=JSON.parse(d)}catch{continue}if(n!==null&&Number.isFinite(n)&&Date.parse(f.timestamp)<n)continue;if(!yt(f.event,i))continue;s.push(f)}}return s}runRetention(t=new Date){if(!E(this.auditDir))return;let r=t.getTime()-dt*24*60*60*1000,n=this.listLogFiles(),i=[];for(let a of n){let l=K.exec(a);if(!l)continue;let c=Date.parse(`${l[1]}T00:00:00Z`),u=y(this.auditDir,a);try{let g=pt(u);if(Number.isFinite(c)&&c<r){V(u);continue}i.push({name:a,size:g.size,mtime:g.mtimeMs})}catch{}}let o=i.reduce((a,l)=>a+l.size,0),s=`audit-${H(t)}.log`;i.sort((a,l)=>a.name.localeCompare(l.name));for(let a of i){if(o<=ht)break;if(a.name===s)continue;try{V(y(this.auditDir,a.name)),o-=a.size}catch{}}}__getAuditDirForTests(){return this.auditDir}}class P{profile;cryptoKey=null;apiKeyHash=null;constructor(t){this.profile=t}async load(t){if(t.byteLength!==32)throw Error(`KeyVault expects 32-byte key, got ${t.byteLength}`);let r=new Uint8Array(t);try{this.cryptoKey=await crypto.subtle.importKey("raw",r,{name:"AES-GCM"},!1,["encrypt","decrypt"])}finally{t.fill(0),r.fill(0)}}async bindApiKey(t){let r=new TextEncoder().encode(t);this.apiKeyHash=await crypto.subtle.digest("SHA-256",r),r.fill(0)}async match(t){if(!this.apiKeyHash)return!1;let r=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",r);return r.fill(0),vt(this.apiKeyHash,n)}hasKey(){return this.cryptoKey!==null}getCryptoKey(){return this.cryptoKey}shutdown(){this.cryptoKey=null,this.apiKeyHash=null}}function vt(t,r){if(t.byteLength!==r.byteLength)return!1;let n=new Uint8Array(t),i=new Uint8Array(r),o=0;for(let s=0;s<n.length;s++)o|=(n[s]??0)^(i[s]??0);return o===0}import{existsSync as h,mkdirSync as Lt,statSync as At,copyFileSync as Pt,truncateSync as kt,renameSync as It,unlinkSync as Ct,createReadStream as _t}from"fs";import{join as Dt}from"path";import{EventEmitter as Ot}from"events";import{createInterface as Gt}from"readline";import{AsyncLocalStorage as St}from"async_hooks";var j=new St,Rt=/^[A-Za-z0-9._:-]{8,128}$/;function Ai(){let t=globalThis.crypto;if(t?.randomUUID)return t.randomUUID();let r=new Uint8Array(16);return t?.getRandomValues?.(r),[...r].map((n)=>n.toString(16).padStart(2,"0")).join("")}function Hi(t){let r=(i)=>{if(t instanceof Headers)return t.get(i)??void 0;return t[i]??t[i.toLowerCase()]??t[i.toUpperCase()]},n=r("x-request-id")??r("X-Request-Id");if(!n)return;return Rt.test(n)?n:void 0}function Vi(t){j.enterWith(t)}function Tt(){return j.getStore()?.requestId}function Et(){let t=process.env.VIBECONTROLS_LOG_SHIP_URL;if(!t)return null;return{url:t,apiKey:process.env.VIBECONTROLS_LOG_SHIP_API_KEY,batchSize:Number.parseInt(process.env.VIBECONTROLS_LOG_SHIP_BATCH??"",10)||100,intervalMs:Number.parseInt(process.env.VIBECONTROLS_LOG_SHIP_INTERVAL_MS??"",10)||1e4,sampleRate:Number.parseFloat(process.env.VIBECONTROLS_LOG_SHIP_SAMPLE??"1")}}var Y=1000;class Q{config=null;queue=[];timer=null;inFlight=!1;dropped=0;init(){if(this.config)return;if(this.config=Et(),!this.config)return;if(this.timer=setInterval(()=>{this.flush()},this.config.intervalMs),this.timer&&typeof this.timer.unref==="function")this.timer.unref()}enqueue(t){if(!this.config)return;if(t.level==="debug"&&this.config.sampleRate<1&&Math.random()>this.config.sampleRate)return;if(this.queue.length>=Y)this.dropped+=1,this.queue.shift();this.queue.push(t)}async flush(){if(!this.config||this.inFlight||this.queue.length===0)return;this.inFlight=!0;let t=this.queue.splice(0,this.config.batchSize);try{await fetch(this.config.url,{method:"POST",headers:{"Content-Type":"application/json",...this.config.apiKey?{Authorization:`Bearer ${this.config.apiKey}`}:{}},body:JSON.stringify({entries:t,dropped:this.dropped}),signal:AbortSignal.timeout(5000)}),this.dropped=0}catch{this.queue=[...t,...this.queue].slice(0,Y)}finally{this.inFlight=!1}}stop(){if(this.timer)clearInterval(this.timer),this.timer=null;this.flush()}}var Yi=new Q;var Ut=10485760,W=7,Ft=60000,S={debug:0,info:1,warn:2,error:3},$t={debug:"\x1B[90m",info:"\x1B[36m",warn:"\x1B[33m",error:"\x1B[31m"},Nt="\x1B[0m";class k extends Ot{logDir;logFile;currentDay="";minLevel;isDaemon;emitOutput;prettyOutput;rotationTimer=null;constructor(t){super();this.setMaxListeners(100),this.logDir=t.logDir;let r=process.env.AGENT_LOG_FILE;this.logFile=r&&r.length>0?r:t.logFile??Dt(this.logDir,"default.log"),this.minLevel=process.env.LOG_LEVEL??"info",this.isDaemon=Boolean(process.env.AGENT_LOG_FILE);let n=process.env.VIBE_FOREGROUND==="1"||process.argv.some((i)=>i==="-f"||i==="--foreground");if(this.emitOutput=this.isDaemon||n||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(),Ft),this.rotationTimer.unref?.()}debug(t,r,n){this.log("debug",t,r,n)}info(t,r,n){this.log("info",t,r,n)}warn(t,r,n){this.log("warn",t,r,n)}error(t,r,n){this.log("error",t,r,n)}setLevel(t){this.minLevel=t}async readHistory(t){let{level:r,source:n,from:i,to:o,limit:s=200,offset:a=0}=t??{},l=[];if(!h(this.logFile))return l;return new Promise((c)=>{let u=Gt({input:_t(this.logFile,"utf8")}),g=0;u.on("line",(d)=>{if(l.length>=s){u.close();return}try{let f=JSON.parse(d);if(r&&S[f.level]<S[r])return;if(n&&!f.source.includes(n))return;if(i&&f.timestamp<i)return;if(o&&f.timestamp>o)return;if(g<a){g++;return}l.push(f)}catch{}}),u.on("close",()=>c(l)),u.on("error",()=>c(l))})}close(){if(this.rotationTimer)clearInterval(this.rotationTimer),this.rotationTimer=null}log(t,r,n,i){if(S[t]<S[this.minLevel])return;let o=Tt(),s=o!==void 0?{requestId:o,...i??{}}:i,a={timestamp:new Date().toISOString(),level:t,source:r,message:n,...s&&Object.keys(s).length>0?{metadata:s}:{}};if(this.emitOutput)if(this.prettyOutput){let l=$t[t],c=t.toUpperCase().padEnd(5),u=r?` [${r}]`:"",g=s&&Object.keys(s).length>0?` ${JSON.stringify(s)}`:"",d=a.timestamp.split("T")[1]?.slice(0,12)??a.timestamp;process.stdout.write(`${l}${d} ${c}${Nt}${u} ${n}${g}
|
|
5
5
|
`)}else process.stdout.write(JSON.stringify(a)+`
|
|
6
|
-
`);this.emit("log",a),
|
|
6
|
+
`);this.emit("log",a),Yi.enqueue(a)}checkRotation(){let t=new Date().toISOString().split("T")[0];if(this.currentDay&&this.currentDay!==t){this.rotate(),this.currentDay=t;return}this.currentDay=t;try{if(h(this.logFile)){if(At(this.logFile).size>=Ut)this.rotate()}}catch{}}rotate(){try{for(let t=W-1;t>=1;t--){let r=`${this.logFile}.${t}`,n=`${this.logFile}.${t+1}`;if(h(r)){if(t+1>W&&h(n))Ct(n);It(r,n)}}if(h(this.logFile))Pt(this.logFile,`${this.logFile}.1`),kt(this.logFile,0)}catch{}}ensureLogDir(){if(!h(this.logDir))Lt(this.logDir,{recursive:!0})}}var b=new Set(["localhost","127.0.0.1","0.0.0.0","::1","[::1]","host.docker.internal"]),qt=new Set(["4000","4001","4002","4003"]),Bt=new Set(["gw-global.local.burdenoff.com","gw-global-int.local.burdenoff.com","gw-wspace.local.burdenoff.com","gw-wspace-int.local.burdenoff.com"]),Mt=new Set(["graphql.burdenoff.com","graphqlworkspaces.burdenoff.com","alphagraphql.burdenoff.com","alphagraphqlworkspaces.burdenoff.com"]);function p(t){return t.toLowerCase().replace(/^\[|\]$/g,"")}function J(t){let r=p(t.hostname);if(!b.has(r))return!1;if(process.env.VIBECONTROLS_ALLOW_UNTRUSTED_GATEWAYS==="1")return!0;return qt.has(t.port)}function X(t){try{let r=new URL(t.trim());if(r.protocol!=="https:"&&r.protocol!=="http:")return!1;if(J(r))return!0;let n=p(r.hostname);if(Bt.has(n))return r.protocol==="https:";if(r.protocol!=="https:")return!1;return Mt.has(n)}catch{return!1}}function z(t,r){let n=t.trim();if(!X(n))throw Error(`${r} is not an allowed gateway URL. Use a trusted Burdenoff gateway, approved gw-*.local.burdenoff.com host, or localhost gateway ports 4000-4003.`);return n.replace(/\/+$/,"")}var _=new Set([".vibecontrols.com"]);function Jt(t){let r=t.trim().toLowerCase();if(!r)return;_.add(r.startsWith(".")?r:`.${r}`)}function Vt(t){try{let r=new URL(t.trim()),n=p(r.hostname);if(b.has(n))return r.protocol==="http:"||r.protocol==="https:";if(r.protocol!=="https:")return!1;for(let i of _)if(n.endsWith(i))return!0;return!1}catch{return!1}}function ci(t){if(!t)return null;let r=t.trim().replace(/\/+$/,"");return Vt(r)?r:null}function Wt(t){if(!t)return null;let r=ci(t);if(r)return r;let n=process.env.AGENT_TUNNEL_URL;if(n&&t.trim().replace(/\/+$/,"")===n.trim().replace(/\/+$/,""))return xt(t);return null}var zt=new Set([".trycloudflare.com"]);function Kt(t){try{let r=new URL(t.trim()),n=p(r.hostname);if(b.has(n))return r.protocol==="http:"||r.protocol==="https:";if(r.protocol!=="https:")return!1;for(let i of _)if(n.endsWith(i))return!0;for(let i of zt)if(n.endsWith(i))return!0;return!1}catch{return!1}}function Ir(t){if(!t)return null;let r=t.trim().replace(/\/+$/,"");return Kt(r)?r:null}function Ht(t){try{let r=new URL(t.trim()),n=p(r.hostname);if(b.has(n))return r.protocol==="http:"||r.protocol==="https:";return r.protocol==="https:"}catch{return!1}}function xt(t){if(!t)return null;let r=t.trim().replace(/\/+$/,"");return Ht(r)?r:null}function Zi(t,r){try{let n=new URL(t.trim());if(n.protocol!=="https:"&&!J(n))return!1;let i=p(n.hostname);for(let o of r){if(!o)continue;let s=new URL(o);if(i===p(s.hostname))return!0}return X(t)}catch{return!1}}var jt=/(?:\/(?:global|workspaces))?\/graphql$/i,Yt=1048576;function G(t){return t.trim().replace(/\/+$/,"").replace(jt,"")}function Z(t,r){return`${G(t)}/${r}/graphql`}function tt(t){return t instanceof Error?t.message:String(t)}async function Qt(t,r){let n=t.headers.get("content-length");if(n){let c=Number.parseInt(n,10);if(Number.isInteger(c)&&c>r)throw Error(`Gateway response is too large (${c} bytes)`)}if(!t.body)return"";let i=t.body.getReader(),o=[],s=0;try{while(!0){let{done:c,value:u}=await i.read();if(c)break;if(!u)continue;if(s+=u.byteLength,s>r)throw await i.cancel().catch(()=>{return}),Error(`Gateway response exceeds ${r} bytes`);o.push(u)}}finally{i.releaseLock()}let a=new Uint8Array(s),l=0;for(let c of o)a.set(c,l),l+=c.byteLength;return new TextDecoder().decode(a)}class ui{config=null;token=null;authInFlight=null;configGeneration=0;configure(t){let r=G(z(t.globalGatewayUrl,"globalGatewayUrl")),n=t.workspaceGatewayUrl?G(z(t.workspaceGatewayUrl,"workspaceGatewayUrl")):void 0,i=t.clientId.trim(),o=t.clientSecret.trim();if(!r)throw Error("globalGatewayUrl is required");if(!i)throw Error("clientId is required");if(!o)throw Error("clientSecret is required");this.configGeneration+=1,this.config={...t,globalGatewayUrl:r,workspaceGatewayUrl:n,clientId:i,clientSecret:o,scopes:t.scopes?.map((s)=>s.trim()).filter(Boolean),workspaceId:t.workspaceId?.trim()||void 0,organizationId:t.organizationId?.trim()||void 0},this.token=null,this.authInFlight=null,e().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:t,...r}=this.config;return r}async getAccessToken(){let{token:t,config:r}=await this.ensureToken();return{token:t,workspaceGatewayUrl:r.workspaceGatewayUrl??"",globalGatewayUrl:r.globalGatewayUrl??"",workspaceId:r.workspaceId??""}}async globalQuery(t,r){return this.executeQuery("global",t,r)}async workspaceQuery(t,r){return this.executeQuery("workspaces",t,r)}async lookupPeerAgent(t,r){if(!this.isConfigured())return null;try{let i=(await this.workspaceQuery(`query AgentNetworkLookup($targetAgentRecordId: ID!, $operation: String!) {
|
|
7
7
|
vibecontrolsAgentNetworkLookup(targetAgentRecordId: $targetAgentRecordId, operation: $operation) {
|
|
8
8
|
tunnelUrl
|
|
9
9
|
peerApiKey
|
|
10
10
|
}
|
|
11
|
-
}`,{targetAgentRecordId:t,operation:r})).data?.vibecontrolsAgentNetworkLookup;if(!i)return null;return{tunnelUrl:i.tunnelUrl,apiKey:i.peerApiKey}}catch(n){return e().logger.warn("gateway-client","Peer agent lookup failed",{targetAgentRecordId:t,error:n instanceof Error?n.message:String(n)}),null}}async executeQuery(t,r,n){let{token:i,config:o}=await this.ensureToken(),s=t==="workspaces"?o.workspaceGatewayUrl??o.globalGatewayUrl:o.globalGatewayUrl,a=Z(s,t);e().logger.debug("gateway-client",`GraphQL ${t} request`,{url:a,queryLength:r.length});let l={"Content-Type":"application/json",Authorization:`Bearer ${i}`};if(o.workspaceId&&t==="workspaces")l["x-workspace-id"]=o.workspaceId;let c=
|
|
11
|
+
}`,{targetAgentRecordId:t,operation:r})).data?.vibecontrolsAgentNetworkLookup;if(!i)return null;return{tunnelUrl:i.tunnelUrl,apiKey:i.peerApiKey}}catch(n){return e().logger.warn("gateway-client","Peer agent lookup failed",{targetAgentRecordId:t,error:n instanceof Error?n.message:String(n)}),null}}async executeQuery(t,r,n){let{token:i,config:o}=await this.ensureToken(),s=t==="workspaces"?o.workspaceGatewayUrl??o.globalGatewayUrl:o.globalGatewayUrl,a=Z(s,t);e().logger.debug("gateway-client",`GraphQL ${t} request`,{url:a,queryLength:r.length});let l={"Content-Type":"application/json",Authorization:`Bearer ${i}`};if(o.workspaceId&&t==="workspaces")l["x-workspace-id"]=o.workspaceId;let c=Tt();if(c)l["X-Request-Id"]=c;let u=await this.postGraphQL(a,l,{query:r,variables:n});if(u.errors?.length)e().logger.warn("gateway-client","GraphQL errors",{supergraph:t,errors:u.errors.map((g)=>g.message)});return u}async ensureToken(){if(!this.config)throw Error("Gateway client not configured. Call configure() first.");let t=this.config,r=this.configGeneration;if(this.token&&this.token.expiresAt>Date.now()+60000)return{token:this.token.accessToken,config:t,generation:r};if(this.authInFlight?.generation===r){let i=await this.authInFlight.promise;if(r!==this.configGeneration||t!==this.config)return this.ensureToken();return{token:i,config:t,generation:r}}let n={generation:r,promise:this.authenticate(t,r)};this.authInFlight=n;try{let i=await n.promise;if(r!==this.configGeneration||t!==this.config)return this.ensureToken();return{token:i,config:t,generation:r}}finally{if(this.authInFlight===n)this.authInFlight=null}}async authenticate(t,r){e().logger.info("gateway-client","Authenticating with gateway",{clientId:t.clientId});let n=Z(t.globalGatewayUrl,"global"),i=await this.postGraphQL(n,{"Content-Type":"application/json"},{query:`
|
|
12
12
|
mutation AuthenticateApp($input: AuthenticateAppInput!) {
|
|
13
13
|
authenticateApp(input: $input) {
|
|
14
14
|
accessToken
|
|
@@ -17,5 +17,5 @@ import{join as Ae}from"path";import{AsyncLocalStorage as Zt}from"async_hooks";im
|
|
|
17
17
|
scopes
|
|
18
18
|
}
|
|
19
19
|
}
|
|
20
|
-
`,variables:{input:{clientId:t.clientId,clientSecret:t.clientSecret,scopes:t.scopes??[]}}});if(i.errors?.length||!i.data?.authenticateApp){let a=i.errors?.[0]?.message??"Authentication failed";throw e().logger.error("gateway-client",`Authentication failed: ${a}`),Error(`Gateway authentication failed: ${a}`)}let o=i.data.authenticateApp,s={accessToken:o.accessToken,expiresAt:Date.now()+o.expiresIn*1000,scopes:o.scopes};if(r!==this.configGeneration||t!==this.config)throw Error("Gateway configuration changed during authentication");return this.token=s,e().logger.info("gateway-client","Authenticated successfully",{expiresIn:o.expiresIn,scopes:o.scopes}),s.accessToken}async postGraphQL(t,r,n){let i;try{i=await fetch(t,{method:"POST",headers:r,body:JSON.stringify(n),signal:AbortSignal.timeout(15000)})}catch(o){throw Error(`Could not reach gateway at ${t}: ${tt(o)}`,{cause:o})}try{let o=await
|
|
21
|
-
`,{encoding:"utf8",mode:384}),ce(n,r)}function
|
|
20
|
+
`,variables:{input:{clientId:t.clientId,clientSecret:t.clientSecret,scopes:t.scopes??[]}}});if(i.errors?.length||!i.data?.authenticateApp){let a=i.errors?.[0]?.message??"Authentication failed";throw e().logger.error("gateway-client",`Authentication failed: ${a}`),Error(`Gateway authentication failed: ${a}`)}let o=i.data.authenticateApp,s={accessToken:o.accessToken,expiresAt:Date.now()+o.expiresIn*1000,scopes:o.scopes};if(r!==this.configGeneration||t!==this.config)throw Error("Gateway configuration changed during authentication");return this.token=s,e().logger.info("gateway-client","Authenticated successfully",{expiresIn:o.expiresIn,scopes:o.scopes}),s.accessToken}async postGraphQL(t,r,n){let i;try{i=await fetch(t,{method:"POST",headers:r,body:JSON.stringify(n),signal:AbortSignal.timeout(15000)})}catch(o){throw Error(`Could not reach gateway at ${t}: ${tt(o)}`,{cause:o})}try{let o=await Qt(i,Yt),s={};if(o)try{s=JSON.parse(o)}catch{let a=o.slice(0,240).replace(/\s+/g," ");throw Error(`Gateway returned a non-JSON response (${i.status} ${i.statusText}) from ${t}${a?`: ${a}`:""}`)}if(!i.ok){let a=s.errors?.[0]?.message??`${i.status} ${i.statusText}`;throw Error(`Gateway request failed at ${t}: ${a} (${i.status})`)}return s}catch(o){if(o instanceof Error)throw o;throw Error(`Failed to process gateway response from ${t}: ${tt(o)}`,{cause:o})}}}function D(){let t=B();if(t)return t.gatewayClient;return e().gatewayClient}var T=new Proxy({},{get(t,r,n){let i=D(),o=i[r];return typeof o==="function"?o.bind(i):o},set(t,r,n){let i=D();return i[r]=n,!0},has(t,r){return r in D()}});var re={maxFileDescriptors:4096,maxChildProcesses:256,maxMemoryMB:4096},U=new Zt;function wt(t){U.enterWith(t)}class F{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(t){this.name=t.name,this.dataDir=t.dataDir,this.spawnOwnerKey=`profile/${t.name}`,this.budget=t.budget??re,te(this.dataDir,{recursive:!0}),this.keyVault=new P(t.name),this.audit=new A(t.name,t.dataDir),this.logger=new k({logDir:et(t.dataDir,"logs")})}run(t){return U.run(this,t)}get gatewayClient(){if(!this._gatewayClient)this._gatewayClient=new ui;return this._gatewayClient}attachServices(t){this.db=t.db,this.serviceRegistry=t.serviceRegistry,this.pluginManager=t.pluginManager,this.lifecycle=t.lifecycle,this.hostServices=t.hostServices}getBootState(){return this.state}setBootState(t){if(this.state===t)return;if(this.state=t,t!=="degraded")this.degradedReasons.length=0;for(let r of this.listeners)try{r(t)}catch{}}recordDegradedReason(t,r){if(this.degradedReasons.push({plugin:t,message:r}),this.state==="ready")this.setBootState("degraded");(async()=>{try{let{telemetryService:n}=await import("./telemetry-1d3t1mbf.js");n.emit("health.degraded",{reason_class:ie(r)})}catch{}})()}getDegradedReasons(){return this.degradedReasons.slice()}recordFinalizeError(t,r){this.lastFinalizeError={message:t,at:new Date().toISOString(),attempt:r}}clearFinalizeError(){this.lastFinalizeError=null}getLastFinalizeError(){return this.lastFinalizeError}onBootStateChange(t){return this.listeners.add(t),()=>this.listeners.delete(t)}async shutdown(){this.setBootState("shutting-down");try{let{unmountProfileRoutes:t}=await import("./profile-mount-ga5z1vx9.js");t(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(t){return et(this.dataDir,t)}}function B(){return U.getStore()??null}function ie(t){let r=t.toLowerCase();if(r.includes("timeout"))return"timeout";if(r.includes("econn")||r.includes("network"))return"network";if(r.includes("permission")||r.includes("eacces"))return"permission";if(r.includes("not found")||r.includes("enoent"))return"not_found";if(r.includes("plugin"))return"plugin";return"other"}class q{profiles=new Map;create(t){if(this.profiles.has(t.name))throw Error(`profile already registered: ${t.name}`);let r=new F(t);return this.profiles.set(t.name,r),this.refreshProcessTitle(),r}refreshProcessTitle(){try{let r=[...this.profiles.keys()].sort().join(","),n=r.length>96?`${r.slice(0,93)}...`:r;process.title=`vibe-daemon[${n}]`}catch{}}get(t){return this.profiles.get(t)}list(){return[...this.profiles.values()]}names(){return[...this.profiles.keys()]}has(t){return this.profiles.has(t)}size(){return this.profiles.size}async destroy(t){let r=this.profiles.get(t);if(!r)return;await r.shutdown(),this.profiles.delete(t),this.refreshProcessTitle()}async destroyAll(){let t=[...this.profiles.keys()];for(let r of t)await this.destroy(r)}}import{isAbsolute as ve,join as w,relative as Se,resolve as M}from"path";import{existsSync as be,readFileSync as Te}from"fs";import{homedir as Re}from"os";import{existsSync as oe,mkdirSync as ae,readFileSync as le,renameSync as ce,writeFileSync as ue}from"fs";import{homedir as ge}from"os";import{dirname as fe,join as rt,resolve as pe}from"path";var m=new Map;async function he(t,r){let n=m.get(t)??Promise.resolve(),i,o=new Promise((s)=>{i=s});m.set(t,n.then(()=>o));try{return await n,await r()}finally{if(i(),m.get(t)===n.then(()=>o));queueMicrotask(()=>{let s=m.get(t);if(!s)return;Promise.race([s,new Promise((a)=>{a(void 0)})]).then(()=>{if(m.get(t)===s)m.delete(t)})})}}var de="agents-registry";async function ot(t){return he(de,t)}function me(){return pe(process.env.VIBECONTROLS_HOME??rt(ge(),".boff","vibecontrols"))}var nt=2,ye="default";function it(){return rt(me(),"agents.json")}function we(){let t=it();if(!oe(t))return null;try{let r=JSON.parse(le(t,"utf8"));if(r&&typeof r==="object"&&!Array.isArray(r)&&"instances"in r)return r;return null}catch{return null}}function x(){let t=we();if(!t)return{schemaVersion:nt,instances:[]};return t}function st(t){let r=it();ae(fe(r),{recursive:!0});let n=`${r}.${process.pid}.tmp`,i={...t,schemaVersion:nt};ue(n,`${JSON.stringify(i,null,2)}
|
|
21
|
+
`,{encoding:"utf8",mode:384}),ce(n,r)}function bt(){return x().instances}function Ji(t){let r=x();st({...r,instances:t})}function Oe(){try{let r=x().defaultProfile;if(r&&typeof r==="string"&&r.length>0)return r}catch{}return ye}function Xt(t){if(!t||typeof t!=="string")throw Error("setDefaultProfile: name is required");let r=x();st({...r,defaultProfile:t})}var xe=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/,Ee=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;function lt(t){if(!xe.test(t))throw Error("Invalid VIBECONTROLS_PROFILE. Use 1-128 characters: letters, numbers, dot, underscore, or dash.");return t}function R(){let t=process.env.VIBECONTROLS_PROFILE;if(t)return lt(t);let r=Oe();return lt(r)}function O(t){if(!Ee.test(t))throw Error("Agent name must use 1-64 characters: letters, numbers, dot, underscore, or dash.");return t}function li(t,r){let n=Se(M(t),M(r));return n===""||!!n&&!n.startsWith("..")&&!ve(n)}function I(){let t=C(),r=R();return w(t,"agents",r)}function ne(){return w(C(),"agents")}function ee(){return w(I(),"agent-db")}function C(){return M(process.env.VIBECONTROLS_HOME??w(Re(),".boff","vibecontrols"))}var Le="https://registry.npmjs.org/";function se(){if(process.env.VIBECONTROLS_REGISTRY)return process.env.VIBECONTROLS_REGISTRY;try{let t=w(I(),"config.json");if(be(t)){let r=JSON.parse(Te(t,"utf8"));if(r.registry)return r.registry}}catch{}return Le}var N=new q,v=null;function Pe(){if(v)return v;let t=R(),r=N.get(t);if(r)return v=r,r;return v=N.create({name:t,dataDir:I()}),v}function e(){return Pe()}function at(t){let r=O(t),n=N.get(r);if(n)return n;return N.create({name:r,dataDir:Ae(C(),"agents",r)})}export{Ai,Hi,Vi,Tt,Yi,z,Jt,ci,Wt,Ir,xt,Zi,ui,T,he,ot,bt,Ji,Oe,Xt,R,O,li,I,ne,ee,C,se,wt,B,N,e,at};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{homedir as y}from"os";import{isAbsolute as b,join as p}from"path";function g({command:t,args:s,platform:r=process.platform}){if(r==="win32")return["cmd","/c",t,...s];return["sh","-c",`${t} "$@"`,"--",...s]}function l(t,s){let r=y();if(t===void 0||t===null||t==="")return s??r;let e=t.trim();if(e==="")return s??r;if(e==="~")return r;if(e.startsWith("~/"))return p(r,e.slice(2));if(b(e))return e;return p(r,e)}function h(){try{return process.cwd()}catch{return}}async function
|
|
3
|
-
`),{exitCode:127}}let i=await d.exited;return{exitCode:typeof i==="number"?i:1}}var f=1048576,R=60000;async function w(t){if(!t)return{text:"",truncated:!1};let s=t.getReader(),r=new TextDecoder,e=0,a=!1,n="";try{while(!0){let{done:d,value:i}=await s.read();if(d)break;if(a)continue;let o=f-e;if(i.byteLength<=o)n+=r.decode(i,{stream:!0}),e+=i.byteLength;else n+=r.decode(i.subarray(0,o),{stream:!0}),e=f,a=!0}n+=r.decode()}finally{s.releaseLock()}if(a)n+="...[truncated]";return{text:n,truncated:a}}async function
|
|
4
|
-
export{
|
|
2
|
+
import{homedir as y}from"os";import{isAbsolute as b,join as p}from"path";function g({command:t,args:s,platform:r=process.platform}){if(r==="win32")return["cmd","/c",t,...s];return["sh","-c",`${t} "$@"`,"--",...s]}function l(t,s){let r=y();if(t===void 0||t===null||t==="")return s??r;let e=t.trim();if(e==="")return s??r;if(e==="~")return r;if(e.startsWith("~/"))return p(r,e.slice(2));if(b(e))return e;return p(r,e)}function h(){try{return process.cwd()}catch{return}}async function Ii(t,s,r=Bun.spawn){let e=g({command:t.command,args:s}),n=t.cwd&&t.cwd.trim()!==""?l(t.cwd):l(t.cwd,h()),d;try{d=r(e,{cwd:n,stdin:"inherit",stdout:"inherit",stderr:"inherit"})}catch(o){let u=o instanceof Error?o.message:String(o);return process.stderr.write(`vibe run: spawn failed in cwd=${n}: ${u}
|
|
3
|
+
`),{exitCode:127}}let i=await d.exited;return{exitCode:typeof i==="number"?i:1}}var f=1048576,R=60000;async function w(t){if(!t)return{text:"",truncated:!1};let s=t.getReader(),r=new TextDecoder,e=0,a=!1,n="";try{while(!0){let{done:d,value:i}=await s.read();if(d)break;if(a)continue;let o=f-e;if(i.byteLength<=o)n+=r.decode(i,{stream:!0}),e+=i.byteLength;else n+=r.decode(i.subarray(0,o),{stream:!0}),e=f,a=!0}n+=r.decode()}finally{s.releaseLock()}if(a)n+="...[truncated]";return{text:n,truncated:a}}async function Ci(t,s){let r=g({command:t.command,args:s}),e=l(t.cwd),a=Date.now(),n;try{n=Bun.spawn(r,{cwd:e,stdin:"ignore",stdout:"pipe",stderr:"pipe"})}catch(c){let x=c instanceof Error?c.message:String(c);return{exit_code:127,stdout:"",stderr:`vibe alias: spawn failed in cwd=${e}: ${x}`,duration_ms:Date.now()-a,truncated:{stdout:!1,stderr:!1},timed_out:!1,cwd:e}}let d=!1,i=setTimeout(()=>{d=!0;try{n.kill()}catch{}},R),[o,u,m]=await Promise.all([w(n.stdout),w(n.stderr),n.exited]);return clearTimeout(i),{exit_code:typeof m==="number"?m:1,stdout:o.text,stderr:u.text,duration_ms:Date.now()-a,truncated:{stdout:o.truncated,stderr:u.truncated},timed_out:d,cwd:e}}
|
|
4
|
+
export{Ii,Ci};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{P,a,j}from"./index-
|
|
2
|
+
import{P,a,j}from"./index-rae5bn1c.js";var Ve=a(function(ui,qe){var Q=1000,X=Q*60,J=X*60,_=J*24,Xt=_*7,Jt=_*365.25;qe.exports=function(e,t){t=t||{};var r=typeof e;if(r==="string"&&e.length>0)return Yt(e);else if(r==="number"&&isFinite(e))return t.long?tr(e):er(e);throw Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))};function Yt(e){if(e=String(e),e.length>100)return;var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(!t)return;var r=parseFloat(t[1]),n=(t[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return r*Jt;case"weeks":case"week":case"w":return r*Xt;case"days":case"day":case"d":return r*_;case"hours":case"hour":case"hrs":case"hr":case"h":return r*J;case"minutes":case"minute":case"mins":case"min":case"m":return r*X;case"seconds":case"second":case"secs":case"sec":case"s":return r*Q;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:return}}function er(e){var t=Math.abs(e);if(t>=_)return Math.round(e/_)+"d";if(t>=J)return Math.round(e/J)+"h";if(t>=X)return Math.round(e/X)+"m";if(t>=Q)return Math.round(e/Q)+"s";return e+"ms"}function tr(e){var t=Math.abs(e);if(t>=_)return fe(e,t,_,"day");if(t>=J)return fe(e,t,J,"hour");if(t>=X)return fe(e,t,X,"minute");if(t>=Q)return fe(e,t,Q,"second");return e+" ms"}function fe(e,t,r,n){var i=t>=r*1.5;return Math.round(e/r)+" "+n+(i?"s":"")}});var Fe=a(function(mi,Ge){function rr(e){r.debug=r,r.default=r,r.coerce=p,r.disable=c,r.enable=i,r.enabled=f,r.humanize=Ve(),r.destroy=u,Object.keys(e).forEach((s)=>{r[s]=e[s]}),r.names=[],r.skips=[],r.formatters={};function t(s){let m=0;for(let h=0;h<s.length;h++)m=(m<<5)-m+s.charCodeAt(h),m|=0;return r.colors[Math.abs(m)%r.colors.length]}r.selectColor=t;function r(s){let m,h=null,k,V;function S(...T){if(!S.enabled)return;let M=S,ie=Number(new Date),Mt=ie-(m||ie);if(M.diff=Mt,M.prev=m,M.curr=ie,m=ie,T[0]=r.coerce(T[0]),typeof T[0]!=="string")T.unshift("%O");let oe=0;T[0]=T[0].replace(/%([a-zA-Z%])/g,(ge,Nt)=>{if(ge==="%%")return"%";oe++;let Re=r.formatters[Nt];if(typeof Re==="function"){let _t=T[oe];ge=Re.call(M,_t),T.splice(oe,1),oe--}return ge}),r.formatArgs.call(M,T),(M.log||r.log).apply(M,T)}if(S.namespace=s,S.useColors=r.useColors(),S.color=r.selectColor(s),S.extend=n,S.destroy=r.destroy,Object.defineProperty(S,"enabled",{enumerable:!0,configurable:!1,get:()=>{if(h!==null)return h;if(k!==r.namespaces)k=r.namespaces,V=r.enabled(s);return V},set:(T)=>{h=T}}),typeof r.init==="function")r.init(S);return S}function n(s,m){let h=r(this.namespace+(typeof m>"u"?":":m)+s);return h.log=this.log,h}function i(s){r.save(s),r.namespaces=s,r.names=[],r.skips=[];let m=(typeof s==="string"?s:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let h of m)if(h[0]==="-")r.skips.push(h.slice(1));else r.names.push(h)}function o(s,m){let h=0,k=0,V=-1,S=0;while(h<s.length)if(k<m.length&&(m[k]===s[h]||m[k]==="*"))if(m[k]==="*")V=k,S=h,k++;else h++,k++;else if(V!==-1)k=V+1,S++,h=S;else return!1;while(k<m.length&&m[k]==="*")k++;return k===m.length}function c(){let s=[...r.names,...r.skips.map((m)=>"-"+m)].join(",");return r.enable(""),s}function f(s){for(let m of r.skips)if(o(s,m))return!1;for(let m of r.names)if(o(s,m))return!0;return!1}function p(s){if(s instanceof Error)return s.stack||s.message;return s}function u(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return r.enable(r.load()),r}Ge.exports=rr});var He=a(function(Te,pe){Te.formatArgs=ir;Te.save=or;Te.load=sr;Te.useColors=nr;Te.storage=ar();Te.destroy=(()=>{let e=!1;return()=>{if(!e)e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}})();Te.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function nr(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let e;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function ir(e){if(e[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+e[0]+(this.useColors?"%c ":" ")+"+"+pe.exports.humanize(this.diff),!this.useColors)return;let t="color: "+this.color;e.splice(1,0,t,"color: inherit");let r=0,n=0;e[0].replace(/%[a-zA-Z%]/g,(i)=>{if(i==="%%")return;if(r++,i==="%c")n=r}),e.splice(n,0,t)}Te.log=console.debug||console.log||(()=>{});function or(e){try{if(e)Te.storage.setItem("debug",e);else Te.storage.removeItem("debug")}catch(t){}}function sr(){let e;try{e=Te.storage.getItem("debug")||Te.storage.getItem("DEBUG")}catch(t){}if(!e&&typeof process<"u"&&"env"in process)e=process.env.DEBUG;return e}function ar(){try{return localStorage}catch(e){}}pe.exports=Fe()(Te);var{formatters:cr}=pe.exports;cr.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}});var Qe=a(function(li,Ke){Ke.exports=(e,t=process.argv)=>{let r=e.startsWith("-")?"":e.length===1?"-":"--",n=t.indexOf(r+e),i=t.indexOf("--");return n!==-1&&(i===-1||n<i)}});var Ye=a(function(di,Je){var Xe=j("os"),ue=j("tty"),v=Qe(),{env:y}=process,L;if(v("no-color")||v("no-colors")||v("color=false")||v("color=never"))L=0;else if(v("color")||v("colors")||v("color=true")||v("color=always"))L=1;if("FORCE_COLOR"in y)if(y.FORCE_COLOR==="true")L=1;else if(y.FORCE_COLOR==="false")L=0;else L=y.FORCE_COLOR.length===0?1:Math.min(parseInt(y.FORCE_COLOR,10),3);function ve(e){if(e===0)return!1;return{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function Be(e,t){if(L===0)return 0;if(v("color=16m")||v("color=full")||v("color=truecolor"))return 3;if(v("color=256"))return 2;if(e&&!t&&L===void 0)return 0;let r=L||0;if(y.TERM==="dumb")return r;if(process.platform==="win32"){let n=Xe.release().split(".");if(Number(n[0])>=10&&Number(n[2])>=10586)return Number(n[2])>=14931?3:2;return 1}if("CI"in y){if(["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some((n)=>(n in y))||y.CI_NAME==="codeship")return 1;return r}if("TEAMCITY_VERSION"in y)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(y.TEAMCITY_VERSION)?1:0;if(y.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in y){let n=parseInt((y.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(y.TERM_PROGRAM){case"iTerm.app":return n>=3?3:2;case"Apple_Terminal":return 2}}if(/-256(color)?$/i.test(y.TERM))return 2;if(/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(y.TERM))return 1;if("COLORTERM"in y)return 1;return r}function hr(e){let t=Be(e,e&&e.isTTY);return ve(t)}Je.exports={supportsColor:hr,stdout:ve(Be(!0,ue.isatty(1))),stderr:ve(Be(!0,ue.isatty(2)))}});var nt=a(function(Ae,me){var et=j("tty"),R=j("util");Ae.init=Cr;Ae.log=kr;Ae.formatArgs=wr;Ae.save=br;Ae.load=Sr;Ae.useColors=gr;Ae.destroy=R.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");Ae.colors=[6,2,3,4,5,1];try{let e=Ye();if(e&&(e.stderr||e).level>=2)Ae.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221]}catch(e){}Ae.inspectOpts=Object.keys(process.env).filter((e)=>/^debug_/i.test(e)).reduce((e,t)=>{let r=t.substring(6).toLowerCase().replace(/_([a-z])/g,(i,o)=>o.toUpperCase()),n=process.env[t];if(/^(yes|on|true|enabled)$/i.test(n))n=!0;else if(/^(no|off|false|disabled)$/i.test(n))n=!1;else if(n==="null")n=null;else n=Number(n);return e[r]=n,e},{});function gr(){return"colors"in Ae.inspectOpts?Boolean(Ae.inspectOpts.colors):et.isatty(process.stderr.fd)}function wr(e){let{namespace:t,useColors:r}=this;if(r){let n=this.color,i="\x1B[3"+(n<8?n:"8;5;"+n),o=` ${i};1m${t} \x1B[0m`;e[0]=o+e[0].split(`
|
|
3
3
|
`).join(`
|
|
4
4
|
`+o),e.push(i+"m+"+me.exports.humanize(this.diff)+"\x1B[0m")}else e[0]=yr()+t+" "+e[0]}function yr(){if(Ae.inspectOpts.hideDate)return"";return new Date().toISOString()+" "}function kr(...e){return process.stderr.write(R.formatWithOptions(Ae.inspectOpts,...e)+`
|
|
5
5
|
`)}function br(e){if(e)process.env.DEBUG=e;else delete process.env.DEBUG}function Sr(){return process.env.DEBUG}function Cr(e){e.inspectOpts={};let t=Object.keys(Ae.inspectOpts);for(let r=0;r<t.length;r++)e.inspectOpts[t[r]]=Ae.inspectOpts[t[r]]}me.exports=Fe()(Ae);var{formatters:tt}=me.exports;tt.o=function(e){return this.inspectOpts.colors=this.useColors,R.inspect(e,this.inspectOpts).split(`
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{T,e}from"./index-7wm4bqx5.js";var A="bridge-client",I=2000,O=30000,C=30000,M=6,u={commandPattern:/^[a-z][a-z0-9]*(\.[a-z][a-z0-9_-]*){0,4}$/,idPattern:/^[A-Za-z0-9-]{1,64}$/,maxTimeoutMs:120000,defaultTimeoutMs:30000,maxConcurrent:16,abandonGraceMs:30000,maxResponseBytes:8388608,errorCodePattern:/^[A-Z][A-Z0-9_]{0,63}$/};class He extends Error{code;constructor(t,r){super(r);this.code=t;this.name="BridgeCommandError"}}var n={ws:null,pingTimer:null,reconnectTimer:null,reconnectAttempt:0,connected:!1,stopped:!1,agentId:null,profile:"default",pendingEvents:[],handlers:new Map,running:new Map,clockOffsetMs:null};function s(t,r,o){e().logger[t](A,r,o)}function N(t){try{let r=new URL(t);r.protocol=r.protocol==="https:"?"wss:":"ws:",r.pathname="/agent-bridge",r.search="",r.hash="";let o=process.env.VIBE_BRIDGE_URL;if(o)return o;return r.toString()}catch{return process.env.VIBE_BRIDGE_URL??""}}async function _(){if(n.stopped||n.ws)return;if(!T.isConfigured()){s("debug","Gateway client not configured yet; deferring bridge connect");return}if(!n.agentId){s("debug","No agentId set yet; deferring bridge connect");return}let t,r,o;try{let i=await T.getAccessToken();t=i.token,r=i.workspaceGatewayUrl,o=i.workspaceId}catch(i){s("warn","Failed to fetch access token for bridge",{error:i instanceof Error?i.message:String(i)}),p();return}if(!t||!r){p();return}let d=N(r);if(!d){s("warn","Cannot resolve bridge URL from workspaceGatewayUrl",{workspaceGatewayUrl:r}),p();return}s("info","Connecting to agent-bridge",{url:d,agentId:n.agentId});let c;try{c=new WebSocket(d,{headers:{Authorization:`Bearer ${t}`,...o?{"x-workspace-id":o}:{}}})}catch(i){s("warn","Bridge connect threw",{error:i instanceof Error?i.message:String(i)}),p();return}n.ws=c,c.addEventListener("open",()=>{n.reconnectAttempt=0,s("info","Bridge socket open \u2014 sending hello"),h({type:"hello",agentId:n.agentId,profile:n.profile,version:process.env.npm_package_version??"unknown"})}),c.addEventListener("message",(i)=>{let m=typeof i.data==="string"?i.data:i.data instanceof Blob?"":new TextDecoder().decode(i.data);if(!m)return;let a;try{a=JSON.parse(m)}catch{return}if(a.type==="welcome")n.connected=!0,n.clockOffsetMs=typeof a.serverTime==="number"&&Number.isFinite(a.serverTime)?a.serverTime-Date.now():null,s("info","Bridge welcome received \u2014 connection ready",{workspaceId:typeof a.workspaceId==="string"?a.workspaceId:void 0}),G(),U();else if(a.type==="request")P(c,a);else if(a.type==="error")s("warn","Bridge error frame",{error:a})}),c.addEventListener("close",(i)=>{if(s("info","Bridge socket closed",{code:i.code,reason:i.reason}),S(),!n.stopped)p()}),c.addEventListener("error",(i)=>{s("warn","Bridge socket error",{message:i.message})})}function k(t,r){if(t.readyState!==1)return;let o;try{o=JSON.stringify(r)}catch{o=JSON.stringify({type:"response",id:r.id,ok:!1,error:{code:"AGENT_ERROR",message:"result is not serializable"}})}if(Buffer.byteLength(o,"utf8")>u.maxResponseBytes)o=JSON.stringify({type:"response",id:r.id,ok:!1,error:{code:"RESPONSE_TOO_LARGE",message:"result is too large"}});try{t.send(o)}catch(d){s("debug","Bridge response send failed",{error:d instanceof Error?d.message:String(d)})}}function x(t){let r=t instanceof He&&u.errorCodePattern.test(t.code)?t.code:"AGENT_ERROR",o=t instanceof Error?t.message:String(t);return{code:r,message:o.slice(0,500)}}async function P(t,r){let o=r.id;if(typeof o!=="string"||!u.idPattern.test(o)){s("warn","Bridge request without a valid id; ignored");return}let d=(l,f)=>k(t,{type:"response",id:o,ok:!1,error:{code:l,message:f}}),c=r.command;if(typeof c!=="string"||!u.commandPattern.test(c)){d("BAD_REQUEST","invalid command name");return}let i=n.handlers.get(c);if(!i){d("UNKNOWN_COMMAND",`this agent does not run '${c}'`);return}if(n.running.has(o)){d("BAD_REQUEST","duplicate request id");return}if(n.running.size>=u.maxConcurrent){d("TOO_MANY_REQUESTS","too many commands running on this agent");return}let m=typeof r.timeoutMs==="number"&&Number.isFinite(r.timeoutMs)?r.timeoutMs:u.defaultTimeoutMs,a=Math.min(Math.max(m,1),u.maxTimeoutMs);if(n.clockOffsetMs!==null&&typeof r.deadline==="number"&&Number.isFinite(r.deadline)){let l=r.deadline-(Date.now()+n.clockOffsetMs);if(l<=0){d("TIMEOUT","the request expired before it arrived");return}a=Math.min(a,l)}let g=new AbortController;n.running.set(o,g);let E=setTimeout(()=>g.abort(),a);E.unref?.();let y=null;g.signal.addEventListener("abort",()=>{y=setTimeout(()=>{if(n.running.get(o)!==g)return;n.running.delete(o),s("warn","Bridge command ignored its abort; slot reclaimed",{command:c})},Math.min(a,u.abandonGraceMs)),y.unref?.()});let v=new Promise((l,f)=>{g.signal.addEventListener("abort",()=>f(new He("TIMEOUT","aborted")))});v.catch(()=>{});let w;try{w=Promise.resolve(i(r.payload??null,{signal:g.signal,deadline:Date.now()+a}))}catch(l){w=Promise.reject(l)}w.catch(()=>{}).finally(()=>{if(clearTimeout(E),y)clearTimeout(y);if(n.running.get(o)===g)n.running.delete(o)});try{let l=await Promise.race([w,v]);k(t,{type:"response",id:o,ok:!0,result:l??null})}catch(l){let{code:f,message:b}=g.signal.aborted?{code:"TIMEOUT",message:`command '${c}' did not finish in time`}:x(l);if(f==="AGENT_ERROR")s("warn","Bridge command failed",{command:c,error:b});d(f,b)}}function L(){for(let t of n.running.values())t.abort()}function h(t){if(!n.ws||n.ws.readyState!==1)return!1;try{return n.ws.send(JSON.stringify(t)),!0}catch(r){return s("debug","safeSend failed",{error:r instanceof Error?r.message:String(r)}),!1}}function G(){B(),n.pingTimer=setInterval(()=>{h({type:"ping"})},C),n.pingTimer.unref?.()}function B(){if(n.pingTimer)clearInterval(n.pingTimer),n.pingTimer=null}function S(){n.connected=!1,n.clockOffsetMs=null,B(),L(),n.ws=null}function p(){if(n.stopped||n.reconnectTimer)return;let t=n.reconnectAttempt+1,r=Math.min(I*2**Math.min(t-1,5),O);if(n.reconnectAttempt=t,t===M)s("warn",`Bridge unavailable after ${t} attempts \u2014 falling back to existing HTTP polling for heartbeat/tunnel sync. Will keep retrying in the background.`);n.reconnectTimer=setTimeout(()=>{n.reconnectTimer=null,_().catch((o)=>{s("debug",`Bridge reconnect attempt failed: ${o instanceof Error?o.message:String(o)}`)})},r),n.reconnectTimer.unref?.()}function U(){if(!n.connected)return;while(n.pendingEvents.length>0){let t=n.pendingEvents.shift();if(!h({type:t.type,...t.payload})){n.pendingEvents.unshift(t);return}}}var D=500;function R(t){if(n.connected&&h({type:t.type,...t.payload}))return;if(n.pendingEvents.length>=D)n.pendingEvents.shift();n.pendingEvents.push(t)}var zi={start(t,r){if(n.stopped=!1,n.agentId===t&&n.connected)return;n.agentId=t,n.profile=r||"default",_().catch((o)=>{s("debug",`Bridge connect failed: ${o instanceof Error?o.message:String(o)}`)})},stop(){if(n.stopped=!0,n.reconnectTimer)clearTimeout(n.reconnectTimer),n.reconnectTimer=null;let t=n.ws;try{t?.close(1000,"agent shutdown")}catch{}S()},publishEvent(t){R({type:"event",payload:{topic:t.topic,payload:t.payload}})},publishLog(t){R({type:"log",payload:{payload:t}})},isConnected(){return n.connected},handle(t,r){if(!u.commandPattern.test(t))throw Error(`invalid bridge command name '${t}'`);return n.handlers.set(t,r),()=>{if(n.handlers.get(t)===r)n.handlers.delete(t)}},commands(){return[...n.handlers.keys()].sort()},isFallbackEngaged(){return n.reconnectAttempt>=M&&!n.connected}};
|
|
3
|
+
export{He,zi};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var o=Symbol.for("@vibecontrols/plugin-sdk:contextProviders@1");function r(){let t=globalThis,e=t[o];if(e)return e;let n=new Map;return t[o]=n,n}function
|
|
3
|
-
export{
|
|
2
|
+
var o=Symbol.for("@vibecontrols/plugin-sdk:contextProviders@1");function r(){let t=globalThis,e=t[o];if(e)return e;let n=new Map;return t[o]=n,n}function Rr(){return Array.from(r().values())}
|
|
3
|
+
export{Rr};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var a=/(^|[_-]|(?<=[a-z]))(secret|password|token|email|url|api[_-]?key|access[_-]?key)(s)?($|[_-]|[A-Z])/i,u=/^(name|user|firstName|lastName|fullName|displayName)$/i;function
|
|
3
|
-
export{
|
|
2
|
+
var a=/(^|[_-]|(?<=[a-z]))(secret|password|token|email|url|api[_-]?key|access[_-]?key)(s)?($|[_-]|[A-Z])/i,u=/^(name|user|firstName|lastName|fullName|displayName)$/i;function Kr(e){if(a.test(e))return!0;if(u.test(e))return!0;return!1}var l={"agent.started":{version:"string",profile:"string",platform:"string"},"agent.stopped":{uptime_s:"number",reason:"string"},"plugin.activated":{plugin_name:"string",version:"string",duration_ms:"number"},"plugin.failed":{plugin_name:"string",error_class:"string"},"command.executed":{command_name:"string"},"alias.executed":{exit_code:"number"},"tunnel.url_assigned":{provider:"string"},"health.degraded":{reason_class:"string"},"telemetry.disabled":{reason:"string"}},g=new Map;function c(e){return l[e]??g.get(e)}function Ke(e,n){let r=c(e);if(!r)return{ok:!1,reason:"unknown_event"};let i={};for(let[t,o]of Object.entries(r)){if(Kr(t))continue;if(!(t in n))continue;let s=n[t];if(typeof s!==o)continue;i[t]=s}return{ok:!0,sanitized:i}}
|
|
3
|
+
export{Kr,Ke};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{R,C}from"./index-
|
|
3
|
-
export{
|
|
2
|
+
import{R,C}from"./index-7wm4bqx5.js";import{J,w}from"./index-j99tkngg.js";import{existsSync as d,readFileSync as y}from"fs";import{join as T}from"path";var p="http://localhost:3005",h=new Set(["localhost","127.0.0.1","0.0.0.0","::1","[::1]"]);function A(r){return r.toLowerCase().replace(/^\[|\]$/g,"")}function $t(r){try{let n=new URL(r);return h.has(A(n.hostname))}catch{return!1}}function u(r){let n=new URL(r.trim());if(n.protocol!=="http:"&&n.protocol!=="https:")throw Error("Agent URL must use http or https");if(n.username||n.password)throw Error("Agent URL must not include credentials");let t=n.toString().replace(/\/+$/,"");if(!$t(t)&&process.env.VIBECONTROLS_ALLOW_REMOTE_AGENT_URL!=="1")throw Error("Refusing non-local agent URL. Set VIBECONTROLS_ALLOW_REMOTE_AGENT_URL=1 to target a remote/tunnel URL explicitly.");return t}function O(r){if(!Number.isInteger(r)||r<=0)return!1;try{return process.kill(r,0),!0}catch{return!1}}function _(){let r=T(C(),"agents.json");if(!d(r))return[];try{let n=JSON.parse(y(r,"utf-8"));return(Array.isArray(n)?n:n&&typeof n==="object"&&Array.isArray(n.instances)?n.instances:[]).filter((e)=>!!e&&typeof e==="object"&&typeof e.name==="string"&&typeof e.port==="number")}catch{return[]}}function E(r){let t=_().find((e)=>e.name===r);if(!t||!t.port)return null;if(typeof t.pid==="number"&&!O(t.pid))return null;return{url:`http://localhost:${t.port}`,port:t.port}}function f(r){let n=r?.agentUrl&&r.agentUrl!==p?r.agentUrl:void 0;if(n)return u(n);if(r?.profile){let t=E(r.profile);if(t)return t.url}if(process.env.AGENT_URL)return u(process.env.AGENT_URL);try{let t=m({}),e=E(t);if(e)return e.url}catch{}return u(p)}async function Fe(r){let n=$t(r);if(process.env.AGENT_API_KEY){if(n||process.env.VIBECONTROLS_SEND_API_KEY_TO_REMOTE==="1")return process.env.AGENT_API_KEY;throw Error("Refusing to send AGENT_API_KEY to a non-local agent URL. Set VIBECONTROLS_SEND_API_KEY_TO_REMOTE=1 only if you trust the target.")}if(!n)return;let t=R(),e=await J(`${t}:static-api-key`);if(e)return e;return w()["static-api-key"]}function m(r){if(r?.profile)return r.profile;if(process.env.VIBECONTROLS_PROFILE)return process.env.VIBECONTROLS_PROFILE;try{let n=T(C(),"agents.json");if(d(n)){let t=JSON.parse(y(n,"utf-8")),e=t&&typeof t==="object"&&!Array.isArray(t)?t.defaultProfile:void 0;if(typeof e==="string"&&e.length>0)return e}}catch{}return"default"}async function c(r,n,t={}){let e=await Fe(r),s={...t.body?{"Content-Type":"application/json"}:{},...e?{"x-agent-api-key":e}:{},...t.headers??{}},o;try{o=await fetch(`${r}${n}`,{...t,headers:s})}catch(i){let g=i instanceof Error?i.message:String(i),l=/unable to connect|ECONNREFUSED|ENOTFOUND|EHOSTUNREACH|fetch failed/i.test(g);if(l&&$t(r))throw Error(`Agent not reachable at ${r}. Is it running? Try 'vibe status' or 'vibe start'.`,{cause:i});if(l)throw Error(`Agent not reachable at ${r}. ${g}`,{cause:i});throw i}let a=await o.json().catch(()=>({}));return{ok:o.ok,status:o.status,data:a}}async function S(r,n){let{ok:t,status:e,data:s}=await c(r,n);if(!t){let o=s?.error||s?.message||`Agent returned ${e}`;throw Error(String(o))}return s}async function q(r,n,t){let{ok:e,status:s,data:o}=await c(r,n,{method:"POST",body:t!=null?JSON.stringify(t):void 0});if(!e){let a=o?.error||o?.message||`Agent returned ${s}`;throw Error(String(a))}return o}async function Te(r,n,t){let{ok:e,status:s,data:o}=await c(r,n,{method:"PUT",body:t!=null?JSON.stringify(t):void 0});if(!e){let a=o?.error||o?.message||`Agent returned ${s}`;throw Error(String(a))}return o}async function ge(r,n){let{ok:t,status:e,data:s}=await c(r,n,{method:"DELETE"});if(!t){let o=s?.error||s?.message||`Agent returned ${e}`;throw Error(String(o))}return s}
|
|
3
|
+
export{$t,f,Fe,m,S,q,Te,ge};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{r,E}from"./index-
|
|
3
|
-
`)}));await Q({title:`vibe git list \u2014 ${c.length} repo(s)`,rows:h})},json:(c)=>c.map((h)=>({id:h.id,name:h.name??null,path:h.path??null,type:h.type??h.projectType??null,isSubmodule:!!h.isSubmodule,scannedAt:h.scannedAt??null}))})}catch(a){s(A(a))}}),i.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",w).option("--json","Emit JSON").action(async function(t){let e={...d.opts(),...t};try{let a=f(t),R=encodeURIComponent(m(e)),c=await q(a,`/api/profiles/${R}/git/scan`,{directory:t.dir,depth:parseInt(t.depth,10)});if(u(e,{ok:!0,found:c?.found??c?.repositories?.length??0}))return;if(l("Git scan completed."),c?.found!==void 0)n("Repositories found",c.found);if(c?.repositories)n("Repositories found",c.repositories.length)}catch(a){if(e.json){u(e,{ok:!1,error:A(a)});return}s(A(a))}}),i.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",w).option("--json","Emit JSON").action(async function(t){let e={...d.opts(),...t};try{let a=f(t),R=encodeURIComponent(m(e)),c={};if(t.vitePort)c.vitePort=parseInt(t.vitePort,10);if(t.projectType)c.projectType=t.projectType;if(await
|
|
2
|
+
import{r,E}from"./index-1t74r13z.js";import{oe,Ft}from"./index-ppxayc0x.js";import"./index-7wm4bqx5.js";import"./index-j99tkngg.js";import{s,A,l,o,g,n,F,v,H}from"./index-12gb48hg.js";import{Q}from"./index-sq5j8bjn.js";import{_,y,u}from"./index-v77bb0rm.js";import{f,m,S,q,Te,ge}from"./index-damc6cvc.js";import{promises as b}from"fs";import P from"path";async function I(d){try{let i=await b.readdir(d);if(i.includes("package.json")){try{let t=JSON.parse(await b.readFile(P.join(d,"package.json"),"utf8")),e={...t.dependencies,...t.devDependencies};if(e.react||e["@types/react"])return"react";if(e.vue||e["@vue/cli"])return"vue";if(e.angular||e["@angular/core"])return"angular";if(e.next||e["@types/next"])return"nextjs";if(e.nuxt||e["@nuxt/core"])return"nuxtjs";if(e.svelte||e["@sveltejs/kit"])return"svelte";if(e.express||e.fastify||e.koa)return"nodejs-backend";if(e.electron)return"electron";if(e.vite)return"vite"}catch{}return"nodejs"}if(i.includes("setup.py")||i.includes("requirements.txt")||i.includes("pyproject.toml")||i.includes("Pipfile")){if(i.includes("manage.py"))return"django";if(i.includes("app.py"))return"flask";return"python"}if(i.includes("go.mod"))return"go";if(i.includes("Cargo.toml"))return"rust";if(i.includes("pom.xml"))return"maven";if(i.includes("build.gradle")||i.includes("build.gradle.kts"))return"gradle";if(i.includes("Gemfile"))return"ruby";if(i.includes("composer.json"))return"php";if(i.some((t)=>t.endsWith(".csproj")||t.endsWith(".sln")))return"dotnet";if(i.includes("CMakeLists.txt")||i.includes("Makefile"))return"cpp";if(i.includes("Package.swift"))return"swift";if(i.includes("pubspec.yaml"))return"flutter";if(i.some((t)=>t.endsWith(".tf")))return"terraform";if(i.includes("Dockerfile"))return"docker"}catch{}return}async function G(d){try{let i=["vite.config.ts","vite.config.js"];for(let t of i)try{let a=(await b.readFile(P.join(d,t),"utf-8")).match(/port:\s*(\d+)/);if(a)return parseInt(a[1],10)}catch{}}catch{}return}var O=new Set([".git","node_modules","__pycache__",".venv","venv","dist","build"]),N=parseInt(process.env.VIBECONTROLS_GIT_SCAN_MAX_DEPTH??"8",10),J=parseInt(process.env.VIBECONTROLS_GIT_SCAN_MAX_DIRECTORIES??"5000",10);async function C(d,i,t,e={visited:0},a=0){let R=[];if(a>N||e.visited>=J)return R;e.visited+=1;try{let c=await Ft(d);if(c.some((p)=>p.name===".git"&&p.isDirectory())){if(R.push({path:d,name:P.basename(d),parentPath:t,isSubmodule:!!t,projectType:await I(d),vitePort:await G(d)}),!i)return R;t=d}for(let p of c)if(p.isDirectory()&&!p.isSymbolicLink()&&!O.has(p.name)&&!p.name.startsWith(".")){let j=P.join(d,p.name),x=await C(j,i,t,e,a+1);R.push(...x)}}catch{}return R}function T(d){let{db:i}=d;return new E().get("/",async()=>({repositories:await i.getAllGitRepositories()})).get("/:id",async({params:t,set:e})=>{let a=await i.getGitRepository(t.id);if(!a)return e.status=404,{error:"Repository not found"};return{repository:a}}).post("/scan",async({body:t,set:e})=>{try{let a=(await oe(t.directory,{mustExist:!0})).path;if(!(await b.stat(a)).isDirectory())return e.status=400,{error:"Path is not a directory"};let c=await C(a,t.includeSubmodules??!0),h=[];for(let p of c){let j=await i.getGitRepositoryByPath(p.path);if(j)await i.updateGitRepository(j.id,p),h.push({...j,...p});else{let x=await i.createGitRepository({id:globalThis.crypto.randomUUID(),...p});h.push(x)}}return{repositories:h,scannedPath:a,totalFound:h.length}}catch(a){return e.status=500,{error:"Failed to scan directory",details:String(a)}}},{body:r.Object({directory:r.String(),includeSubmodules:r.Optional(r.Boolean())})}).put("/:id",async({params:t,body:e,set:a})=>{if(!await i.getGitRepository(t.id))return a.status=404,{error:"Repository not found"};try{return await i.updateGitRepository(t.id,e),{success:!0}}catch(c){return a.status=500,{error:"Failed to update repository",details:String(c)}}},{body:r.Object({name:r.Optional(r.String()),projectType:r.Optional(r.String()),vitePort:r.Optional(r.Number())})}).delete("/:id",async({params:t,set:e})=>{if(!await i.getGitRepository(t.id))return e.status=404,{error:"Repository not found"};try{return await i.deleteGitRepository(t.id),{success:!0}}catch(R){return e.status=500,{error:"Failed to delete repository",details:String(R)}}}).post("/fix-hierarchy",async({set:t})=>{try{let e=await i.fixGitHierarchy(),a=await i.getAllGitRepositories();return{success:!0,fixed:e.fixed,total:a.length}}catch(e){return t.status=500,{error:"Failed to fix hierarchy",details:String(e)}}})}var w="http://localhost:3005";function k(d){let i=d.command("git").description("Manage git repositories");i.command("list").description("List discovered git repositories").option("--agent-url <url>","Agent URL",w).option("--json","Emit JSON").option("--plain","Force plain text output").action(async function(t){let e={...d.opts(),...t};try{let a=f(t),R=encodeURIComponent(m(e));await y({mode:_(e),fetchData:async()=>(await S(a,`/api/profiles/${R}/git`)).repositories||[],plain:(c)=>{if(!c||c.length===0){o("No git repositories found.");return}g("Git Repositories"),F(c.map((h)=>({ID:H(h.id),Name:h.name||"-",Path:h.path||"-",Type:h.type||h.projectType||"-",Submodule:h.isSubmodule?"Yes":"No",Scanned:h.scannedAt?v(h.scannedAt):"-"})))},interactive:async(c)=>{if(!c||c.length===0){g("Git Repositories"),o("No git repositories found.");return}let h=c.map((p)=>({id:String(p.id),label:p.name||H(p.id),hint:p.type||p.projectType||"",detail:[`ID: ${p.id}`,`Name: ${p.name??"-"}`,`Path: ${p.path??"-"}`,`Type: ${p.type??p.projectType??"-"}`,`Submodule: ${p.isSubmodule?"Yes":"No"}`,`Scanned: ${p.scannedAt?v(p.scannedAt):"-"}`].join(`
|
|
3
|
+
`)}));await Q({title:`vibe git list \u2014 ${c.length} repo(s)`,rows:h})},json:(c)=>c.map((h)=>({id:h.id,name:h.name??null,path:h.path??null,type:h.type??h.projectType??null,isSubmodule:!!h.isSubmodule,scannedAt:h.scannedAt??null}))})}catch(a){s(A(a))}}),i.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",w).option("--json","Emit JSON").action(async function(t){let e={...d.opts(),...t};try{let a=f(t),R=encodeURIComponent(m(e)),c=await q(a,`/api/profiles/${R}/git/scan`,{directory:t.dir,depth:parseInt(t.depth,10)});if(u(e,{ok:!0,found:c?.found??c?.repositories?.length??0}))return;if(l("Git scan completed."),c?.found!==void 0)n("Repositories found",c.found);if(c?.repositories)n("Repositories found",c.repositories.length)}catch(a){if(e.json){u(e,{ok:!1,error:A(a)});return}s(A(a))}}),i.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",w).option("--json","Emit JSON").action(async function(t){let e={...d.opts(),...t};try{let a=f(t),R=encodeURIComponent(m(e)),c={};if(t.vitePort)c.vitePort=parseInt(t.vitePort,10);if(t.projectType)c.projectType=t.projectType;if(await Te(a,`/api/profiles/${R}/git/${t.id}`,c),u(e,{ok:!0,id:t.id}))return;l(`Repository ${H(t.id)} updated.`)}catch(a){if(e.json){u(e,{ok:!1,error:A(a)});return}s(A(a))}}),i.command("delete").description("Delete a git repository entry").requiredOption("-i, --id <id>","Repository ID").option("--agent-url <url>","Agent URL",w).option("--json","Emit JSON").action(async function(t){let e={...d.opts(),...t};try{let a=f(t),R=encodeURIComponent(m(e));if(await ge(a,`/api/profiles/${R}/git/${t.id}`),u(e,{ok:!0,id:t.id}))return;l(`Repository ${H(t.id)} deleted.`)}catch(a){if(e.json){u(e,{ok:!1,error:A(a)});return}s(A(a))}}),i.command("fix-hierarchy").description("Fix repository parent-child hierarchy").option("--agent-url <url>","Agent URL",w).option("--json","Emit JSON").action(async function(t){let e={...d.opts(),...t};try{let a=f(t),R=encodeURIComponent(m(e)),c=await q(a,`/api/profiles/${R}/git/fix-hierarchy`,{});if(u(e,{ok:!0,fixed:c?.fixed??null}))return;if(l("Hierarchy fix completed."),c?.fixed!==void 0)n("Fixed",c.fixed)}catch(a){if(e.json){u(e,{ok:!1,error:A(a)});return}s(A(a))}})}function D(d,i){k(d)}function te(d){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:(i)=>T(i),onCliSetup:async(i,t)=>{D(i,t)}}}export{te as createPlugin};
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{r,E}from"./index-1t74r13z.js";import{e}from"./index-7wm4bqx5.js";import{Et,Bi,cr,ur,kt,tt,Ue,ce,Lt,fe}from"./index-p1b10hs1.js";import{St,Qt}from"./index-x4z055t8.js";import"./index-j99tkngg.js";import{rr}from"./index-6b9vh0gq.js";import"./index-qzwbctkv.js";import"./index-p7fbnfwd.js";import{qt,Cr}from"./index-vhz1c474.js";import{i,s,A,l,p,o,g,n,F}from"./index-12gb48hg.js";import{Q,U}from"./index-sq5j8bjn.js";import"./index-0rmmrrfh.js";import"./index-6wfd7cv3.js";import{ue,le,_,y,u}from"./index-v77bb0rm.js";import{f,m,S,q}from"./index-damc6cvc.js";import{timingSafeEqual as ye}from"crypto";function he(){return(process.env.NPM_CONFIG_REGISTRY||process.env.npm_config_registry||"https://registry.npmjs.org").replace(/\/+$/,"")}async function Y(c,R){try{let b=await fetch(`${he()}/${c}/${R}`,{headers:{accept:"application/json"},signal:AbortSignal.timeout(1e4)});if(b.ok){let a=(await b.json()).dist?.integrity;if(typeof a==="string"&&a.startsWith("sha"))return a}}catch{}try{let b=Bun.spawn({cmd:["npm","view",`${c}@${R}`,"dist.integrity","--json"],stdout:"pipe",stderr:"pipe"});if(await b.exited!==0)return null;let d=(await new Response(b.stdout).text()).trim();if(!d)return null;if(d.startsWith('"'))try{let P=JSON.parse(d);return typeof P==="string"?P:null}catch{return null}return d}catch{return null}}function Z(c,R){let b=Buffer.from(c),t=Buffer.from(R);if(b.length!==t.length)return!1;try{return ye(b,t)}catch{return!1}}var be=Bi.map((c)=>({packageName:c.packageName,name:c.pluginName,description:c.description,cliCommand:c.cliCommand,apiPrefix:c.apiPrefix,installed:!1,category:c.category})),H=new Map;function O(c,R){let t=(H.get(c)??Promise.resolve()).then(R,R),a=t.then(()=>{return},()=>{return});return H.set(c,a),a.finally(()=>{if(H.get(c)===a)H.delete(c)}),t}function X(c){return H.has(c)}function ee(c){let R=c.getPluginDetails(),b=new Set(R.map((t)=>t.packageName));return{plugins:be.map((t)=>({...t,installed:b.has(t.packageName)}))}}function te(c){let{pluginManager:R}=c;return new E().get("/",()=>{let b=R.getPluginDetails();return{plugins:b,count:b.length}}).get("/available",()=>ee(R)).get("/catalog",()=>ee(R)).get("/contributions",({query:b})=>{let t=typeof b?.mountPoint==="string"&&b.mountPoint?b.mountPoint:null,a=[],d=new Map;for(let P of R.getPluginDetails())d.set(P.pluginName,P.packageName);for(let P of R.getAllPlugins()){let N=P.ui;if(!N||!N.contributions||N.contributions.length===0)continue;let v=N.capabilities??{restPaths:[],wsTopics:[],rpcMethods:[]};for(let k of N.contributions){if(t&&k.mountPoint!==t)continue;let h=k.meta,w=h&&typeof h.url==="string"?h.url:null,C=w&&w.startsWith("/")&&!w.startsWith("//")&&!w.includes("\x00")&&!w.includes("..")?w:null;a.push({pluginKey:P.name,pluginPackageName:d.get(P.name),contribution:k,capabilities:k.capabilities??v,url:C??`/ui/${encodeURIComponent(P.name)}`})}}return{contributions:a,count:a.length}}).post("/install",async({body:b,set:t})=>{if(!b.packageName||typeof b.packageName!=="string")return t.status=400,{error:"Missing required field: packageName"};if(b.packageName.startsWith("@burdenoff/"))b.packageName=b.packageName.replace(/^@burdenoff\//,"@vibecontrols/");if(!kt(b.packageName))return t.status=403,{error:"Plugin package is not in the trusted VibeControls catalog"};if(tt(b.packageName)&&b.confirmUntrusted!==!0)return t.status=428,{error:"confirmation_required",code:"CONFIRMATION_REQUIRED",packageName:b.packageName,message:`${b.packageName} is not a trusted plugin. Installing it needs confirmation.`};try{let a=fe(b.packageName);if(X(a)){let d=a.split("/").pop()?.replace("vibe-plugin-","");if(R.getAllPlugins().some((N)=>N.name===d))return{success:!0,message:`Plugin ${a} is already installed`,packageName:a,alreadyInstalled:!0};return t.status=409,{error:"Install for this package is already in progress. Wait for it to finish.",packageName:a}}return await O(a,async()=>{let d=a.split("/").pop()?.replace("vibe-plugin-",""),P=d?.startsWith("ai-")?d.slice(3):void 0,N=R.getAllPlugins().find((I)=>I.name===d||I.name===P),v=!!N,k=await R.install(a,{confirmUntrusted:b.confirmUntrusted===!0}),h=cr(a);if(h?.integrity){let I=await Y(a,k.version);if(I&&!Z(h.integrity,I)){try{await R.remove(a,c.hostServices)}catch(x){console.warn(`[plugin-mgr] integrity rollback uninstall failed for ${a}:`,x)}return e().audit.emit("agent","plugin.install.rejected",{packageName:a,version:k.version,reason:"integrity_mismatch",expected:h.integrity,actual:I}),t.status=400,{error:"integrity mismatch",expected:h.integrity,actual:I}}if(!I)console.warn(`[plugin-mgr] could not fetch registry integrity for ${a}@${k.version}; accepting the package-manager-verified tarball (pin present but unverifiable)`),e().audit.emit("agent","plugin.install.integrity_unverified",{packageName:a,version:k.version,expected:h.integrity})}else console.warn(`[plugin-mgr] plugin ${a} has no pinned integrity \u2014 accepting npm registry's hash`);let w=R.getAllPlugins().find((I)=>I.name===k.pluginName);if(w){let I=[];if(c.mountPlugin)c.mountPlugin(w);if(c.hostServices){if(v&&N?.onServerStop)try{await N.onServerStop()}catch(L){I.push(`onServerStop failed: ${L instanceof Error?L.message:String(L)}`)}R.registerProviders(w,c.hostServices);let x=R.hostServicesFor(w,c.hostServices);if(w.onServerStart&&c.app)try{await w.onServerStart(c.app,x),R.registerProviders(w,c.hostServices)}catch(L){I.push(`onServerStart failed: ${L instanceof Error?L.message:String(L)}`)}if(w.onServerReady&&c.app)try{await w.onServerReady(c.app,x)}catch(L){I.push(`onServerReady failed: ${L instanceof Error?L.message:String(L)}`)}}if(c.rebuildPluginSurfaces?.(),I.length>0)return t.status=500,{success:!1,message:`Plugin ${a} installed but failed to start`,lifecycleErrors:I,restartRequired:!0}}let C;if(w&&c.app)try{C=await qt(w,a,c.app,c.db,{skipInstall:!!b.skipPrereqs})}catch(I){C=void 0,console.warn(`[plugin-mgr] prereq run failed for ${a}:`,I)}return rr(c.db),e().audit.emit("agent","plugin.installed",{packageName:a,version:k.version,pluginName:k.pluginName,wasRunning:v}),{success:!0,message:`Plugin ${a} installed and loaded successfully`,prereqs:C?{satisfied:C.satisfied,missing:C.status?.missing??[],pendingSudo:C.pendingSudo,skipped:!!b.skipPrereqs}:void 0}})}catch(a){if(a instanceof ce)return t.status=400,{error:"signature_check_failed",reason:a.reason,details:a.message};if(a instanceof Lt)return t.status=428,{error:"confirmation_required",code:a.code,packageName:a.packageName,message:a.message};return t.status=500,{error:"Failed to install plugin",details:String(a)}}},{body:r.Object({packageName:r.String(),skipPrereqs:r.Optional(r.Boolean()),confirmUntrusted:r.Optional(r.Boolean())})}).post("/prereqs/status",async({body:b,set:t})=>{if(!b.packageName)return t.status=400,{error:"Missing packageName"};let a=b.packageName,d=R.getAllPlugins().find((P)=>P.name===a||R.getLoaded(a)?.name===P.name);if(!d||!c.app)return await Cr(c.db,a)??{satisfied:!0,missing:[]};try{let P=await qt(d,a,c.app,c.db,{skipInstall:!0});return{satisfied:P.satisfied,missing:P.status?.missing??[],noProtocol:P.noProtocol}}catch(P){return t.status=500,{error:String(P)}}},{body:r.Object({packageName:r.String()})}).post("/prereqs/install",async({body:b,set:t})=>{if(!b.packageName)return t.status=400,{error:"Missing packageName"};let a=b.packageName,d=R.getAllPlugins().find((P)=>P.name===a||R.getLoaded(a)?.name===P.name);if(!d||!c.app)return t.status=404,{error:"Plugin not loaded"};try{let P=await qt(d,a,c.app,c.db,{skipInstall:!1});return{satisfied:P.satisfied,installed:P.install?.installed??[],pendingSudo:P.pendingSudo,errors:P.install?.errors??[],noProtocol:P.noProtocol}}catch(P){return t.status=500,{error:String(P)}}},{body:r.Object({packageName:r.String(),approveSudo:r.Optional(r.Boolean())})}).post("/prereqs/uninstall",async({body:b,set:t})=>{if(!b.packageName)return t.status=400,{error:"Missing packageName"};let a=b.packageName,d=R.getAllPlugins().find((k)=>k.name===a);if(!d||!d.apiPrefix||!c.app)return t.status=404,{error:"Plugin not loaded"};let P=c.app.handle;if(typeof P!=="function")return t.status=500,{error:"App handle unavailable"};let N=`${d.apiPrefix.replace(/\/+$/,"")}/prereqs/uninstall`,v=await P.call(c.app,new Request(`http://agent.local${N}`,{method:"POST",headers:{"x-vc-profile-rewrite":"1",[St]:Qt()}}));if(v.status===404)return t.status=404,{error:"Plugin has no prereqs/uninstall endpoint"};return v.json()},{body:r.Object({packageName:r.String()})}).post("/nuke",async({body:b,set:t})=>{if(!c.hostServices)return t.status=503,{error:"hostServices unavailable"};let a=c.hostServices.getDataDir?.();return{ok:!0,...await R.runPluginNuke(b.packageName,c.hostServices,{agentDir:a,dryRun:!!b.dryRun})}},{body:r.Object({packageName:r.Optional(r.String()),dryRun:r.Optional(r.Boolean())})}).post("/remove",async({body:b,set:t})=>{if(!b.packageName||typeof b.packageName!=="string")return t.status=400,{error:"Missing required field: packageName"};if(b.packageName.startsWith("@burdenoff/"))b.packageName=b.packageName.replace(/^@burdenoff\//,"@vibecontrols/");if(Et(b.packageName))return{success:!0,message:`Plugin ${b.packageName} is critical and cannot be removed; treating remove as a no-op.`,skipped:!0};try{let a=fe(b.packageName);return await O(a,async()=>(await R.remove(a,c.hostServices),c.rebuildPluginSurfaces?.(),rr(c.db),e().audit.emit("agent","plugin.removed",{packageName:a}),{success:!0,message:`Plugin ${a} removed successfully`}))}catch(a){return t.status=500,{error:"Failed to remove plugin",details:String(a)}}},{body:r.Object({packageName:r.String()})}).post("/update",async({body:b,set:t})=>{if(!b.packageName||typeof b.packageName!=="string")return t.status=400,{error:"Missing required field: packageName"};let a=typeof b.version==="string"&&b.version.trim()?b.version.trim():void 0;if(a&&!/^[0-9][0-9A-Za-z.+-]{0,63}$/.test(a))return t.status=400,{error:`Invalid version "${a}"`};try{let d=fe(b.packageName);return await O(d,async()=>{let P=R.getLoaded(d);if(P?.onServerStop)await P.onServerStop({reason:"reload"});if(P&&c.hostServices)c.hostServices.serviceRegistry.unregisterPlugin(P.name);let N=await R.update(d,a),v=R.getLoaded(d);if(v&&c.hostServices){R.registerProviders(v,c.hostServices);let k=R.hostServicesFor(v,c.hostServices);if(v.onServerStart&&c.app)await v.onServerStart(c.app,k),R.registerProviders(v,c.hostServices);if(v.onServerReady&&c.app)await v.onServerReady(c.app,k)}return c.rebuildPluginSurfaces?.(),rr(c.db),{success:!0,message:`Plugin ${d} updated to v${N.version}`,version:N.version}})}catch(d){return t.status=500,{error:"Failed to update plugin",details:String(d)}}},{body:r.Object({packageName:r.String(),version:r.Optional(r.String())})}).post("/update-all",async({set:b})=>{try{let t=await O("*",()=>R.updateAll());return{success:!0,results:t,message:`Updated ${t.filter((a)=>a.success).length}/${t.length} plugin(s)`}}catch(t){return b.status=500,{error:"Failed to update all plugins",details:String(t)}}}).post("/remove-all",async({set:b})=>{try{let t=await O("*",async()=>{let a=await R.removeAll(c.hostServices);return c.rebuildPluginSurfaces?.(),a});return{success:!0,results:t,message:`Removed ${t.filter((a)=>a.success).length}/${t.length} plugin(s)`}}catch(t){return b.status=500,{error:"Failed to remove all plugins",details:String(t)}}}).post("/reload",async({set:b})=>{try{if(!c.app||!c.hostServices)return b.status=503,{error:"Plugin lifecycle services are not ready"};let t=await O("*",async()=>(await R.reloadAll(c.app,c.hostServices),c.rebuildPluginSurfaces?.(),R.getPluginDetails()));return{success:!0,plugins:t,message:`Reloaded ${t.length} plugin(s)`}}catch(t){return b.status=500,{error:"Failed to reload plugins",details:String(t)}}}).post("/:name/reload",async({params:b,set:t})=>{if(!c.app||!c.hostServices)return t.status=503,{error:"Plugin lifecycle services are not ready"};let a=b.name,d=R.getAllPlugins().find((v)=>v.name===a);if(!d)return t.status=404,{error:`Plugin "${a}" not found`};let N=R.getPluginDetails().find((v)=>v.pluginName===a)?.packageName??`core:${a}`;if(X(N))return t.status=409,{error:"Plugin lifecycle in progress; try again shortly",packageName:N};try{R.verifyLoadedSignature(N)}catch(v){if(!(v instanceof ce))throw v;try{await d.onServerStop?.({reason:"shutdown"})}catch(k){console.warn(`[plugin-mgr] onServerStop after a failed signature check of ${a}:`,k)}return c.hostServices.serviceRegistry.unregisterPlugin(d.name),await R.evictLoaded(N),t.status=400,{error:"signature_check_failed",reason:v.reason,details:v.message}}try{return await O(N,async()=>{if(d.onServerStop)try{await d.onServerStop({reason:"reload"})}catch(k){console.warn(`[plugin-mgr] onServerStop during reload of ${a}:`,k)}if(c.hostServices)c.hostServices.serviceRegistry.unregisterPlugin(d.name);R.registerProviders(d,c.hostServices);let v=R.hostServicesFor(d,c.hostServices);if(d.onServerStart)await d.onServerStart(c.app,v),R.registerProviders(d,c.hostServices);if(d.onServerReady)await d.onServerReady(c.app,v);return c.rebuildPluginSurfaces?.(),{success:!0,message:`Plugin ${a} reloaded`,version:d.version}})}catch(v){return t.status=500,{error:"Failed to reload plugin",details:String(v)}}},{params:r.Object({name:r.String()})})}import{mkdirSync as W,writeFileSync as M,existsSync as ne}from"fs";import{isAbsolute as Se,join as j,relative as Pe,resolve as G}from"path";var J="http://localhost:3005";async function we(c,R,b={interactive:ue,prompt:le,warn:p}){if(!tt(c))return!0;if(b.warn(ur(c)?`${c} is a desk plugin: it lets a BotManor Steward see and use this machine. Remote control stays off until you turn it on.`:`${c} is not a trusted plugin.`),R.yes===!0)return!0;if(!b.interactive())return b.warn("Re-run with --yes to confirm the install."),!1;return b.prompt(`Install ${c}?`)}var ke=/^[a-z0-9][a-z0-9-]{0,63}$/,$e=new Set(["backend","frontend","cli","provider","adapter","integration"]);function ie(c,R){let b=Pe(c,R);if(b.startsWith("..")||Se(b))throw Error("Plugin scaffold path escapes the selected directory.")}function T(c){return JSON.stringify(c)}function re(c){let R=c.command("plugin").description("Manage plugins");R.command("list").description("List installed plugins").option("--agent-url <url>","Agent URL",J).option("--profile <name>","Target a specific profile by name").option("--json","Emit JSON").option("--plain","Force plain text output").action(async(t)=>{try{let a={...c.opts(),...t},d=f(t),P=encodeURIComponent(m(a)),N=async()=>{try{return(await S(d,`/api/profiles/${P}/plugins`)).plugins||[]}catch{p("Agent not reachable. Attempting local plugin registry...");let{PluginManager:h}=await import("./plugin-system-7qjqrq7s.js");return new h().getPluginDetails()||[]}},v=(h)=>h.status??(h.loaded===!0||h.enabled===!0?"enabled":"disabled"),k=(h)=>h.pluginName||h.name||h.packageName||h.package||"-";await y({mode:_(a),fetchData:N,plain:(h)=>{if(!h.length){o("No plugins installed.");return}g("Installed Plugins"),F(h.map((w)=>({Name:k(w),Version:w.version||"-",Status:v(w),Description:w.description||"-"})))},interactive:async(h)=>{if(!h.length){g("Installed Plugins"),o("No plugins installed.");return}let w=h.map((C)=>{let I=k(C),x=v(C),L=[`${i.bold(I)} ${x==="enabled"?i.green(x):i.dim(x)}`,"",` Version: ${C.version||"-"}`,` Description: ${C.description||"-"}`];if(C.tags&&Array.isArray(C.tags))L.push(` Tags: ${C.tags.join(", ")}`);if(C.cliCommand)L.push(` CLI command: vibe ${C.cliCommand}`);return{id:I,label:I,hint:x,detail:L.join(`
|
|
3
|
+
`)}});await Q({title:`vibe plugin \u2014 ${h.length} installed`,rows:w,footer:"\u2191/\u2193 navigate \xB7 q to quit"})},json:(h)=>h.map((w)=>({name:k(w),version:w.version??null,status:v(w),description:w.description??null,tags:w.tags??null,cliCommand:w.cliCommand??null}))})}catch(a){s(A(a))}}),R.command("install").description("Install a plugin").argument("<package>","NPM package name to install").option("--agent-url <url>","Agent URL",J).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").option("-y, --yes","Confirm installing an untrusted plugin",!1).action(async(t,a)=>{try{let d={...c.opts(),...a},P=f(a),N=encodeURIComponent(m(d)),v=Ue(t)??t,k=tt(v);if(!await we(v,d)){s(`Install of ${v} cancelled.`);return}try{let h=await q(P,`/api/profiles/${N}/plugins/install`,{packageName:t,skipPrereqs:!!a.skipPrereqs,...k?{confirmUntrusted:!0}:{}});if(u(d,{ok:!0,action:"install",package:t,version:h?.version??null,prereqs:h?.prereqs??null}))return;if(l(`Plugin "${t}" installed.`),h?.version)n("Version",h.version);if(h?.prereqs){let w=h.prereqs;if(w.skipped)p(`Prerequisite install skipped. Run \`vibe plugin prereqs ${t} install\` later.`);else if(!w.satisfied)p(`Prerequisites not yet satisfied: ${(w.missing||[]).map((C)=>C.name).join(", ")||"(unknown)"}`);if((w.pendingSudo||[]).length>0){p(`${w.pendingSudo.length} command(s) need sudo. Run them and re-check with \`vibe plugin prereqs ${t} status\`:`);for(let C of w.pendingSudo)n(` ${C.name}`,C.command)}}}catch{p("Agent not reachable. Attempting local install...");try{let{PluginManager:h}=await import("./plugin-system-7qjqrq7s.js");if(await new h().install(t,{confirmUntrusted:k}),u(d,{ok:!0,action:"install",package:t,local:!0}))return;l(`Plugin "${t}" installed locally.`)}catch(h){s(`Could not install plugin via agent or locally: ${A(h)}`)}}}catch(d){s(A(d))}}),R.command("remove").description("Remove a plugin").argument("<package>","NPM package name to remove").option("--agent-url <url>","Agent URL",J).option("--profile <name>","Target a specific profile by name").option("--json","Emit JSON result").action(async(t,a)=>{try{let d={...c.opts(),...a},P=f(a),N=encodeURIComponent(m(d));try{if(await q(P,`/api/profiles/${N}/plugins/remove`,{packageName:t}),u(d,{ok:!0,action:"remove",package:t}))return;l(`Plugin "${t}" removed.`)}catch{p("Agent not reachable. Attempting local removal...");try{let{PluginManager:v}=await import("./plugin-system-7qjqrq7s.js");if(await new v().remove(t),u(d,{ok:!0,action:"remove",package:t,local:!0}))return;l(`Plugin "${t}" removed locally.`)}catch(v){s(`Could not remove plugin via agent or locally: ${A(v)}`)}}}catch(d){s(A(d))}}),R.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",J).option("--profile <name>","Target a specific profile by name").option("--json","Emit JSON result").action(async(t,a)=>{try{let d={...c.opts(),...a},P=f(a),N=encodeURIComponent(m(d));if(a.all){o("Updating all plugins...");try{let v=await q(P,`/api/profiles/${N}/plugins/update-all`,{}),k=v?.results||[];if(u(d,{ok:!0,action:"update-all",results:k}))return;for(let h of k)if(h.success)l(`Updated ${h.packageName}${h.version?` to v${h.version}`:""}`);else p(`Failed to update ${h.packageName}: ${h.error}`);l(v?.message||"Done.")}catch{p("Agent not reachable. Attempting local update...");try{let{PluginManager:v}=await import("./plugin-system-7qjqrq7s.js"),h=await new v().updateAll();if(u(d,{ok:!0,action:"update-all",results:h,local:!0}))return;for(let w of h)if(w.success)l(`Updated ${w.packageName}${w.version?` to v${w.version}`:""}`);else p(`Failed to update ${w.packageName}: ${w.error}`)}catch(v){s(`Could not update plugins: ${A(v)}`)}}}else if(t){o(`Updating ${t}...`);try{let v=await q(P,`/api/profiles/${N}/plugins/update`,{packageName:t});if(u(d,{ok:!0,action:"update",package:t,version:v?.version??null,message:v?.message??null}))return;l(v?.message||`Plugin "${t}" updated.`)}catch{p("Agent not reachable. Attempting local update...");try{let{PluginManager:v}=await import("./plugin-system-7qjqrq7s.js"),h=await new v().update(t);if(u(d,{ok:!0,action:"update",package:t,version:h.version,local:!0}))return;l(`Plugin "${t}" updated to v${h.version}.`)}catch(v){s(`Could not update plugin: ${A(v)}`)}}}else s("Provide a package name to update, or use --all to update all plugins.")}catch(d){s(A(d))}}),R.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",J).option("--profile <name>","Target a specific profile by name").option("--json","Emit JSON result").action(async(t,a)=>{try{let d={...c.opts(),...a},P=f(a),N=encodeURIComponent(m(d));if(a.all){o("Uninstalling all plugins...");try{let v=await q(P,`/api/profiles/${N}/plugins/remove-all`,{}),k=v?.results||[];if(u(d,{ok:!0,action:"uninstall-all",results:k}))return;for(let h of k)if(h.success)l(`Removed ${h.packageName}`);else p(`Failed to remove ${h.packageName}: ${h.error}`);l(v?.message||"Done.")}catch{p("Agent not reachable. Attempting local removal...");try{let{PluginManager:v}=await import("./plugin-system-7qjqrq7s.js"),h=await new v().removeAll();if(u(d,{ok:!0,action:"uninstall-all",results:h,local:!0}))return;for(let w of h)if(w.success)l(`Removed ${w.packageName}`);else p(`Failed to remove ${w.packageName}: ${w.error}`)}catch(v){s(`Could not uninstall plugins: ${A(v)}`)}}}else if(t)try{if(await q(P,`/api/profiles/${N}/plugins/remove`,{packageName:t}),u(d,{ok:!0,action:"uninstall",package:t}))return;l(`Plugin "${t}" uninstalled.`)}catch{p("Agent not reachable. Attempting local removal...");try{let{PluginManager:v}=await import("./plugin-system-7qjqrq7s.js");if(await new v().remove(t),u(d,{ok:!0,action:"uninstall",package:t,local:!0}))return;l(`Plugin "${t}" uninstalled locally.`)}catch(v){s(`Could not uninstall plugin: ${A(v)}`)}}else s("Provide a package name to uninstall, or use --all to uninstall all plugins.")}catch(d){s(A(d))}}),R.command("reload").description("Reload all plugins").option("--agent-url <url>","Agent URL",J).option("--profile <name>","Target a specific profile by name").option("--json","Emit JSON result").action(async(t)=>{try{let a={...c.opts(),...t},d=f(t),P=encodeURIComponent(m(a));if(await q(d,`/api/profiles/${P}/plugins/reload`,{}),u(a,{ok:!0,action:"reload"}))return;l("Plugins reloaded.")}catch(a){s(A(a))}}),R.command("available").description("Show available plugins").option("--agent-url <url>","Agent URL",J).option("--profile <name>","Target a specific profile by name").option("--json","Emit JSON").option("--plain","Force plain text output").action(async(t)=>{try{let a={...c.opts(),...t},d=f(t),P=encodeURIComponent(m(a)),N=async()=>(await S(d,`/api/profiles/${P}/plugins/available`)).plugins||[],v=(h)=>h.name||h.package||"-",k=(h)=>h.version||h.latestVersion||"-";await y({mode:_(a),fetchData:N,plain:(h)=>{if(!h||h.length===0){o("No available plugins found.");return}g("Available Plugins"),F(h.map((w)=>({Name:v(w),Version:k(w),Description:w.description||"-"})))},interactive:async(h)=>{if(!h||h.length===0){g("Available Plugins"),o("No available plugins found.");return}let w=h.map((C)=>{let I=v(C),x=[i.bold(I),"",` Version: ${k(C)}`,` Description: ${C.description||"-"}`];return{id:I,label:I,hint:k(C),detail:x.join(`
|
|
4
|
+
`)}});await Q({title:`vibe plugin available \u2014 ${h.length} plugin(s)`,rows:w,footer:"\u2191/\u2193 navigate \xB7 q to quit"})},json:(h)=>h.map((w)=>({name:v(w),version:k(w),description:w.description??null}))})}catch(a){s(A(a))}});let b=R.command("prereqs").description("Inspect or run a plugin's prerequisite-install protocol").argument("<package>","NPM package name (or short plugin name)");b.command("status",{isDefault:!0}).description("Show the plugin's prereq status").option("--agent-url <url>","Agent URL",J).option("--profile <name>","Target a specific profile by name").option("--json","Emit JSON").option("--plain","Force plain text output").action(async(t,a)=>{let d=a.parent?.args?.[0];if(!d){s("Missing plugin package argument.");return}try{let P={...c.opts(),...t},N=f(t),v=async()=>q(N,"/api/plugins/prereqs/status",{packageName:d});await y({mode:_(P),fetchData:v,plain:(k)=>{if(n("Plugin",d),n("Satisfied",k?.satisfied?"yes":"no"),Array.isArray(k?.missing)&&k.missing.length>0)n("Missing",k.missing.map((h)=>h.name).join(", "))},interactive:async(k)=>{let h=[`Plugin: ${d}`,`Satisfied: ${k?.satisfied?"yes":"no"}`];if(Array.isArray(k?.missing)&&k.missing.length>0)h.push(`Missing: ${k.missing.map((w)=>w.name).join(", ")}`);await U({title:`Prereqs: ${d}`,body:h.join(`
|
|
5
|
+
`),footer:"q / Esc to quit"})},json:(k)=>({plugin:d,satisfied:!!k?.satisfied,missing:Array.isArray(k?.missing)?k.missing:[],pendingSudo:Array.isArray(k?.pendingSudo)?k.pendingSudo:[]})})}catch(P){s(`Could not read prereq status: ${A(P)}`)}}),b.command("install").description("Run the plugin's prerequisite install endpoint").option("--agent-url <url>","Agent URL",J).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(t,a)=>{let d=a.parent?.args?.[0];if(!d){s("Missing plugin package argument.");return}try{let P={...c.opts(),...t},N=f(t),v=await q(N,"/api/plugins/prereqs/install",{packageName:d,approveSudo:!!t.approveSudo});if(u(P,{ok:!0,action:"prereqs-install",plugin:d,satisfied:!!v?.satisfied,pendingSudo:v?.pendingSudo??[]}))return;if(v?.satisfied)l(`Prerequisites satisfied for ${d}.`);else p(`Prerequisites still missing for ${d}.`);if(Array.isArray(v?.pendingSudo)&&v.pendingSudo.length>0){p(`${v.pendingSudo.length} command(s) require sudo:`);for(let k of v.pendingSudo)n(` ${k.name}`,k.command)}}catch(P){s(`Prereq install failed: ${A(P)}`)}}),b.command("uninstall").description("Run the plugin's prerequisite uninstall endpoint (if supported)").option("--agent-url <url>","Agent URL",J).option("--profile <name>","Target a specific profile by name").option("--json","Emit JSON result").action(async(t,a)=>{let d=a.parent?.args?.[0];if(!d){s("Missing plugin package argument.");return}try{let P={...c.opts(),...t},N=f(t);if(await q(N,"/api/plugins/prereqs/uninstall",{packageName:d}),u(P,{ok:!0,action:"prereqs-uninstall",plugin:d}))return;l(`Prereq uninstall completed for ${d}.`)}catch(P){p(`Prereq uninstall not supported or failed: ${A(P)}`)}}),R.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(t,a)=>{try{let d={...c.opts(),...a},P=t.startsWith("vibe-plugin-")?t.slice(12):t;if(!ke.test(P)){s("Plugin name must use lowercase letters, numbers, and dashes only.");return}let N=a.tag;if(!$e.has(N)){s("Invalid plugin tag.");return}let v=`vibe-plugin-${P}`,k=G(a.dir),h=G(k,v);if(ie(k,h),ne(h)){s(`Directory "${h}" already exists.`);return}o(`Scaffolding ${v}...`),W(j(h,"src"),{recursive:!0}),W(j(h,"dist"),{recursive:!0});let w=`VibeControls plugin: ${P}`,C={name:`@vibecontrols/${v}`,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",P,"bun"],author:{name:"Your Name",email:"you@example.com"},license:"SEE LICENSE IN LICENSE",description:w,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"]};M(j(h,"package.json"),JSON.stringify(C,null,2)+`
|
|
6
|
+
`);let I={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"]};M(j(h,"tsconfig.json"),JSON.stringify(I,null,2)+`
|
|
7
|
+
`),M(j(h,".gitignore"),["node_modules/","dist/","bun.lock",".env",".env.local","*.tgz"].join(`
|
|
8
|
+
`)+`
|
|
9
|
+
`);let x=P,L=T(v),K=T(w),se=T(N),z=T(x),oe=`import type { Command } from "commander";
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* @vibecontrols/${v}
|
|
13
|
+
*
|
|
14
|
+
* ${w}
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
// \u2500\u2500 Plugin Interfaces \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
18
|
+
|
|
19
|
+
export interface HostServices {
|
|
20
|
+
logger?: {
|
|
21
|
+
info: (msg: string) => void;
|
|
22
|
+
warn: (msg: string) => void;
|
|
23
|
+
error: (msg: string) => void;
|
|
24
|
+
debug: (msg: string) => void;
|
|
25
|
+
};
|
|
26
|
+
config?: Record<string, unknown>;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export interface VibePlugin {
|
|
30
|
+
name: string;
|
|
31
|
+
version: string;
|
|
32
|
+
description: string;
|
|
33
|
+
tags?: Array<
|
|
34
|
+
"backend" | "frontend" | "cli" | "provider" | "adapter" | "integration"
|
|
35
|
+
>;
|
|
36
|
+
cliCommand: string;
|
|
37
|
+
onCliSetup: (program: Command, hostServices?: HostServices) => void;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// \u2500\u2500 Plugin Implementation \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
41
|
+
|
|
42
|
+
const plugin: VibePlugin = {
|
|
43
|
+
name: ${L},
|
|
44
|
+
version: "0.1.0",
|
|
45
|
+
description: ${K},
|
|
46
|
+
tags: [${se}],
|
|
47
|
+
cliCommand: ${z},
|
|
48
|
+
|
|
49
|
+
onCliSetup(program: Command, _hostServices?: HostServices): void {
|
|
50
|
+
const cmd = program
|
|
51
|
+
.command(${z})
|
|
52
|
+
.description(${K});
|
|
53
|
+
|
|
54
|
+
cmd
|
|
55
|
+
.command("status")
|
|
56
|
+
.description(`+T(`Show ${P} status`)+`)
|
|
57
|
+
.action(() => {
|
|
58
|
+
console.log(`+T(`${v} is ready.`)+`);
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
cmd
|
|
62
|
+
.command("info")
|
|
63
|
+
.description("Show plugin info")
|
|
64
|
+
.action(() => {
|
|
65
|
+
console.log(JSON.stringify({
|
|
66
|
+
name: plugin.name,
|
|
67
|
+
version: plugin.version,
|
|
68
|
+
description: plugin.description,
|
|
69
|
+
tags: plugin.tags,
|
|
70
|
+
}, null, 2));
|
|
71
|
+
});
|
|
72
|
+
},
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
export default plugin;
|
|
76
|
+
`;M(j(h,"src","index.ts"),oe);let ge=`# ${v}
|
|
77
|
+
|
|
78
|
+
${w}
|
|
79
|
+
|
|
80
|
+
## Installation
|
|
81
|
+
|
|
82
|
+
\`\`\`bash
|
|
83
|
+
vibe plugin install @vibecontrols/${v}
|
|
84
|
+
\`\`\`
|
|
85
|
+
|
|
86
|
+
## Usage
|
|
87
|
+
|
|
88
|
+
\`\`\`bash
|
|
89
|
+
vibe ${x} status
|
|
90
|
+
vibe ${x} info
|
|
91
|
+
\`\`\`
|
|
92
|
+
|
|
93
|
+
## Development
|
|
94
|
+
|
|
95
|
+
\`\`\`bash
|
|
96
|
+
bun install
|
|
97
|
+
bun run build
|
|
98
|
+
bun run sanity
|
|
99
|
+
\`\`\`
|
|
100
|
+
|
|
101
|
+
## Publishing
|
|
102
|
+
|
|
103
|
+
\`\`\`bash
|
|
104
|
+
bun run build
|
|
105
|
+
npm publish
|
|
106
|
+
\`\`\`
|
|
107
|
+
`;M(j(h,"README.md"),ge);let B={ok:!0,action:"create",plugin:v,packageName:`@vibecontrols/${v}`,cliCommand:x,tag:N,dir:h,withUi:a.withUi===!0};if(!d.json)l(`Created ${v} at ${h}`),n("Plugin Name",`@vibecontrols/${v}`),n("CLI Command",`vibe ${x}`),n("Tag",N),o(`
|
|
108
|
+
Next steps:`),o(` cd ${v}`),o(" bun install"),o(" bun run build"),o(` publish @vibecontrols/${v}, then install from catalog`);if(a.withUi){let V=`${v.replace("vibe-plugin-","vibe-plugin-ui-")}`,D=G(k,V);if(ie(k,D),ne(D)){if(!d.json)p(`UI directory "${D}" already exists, skipping.`);B.uiSkipped=!0,B.uiDir=D}else{W(j(D,"src"),{recursive:!0}),W(j(D,"public"),{recursive:!0});let pe={name:`@vibecontrols/${V}`,version:"0.1.0",private:!1,type:"module",scripts:{dev:"vite --port 5180",build:"tsc && vite build",preview:"vite preview",lint:"eslint ./src",format:"bunx prettier . --write","format:check":"bunx prettier . --check","type:check":"tsc --noEmit",sanity:"bun run format:check && bun run lint && bun run type:check && bun run build"},keywords:["vibecontrols","vibe-plugin","ui",P],author:{name:"Your Name",email:"you@example.com"},license:"SEE LICENSE IN LICENSE",description:`UI for ${v}`,dependencies:{react:"^19.0.0","react-dom":"^19.0.0"},devDependencies:{"@types/react":"^19.0.0","@types/react-dom":"^19.0.0","@vitejs/plugin-react":"^4.5.2",typescript:"^5.8.3",vite:"^7.0.0"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},files:["dist/**/*","README.md"]};M(j(D,"package.json"),JSON.stringify(pe,null,2)+`
|
|
109
|
+
`);let de=`import React from "react";
|
|
110
|
+
import ReactDOM from "react-dom/client";
|
|
111
|
+
import App from "./App";
|
|
112
|
+
|
|
113
|
+
ReactDOM.createRoot(document.getElementById("root")!).render(
|
|
114
|
+
<React.StrictMode>
|
|
115
|
+
<App />
|
|
116
|
+
</React.StrictMode>
|
|
117
|
+
);
|
|
118
|
+
`;M(j(D,"src","main.tsx"),de);let me=`import { useState, useEffect } from "react";
|
|
119
|
+
|
|
120
|
+
const TITLE = ${T(`${P} UI`)};
|
|
121
|
+
|
|
122
|
+
export default function App() {
|
|
123
|
+
const [apiKey, setApiKey] = useState<string | null>(null);
|
|
124
|
+
const [status, setStatus] = useState("loading...");
|
|
125
|
+
|
|
126
|
+
useEffect(() => {
|
|
127
|
+
// Auth via postMessage (iframe) or URL param (new tab)
|
|
128
|
+
const params = new URLSearchParams(window.location.search);
|
|
129
|
+
const key = params.get("apiKey");
|
|
130
|
+
if (key) {
|
|
131
|
+
setApiKey(key);
|
|
132
|
+
setStatus("connected");
|
|
133
|
+
return;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
const handler = (e: MessageEvent) => {
|
|
137
|
+
if (e.data?.type === "vibe-auth" && e.data.apiKey) {
|
|
138
|
+
setApiKey(e.data.apiKey);
|
|
139
|
+
setStatus("connected");
|
|
140
|
+
}
|
|
141
|
+
};
|
|
142
|
+
window.addEventListener("message", handler);
|
|
143
|
+
return () => window.removeEventListener("message", handler);
|
|
144
|
+
}, []);
|
|
145
|
+
|
|
146
|
+
return (
|
|
147
|
+
<div style={{ background: "var(--vibe-surface, Canvas)", color: "var(--vibe-text, CanvasText)", minHeight: "100vh", padding: 24, fontFamily: "system-ui" }}>
|
|
148
|
+
<h1>{TITLE}</h1>
|
|
149
|
+
<p>Status: {status}</p>
|
|
150
|
+
{apiKey && <p style={{ color: "var(--vibe-success, CanvasText)" }}>Authenticated</p>}
|
|
151
|
+
</div>
|
|
152
|
+
);
|
|
153
|
+
}
|
|
154
|
+
`;M(j(D,"src","App.tsx"),me);let ve=`<!DOCTYPE html>
|
|
155
|
+
<html lang="en">
|
|
156
|
+
<head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>${P} UI</title></head>
|
|
157
|
+
<body><div id="root"></div><script type="module" src="/src/main.tsx"></script></body>
|
|
158
|
+
</html>`;if(M(j(D,"index.html"),ve),!d.json)l(`Created UI plugin ${V} at ${D}`);B.uiPluginName=V,B.uiPackageName=`@vibecontrols/${V}`,B.uiDir=D}}u(d,B)}catch(d){s(A(d))}})}function ae(c,R){re(c)}function Ke(c){return{name:"plugin-mgr",version:"2.2.0",description:"Plugin lifecycle management \u2014 install, remove, reload, catalog",capabilities:{storage:"rw",subprocess:!0,gateway:!0,audit:!0,telemetry:!0},tags:["backend","cli"],cliCommand:"plugin",apiPrefix:"/api/plugins",createRoutes:(R)=>te(R),onCliSetup:async(R,b)=>{ae(R,b)}}}export{Ke as createPlugin};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
var i=new Set(["static-api-key","plugin-state:external-config"]),o=["gateway-auth:"],s=[/(^|[-_:])secret($|[-_:])/i,/(^|[-_:])token($|[-_:])/i,/(^|[-_:])password($|[-_:])/i,/(^|[-_:])api[-_]?key($|[-_:])/i,/^static-api-key$/i,/^gateway-auth:/i,/^clientSecret$/i,/^plugin-state:external-config$/i],Mi="[redacted]";function vt(t){return i.has(t)||o.some((n)=>t.startsWith(n))}function r(t){return s.some((n)=>n.test(t))}function be(t,n){return r(t)&&n!==void 0?"[redacted]":n}function Di(t){return Object.fromEntries(Object.entries(t).map(([n,e])=>[n,be(n,e)]))}function k(t){if(Array.isArray(t))return t.map((n)=>k(n));if(!t||typeof t!=="object")return t;return Object.fromEntries(Object.entries(t).map(([n,e])=>[n,r(n)?"[redacted]":k(e)]))}
|
|
3
|
+
export{Mi,vt,be,Di,k};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{e}from"./index-
|
|
3
|
-
export{
|
|
2
|
+
import{e}from"./index-7wm4bqx5.js";import{b}from"./index-w4jqdhc2.js";var a=5000,i=new Map,d=1;function c(r){return`${r}#${d++}`}function wr(r){let n=Bun.spawn(r.cmd,{env:r.env,cwd:r.cwd,stdout:r.stdout??"pipe",stderr:r.stderr??"pipe",stdin:r.stdin??"pipe",...b().processGroupSpawnOpts()}),t={id:c(r.owner),owner:r.owner,pid:n.pid??null,startedAt:new Date().toISOString(),proc:n,meta:r.meta};return i.set(t.id,t),n.exited.finally(()=>{i.delete(t.id)}),t}function qr(r){return[...i.values()].filter((n)=>n.owner===r)}async function l(r,n){let t=b(),s=Date.now()+n;while(Date.now()<s){if(!t.isProcessAlive(r))return!0;await new Promise((o)=>setTimeout(o,100))}return!t.isProcessAlive(r)}async function p(r,n="SIGTERM"){let t=r.pid;if(t==null)return;let s=b();if(s.killProcessTree(t,n),await l(t,a))return;s.killProcessTree(t,"SIGKILL")}async function en(){let r=[...i.values()];if(r.length===0)return{reaped:0};return e().logger.info("subprocess",`Reaping ${r.length} tracked child process(es)`,{owners:[...new Set(r.map((n)=>n.owner))]}),await Promise.all(r.map((n)=>p(n))),i.clear(),{reaped:r.length}}
|
|
3
|
+
export{wr,qr,en};
|