@vibecontrols/agent 2026.1125.2 → 2026.1127.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. package/dist/agent-config-xwvsmn6b.js +2 -0
  2. package/dist/{agent-ready-tracker-mewxehg9.js → agent-ready-tracker-7ebr09d9.js} +1 -1
  3. package/dist/app-1dqn9qaw.js +2 -0
  4. package/dist/autostart.cmd-mdyv35dn.js +2 -0
  5. package/dist/bootstrap-workspace-1pt0bwy6.js +2 -0
  6. package/dist/bootstrap.service-gehm65tt.js +2 -0
  7. package/dist/bridge-client-9ax1cvj6.js +2 -0
  8. package/dist/bridge-commands-6dj7ewgx.js +2 -0
  9. package/dist/cli.js +2 -2
  10. package/dist/daemon-profile-fnhc7pcf.js +2 -0
  11. package/dist/{finalize-retry-worker-az74f2qv.js → finalize-retry-worker-c38km3mt.js} +1 -1
  12. package/dist/gateway-client-3zp6kkav.js +2 -0
  13. package/dist/{getMachineId-bsd-4w1wmcjv.js → getMachineId-bsd-qjqk66se.js} +1 -1
  14. package/dist/{getMachineId-darwin-kejwz8w5.js → getMachineId-darwin-tqhg8pqb.js} +1 -1
  15. package/dist/{getMachineId-linux-mpm53wat.js → getMachineId-linux-ygfapc26.js} +1 -1
  16. package/dist/{getMachineId-unsupported-54seyw5v.js → getMachineId-unsupported-87w3cred.js} +1 -1
  17. package/dist/{getMachineId-win-cva7ghz9.js → getMachineId-win-jrtkq63e.js} +1 -1
  18. package/dist/{index-0gmhd3hs.js → index-0rmmrrfh.js} +3 -3
  19. package/dist/{index-7f2k4g6q.js → index-12gb48hg.js} +4 -4
  20. package/dist/{index-7wben1jx.js → index-164mtd7z.js} +2 -2
  21. package/dist/{index-w0m3jm0s.js → index-1t74r13z.js} +2 -2
  22. package/dist/{index-thm1bzpj.js → index-2gj8zktr.js} +9 -9
  23. package/dist/{index-9xrhb68w.js → index-31ssvzw8.js} +2 -2
  24. package/dist/{index-652f9scs.js → index-4kf3nr14.js} +2 -2
  25. package/dist/{index-qe3xpt41.js → index-5s4mtrqb.js} +2 -2
  26. package/dist/{index-jmx5awkj.js → index-62vfxd90.js} +2 -2
  27. package/dist/{index-7gk1x74m.js → index-6nv5rdqh.js} +2 -2
  28. package/dist/{index-5ccmrpb5.js → index-6vsjepw2.js} +48 -48
  29. package/dist/{index-t6p4szqx.js → index-76vza24h.js} +3 -3
  30. package/dist/{index-76m37yd8.js → index-7bm1kptr.js} +3 -3
  31. package/dist/{index-0qjbnyg4.js → index-7wm4bqx5.js} +5 -5
  32. package/dist/{index-akk3rxnn.js → index-90gn0b6x.js} +3 -3
  33. package/dist/index-awj0w14r.js +11 -0
  34. package/dist/{index-2r6cmxxz.js → index-axkwyajz.js} +1 -1
  35. package/dist/index-bk17490n.js +3 -0
  36. package/dist/{index-fqz9n560.js → index-bp82hgag.js} +3 -3
  37. package/dist/{index-2vcxt38h.js → index-bpzk441p.js} +2 -2
  38. package/dist/{index-4z1y39jt.js → index-cn4p1ks0.js} +2 -2
  39. package/dist/{index-byerrz46.js → index-damc6cvc.js} +2 -2
  40. package/dist/{index-xtd0j8ve.js → index-dgbe8jm8.js} +2 -2
  41. package/dist/index-e5jdx9c1.js +3 -0
  42. package/dist/{index-tahaxp6n.js → index-ednz6yz2.js} +2 -2
  43. package/dist/{index-hsrt2v87.js → index-f5nmxa9e.js} +1 -1
  44. package/dist/{index-7s7ee1y9.js → index-he4hy261.js} +4 -4
  45. package/dist/{index-kwhx023z.js → index-j99tkngg.js} +10 -10
  46. package/dist/{index-4rasb3ph.js → index-k12bymz4.js} +9 -9
  47. package/dist/{index-qfxwk38p.js → index-p7fbnfwd.js} +2 -2
  48. package/dist/{index-jnxjjx2y.js → index-ppxayc0x.js} +2 -2
  49. package/dist/{index-er5k6qtr.js → index-qqnb0axh.js} +4 -4
  50. package/dist/index-qzwbctkv.js +16 -0
  51. package/dist/{index-a0vx2zyx.js → index-rae5bn1c.js} +2 -2
  52. package/dist/{index-8rbhm4g8.js → index-rhn7wy1p.js} +2 -2
  53. package/dist/index-sd5bt3g5.js +2 -0
  54. package/dist/{index-vtsd74g0.js → index-sq5j8bjn.js} +6 -6
  55. package/dist/{index-t5cfkz1e.js → index-v77bb0rm.js} +3 -3
  56. package/dist/{index-v16qz1fa.js → index-vhz1c474.js} +2 -2
  57. package/dist/{index-ywnfz6nm.js → index-wxb9dgwq.js} +1 -1
  58. package/dist/index-x4z055t8.js +3 -0
  59. package/dist/{index-haww9jpq.js → index-xetd52ad.js} +2 -2
  60. package/dist/index-xjnanwbf.js +116 -0
  61. package/dist/index-xp8g5akn.js +158 -0
  62. package/dist/{index-d59kp6zr.js → index-yfk0pb00.js} +2 -2
  63. package/dist/{index-cy97asyh.js → index-zcnfj1q4.js} +3 -3
  64. package/dist/{index-c4whjk5r.js → index-zn9snqbg.js} +2 -2
  65. package/dist/index.js +3 -3
  66. package/dist/interactive-52x9hv6c.js +2 -0
  67. package/dist/key.cmd-y415ngam.js +2 -0
  68. package/dist/log-shipper-02rqvtq8.js +2 -0
  69. package/dist/{path-utils-r4df8d3w.js → path-utils-qgkdkp5j.js} +1 -1
  70. package/dist/plugin-system-yxztgnyz.js +2 -0
  71. package/dist/prereqs-runner-w7z2dwa6.js +2 -0
  72. package/dist/profile-mount-ga5z1vx9.js +2 -0
  73. package/dist/prune-stale-shims-vejvb1rj.js +2 -0
  74. package/dist/register-core-pv4qe8zc.js +2 -0
  75. package/dist/secondary-profile-attach-h9kga6ss.js +2 -0
  76. package/dist/subprocess-p9bv9nqz.js +2 -0
  77. package/dist/telemetry-1d3t1mbf.js +2 -0
  78. package/dist/tunnel-bootstrap-esay39d5.js +2 -0
  79. package/package.json +1 -1
  80. package/dist/agent-config-v9d7gcz0.js +0 -2
  81. package/dist/app-xc9c1d71.js +0 -2
  82. package/dist/autostart.cmd-ahet7b1t.js +0 -2
  83. package/dist/bootstrap-workspace-3pb8qjsh.js +0 -2
  84. package/dist/bootstrap.service-9m7m1ksa.js +0 -2
  85. package/dist/bridge-client-xvqy3n15.js +0 -2
  86. package/dist/daemon-profile-sg8fp50z.js +0 -2
  87. package/dist/gateway-client-ermpz52n.js +0 -2
  88. package/dist/index-5021rk8n.js +0 -3
  89. package/dist/index-b3v08awy.js +0 -3
  90. package/dist/index-mmx2kp76.js +0 -16
  91. package/dist/index-ss5gez2p.js +0 -2
  92. package/dist/index-tts92sdm.js +0 -5
  93. package/dist/index-x83tcr8f.js +0 -158
  94. package/dist/index-zcmhy3jv.js +0 -116
  95. package/dist/interactive-vbz68zh5.js +0 -2
  96. package/dist/key.cmd-f6rjvjy8.js +0 -2
  97. package/dist/log-shipper-0erbwn0q.js +0 -2
  98. package/dist/plugin-system-byzwda4c.js +0 -2
  99. package/dist/prereqs-runner-gca0bytz.js +0 -2
  100. package/dist/profile-mount-s4mc1x18.js +0 -2
  101. package/dist/prune-stale-shims-4nqtv0xt.js +0 -2
  102. package/dist/register-core-ws2axmcf.js +0 -2
  103. package/dist/secondary-profile-attach-em1tq7vq.js +0 -2
  104. package/dist/subprocess-4gg77skg.js +0 -2
  105. package/dist/telemetry-nmtywcba.js +0 -2
  106. 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),wt(this.apiKeyHash,n)}hasKey(){return this.cryptoKey!==null}getCryptoKey(){return this.cryptoKey}shutdown(){this.cryptoKey=null,this.apiKeyHash=null}}function wt(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 xt,statSync as Et,copyFileSync as Lt,truncateSync as At,renameSync as Pt,unlinkSync as kt,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 vt}from"async_hooks";var j=new vt,bt=/^[A-Za-z0-9._:-]{8,128}$/;function ri(){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 Ki(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 bt.test(n)?n:void 0}function Qi(t){j.enterWith(t)}function St(){return j.getStore()?.requestId}function Rt(){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=Rt(),!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 ji=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=St(),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}
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),ji.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(Et(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))kt(n);Pt(r,n)}}if(h(this.logFile))Lt(this.logFile,`${this.logFile}.1`),At(this.logFile,0)}catch{}}ensureLogDir(){if(!h(this.logDir))xt(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 Ht(t){let r=t.trim().toLowerCase();if(!r)return;_.add(r.startsWith(".")?r:`.${r}`)}function zt(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 ii(t){if(!t)return null;let r=t.trim().replace(/\/+$/,"");return zt(r)?r:null}function Vt(t){if(!t)return null;let r=ii(t);if(r)return r;let n=process.env.AGENT_TUNNEL_URL;if(n&&t.trim().replace(/\/+$/,"")===n.trim().replace(/\/+$/,""))return It(t);return null}var Kt=new Set([".trycloudflare.com"]);function jt(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 Kt)if(n.endsWith(i))return!0;return!1}catch{return!1}}function fr(t){if(!t)return null;let r=t.trim().replace(/\/+$/,"");return jt(r)?r:null}function Qt(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 It(t){if(!t)return null;let r=t.trim().replace(/\/+$/,"");return Qt(r)?r:null}function Gi(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 Wt=/(?:\/(?:global|workspaces))?\/graphql$/i,Jt=1048576;function G(t){return t.trim().replace(/\/+$/,"").replace(Wt,"")}function Z(t,r){return`${G(t)}/${r}/graphql`}function tt(t){return t instanceof Error?t.message:String(t)}async function Xt(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 ni{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!) {
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=St();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:`
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 Xt(i,Jt),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 Tt(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 ni;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-nmtywcba.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-s4mc1x18.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 ge}from"fs";import{homedir as fe}from"os";import{dirname as pe,join as nt,resolve as de}from"path";var m=new Map;async function ue(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 he="agents-registry";async function rt(t){return ue(he,t)}function me(){return de(process.env.VIBECONTROLS_HOME??nt(fe(),".boff","vibecontrols"))}var ot=2,ye="default";function st(){return nt(me(),"agents.json")}function we(){let t=st();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:ot,instances:[]};return t}function at(t){let r=st();ae(pe(r),{recursive:!0});let n=`${r}.${process.pid}.tmp`,i={...t,schemaVersion:ot};ge(n,`${JSON.stringify(i,null,2)}
21
- `,{encoding:"utf8",mode:384}),ce(n,r)}function Ct(){return x().instances}function $i(t){let r=x();at({...r,instances:t})}function Fe(){try{let r=x().defaultProfile;if(r&&typeof r==="string"&&r.length>0)return r}catch{}return ye}function Yt(t){if(!t||typeof t!=="string")throw Error("setDefaultProfile: name is required");let r=x();at({...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=Fe();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 si(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 it(t){let r=O(t),n=N.get(r);if(n)return n;return N.create({name:r,dataDir:Ae(C(),"agents",r)})}export{ri,Ki,Qi,St,ji,z,Ht,ii,Vt,fr,It,Gi,ni,T,ue,rt,Ct,$i,Fe,Yt,R,O,si,I,ne,ee,C,se,Tt,B,N,e,it};
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 pi(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 mi(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{pi,mi};
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};
@@ -0,0 +1,11 @@
1
+ // @bun
2
+ import{Jt,I,se,N,e}from"./index-7wm4bqx5.js";import{b}from"./index-w4jqdhc2.js";import{existsSync as m,mkdirSync as te,readdirSync as Qe,readFileSync as V,renameSync as Ze,realpathSync as re,rmSync as P,statSync as Xe,writeFileSync as ne}from"fs";import{homedir as et}from"os";import{dirname as k,isAbsolute as rt,join as p,relative as it,sep as oe}from"path";import{fileURLToPath as H}from"url";import{existsSync as ye,readFileSync as me}from"fs";import{dirname as L,join as ve}from"path";import{fileURLToPath as he}from"url";var Pe="@vibecontrols/agent",S;function Ae(){if(S)return S;try{let t=L(he(import.meta.url));for(let r=0;r<10&&t&&t!==L(t);r++){let i=ve(t,"package.json");if(ye(i))try{let n=JSON.parse(me(i,"utf8"));if(n.name===Pe&&typeof n.version==="string")return S=n.version,S}catch{}t=L(t)}}catch{}return S??"0.0.0"}function M(){let t=process.env.VIBECONTROLS_PLUGIN_CONTRACT_V2_ENFORCE;return t==="1"||t==="true"||t==="on"}var K={storage:"rw",secrets:"rw",gateway:!0,broadcast:!0,subprocess:!0,audit:!0,telemetry:!0,singletonOnly:!1,requiresIsolation:!1},j={storage:"none",secrets:"none",gateway:!1,broadcast:!1,subprocess:!1,audit:!1,telemetry:!1,singletonOnly:!1,requiresIsolation:!1};function q(){let t=process.env.VIBECONTROLS_STRICT_PLUGIN_CAPS;return t==="1"||t==="true"||t==="on"}function J(t,r,i,n,s=!1){return new Proxy(t,{get(a,o,l){if(o==="plugins"){if(!s)return;return Reflect.get(a,o,l)}if(o==="storage")return Se(a.storage,i.storage??"none",r,n);if(o==="broadcast"&&!i.broadcast)return w(r,"broadcast",n);if(o==="workspaceQuery"&&!i.gateway)return w(r,"workspaceQuery",n);if(o==="getAgentRecordId"&&!i.gateway)return w(r,"getAgentRecordId",n);if(o==="getWorkspaceId"&&!i.gateway)return w(r,"getWorkspaceId",n);if(o==="iframeBridge"&&!s){let g=Reflect.get(a,o,l);if(!g)return g;return{...g,getAgentApiKey:w(r,"iframeBridge.getAgentApiKey",n)}}if(o==="telemetry"){if(!i.telemetry)return;return Reflect.get(a,o,l)}return Reflect.get(a,o,l)}})}function Se(t,r,i,n){if(r==="rw")return t;return new Proxy(t,{get(s,a,o){let l=String(a),g=l==="set"||l==="delete"||l==="deleteAll";if(r==="none"||r==="read"&&g)return(...c)=>{throw n("plugin.capability.denied",{pluginName:i,surface:"storage",op:l,mode:r}),Error(`plugin '${i}' lacks storage:${g?"rw":"read"} capability (op=${l})`)};return Reflect.get(s,a,o)}})}function w(t,r,i){return(...n)=>{throw i("plugin.capability.denied",{pluginName:t,op:r}),Error(`plugin '${t}' lacks capability for ${r}`)}}import{Worker as we}from"worker_threads";import{fileURLToPath as be}from"url";import{randomUUID as Ee}from"crypto";function ke(){let t=be(import.meta.url),r=t.lastIndexOf("/"),i=r>=0?t.slice(0,r):t,n=`${i}/plugin-worker-runtime.ts`,s=`${i}/plugin-worker-runtime.js`;if(t.endsWith(".ts"))return n;return s}class _{worker;pending=new Map;spec;initPromise;terminated=!1;constructor(t){this.spec=t}async start(){if(this.initPromise)return this.initPromise;return this.initPromise=this.spawn(),this.initPromise}async spawn(){let t=this.spec.runtimeEntry??ke(),r=["PATH","HOME","USERPROFILE","TMPDIR","TMP","TEMP","LANG","LC_ALL","LC_CTYPE","TZ","SystemRoot","SystemDrive","ComSpec","PATHEXT","windir"],i={};for(let s of r){let a=process.env[s];if(typeof a==="string")i[s]=a}let n=new we(t,{env:i});this.worker=n,n.on("message",(s)=>this.onMessage(s)),n.on("error",(s)=>this.onWorkerError(s instanceof Error?s:Error(String(s)))),n.on("exit",(s)=>this.onWorkerExit(s)),await this.call("init",{modulePath:this.spec.modulePath,ctxStub:{name:this.spec.ctx.name,dataDir:this.spec.ctx.dataDir}})}async dispatch(t,r=[]){if(this.terminated)throw Error("PluginWorkerHost terminated");if(!this.worker)await this.start();return this.call("dispatch",{method:t,params:r})}call(t,r){if(!this.worker)return Promise.reject(Error("worker not spawned"));let i=Ee();return new Promise((n,s)=>{this.pending.set(i,{resolve:n,reject:s});try{this.worker?.postMessage({id:i,op:t,args:r})}catch(a){this.pending.delete(i),s(a instanceof Error?a:Error(String(a)))}})}onMessage(t){let r=this.pending.get(t.id);if(!r)return;if(this.pending.delete(t.id),t.ok)r.resolve(t.result);else{let i=Error(t.error?.message??"worker error");if(t.error?.stack)i.stack=t.error.stack;r.reject(i)}}onWorkerError(t){for(let[,r]of this.pending)r.reject(t);this.pending.clear()}onWorkerExit(t){if(this.pending.size>0){let r=Error(`worker exited (code=${t}) with pending calls`);for(let[,i]of this.pending)i.reject(r);this.pending.clear()}this.terminated=!0}async terminate(){if(this.terminated=!0,!this.worker)return;try{await this.worker.terminate()}catch{}this.worker=void 0}}var Ie=[{packageName:"@vibecontrols/vibe-plugin-storage",pluginName:"storage",label:"Storage facade",description:"Storage provider registry \u2014 owns AgentDatabase contract. Bundled with the agent; the storage meta lazy-loads the configured provider by name.",category:"storage",trusted:!0,isCore:!0,isDefault:!0,isCritical:!0,removable:!1,integrity:"sha512-E0agrBuSwO7R5z7dBA6Jb0Mq5zibhkFzvEh0lcb4N+byt25yStrDcsJqJ3bJpVdavw/OkAjB+MAC06zkTtHraQ=="},...["agent","task","config","git","plugin-mgr","log"].map((t)=>({packageName:`@vibecontrols/vibe-plugin-${t}`,pluginName:t,label:`${t} (built-in)`,description:`Built-in ${t} plugin bundled with the agent.`,category:"core",trusted:!0,isCore:!0,removable:!1}))],Re=[{packageName:"@vibecontrols/vibe-plugin-tunnel",pluginName:"tunnel",label:"Tunnel manager",description:"Owns TunnelProvider interface. Routes to a registered tunnel provider.",category:"tunnel",trusted:!0,isDefault:!0,isCritical:!0,cliCommand:"tunnel",apiPrefix:"/api/tunnel",integrity:"sha512-FFqJjvPNCAYZwMjOKt1vHiBuzd+6W9sYI6vZqls7kr3Za+m++tIueT9OV2DlpAJT8XU+fidrgsWgQi8AcjPHWQ=="},{packageName:"@vibecontrols/vibe-plugin-session-manager",pluginName:"session-manager",label:"Session manager",description:"Owns SessionProvider interface. Routes to a registered session backend.",category:"session",trusted:!0,isCore:!0,isDefault:!0,isCritical:!0,cliCommand:"session",apiPrefix:"/api/sessions",integrity:"sha512-1841STCBKRDc0h0BFgcZ3ZJydThKUkHKtDdnC2YMZOiSYVB4N/+7fJQhyMSq3bc6zj/FO7jBne9Gmg+PLoXiQA=="},{packageName:"@vibecontrols/vibe-plugin-ai",pluginName:"ai",label:"AI orchestration",description:"Owns AIAgentProvider interface. Prompts, contexts, sessions, dispatch, logs.",category:"ai",trusted:!0,isDefault:!0,isCritical:!0,cliCommand:"ai",apiPrefix:"/api/ai",integrity:"sha512-mIkzkzMDU38ILFa2lRsjeaJqAidtlUBWoQ3KaFxkpG88AHWUtcA6Vha/wZQ5Ns16h0g4vRKxtbOLfFSTEgRerA=="},{packageName:"@vibecontrols/vibe-plugin-plan",pluginName:"plan",label:"Plan orchestration",description:"Owns PlanProvider interface. Routes plan sessions to a registered provider.",category:"plan",trusted:!0,isDefault:!1,cliCommand:"plan",apiPrefix:"/api/plan",integrity:"sha512-SSCFLFkmAhHesLYgETeEyAZs2Gu8tDEaMMuJtMMKG5eKGQIXYJaJZnQBuXP/vKOAlLd//l8es5hPqhmiNSi4Gw=="},{packageName:"@vibecontrols/vibe-plugin-gitops",pluginName:"gitops",label:"GitOps orchestrator",description:"Owns GitOpsProvider interface. Routes repo / PR / CI / security queries to a registered provider.",category:"gitops",trusted:!0,isDefault:!1,cliCommand:"gitops",apiPrefix:"/api/gitops",integrity:"sha512-KzoSmBDgQ5mbSFxAuIyIBnC/HKwYhtXluGp06DvzQmwqOQ4vEC72PuSiVx3doWrt+Z6fZ6i6gxNzmYNpdhPLXA=="},{packageName:"@vibecontrols/vibe-plugin-security",pluginName:"security",label:"Security lifecycle",description:"Security lifecycle orchestrator \u2014 owns /api/security and dispatches to per-stage providers.",category:"security",trusted:!0,isDefault:!1,cliCommand:"security",apiPrefix:"/api/security",integrity:"sha512-K6w3tC7qnCotvnNWWdmHnjqGgCNJoPNMs8gCwWFbcNI5MmbIrUQfFQdcjwGudwryvN2+TrX12MhfhWz4p1qcMA=="},{packageName:"@vibecontrols/vibe-plugin-desk",pluginName:"desk",label:"Steward desk",description:"Owns the desk provider routing. Lets a BotManor Steward use this machine's browser or desktop, with remote control off until the owner turns it on.",category:"desk",trusted:!1,isDefault:!1,apiPrefix:"/api/desk",integrity:"sha512-iruslyu+ixyovPtAUIy5qujInhVFWNgBqJpmVX8S8xGJeS4/1D9SkxbIpF3cRhKfKAAqVtgoF7BngPJFMdcUFQ=="},{packageName:"@vibecontrols/vibe-plugin-desk-browser",pluginName:"desk-browser",label:"Steward browser desk",description:"A dedicated browser a BotManor Steward can drive through the desk API: screenshots, page snapshots, clicks, typing and guarded navigation. Needs the Steward desk plugin.",category:"desk",trusted:!1,isDefault:!1,integrity:"sha512-WVYFnDcT8jpzF1yl2DPwBa+fEpCRDt2sdfhn2S5Mb1+nrv74giQHHIt6u+kkdcSVhuBC+VHGCGqlVYBgOJUD/g=="}],$e=[{packageName:"@vibecontrols/vibe-plugin-tool-code-server",pluginName:"code-server",label:"Browser code editor",description:"Browser-based VS Code via code-server \u2014 open any Vibe in an in-browser editor.",category:"tool",trusted:!0,isDefault:!1,cliCommand:"code-server",apiPrefix:"/api/code-server"}],xe=[{packageName:"@vibecontrols/vibe-plugin-agent-backup",pluginName:"agent-backup",label:"Agent backup",description:"Backup and restore agent state.",category:"agent",trusted:!0,isDefault:!0,integrity:"sha512-KhN2Vaahtnl4IKRbaHKtlEbsuvW9dbgC2l4kkIXcme55DaSmLy5kYkiysnwyZdC4PRQu4NKM4GQLoW9hD86dRw=="}],ie=[...Ie,...Re,...$e,...xe],Y=[{key:"storage",label:"Storage",description:"Encrypted local state for the agent.",categories:["storage"],mandatory:!0,defaultSelected:!0},{key:"tunnel",label:"Tunnels",description:"Expose the agent for remote access + share links.",categories:["tunnel"],mandatory:!0,defaultSelected:!0},{key:"backup",label:"Backup",description:"Backup + restore agent state.",categories:["agent"],mandatory:!0,defaultSelected:!0},{key:"session",label:"Terminal sessions",description:"Long-lived terminal / AI agent sessions.",categories:["session"],mandatory:!1,defaultSelected:!0},{key:"editor",label:"Browser code editor",description:"Open any Vibe in an in-browser VS Code editor (code-server).",categories:["tool"],mandatory:!1,defaultSelected:!0},{key:"ai",label:"AI orchestration",description:"AI agent harnesses, prompts + dispatch.",categories:["ai"],mandatory:!1,defaultSelected:!0},{key:"plan",label:"Plan review",description:"Review / approve AI-proposed plans.",categories:["plan"],mandatory:!1,defaultSelected:!1},{key:"gitops",label:"GitOps",description:"Repo / PR / CI / security integration.",categories:["gitops"],mandatory:!1,defaultSelected:!1},{key:"security",label:"Security",description:"Security scanning lifecycle.",categories:["security"],mandatory:!1,defaultSelected:!1}],T=ie.filter((t)=>t.isCore&&t.category==="core").map((t)=>t.pluginName),z=ie.filter((t)=>t.isDefault===!0);function O(t){return z}function Ce(t,r){let i=r instanceof Set?r:new Set(r),n=new Set;for(let s of Y)if(s.mandatory||i.has(s.key))for(let a of s.categories)n.add(a);return ie.filter((s)=>n.has(s.category))}var Q=new Set(ie.filter((t)=>t.trusted).map((t)=>t.packageName));function Le(){let t=ie.filter((i)=>i.isCritical).flatMap((i)=>[i.packageName,i.pluginName]),r=process.env.VIBECONTROLS_CRITICAL_PLUGINS;if(r){let i=r.split(",").map((n)=>n.trim()).filter(Boolean);return new Set([...t,...i])}return new Set(t)}function Et(t){return Le().has(t)}var Bi=ie.filter((t)=>!t.isCore||t.category!=="core");function cr(t){return ie.find((r)=>r.packageName===t)}function Pi(t){return new Set}var _e=/^@vibecontrols\/vibe-plugin-desk(-[a-z0-9][a-z0-9-]*)?$/;function ur(t){return _e.test(t)||cr(t)?.category==="desk"}function kt(t){return t.startsWith("@vibecontrols/vibe-plugin-")||Q.has(t)}function D(t){let r=cr(t);if(r)return r.trusted;if(ur(t))return!1;return t.startsWith("@vibecontrols/vibe-plugin-")}function tt(t){return!D(t)}function C(t){return ur(t)||process.env.VIBECONTROLS_REQUIRE_PLUGIN_SIGNATURES==="1"}function Ur(t){let r=t.trim();if(!r)return;if(r.startsWith("@vibecontrols/"))return ie.find((n)=>n.packageName===r);if(r.startsWith("vibe-plugin-"))return ie.find((n)=>n.packageName===`@vibecontrols/${r}`);let i=ie.find((n)=>n.pluginName===r);if(i)return i;return ie.find((n)=>n.packageName===`@vibecontrols/vibe-plugin-${r}`)}function Ue(t){let r=t.trim();if(!r)return;let i=Ur(r);if(i)return i.packageName;if(r.startsWith("@vibecontrols/"))return r;if(r.startsWith("vibe-plugin-"))return`@vibecontrols/${r}`;return`@vibecontrols/vibe-plugin-${r}`}import{createHash as Te,createPublicKey as Ne,verify as Oe}from"crypto";import{lstatSync as Z,readFileSync as G,readdirSync as De}from"fs";import{join as A,relative as Ge,sep as Fe}from"path";var F="vibecontrols-plugin-signature/v1",E="vibe-plugin.sig.json",x={maxFiles:5000,maxTotalBytes:209715200,maxSignatureFileBytes:2097152};class ce extends Error{packageName;reason;constructor(t,r,i){super(`Refusing plugin ${t}: signature check failed (${r}): ${i}`);this.packageName=t;this.reason=r;this.name="PluginSignatureError"}}function Ve(t){let r=[F,t.package,t.version,t.keyId],i=Object.keys(t.files).sort((n,s)=>Buffer.compare(Buffer.from(n),Buffer.from(s)));for(let n of i)r.push(`${n} ${t.files[n]}`);return Buffer.from(`${r.join(`
3
+ `)}
4
+ `,"utf8")}function He(t){return`sha512-${Te("sha512").update(t).digest("base64")}`}function Be(t){let r=[],i=(n)=>{for(let s of De(n)){let a=A(n,s),o=Ge(t,a).split(Fe).join("/");if(o==="node_modules"||o===E)continue;let l=Z(a);if(l.isSymbolicLink())throw new ce(t,"FILE_UNSIGNED",`symbolic link ${o} is not allowed in a signed package`);if(l.isDirectory())i(a);else if(l.isFile())r.push(o);if(r.length>x.maxFiles)throw new ce(t,"PACKAGE_TOO_LARGE",`more than ${x.maxFiles} files`)}};return i(t),r.sort((n,s)=>Buffer.compare(Buffer.from(n),Buffer.from(s)))}function Me(t){return typeof t==="object"&&t!==null&&!Array.isArray(t)&&Object.values(t).every((r)=>typeof r==="string")}function Ke(t){let r;try{r=JSON.parse(t)}catch{return null}if(typeof r!=="object"||r===null)return null;let i=r;if(i.format!==F||typeof i.package!=="string"||typeof i.version!=="string"||typeof i.keyId!=="string"||typeof i.signature!=="string"||!Me(i.files))return null;for(let n of Object.keys(i.files))if(!n||n.startsWith("/")||n.split("/").some((s)=>s===".."||s==="")||n.includes("\\")||n.includes("\t")||n.includes(`
5
+ `))return null;return{format:F,package:i.package,version:i.version,keyId:i.keyId,files:i.files,signature:i.signature}}var f=(t,r)=>({ok:!1,reason:t,detail:r});function X(t,r,i){let n;try{let c=A(t,E),d=Z(c);if(!d.isFile())return f("SIGNATURE_MALFORMED","not a file");if(d.size>x.maxSignatureFileBytes)return f("SIGNATURE_MALFORMED","signature file is too large");n=G(c,"utf8")}catch{return f("SIGNATURE_MISSING",`${E} not found`)}let s=Ke(n);if(!s)return f("SIGNATURE_MALFORMED","not a v1 signature file");if(s.package!==r)return f("PACKAGE_MISMATCH",`signed for ${s.package}, not ${r}`);let a=i.find((c)=>c.keyId===s.keyId);if(!a)return f("UNKNOWN_KEY",`key ${s.keyId} is not trusted`);if(a.revoked)return f("KEY_REVOKED",`key ${s.keyId} is revoked`);let o=!1;try{o=Oe(null,Ve(s),Ne(a.publicKeyPem),Buffer.from(s.signature,"base64"))}catch{o=!1}if(!o)return f("BAD_SIGNATURE","the signature does not verify");let l;try{l=Be(t)}catch(c){if(c instanceof ce)return f(c.reason,c.message);return f("FILE_MISSING","the package directory cannot be read")}let g=new Set(Object.keys(s.files));for(let c of l)if(!g.has(c))return f("FILE_UNSIGNED",`${c} is not signed`);let u=0;for(let c of g){let d;try{d=G(A(t,...c.split("/")))}catch{return f("FILE_MISSING",`${c} is missing`)}if(u+=d.byteLength,u>x.maxTotalBytes)return f("PACKAGE_TOO_LARGE","package is too large to verify");if(He(d)!==s.files[c])return f("FILE_CHANGED",`${c} does not match its signature`)}try{let c=JSON.parse(G(A(t,"package.json"),"utf8"));if(c.name!==s.package||c.version!==s.version)return f("PACKAGE_MISMATCH","package.json name or version differs from the signature")}catch{return f("FILE_MISSING","package.json is missing or invalid")}return{ok:!0,keyId:s.keyId,version:s.version,files:g.size}}import{existsSync as je,readFileSync as We}from"fs";import{join as qe}from"path";var U=[{keyId:"vc-plugins-2026-11",publicKeyPem:`-----BEGIN PUBLIC KEY-----
6
+ MCowBQYDK2VwAyEAgJhrjPVgiE+OUrorI1vgLpea80X2oky8vBGwNk8CbGs=
7
+ -----END PUBLIC KEY-----
8
+ `}];function Je(t){return null}function Ye(t=process.env){let r=Je(t);return r?[...U,r]:U}function ze(t){return je(qe(t,E))}function ee(t,r,i=Ye()){let n=C(t);if(!r){if(!n)return{status:"unsigned"};throw new ce(t,"SIGNATURE_MISSING","the package location could not be resolved for verification")}if(!n&&!ze(r))return{status:"unsigned"};let s=X(r,t,i);if(!s.ok)throw new ce(t,s.reason,s.detail);return{status:"verified",keyId:s.keyId,version:s.version}}class Lt extends Error{packageName;code="CONFIRMATION_REQUIRED";constructor(t){super(`Installing ${t} needs confirmation: it is not a trusted plugin. Confirm the install to continue.`);this.packageName=t;this.name="PluginConfirmationRequiredError"}}function ae(t){return ie.find((r)=>r.pluginName===t)}function nt(t){return ie.find((r)=>r.packageName===t)}function st(t,r){if(t.length!==r.length)return!1;let i=0;for(let n=0;n<t.length;n++)i|=t.charCodeAt(n)^r.charCodeAt(n);return i===0}async function ot(t,r,i){let n=nt(t),s=process.env.VIBECONTROLS_REQUIRE_PLUGIN_INTEGRITY==="1";if(!n?.integrity){if(s)throw Error(`Refusing to install ${t}: catalog has no pinned integrity and VIBECONTROLS_REQUIRE_PLUGIN_INTEGRITY=1`);return}let a=i,o;try{let g=`${r.replace(/\/+$/,"")}/${t.replace("/","%2F")}`,u=await fetch(g,{headers:{accept:"application/json"},signal:AbortSignal.timeout(20000)});if(!u.ok)throw Error(`registry packument fetch failed (HTTP ${u.status})`);let c=await u.json();if(a=a??c["dist-tags"]?.latest,!a)throw Error("could not resolve version from registry");if(o=c.versions?.[a]?.dist?.integrity,typeof o!=="string"||o.length===0)throw Error(`registry did not return dist.integrity for ${t}@${a}`)}catch(l){let g=l instanceof Error?l.message:String(l);throw Error(`Pre-install integrity gate refused ${t}: ${g}`,{cause:l})}if(!st(n.integrity,o)){let l=process.env.VIBECONTROLS_STRICT_PLUGIN_INTEGRITY==="1";if(D(t)&&!l){e().logger.warn("plugin-manager",`Integrity pin for ${t} is stale \u2014 catalog expects ${n.integrity}, the allowlisted registry has ${o} for ${a}. Proceeding (first-party package, registry allowlisted). Re-pin plugins.config.ts to silence this.`);return}throw Error(`Pre-install integrity gate refused ${t}: integrity mismatch for ${a}: expected ${n.integrity}, got ${o}`)}}var at=["https://registry.npmjs.org/","https://registry.npmjs.org"];function lt(){let t=process.env.VIBECONTROLS_REGISTRY_ALLOWLIST,r=[...at];if(typeof t==="string"&&t.length>0)for(let i of t.split(",").map((n)=>n.trim()).filter(Boolean))r.push(i);return r}function gt(t){let r=lt(),i;try{i=new URL(t).origin}catch{throw Error(`Invalid plugin registry URL: ${t}`)}for(let n of r)try{if(new URL(n).origin===i)return}catch{}throw Error(`Plugin registry '${t}' is not in the allow-list. Add it to VIBECONTROLS_REGISTRY_ALLOWLIST at daemon start.`)}var le="plugins.json",ut=/^@vibecontrols\/vibe-plugin-[a-z0-9][a-z0-9-]{0,80}$/,ge=/^[a-z0-9][a-z0-9-]{0,63}$/,ct=/^\/api\/[A-Za-z0-9][A-Za-z0-9/_-]{0,127}$/,dt=/^\/[A-Za-z0-9][A-Za-z0-9/_-]{0,159}$/,de=Symbol.for("vibecontrols.pluginPackageRoot");function lr(t){return t[de]}function fe(t){let r=t.trim();if(!ut.test(r))throw Error("Plugin package must be a @vibecontrols/vibe-plugin-* package name.");if(!kt(r)&&process.env.VIBECONTROLS_ALLOW_UNTRUSTED_PLUGINS!=="1")throw Error("Plugin package is not in the trusted VibeControls catalog.");return r}function pt(t,r){let i=it(t,r);return i===""||!!i&&!i.startsWith("..")&&!rt(i)}function pe(){return p(I(),"agent-plugins","node_modules")}function ft(){try{let t=pe();return m(t)&&Qe(t).length>0}catch{return!1}}function B(){let t=(process.env.VIBECONTROLS_PLUGIN_INSTALL_SCOPE??process.env.VIBECONTROLS_PLUGIN_INSTALL_MODE??"").toLowerCase();if(t==="local")return"local";if(t==="global")return"global";return ft()?"local":"global"}var ue="provider:default:";function yt(t){if(!t||typeof t!=="object")return!1;let r=t;return typeof r.packageName==="string"&&typeof r.version==="string"&&typeof r.pluginName==="string"&&typeof r.installedAt==="string"}class W{registry=[];loaded=new Map;corePlugins=new Map;db;forcedIsolation=new Set;workerHosts=new Map;lifecycleChain=Promise.resolve();withLifecycleLock(t){let i=this.lifecycleChain.then(t,t);return this.lifecycleChain=i.then(()=>{return},()=>{return}),i}async terminateWorkerHost(t){let r=this.workerHosts.get(t);if(!r)return;try{await r.terminate()}catch(i){e().logger.warn("plugin-manager",`Failed to terminate worker for '${t}': ${i instanceof Error?i.message:String(i)}`)}finally{this.workerHosts.delete(t)}}async terminateAllWorkerHosts(){let t=Array.from(this.workerHosts.keys());await Promise.all(t.map((r)=>this.terminateWorkerHost(r)))}constructor(t){this.db=t,this.ensureDir(),this.loadRegistry();let r=process.env.VIBE_ISOLATE_PLUGINS;if(typeof r==="string"&&r.length>0)this.setForcedIsolation(r.split(",").map((i)=>i.trim()).filter((i)=>i.length>0))}setForcedIsolation(t){this.forcedIsolation=new Set(t.filter((r)=>r.length>0))}shouldIsolate(t){if(this.forcedIsolation.has(t.name))return!0;return t.capabilities?.requiresIsolation===!0}getWorkerHost(t){return this.workerHosts.get(t)}registerWorkerHost(t,r){this.workerHosts.set(t,r)}auditSink=(t,r)=>{e().logger.warn("plugin-capability",t,r)};static resolveEffectiveCapabilities(t,r){if(t.capabilities)return t.capabilities;return r?K:j}hostServicesFor(t,r){return this.wrapHostServices(t,r)}wrapHostServices(t,r){let i=this.corePlugins.has(t.name),n=W.resolveEffectiveCapabilities(t,i),s=i||this.isTrustedLoadedPlugin(t);return J(r,t.name,n,this.auditSink,s)}routeDepsFor(t,r){if(this.corePlugins.has(t.name)||this.isTrustedLoadedPlugin(t))return r;let n=W.resolveEffectiveCapabilities(t,!1),s=r.hostServices?this.wrapHostServices(t,r.hostServices):void 0,a=this.auditSink,o=(l)=>{throw a("plugin.capability.denied",{plugin:t.name,capability:`routeDeps.${l}`}),Error(`Plugin '${t.name}' may not use routeDeps.${l}: untrusted plugins receive only capability-scoped host services`)};return new Proxy({},{get(l,g){if(g==="hostServices")return s;if(g==="broadcast")return n.broadcast?r.broadcast:()=>o("broadcast");if(typeof g==="string")return o(g);return}})}isTrustedLoadedPlugin(t){for(let[r,i]of this.loaded)if(i===t)return kt(r);return!1}acceptCapabilities(t,r){if(t.capabilities?.singletonOnly===!0&&N.size()>1)return e().logger.error("plugin-manager",`[plugin] '${t.name}' refused to load: singletonOnly capability incompatible with multi-profile daemon (profiles=${N.size()}, source=${r})`),!1;if(t.capabilities)return!0;if(q())return e().logger.error("plugin-manager",`[plugin] '${t.name}' refused to load: missing required capabilities declaration (source=${r})`),!1;if(r.startsWith("core:"))e().logger.warn("plugin-manager",`[plugin] '${t.name}' loaded without a capabilities declaration \u2014 granting full trust (core plugin). Declare capabilities explicitly. (source=${r})`);else e().logger.warn("plugin-manager",`[plugin] '${t.name}' loaded without a capabilities declaration \u2014 defaulting to EMPTY capability set (deny by default). External plugins MUST declare capabilities explicitly to access host services. (source=${r})`);return!0}ensureDir(){let t=I();if(!m(t))te(t,{recursive:!0})}loadRegistry(){let t=p(I(),le);try{if(m(t)){let r=V(t,"utf-8"),i=JSON.parse(r);if(Array.isArray(i)&&i.every(yt))this.registry=i.filter((n)=>{try{return fe(n.packageName),!0}catch(s){return e().logger.warn("plugin-manager","Ignoring invalid plugin entry",{packageName:n.packageName,error:String(s)}),!1}});else throw Error("plugins.json has an invalid schema")}}catch(r){e().logger.warn("plugin-manager","Failed to load plugin registry",{path:t,error:String(r)}),this.registry=[]}}saveRegistry(){this.ensureDir();let t=p(I(),le),r=`${t}.${process.pid}.tmp`;ne(r,`${JSON.stringify(this.registry,null,2)}
9
+ `,{encoding:"utf-8",mode:384}),Ze(r,t)}async loadCorePlugins(){let t=await Promise.allSettled([import("./index-2gj8zktr.js"),import("./index-76vza24h.js"),import("./index-f5nmxa9e.js"),import("./index-dgbe8jm8.js"),import("./index-xp8g5akn.js"),import("./index-6nv5rdqh.js")]),r=e();for(let i=0;i<t.length;i++){let n=t[i],s=T[i];if(n.status==="fulfilled"){let a=n.value,o;try{o=this.extractPlugin(a,`core:${s}`,r)}catch(l){e().logger.error("plugin-manager",`Core plugin '${s}' refused to load: ${l instanceof Error?l.message:String(l)}`);continue}if(o?.name){if(!this.acceptCapabilities(o,`core:${s}`))continue;this.corePlugins.set(o.name,o),e().logger.info("plugin-manager",`Core plugin loaded: ${o.name} v${o.version}`)}else e().logger.warn("plugin-manager",`Core plugin '${s}' did not export a valid createPlugin(ctx) factory`)}else e().logger.warn("plugin-manager",`Failed to load core plugin '${s}': ${n.reason}`)}e().logger.info("plugin-manager",`Core plugins loaded: ${this.corePlugins.size}/${T.length}`)}async resolveConcreteLatest(t,r){try{let n=`${r.replace(/\/+$/,"")}/${t.replace("/","%2F")}`,s=await fetch(n,{headers:{accept:"application/json"},signal:AbortSignal.timeout(20000)});if(!s.ok)return;let o=(await s.json())["dist-tags"]?.latest;if(typeof o==="string"&&/^\d+\.\d+\.\d+/.test(o))return o}catch{}return}async install(t,r={}){return this.withLifecycleLock(()=>this.installLocked(t,r))}async installLocked(t,r={}){if(t=fe(t),tt(t)&&!r.confirmUntrusted)throw new Lt(t);let i=r.version?.trim()||void 0,n=r.refreshLatest===!0||!!i;e().logger.info("plugin-manager",`Installing ${t}${n?"@latest (refresh)":""}...`);let s=se();if(gt(s),await ot(t,s,void 0),!n)try{await this.probeResolvable(t),e().logger.info("plugin-manager",`${t} already resolvable \u2014 skipping global install`);let d=await this.importPlugin(t),y={packageName:t,version:d.version,pluginName:d.name,installedAt:new Date().toISOString()};return this.registry=this.registry.filter((h)=>h.packageName!==t),this.registry.push(y),this.saveRegistry(),y}catch(d){if(d instanceof ce)throw d}let a=se(),o=B(),l=i?i:n?await this.resolveConcreteLatest(t,a):void 0,g=n?`${t}@${l??"latest"}`:t;try{if(o==="local"){let d=p(I(),"agent-plugins");if(!m(d))te(d,{recursive:!0});let y=p(d,"package.json");if(!m(y))ne(y,JSON.stringify({name:"vibecontrols-agent-plugins",private:!0,version:"0.0.0",dependencies:{}},null,2)+`
10
+ `);if(n&&l){let v=this.readInstalledVersion(p(d,"node_modules"),t);if(v&&v!==l){e().logger.info("plugin-manager",`Pre-clean ${t}: on-disk v${v} != target v${l} \u2014 removing stale copy + lockfile to force fresh resolve`);try{P(p(d,"node_modules",t),{recursive:!0,force:!0})}catch{}try{P(p(d,"bun.lock"),{force:!0}),P(p(d,"bun.lockb"),{force:!0})}catch{}}try{P(p(d,"bun.lock"),{force:!0}),P(p(d,"bun.lockb"),{force:!0})}catch{}}if(Bun.spawnSync(["bun","add",g,"--registry",a],{cwd:d,timeout:120000,stdout:"pipe",stderr:"pipe"}).exitCode!==0){let v=Bun.spawnSync(["npm","install",g,"--registry",a],{cwd:d,timeout:120000,stdout:"pipe",stderr:"pipe"});if(v.exitCode!==0)throw Error(v.stderr.toString().trim())}if(n&&l){let v=this.readInstalledVersion(p(d,"node_modules"),t);if(v!==l){e().logger.warn("plugin-manager",`bun kept ${t}@${v??"missing"} after requesting ${l}; retrying with npm after removing stale local copy`);try{P(p(d,"node_modules",t),{recursive:!0,force:!0}),P(p(d,"bun.lock"),{force:!0}),P(p(d,"bun.lockb"),{force:!0}),P(p(d,"package-lock.json"),{force:!0})}catch{}let R=Bun.spawnSync(["npm","install",g,"--registry",a,"--save-exact"],{cwd:d,timeout:120000,stdout:"pipe",stderr:"pipe"});if(R.exitCode!==0)throw Error(R.stderr.toString().trim())}}}else if(Bun.spawnSync(["bun","install","-g",g,"--registry",a],{timeout:120000,stdout:"pipe",stderr:"pipe"}).exitCode!==0){let y=Bun.spawnSync(["npm","install","-g",g,"--registry",a],{timeout:120000,stdout:"pipe",stderr:"pipe"});if(y.exitCode!==0)throw Error(y.stderr.toString().trim())}this.pluginRoots=void 0}catch(d){let y=d instanceof Error?d.message:String(d);if(n)try{await this.probeResolvable(t),e().logger.warn("plugin-manager",`Could not refresh ${t} to @latest (${y}); using the already-installed copy`),this.pluginRoots=void 0;let h=await this.importPlugin(t),v={packageName:t,version:h.version,pluginName:h.name,installedAt:new Date().toISOString()};return this.registry=this.registry.filter((R)=>R.packageName!==t),this.registry.push(v),this.saveRegistry(),v}catch(h){if(h instanceof ce)throw h}throw Error(`Failed to install ${t}: ${y}`,{cause:d})}let u=await this.importPlugin(t);if(n&&l&&u.version!==l)e().logger.warn("plugin-manager",`${t} refreshed to ${u.version} but registry latest is ${l} \u2014 a stale resolver/cache may still be in play`);if(this.corePlugins.has(u.name))e().logger.info("plugin-manager",`External plugin '${t}' overrides core plugin '${u.name}'`);let c={packageName:t,version:u.version,pluginName:u.name,installedAt:new Date().toISOString()};return this.registry=this.registry.filter((d)=>d.packageName!==t),this.registry.push(c),this.saveRegistry(),e().logger.info("plugin-manager",`Installed ${t}@${u.version} (${u.name})`),c}async ensureDefaultPlugins(t,r=[],i){let n=[],s=new Set(r),a=i?Ce(process.platform,i):O(process.platform);for(let o of a){if(s.has(o.packageName)||s.has(o.pluginName)){e().logger.info("plugin-manager",`${o.packageName} skipped by --skip-plugin`);continue}if(o.isCore&&o.category==="core"){e().logger.info("plugin-manager",`${o.packageName} is bundled with the agent \u2014 skipping auto-install`);continue}if(this.registry.some((g)=>g.packageName===o.packageName)){e().logger.info("plugin-manager",`${o.packageName} already installed, skipping auto-install`);continue}t?.(`Installing ${o.label} (${o.packageName})...`);try{await this.install(o.packageName,{refreshLatest:!0}),n.push(o),t?.(`Installed ${o.label} (${o.packageName})`)}catch(g){let u=g instanceof Error?g.message:String(g);e().logger.error("plugin-manager",`Failed to auto-install ${o.packageName}: ${u}`),t?.(`Failed to install ${o.label}: ${u}`)}}if(n.length>0)this.loadRegistry();return n}async installAndLoad(t,r,i){let n=await this.install(t),s=this.loaded.get(n.packageName);if(s){this.registerPluginProviders(s,i);let a=this.wrapHostServices(s,i);if(s.onServerStart)await s.onServerStart(r,a);if(s.onServerReady)await s.onServerReady(r,a)}return n}async update(t,r){return this.withLifecycleLock(()=>this.updateLocked(t,r))}async updateLocked(t,r){if(t=fe(t),e().logger.info("plugin-manager",`Updating ${t}${r?`@${r}`:""}...`),!this.registry.find((a)=>a.packageName===t))throw Error(`Plugin ${t} is not installed. Use 'install' first.`);let n=this.loaded.get(t);if(n)await this.terminateWorkerHost(n.name);this.loaded.delete(t);let s=await this.installLocked(t,{refreshLatest:!0,version:r,confirmUntrusted:!0});return e().logger.info("plugin-manager",`Updated ${t} to v${s.version}`),s}async updateAll(){let t=[];for(let r of[...this.registry])try{let i=await this.update(r.packageName);t.push({packageName:r.packageName,success:!0,version:i.version})}catch(i){t.push({packageName:r.packageName,success:!1,error:i instanceof Error?i.message:String(i)})}return t}async removeAll(t){let r=[],i=[...this.registry];for(let n of i)try{await this.remove(n.packageName,t),r.push({packageName:n.packageName,success:!0})}catch(s){r.push({packageName:n.packageName,success:!1,error:s instanceof Error?s.message:String(s)})}return r}async remove(t,r){return this.withLifecycleLock(()=>this.removeLocked(t,r))}async removeLocked(t,r){t=fe(t),e().logger.info("plugin-manager",`Removing ${t}...`);let i=this.loaded.get(t);if(i?.onServerStop)try{await i.onServerStop()}catch(a){e().logger.warn("plugin-manager",`Error stopping ${t}: ${a}`)}if(i)await this.terminateWorkerHost(i.name),r?.serviceRegistry.unregisterPlugin(i.name),this.loaded.delete(t);let n=this.registry.find((a)=>a.packageName===t);if(!i&&n)r?.serviceRegistry.unregisterPlugin(n.pluginName);let s=p(I(),"agent-plugins");try{if(m(p(s,"package.json")))Bun.spawnSync(["bun","remove",t],{cwd:s,timeout:60000,stdout:"pipe",stderr:"pipe"})}catch{}try{Bun.spawnSync(["bun","remove","-g",t],{timeout:60000,stdout:"pipe",stderr:"pipe"})}catch{try{Bun.spawnSync(["npm","uninstall","-g",t],{timeout:60000,stdout:"pipe",stderr:"pipe"})}catch{}}this.pluginRoots=void 0,this.registry=this.registry.filter((a)=>a.packageName!==t),this.saveRegistry(),e().logger.info("plugin-manager",`Removed ${t}`)}async loadAll(){this.loaded.clear();let t=[];for(let r of this.registry)try{fe(r.packageName),await this.importPlugin(r.packageName),e().logger.info("plugin-manager",`Loaded ${r.packageName} (${r.pluginName})`)}catch(i){let n=i.code;if(n==="ENOENT_PLUGIN")e().logger.info("plugin-manager",`${r.packageName} not present on disk \u2014 dropping from registry`),t.push(r.packageName);else if(n==="EPLUGIN_LEGACY_SINGLETON")e().logger.warn("plugin-manager",`Skipping ${r.packageName}: ${i instanceof Error?i.message:String(i)}`);else e().logger.warn("plugin-manager",`Failed to load ${r.packageName} \u2014 dropping from registry: ${i}`),t.push(r.packageName)}if(t.length>0){this.registry=this.registry.filter((r)=>!t.includes(r.packageName));try{this.saveRegistry()}catch(r){e().logger.warn("plugin-manager",`Failed to persist pruned registry: ${r}`)}}}async importPlugin(t){t=fe(t);let r={},i;{let s=this.getGlobalRoots(),a=!1,o=[],l=!0;for(let g of s){let u=p(g,t);if(!m(u)){o.push({path:u,error:"directory missing"});continue}l=!1,this.verifySignature(t,u);try{i=u,r=await import(u),a=!0;break}catch(c){o.push({path:u,error:c instanceof Error?c.message:String(c)})}try{let c=p(u,"package.json");if(!m(c)){o.push({path:c,error:"package.json missing"});continue}let d=JSON.parse(V(c,"utf8")),y=d.module??d.main??"./index.js",h=p(u,y);i=u,r=await import(h),a=!0;break}catch(c){o.push({path:u,error:c instanceof Error?c.message:String(c)})}}if(!a){i=this.resolvePackageRoot(t)??i,this.verifySignature(t,i);try{r=await import(t),a=!0}catch(g){o.push({path:`bare:${t}`,error:g instanceof Error?g.message:String(g)})}}if(!a){let g=o.map((c)=>`${c.path} (${c.error})`).join("; "),u=Error(`Cannot find module '${t}': explicit root attempts and bare import failed: ${g||"(no roots probed)"}`);if(l&&s.length>0)u.code="ENOENT_PLUGIN";throw u}}let n=this.extractPlugin(r,`external:${t}`,e());if(!n){if(this.hasLegacySingleton(r)){let s=Error(`${t} uses removed singleton contract; upgrade to createPlugin(ctx) factory (set VIBECONTROLS_PLUGIN_CONTRACT_V2_ENFORCE=1 to refuse strictly)`);throw s.code="EPLUGIN_LEGACY_SINGLETON",s}throw Error(`${t} does not export a valid createPlugin(ctx) factory`)}if(this.validatePluginExport(n,t,i),!this.acceptCapabilities(n,`external:${t}`))throw Error(`${t} refused to load: missing required capabilities declaration`);if(i)Object.defineProperty(n,de,{value:i,enumerable:!1,configurable:!1});if(this.logResolvedPlugin(t,n.version,i),this.loaded.set(t,n),this.shouldIsolate(n)){let s=e(),a=new _({modulePath:t,pluginName:n.name,ctx:{name:s.name,dataDir:s.dataDir}});try{await a.start(),this.workerHosts.set(n.name,a),s.logger.info("plugin-manager",`Isolated plugin '${n.name}' running in worker_threads`)}catch(o){try{await a.terminate()}catch{}this.loaded.delete(t);let l=o instanceof Error?o.message:String(o);throw s.logger.error("plugin-manager",`Isolation required for '${n.name}' but worker failed to start (${l}); refusing to load in host process`),Error(`Plugin '${n.name}' requires isolation but the worker failed to start: ${l}`,{cause:o})}}return n}verifySignature(t,r){try{let i=ee(t,r);if(i.status==="verified")this.auditSink("plugin.signature.verified",{packageName:t,keyId:i.keyId,version:i.version})}catch(i){throw this.auditSink("plugin.signature.refused",{packageName:t,reason:i instanceof Error?i.message:String(i)}),i}}async probeResolvable(t){if(!C(t)){await import(t);return}if(!(this.getGlobalRoots().some((i)=>m(p(i,t)))||this.resolvePackageRoot(t)!==void 0))throw Error(`Cannot find module '${t}'`)}resolvePackageRoot(t){let r=import.meta;if(typeof r.resolve!=="function")return;try{let i=r.resolve(t);if(!i.startsWith("file:"))return;let n=k(H(i));while(n&&n!==k(n)){if(m(p(n,"package.json")))return n;n=k(n)}}catch{return}return}validatePluginExport(t,r,i){if(!ge.test(t.name))throw Error(`${r} exports an invalid plugin name`);if(!t.version||t.version.length>64)throw Error(`${r} exports an invalid plugin version`);if(t.description&&t.description.length>500)throw Error(`${r} description is too long`);if(t.cliCommand&&!ge.test(t.cliCommand))throw Error(`${r} exports an invalid CLI command`);if(t.apiPrefix){if(!ct.test(t.apiPrefix)||t.apiPrefix.includes("..")||t.apiPrefix.includes("//"))throw Error(`${r} exports an invalid API prefix`)}if(t.publicPaths){if(t.publicPaths.length>20)throw Error(`${r} exports too many public paths`);for(let n of t.publicPaths)if(!dt.test(n)||n.includes("..")||n.includes("//"))throw Error(`${r} exports an invalid public path`)}if(t.dependencies&&t.dependencies.length>20)throw Error(`${r} exports too many dependencies`);if(t.tags){let n=new Set(["backend","frontend","cli","provider","adapter","integration"]);if(t.tags.length>n.size)throw Error(`${r} exports too many tags`);for(let s of t.tags)if(!n.has(s))throw Error(`${r} exports an invalid tag`)}if(t.ui){if(t.ui.title&&t.ui.title.length>120)throw Error(`${r} UI title is too long`);if(t.ui.staticDir){if(!i)throw Error(`${r} UI staticDir requires a package root`);let n=re(i),s=re(t.ui.staticDir);if(!Xe(s).isDirectory()||!pt(n,s))throw Error(`${r} UI staticDir must be inside the plugin package`)}}}pluginRoots;getPluginRoots(){if(this.pluginRoots!==void 0)return this.pluginRoots;let t=b(),r=[],i=new Set,n=(a)=>{if(!a||i.has(a)||!m(a))return;i.add(a),r.push(a)},s=process.env.VIBECONTROLS_PLUGIN_ROOTS;if(s)for(let a of s.split(t.pathSep).map((o)=>o.trim()).filter(Boolean))n(a);if(B()==="local")n(pe());else n(p(et(),".bun","install","global","node_modules")),n(t.npmGlobalRoot());if(this.isRunningFromSource())n(this.agentOwnNodeModules());return this.pluginRoots=r,r}isRunningFromSource(){try{let t=H(import.meta.url);return t.includes(`${oe}src${oe}`)||t.includes("/src/")}catch{return!1}}agentOwnNodeModules(){try{let t=k(H(import.meta.url)),r="";while(t&&t!==r){if(m(p(t,"package.json")))return p(t,"node_modules");r=t,t=k(t)}}catch{}return null}getGlobalRoots(){return this.getPluginRoots()}readInstalledVersion(t,r){try{let i=p(t,r,"package.json");if(!m(i))return;let n=JSON.parse(V(i,"utf8"));return typeof n.version==="string"?n.version:void 0}catch{return}}logResolvedPlugin(t,r,i){let n=e().logger;n.debug("plugin-manager",`Resolved ${t}@${r}`,{from:i??"(bare import)"});try{let s=[];for(let a of this.getPluginRoots()){let o=p(a,t);if(i&&o===i)continue;let l=this.readInstalledVersion(a,t);if(l&&l!==r)s.push(`${o} (v${l})`)}if(s.length>0)n.warn("plugin-manager",`${t}: loaded v${r} but stale duplicate copy(ies) exist at a different version \u2014 these shadow the active copy across reinstalls. Run \`vibe nuke --all\` to purge them.`,{loadedVersion:r,loadedFrom:i??"(bare import)",shadows:s})}catch{}}extractPlugin(t,r,i){let n=this.findFactory(t);if(n){let s=n(i);if(!this.isVibePlugin(s))throw Error(`plugin '${r}' createPlugin(ctx) factory returned an invalid VibePlugin`);return s}if(this.hasLegacySingleton(t)){let s=`plugin '${r}' uses removed singleton contract; upgrade to createPlugin(ctx) factory`;if(M())throw Error(s);e().logger.warn("plugin-manager",s);return}return}findFactory(t){if(typeof t.createPlugin==="function")return t.createPlugin;let r=t.default;if(r&&typeof r.createPlugin==="function")return r.createPlugin;return}hasLegacySingleton(t){if(this.isVibePlugin(t.vibePlugin))return!0;let r=t.default;if(r&&this.isVibePlugin(r.vibePlugin))return!0;if(this.isVibePlugin(r))return!0;return!1}isVibePlugin(t){if(!t||typeof t!=="object")return!1;let r=t;return typeof r.name==="string"&&typeof r.version==="string"}registerProviders(t,r){this.registerPluginProviders(t,r)}registerPluginProviders(t,r){let n=ae(t.name)?.isDefault===!0,s=(a)=>{if(!n)return;r.serviceRegistry.setProviderDefault(a,t.name)};if(t.providers?.tunnel){if(r.serviceRegistry.registerProvider("tunnel",t.providers.tunnel,t.name),s("tunnel"),t.tunnelDomainSuffixes)for(let a of t.tunnelDomainSuffixes)Jt(a)}if(t.providers?.session)r.serviceRegistry.registerProvider("session",t.providers.session,t.name),s("session");if(t.providers?.ai)r.serviceRegistry.registerProvider("ai",t.providers.ai,t.name),s("ai")}async dispatchCliSetup(t,r){for(let i of this.getAllPlugins())if(i.onCliSetup)try{await i.onCliSetup(t,this.wrapHostServices(i,r))}catch(n){e().logger.warn("plugin-manager",`onCliSetup failed for ${i.name}: ${n}`)}}async dispatchServerStart(t,r){let i=this.sortAllByDependencies(),n=[];for(let s of i){if(this.registerPluginProviders(s,r),s.onServerStart){let a=Date.now();try{await s.onServerStart(t,this.wrapHostServices(s,r)),(async()=>{try{let{telemetryService:o}=await import("./telemetry-1d3t1mbf.js");o.emit("plugin.activated",{plugin_name:s.name,version:s.version,duration_ms:Date.now()-a})}catch{}})()}catch(o){let l=o instanceof Error?o.message:String(o);e().logger.error("plugin-manager",`onServerStart failed for ${s.name}: ${l}`),(async()=>{try{let{telemetryService:u}=await import("./telemetry-1d3t1mbf.js");u.emit("plugin.failed",{plugin_name:s.name,error_class:o instanceof Error?o.constructor.name:"Error"})}catch{}})();let g=this.registry.find((u)=>u.pluginName===s.name);n.push({plugin:s.name,packageName:g?.packageName,error:l})}}this.registerPluginProviders(s,r)}return{failures:n}}async dispatchServerReady(t,r){for(let i of this.getAllPlugins())if(i.onServerReady)try{await i.onServerReady(t,this.wrapHostServices(i,r))}catch(n){e().logger.warn("plugin-manager",`onServerReady failed for ${i.name}: ${n}`)}}async provisionDefaultPrereqs(t,r,i,n){let s=process.env.VIBE_SKIP_PREREQ_INSTALL==="1",a=process.platform;e().logger.info("plugin-manager",`Provisioning default providers \u2014 agent build v${Ae()}, platform=${a}, pluginInstallScope=${B()}, skipInstall=${s}`);let o=(n?Ce(process.platform,n):O(process.platform)).map((u)=>u.packageName);if(!s)for(let u of o){if(this.loaded.has(u))continue;try{e().logger.info("plugin-manager",`Installing default meta ${u}`),await this.install(u,{refreshLatest:!0})}catch(c){e().logger.warn("plugin-manager",`Failed to install default meta ${u}: ${c}`)}}let l=this.buildHostPluginsFacade(t,r,i),g=this.attachPluginsFacade(r,l);for(let[u,c]of this.getAllLoaded()){if(!c.provisionProviders)continue;try{await c.provisionProviders(this.wrapHostServices(c,g)),e().logger.info("plugin-manager",`${u}: providers provisioned`)}catch(d){e().logger.warn("plugin-manager",`${u}: provisionProviders failed: ${d}`)}}}buildHostPluginsFacade(t,r,i){return{install:async(n,s)=>{await this.install(n,s??{})},loadProvider:async(n)=>{await this.loadAndStartProvider(n,t,r,i)},runPrereqs:async(n,s)=>{let{runPluginPrereqs:a}=await import("./prereqs-runner-w7z2dwa6.js"),o=this.loaded.get(n);if(!o)return{satisfied:!1};let l=await a(o,n,t,this.db??null,{skipInstall:s?.skipInstall===!0});return{satisfied:l.noProtocol?!0:l.satisfied}},electDefault:async(n,s)=>{await this.electProviderDefault(n,s,r)},isProviderRegistered:(n,s)=>r.serviceRegistry.listProvidersForType(n).some((a)=>a.pluginName===s),skipInstall:()=>process.env.VIBE_SKIP_PREREQ_INSTALL==="1"}}attachPluginsFacade(t,r){return new Proxy(t,{get(i,n,s){if(n==="plugins")return r;return Reflect.get(i,n,s)}})}async loadAndStartProvider(t,r,i,n){let s=this.loaded.get(t);if(!s)s=await this.importPlugin(t);if(s.createRoutes&&n?.(s))e().logger.info("plugin-manager",`${t}: mounted routes after provisioning`);this.registerPluginProviders(s,i);let a=this.wrapHostServices(s,i);if(s.onServerStart)await s.onServerStart(r,a);if(s.onServerReady)await s.onServerReady(r,a)}async electProviderDefault(t,r,i){if(!i.serviceRegistry.listProvidersForType(t).some((s)=>s.pluginName===r))return;try{let s=await this.getDefaultProvider(t);if(s&&s!==r)return;if(i.serviceRegistry.setProviderDefault(t,r),!s)await this.setDefaultProvider(t,r).catch(()=>{});e().logger.info("plugin-manager",`Elected platform-default '${t}' provider '${r}'`)}catch(s){e().logger.warn("plugin-manager",`Failed to elect default '${t}' provider '${r}': ${s}`)}}async dispatchServerStop(t){for(let r of this.getAllPlugins())if(r.onServerStop)try{await r.onServerStop(t)}catch(i){e().logger.warn("plugin-manager",`onServerStop failed for ${r.name}: ${i}`)}if(t?.reason==="shutdown")await this.terminateAllWorkerHosts()}async runPluginNuke(t,r,i){let n=t?this.loaded.has(t)?[[t,this.loaded.get(t)]]:[]:Array.from(this.loaded.entries()),s=[];for(let[a,o]of n){if(!o.onNuke)continue;try{let l=this.wrapHostServices(o,r),g=await o.onNuke(l,i);s.push({plugin:a,ok:!0,reaped:g?.reaped??[],notes:g?.notes??[]}),e().logger.info("plugin-manager",`onNuke ${i.dryRun?"(dry-run) ":""}completed for ${a}`,{reaped:g?.reaped??[]})}catch(l){let g=l instanceof Error?l.message:String(l);s.push({plugin:a,ok:!1,reaped:[],notes:[],error:g}),e().logger.warn("plugin-manager",`onNuke failed for ${a}: ${g}`)}}return{results:s}}async reloadAll(t,r){await this.dispatchServerStop({reason:"reload"}),await this.terminateAllWorkerHosts();for(let i of this.loaded.values())r.serviceRegistry.unregisterPlugin(i.name);this.loaded.clear(),this.corePlugins.clear(),this.loadRegistry(),await this.loadCorePlugins(),await this.loadAll(),await this.dispatchServerStart(t,r),await this.dispatchServerReady(t,r)}sortAllByDependencies(){let t=this.getAllPlugins(),r=new Map;for(let o of t)r.set(o.name,o);let i=new Set,n=new Set,s=[],a=(o)=>{if(i.has(o))return;if(n.has(o))throw Error(`Plugin dependency cycle detected at '${o}'`);let l=r.get(o);if(!l)return;if(n.add(o),l.dependencies)for(let g of l.dependencies){if(!r.has(g)){e().logger.warn("plugin-manager",`Plugin '${l.name}' depends on missing plugin '${g}'`);continue}a(g)}n.delete(o),i.add(o),s.push(l)};for(let o of t)a(o.name);return s}sortByDependencies(){let t=Array.from(this.loaded.entries()),r=new Map;for(let[a,o]of t)r.set(o.name,a);let i=new Set,n=[],s=(a)=>{if(i.has(a))return;i.add(a);let o=this.loaded.get(a);if(o?.dependencies)for(let g of o.dependencies){let u=r.get(g);if(u&&this.loaded.has(u))s(u)}let l=this.loaded.get(a);if(l)n.push([a,l])};for(let[a]of t)s(a);return n}getPluginByKey(t){for(let[,r]of this.loaded)if(r.name===t)return r;return this.corePlugins.get(t)}getAllPlugins(){let t=new Map;for(let[r,i]of this.corePlugins)t.set(r,i);for(let[,r]of this.loaded)t.set(r.name,r);return Array.from(t.values())}getAllPluginsByTag(t){return this.getAllPlugins().filter((r)=>r.tags?.includes(t)??!1)}resolvePluginChain(t){let r=new Set;for(let s of this.getAllPlugins())r.add(s.name);let i=[],n=-1;for(let s=0;s<t.length;s++){if(t[s].startsWith("-")){n=s;break}if(r.has(t[s]))i.push(t[s]);else{n=s;break}}if(n===-1)return{chain:i,command:"",args:[]};return{chain:i,command:t[n],args:t.slice(n+1)}}async getDefaultProvider(t){if(!this.db)return null;return await this.db.getConfig(`${ue}${t}`)??null}async setDefaultProvider(t,r){if(!this.db)throw Error("Cannot set default provider: PluginManager was constructed without a database reference");if(!this.getPluginByKey(r))throw Error(`Plugin '${r}' not found`);await this.db.setConfig(`${ue}${t}`,r),e().logger.info("plugin-manager",`Set default '${t}' provider to '${r}'`)}getPluginDetails(){let t=this.getCorePluginDetails(),r=this.getExternalPluginDetails(),i=new Map;for(let n of t)i.set(n.pluginName,n);for(let n of r)i.set(n.pluginName,n);return Array.from(i.values())}getCorePluginDetails(){let t=[];for(let[r,i]of this.corePlugins)t.push({packageName:`@vibecontrols/plugin-${r}`,pluginName:r,version:i.version,description:i.description,tags:i.tags,cliCommand:i.cliCommand,apiPrefix:i.apiPrefix,dependencies:i.dependencies,installedAt:"",loaded:!0,isCore:!0,hasUI:!!i.ui,uiUrl:i.ui?`/ui/${r}`:void 0,hasCliSetup:!!i.onCliSetup,hasServerStart:!!i.onServerStart,hasServerStop:!!i.onServerStop,hasServerReady:!!i.onServerReady,hasProviders:!!(i.providers?.tunnel||i.providers?.session||i.providers?.ai)});return t}getExternalPluginDetails(){return this.registry.map((t)=>{let r=this.loaded.get(t.packageName),i=ae(t.pluginName);return{packageName:t.packageName,pluginName:t.pluginName,version:r?.version??t.version,description:r?.description,tags:r?.tags,cliCommand:r?.cliCommand,apiPrefix:r?.apiPrefix,dependencies:r?.dependencies,installedAt:t.installedAt,loaded:!!r,isCore:i?.isCore===!0,hasUI:!!r?.ui,uiUrl:r?.ui?`/ui/${t.pluginName}`:void 0,hasCliSetup:!!r?.onCliSetup,hasServerStart:!!r?.onServerStart,hasServerStop:!!r?.onServerStop,hasServerReady:!!r?.onServerReady,hasProviders:!!(r?.providers?.tunnel||r?.providers?.session||r?.providers?.ai)}})}getRegistry(){return[...this.registry]}getLoaded(t){return this.loaded.get(t)}verifyLoadedSignature(t){let r=this.loaded.get(t);if(!r)return;this.verifySignature(t,lr(r))}async evictLoaded(t){let r=this.loaded.get(t);if(!r)return;await this.terminateWorkerHost(r.name),this.loaded.delete(t)}getAllLoaded(){return new Map(this.loaded)}isInstalled(t){return this.registry.some((r)=>r.packageName===t)}isLoaded(t){return this.loaded.has(t)}}
11
+ export{Ae,ie,Y,Ce,Et,Bi,cr,Pi,ur,kt,tt,Ur,Ue,ce,Lt,lr,fe,W};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{P,a,j}from"./index-a0vx2zyx.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(`
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,5 +1,5 @@
1
1
  // @bun
2
- import{Y,ye,Mt}from"./index-tts92sdm.js";import{Ht,It,T,R,I,ne,se,B,e}from"./index-0qjbnyg4.js";import{Z}from"./index-ywnfz6nm.js";import{D}from"./index-7s7ee1y9.js";import{b}from"./index-w4jqdhc2.js";import{Re}from"./index-byerrz46.js";import{existsSync as q,readFileSync as S,unlinkSync as ht,writeFileSync as U}from"fs";import{join as X}from"path";var Q=".consent.json";function He(t){try{let r=S(P(t),"utf8"),n=JSON.parse(r);if(Array.isArray(n.abilities)&&n.abilities.length>0)return new Set(n.abilities)}catch{}return null}function qt(t){try{let r=S(P(t),"utf8"),n=JSON.parse(r);if(Array.isArray(n.providers))return n.providers.filter((o)=>typeof o==="string")}catch{}return[]}function Ei(t){let r=new Set;for(let n of t.split(",").map((o)=>o.trim()).filter(Boolean)){let o=Mt(n);if(o)r.add(o)}return[...r]}function P(t){return X(t,Q)}function _i(t,r){let n=r??new Set(Y.filter((i)=>i.defaultSelected||i.mandatory).map((i)=>i.key)),o=t.skipPluginInstall?[]:ye(process.platform,n).filter((i)=>!t.skipPlugins.includes(i.packageName)&&!t.skipPlugins.includes(i.pluginName)).map((i)=>({packageName:i.packageName,pluginName:i.pluginName,reason:i.description}));return{tools:[],plugins:o}}async function er(){let t=new Set(Y.filter((n)=>n.defaultSelected||n.mandatory).map((n)=>n.key));for(let n of Y)if(n.mandatory)t.add(n.key);if(!(Boolean(process.stdin.isTTY)&&process.env.VIBE_AUTO_ACCEPT!=="1"))return t;try{let{interactiveCheckboxes:n}=await import("./interactive-vbz68zh5.js"),o=await n("Select the agent abilities to install",Y.map((i)=>({key:i.key,label:i.label,description:i.description,mandatory:i.mandatory})),t);if(o){for(let i of Y)if(i.mandatory)o.add(i.key);return o}return t}catch(n){process.stdout.write(`
2
+ import{Y,Ce,Ue}from"./index-awj0w14r.js";import{Jt,xt,T,R,I,ne,se,B,e}from"./index-7wm4bqx5.js";import{Z}from"./index-wxb9dgwq.js";import{D}from"./index-he4hy261.js";import{b}from"./index-w4jqdhc2.js";import{Fe}from"./index-damc6cvc.js";import{existsSync as q,readFileSync as S,unlinkSync as wt,writeFileSync as U}from"fs";import{join as X}from"path";var Q=".consent.json";function Ze(t){try{let r=S(P(t),"utf8"),n=JSON.parse(r);if(Array.isArray(n.abilities)&&n.abilities.length>0)return new Set(n.abilities)}catch{}return null}function Ot(t){try{let r=S(P(t),"utf8"),n=JSON.parse(r);if(Array.isArray(n.providers))return n.providers.filter((o)=>typeof o==="string")}catch{}return[]}function Ti(t){let r=new Set;for(let n of t.split(",").map((o)=>o.trim()).filter(Boolean)){let o=Ue(n);if(o)r.add(o)}return[...r]}function P(t){return X(t,Q)}function xi(t,r){let n=r??new Set(Y.filter((i)=>i.defaultSelected||i.mandatory).map((i)=>i.key)),o=t.skipPluginInstall?[]:Ce(process.platform,n).filter((i)=>!t.skipPlugins.includes(i.packageName)&&!t.skipPlugins.includes(i.pluginName)).map((i)=>({packageName:i.packageName,pluginName:i.pluginName,reason:i.description}));return{tools:[],plugins:o}}async function nr(){let t=new Set(Y.filter((n)=>n.defaultSelected||n.mandatory).map((n)=>n.key));for(let n of Y)if(n.mandatory)t.add(n.key);if(!(Boolean(process.stdin.isTTY)&&process.env.VIBE_AUTO_ACCEPT!=="1"))return t;try{let{interactiveCheckboxes:n}=await import("./interactive-52x9hv6c.js"),o=await n("Select the agent abilities to install",Y.map((i)=>({key:i.key,label:i.label,description:i.description,mandatory:i.mandatory})),t);if(o){for(let i of Y)if(i.mandatory)o.add(i.key);return o}return t}catch(n){process.stdout.write(`
3
3
  [vibe] Falling back to plain prompt \u2014 ${n instanceof Error?n.message:String(n)}
4
4
 
5
5
  `);let o=await ee("Select the agent abilities to install",Y.map((i)=>({key:i.key,label:i.label,description:i.description,mandatory:i.mandatory})),t);if(o){for(let i of Y)if(i.mandatory)o.add(i.key);return o}return t}}async function ee(t,r,n){let o=new Set(n);for(let s of r)if(s.mandatory)o.add(s.key);let i=()=>{process.stdout.write(`
@@ -13,5 +13,5 @@ Type numbers to toggle (e.g. '2 4'), 'a' = all, 'n' = none, '?' = help, Enter =
13
13
  `+` \u2022 Type 'a' to select all, 'n' to deselect everything except required rows.
14
14
  `+` \u2022 Press Enter on a blank line to confirm the current selection.
15
15
  `+` \u2022 Press Ctrl-C to cancel and accept the safe defaults (everything on).
16
- `);continue}if(s.toLowerCase()==="a"){for(let c of r)o.add(c.key);continue}if(s.toLowerCase()==="n"){o.clear();for(let c of r)if(c.mandatory)o.add(c.key);continue}let l=s.split(/[\s,]+/u).filter(Boolean);for(let c of l){let d=Number.parseInt(c,10);if(!Number.isFinite(d)||d<1||d>r.length)continue;let u=r[d-1];if(!u||u.mandatory)continue;if(o.has(u.key))o.delete(u.key);else o.add(u.key)}}}finally{process.stdin.pause()}}function yi(t){let r=new Set(Y.map((o)=>o.key)),n=new Set;for(let o of t.split(",").map((i)=>i.trim().toLowerCase()))if(r.has(o))n.add(o);for(let o of Y)if(o.mandatory)n.add(o.key);return n}function tr(){return new Set(Y.filter((t)=>t.defaultSelected||t.mandatory).map((t)=>t.key))}function Si(t,r,n,o,i){let a={acceptedAt:new Date().toISOString(),agentVersion:o,abilities:[...n],providers:i?[...i]:void 0,tools:r.tools.map((s)=>({name:s.name,reason:s.reason})),plugins:r.plugins.map((s)=>({packageName:s.packageName,reason:s.reason}))};U(P(t),JSON.stringify(a,null,2))}function ot(t,r){let n=oe(t),o={acceptedAt:n?.acceptedAt??new Date().toISOString(),agentVersion:r.agentVersion??n?.agentVersion,abilities:r.abilities?[...r.abilities]:n?.abilities,providers:r.providers?[...r.providers]:n?.providers,tools:n?.tools??[],plugins:n?.plugins??[]};U(P(t),JSON.stringify(o,null,2))}function oe(t){try{let r=P(t);if(!q(r))return null;return JSON.parse(S(r,"utf8"))}catch{return null}}import{createHash as ie}from"crypto";import{homedir as le,tmpdir as ce}from"os";import*as f from"path";import{spawn as E}from"child_process";import{createWriteStream as ue,existsSync as de,promises as h}from"fs";import{Readable as pe}from"stream";import{pipeline as ge}from"stream/promises";function fe(){let t=process.arch==="x64"?"x64":"arm64";return`${process.platform==="win32"?"win32":process.platform==="darwin"?"darwin":"linux"}-${t}`}function he(){return f.join(le(),".boff","vibecontrols","tools")}function O(t,r){let n=r??t;if(process.platform==="win32"&&!n.toLowerCase().endsWith(".exe"))return`${n}.exe`;return n}function we(t,r,n){return f.join(n??he(),t,O(t,r))}async function N(t,r){if(!r.versionMatcher)return!0;return new Promise((n)=>{let o=E(t,r.versionArgs??["--version"],{stdio:["ignore","pipe","pipe"]}),i="";o.stdout.on("data",(a)=>i+=a.toString()),o.stderr.on("data",(a)=>i+=a.toString()),o.on("close",()=>{try{n(new RegExp(r.versionMatcher).test(i))}catch{n(!1)}}),o.on("error",()=>n(!1))})}async function be(t){let r=t.platform??fe(),n=O(t.name,t.binaryName),o=we(t.name,t.binaryName,t.cacheRoot);if(de(o)&&await N(o,t))return o;try{let a=typeof Bun<"u"&&typeof Bun.which==="function"?Bun.which(t.binaryName??t.name,{PATH:process.env.PATH}):null;if(a&&await N(a,t))return t.log?.info?.(`[install] using PATH binary ${t.name} (${a})`),a}catch{}let i=t.downloads[r];if(!i)throw Error(`[install] no download manifest entry for ${t.name} on ${r}`);return t.log?.info?.(`[install] downloading ${t.name} for ${r}`),await h.mkdir(f.dirname(o),{recursive:!0}),await ke(i,o,n,t.name),t.log?.info?.(`[install] installed ${t.name} \u2192 ${o}`),o}async function ke(t,r,n,o){f.dirname(r);let i=f.join(ce(),`vibe-install-${o}-${process.pid}`);await h.mkdir(i,{recursive:!0});let a=f.join(i,"artifact");try{let s=await fetch(t.url,{redirect:"follow"});if(!s.ok)throw Error(`download failed (${s.status}) for ${t.url}`);if(!s.body)throw Error(`empty response body for ${t.url}`);if(await ge(pe.fromWeb(s.body),ue(a)),t.sha256){let c=ie("sha256").update(await h.readFile(a)).digest("hex");if(c!==t.sha256)throw Error(`sha256 mismatch for ${o}: expected ${t.sha256}, got ${c}`)}let l=t.archive??(t.url.endsWith(".tar.gz")||t.url.endsWith(".tgz")?"tar.gz":t.url.endsWith(".zip")?"zip":"raw");if(l==="raw")await h.copyFile(a,r);else{if(l==="tar.gz")await x("tar",["-xzf",a,"-C",i]);else await Pe(a,i);let c=t.binaryWithinArchive??n;await h.copyFile(f.join(i,c),r)}if(process.platform!=="win32")await h.chmod(r,493)}finally{await h.rm(i,{recursive:!0,force:!0})}}async function Pe(t,r){try{await x("unzip",["-q","-o",t,"-d",r]);return}catch(n){if(process.platform!=="win32")throw n;await x("tar",["-xf",t,"-C",r])}}async function x(t,r){return new Promise((n,o)=>{let i=E(t,r,{stdio:["ignore","ignore","pipe"]}),a="";i.stderr.on("data",(s)=>a+=s.toString()),i.on("close",(s)=>s===0?n():o(Error(`${t} exit ${s}: ${a}`))),i.on("error",o)})}var k="https://github.com/cloudflare/cloudflared/releases/latest/download",ve={"linux-x64":{url:`${k}/cloudflared-linux-amd64`,archive:"raw"},"linux-arm64":{url:`${k}/cloudflared-linux-arm64`,archive:"raw"},"darwin-x64":{url:`${k}/cloudflared-darwin-amd64.tgz`,archive:"tar.gz",binaryWithinArchive:"cloudflared"},"darwin-arm64":{url:`${k}/cloudflared-darwin-arm64.tgz`,archive:"tar.gz",binaryWithinArchive:"cloudflared"},"win32-x64":{url:`${k}/cloudflared-windows-amd64.exe`,archive:"raw"},"win32-arm64":{url:`${k}/cloudflared-windows-arm64.exe`,archive:"raw"}},Se=/(https:\/\/(?!api\.)[a-zA-Z0-9-]+\.trycloudflare\.com)/;async function L(t,r){let n=r?.log??{},o;try{o=await be({name:"cloudflared",downloads:ve,versionMatcher:"cloudflared version",log:n})}catch(s){return n.warn?.(`quick-tunnel: could not obtain cloudflared: ${String(s)}`),null}let i;try{i=E(o,["tunnel","--url",`http://127.0.0.1:${t}`,"--no-autoupdate"],{stdio:["ignore","pipe","pipe"]})}catch(s){return n.warn?.(`quick-tunnel: failed to spawn cloudflared: ${String(s)}`),null}let a=await new Promise((s)=>{let l=!1,c=(g)=>{if(l)return;l=!0,s(g)},d=setTimeout(()=>{n.warn?.("quick-tunnel: cloudflared did not advertise a URL in time"),c(null)},r?.timeoutMs??30000),u=(g)=>{let p=g.toString("utf8").match(Se);if(p)clearTimeout(d),c(p[0])};i.stdout?.on("data",u),i.stderr?.on("data",u),i.on("error",(g)=>{clearTimeout(d),n.warn?.(`quick-tunnel: cloudflared failed to spawn: ${String(g)}`),c(null)}),i.on("exit",(g)=>{clearTimeout(d),n.warn?.(`quick-tunnel: cloudflared exited (code=${g})`),c(null)})});if(!a)return null;return{url:a,child:i}}import{existsSync as M,mkdirSync as xe,readFileSync as $e,writeFileSync as Te,unlinkSync as Ee}from"fs";import{dirname as Ae,join as F}from"path";import{readdirSync as Ce}from"fs";function A(t){return F(t??I(),"tunnel.state.json")}function j(t,r){let n=A(r);try{xe(Ae(n),{recursive:!0}),Te(n,JSON.stringify(t,null,2),"utf8")}catch(o){e().logger.warn("tunnel-state","Failed to persist tunnel state",{error:String(o)})}}function te(t){let r=A(t);if(!M(r))return null;try{let n=$e(r,"utf8"),o=JSON.parse(n);if(typeof o.pid!=="number")return null;return o}catch(n){return e().logger.warn("tunnel-state","Failed to read tunnel state",{error:String(n)}),null}}function re(t){let r=A(t);if(!M(r))return;try{Ee(r)}catch{}}function ae(t){return b().isProcessAlive(t)}function Ii(t){let r=[];if(t?.allProfiles){let o;try{o=ne()}catch{return r}let i;try{i=Ce(o)}catch{return r}for(let a of i){let s=F(o,a),l=te(s);if(l)r.push({...l,alive:ae(l.pid),profileDir:s})}return r}let n=te();if(n)r.push({...n,alive:ae(n.pid),profileDir:I()});return r}function rr(t){return t.replace(/[^A-Za-z0-9_]/g,"_")}function v(){return(B()??e()).tunnel}async function Rr(t,r){let n=v();_e(t),Ie();let o=process.env.AGENT_TUNNEL_URL;if(o){let s=It(o);if(!s)return e().logger.warn("tunnel-bootstrap","Ignoring invalid AGENT_TUNNEL_URL"),null;n.url=s,n.externalUrl=!0,e().logger.info("tunnel-bootstrap",`Using AGENT_TUNNEL_URL=${s}`);try{Z.emit("tunnel.url_assigned",{provider:"external"})}catch{}return s}let i=r.port,a=await L(i,{log:{info:(s)=>e().logger.info("tunnel-bootstrap",s),warn:(s)=>e().logger.warn("tunnel-bootstrap",s)}});if(!a)return e().logger.warn("tunnel-bootstrap","No bootstrap tunnel \u2014 the agent will register once the tunnel provider starts post-config"),null;if(n.child=a.child,n.url=a.url,n.url){e().logger.info("tunnel-bootstrap",`Bootstrap tunnel ready: ${n.url}`);try{let c=new URL(n.url).hostname.split(".");if(c.length>=2)Ht("."+c.slice(-2).join("."))}catch{}try{Z.emit("tunnel.url_assigned",{provider:"bootstrap"})}catch{}let s=rr(R());if(process.env[`AGENT_TUNNEL_URL_${s}`]=n.url,n.child?.pid!==void 0)process.env[`AGENT_TUNNEL_PID_${s}`]=String(n.child.pid),j({pid:n.child.pid,url:n.url,startedAt:new Date().toISOString(),provider:"bootstrap",port:i,cmd:`cloudflared tunnel --url http://127.0.0.1:${i}`})}return n.url}function Ji(){let t=v();if(t.externalUrl)return!1;if(!t.child||t.child.killed)return!1;let r=t.child.pid;if(r===void 0)return!1;try{process.kill(r,0)}catch{return!1}return t.child=null,re(),e().logger.info("tunnel-bootstrap",`Handed over bootstrap tunnel (PID ${r}) to plugin \u2014 process kept alive`),!0}function ir(){let t=v();if(t.externalUrl){re();return}let r=t.child;if(t.child=null,re(),!r||r.killed)return;try{r.kill("SIGTERM"),e().logger.info("tunnel-bootstrap","Bootstrap tunnel stopped")}catch{}}function at(){return v().url}function Ie(){let t=te();if(!t)return;if(!ae(t.pid)){re();return}try{process.kill(t.pid,"SIGTERM"),e().logger.info("tunnel-bootstrap","Reaped orphan tunnel from prior run",{pid:t.pid,provider:t.provider})}catch{}let r=Date.now();while(Date.now()-r<2000&&ae(t.pid))Bun.sleepSync(50);if(ae(t.pid))try{process.kill(t.pid,"SIGKILL")}catch{}re()}function _e(t){let r={name:"bootstrap",async getActiveTunnelUrl(){return v().url}};t.registerProvider("tunnel",r,"bootstrap")}import{existsSync as Ue,mkdirSync as Oe,readFileSync as Be,renameSync as Me,writeFileSync as Fe}from"fs";import{dirname as je,join as ze}from"path";var De=["tunnel:read","session:list","session:share:read","session:share:write","plugin:list","plugin:install","plugin:remove","log:read","diagnostics:read","key:mint","mesh:forward","admin"];function z(t){return ze(t??I(),"agent-network.json")}function y(t){let r=z(t);if(!Ue(r))return{schemaVersion:1,peers:[]};let n=Be(r,"utf8");try{let o=JSON.parse(n);if(!o||!Array.isArray(o.peers))return{schemaVersion:1,peers:[]};return o}catch{return{schemaVersion:1,peers:[]}}}function C(t,r){let n=z(r);Oe(je(n),{recursive:!0});let o=`${n}.${process.pid}.tmp`;Fe(o,JSON.stringify(t,null,2),{mode:384}),Me(o,n)}function Ci(t){return y(t).peers}function Ve(t,r){return y(r).peers.find((n)=>n.id===t)??null}function H(t,r){if(r.workspaceId&&t.workspaceId&&t.workspaceId!==r.workspaceId)return!1;if(r.ownerUserId)return(t.ownerUserId??r.ownerUserId)===r.ownerUserId;return!0}function At(t,r){return y(r).peers.filter((n)=>H(n,t))}function Fr(t,r,n){return y(n).peers.find((o)=>o.agentRecordId===t&&H(o,r))??null}function Ye(t,r){let n=y(r),o=n.peers.findIndex((i)=>i.id===t.id);if(o>=0)n.peers[o]={...n.peers[o],...t};else n.peers.push(t);return C(n,r),t}function Ne(t,r,n){let o=y(n),i=o.peers.findIndex((a)=>a.id===t);if(i<0)return null;return o.peers[i]={...o.peers[i],...r},C(o,n),o.peers[i]}function Rt(t,r){let n=y(r),o=n.peers.length;if(n.peers=n.peers.filter((i)=>i.id!==t),n.peers.length===o)return!1;return C(n,r),!0}function Ze(t){let r=new Set(De);return[...t].filter((n)=>r.has(n)).map((n)=>n)}import{join as Ke}from"path";function w(t){let r=b();return r.which(t)??`${t}${r.executableSuffix}`}async function nr(){let t=["..","../..","../../.."];for(let r of t)try{let n=Ke(import.meta.dir,r,"package.json"),o=await Bun.file(n).json(),{name:i,version:a}=o;if(i&&a){let s=o.publishConfig;return{name:i,version:a,registry:s?.registry??se()}}}catch{}throw Error("package.json not found")}function Ge(t,r,n){try{let o=Bun.spawnSync([w("npm"),"view",`${t}@${r}`,"--json",`--registry=${n}`],{stdout:"pipe",stderr:"pipe"});if(o.exitCode!==0)return null;let i=JSON.parse(o.stdout.toString());return Array.isArray(i)?i[0]??null:i}catch{return null}}function V(t,r){let n=(a)=>a.replace(/^[\^~>=<v]+/,"").split(/[.+-]/).map((s)=>Number(s)||0),o=n(t),i=n(r);for(let a=0;a<Math.max(o.length,i.length);a++){let s=o[a]??0,l=i[a]??0;if(s!==l)return s-l}return 0}function qe(t,r){if(!t)return{ok:!0,message:""};let n=t.replace(/^[\^~]/,"").replace(/^>=?\s*/,"");if(V(r,n)>=0)return{ok:!0,message:`bun ${r} >= ${n}`};return{ok:!1,message:`requires bun ${t}, this process is bun ${r}`}}function Xe(t){try{let r=w("npm"),n=Bun.spawnSync([r,"root","-g"],{stdout:"pipe",stderr:"pipe"});if(n.exitCode!==0)return null;return`${n.stdout.toString().trim()}/${t}`}catch{return null}}function Qe(t){let r=Xe(t);if(!r)return{ok:!0,step:"(skipped, install root unknown)"};let n=`${r}/dist/cli.js`,o=(l,c,d)=>{try{let u=w("bun"),g=Bun.spawnSync([u,n,...l],{stdout:"pipe",stderr:"pipe",timeout:d});if(g.exitCode===0)return{ok:!0,step:c};return{ok:!1,step:c,detail:g.stderr.toString().slice(0,300)||`exit ${g.exitCode}`}}catch(u){return{ok:!1,step:c,detail:String(u)}}},i=o(["--version"],"vibe --version",1e4);if(!i.ok)return i;let a=o(["info"],"vibe info",15000);if(!a.ok)return a;let s=o(["plugin","list","--json"],"vibe plugin list",30000);if(!s.ok)return s;return{ok:!0,step:"all checks passed"}}async function et(t,r=60000){try{let n=new D,o=await n.getStatus(t);if(!o||o.status!=="running")return{kind:"not-running"};let i=`http://localhost:${o.port}`,a;try{a=await Re(i)}catch{}let s={};if(a)s["x-agent-api-key"]=a;let l=1000,c=Date.now();while(Date.now()-c<r){try{let d=await fetch(`${i}/api/profiles/${encodeURIComponent(t)}/stats/inflight`,{headers:s,signal:AbortSignal.timeout(2000)});if(d.ok){let u=await d.json();if(typeof u.inflight==="number"&&u.inflight===0){let g=o.config;return await n.restart(t,g),{kind:"restarted"}}}}catch{}await new Promise((d)=>setTimeout(d,l))}return{kind:"still-busy"}}catch(n){return{kind:"error",message:n instanceof Error?n.message:String(n)}}}async function Le(){let t;try{t=await nr()}catch(n){return{name:"@vibecontrols/agent",registry:se(),current:"unknown",latest:null,hasUpdate:!1,error:n instanceof Error?n.message:String(n)}}let r=null;try{let n=Bun.spawnSync([w("npm"),"view",t.name,"version",`--registry=${t.registry}`],{stdout:"pipe",stderr:"pipe"});if(n.exitCode===0)r=n.stdout.toString().trim()||null}catch{}if(!r)return{name:t.name,registry:t.registry,current:t.version,latest:null,hasUpdate:!1,error:"Could not reach the registry to check for updates"};return{name:t.name,registry:t.registry,current:t.version,latest:r,hasUpdate:V(r,t.version)>0}}async function Je(t={}){let r=t.onLog??(()=>{}),n=t.restart!==!1,o=t.name||"default",i;try{i=await nr()}catch(p){return{ok:!1,updated:!1,current:"unknown",previous:"unknown",latest:null,target:null,restart:"skipped",error:p instanceof Error?p.message:String(p)}}let a=i.version,s=t.targetVersion?.trim(),l=null;if(!s||s==="latest"){try{let p=Bun.spawnSync([w("npm"),"view",i.name,"version",`--registry=${i.registry}`],{stdout:"pipe",stderr:"pipe"});if(p.exitCode===0)l=p.stdout.toString().trim()||null}catch{}if(!l)return{ok:!1,updated:!1,current:a,previous:a,latest:null,target:null,restart:"skipped",error:"Could not check for updates (registry unreachable)"};s=l}if(s===a)return r(`Already on ${a}; nothing to do.`),{ok:!0,updated:!1,current:a,previous:a,latest:l??a,target:s,restart:"skipped"};let c,d=Ge(i.name,s,i.registry);if(d){let p=typeof Bun<"u"?Bun.version:"0.0.0",m=qe(d.engines?.bun,p);if(c=m.message,!m.ok&&!t.allowIncompatible)return{ok:!1,updated:!1,current:a,previous:a,latest:l,target:s,engineMessage:m.message,restart:"skipped",error:`Refusing to upgrade: ${m.message}. Pass allowIncompatible to override.`}}r(`Installing ${i.name}@${s}...`);try{let p=Bun.spawnSync([w("npm"),"install","-g",`${i.name}@${s}`,`--registry=${i.registry}`],{stdout:"pipe",stderr:"pipe"});if(p.exitCode!==0){let m=p.stderr.toString().slice(0,500);return{ok:!1,updated:!1,current:a,previous:a,latest:l,target:s,engineMessage:c,restart:"skipped",error:`npm install failed: ${m||`exit ${p.exitCode}`}`}}}catch(p){return{ok:!1,updated:!1,current:a,previous:a,latest:l,target:s,engineMessage:c,restart:"skipped",error:`npm install threw: ${p instanceof Error?p.message:String(p)}`}}let u=Qe(i.name);if(!u.ok){r(`Smoke test failed at "${u.step}" \u2014 rolling back to ${a}.`);let p=!1;try{p=Bun.spawnSync([w("npm"),"install","-g",`${i.name}@${a}`,`--registry=${i.registry}`],{stdout:"pipe",stderr:"pipe"}).exitCode===0}catch{}return{ok:!1,updated:!1,current:p?a:s,previous:a,latest:l,target:s,engineMessage:c,smoke:u,rolledBack:p,restart:"skipped",error:`Post-install smoke test failed at "${u.step}"${u.detail?`: ${u.detail}`:""}. ${p?"Rolled back.":"Rollback FAILED \u2014 reinstall manually."}`}}let g={kind:"skipped"};if(n)r(`Waiting for agent "${o}" to become idle before restart...`),g=await et(o,t.restartBudgetMs);return r(`Updated to ${s}.`),{ok:!0,updated:!0,current:s,previous:a,latest:l,target:s,engineMessage:c,smoke:u,rolledBack:!1,restart:g.kind,restartError:g.kind==="error"?g.message:void 0}}function tt(t){let r=/^(?:ssh:\/\/)?(?:([^@\s]+)@)?([^:/\s]+)(?::(\d+))?$/.exec(t.trim());if(!r)throw Error(`Could not parse SSH target: ${t}`);let n=Boolean(r[1]),o=Boolean(r[3]);if(!n&&!o&&!t.includes(":"))return{alias:r[2],host:r[2]};return{user:r[1],host:r[2],port:r[3]?Number(r[3]):void 0}}class K{mode="ssh";id;target;constructor(t){if(this.target=t,t.alias)this.id=`ssh://${t.alias}`;else{let r=t.user?`${t.user}@`:"",n=t.port?`:${t.port}`:"";this.id=`ssh://${r}${t.host}${n}`}}sshArgv(){let t=["ssh","-o","BatchMode=yes","-o","StrictHostKeyChecking=accept-new","-o","ServerAliveInterval=30"];if(this.target.identityFile)t.push("-i",this.target.identityFile);if(this.target.port)t.push("-p",String(this.target.port));return t.push(this.target.alias??(this.target.user?`${this.target.user}@${this.target.host}`:this.target.host)),t}async probe(){let t={},r=[["npm","command -v npm"],["node","command -v node"],["bun","command -v bun"],["vibe","command -v vibe"],["os","uname -s 2>/dev/null || echo unknown"],["arch","uname -m 2>/dev/null || echo unknown"]];for(let[n,o]of r){let i=await this.run(["sh","-c",o]),a=i.stdout.trim();if(i.code===0&&a)t[n]=a}return t}async run(t,r){let n=t.map(_).join(" "),o=[...this.sshArgv(),n],i=Bun.spawnSync(o,{stdout:"pipe",stderr:"pipe",timeout:r?.timeoutMs??600000});return{code:i.exitCode??1,stdout:i.stdout.toString(),stderr:i.stderr.toString()}}async upload(t,r,n){let o=[...this.sshArgv(),`cat > ${_(t)} && chmod ${(n??384).toString(8)} ${_(t)}`],i=Bun.spawn(o,{stdin:"pipe",stdout:"pipe",stderr:"pipe"}),a=i.stdin;a.write(typeof r==="string"?r:Buffer.from(r).toString("binary")),await a.end();let s=await i.exited;if(s!==0){let l=await new Response(i.stderr).text();throw Error(`upload to ${t} failed (exit ${s}): ${l}`)}}async close(){}}function _(t){if(/^[A-Za-z0-9._\-/=:]+$/.test(t))return t;return`'${t.replace(/'/g,"'\\''")}'`}class W{mode="local";id="local";async probe(){let t={},r=[["npm","command -v npm"],["node","command -v node"],["bun","command -v bun"],["vibe","command -v vibe"],["os","uname -s 2>/dev/null || echo unknown"],["arch","uname -m 2>/dev/null || echo unknown"]];for(let[n,o]of r){let i=await this.run(["sh","-c",o]),a=i.stdout.trim();if(i.code===0&&a)t[n]=a}return t}async run(t,r){let n=Bun.spawnSync(t,{stdout:"pipe",stderr:"pipe",timeout:r?.timeoutMs??600000});return{code:n.exitCode??1,stdout:n.stdout.toString(),stderr:n.stderr.toString()}}async upload(t,r,n){await Bun.write(t,r);try{let{chmodSync:o}=await import("fs");o(t,n??384)}catch{}}async close(){}}function We(t,r){let n=/^([a-z]+):\/\//.exec(t)?.[1];if(n==="local"||t.trim()==="local"||t.trim()==="localhost")return new W;if(!n||n==="ssh"){let o=tt(t);if(r?.identityFile)o.identityFile=r.identityFile;return new K(o)}throw Error(`Unsupported install transport scheme: ${n}://. Supported today: ssh:// (and bare host or ssh_config alias). Future: winrm://, ssm://, docker://, k8s://`)}var rt=/^[A-Za-z0-9._+-]+$/,nt=/^(?:@[a-z0-9][a-z0-9._-]{0,127}\/)?[a-z0-9][a-z0-9._-]{0,127}(?:@[A-Za-z0-9][A-Za-z0-9._+-]{0,127})?$/,it=/^\d+[smhdw]?$/,st=/^[a-z0-9:_-]{1,64}$/,pt=/[`$;&|<>'"\\]/,ft=/['"`$\s;|&<>()\\]/;function G(t){for(let r=0;r<t.length;r++){let n=t.charCodeAt(r);if(n<=31||n===127)return!0}return!1}function ct(t){if(!t||t.length>128||t.startsWith("-")||!rt.test(t))throw Error(`Invalid agent version: ${t}`);return t}function ut(t){if(!t||t.length>2048||G(t)||ft.test(t))throw Error(`Invalid registry URL: ${t}`);let r;try{r=new URL(t)}catch{throw Error(`Invalid registry URL: ${t}`)}if(r.protocol!=="http:"&&r.protocol!=="https:"||!r.hostname)throw Error(`Invalid registry URL: ${t}`);return t}function lt(t){let r=t.trim();if(!r||r.includes("..")||!nt.test(r))throw Error(`Invalid plugin package name: ${t}`);return r}function gt(t){let r=t.trim();if(!r||r.length>16||!it.test(r))throw Error(`Invalid --expires-in value: ${t}`);return r}function Or(t){let r=t.split(",").map((n)=>n.trim()).filter(Boolean);if(r.length===0)throw Error(`Invalid --permissions value: ${t}`);for(let n of r)if(!st.test(n))throw Error(`Invalid --permissions value: ${t}`);return r.join(",")}function dt(t){let r=t.trim();if(!r||r.length>128||r.startsWith("-")||G(r)||pt.test(r))throw Error(`Invalid --label value: ${t}`);return r}function Ft(t,r){let n=ut(t),o=ct(r);return["sh","-c",'export PATH="$HOME/.bun/bin:$PATH"; npm_config_registry="$1" bun install -g @vibecontrols/agent@"$2" --no-cache',"_",n,o]}function Ot(t){return["sh","-c",'export PATH="$HOME/.bun/bin:$PATH"; vibe plugin install "$1"',"_",lt(t)]}function Bt(t){let r=dt(t.label),n=Or(t.scope),o=t.expiresIn?gt(t.expiresIn):void 0,i=[];if(t.json)i.push("--json");if(t.emitDefaultKey)i.push("--emit-default-key");let a=i.length>0?`${i.join(" ")} `:"";if(o)return["sh","-c",`export PATH="$HOME/.bun/bin:$PATH"; vibe peer-bootstrap ${a}--label "$1" --scope "$2" --expires-in "$3" 2>/dev/null`,"_",r,n,o];return["sh","-c",`export PATH="$HOME/.bun/bin:$PATH"; vibe peer-bootstrap ${a}--label "$1" --scope "$2" 2>/dev/null`,"_",r,n]}async function J(t,r,n){let o=`${t.tunnelUrl.replace(/\/$/,"")}${r}`;try{let i=await fetch(o,{method:n.method??"GET",headers:{"x-agent-api-key":t.apiKey,"content-type":n.body?"application/json":"application/octet-stream"},body:n.body?JSON.stringify(n.body):void 0,signal:AbortSignal.timeout(n.timeoutMs??30000)});if(i.status===200||i.status===201||i.status===204){let s=await i.json().catch(()=>{return});return{ok:!0,status:i.status,data:s}}let a=await i.text().catch(()=>"");return{ok:!1,status:i.status,error:a}}catch(i){return{ok:!1,status:0,error:i instanceof Error?i.message:String(i)}}}async function me(t,r,n={}){let o=Ve(t);if(!o)return{ok:!1,status:0,error:`No peer with id ${t}`};let i=await J(o,r,n);if(i.ok)return Ne(o.id,{lastReachable:new Date().toISOString()}),i;if(!(i.status===401||i.status===0||i.status===502||i.status===503||i.status===504))return i;if(!o.agentRecordId||!T.isConfigured())return i;let s=null;try{s=await T.lookupPeerAgent(o.agentRecordId,n.operation??"peer-call")}catch(d){e().logger.warn("peer-client","Backend rotation lookup failed",{peerId:t,error:d instanceof Error?d.message:String(d)})}if(!s)return i;Ne(o.id,{tunnelUrl:s.tunnelUrl,apiKey:s.apiKey});let l={...o,tunnelUrl:s.tunnelUrl,apiKey:s.apiKey};return{...await J(l,r,n),rotated:!0}}
17
- export{He,qt,Ei,_i,er,yi,tr,Si,ot,te,re,ae,Ii,rr,Rr,Ji,ir,at,De,Ci,Ve,At,Fr,Ye,Ne,Rt,Ze,nr,Le,Je,We,ct,ut,lt,gt,Or,dt,Ft,Ot,Bt,me};
16
+ `);continue}if(s.toLowerCase()==="a"){for(let c of r)o.add(c.key);continue}if(s.toLowerCase()==="n"){o.clear();for(let c of r)if(c.mandatory)o.add(c.key);continue}let l=s.split(/[\s,]+/u).filter(Boolean);for(let c of l){let d=Number.parseInt(c,10);if(!Number.isFinite(d)||d<1||d>r.length)continue;let u=r[d-1];if(!u||u.mandatory)continue;if(o.has(u.key))o.delete(u.key);else o.add(u.key)}}}finally{process.stdin.pause()}}function bi(t){let r=new Set(Y.map((o)=>o.key)),n=new Set;for(let o of t.split(",").map((i)=>i.trim().toLowerCase()))if(r.has(o))n.add(o);for(let o of Y)if(o.mandatory)n.add(o.key);return n}function sr(){return new Set(Y.filter((t)=>t.defaultSelected||t.mandatory).map((t)=>t.key))}function wi(t,r,n,o,i){let a={acceptedAt:new Date().toISOString(),agentVersion:o,abilities:[...n],providers:i?[...i]:void 0,tools:r.tools.map((s)=>({name:s.name,reason:s.reason})),plugins:r.plugins.map((s)=>({packageName:s.packageName,reason:s.reason}))};U(P(t),JSON.stringify(a,null,2))}function ut(t,r){let n=oe(t),o={acceptedAt:n?.acceptedAt??new Date().toISOString(),agentVersion:r.agentVersion??n?.agentVersion,abilities:r.abilities?[...r.abilities]:n?.abilities,providers:r.providers?[...r.providers]:n?.providers,tools:n?.tools??[],plugins:n?.plugins??[]};U(P(t),JSON.stringify(o,null,2))}function oe(t){try{let r=P(t);if(!q(r))return null;return JSON.parse(S(r,"utf8"))}catch{return null}}import{createHash as ie}from"crypto";import{homedir as le,tmpdir as ce}from"os";import*as f from"path";import{spawn as E}from"child_process";import{createWriteStream as ue,existsSync as de,promises as h}from"fs";import{Readable as pe}from"stream";import{pipeline as ge}from"stream/promises";function fe(){let t=process.arch==="x64"?"x64":"arm64";return`${process.platform==="win32"?"win32":process.platform==="darwin"?"darwin":"linux"}-${t}`}function me(){return f.join(le(),".boff","vibecontrols","tools")}function O(t,r){let n=r??t;if(process.platform==="win32"&&!n.toLowerCase().endsWith(".exe"))return`${n}.exe`;return n}function he(t,r,n){return f.join(n??me(),t,O(t,r))}async function N(t,r){if(!r.versionMatcher)return!0;return new Promise((n)=>{let o=E(t,r.versionArgs??["--version"],{stdio:["ignore","pipe","pipe"]}),i="";o.stdout.on("data",(a)=>i+=a.toString()),o.stderr.on("data",(a)=>i+=a.toString()),o.on("close",()=>{try{n(new RegExp(r.versionMatcher).test(i))}catch{n(!1)}}),o.on("error",()=>n(!1))})}async function ye(t){let r=t.platform??fe(),n=O(t.name,t.binaryName),o=he(t.name,t.binaryName,t.cacheRoot);if(de(o)&&await N(o,t))return o;try{let a=typeof Bun<"u"&&typeof Bun.which==="function"?Bun.which(t.binaryName??t.name,{PATH:process.env.PATH}):null;if(a&&await N(a,t))return t.log?.info?.(`[install] using PATH binary ${t.name} (${a})`),a}catch{}let i=t.downloads[r];if(!i)throw Error(`[install] no download manifest entry for ${t.name} on ${r}`);return t.log?.info?.(`[install] downloading ${t.name} for ${r}`),await h.mkdir(f.dirname(o),{recursive:!0}),await we(i,o,n,t.name),t.log?.info?.(`[install] installed ${t.name} \u2192 ${o}`),o}async function we(t,r,n,o){f.dirname(r);let i=f.join(ce(),`vibe-install-${o}-${process.pid}`);await h.mkdir(i,{recursive:!0});let a=f.join(i,"artifact");try{let s=await fetch(t.url,{redirect:"follow"});if(!s.ok)throw Error(`download failed (${s.status}) for ${t.url}`);if(!s.body)throw Error(`empty response body for ${t.url}`);if(await ge(pe.fromWeb(s.body),ue(a)),t.sha256){let c=ie("sha256").update(await h.readFile(a)).digest("hex");if(c!==t.sha256)throw Error(`sha256 mismatch for ${o}: expected ${t.sha256}, got ${c}`)}let l=t.archive??(t.url.endsWith(".tar.gz")||t.url.endsWith(".tgz")?"tar.gz":t.url.endsWith(".zip")?"zip":"raw");if(l==="raw")await h.copyFile(a,r);else{if(l==="tar.gz")await x("tar",["-xzf",a,"-C",i]);else await be(a,i);let c=t.binaryWithinArchive??n;await h.copyFile(f.join(i,c),r)}if(process.platform!=="win32")await h.chmod(r,493)}finally{await h.rm(i,{recursive:!0,force:!0})}}async function be(t,r){try{await x("unzip",["-q","-o",t,"-d",r]);return}catch(n){if(process.platform!=="win32")throw n;await x("tar",["-xf",t,"-C",r])}}async function x(t,r){return new Promise((n,o)=>{let i=E(t,r,{stdio:["ignore","ignore","pipe"]}),a="";i.stderr.on("data",(s)=>a+=s.toString()),i.on("close",(s)=>s===0?n():o(Error(`${t} exit ${s}: ${a}`))),i.on("error",o)})}var k="https://github.com/cloudflare/cloudflared/releases/latest/download",Pe={"linux-x64":{url:`${k}/cloudflared-linux-amd64`,archive:"raw"},"linux-arm64":{url:`${k}/cloudflared-linux-arm64`,archive:"raw"},"darwin-x64":{url:`${k}/cloudflared-darwin-amd64.tgz`,archive:"tar.gz",binaryWithinArchive:"cloudflared"},"darwin-arm64":{url:`${k}/cloudflared-darwin-arm64.tgz`,archive:"tar.gz",binaryWithinArchive:"cloudflared"},"win32-x64":{url:`${k}/cloudflared-windows-amd64.exe`,archive:"raw"},"win32-arm64":{url:`${k}/cloudflared-windows-arm64.exe`,archive:"raw"}},ve=/(https:\/\/(?!api\.)[a-zA-Z0-9-]+\.trycloudflare\.com)/;async function L(t,r){let n=r?.log??{},o;try{o=await ye({name:"cloudflared",downloads:Pe,versionMatcher:"cloudflared version",log:n})}catch(s){return n.warn?.(`quick-tunnel: could not obtain cloudflared: ${String(s)}`),null}let i;try{i=E(o,["tunnel","--url",`http://127.0.0.1:${t}`,"--no-autoupdate"],{stdio:["ignore","pipe","pipe"]})}catch(s){return n.warn?.(`quick-tunnel: failed to spawn cloudflared: ${String(s)}`),null}let a=await new Promise((s)=>{let l=!1,c=(g)=>{if(l)return;l=!0,s(g)},d=setTimeout(()=>{n.warn?.("quick-tunnel: cloudflared did not advertise a URL in time"),c(null)},r?.timeoutMs??30000),u=(g)=>{let p=g.toString("utf8").match(ve);if(p)clearTimeout(d),c(p[0])};i.stdout?.on("data",u),i.stderr?.on("data",u),i.on("error",(g)=>{clearTimeout(d),n.warn?.(`quick-tunnel: cloudflared failed to spawn: ${String(g)}`),c(null)}),i.on("exit",(g)=>{clearTimeout(d),n.warn?.(`quick-tunnel: cloudflared exited (code=${g})`),c(null)})});if(!a)return null;return{url:a,child:i}}import{existsSync as M,mkdirSync as xe,readFileSync as $e,writeFileSync as Re,unlinkSync as Te}from"fs";import{dirname as Ee,join as F}from"path";import{readdirSync as Ae}from"fs";function A(t){return F(t??I(),"tunnel.state.json")}function j(t,r){let n=A(r);try{xe(Ee(n),{recursive:!0}),Re(n,JSON.stringify(t,null,2),"utf8")}catch(o){e().logger.warn("tunnel-state","Failed to persist tunnel state",{error:String(o)})}}function te(t){let r=A(t);if(!M(r))return null;try{let n=$e(r,"utf8"),o=JSON.parse(n);if(typeof o.pid!=="number")return null;return o}catch(n){return e().logger.warn("tunnel-state","Failed to read tunnel state",{error:String(n)}),null}}function re(t){let r=A(t);if(!M(r))return;try{Te(r)}catch{}}function ae(t){return b().isProcessAlive(t)}function qi(t){let r=[];if(t?.allProfiles){let o;try{o=ne()}catch{return r}let i;try{i=Ae(o)}catch{return r}for(let a of i){let s=F(o,a),l=te(s);if(l)r.push({...l,alive:ae(l.pid),profileDir:s})}return r}let n=te();if(n)r.push({...n,alive:ae(n.pid),profileDir:I()});return r}function or(t){return t.replace(/[^A-Za-z0-9_]/g,"_")}function v(){return(B()??e()).tunnel}async function Nr(t,r){let n=v();_e(t),Ie();let o=process.env.AGENT_TUNNEL_URL;if(o){let s=xt(o);if(!s)return e().logger.warn("tunnel-bootstrap","Ignoring invalid AGENT_TUNNEL_URL"),null;n.url=s,n.externalUrl=!0,e().logger.info("tunnel-bootstrap",`Using AGENT_TUNNEL_URL=${s}`);try{Z.emit("tunnel.url_assigned",{provider:"external"})}catch{}return s}let i=r.port,a=await L(i,{log:{info:(s)=>e().logger.info("tunnel-bootstrap",s),warn:(s)=>e().logger.warn("tunnel-bootstrap",s)}});if(!a)return e().logger.warn("tunnel-bootstrap","No bootstrap tunnel \u2014 the agent will register once the tunnel provider starts post-config"),null;if(n.child=a.child,n.url=a.url,n.url){e().logger.info("tunnel-bootstrap",`Bootstrap tunnel ready: ${n.url}`);try{let c=new URL(n.url).hostname.split(".");if(c.length>=2)Jt("."+c.slice(-2).join("."))}catch{}try{Z.emit("tunnel.url_assigned",{provider:"bootstrap"})}catch{}let s=or(R());if(process.env[`AGENT_TUNNEL_URL_${s}`]=n.url,n.child?.pid!==void 0)process.env[`AGENT_TUNNEL_PID_${s}`]=String(n.child.pid),j({pid:n.child.pid,url:n.url,startedAt:new Date().toISOString(),provider:"bootstrap",port:i,cmd:`cloudflared tunnel --url http://127.0.0.1:${i}`})}return n.url}function rn(){let t=v();if(t.externalUrl)return!1;if(!t.child||t.child.killed)return!1;let r=t.child.pid;if(r===void 0)return!1;try{process.kill(r,0)}catch{return!1}return t.child=null,re(),e().logger.info("tunnel-bootstrap",`Handed over bootstrap tunnel (PID ${r}) to plugin \u2014 process kept alive`),!0}function ar(){let t=v();if(t.externalUrl){re();return}let r=t.child;if(t.child=null,re(),!r||r.killed)return;try{r.kill("SIGTERM"),e().logger.info("tunnel-bootstrap","Bootstrap tunnel stopped")}catch{}}function lt(){return v().url}function Ie(){let t=te();if(!t)return;if(!ae(t.pid)){re();return}try{process.kill(t.pid,"SIGTERM"),e().logger.info("tunnel-bootstrap","Reaped orphan tunnel from prior run",{pid:t.pid,provider:t.provider})}catch{}let r=Date.now();while(Date.now()-r<2000&&ae(t.pid))Bun.sleepSync(50);if(ae(t.pid))try{process.kill(t.pid,"SIGKILL")}catch{}re()}function _e(t){let r={name:"bootstrap",async getActiveTunnelUrl(){return v().url}};t.registerProvider("tunnel",r,"bootstrap")}import{existsSync as Oe,mkdirSync as Be,readFileSync as Me,renameSync as De,writeFileSync as je}from"fs";import{dirname as He,join as Ve}from"path";var Ne=["tunnel:read","session:list","session:share:read","session:share:write","plugin:list","plugin:install","plugin:remove","log:read","diagnostics:read","key:mint","mesh:forward","admin"];function z(t){return Ve(t??I(),"agent-network.json")}function y(t){let r=z(t);if(!Oe(r))return{schemaVersion:1,peers:[]};let n=Me(r,"utf8");try{let o=JSON.parse(n);if(!o||!Array.isArray(o.peers))return{schemaVersion:1,peers:[]};return o}catch{return{schemaVersion:1,peers:[]}}}function C(t,r){let n=z(r);Be(He(n),{recursive:!0});let o=`${n}.${process.pid}.tmp`;je(o,JSON.stringify(t,null,2),{mode:384}),De(o,n)}function Ri(t){return y(t).peers}function Je(t,r){return y(r).peers.find((n)=>n.id===t)??null}function H(t,r){if(r.workspaceId&&t.workspaceId&&t.workspaceId!==r.workspaceId)return!1;if(r.ownerUserId)return(t.ownerUserId??r.ownerUserId)===r.ownerUserId;return!0}function gt(t,r){return y(r).peers.filter((n)=>H(n,t))}function kr(t,r,n){return y(n).peers.find((o)=>o.agentRecordId===t&&H(o,r))??null}function We(t,r){let n=y(r),o=n.peers.findIndex((i)=>i.id===t.id);if(o>=0)n.peers[o]={...n.peers[o],...t};else n.peers.push(t);return C(n,r),t}function ke(t,r,n){let o=y(n),i=o.peers.findIndex((a)=>a.id===t);if(i<0)return null;return o.peers[i]={...o.peers[i],...r},C(o,n),o.peers[i]}function Bt(t,r){let n=y(r),o=n.peers.length;if(n.peers=n.peers.filter((i)=>i.id!==t),n.peers.length===o)return!1;return C(n,r),!0}function Xe(t){let r=new Set(Ne);return[...t].filter((n)=>r.has(n)).map((n)=>n)}import{join as Ke}from"path";function w(t){let r=b();return r.which(t)??`${t}${r.executableSuffix}`}async function Ar(){let t=["..","../..","../../.."];for(let r of t)try{let n=Ke(import.meta.dir,r,"package.json"),o=await Bun.file(n).json(),{name:i,version:a}=o;if(i&&a){let s=o.publishConfig;return{name:i,version:a,registry:s?.registry??se()}}}catch{}throw Error("package.json not found")}function Ge(t,r,n){try{let o=Bun.spawnSync([w("npm"),"view",`${t}@${r}`,"--json",`--registry=${n}`],{stdout:"pipe",stderr:"pipe"});if(o.exitCode!==0)return null;let i=JSON.parse(o.stdout.toString());return Array.isArray(i)?i[0]??null:i}catch{return null}}function V(t,r){let n=(a)=>a.replace(/^[\^~>=<v]+/,"").split(/[.+-]/).map((s)=>Number(s)||0),o=n(t),i=n(r);for(let a=0;a<Math.max(o.length,i.length);a++){let s=o[a]??0,l=i[a]??0;if(s!==l)return s-l}return 0}function qe(t,r){if(!t)return{ok:!0,message:""};let n=t.replace(/^[\^~]/,"").replace(/^>=?\s*/,"");if(V(r,n)>=0)return{ok:!0,message:`bun ${r} >= ${n}`};return{ok:!1,message:`requires bun ${t}, this process is bun ${r}`}}function Qe(t){try{let r=w("npm"),n=Bun.spawnSync([r,"root","-g"],{stdout:"pipe",stderr:"pipe"});if(n.exitCode!==0)return null;return`${n.stdout.toString().trim()}/${t}`}catch{return null}}function Ye(t){let r=Qe(t);if(!r)return{ok:!0,step:"(skipped, install root unknown)"};let n=`${r}/dist/cli.js`,o=(l,c,d)=>{try{let u=w("bun"),g=Bun.spawnSync([u,n,...l],{stdout:"pipe",stderr:"pipe",timeout:d});if(g.exitCode===0)return{ok:!0,step:c};return{ok:!1,step:c,detail:g.stderr.toString().slice(0,300)||`exit ${g.exitCode}`}}catch(u){return{ok:!1,step:c,detail:String(u)}}},i=o(["--version"],"vibe --version",1e4);if(!i.ok)return i;let a=o(["info"],"vibe info",15000);if(!a.ok)return a;let s=o(["plugin","list","--json"],"vibe plugin list",30000);if(!s.ok)return s;return{ok:!0,step:"all checks passed"}}async function tt(t,r=60000){try{let n=new D,o=await n.getStatus(t);if(!o||o.status!=="running")return{kind:"not-running"};let i=`http://localhost:${o.port}`,a;try{a=await Fe(i)}catch{}let s={};if(a)s["x-agent-api-key"]=a;let l=1000,c=Date.now();while(Date.now()-c<r){try{let d=await fetch(`${i}/api/profiles/${encodeURIComponent(t)}/stats/inflight`,{headers:s,signal:AbortSignal.timeout(2000)});if(d.ok){let u=await d.json();if(typeof u.inflight==="number"&&u.inflight===0){let g=o.config;return await n.restart(t,g),{kind:"restarted"}}}}catch{}await new Promise((d)=>setTimeout(d,l))}return{kind:"still-busy"}}catch(n){return{kind:"error",message:n instanceof Error?n.message:String(n)}}}async function Le(){let t;try{t=await Ar()}catch(n){return{name:"@vibecontrols/agent",registry:se(),current:"unknown",latest:null,hasUpdate:!1,error:n instanceof Error?n.message:String(n)}}let r=null;try{let n=Bun.spawnSync([w("npm"),"view",t.name,"version",`--registry=${t.registry}`],{stdout:"pipe",stderr:"pipe"});if(n.exitCode===0)r=n.stdout.toString().trim()||null}catch{}if(!r)return{name:t.name,registry:t.registry,current:t.version,latest:null,hasUpdate:!1,error:"Could not reach the registry to check for updates"};return{name:t.name,registry:t.registry,current:t.version,latest:r,hasUpdate:V(r,t.version)>0}}async function ze(t={}){let r=t.onLog??(()=>{}),n=t.restart!==!1,o=t.name||"default",i;try{i=await Ar()}catch(p){return{ok:!1,updated:!1,current:"unknown",previous:"unknown",latest:null,target:null,restart:"skipped",error:p instanceof Error?p.message:String(p)}}let a=i.version,s=t.targetVersion?.trim(),l=null;if(!s||s==="latest"){try{let p=Bun.spawnSync([w("npm"),"view",i.name,"version",`--registry=${i.registry}`],{stdout:"pipe",stderr:"pipe"});if(p.exitCode===0)l=p.stdout.toString().trim()||null}catch{}if(!l)return{ok:!1,updated:!1,current:a,previous:a,latest:null,target:null,restart:"skipped",error:"Could not check for updates (registry unreachable)"};s=l}if(s===a)return r(`Already on ${a}; nothing to do.`),{ok:!0,updated:!1,current:a,previous:a,latest:l??a,target:s,restart:"skipped"};let c,d=Ge(i.name,s,i.registry);if(d){let p=typeof Bun<"u"?Bun.version:"0.0.0",m=qe(d.engines?.bun,p);if(c=m.message,!m.ok&&!t.allowIncompatible)return{ok:!1,updated:!1,current:a,previous:a,latest:l,target:s,engineMessage:m.message,restart:"skipped",error:`Refusing to upgrade: ${m.message}. Pass allowIncompatible to override.`}}r(`Installing ${i.name}@${s}...`);try{let p=Bun.spawnSync([w("npm"),"install","-g",`${i.name}@${s}`,`--registry=${i.registry}`],{stdout:"pipe",stderr:"pipe"});if(p.exitCode!==0){let m=p.stderr.toString().slice(0,500);return{ok:!1,updated:!1,current:a,previous:a,latest:l,target:s,engineMessage:c,restart:"skipped",error:`npm install failed: ${m||`exit ${p.exitCode}`}`}}}catch(p){return{ok:!1,updated:!1,current:a,previous:a,latest:l,target:s,engineMessage:c,restart:"skipped",error:`npm install threw: ${p instanceof Error?p.message:String(p)}`}}let u=Ye(i.name);if(!u.ok){r(`Smoke test failed at "${u.step}" \u2014 rolling back to ${a}.`);let p=!1;try{p=Bun.spawnSync([w("npm"),"install","-g",`${i.name}@${a}`,`--registry=${i.registry}`],{stdout:"pipe",stderr:"pipe"}).exitCode===0}catch{}return{ok:!1,updated:!1,current:p?a:s,previous:a,latest:l,target:s,engineMessage:c,smoke:u,rolledBack:p,restart:"skipped",error:`Post-install smoke test failed at "${u.step}"${u.detail?`: ${u.detail}`:""}. ${p?"Rolled back.":"Rollback FAILED \u2014 reinstall manually."}`}}let g={kind:"skipped"};if(n)r(`Waiting for agent "${o}" to become idle before restart...`),g=await tt(o,t.restartBudgetMs);return r(`Updated to ${s}.`),{ok:!0,updated:!0,current:s,previous:a,latest:l,target:s,engineMessage:c,smoke:u,rolledBack:!1,restart:g.kind,restartError:g.kind==="error"?g.message:void 0}}function rt(t){let r=/^(?:ssh:\/\/)?(?:([^@\s]+)@)?([^:/\s]+)(?::(\d+))?$/.exec(t.trim());if(!r)throw Error(`Could not parse SSH target: ${t}`);let n=Boolean(r[1]),o=Boolean(r[3]);if(!n&&!o&&!t.includes(":"))return{alias:r[2],host:r[2]};return{user:r[1],host:r[2],port:r[3]?Number(r[3]):void 0}}class K{mode="ssh";id;target;constructor(t){if(this.target=t,t.alias)this.id=`ssh://${t.alias}`;else{let r=t.user?`${t.user}@`:"",n=t.port?`:${t.port}`:"";this.id=`ssh://${r}${t.host}${n}`}}sshArgv(){let t=["ssh","-o","BatchMode=yes","-o","StrictHostKeyChecking=accept-new","-o","ServerAliveInterval=30"];if(this.target.identityFile)t.push("-i",this.target.identityFile);if(this.target.port)t.push("-p",String(this.target.port));return t.push(this.target.alias??(this.target.user?`${this.target.user}@${this.target.host}`:this.target.host)),t}async probe(){let t={},r=[["npm","command -v npm"],["node","command -v node"],["bun","command -v bun"],["vibe","command -v vibe"],["os","uname -s 2>/dev/null || echo unknown"],["arch","uname -m 2>/dev/null || echo unknown"]];for(let[n,o]of r){let i=await this.run(["sh","-c",o]),a=i.stdout.trim();if(i.code===0&&a)t[n]=a}return t}async run(t,r){let n=t.map(_).join(" "),o=[...this.sshArgv(),n],i=Bun.spawnSync(o,{stdout:"pipe",stderr:"pipe",timeout:r?.timeoutMs??600000});return{code:i.exitCode??1,stdout:i.stdout.toString(),stderr:i.stderr.toString()}}async upload(t,r,n){let o=[...this.sshArgv(),`cat > ${_(t)} && chmod ${(n??384).toString(8)} ${_(t)}`],i=Bun.spawn(o,{stdin:"pipe",stdout:"pipe",stderr:"pipe"}),a=i.stdin;a.write(typeof r==="string"?r:Buffer.from(r).toString("binary")),await a.end();let s=await i.exited;if(s!==0){let l=await new Response(i.stderr).text();throw Error(`upload to ${t} failed (exit ${s}): ${l}`)}}async close(){}}function _(t){if(/^[A-Za-z0-9._\-/=:]+$/.test(t))return t;return`'${t.replace(/'/g,"'\\''")}'`}class W{mode="local";id="local";async probe(){let t={},r=[["npm","command -v npm"],["node","command -v node"],["bun","command -v bun"],["vibe","command -v vibe"],["os","uname -s 2>/dev/null || echo unknown"],["arch","uname -m 2>/dev/null || echo unknown"]];for(let[n,o]of r){let i=await this.run(["sh","-c",o]),a=i.stdout.trim();if(i.code===0&&a)t[n]=a}return t}async run(t,r){let n=Bun.spawnSync(t,{stdout:"pipe",stderr:"pipe",timeout:r?.timeoutMs??600000});return{code:n.exitCode??1,stdout:n.stdout.toString(),stderr:n.stderr.toString()}}async upload(t,r,n){await Bun.write(t,r);try{let{chmodSync:o}=await import("fs");o(t,n??384)}catch{}}async close(){}}function et(t,r){let n=/^([a-z]+):\/\//.exec(t)?.[1];if(n==="local"||t.trim()==="local"||t.trim()==="localhost")return new W;if(!n||n==="ssh"){let o=rt(t);if(r?.identityFile)o.identityFile=r.identityFile;return new K(o)}throw Error(`Unsupported install transport scheme: ${n}://. Supported today: ssh:// (and bare host or ssh_config alias). Future: winrm://, ssm://, docker://, k8s://`)}var nt=/^[A-Za-z0-9._+-]+$/,ot=/^(?:@[a-z0-9][a-z0-9._-]{0,127}\/)?[a-z0-9][a-z0-9._-]{0,127}(?:@[A-Za-z0-9][A-Za-z0-9._+-]{0,127})?$/,it=/^\d+[smhdw]?$/,st=/^[a-z0-9:_-]{1,64}$/,at=/[`$;&|<>'"\\]/,ct=/['"`$\s;|&<>()\\]/;function G(t){for(let r=0;r<t.length;r++){let n=t.charCodeAt(r);if(n<=31||n===127)return!0}return!1}function dt(t){if(!t||t.length>128||t.startsWith("-")||!nt.test(t))throw Error(`Invalid agent version: ${t}`);return t}function ht(t){if(!t||t.length>2048||G(t)||ct.test(t))throw Error(`Invalid registry URL: ${t}`);let r;try{r=new URL(t)}catch{throw Error(`Invalid registry URL: ${t}`)}if(r.protocol!=="http:"&&r.protocol!=="https:"||!r.hostname)throw Error(`Invalid registry URL: ${t}`);return t}function ft(t){let r=t.trim();if(!r||r.includes("..")||!ot.test(r))throw Error(`Invalid plugin package name: ${t}`);return r}function pt(t){let r=t.trim();if(!r||r.length>16||!it.test(r))throw Error(`Invalid --expires-in value: ${t}`);return r}function Lr(t){let r=t.split(",").map((n)=>n.trim()).filter(Boolean);if(r.length===0)throw Error(`Invalid --permissions value: ${t}`);for(let n of r)if(!st.test(n))throw Error(`Invalid --permissions value: ${t}`);return r.join(",")}function mt(t){let r=t.trim();if(!r||r.length>128||r.startsWith("-")||G(r)||at.test(r))throw Error(`Invalid --label value: ${t}`);return r}function Pt(t,r){let n=ht(t),o=dt(r);return["sh","-c",'export PATH="$HOME/.bun/bin:$PATH"; npm_config_registry="$1" bun install -g @vibecontrols/agent@"$2" --no-cache',"_",n,o]}function Mt(t){return["sh","-c",'export PATH="$HOME/.bun/bin:$PATH"; vibe plugin install "$1"',"_",ft(t)]}function Dt(t){let r=mt(t.label),n=Lr(t.scope),o=t.expiresIn?pt(t.expiresIn):void 0,i=[];if(t.json)i.push("--json");if(t.emitDefaultKey)i.push("--emit-default-key");let a=i.length>0?`${i.join(" ")} `:"";if(o)return["sh","-c",`export PATH="$HOME/.bun/bin:$PATH"; vibe peer-bootstrap ${a}--label "$1" --scope "$2" --expires-in "$3" 2>/dev/null`,"_",r,n,o];return["sh","-c",`export PATH="$HOME/.bun/bin:$PATH"; vibe peer-bootstrap ${a}--label "$1" --scope "$2" 2>/dev/null`,"_",r,n]}async function J(t,r,n){let o=`${t.tunnelUrl.replace(/\/$/,"")}${r}`;try{let i=await fetch(o,{method:n.method??"GET",headers:{"x-agent-api-key":t.apiKey,"content-type":n.body?"application/json":"application/octet-stream"},body:n.body?JSON.stringify(n.body):void 0,signal:AbortSignal.timeout(n.timeoutMs??30000)});if(i.status===200||i.status===201||i.status===204){let s=await i.json().catch(()=>{return});return{ok:!0,status:i.status,data:s}}let a=await i.text().catch(()=>"");return{ok:!1,status:i.status,error:a}}catch(i){return{ok:!1,status:0,error:i instanceof Error?i.message:String(i)}}}async function Se(t,r,n={}){let o=Je(t);if(!o)return{ok:!1,status:0,error:`No peer with id ${t}`};let i=await J(o,r,n);if(i.ok)return ke(o.id,{lastReachable:new Date().toISOString()}),i;if(!(i.status===401||i.status===0||i.status===502||i.status===503||i.status===504))return i;if(!o.agentRecordId||!T.isConfigured())return i;let s=null;try{s=await T.lookupPeerAgent(o.agentRecordId,n.operation??"peer-call")}catch(d){e().logger.warn("peer-client","Backend rotation lookup failed",{peerId:t,error:d instanceof Error?d.message:String(d)})}if(!s)return i;ke(o.id,{tunnelUrl:s.tunnelUrl,apiKey:s.apiKey});let l={...o,tunnelUrl:s.tunnelUrl,apiKey:s.apiKey};return{...await J(l,r,n),rotated:!0}}
17
+ export{Ze,Ot,Ti,xi,nr,bi,sr,wi,ut,te,re,ae,qi,or,Nr,rn,ar,lt,Ne,Ri,Je,gt,kr,We,ke,Bt,Xe,Ar,Le,ze,et,dt,ht,ft,pt,Lr,mt,Pt,Mt,Dt,Se};
@@ -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 Ir(){return Array.from(r().values())}
3
- export{Ir};
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 Dr(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 ve(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(Dr(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{Dr,ve};
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-0qjbnyg4.js";import{J,w}from"./index-kwhx023z.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 Kt(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(!Kt(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 Re(r){let n=Kt(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 Re(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&&Kt(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 Ce(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 Ae(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{Kt,f,Re,m,S,q,Ce,Ae};
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};