@vibecontrols/agent 2026.814.1 → 2026.820.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 (126) hide show
  1. package/dist/agent-config-t242qh84.js +2 -0
  2. package/dist/{agent-ready-tracker-gx1yqwjk.js → agent-ready-tracker-y9wbqt6y.js} +1 -1
  3. package/dist/app-7rmybh7z.js +2 -0
  4. package/dist/autostart.cmd-arjjfy8k.js +2 -0
  5. package/dist/bootstrap-workspace-dvxqq79t.js +2 -0
  6. package/dist/bootstrap.service-3zpbgsg0.js +2 -0
  7. package/dist/{bridge-client-zye1vz1y.js → bridge-client-emc7mttx.js} +1 -1
  8. package/dist/cli.js +1 -1
  9. package/dist/daemon-profile-nbe3pww8.js +2 -0
  10. package/dist/esm-br6epktf.js +2 -0
  11. package/dist/{finalize-retry-handle-registry-kzfqhvwv.js → finalize-retry-handle-registry-ndbsa6a3.js} +1 -1
  12. package/dist/{finalize-retry-worker-74wxbdsh.js → finalize-retry-worker-mfj115ek.js} +1 -1
  13. package/dist/gateway-client-dnjxwbnj.js +2 -0
  14. package/dist/{getMachineId-bsd-65jabrgp.js → getMachineId-bsd-gvxzt2gm.js} +1 -1
  15. package/dist/{getMachineId-darwin-yykv9khr.js → getMachineId-darwin-g66tx8f2.js} +1 -1
  16. package/dist/{getMachineId-linux-w09acg2n.js → getMachineId-linux-f0mt4jq9.js} +1 -1
  17. package/dist/{getMachineId-unsupported-dwr7bb60.js → getMachineId-unsupported-bsmqnjcv.js} +1 -1
  18. package/dist/{getMachineId-win-0wkw4jek.js → getMachineId-win-172fq57c.js} +1 -1
  19. package/dist/highlights-3g7x1wxx.js +2 -0
  20. package/dist/highlights-66pe672g.js +2 -0
  21. package/dist/highlights-78tmcgkr.js +2 -0
  22. package/dist/highlights-dhv8z6p7.js +2 -0
  23. package/dist/highlights-j95xsvt4.js +2 -0
  24. package/dist/index-014sfc8c.js +2 -0
  25. package/dist/{index-gb5bnx7a.js → index-149rjxa5.js} +1 -1
  26. package/dist/{index-16czz4df.js → index-1hfchgm5.js} +1 -1
  27. package/dist/{index-nj7bvgws.js → index-1xw2wxyf.js} +1 -1
  28. package/dist/{index-5wsfsj88.js → index-2244sbdx.js} +4 -4
  29. package/dist/{index-4gt22c81.js → index-34g3tenj.js} +2 -2
  30. package/dist/{index-1ptfacy9.js → index-426ddch6.js} +1 -1
  31. package/dist/{index-r49hb09r.js → index-4beawmtx.js} +2 -2
  32. package/dist/{index-wndzw5pk.js → index-4f3ac5nf.js} +2 -2
  33. package/dist/{index-e1bw1bwr.js → index-54mmh1eb.js} +1 -1
  34. package/dist/{index-c975k3pk.js → index-6nz3c1ys.js} +3 -3
  35. package/dist/{index-ntj6ymk8.js → index-73qwyf9q.js} +1 -1
  36. package/dist/{index-5s2zc91f.js → index-81gn264d.js} +1 -1
  37. package/dist/{index-13xxbf03.js → index-97r6ekww.js} +2 -2
  38. package/dist/{index-zb7nfmts.js → index-a3mwtteb.js} +2 -2
  39. package/dist/index-a9x5swye.js +11 -0
  40. package/dist/{index-53qthjhb.js → index-at6z8tds.js} +2 -2
  41. package/dist/{index-c4p1qcnn.js → index-axgp7ryd.js} +3 -3
  42. package/dist/{index-5dysvvjv.js → index-bv1z3fxw.js} +1 -1
  43. package/dist/{index-q9dp55wv.js → index-c4zn91z3.js} +1 -1
  44. package/dist/{index-9g3vxhby.js → index-d384edvr.js} +2 -2
  45. package/dist/index-dpyv0pqb.js +26 -0
  46. package/dist/{index-zaw78sxw.js → index-e0jbxcn1.js} +3 -3
  47. package/dist/{index-0ckffygp.js → index-ea42kfvk.js} +1 -1
  48. package/dist/{index-52cp759f.js → index-ekr40gvh.js} +1 -1
  49. package/dist/{index-2gwc485c.js → index-ff8acg43.js} +2 -2
  50. package/dist/{index-jqfsvf8f.js → index-gmwpaz2a.js} +2 -2
  51. package/dist/{index-4wgjx8bf.js → index-hey6w5m0.js} +1 -1
  52. package/dist/{index-b5dhmybd.js → index-hwpmdq5z.js} +1 -1
  53. package/dist/{index-qzhvhyvq.js → index-hym4bq94.js} +1 -1
  54. package/dist/{index-m2kkd6t6.js → index-jnrqbhew.js} +2 -2
  55. package/dist/{index-wd2ak0q4.js → index-jq7vqe4a.js} +1 -1
  56. package/dist/{index-gx53t38f.js → index-m1bteh0j.js} +1 -1
  57. package/dist/{index-2bjqvapr.js → index-najxwhng.js} +1 -1
  58. package/dist/{index-jb3v3b39.js → index-paxfq5k4.js} +1 -1
  59. package/dist/{index-7vwefvxd.js → index-r1v6p7vc.js} +1 -1
  60. package/dist/{index-pc05r6fd.js → index-rhcsaqc0.js} +2 -2
  61. package/dist/{index-rc79x8fw.js → index-rmh8pff5.js} +1 -1
  62. package/dist/{index-8k78bp4w.js → index-sasygg1e.js} +1 -1
  63. package/dist/{index-0s81cfpe.js → index-sj39bx7y.js} +2 -2
  64. package/dist/{index-e2dqz3tw.js → index-svtmb9t1.js} +2 -2
  65. package/dist/{index-g9fthh7a.js → index-tcew34xr.js} +2 -2
  66. package/dist/index-vd3njzs5.js +116 -0
  67. package/dist/index-w893wd2g.js +130 -0
  68. package/dist/{index-8nqp3a4d.js → index-wj5hx7gq.js} +1 -1
  69. package/dist/{index-c0fgge10.js → index-wqwzfy0e.js} +2 -2
  70. package/dist/{index-jrxbbb7p.js → index-xyfcpfec.js} +2 -2
  71. package/dist/{index-zabjc8f2.js → index-ywv7amgf.js} +1 -1
  72. package/dist/index.js +3 -3
  73. package/dist/injections-2pt7wmtk.js +2 -0
  74. package/dist/interactive-svpgqn7v.js +2 -0
  75. package/dist/key.cmd-m0zst9pm.js +2 -0
  76. package/dist/log-shipper-m9h3jxem.js +2 -0
  77. package/dist/{path-utils-cg1gsy4m.js → path-utils-rzsac4g6.js} +1 -1
  78. package/dist/plugin-system-jww7bh2a.js +2 -0
  79. package/dist/prereqs-runner-fhjjgzhw.js +2 -0
  80. package/dist/profile-mount-xchr4y5e.js +2 -0
  81. package/dist/prune-stale-shims-wttq2y0f.js +2 -0
  82. package/dist/register-core-n2kb3mhq.js +2 -0
  83. package/dist/secondary-profile-attach-yzwncw4f.js +2 -0
  84. package/dist/subprocess-chzm6zj2.js +2 -0
  85. package/dist/telemetry-h9pa43c9.js +2 -0
  86. package/dist/tree-sitter-javascript-jre8s337.js +2 -0
  87. package/dist/tree-sitter-markdown-3as64nwe.js +2 -0
  88. package/dist/tree-sitter-markdown_inline-rs74pnzp.js +2 -0
  89. package/dist/tree-sitter-typescript-dgsjhgb0.js +2 -0
  90. package/dist/tree-sitter-zig-p8cc70k0.js +2 -0
  91. package/dist/tunnel-bootstrap-6xm4w7dm.js +2 -0
  92. package/package.json +1 -1
  93. package/dist/agent-config-hzzh97dn.js +0 -2
  94. package/dist/app-k3dex7x4.js +0 -2
  95. package/dist/bootstrap-workspace-dg1e3fp6.js +0 -2
  96. package/dist/bootstrap.service-nbhhd4pa.js +0 -2
  97. package/dist/daemon-profile-ryakpcbx.js +0 -2
  98. package/dist/esm-cg5tnbkd.js +0 -2
  99. package/dist/gateway-client-8y9yd0ch.js +0 -2
  100. package/dist/highlights-5wfvq2xq.js +0 -2
  101. package/dist/highlights-fdyzf5xj.js +0 -2
  102. package/dist/highlights-g5bek66n.js +0 -2
  103. package/dist/highlights-scv26t06.js +0 -2
  104. package/dist/highlights-tx5ed845.js +0 -2
  105. package/dist/index-2jxqpj7r.js +0 -26
  106. package/dist/index-nwh7j7ap.js +0 -2
  107. package/dist/index-sv4rzv3f.js +0 -11
  108. package/dist/index-tcwmw7ed.js +0 -231
  109. package/dist/injections-agpjxatz.js +0 -2
  110. package/dist/interactive-ewe5szk5.js +0 -2
  111. package/dist/key.cmd-xefsd8p4.js +0 -2
  112. package/dist/log-shipper-4h1k4kp6.js +0 -2
  113. package/dist/plugin-system-ksatnqp4.js +0 -2
  114. package/dist/prereqs-runner-6yf1e5e3.js +0 -2
  115. package/dist/profile-mount-13qvjqbg.js +0 -2
  116. package/dist/prune-stale-shims-t6kdd2an.js +0 -2
  117. package/dist/register-core-9k4zxnsg.js +0 -2
  118. package/dist/secondary-profile-attach-42x68g0c.js +0 -2
  119. package/dist/subprocess-6m8bja6s.js +0 -2
  120. package/dist/telemetry-mq37zapd.js +0 -2
  121. package/dist/tree-sitter-javascript-emqv64wx.js +0 -2
  122. package/dist/tree-sitter-markdown-v98rp3y1.js +0 -2
  123. package/dist/tree-sitter-markdown_inline-5gq03gn2.js +0 -2
  124. package/dist/tree-sitter-typescript-gr7ymg9w.js +0 -2
  125. package/dist/tree-sitter-zig-59q80fch.js +0 -2
  126. package/dist/tunnel-bootstrap-50fm2wt8.js +0 -2
@@ -1,4 +1,4 @@
1
1
  // @bun
2
2
  function V(j){let H=[["--version"],["-V"],["version"]];for(let F of H)try{let z=Bun.spawnSync([j,...F],{timeout:5000,stdout:"pipe",stderr:"pipe"});if(z.exitCode===0){let J=z.stdout.toString().trim(),K=z.stderr.toString().trim();return{installed:!0,version:(J||K).split(`
3
3
  `)[0]||void 0}}}catch{}try{if(Bun.which(j,{PATH:process.env.PATH}))return{installed:!0}}catch{}return{installed:!1}}var X=[{name:"bun",cmd:"bun",required:!0,category:"runtime"}];function Z(j){let H=X.map((F)=>{let{installed:z,version:J}=V(F.cmd);return{name:F.name,installed:z,version:J,required:F.required,category:F.category}});if(j!==void 0){let F=j instanceof Set?j:new Set(j);for(let z of F){if(H.some((Q)=>Q.name===z))continue;let{installed:J,version:K}=V(z);H.push({name:z,installed:J,version:K,required:!1,category:"tool"})}}return H}async function $(j){return{success:!0,installed:[],failed:[],skipped:j??[]}}
4
- export{Z as O,$ as P};
4
+ export{Z as S,$ as T};
@@ -1,8 +1,8 @@
1
1
  // @bun
2
- import{je as A}from"./index-gb5bnx7a.js";var j=!process.env.NO_COLOR&&!!process.stdout.isTTY;function L(q){j=q}var C=(q,B)=>(F)=>j?`${q}${F}${B}`:F,z={bold:C("\x1B[1m","\x1B[22m"),dim:C("\x1B[2m","\x1B[22m"),italic:C("\x1B[3m","\x1B[23m"),underline:C("\x1B[4m","\x1B[24m"),red:C("\x1B[31m","\x1B[39m"),green:C("\x1B[32m","\x1B[39m"),yellow:C("\x1B[33m","\x1B[39m"),blue:C("\x1B[34m","\x1B[39m"),magenta:C("\x1B[35m","\x1B[39m"),cyan:C("\x1B[36m","\x1B[39m"),white:C("\x1B[37m","\x1B[39m"),gray:C("\x1B[90m","\x1B[39m"),brightRed:C("\x1B[91m","\x1B[39m"),brightGreen:C("\x1B[92m","\x1B[39m"),brightYellow:C("\x1B[93m","\x1B[39m"),brightBlue:C("\x1B[94m","\x1B[39m"),reset:"\x1B[0m"},Q={get success(){return z.green("\u2713")},get error(){return z.red("\u2717")},get warning(){return z.yellow("\u26A0")},get info(){return z.blue("\u25CF")},get running(){return z.green("\u25CF")},get stopped(){return z.red("\u25CB")},get pending(){return z.yellow("\u25CC")},get arrow(){return z.gray("\u2192")},get bullet(){return z.gray("\u2022")},get check(){return z.green("\u2714")}};function T(q){console.error(`${z.red("Error:")} ${q}`),process.exit(1)}function H(q){if(q instanceof Error)return q.message;if(typeof q==="string")return q;try{return JSON.stringify(q)}catch{return String(q)}}function M(q){console.log(` ${Q.success} ${q}`)}function f(q){console.log(` ${Q.warning} ${q}`)}function E(q){console.log(` ${Q.info} ${q}`)}function D(q){console.log(`
2
+ import{qe as A}from"./index-149rjxa5.js";var j=!process.env.NO_COLOR&&!!process.stdout.isTTY;function L(q){j=q}var C=(q,B)=>(F)=>j?`${q}${F}${B}`:F,z={bold:C("\x1B[1m","\x1B[22m"),dim:C("\x1B[2m","\x1B[22m"),italic:C("\x1B[3m","\x1B[23m"),underline:C("\x1B[4m","\x1B[24m"),red:C("\x1B[31m","\x1B[39m"),green:C("\x1B[32m","\x1B[39m"),yellow:C("\x1B[33m","\x1B[39m"),blue:C("\x1B[34m","\x1B[39m"),magenta:C("\x1B[35m","\x1B[39m"),cyan:C("\x1B[36m","\x1B[39m"),white:C("\x1B[37m","\x1B[39m"),gray:C("\x1B[90m","\x1B[39m"),brightRed:C("\x1B[91m","\x1B[39m"),brightGreen:C("\x1B[92m","\x1B[39m"),brightYellow:C("\x1B[93m","\x1B[39m"),brightBlue:C("\x1B[94m","\x1B[39m"),reset:"\x1B[0m"},Q={get success(){return z.green("\u2713")},get error(){return z.red("\u2717")},get warning(){return z.yellow("\u26A0")},get info(){return z.blue("\u25CF")},get running(){return z.green("\u25CF")},get stopped(){return z.red("\u25CB")},get pending(){return z.yellow("\u25CC")},get arrow(){return z.gray("\u2192")},get bullet(){return z.gray("\u2022")},get check(){return z.green("\u2714")}};function T(q){console.error(`${z.red("Error:")} ${q}`),process.exit(1)}function H(q){if(q instanceof Error)return q.message;if(typeof q==="string")return q;try{return JSON.stringify(q)}catch{return String(q)}}function M(q){console.log(` ${Q.success} ${q}`)}function f(q){console.log(` ${Q.warning} ${q}`)}function E(q){console.log(` ${Q.info} ${q}`)}function D(q){console.log(`
3
3
  ${z.bold(`\u2500\u2500 ${q} \u2500\u2500`)}
4
4
  `)}function X(q,B){let F=B===null||B===void 0?z.gray("(none)"):String(B);console.log(` ${z.bold(q.padEnd(14))} ${F}`)}function $(){console.log()}function S(q){if(q.length===0){console.log(" (none)");return}console.table(q)}function W(q){let B=Date.now()-new Date(q).getTime(),F=Math.floor(B/1000);if(F<0)return"just now";if(F<60)return`${F}s ago`;let J=Math.floor(F/60);if(J<60)return`${J}m ago`;let N=Math.floor(J/60);if(N<24)return`${N}h ago`;let P=Math.floor(N/24);if(P<30)return`${P}d ago`;return`${Math.floor(P/30)}mo ago`}function x(q){if(q<60)return`${Math.floor(q)}s`;let B=Math.floor(q/60),F=Math.floor(q%60);if(B<60)return`${B}m ${F}s`;let J=Math.floor(B/60),N=B%60;return`${J}h ${N}m`}function K(q){if(q<1024)return`${q} B`;if(q<1048576)return`${(q/1024).toFixed(1)} KB`;if(q<1073741824)return`${(q/1048576).toFixed(1)} MB`;return`${(q/1073741824).toFixed(1)} GB`}function h(q){switch(q){case"running":case"active":case"healthy":case"success":case"completed":return z.green(q);case"stopped":case"inactive":case"terminated":case"failed":return z.red(q);case"starting":case"stopping":case"pending":case"warning":return z.yellow(q);case"error":return z.red(q);default:return q}}function k(q,B=10){if(q.length<=B)return q;return q.substring(0,B)+"..."}async function v(q,B=15000){let F=Date.now(),J=!1;while(Date.now()-F<B){try{if((await fetch(`${q}/health`)).ok){J=!0;break}}catch{}await new Promise((G)=>setTimeout(G,500))}if(!J){console.log(`
5
5
  ${Q.warning} Agent not yet responding at ${q}. Check ${z.bold("vibe logs")} for details.
6
- `);return}let N=process.env.VIBECONTROLS_PROFILE||"default",P=`${q}/api/profiles/${encodeURIComponent(N)}/agent/tunnel`,R="(unavailable)";try{let{resolveDefaultApiKey:G}=await import("./key.cmd-xefsd8p4.js"),I=await G();if(I)R=I}catch{}let Y=R&&R!=="(unavailable)"?{"x-agent-api-key":R}:{},O="(not running)",Z=!1;try{let G=await fetch(P,{headers:Y});if(G.ok){let I=await G.json();if(I.tunnelUrl)O=I.tunnelUrl;else if(I.status!=="inactive")Z=!0}}catch{}if(Z||O==="(not running)"){process.stdout.write(` ${Q.info} Provisioning tunnel (first run downloads the tunnel binary)\u2026`);let G=150000,I=Date.now();while(Date.now()-I<G){try{let V=await fetch(P,{headers:Y});if(V.ok){let _=await V.json();if(_.tunnelUrl){O=_.tunnelUrl;break}}}catch{}await new Promise((V)=>setTimeout(V,1500)),process.stdout.write(`\r ${Q.info} Provisioning tunnel (first run downloads the tunnel binary)\u2026 ${Math.round((Date.now()-I)/1000)}s`)}process.stdout.write(`
6
+ `);return}let N=process.env.VIBECONTROLS_PROFILE||"default",P=`${q}/api/profiles/${encodeURIComponent(N)}/agent/tunnel`,R="(unavailable)";try{let{resolveDefaultApiKey:G}=await import("./key.cmd-m0zst9pm.js"),I=await G();if(I)R=I}catch{}let Y=R&&R!=="(unavailable)"?{"x-agent-api-key":R}:{},O="(not running)",Z=!1;try{let G=await fetch(P,{headers:Y});if(G.ok){let I=await G.json();if(I.tunnelUrl)O=I.tunnelUrl;else if(I.status!=="inactive")Z=!0}}catch{}if(Z||O==="(not running)"){process.stdout.write(` ${Q.info} Provisioning tunnel (first run downloads the tunnel binary)\u2026`);let G=150000,I=Date.now();while(Date.now()-I<G){try{let V=await fetch(P,{headers:Y});if(V.ok){let _=await V.json();if(_.tunnelUrl){O=_.tunnelUrl;break}}}catch{}await new Promise((V)=>setTimeout(V,1500)),process.stdout.write(`\r ${Q.info} Provisioning tunnel (first run downloads the tunnel binary)\u2026 ${Math.round((Date.now()-I)/1000)}s`)}process.stdout.write(`
7
7
  `)}if(D("Agent Connection Details"),X("Agent URL:",q),X("API Key:",R),X("Tunnel URL:",O==="(not running)"?z.yellow(O):z.green(O)),$(),console.log(" Copy the API Key and Tunnel URL into the VibeControls UI agent configuration."),O==="(not running)")console.log(` ${z.yellow("Tunnel still provisioning")} \u2014 the cloudflared download may still be running in the daemon.`),console.log(` Re-check shortly: ${z.bold("vibe url")}`),console.log(` Start it manually: ${z.bold(`vibe tunnel agent --start --agent-url ${q}`)}`),console.log(` If it never appears: ${z.bold("vibe logs --tail 80")} (look for 'tunnel-bootstrap' / 'install')`);$()}
8
- export{L as nc,z as oc,Q as pc,T as qc,H as rc,M as sc,f as tc,E as uc,D as vc,X as wc,$ as xc,S as yc,W as zc,x as Ac,K as Bc,h as Cc,k as Dc,v as Ec};
8
+ export{L as rc,z as sc,Q as tc,T as uc,H as vc,M as wc,f as xc,E as yc,D as zc,X as Ac,$ as Bc,S as Cc,W as Dc,x as Ec,K as Fc,h as Gc,k as Hc,v as Ic};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
2
  function z(){let j=process.env.VIBECONTROLS_LOG_SHIP_URL;if(!j)return null;return{url:j,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 k=1000;class s{config=null;queue=[];timer=null;inFlight=!1;dropped=0;init(){if(this.config)return;if(this.config=z(),!this.config)return;if(this.timer=setInterval(()=>{this.flush()},this.config.intervalMs),this.timer&&typeof this.timer.unref==="function")this.timer.unref()}enqueue(j){if(!this.config)return;if(j.level==="debug"&&this.config.sampleRate<1&&Math.random()>this.config.sampleRate)return;if(this.queue.length>=k)this.dropped+=1,this.queue.shift();this.queue.push(j)}async flush(){if(!this.config||this.inFlight||this.queue.length===0)return;this.inFlight=!0;let j=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:j,dropped:this.dropped}),signal:AbortSignal.timeout(5000)}),this.dropped=0}catch{this.queue=[...j,...this.queue].slice(0,k)}finally{this.inFlight=!1}}stop(){if(this.timer)clearInterval(this.timer),this.timer=null;this.flush()}}var B=new s;
3
- export{B as fe};
3
+ export{B as me};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{E as A,G as N}from"./index-6jzsthh9.js";import{Ub as l,Vb as T}from"./index-zaw78sxw.js";import{jc as G,kc as D,lc as f}from"./index-8nqp3a4d.js";import{Dc as y,qc as d,rc as r,sc as j,uc as J,vc as U,wc as w,yc as P,zc as v}from"./index-c975k3pk.js";import{Gc as E}from"./index-0s81cfpe.js";import{Lc as p,Nc as g,Oc as L,Pc as x,Qc as S,Rc as O}from"./index-e2dqz3tw.js";import"./index-sv4rzv3f.js";import"./index-c4p1qcnn.js";import"./index-q9dp55wv.js";import"./index-ntj6ymk8.js";import"./index-gb5bnx7a.js";import{promises as R}from"fs";import C from"path";async function M(a){try{let n=await R.readdir(a);if(n.includes("package.json")){try{let i=JSON.parse(await R.readFile(C.join(a,"package.json"),"utf8")),o={...i.dependencies,...i.devDependencies};if(o.react||o["@types/react"])return"react";if(o.vue||o["@vue/cli"])return"vue";if(o.angular||o["@angular/core"])return"angular";if(o.next||o["@types/next"])return"nextjs";if(o.nuxt||o["@nuxt/core"])return"nuxtjs";if(o.svelte||o["@sveltejs/kit"])return"svelte";if(o.express||o.fastify||o.koa)return"nodejs-backend";if(o.electron)return"electron";if(o.vite)return"vite"}catch{}return"nodejs"}if(n.includes("setup.py")||n.includes("requirements.txt")||n.includes("pyproject.toml")||n.includes("Pipfile")){if(n.includes("manage.py"))return"django";if(n.includes("app.py"))return"flask";return"python"}if(n.includes("go.mod"))return"go";if(n.includes("Cargo.toml"))return"rust";if(n.includes("pom.xml"))return"maven";if(n.includes("build.gradle")||n.includes("build.gradle.kts"))return"gradle";if(n.includes("Gemfile"))return"ruby";if(n.includes("composer.json"))return"php";if(n.some((i)=>i.endsWith(".csproj")||i.endsWith(".sln")))return"dotnet";if(n.includes("CMakeLists.txt")||n.includes("Makefile"))return"cpp";if(n.includes("Package.swift"))return"swift";if(n.includes("pubspec.yaml"))return"flutter";if(n.some((i)=>i.endsWith(".tf")))return"terraform";if(n.includes("Dockerfile"))return"docker"}catch{}return}async function V(a){try{let n=["vite.config.ts","vite.config.js"];for(let i of n)try{let t=(await R.readFile(C.join(a,i),"utf-8")).match(/port:\s*(\d+)/);if(t)return parseInt(t[1],10)}catch{}}catch{}return}var Y=new Set([".git","node_modules","__pycache__",".venv","venv","dist","build"]),F=parseInt(process.env.VIBECONTROLS_GIT_SCAN_MAX_DEPTH??"8",10),z=parseInt(process.env.VIBECONTROLS_GIT_SCAN_MAX_DIRECTORIES??"5000",10);async function k(a,n,i,o={visited:0},t=0){let u=[];if(t>F||o.visited>=z)return u;o.visited+=1;try{let e=await N(a);if(e.some((c)=>c.name===".git"&&c.isDirectory())){if(u.push({path:a,name:C.basename(a),parentPath:i,isSubmodule:!!i,projectType:await M(a),vitePort:await V(a)}),!n)return u;i=a}for(let c of e)if(c.isDirectory()&&!c.isSymbolicLink()&&!Y.has(c.name)&&!c.name.startsWith(".")){let s=C.join(a,c.name),$=await k(s,n,i,o,t+1);u.push(...$)}}catch{}return u}function I(a){let{db:n}=a;return new T().get("/",async()=>{return{repositories:await n.getAllGitRepositories()}}).get("/:id",async({params:i,set:o})=>{let t=await n.getGitRepository(i.id);if(!t)return o.status=404,{error:"Repository not found"};return{repository:t}}).post("/scan",async({body:i,set:o})=>{try{let t=(await A(i.directory,{mustExist:!0})).path;if(!(await R.stat(t)).isDirectory())return o.status=400,{error:"Path is not a directory"};let e=await k(t,i.includeSubmodules??!0),m=[];for(let c of e){let s=await n.getGitRepositoryByPath(c.path);if(s)await n.updateGitRepository(s.id,c),m.push({...s,...c});else{let $=await n.createGitRepository({id:globalThis.crypto.randomUUID(),...c});m.push($)}}return{repositories:m,scannedPath:t,totalFound:m.length}}catch(t){return o.status=500,{error:"Failed to scan directory",details:String(t)}}},{body:l.Object({directory:l.String(),includeSubmodules:l.Optional(l.Boolean())})}).put("/:id",async({params:i,body:o,set:t})=>{if(!await n.getGitRepository(i.id))return t.status=404,{error:"Repository not found"};try{return await n.updateGitRepository(i.id,o),{success:!0}}catch(e){return t.status=500,{error:"Failed to update repository",details:String(e)}}},{body:l.Object({name:l.Optional(l.String()),projectType:l.Optional(l.String()),vitePort:l.Optional(l.Number())})}).delete("/:id",async({params:i,set:o})=>{if(!await n.getGitRepository(i.id))return o.status=404,{error:"Repository not found"};try{return await n.deleteGitRepository(i.id),{success:!0}}catch(u){return o.status=500,{error:"Failed to delete repository",details:String(u)}}}).post("/fix-hierarchy",async({set:i})=>{try{let o=await n.fixGitHierarchy(),t=await n.getAllGitRepositories();return{success:!0,fixed:o.fixed,total:t.length}}catch(o){return i.status=500,{error:"Failed to fix hierarchy",details:String(o)}}})}var h="http://localhost:3005";function q(a){let n=a.command("git").description("Manage git repositories");n.command("list").description("List discovered git repositories").option("--agent-url <url>","Agent URL",h).option("--json","Emit JSON").option("--plain","Force plain text output").action(async function(i){let o={...a.opts(),...i};try{let t=p(i),u=encodeURIComponent(g(o));await D({mode:G(o),fetchData:async()=>{return(await L(t,`/api/profiles/${u}/git`)).repositories||[]},plain:(e)=>{if(!e||e.length===0){J("No git repositories found.");return}U("Git Repositories"),P(e.map((m)=>({ID:y(m.id),Name:m.name||"-",Path:m.path||"-",Type:m.type||m.projectType||"-",Submodule:m.isSubmodule?"Yes":"No",Scanned:m.scannedAt?v(m.scannedAt):"-"})))},interactive:async(e)=>{if(!e||e.length===0){U("Git Repositories"),J("No git repositories found.");return}let m=e.map((c)=>({id:String(c.id),label:c.name||y(c.id),hint:c.type||c.projectType||"",detail:[`ID: ${c.id}`,`Name: ${c.name??"-"}`,`Path: ${c.path??"-"}`,`Type: ${c.type??c.projectType??"-"}`,`Submodule: ${c.isSubmodule?"Yes":"No"}`,`Scanned: ${c.scannedAt?v(c.scannedAt):"-"}`].join(`
2
+ import{E as A,G as N}from"./index-6jzsthh9.js";import{Yb as l,Zb as T}from"./index-e0jbxcn1.js";import{nc as G,oc as D,pc as f}from"./index-wj5hx7gq.js";import{Ac as w,Cc as P,Dc as v,Hc as y,uc as d,vc as r,wc as j,yc as J,zc as U}from"./index-6nz3c1ys.js";import{Kc as E}from"./index-sj39bx7y.js";import{Pc as p,Rc as g,Sc as L,Tc as x,Uc as S,Vc as O}from"./index-svtmb9t1.js";import"./index-a9x5swye.js";import"./index-axgp7ryd.js";import"./index-c4zn91z3.js";import"./index-73qwyf9q.js";import"./index-149rjxa5.js";import{promises as R}from"fs";import C from"path";async function M(a){try{let n=await R.readdir(a);if(n.includes("package.json")){try{let i=JSON.parse(await R.readFile(C.join(a,"package.json"),"utf8")),o={...i.dependencies,...i.devDependencies};if(o.react||o["@types/react"])return"react";if(o.vue||o["@vue/cli"])return"vue";if(o.angular||o["@angular/core"])return"angular";if(o.next||o["@types/next"])return"nextjs";if(o.nuxt||o["@nuxt/core"])return"nuxtjs";if(o.svelte||o["@sveltejs/kit"])return"svelte";if(o.express||o.fastify||o.koa)return"nodejs-backend";if(o.electron)return"electron";if(o.vite)return"vite"}catch{}return"nodejs"}if(n.includes("setup.py")||n.includes("requirements.txt")||n.includes("pyproject.toml")||n.includes("Pipfile")){if(n.includes("manage.py"))return"django";if(n.includes("app.py"))return"flask";return"python"}if(n.includes("go.mod"))return"go";if(n.includes("Cargo.toml"))return"rust";if(n.includes("pom.xml"))return"maven";if(n.includes("build.gradle")||n.includes("build.gradle.kts"))return"gradle";if(n.includes("Gemfile"))return"ruby";if(n.includes("composer.json"))return"php";if(n.some((i)=>i.endsWith(".csproj")||i.endsWith(".sln")))return"dotnet";if(n.includes("CMakeLists.txt")||n.includes("Makefile"))return"cpp";if(n.includes("Package.swift"))return"swift";if(n.includes("pubspec.yaml"))return"flutter";if(n.some((i)=>i.endsWith(".tf")))return"terraform";if(n.includes("Dockerfile"))return"docker"}catch{}return}async function V(a){try{let n=["vite.config.ts","vite.config.js"];for(let i of n)try{let t=(await R.readFile(C.join(a,i),"utf-8")).match(/port:\s*(\d+)/);if(t)return parseInt(t[1],10)}catch{}}catch{}return}var Y=new Set([".git","node_modules","__pycache__",".venv","venv","dist","build"]),F=parseInt(process.env.VIBECONTROLS_GIT_SCAN_MAX_DEPTH??"8",10),z=parseInt(process.env.VIBECONTROLS_GIT_SCAN_MAX_DIRECTORIES??"5000",10);async function k(a,n,i,o={visited:0},t=0){let u=[];if(t>F||o.visited>=z)return u;o.visited+=1;try{let e=await N(a);if(e.some((c)=>c.name===".git"&&c.isDirectory())){if(u.push({path:a,name:C.basename(a),parentPath:i,isSubmodule:!!i,projectType:await M(a),vitePort:await V(a)}),!n)return u;i=a}for(let c of e)if(c.isDirectory()&&!c.isSymbolicLink()&&!Y.has(c.name)&&!c.name.startsWith(".")){let s=C.join(a,c.name),$=await k(s,n,i,o,t+1);u.push(...$)}}catch{}return u}function I(a){let{db:n}=a;return new T().get("/",async()=>{return{repositories:await n.getAllGitRepositories()}}).get("/:id",async({params:i,set:o})=>{let t=await n.getGitRepository(i.id);if(!t)return o.status=404,{error:"Repository not found"};return{repository:t}}).post("/scan",async({body:i,set:o})=>{try{let t=(await A(i.directory,{mustExist:!0})).path;if(!(await R.stat(t)).isDirectory())return o.status=400,{error:"Path is not a directory"};let e=await k(t,i.includeSubmodules??!0),m=[];for(let c of e){let s=await n.getGitRepositoryByPath(c.path);if(s)await n.updateGitRepository(s.id,c),m.push({...s,...c});else{let $=await n.createGitRepository({id:globalThis.crypto.randomUUID(),...c});m.push($)}}return{repositories:m,scannedPath:t,totalFound:m.length}}catch(t){return o.status=500,{error:"Failed to scan directory",details:String(t)}}},{body:l.Object({directory:l.String(),includeSubmodules:l.Optional(l.Boolean())})}).put("/:id",async({params:i,body:o,set:t})=>{if(!await n.getGitRepository(i.id))return t.status=404,{error:"Repository not found"};try{return await n.updateGitRepository(i.id,o),{success:!0}}catch(e){return t.status=500,{error:"Failed to update repository",details:String(e)}}},{body:l.Object({name:l.Optional(l.String()),projectType:l.Optional(l.String()),vitePort:l.Optional(l.Number())})}).delete("/:id",async({params:i,set:o})=>{if(!await n.getGitRepository(i.id))return o.status=404,{error:"Repository not found"};try{return await n.deleteGitRepository(i.id),{success:!0}}catch(u){return o.status=500,{error:"Failed to delete repository",details:String(u)}}}).post("/fix-hierarchy",async({set:i})=>{try{let o=await n.fixGitHierarchy(),t=await n.getAllGitRepositories();return{success:!0,fixed:o.fixed,total:t.length}}catch(o){return i.status=500,{error:"Failed to fix hierarchy",details:String(o)}}})}var h="http://localhost:3005";function q(a){let n=a.command("git").description("Manage git repositories");n.command("list").description("List discovered git repositories").option("--agent-url <url>","Agent URL",h).option("--json","Emit JSON").option("--plain","Force plain text output").action(async function(i){let o={...a.opts(),...i};try{let t=p(i),u=encodeURIComponent(g(o));await D({mode:G(o),fetchData:async()=>{return(await L(t,`/api/profiles/${u}/git`)).repositories||[]},plain:(e)=>{if(!e||e.length===0){J("No git repositories found.");return}U("Git Repositories"),P(e.map((m)=>({ID:y(m.id),Name:m.name||"-",Path:m.path||"-",Type:m.type||m.projectType||"-",Submodule:m.isSubmodule?"Yes":"No",Scanned:m.scannedAt?v(m.scannedAt):"-"})))},interactive:async(e)=>{if(!e||e.length===0){U("Git Repositories"),J("No git repositories found.");return}let m=e.map((c)=>({id:String(c.id),label:c.name||y(c.id),hint:c.type||c.projectType||"",detail:[`ID: ${c.id}`,`Name: ${c.name??"-"}`,`Path: ${c.path??"-"}`,`Type: ${c.type??c.projectType??"-"}`,`Submodule: ${c.isSubmodule?"Yes":"No"}`,`Scanned: ${c.scannedAt?v(c.scannedAt):"-"}`].join(`
3
3
  `)}));await E({title:`vibe git list \u2014 ${e.length} repo(s)`,rows:m})},json:(e)=>e.map((m)=>({id:m.id,name:m.name??null,path:m.path??null,type:m.type??m.projectType??null,isSubmodule:!!m.isSubmodule,scannedAt:m.scannedAt??null}))})}catch(t){d(r(t))}}),n.command("scan").description("Scan a directory for git repositories").requiredOption("--dir <directory>","Directory to scan").option("--depth <depth>","Scan depth","3").option("--agent-url <url>","Agent URL",h).option("--json","Emit JSON").action(async function(i){let o={...a.opts(),...i};try{let t=p(i),u=encodeURIComponent(g(o)),e=await x(t,`/api/profiles/${u}/git/scan`,{directory:i.dir,depth:parseInt(i.depth,10)});if(f(o,{ok:!0,found:e?.found??e?.repositories?.length??0}))return;if(j("Git scan completed."),e?.found!==void 0)w("Repositories found",e.found);if(e?.repositories)w("Repositories found",e.repositories.length)}catch(t){if(o.json){f(o,{ok:!1,error:r(t)});return}d(r(t))}}),n.command("update").description("Update a git repository entry").requiredOption("-i, --id <id>","Repository ID").option("--vite-port <port>","Vite dev server port").option("--project-type <type>","Project type").option("--agent-url <url>","Agent URL",h).option("--json","Emit JSON").action(async function(i){let o={...a.opts(),...i};try{let t=p(i),u=encodeURIComponent(g(o)),e={};if(i.vitePort)e.vitePort=parseInt(i.vitePort,10);if(i.projectType)e.projectType=i.projectType;if(await S(t,`/api/profiles/${u}/git/${i.id}`,e),f(o,{ok:!0,id:i.id}))return;j(`Repository ${y(i.id)} updated.`)}catch(t){if(o.json){f(o,{ok:!1,error:r(t)});return}d(r(t))}}),n.command("delete").description("Delete a git repository entry").requiredOption("-i, --id <id>","Repository ID").option("--agent-url <url>","Agent URL",h).option("--json","Emit JSON").action(async function(i){let o={...a.opts(),...i};try{let t=p(i),u=encodeURIComponent(g(o));if(await O(t,`/api/profiles/${u}/git/${i.id}`),f(o,{ok:!0,id:i.id}))return;j(`Repository ${y(i.id)} deleted.`)}catch(t){if(o.json){f(o,{ok:!1,error:r(t)});return}d(r(t))}}),n.command("fix-hierarchy").description("Fix repository parent-child hierarchy").option("--agent-url <url>","Agent URL",h).option("--json","Emit JSON").action(async function(i){let o={...a.opts(),...i};try{let t=p(i),u=encodeURIComponent(g(o)),e=await x(t,`/api/profiles/${u}/git/fix-hierarchy`,{});if(f(o,{ok:!0,fixed:e?.fixed??null}))return;if(j("Hierarchy fix completed."),e?.fixed!==void 0)w("Fixed",e.fixed)}catch(t){if(o.json){f(o,{ok:!1,error:r(t)});return}d(r(t))}})}function H(a,n){q(a)}function eo(a){return{name:"git",version:"2.2.0",description:"Git repository scanning, tracking, and hierarchy management",capabilities:{storage:"rw",subprocess:!0,audit:!0,telemetry:!0},tags:["backend","cli"],cliCommand:"git",apiPrefix:"/api/git",createRoutes:(n)=>I(n),onCliSetup:async(n,i)=>{H(n,i)}}}export{eo as createPlugin};
@@ -1,4 +1,4 @@
1
1
  // @bun
2
- import{Pd as Q}from"./index-c4p1qcnn.js";import{ae as K}from"./index-q9dp55wv.js";import{existsSync as X,mkdirSync as C,readFileSync as G,renameSync as I,writeFileSync as M}from"fs";import{dirname as R,join as U}from"path";var V="prereqs-installed.json",W="prereqs-installed";function Y(q){return U(q??K(),V)}function Z(q){let v=Y(q);if(!X(v))return[];try{let z=JSON.parse(G(v,"utf8"));if(!Array.isArray(z))return[];return z.filter((B)=>!!B&&typeof B==="object"&&typeof B.name==="string"&&typeof B.pluginPackageName==="string")}catch(z){return Q().logger.warn(W,`Failed to read tracker at ${v}: ${z}`),[]}}function x(q,v){let z=Y(v),B=R(z);if(!X(B))C(B,{recursive:!0});let J=`${z}.${process.pid}.tmp`;M(J,`${JSON.stringify(q,null,2)}
2
+ import{Wd as Q}from"./index-axgp7ryd.js";import{he as K}from"./index-c4zn91z3.js";import{existsSync as X,mkdirSync as C,readFileSync as G,renameSync as I,writeFileSync as M}from"fs";import{dirname as R,join as U}from"path";var V="prereqs-installed.json",W="prereqs-installed";function Y(q){return U(q??K(),V)}function Z(q){let v=Y(q);if(!X(v))return[];try{let z=JSON.parse(G(v,"utf8"));if(!Array.isArray(z))return[];return z.filter((B)=>!!B&&typeof B==="object"&&typeof B.name==="string"&&typeof B.pluginPackageName==="string")}catch(z){return Q().logger.warn(W,`Failed to read tracker at ${v}: ${z}`),[]}}function x(q,v){let z=Y(v),B=R(z);if(!X(B))C(B,{recursive:!0});let J=`${z}.${process.pid}.tmp`;M(J,`${JSON.stringify(q,null,2)}
3
3
  `,{encoding:"utf8",mode:384}),I(J,z)}function j(q,v){if(v.length===0)return;let B=Z().filter((H)=>!(H.pluginPackageName===q&&v.some((b)=>b.name===H.name))),J=new Date().toISOString(),$=v.map((H)=>({name:H.name,kind:H.kind,installedAt:J,pluginPackageName:q}));x([...B,...$])}function E(q){return Z(q)}
4
- export{j as K,E as L};
4
+ export{j as O,E as P};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{Xa as R}from"./index-0ckffygp.js";import{bb as j}from"./index-53qthjhb.js";import{Bd as D,Fd as P,Md as g,Pd as M}from"./index-c4p1qcnn.js";import{Zd as y,ae as x,be as A}from"./index-q9dp55wv.js";import{spawn as _}from"child_process";import{createHash as f}from"crypto";import{existsSync as u,promises as V,createWriteStream as h}from"fs";import{homedir as m,tmpdir as p}from"os";import*as q from"path";import{Readable as d}from"stream";import{pipeline as l}from"stream/promises";function n(){let G=process.arch==="x64"?"x64":"arm64";return`${process.platform==="win32"?"win32":process.platform==="darwin"?"darwin":"linux"}-${G}`}function c(){return q.join(m(),".boff","vibecontrols","tools")}function L(G,J){let X=J??G;if(process.platform==="win32"&&!X.toLowerCase().endsWith(".exe"))return`${X}.exe`;return X}function o(G,J,X){return q.join(X??c(),G,L(G,J))}async function E(G,J){if(!J.versionMatcher)return!0;return new Promise((X)=>{let Y=_(G,J.versionArgs??["--version"],{stdio:["ignore","pipe","pipe"]}),K="";Y.stdout.on("data",(H)=>K+=H.toString()),Y.stderr.on("data",(H)=>K+=H.toString()),Y.on("close",()=>{try{X(new RegExp(J.versionMatcher).test(K))}catch{X(!1)}}),Y.on("error",()=>X(!1))})}async function i(G){let J=G.platform??n(),X=L(G.name,G.binaryName),Y=o(G.name,G.binaryName,G.cacheRoot);if(u(Y)&&await E(Y,G))return Y;try{let H=typeof Bun<"u"&&typeof Bun.which==="function"?Bun.which(G.binaryName??G.name,{PATH:process.env.PATH}):null;if(H&&await E(H,G))return G.log?.info?.(`[install] using PATH binary ${G.name} (${H})`),H}catch{}let K=G.downloads[J];if(!K)throw Error(`[install] no download manifest entry for ${G.name} on ${J}`);return G.log?.info?.(`[install] downloading ${G.name} for ${J}`),await V.mkdir(q.dirname(Y),{recursive:!0}),await a(K,Y,X,G.name),G.log?.info?.(`[install] installed ${G.name} \u2192 ${Y}`),Y}async function a(G,J,X,Y){let K=q.dirname(J),H=q.join(p(),`vibe-install-${Y}-${process.pid}`);await V.mkdir(H,{recursive:!0});let $=q.join(H,"artifact");try{let Z=await fetch(G.url,{redirect:"follow"});if(!Z.ok)throw Error(`download failed (${Z.status}) for ${G.url}`);if(!Z.body)throw Error(`empty response body for ${G.url}`);if(await l(d.fromWeb(Z.body),h($)),G.sha256){let I=f("sha256").update(await V.readFile($)).digest("hex");if(I!==G.sha256)throw Error(`sha256 mismatch for ${Y}: expected ${G.sha256}, got ${I}`)}let z=G.archive??(G.url.endsWith(".tar.gz")||G.url.endsWith(".tgz")?"tar.gz":G.url.endsWith(".zip")?"zip":"raw");if(z==="raw")await V.copyFile($,J);else{if(z==="tar.gz")await w("tar",["-xzf",$,"-C",H]);else await s($,H);let I=G.binaryWithinArchive??X;await V.copyFile(q.join(H,I),J)}if(process.platform!=="win32")await V.chmod(J,493)}finally{await V.rm(H,{recursive:!0,force:!0})}}async function s(G,J){try{await w("unzip",["-q","-o",G,"-d",J]);return}catch(X){if(process.platform!=="win32")throw X;await w("tar",["-xf",G,"-C",J])}}async function w(G,J){return new Promise((X,Y)=>{let K=_(G,J,{stdio:["ignore","ignore","pipe"]}),H="";K.stderr.on("data",($)=>H+=$.toString()),K.on("close",($)=>$===0?X():Y(Error(`${G} exit ${$}: ${H}`))),K.on("error",Y)})}var W="https://github.com/cloudflare/cloudflared/releases/latest/download",r={"linux-x64":{url:`${W}/cloudflared-linux-amd64`,archive:"raw"},"linux-arm64":{url:`${W}/cloudflared-linux-arm64`,archive:"raw"},"darwin-x64":{url:`${W}/cloudflared-darwin-amd64.tgz`,archive:"tar.gz",binaryWithinArchive:"cloudflared"},"darwin-arm64":{url:`${W}/cloudflared-darwin-arm64.tgz`,archive:"tar.gz",binaryWithinArchive:"cloudflared"},"win32-x64":{url:`${W}/cloudflared-windows-amd64.exe`,archive:"raw"},"win32-arm64":{url:`${W}/cloudflared-windows-arm64.exe`,archive:"raw"}},t=/(https:\/\/(?!api\.)[a-zA-Z0-9-]+\.trycloudflare\.com)/;async function N(G,J){let X=J?.log??{},Y;try{Y=await i({name:"cloudflared",downloads:r,versionMatcher:"cloudflared version",log:X})}catch($){return X.warn?.(`quick-tunnel: could not obtain cloudflared: ${String($)}`),null}let K;try{K=_(Y,["tunnel","--url",`http://127.0.0.1:${G}`,"--no-autoupdate"],{stdio:["ignore","pipe","pipe"]})}catch($){return X.warn?.(`quick-tunnel: failed to spawn cloudflared: ${String($)}`),null}let H=await new Promise(($)=>{let Z=!1,z=(Q)=>{if(Z)return;Z=!0,$(Q)},I=setTimeout(()=>{X.warn?.("quick-tunnel: cloudflared did not advertise a URL in time"),z(null)},J?.timeoutMs??30000),O=(Q)=>{let B=Q.toString("utf8").match(t);if(B)clearTimeout(I),z(B[0])};K.stdout?.on("data",O),K.stderr?.on("data",O),K.on("error",(Q)=>{clearTimeout(I),X.warn?.(`quick-tunnel: cloudflared failed to spawn: ${String(Q)}`),z(null)}),K.on("exit",(Q)=>{clearTimeout(I),X.warn?.(`quick-tunnel: cloudflared exited (code=${Q})`),z(null)})});if(!H)return null;return{url:H,child:K}}import{existsSync as b,mkdirSync as e,readFileSync as GG,writeFileSync as JG,unlinkSync as XG}from"fs";import{dirname as YG,join as S}from"path";import{readdirSync as $G}from"fs";function T(G){return S(G??x(),"tunnel.state.json")}function v(G,J){let X=T(J);try{e(YG(X),{recursive:!0}),JG(X,JSON.stringify(G,null,2),"utf8")}catch(Y){M().logger.warn("tunnel-state","Failed to persist tunnel state",{error:String(Y)})}}function k(G){let J=T(G);if(!b(J))return null;try{let X=GG(J,"utf8"),Y=JSON.parse(X);if(typeof Y.pid!=="number")return null;return Y}catch(X){return M().logger.warn("tunnel-state","Failed to read tunnel state",{error:String(X)}),null}}function F(G){let J=T(G);if(!b(J))return;try{XG(J)}catch{}}function C(G){return R().isProcessAlive(G)}function xG(G){let J=[];if(G?.allProfiles){let Y;try{Y=A()}catch{return J}let K;try{K=$G(Y)}catch{return J}for(let H of K){let $=S(Y,H),Z=k($);if(Z)J.push({...Z,alive:C(Z.pid),profileDir:$})}return J}let X=k();if(X)J.push({...X,alive:C(X.pid),profileDir:x()});return J}function HG(G){return G.replace(/[^A-Za-z0-9_]/g,"_")}function U(){return(g()??M()).tunnel}async function AG(G,J){let X=U();MG(G),KG();let Y=process.env.AGENT_TUNNEL_URL;if(Y){let $=P(Y);if(!$)return M().logger.warn("tunnel-bootstrap","Ignoring invalid AGENT_TUNNEL_URL"),null;X.url=$,X.externalUrl=!0,M().logger.info("tunnel-bootstrap",`Using AGENT_TUNNEL_URL=${$}`);try{j.emit("tunnel.url_assigned",{provider:"external"})}catch{}return $}let K=J.port,H=await N(K,{log:{info:($)=>M().logger.info("tunnel-bootstrap",$),warn:($)=>M().logger.warn("tunnel-bootstrap",$)}});if(!H)return M().logger.warn("tunnel-bootstrap","No bootstrap tunnel \u2014 the agent will register once the tunnel provider starts post-config"),null;if(X.child=H.child,X.url=H.url,X.url){M().logger.info("tunnel-bootstrap",`Bootstrap tunnel ready: ${X.url}`);try{let z=new URL(X.url).hostname.split(".");if(z.length>=2)D("."+z.slice(-2).join("."))}catch{}try{j.emit("tunnel.url_assigned",{provider:"bootstrap"})}catch{}let $=HG(y());if(process.env[`AGENT_TUNNEL_URL_${$}`]=X.url,X.child?.pid!==void 0)process.env[`AGENT_TUNNEL_PID_${$}`]=String(X.child.pid),v({pid:X.child.pid,url:X.url,startedAt:new Date().toISOString(),provider:"bootstrap",port:K,cmd:`cloudflared tunnel --url http://127.0.0.1:${K}`})}return X.url}function bG(){let G=U();if(G.externalUrl)return!1;if(!G.child||G.child.killed)return!1;let J=G.child.pid;if(J===void 0)return!1;try{process.kill(J,0)}catch{return!1}return G.child=null,F(),M().logger.info("tunnel-bootstrap",`Handed over bootstrap tunnel (PID ${J}) to plugin \u2014 process kept alive`),!0}function SG(){let G=U();if(G.externalUrl){F();return}let J=G.child;if(G.child=null,F(),!J||J.killed)return;try{J.kill("SIGTERM"),M().logger.info("tunnel-bootstrap","Bootstrap tunnel stopped")}catch{}}function vG(){return U().url}function KG(){let G=k();if(!G)return;if(!C(G.pid)){F();return}try{process.kill(G.pid,"SIGTERM"),M().logger.info("tunnel-bootstrap","Reaped orphan tunnel from prior run",{pid:G.pid,provider:G.provider})}catch{}let J=Date.now();while(Date.now()-J<2000&&C(G.pid))Bun.sleepSync(50);if(C(G.pid))try{process.kill(G.pid,"SIGKILL")}catch{}F()}function MG(G){let J={name:"bootstrap",async getActiveTunnelUrl(){return U().url}};G.registerProvider("tunnel",J,"bootstrap")}
3
- export{k as la,F as ma,C as na,xG as oa,HG as pa,AG as qa,bG as ra,SG as sa,vG as ta,KG as ua};
2
+ import{$a as R}from"./index-ea42kfvk.js";import{fb as j}from"./index-at6z8tds.js";import{Id as D,Md as P,Td as g,Wd as M}from"./index-axgp7ryd.js";import{ee as y,he as x,ie as A}from"./index-c4zn91z3.js";import{spawn as _}from"child_process";import{createHash as f}from"crypto";import{existsSync as u,promises as V,createWriteStream as h}from"fs";import{homedir as m,tmpdir as p}from"os";import*as q from"path";import{Readable as d}from"stream";import{pipeline as l}from"stream/promises";function n(){let G=process.arch==="x64"?"x64":"arm64";return`${process.platform==="win32"?"win32":process.platform==="darwin"?"darwin":"linux"}-${G}`}function c(){return q.join(m(),".boff","vibecontrols","tools")}function L(G,J){let X=J??G;if(process.platform==="win32"&&!X.toLowerCase().endsWith(".exe"))return`${X}.exe`;return X}function o(G,J,X){return q.join(X??c(),G,L(G,J))}async function E(G,J){if(!J.versionMatcher)return!0;return new Promise((X)=>{let Y=_(G,J.versionArgs??["--version"],{stdio:["ignore","pipe","pipe"]}),K="";Y.stdout.on("data",(H)=>K+=H.toString()),Y.stderr.on("data",(H)=>K+=H.toString()),Y.on("close",()=>{try{X(new RegExp(J.versionMatcher).test(K))}catch{X(!1)}}),Y.on("error",()=>X(!1))})}async function i(G){let J=G.platform??n(),X=L(G.name,G.binaryName),Y=o(G.name,G.binaryName,G.cacheRoot);if(u(Y)&&await E(Y,G))return Y;try{let H=typeof Bun<"u"&&typeof Bun.which==="function"?Bun.which(G.binaryName??G.name,{PATH:process.env.PATH}):null;if(H&&await E(H,G))return G.log?.info?.(`[install] using PATH binary ${G.name} (${H})`),H}catch{}let K=G.downloads[J];if(!K)throw Error(`[install] no download manifest entry for ${G.name} on ${J}`);return G.log?.info?.(`[install] downloading ${G.name} for ${J}`),await V.mkdir(q.dirname(Y),{recursive:!0}),await a(K,Y,X,G.name),G.log?.info?.(`[install] installed ${G.name} \u2192 ${Y}`),Y}async function a(G,J,X,Y){let K=q.dirname(J),H=q.join(p(),`vibe-install-${Y}-${process.pid}`);await V.mkdir(H,{recursive:!0});let $=q.join(H,"artifact");try{let Z=await fetch(G.url,{redirect:"follow"});if(!Z.ok)throw Error(`download failed (${Z.status}) for ${G.url}`);if(!Z.body)throw Error(`empty response body for ${G.url}`);if(await l(d.fromWeb(Z.body),h($)),G.sha256){let I=f("sha256").update(await V.readFile($)).digest("hex");if(I!==G.sha256)throw Error(`sha256 mismatch for ${Y}: expected ${G.sha256}, got ${I}`)}let z=G.archive??(G.url.endsWith(".tar.gz")||G.url.endsWith(".tgz")?"tar.gz":G.url.endsWith(".zip")?"zip":"raw");if(z==="raw")await V.copyFile($,J);else{if(z==="tar.gz")await w("tar",["-xzf",$,"-C",H]);else await s($,H);let I=G.binaryWithinArchive??X;await V.copyFile(q.join(H,I),J)}if(process.platform!=="win32")await V.chmod(J,493)}finally{await V.rm(H,{recursive:!0,force:!0})}}async function s(G,J){try{await w("unzip",["-q","-o",G,"-d",J]);return}catch(X){if(process.platform!=="win32")throw X;await w("tar",["-xf",G,"-C",J])}}async function w(G,J){return new Promise((X,Y)=>{let K=_(G,J,{stdio:["ignore","ignore","pipe"]}),H="";K.stderr.on("data",($)=>H+=$.toString()),K.on("close",($)=>$===0?X():Y(Error(`${G} exit ${$}: ${H}`))),K.on("error",Y)})}var W="https://github.com/cloudflare/cloudflared/releases/latest/download",r={"linux-x64":{url:`${W}/cloudflared-linux-amd64`,archive:"raw"},"linux-arm64":{url:`${W}/cloudflared-linux-arm64`,archive:"raw"},"darwin-x64":{url:`${W}/cloudflared-darwin-amd64.tgz`,archive:"tar.gz",binaryWithinArchive:"cloudflared"},"darwin-arm64":{url:`${W}/cloudflared-darwin-arm64.tgz`,archive:"tar.gz",binaryWithinArchive:"cloudflared"},"win32-x64":{url:`${W}/cloudflared-windows-amd64.exe`,archive:"raw"},"win32-arm64":{url:`${W}/cloudflared-windows-arm64.exe`,archive:"raw"}},t=/(https:\/\/(?!api\.)[a-zA-Z0-9-]+\.trycloudflare\.com)/;async function N(G,J){let X=J?.log??{},Y;try{Y=await i({name:"cloudflared",downloads:r,versionMatcher:"cloudflared version",log:X})}catch($){return X.warn?.(`quick-tunnel: could not obtain cloudflared: ${String($)}`),null}let K;try{K=_(Y,["tunnel","--url",`http://127.0.0.1:${G}`,"--no-autoupdate"],{stdio:["ignore","pipe","pipe"]})}catch($){return X.warn?.(`quick-tunnel: failed to spawn cloudflared: ${String($)}`),null}let H=await new Promise(($)=>{let Z=!1,z=(Q)=>{if(Z)return;Z=!0,$(Q)},I=setTimeout(()=>{X.warn?.("quick-tunnel: cloudflared did not advertise a URL in time"),z(null)},J?.timeoutMs??30000),O=(Q)=>{let B=Q.toString("utf8").match(t);if(B)clearTimeout(I),z(B[0])};K.stdout?.on("data",O),K.stderr?.on("data",O),K.on("error",(Q)=>{clearTimeout(I),X.warn?.(`quick-tunnel: cloudflared failed to spawn: ${String(Q)}`),z(null)}),K.on("exit",(Q)=>{clearTimeout(I),X.warn?.(`quick-tunnel: cloudflared exited (code=${Q})`),z(null)})});if(!H)return null;return{url:H,child:K}}import{existsSync as b,mkdirSync as e,readFileSync as GG,writeFileSync as JG,unlinkSync as XG}from"fs";import{dirname as YG,join as S}from"path";import{readdirSync as $G}from"fs";function T(G){return S(G??x(),"tunnel.state.json")}function v(G,J){let X=T(J);try{e(YG(X),{recursive:!0}),JG(X,JSON.stringify(G,null,2),"utf8")}catch(Y){M().logger.warn("tunnel-state","Failed to persist tunnel state",{error:String(Y)})}}function k(G){let J=T(G);if(!b(J))return null;try{let X=GG(J,"utf8"),Y=JSON.parse(X);if(typeof Y.pid!=="number")return null;return Y}catch(X){return M().logger.warn("tunnel-state","Failed to read tunnel state",{error:String(X)}),null}}function F(G){let J=T(G);if(!b(J))return;try{XG(J)}catch{}}function C(G){return R().isProcessAlive(G)}function xG(G){let J=[];if(G?.allProfiles){let Y;try{Y=A()}catch{return J}let K;try{K=$G(Y)}catch{return J}for(let H of K){let $=S(Y,H),Z=k($);if(Z)J.push({...Z,alive:C(Z.pid),profileDir:$})}return J}let X=k();if(X)J.push({...X,alive:C(X.pid),profileDir:x()});return J}function HG(G){return G.replace(/[^A-Za-z0-9_]/g,"_")}function U(){return(g()??M()).tunnel}async function AG(G,J){let X=U();MG(G),KG();let Y=process.env.AGENT_TUNNEL_URL;if(Y){let $=P(Y);if(!$)return M().logger.warn("tunnel-bootstrap","Ignoring invalid AGENT_TUNNEL_URL"),null;X.url=$,X.externalUrl=!0,M().logger.info("tunnel-bootstrap",`Using AGENT_TUNNEL_URL=${$}`);try{j.emit("tunnel.url_assigned",{provider:"external"})}catch{}return $}let K=J.port,H=await N(K,{log:{info:($)=>M().logger.info("tunnel-bootstrap",$),warn:($)=>M().logger.warn("tunnel-bootstrap",$)}});if(!H)return M().logger.warn("tunnel-bootstrap","No bootstrap tunnel \u2014 the agent will register once the tunnel provider starts post-config"),null;if(X.child=H.child,X.url=H.url,X.url){M().logger.info("tunnel-bootstrap",`Bootstrap tunnel ready: ${X.url}`);try{let z=new URL(X.url).hostname.split(".");if(z.length>=2)D("."+z.slice(-2).join("."))}catch{}try{j.emit("tunnel.url_assigned",{provider:"bootstrap"})}catch{}let $=HG(y());if(process.env[`AGENT_TUNNEL_URL_${$}`]=X.url,X.child?.pid!==void 0)process.env[`AGENT_TUNNEL_PID_${$}`]=String(X.child.pid),v({pid:X.child.pid,url:X.url,startedAt:new Date().toISOString(),provider:"bootstrap",port:K,cmd:`cloudflared tunnel --url http://127.0.0.1:${K}`})}return X.url}function bG(){let G=U();if(G.externalUrl)return!1;if(!G.child||G.child.killed)return!1;let J=G.child.pid;if(J===void 0)return!1;try{process.kill(J,0)}catch{return!1}return G.child=null,F(),M().logger.info("tunnel-bootstrap",`Handed over bootstrap tunnel (PID ${J}) to plugin \u2014 process kept alive`),!0}function SG(){let G=U();if(G.externalUrl){F();return}let J=G.child;if(G.child=null,F(),!J||J.killed)return;try{J.kill("SIGTERM"),M().logger.info("tunnel-bootstrap","Bootstrap tunnel stopped")}catch{}}function vG(){return U().url}function KG(){let G=k();if(!G)return;if(!C(G.pid)){F();return}try{process.kill(G.pid,"SIGTERM"),M().logger.info("tunnel-bootstrap","Reaped orphan tunnel from prior run",{pid:G.pid,provider:G.provider})}catch{}let J=Date.now();while(Date.now()-J<2000&&C(G.pid))Bun.sleepSync(50);if(C(G.pid))try{process.kill(G.pid,"SIGKILL")}catch{}F()}function MG(G){let J={name:"bootstrap",async getActiveTunnelUrl(){return U().url}};G.registerProvider("tunnel",J,"bootstrap")}
3
+ export{k as pa,F as qa,C as ra,xG as sa,HG as ta,AG as ua,bG as va,SG as wa,vG as xa,KG as ya};
@@ -0,0 +1,11 @@
1
+ // @bun
2
+ import{Wd as s}from"./index-axgp7ryd.js";import{Zd as K,ee as wq,he as Oq,ke as j}from"./index-c4zn91z3.js";import{existsSync as G,mkdirSync as k,readdirSync as cq,readFileSync as b,renameSync as _,rmSync as sq,writeFileSync as D}from"fs";import{dirname as I,join as h}from"path";import{randomUUID as rq}from"crypto";import{existsSync as w,mkdirSync as o,readFileSync as Xq,renameSync as Hq,unlinkSync as Fq,writeFileSync as A}from"fs";import{dirname as m,join as V}from"path";import{spawnSync as a}from"child_process";import{hostname as Nq,networkInterfaces as Aq,platform as Yq,userInfo as Rq}from"os";import{createCipheriv as Pq,createDecipheriv as xq,pbkdf2Sync as uq,randomBytes as kq}from"crypto";var t="secrets:fallback",Wq="secrets:index",e=10,_q=100,qq=new Map;function jq(q,Q){let $=`${q}:${Q}`,z=(qq.get($)??0)+1;if(qq.set($,z),z<=e)return!0;return(z-e)%_q===0}var N="vibecontrols-agent",Gq=".libsecret-install-attempted",Vq="secrets.json";function Iq(){return globalThis.Bun?.secrets??null}class d{api;kind="bun-secrets";constructor(q){this.api=q}async get(q){return this.api.get({service:N,name:q})}async set(q,Q){await this.api.set({service:N,name:q,value:Q}),await gq(q)}async delete(q){let Q=await this.api.delete({service:N,name:q});return await mq(q),Q}async list(q){return dq(q)}}var Kq=".secrets-encrypted-v1",hq=1e5,vq=32,fq="sha256",C=null,Qq=null;function yq(){let q=Aq();for(let Q of Object.values(q)){if(!Q)continue;for(let $ of Q){let z=$?.mac;if(z&&z!=="00:00:00:00:00:00")return z}}return"no-mac"}function $q(){if(Qq!==null)return Qq;let q;try{q=Rq().username||"unknown"}catch{q=process.env.USER||process.env.USERNAME||"unknown"}return`${Nq()}|${q}|${yq()}`}function Uq(){if(C)return C;let q=`vibecontrols-agent::${$q()}`;return C=uq(q,$q(),hq,vq,fq),C}function zq(q){let Q=kq(12),$=Pq("aes-256-gcm",Uq(),Q),z=Buffer.concat([$.update(q,"utf8"),$.final()]),Z=$.getAuthTag();return`${Q.toString("hex")}:${Z.toString("hex")}:${z.toString("hex")}`}function Eq(q){let Q=q.split(":");if(Q.length!==3)return!1;let[$,z,Z]=Q;return/^[0-9a-f]+$/i.test($)&&$.length===24&&/^[0-9a-f]+$/i.test(z)&&z.length===32&&/^[0-9a-f]*$/i.test(Z)}function Sq(q){if(!Eq(q))return null;try{let[Q,$,z]=q.split(":"),Z=xq("aes-256-gcm",Uq(),Buffer.from(Q,"hex"));return Z.setAuthTag(Buffer.from($,"hex")),Buffer.concat([Z.update(Buffer.from(z,"hex")),Z.final()]).toString("utf8")}catch{return null}}class Mq{kind="json-fallback";path;constructor(){this.path=V(j(),Vq)}async get(q){let{plain:Q}=this.readWithMigration(),$=Q[q];return typeof $==="string"?$:null}async set(q,Q){await K(t,async()=>{let{encrypted:$}=this.readWithMigration();$[q]=zq(Q),this.writeEncrypted($)})}async delete(q){return K(t,async()=>{let{encrypted:Q}=this.readWithMigration();if(!(q in Q))return!1;return delete Q[q],this.writeEncrypted(Q),!0})}async list(q){let{encrypted:Q}=this.readWithMigration(),$=Object.keys(Q);return(q?$.filter((Z)=>Z.startsWith(q)):$).sort().map((Z)=>({name:Z}))}readWithMigration(){if(!w(this.path))return{encrypted:{},plain:{}};let q;try{q=Xq(this.path,"utf8")}catch{return{encrypted:{},plain:{}}}let Q;try{Q=JSON.parse(q)}catch{return{encrypted:{},plain:{}}}if(!Q||typeof Q!=="object"||Array.isArray(Q))return{encrypted:{},plain:{}};let $={},z={},Z=!1;for(let[J,X]of Object.entries(Q)){if(typeof X!=="string")continue;let W=Sq(X);if(W!==null){$[J]=X,z[J]=W;continue}$[J]=zq(X),z[J]=X,Z=!0}if(Z)try{this.writeEncrypted($),this.writeMarker()}catch{}return{encrypted:$,plain:z}}writeEncrypted(q){o(m(this.path),{recursive:!0});let Q=`${this.path}.${process.pid}.tmp`;if(A(Q,`${JSON.stringify(q,null,2)}
3
+ `,{mode:384}),Hq(Q,this.path),!w(this.markerPath()))this.writeMarker()}markerPath(){return V(m(this.path),Kq)}writeMarker(){try{A(this.markerPath(),`${new Date().toISOString()}
4
+ `,{mode:384})}catch{}}}var lq=".secrets-index.json";function p(){return V(j(),lq)}function c(){let q=p();if(!w(q))return new Set;try{let Q=Xq(q,"utf8"),$=JSON.parse(Q);if(Array.isArray($))return new Set($.filter((z)=>typeof z==="string"))}catch{}return new Set}function Bq(q){let Q=p();o(m(Q),{recursive:!0});let $=`${Q}.${process.pid}.tmp`;A($,`${JSON.stringify([...q].sort(),null,2)}
5
+ `,{mode:384}),Hq($,Q)}async function gq(q){await K(Wq,()=>{let Q=c();if(Q.has(q))return;Q.add(q),Bq(Q)})}async function mq(q){await K(Wq,()=>{let Q=c();if(!Q.delete(q))return;Bq(Q)})}function dq(q){let $=[...c()];return(q?$.filter((Z)=>Z.startsWith(q)):$).sort().map((Z)=>({name:Z}))}function oq(){if(Yq()!=="linux")return{ok:!1};if(process.env.CI==="true")return{ok:!1,warning:"CI/test environment detected; using JSON fallback"};if(process.env.VIBE_SKIP_LIBSECRET_INSTALL==="1")return{ok:!1,warning:"VIBE_SKIP_LIBSECRET_INSTALL=1 set; using JSON fallback"};let q=j(),Q=V(q,Gq);if(w(Q))return{ok:!1,warning:"previous attempt failed; not retrying"};try{o(q,{recursive:!0}),A(Q,`${new Date().toISOString()}
6
+ `,{mode:384})}catch{return{ok:!1,warning:"could not write install marker"}}let $=[{check:["sh","-c","command -v apt-get"],install:["sudo","-n","apt-get","install","-y","libsecret-1-0"]},{check:["sh","-c","command -v dnf"],install:["sudo","-n","dnf","install","-y","libsecret"]},{check:["sh","-c","command -v pacman"],install:["sudo","-n","pacman","-S","--noconfirm","libsecret"]}];for(let z of $){if(a(z.check[0],z.check.slice(1),{stdio:["ignore","pipe","pipe"]}).status!==0)continue;let J=a(z.install[0],z.install.slice(1),{stdio:["ignore","pipe","pipe"]});if(J.status===0)return{ok:!0};return{ok:!1,warning:`auto-install via '${z.install.join(" ")}' failed (exit ${J.status??"unknown"})`}}return{ok:!1,warning:"no supported package manager found"}}var l=null,g=null,Zq=null;async function Jq(q){try{return await q.get({service:N,name:"__probe__"}),!0}catch{return!1}}async function pq(){if(Zq)return Zq;let q=Iq();if(q&&await Jq(q))return new d(q);if(Yq()==="linux"&&q){let Q=oq();if(Q.ok&&await Jq(q))return new d(q);if(Q.warning)console.warn(`[secrets] libsecret unavailable (${Q.warning}); using JSON fallback`);else console.warn("[secrets] Bun.secrets unavailable; using JSON fallback. Install libsecret-1-0 (apt) / libsecret (dnf/pacman) for OS keychain support.")}else if(!q)console.warn("[secrets] Bun.secrets API not present in this runtime; using JSON fallback.");return new Mq}async function R(){if(l)return l;if(!g)g=pq().then((q)=>{return l=q,q});return g}async function P(q){let $=await(await R()).get(q);if(jq("read",q))s().audit.emit("agent","secret.read",{name:q,hit:$!==null});return $}async function x(q,Q){if(await(await R()).set(q,Q),jq("written",q))s().audit.emit("agent","secret.written",{name:q,valueLen:Q.length})}async function wQ(){let q=await R(),Q=(await q.list()).map(($)=>$.name);return{count:Q.length,backend:Q.length===0?"none":q.kind,names:Q}}async function OQ(){let q=await R(),$=(await q.list()).map((z)=>z.name);for(let z of $)try{await q.delete(z)}catch{}if(q.kind==="bun-secrets")F(p()),F(V(j(),Gq));else if(q.kind==="json-fallback"){let z=j();F(V(z,Vq)),F(V(z,Kq))}return{count:$.length,backend:$.length===0?"none":q.kind,names:$}}function F(q){try{if(w(q))Fq(q)}catch{}}function iq(q){return`agent-config:${q}`}var L=["clientId","clientSecret","gatewayClientId","gatewayClientSecret","static-api-key"];function Tq(q){return L.includes(q)}function B(q,Q){return`${q}:${Q}`}function v(){try{return wq()}catch{return"default"}}var M=1,nq=[],f={globalGatewayUrl:"https://graphql.burdenoff.com/global/graphql",workspaceGatewayUrl:"https://graphqlworkspaces.burdenoff.com/workspaces/graphql"},aq={globalGatewayUrl:"https://alphagraphql.burdenoff.com/global/graphql",workspaceGatewayUrl:"https://alphagraphqlworkspaces.burdenoff.com/workspaces/graphql"},tq={globalGatewayUrl:"http://localhost:4000/global/graphql",workspaceGatewayUrl:"http://localhost:4003/workspaces/graphql"},bq={default:{...f}},AQ={local:{...tq},alpha:{...aq},prod:{...f}},T="default",Dq=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;function y(q){if(!Dq.test(q))throw Error("Profile name must use 1-64 characters: letters, numbers, dot, underscore, or dash.");return q}function Lq(){return h(j(),"profiles")}function r(){return h(j(),"active")}function E(q){return h(Lq(),`${y(q)}.json`)}function eq(){let q=r();if(!G(q))return T;try{let Q=b(q,"utf8").trim();if(!Q)return T;return y(Q)}catch{return T}}function qQ(q){let Q=y(q),$=r();k(I($),{recursive:!0});let z=`${$}.${process.pid}.tmp`;D(z,`${Q}
7
+ `,{mode:384}),_(z,$)}function RQ(){let q=Lq();if(!G(q))return[];return cq(q,{withFileTypes:!0}).filter((Q)=>Q.isFile()&&Q.name.endsWith(".json")).map((Q)=>Q.name.slice(0,-5)).filter((Q)=>Dq.test(Q)).sort()}function QQ(q){let Q=E(q);if(!G(Q))return{};try{return S(b(Q,"utf8"))}catch{return{}}}function $Q(q,Q){let $=y(q),z=E($);k(I(z),{recursive:!0});let Z={schemaVersion:M,...Q},J={...Z};for(let W of L){let H=J[W];if(typeof H==="string"&&H.length>0)x(B($,W),H).catch(()=>{});delete J[W]}let X=`${z}.${process.pid}.tmp`;return D(X,`${JSON.stringify(J,null,2)}
8
+ `,{mode:384}),_(X,z),Z}function PQ(q){let Q=E(q);if(!G(Q))return!1;return sq(Q,{force:!0}),!0}function zQ(q,Q={}){let $=bq[q];return{schemaVersion:M,globalGatewayUrl:$.globalGatewayUrl,workspaceGatewayUrl:$.workspaceGatewayUrl,...Q}}function ZQ(){let q={created:[],activeWritten:null};for(let Q of Object.keys(bq))if(!G(E(Q)))$Q(Q,zQ(Q)),q.created.push(Q);if(!G(r()))qQ(T),q.activeWritten=T;return q}function JQ(){return{...f}}function i(q){let Q=q?.dir??Oq();return h(Q,"config.json")}function XQ(){return{...f}}function xQ(q={}){let Q=JQ();return{schemaVersion:M,globalGatewayUrl:Q.globalGatewayUrl,workspaceGatewayUrl:Q.workspaceGatewayUrl,...q}}function S(q){try{let Q=JSON.parse(q);if(Q&&typeof Q==="object")return Q}catch{}return{}}function n(q){let Q=i(q);if(!G(Q))return{};let $;try{$=S(b(Q,"utf8"))}catch{return{}}if(($.schemaVersion??0)>=M)return $;for(let Z of nq){if(Z.from<($.schemaVersion??0))continue;$=Z.apply($),$.schemaVersion=Z.to}if($.schemaVersion!==M)$.schemaVersion=M;try{D(Q,JSON.stringify($,null,2),{mode:384})}catch{}return $}function uQ(q){let Q=n(q);if(Q.agentInstanceId)return Q.agentInstanceId;let $=rq();return HQ({agentInstanceId:$},q),$}function HQ(q,Q){let $=i(Q);k(I($),{recursive:!0});let z=G($)?S(b($,"utf8")):{},Z={...z},J={...z};for(let H of L)delete J[H];let X=Q?.scope??v();for(let[H,Y]of Object.entries(q)){if(Y===void 0||Y==="")continue;if(Z[H]=Y,Tq(H)&&typeof Y==="string"){x(B(X,H),Y).catch(()=>{});continue}J[H]=Y}let W=`${$}.${process.pid}.tmp`;return D(W,`${JSON.stringify(J,null,2)}
9
+ `,{mode:384}),_(W,$),Z}async function kQ(q,Q){let $=i(Q);return K(iq($),async()=>{k(I($),{recursive:!0});let z=G($)?S(b($,"utf8")):{},Z={...z},J={...z};for(let Y of L)delete J[Y];let X=Q?.scope??v(),W=[];for(let[Y,U]of Object.entries(q)){if(U===void 0||U==="")continue;if(Z[Y]=U,Tq(Y)&&typeof U==="string"){W.push(x(B(X,Y),U));continue}J[Y]=U}await Promise.all(W);let H=`${$}.${process.pid}.tmp`;return D(H,`${JSON.stringify(J,null,2)}
10
+ `,{mode:384}),_(H,$),Z})}async function _Q(q){let Q=n(q?{dir:q.dir}:void 0),$=q?.scope??v();for(let z of L){if(Q[z])continue;try{let Z=await P(B($,z));if(Z)Q[z]=Z}catch(Z){if(q?.strict)throw Z}}return Q}function YQ(){return QQ(eq())}function O(q){if(!q)return null;try{return new URL(q).origin}catch{return null}}function IQ(q,Q){if(!q.clientId)return null;let $=Cq(q,Q);if(!$.length)return null;return`This agent is already paired with ${u(q)}. Refusing a credential push from ${u(Q)} (${$.join("; ")}): it would overwrite the only credential slot and strand the existing pairing on 401. Re-send with "force": true to repair deliberately, or run the other environment under its own profile (VIBECONTROLS_PROFILE).`}function u(q){return`${O(q.globalGatewayUrl)??"unknown gateway"} (workspace ${q.workspaceId??"unknown"})`}function Cq(q,Q){let $=[],z=O(q.globalGatewayUrl),Z=O(Q.globalGatewayUrl);if(z&&Z&&z!==Z)$.push(`global gateway ${z} -> ${Z}`);let J=O(q.workspaceGatewayUrl),X=O(Q.workspaceGatewayUrl);if(J&&X&&J!==X)$.push(`workspace gateway ${J} -> ${X}`);if(q.workspaceId&&Q.workspaceId&&q.workspaceId!==Q.workspaceId)$.push(`workspace ${q.workspaceId} -> ${Q.workspaceId}`);return $}function hQ(q,Q){if(!q.clientId)return null;let $=Cq(q,Q);if(!$.length)return null;return`Credentials were issued for ${u(q)} but this agent is configured for ${u(Q)} (${$.join("; ")}). `+"They cannot authenticate there \u2014 re-pair the agent from the environment "+"it should belong to, or clear the conflicting environment override (VIBE_GLOBAL_GATEWAY_URL / VIBE_WORKSPACE_GATEWAY_URL / VIBE_WORKSPACE_ID)."}function vQ(){try{ZQ()}catch{}let q=YQ(),Q=n(),$={...q,...Q},z=(J,X)=>{if(!process.env[J]&&X)process.env[J]=X};z("VIBE_WORKSPACE_ID",$.workspaceId),z("VIBE_ORGANIZATION_ID",$.organizationId);let Z=XQ();return z("VIBE_GLOBAL_GATEWAY_URL",$.globalGatewayUrl??Z.globalGatewayUrl),z("VIBE_WORKSPACE_GATEWAY_URL",$.workspaceGatewayUrl??Z.workspaceGatewayUrl),z("VIBE_STORAGE_ADAPTER",$.storageAdapter),z("VIBECONTROLS_PLUGIN_INSTALL_SCOPE",$.pluginInstallScope),$}async function fQ(){let q=($,z)=>{if(!process.env[$]&&z)process.env[$]=z},Q=v();try{let $=await P(B(Q,"clientId"));q("VIBE_CLIENT_ID",$??void 0)}catch{}try{let $=await P(B(Q,"clientSecret"));q("VIBE_CLIENT_SECRET",$??void 0)}catch{}}
11
+ export{P as Wc,x as Xc,wQ as Yc,OQ as Zc,M as _c,bq as $c,AQ as ad,T as bd,y as cd,Lq as dd,r as ed,E as fd,eq as gd,qQ as hd,RQ as id,QQ as jd,$Q as kd,PQ as ld,zQ as md,ZQ as nd,JQ as od,i as pd,XQ as qd,xQ as rd,n as sd,uQ as td,HQ as ud,kQ as vd,_Q as wd,YQ as xd,O as yd,IQ as zd,hQ as Ad,vQ as Bd,fQ as Cd};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{cb as Y,db as k}from"./index-52cp759f.js";import{Pd as W}from"./index-c4p1qcnn.js";import{de as V}from"./index-q9dp55wv.js";import{createHash as g,randomUUID as x}from"crypto";import{existsSync as $,mkdirSync as L,readFileSync as O,writeFileSync as j}from"fs";import{join as K}from"path";import*as X from"os";var A="https://analytics.burdenoff.com/api/track",H="cd7d5ccc3667",w=200,f=10,B=30000,R=5000;function C(q){if(process.env.DO_NOT_TRACK==="1")return!1;let z=process.env.VIBECONTROLS_TELEMETRY?.toLowerCase();if(z==="on"||z==="true"||z==="1")return!0;if(z==="off"||z==="false"||z==="0")return!1;return q}class M{enabled=!1;persisted=!1;buffer=[];flushTimer=null;cachedAnonymousId=null;overflowWarned=!1;postFailureWarned=!1;initialized=!1;init(q){if(q?.persisted!==void 0)this.persisted=q.persisted;if(this.enabled=C(this.persisted),!this.initialized)this.initialized=!0,this.startFlushTimer()}setEnabled(q){let z=this.enabled;if(this.persisted=q,this.enabled=C(this.persisted),z&&!this.enabled)this.buffer=[],this.enqueueRaw("telemetry.disabled",{reason:"user_opt_out"}),this.flush()}emit(q,z={}){if(!this.enabled)return;let G={},J=!1;for(let[Z,N]of Object.entries(z)){if(Y(Z)){J=!0;continue}G[Z]=N}let Q=k(q,G);if(!Q.ok||!Q.sanitized){W().logger.warn("telemetry",`dropping event '${q}': ${Q.reason??"invalid"}`);return}this.enqueue(q,Q.sanitized)}enqueueRaw(q,z){this.enqueue(q,z)}enqueue(q,z){let G={site_id:H,event_name:q,properties:z,anonymous_id:this.getAnonymousId(),timestamp:new Date().toISOString()};if(this.buffer.length>=w){if(this.buffer.shift(),!this.overflowWarned)this.overflowWarned=!0,W().logger.warn("telemetry",`buffer overflow (cap=${w}) \u2014 dropping oldest events`)}if(this.buffer.push(G),this.buffer.length>=f)this.flush()}async flush(){if(this.buffer.length===0)return;let q=this.buffer.splice(0,this.buffer.length),z=new AbortController,G=setTimeout(()=>z.abort(),R);try{await fetch(A,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({events:q}),signal:z.signal})}catch(J){if(!this.postFailureWarned)this.postFailureWarned=!0,W().logger.warn("telemetry","shipper POST failed; dropping batch",{error:String(J)})}finally{clearTimeout(G)}}stop(){if(this.flushTimer)clearInterval(this.flushTimer),this.flushTimer=null;this.initialized=!1}_resetForTest(){this.stop(),this.enabled=!1,this.persisted=!1,this.buffer=[],this.cachedAnonymousId=null,this.overflowWarned=!1,this.postFailureWarned=!1}_bufferLength(){return this.buffer.length}_isEnabled(){return this.enabled}startFlushTimer(){if(this.flushTimer)return;if(this.flushTimer=setInterval(()=>{this.flush()},B),typeof this.flushTimer.unref==="function")this.flushTimer.unref()}getAnonymousId(){if(this.cachedAnonymousId)return this.cachedAnonymousId;let q=`${X.hostname()}${X.platform()}`,z=this.readOrCreateInstallId(),G=g("sha256").update(q+z).digest("hex");return this.cachedAnonymousId=G.slice(0,16),this.cachedAnonymousId}readOrCreateInstallId(){let q;try{q=V()}catch{q=K(process.cwd(),".boff","vibecontrols")}if(!$(q))try{L(q,{recursive:!0,mode:448})}catch{}let z=K(q,".install-id");if($(z))try{let J=O(z,"utf-8").trim();if(J)return J}catch{}let G=x();try{j(z,G,{mode:384})}catch{}return G}}var b=new M;
3
- export{b as bb};
2
+ import{gb as Y,hb as k}from"./index-ekr40gvh.js";import{Wd as W}from"./index-axgp7ryd.js";import{ke as V}from"./index-c4zn91z3.js";import{createHash as g,randomUUID as x}from"crypto";import{existsSync as $,mkdirSync as L,readFileSync as O,writeFileSync as j}from"fs";import{join as K}from"path";import*as X from"os";var A="https://analytics.burdenoff.com/api/track",H="cd7d5ccc3667",w=200,f=10,B=30000,R=5000;function C(q){if(process.env.DO_NOT_TRACK==="1")return!1;let z=process.env.VIBECONTROLS_TELEMETRY?.toLowerCase();if(z==="on"||z==="true"||z==="1")return!0;if(z==="off"||z==="false"||z==="0")return!1;return q}class M{enabled=!1;persisted=!1;buffer=[];flushTimer=null;cachedAnonymousId=null;overflowWarned=!1;postFailureWarned=!1;initialized=!1;init(q){if(q?.persisted!==void 0)this.persisted=q.persisted;if(this.enabled=C(this.persisted),!this.initialized)this.initialized=!0,this.startFlushTimer()}setEnabled(q){let z=this.enabled;if(this.persisted=q,this.enabled=C(this.persisted),z&&!this.enabled)this.buffer=[],this.enqueueRaw("telemetry.disabled",{reason:"user_opt_out"}),this.flush()}emit(q,z={}){if(!this.enabled)return;let G={},J=!1;for(let[Z,N]of Object.entries(z)){if(Y(Z)){J=!0;continue}G[Z]=N}let Q=k(q,G);if(!Q.ok||!Q.sanitized){W().logger.warn("telemetry",`dropping event '${q}': ${Q.reason??"invalid"}`);return}this.enqueue(q,Q.sanitized)}enqueueRaw(q,z){this.enqueue(q,z)}enqueue(q,z){let G={site_id:H,event_name:q,properties:z,anonymous_id:this.getAnonymousId(),timestamp:new Date().toISOString()};if(this.buffer.length>=w){if(this.buffer.shift(),!this.overflowWarned)this.overflowWarned=!0,W().logger.warn("telemetry",`buffer overflow (cap=${w}) \u2014 dropping oldest events`)}if(this.buffer.push(G),this.buffer.length>=f)this.flush()}async flush(){if(this.buffer.length===0)return;let q=this.buffer.splice(0,this.buffer.length),z=new AbortController,G=setTimeout(()=>z.abort(),R);try{await fetch(A,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({events:q}),signal:z.signal})}catch(J){if(!this.postFailureWarned)this.postFailureWarned=!0,W().logger.warn("telemetry","shipper POST failed; dropping batch",{error:String(J)})}finally{clearTimeout(G)}}stop(){if(this.flushTimer)clearInterval(this.flushTimer),this.flushTimer=null;this.initialized=!1}_resetForTest(){this.stop(),this.enabled=!1,this.persisted=!1,this.buffer=[],this.cachedAnonymousId=null,this.overflowWarned=!1,this.postFailureWarned=!1}_bufferLength(){return this.buffer.length}_isEnabled(){return this.enabled}startFlushTimer(){if(this.flushTimer)return;if(this.flushTimer=setInterval(()=>{this.flush()},B),typeof this.flushTimer.unref==="function")this.flushTimer.unref()}getAnonymousId(){if(this.cachedAnonymousId)return this.cachedAnonymousId;let q=`${X.hostname()}${X.platform()}`,z=this.readOrCreateInstallId(),G=g("sha256").update(q+z).digest("hex");return this.cachedAnonymousId=G.slice(0,16),this.cachedAnonymousId}readOrCreateInstallId(){let q;try{q=V()}catch{q=K(process.cwd(),".boff","vibecontrols")}if(!$(q))try{L(q,{recursive:!0,mode:448})}catch{}let z=K(q,".install-id");if($(z))try{let J=O(z,"utf-8").trim();if(J)return J}catch{}let G=x();try{j(z,G,{mode:384})}catch{}return G}}var b=new M;
3
+ export{b as fb};
@@ -1,9 +1,9 @@
1
1
  // @bun
2
- import{Zd as c,_d as i,ae as l,de as n}from"./index-q9dp55wv.js";import{fe as g}from"./index-ntj6ymk8.js";import{je as p}from"./index-gb5bnx7a.js";import{join as xJ}from"path";import{AsyncLocalStorage as IJ}from"async_hooks";import{mkdirSync as _J}from"fs";import{join as u}from"path";import{appendFileSync as r,existsSync as O,mkdirSync as e,readFileSync as JJ,readdirSync as ZJ,statSync as $J,unlinkSync as w}from"fs";import{join as F}from"path";var QJ=30,XJ=104857600,WJ=/secret|password|token|key|email/i,h=/^audit-(\d{4}-\d{2}-\d{2})\.log$/;function y(J=new Date){let Z=J.getUTCFullYear(),$=String(J.getUTCMonth()+1).padStart(2,"0"),Q=String(J.getUTCDate()).padStart(2,"0");return`${Z}-${$}-${Q}`}function k(J){if(Array.isArray(J))return J.map(k);if(J&&typeof J==="object"){let Z={};for(let[$,Q]of Object.entries(J)){if(WJ.test($)){Z[$]="[redacted]";continue}Z[$]=k(Q)}return Z}return J}function KJ(J,Z){if(!Z)return!0;if(Z.includes("*"))return new RegExp(`^${Z.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*")}$`).test(J);return J.includes(Z)}class I{profile;auditDir;constructor(J,Z){this.profile=J,this.auditDir=F(Z,"audit")}ensureDir(){if(!O(this.auditDir))e(this.auditDir,{recursive:!0});return this.auditDir}activeFilePath(){return F(this.ensureDir(),`audit-${y()}.log`)}emit(J,Z,$={}){let Q=k($),X={timestamp:new Date().toISOString(),source:J,event:Z,payload:{...Q,profile:this.profile}};try{r(this.activeFilePath(),`${JSON.stringify(X)}
2
+ import{ee as c,fe as i,he as l,ke as n}from"./index-c4zn91z3.js";import{me as g}from"./index-73qwyf9q.js";import{qe as p}from"./index-149rjxa5.js";import{join as xJ}from"path";import{AsyncLocalStorage as IJ}from"async_hooks";import{mkdirSync as _J}from"fs";import{join as u}from"path";import{appendFileSync as r,existsSync as O,mkdirSync as e,readFileSync as JJ,readdirSync as ZJ,statSync as $J,unlinkSync as w}from"fs";import{join as F}from"path";var QJ=30,XJ=104857600,WJ=/secret|password|token|key|email/i,h=/^audit-(\d{4}-\d{2}-\d{2})\.log$/;function y(J=new Date){let Z=J.getUTCFullYear(),$=String(J.getUTCMonth()+1).padStart(2,"0"),Q=String(J.getUTCDate()).padStart(2,"0");return`${Z}-${$}-${Q}`}function k(J){if(Array.isArray(J))return J.map(k);if(J&&typeof J==="object"){let Z={};for(let[$,Q]of Object.entries(J)){if(WJ.test($)){Z[$]="[redacted]";continue}Z[$]=k(Q)}return Z}return J}function KJ(J,Z){if(!Z)return!0;if(Z.includes("*"))return new RegExp(`^${Z.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*")}$`).test(J);return J.includes(Z)}class I{profile;auditDir;constructor(J,Z){this.profile=J,this.auditDir=F(Z,"audit")}ensureDir(){if(!O(this.auditDir))e(this.auditDir,{recursive:!0});return this.auditDir}activeFilePath(){return F(this.ensureDir(),`audit-${y()}.log`)}emit(J,Z,$={}){let Q=k($),X={timestamp:new Date().toISOString(),source:J,event:Z,payload:{...Q,profile:this.profile}};try{r(this.activeFilePath(),`${JSON.stringify(X)}
3
3
  `,{mode:384})}catch{}}listLogFiles(){if(!O(this.auditDir))return[];return ZJ(this.auditDir).filter((J)=>h.test(J)).sort()}listEvents(J={}){let Z=Math.max(1,Math.min(J.limit??200,5000)),$=J.since?Date.parse(J.since):null,Q=J.event??"",X=this.listLogFiles(),W=[];for(let K=X.length-1;K>=0&&W.length<Z;K--){let V=X[K],z;try{z=JJ(F(this.auditDir,V),"utf8")}catch{continue}let Y=z.split(`
4
4
  `);for(let M=Y.length-1;M>=0&&W.length<Z;M--){let q=Y[M];if(!q)continue;let H;try{H=JSON.parse(q)}catch{continue}if($!==null&&Number.isFinite($)&&Date.parse(H.timestamp)<$)continue;if(!KJ(H.event,Q))continue;W.push(H)}}return W}runRetention(J=new Date){if(!O(this.auditDir))return;let Z=J.getTime()-QJ*24*60*60*1000,$=this.listLogFiles(),Q=[];for(let K of $){let V=h.exec(K);if(!V)continue;let z=Date.parse(`${V[1]}T00:00:00Z`),Y=F(this.auditDir,K);try{let M=$J(Y);if(Number.isFinite(z)&&z<Z){w(Y);continue}Q.push({name:K,size:M.size,mtime:M.mtimeMs})}catch{}}let X=Q.reduce((K,V)=>K+V.size,0),W=`audit-${y(J)}.log`;Q.sort((K,V)=>K.name.localeCompare(V.name));for(let K of Q){if(X<=XJ)break;if(K.name===W)continue;try{w(F(this.auditDir,K.name)),X-=K.size}catch{}}}__getAuditDirForTests(){return this.auditDir}}class _{profile;cryptoKey=null;apiKeyHash=null;constructor(J){this.profile=J}async load(J){if(J.byteLength!==32)throw Error(`KeyVault expects 32-byte key, got ${J.byteLength}`);let Z=new Uint8Array(J);try{this.cryptoKey=await crypto.subtle.importKey("raw",Z,{name:"AES-GCM"},!1,["encrypt","decrypt"])}finally{J.fill(0),Z.fill(0)}}async bindApiKey(J){let Z=new TextEncoder().encode(J);this.apiKeyHash=await crypto.subtle.digest("SHA-256",Z),Z.fill(0)}async match(J){if(!this.apiKeyHash)return!1;let Z=new TextEncoder().encode(J),$=await crypto.subtle.digest("SHA-256",Z);return Z.fill(0),VJ(this.apiKeyHash,$)}hasKey(){return this.cryptoKey!==null}getCryptoKey(){return this.cryptoKey}shutdown(){this.cryptoKey=null,this.apiKeyHash=null}}function VJ(J,Z){if(J.byteLength!==Z.byteLength)return!1;let $=new Uint8Array(J),Q=new Uint8Array(Z),X=0;for(let W=0;W<$.length;W++)X|=($[W]??0)^(Q[W]??0);return X===0}import{existsSync as N,mkdirSync as MJ,statSync as HJ,copyFileSync as BJ,truncateSync as CJ,renameSync as qJ,unlinkSync as NJ,createReadStream as DJ}from"fs";import{join as FJ}from"path";import{EventEmitter as jJ}from"events";import{createInterface as GJ}from"readline";import{AsyncLocalStorage as zJ}from"async_hooks";var f=new zJ,YJ=/^[A-Za-z0-9._:-]{8,128}$/;function oJ(){let J=globalThis.crypto;if(J?.randomUUID)return J.randomUUID();let Z=new Uint8Array(16);return J?.getRandomValues?.(Z),[...Z].map(($)=>$.toString(16).padStart(2,"0")).join("")}function sJ(J){let Z=(Q)=>{if(J instanceof Headers)return J.get(Q)??void 0;return J[Q]??J[Q.toLowerCase()]??J[Q.toUpperCase()]},$=Z("x-request-id")??Z("X-Request-Id");if(!$)return;return YJ.test($)?$:void 0}function aJ(J){f.enterWith(J)}function G(){return f.getStore()?.requestId}var bJ=10485760,m=7,PJ=60000,b={debug:0,info:1,warn:2,error:3},OJ={debug:"\x1B[90m",info:"\x1B[36m",warn:"\x1B[33m",error:"\x1B[31m"},kJ="\x1B[0m";class L extends jJ{logDir;logFile;currentDay="";minLevel;isDaemon;emitOutput;prettyOutput;rotationTimer=null;constructor(J){super();this.setMaxListeners(100),this.logDir=J.logDir;let Z=process.env.AGENT_LOG_FILE;this.logFile=Z&&Z.length>0?Z:J.logFile??FJ(this.logDir,"default.log"),this.minLevel=process.env.LOG_LEVEL??"info",this.isDaemon=Boolean(process.env.AGENT_LOG_FILE);let $=process.env.VIBE_FOREGROUND==="1"||process.argv.some((Q)=>Q==="-f"||Q==="--foreground");if(this.emitOutput=this.isDaemon||$||process.env.LOG_CONSOLE==="true"||!1,this.prettyOutput=this.emitOutput&&!this.isDaemon&&Boolean(process.stdout.isTTY),this.ensureLogDir(),this.currentDay=new Date().toISOString().split("T")[0]??"",this.isDaemon)this.rotationTimer=setInterval(()=>this.checkRotation(),PJ),this.rotationTimer.unref?.()}debug(J,Z,$){this.log("debug",J,Z,$)}info(J,Z,$){this.log("info",J,Z,$)}warn(J,Z,$){this.log("warn",J,Z,$)}error(J,Z,$){this.log("error",J,Z,$)}setLevel(J){this.minLevel=J}async readHistory(J){let{level:Z,source:$,from:Q,to:X,limit:W=200,offset:K=0}=J??{},V=[];if(!N(this.logFile))return V;return new Promise((z)=>{let Y=GJ({input:DJ(this.logFile,"utf8")}),M=0;Y.on("line",(q)=>{if(V.length>=W){Y.close();return}try{let H=JSON.parse(q);if(Z&&b[H.level]<b[Z])return;if($&&!H.source.includes($))return;if(Q&&H.timestamp<Q)return;if(X&&H.timestamp>X)return;if(M<K){M++;return}V.push(H)}catch{}}),Y.on("close",()=>z(V)),Y.on("error",()=>z(V))})}close(){if(this.rotationTimer)clearInterval(this.rotationTimer),this.rotationTimer=null}log(J,Z,$,Q){if(b[J]<b[this.minLevel])return;let X=G(),W=X!==void 0?{requestId:X,...Q??{}}:Q,K={timestamp:new Date().toISOString(),level:J,source:Z,message:$,...W&&Object.keys(W).length>0?{metadata:W}:{}};if(this.emitOutput)if(this.prettyOutput){let V=OJ[J],z=J.toUpperCase().padEnd(5),Y=Z?` [${Z}]`:"",M=W&&Object.keys(W).length>0?` ${JSON.stringify(W)}`:"",q=K.timestamp.split("T")[1]?.slice(0,12)??K.timestamp;process.stdout.write(`${V}${q} ${z}${kJ}${Y} ${$}${M}
5
5
  `)}else process.stdout.write(JSON.stringify(K)+`
6
- `);this.emit("log",K),g.enqueue(K)}checkRotation(){let J=new Date().toISOString().split("T")[0];if(this.currentDay&&this.currentDay!==J){this.rotate(),this.currentDay=J;return}this.currentDay=J;try{if(N(this.logFile)){if(HJ(this.logFile).size>=bJ)this.rotate()}}catch{}}rotate(){try{for(let J=m-1;J>=1;J--){let Z=`${this.logFile}.${J}`,$=`${this.logFile}.${J+1}`;if(N(Z)){if(J+1>m&&N($))NJ($);qJ(Z,$)}}if(N(this.logFile))BJ(this.logFile,`${this.logFile}.1`),CJ(this.logFile,0)}catch{}}ensureLogDir(){if(!N(this.logDir))MJ(this.logDir,{recursive:!0})}}var LJ={maxFileDescriptors:4096,maxChildProcesses:256,maxMemoryMB:4096},x=new IJ;function B2(J){x.enterWith(J)}class A{name;dataDir;spawnOwnerKey;keyVault;audit;logger;budget;db=null;serviceRegistry=null;pluginManager=null;lifecycle=null;hostServices=null;tunnel={url:null,child:null,externalUrl:!1};_gatewayClient=null;state="awaiting-config";degradedReasons=[];listeners=new Set;lastFinalizeError=null;constructor(J){this.name=J.name,this.dataDir=J.dataDir,this.spawnOwnerKey=`profile/${J.name}`,this.budget=J.budget??LJ,_J(this.dataDir,{recursive:!0}),this.keyVault=new _(J.name),this.audit=new I(J.name,J.dataDir),this.logger=new L({logDir:u(J.dataDir,"logs")})}run(J){return x.run(this,J)}get gatewayClient(){if(!this._gatewayClient)this._gatewayClient=new R;return this._gatewayClient}attachServices(J){this.db=J.db,this.serviceRegistry=J.serviceRegistry,this.pluginManager=J.pluginManager,this.lifecycle=J.lifecycle,this.hostServices=J.hostServices}getBootState(){return this.state}setBootState(J){if(this.state===J)return;if(this.state=J,J!=="degraded")this.degradedReasons.length=0;for(let Z of this.listeners)try{Z(J)}catch{}}recordDegradedReason(J,Z){if(this.degradedReasons.push({plugin:J,message:Z}),this.state==="ready")this.setBootState("degraded");(async()=>{try{let{telemetryService:$}=await import("./telemetry-mq37zapd.js");$.emit("health.degraded",{reason_class:RJ(Z)})}catch{}})()}getDegradedReasons(){return this.degradedReasons.slice()}recordFinalizeError(J,Z){this.lastFinalizeError={message:J,at:new Date().toISOString(),attempt:Z}}clearFinalizeError(){this.lastFinalizeError=null}getLastFinalizeError(){return this.lastFinalizeError}onBootStateChange(J){return this.listeners.add(J),()=>this.listeners.delete(J)}async shutdown(){this.setBootState("shutting-down");try{let{unmountProfileRoutes:J}=await import("./profile-mount-13qvjqbg.js");J(this.name)}catch{}try{if(this.pluginManager)await this.pluginManager.dispatchServerStop({reason:"shutdown"})}catch{}try{if(this.db)await this.db.close()}catch{}this.lifecycle=null,this.pluginManager=null,this.hostServices=null,this.serviceRegistry=null,this.db=null,this._gatewayClient=null,this.tunnel={url:null,child:null,externalUrl:!1},this.keyVault.shutdown(),this.listeners.clear()}subdir(J){return u(this.dataDir,J)}}function d(){return x.getStore()??null}function RJ(J){let Z=J.toLowerCase();if(Z.includes("timeout"))return"timeout";if(Z.includes("econn")||Z.includes("network"))return"network";if(Z.includes("permission")||Z.includes("eacces"))return"permission";if(Z.includes("not found")||Z.includes("enoent"))return"not_found";if(Z.includes("plugin"))return"plugin";return"other"}class T{profiles=new Map;create(J){if(this.profiles.has(J.name))throw Error(`profile already registered: ${J.name}`);let Z=new A(J);return this.profiles.set(J.name,Z),this.refreshProcessTitle(),Z}refreshProcessTitle(){try{let Z=[...this.profiles.keys()].sort().join(","),$=Z.length>96?`${Z.slice(0,93)}...`:Z;process.title=`vibe-daemon[${$}]`}catch{}}get(J){return this.profiles.get(J)}list(){return[...this.profiles.values()]}names(){return[...this.profiles.keys()]}has(J){return this.profiles.has(J)}size(){return this.profiles.size}async destroy(J){let Z=this.profiles.get(J);if(!Z)return;await Z.shutdown(),this.profiles.delete(J),this.refreshProcessTitle()}async destroyAll(){let J=[...this.profiles.keys()];for(let Z of J)await this.destroy(Z)}}var j=new T,D=null;function AJ(){if(D)return D;let J=c(),Z=j.get(J);if(Z)return D=Z,Z;return D=j.create({name:J,dataDir:l()}),D}function B(){return AJ()}function G2(J){let Z=i(J),$=j.get(Z);if($)return $;return j.create({name:Z,dataDir:xJ(n(),"agents",Z)})}async function b2(){D=null,await j.destroyAll()}var P=new Set(["localhost","127.0.0.1","0.0.0.0","::1","[::1]","host.docker.internal"]),TJ=new Set(["4000","4001","4002","4003"]),UJ=new Set(["gw-global.local.burdenoff.com","gw-global-int.local.burdenoff.com","gw-wspace.local.burdenoff.com","gw-wspace-int.local.burdenoff.com"]),EJ=new Set(["graphql.burdenoff.com","graphqlworkspaces.burdenoff.com","alphagraphql.burdenoff.com","alphagraphqlworkspaces.burdenoff.com"]);function C(J){return J.toLowerCase().replace(/^\[|\]$/g,"")}function o(J){let Z=C(J.hostname);if(!P.has(Z))return!1;if(process.env.VIBECONTROLS_ALLOW_UNTRUSTED_GATEWAYS==="1")return!0;return TJ.has(J.port)}function s(J){try{let Z=new URL(J.trim());if(Z.protocol!=="https:"&&Z.protocol!=="http:")return!1;if(o(Z))return!0;let $=C(Z.hostname);if(UJ.has($))return Z.protocol==="https:";if(Z.protocol!=="https:")return!1;return EJ.has($)}catch{return!1}}function U(J,Z){let $=J.trim();if(!s($))throw Error(`${Z} is not an allowed gateway URL. Use a trusted Burdenoff gateway, approved gw-*.local.burdenoff.com host, or localhost gateway ports 4000-4003.`);return $.replace(/\/+$/,"")}var E=new Set([".vibecontrols.com"]);function O2(J){let Z=J.trim().toLowerCase();if(!Z)return;E.add(Z.startsWith(".")?Z:`.${Z}`)}function SJ(J){try{let Z=new URL(J.trim()),$=C(Z.hostname);if(P.has($))return Z.protocol==="http:"||Z.protocol==="https:";if(Z.protocol!=="https:")return!1;for(let Q of E)if($.endsWith(Q))return!0;return!1}catch{return!1}}function vJ(J){if(!J)return null;let Z=J.trim().replace(/\/+$/,"");return SJ(Z)?Z:null}function k2(J){if(!J)return null;let Z=vJ(J);if(Z)return Z;let $=process.env.AGENT_TUNNEL_URL;if($&&J.trim().replace(/\/+$/,"")===$.trim().replace(/\/+$/,""))return fJ(J);return null}var wJ=new Set([".trycloudflare.com"]);function hJ(J){try{let Z=new URL(J.trim()),$=C(Z.hostname);if(P.has($))return Z.protocol==="http:"||Z.protocol==="https:";if(Z.protocol!=="https:")return!1;for(let Q of E)if($.endsWith(Q))return!0;for(let Q of wJ)if($.endsWith(Q))return!0;return!1}catch{return!1}}function I2(J){if(!J)return null;let Z=J.trim().replace(/\/+$/,"");return hJ(Z)?Z:null}function yJ(J){try{let Z=new URL(J.trim()),$=C(Z.hostname);if(P.has($))return Z.protocol==="http:"||Z.protocol==="https:";return Z.protocol==="https:"}catch{return!1}}function fJ(J){if(!J)return null;let Z=J.trim().replace(/\/+$/,"");return yJ(Z)?Z:null}function _2(J,Z){try{let $=new URL(J.trim());if($.protocol!=="https:"&&!o($))return!1;let Q=C($.hostname);for(let X of Z){if(!X)continue;let W=new URL(X);if(Q===C(W.hostname))return!0}return s(J)}catch{return!1}}var mJ=/(?:\/(?:global|workspaces))?\/graphql$/i,gJ=1048576;function v(J){return J.trim().replace(/\/+$/,"").replace(mJ,"")}function a(J,Z){return`${v(J)}/${Z}/graphql`}function t(J){return J instanceof Error?J.message:String(J)}async function pJ(J,Z){let $=J.headers.get("content-length");if($){let z=Number.parseInt($,10);if(Number.isInteger(z)&&z>Z)throw Error(`Gateway response is too large (${z} bytes)`)}if(!J.body)return"";let Q=J.body.getReader(),X=[],W=0;try{while(!0){let{done:z,value:Y}=await Q.read();if(z)break;if(!Y)continue;if(W+=Y.byteLength,W>Z)throw await Q.cancel().catch(()=>{return}),Error(`Gateway response exceeds ${Z} bytes`);X.push(Y)}}finally{Q.releaseLock()}let K=new Uint8Array(W),V=0;for(let z of X)K.set(z,V),V+=z.byteLength;return new TextDecoder().decode(K)}class R{config=null;token=null;authInFlight=null;configGeneration=0;configure(J){let Z=v(U(J.globalGatewayUrl,"globalGatewayUrl")),$=J.workspaceGatewayUrl?v(U(J.workspaceGatewayUrl,"workspaceGatewayUrl")):void 0,Q=J.clientId.trim(),X=J.clientSecret.trim();if(!Z)throw Error("globalGatewayUrl is required");if(!Q)throw Error("clientId is required");if(!X)throw Error("clientSecret is required");this.configGeneration+=1,this.config={...J,globalGatewayUrl:Z,workspaceGatewayUrl:$,clientId:Q,clientSecret:X,scopes:J.scopes?.map((W)=>W.trim()).filter(Boolean),workspaceId:J.workspaceId?.trim()||void 0,organizationId:J.organizationId?.trim()||void 0},this.token=null,this.authInFlight=null,B().logger.info("gateway-client","Gateway client configured",{globalGatewayUrl:this.config.globalGatewayUrl,workspaceGatewayUrl:this.config.workspaceGatewayUrl,clientId:this.config.clientId})}isConfigured(){return this.config!==null}getConfig(){if(!this.config)return null;let{clientSecret:J,...Z}=this.config;return Z}async getAccessToken(){let{token:J,config:Z}=await this.ensureToken();return{token:J,workspaceGatewayUrl:Z.workspaceGatewayUrl??"",globalGatewayUrl:Z.globalGatewayUrl??"",workspaceId:Z.workspaceId??""}}async globalQuery(J,Z){return this.executeQuery("global",J,Z)}async workspaceQuery(J,Z){return this.executeQuery("workspaces",J,Z)}async lookupPeerAgent(J,Z){if(!this.isConfigured())return null;try{let Q=(await this.workspaceQuery(`query AgentNetworkLookup($targetAgentRecordId: ID!, $operation: String!) {
6
+ `);this.emit("log",K),g.enqueue(K)}checkRotation(){let J=new Date().toISOString().split("T")[0];if(this.currentDay&&this.currentDay!==J){this.rotate(),this.currentDay=J;return}this.currentDay=J;try{if(N(this.logFile)){if(HJ(this.logFile).size>=bJ)this.rotate()}}catch{}}rotate(){try{for(let J=m-1;J>=1;J--){let Z=`${this.logFile}.${J}`,$=`${this.logFile}.${J+1}`;if(N(Z)){if(J+1>m&&N($))NJ($);qJ(Z,$)}}if(N(this.logFile))BJ(this.logFile,`${this.logFile}.1`),CJ(this.logFile,0)}catch{}}ensureLogDir(){if(!N(this.logDir))MJ(this.logDir,{recursive:!0})}}var LJ={maxFileDescriptors:4096,maxChildProcesses:256,maxMemoryMB:4096},x=new IJ;function B2(J){x.enterWith(J)}class A{name;dataDir;spawnOwnerKey;keyVault;audit;logger;budget;db=null;serviceRegistry=null;pluginManager=null;lifecycle=null;hostServices=null;tunnel={url:null,child:null,externalUrl:!1};_gatewayClient=null;state="awaiting-config";degradedReasons=[];listeners=new Set;lastFinalizeError=null;constructor(J){this.name=J.name,this.dataDir=J.dataDir,this.spawnOwnerKey=`profile/${J.name}`,this.budget=J.budget??LJ,_J(this.dataDir,{recursive:!0}),this.keyVault=new _(J.name),this.audit=new I(J.name,J.dataDir),this.logger=new L({logDir:u(J.dataDir,"logs")})}run(J){return x.run(this,J)}get gatewayClient(){if(!this._gatewayClient)this._gatewayClient=new R;return this._gatewayClient}attachServices(J){this.db=J.db,this.serviceRegistry=J.serviceRegistry,this.pluginManager=J.pluginManager,this.lifecycle=J.lifecycle,this.hostServices=J.hostServices}getBootState(){return this.state}setBootState(J){if(this.state===J)return;if(this.state=J,J!=="degraded")this.degradedReasons.length=0;for(let Z of this.listeners)try{Z(J)}catch{}}recordDegradedReason(J,Z){if(this.degradedReasons.push({plugin:J,message:Z}),this.state==="ready")this.setBootState("degraded");(async()=>{try{let{telemetryService:$}=await import("./telemetry-h9pa43c9.js");$.emit("health.degraded",{reason_class:RJ(Z)})}catch{}})()}getDegradedReasons(){return this.degradedReasons.slice()}recordFinalizeError(J,Z){this.lastFinalizeError={message:J,at:new Date().toISOString(),attempt:Z}}clearFinalizeError(){this.lastFinalizeError=null}getLastFinalizeError(){return this.lastFinalizeError}onBootStateChange(J){return this.listeners.add(J),()=>this.listeners.delete(J)}async shutdown(){this.setBootState("shutting-down");try{let{unmountProfileRoutes:J}=await import("./profile-mount-xchr4y5e.js");J(this.name)}catch{}try{if(this.pluginManager)await this.pluginManager.dispatchServerStop({reason:"shutdown"})}catch{}try{if(this.db)await this.db.close()}catch{}this.lifecycle=null,this.pluginManager=null,this.hostServices=null,this.serviceRegistry=null,this.db=null,this._gatewayClient=null,this.tunnel={url:null,child:null,externalUrl:!1},this.keyVault.shutdown(),this.listeners.clear()}subdir(J){return u(this.dataDir,J)}}function d(){return x.getStore()??null}function RJ(J){let Z=J.toLowerCase();if(Z.includes("timeout"))return"timeout";if(Z.includes("econn")||Z.includes("network"))return"network";if(Z.includes("permission")||Z.includes("eacces"))return"permission";if(Z.includes("not found")||Z.includes("enoent"))return"not_found";if(Z.includes("plugin"))return"plugin";return"other"}class T{profiles=new Map;create(J){if(this.profiles.has(J.name))throw Error(`profile already registered: ${J.name}`);let Z=new A(J);return this.profiles.set(J.name,Z),this.refreshProcessTitle(),Z}refreshProcessTitle(){try{let Z=[...this.profiles.keys()].sort().join(","),$=Z.length>96?`${Z.slice(0,93)}...`:Z;process.title=`vibe-daemon[${$}]`}catch{}}get(J){return this.profiles.get(J)}list(){return[...this.profiles.values()]}names(){return[...this.profiles.keys()]}has(J){return this.profiles.has(J)}size(){return this.profiles.size}async destroy(J){let Z=this.profiles.get(J);if(!Z)return;await Z.shutdown(),this.profiles.delete(J),this.refreshProcessTitle()}async destroyAll(){let J=[...this.profiles.keys()];for(let Z of J)await this.destroy(Z)}}var j=new T,D=null;function AJ(){if(D)return D;let J=c(),Z=j.get(J);if(Z)return D=Z,Z;return D=j.create({name:J,dataDir:l()}),D}function B(){return AJ()}function G2(J){let Z=i(J),$=j.get(Z);if($)return $;return j.create({name:Z,dataDir:xJ(n(),"agents",Z)})}async function b2(){D=null,await j.destroyAll()}var P=new Set(["localhost","127.0.0.1","0.0.0.0","::1","[::1]","host.docker.internal"]),TJ=new Set(["4000","4001","4002","4003"]),UJ=new Set(["gw-global.local.burdenoff.com","gw-global-int.local.burdenoff.com","gw-wspace.local.burdenoff.com","gw-wspace-int.local.burdenoff.com"]),EJ=new Set(["graphql.burdenoff.com","graphqlworkspaces.burdenoff.com","alphagraphql.burdenoff.com","alphagraphqlworkspaces.burdenoff.com"]);function C(J){return J.toLowerCase().replace(/^\[|\]$/g,"")}function o(J){let Z=C(J.hostname);if(!P.has(Z))return!1;if(process.env.VIBECONTROLS_ALLOW_UNTRUSTED_GATEWAYS==="1")return!0;return TJ.has(J.port)}function s(J){try{let Z=new URL(J.trim());if(Z.protocol!=="https:"&&Z.protocol!=="http:")return!1;if(o(Z))return!0;let $=C(Z.hostname);if(UJ.has($))return Z.protocol==="https:";if(Z.protocol!=="https:")return!1;return EJ.has($)}catch{return!1}}function U(J,Z){let $=J.trim();if(!s($))throw Error(`${Z} is not an allowed gateway URL. Use a trusted Burdenoff gateway, approved gw-*.local.burdenoff.com host, or localhost gateway ports 4000-4003.`);return $.replace(/\/+$/,"")}var E=new Set([".vibecontrols.com"]);function O2(J){let Z=J.trim().toLowerCase();if(!Z)return;E.add(Z.startsWith(".")?Z:`.${Z}`)}function SJ(J){try{let Z=new URL(J.trim()),$=C(Z.hostname);if(P.has($))return Z.protocol==="http:"||Z.protocol==="https:";if(Z.protocol!=="https:")return!1;for(let Q of E)if($.endsWith(Q))return!0;return!1}catch{return!1}}function vJ(J){if(!J)return null;let Z=J.trim().replace(/\/+$/,"");return SJ(Z)?Z:null}function k2(J){if(!J)return null;let Z=vJ(J);if(Z)return Z;let $=process.env.AGENT_TUNNEL_URL;if($&&J.trim().replace(/\/+$/,"")===$.trim().replace(/\/+$/,""))return fJ(J);return null}var wJ=new Set([".trycloudflare.com"]);function hJ(J){try{let Z=new URL(J.trim()),$=C(Z.hostname);if(P.has($))return Z.protocol==="http:"||Z.protocol==="https:";if(Z.protocol!=="https:")return!1;for(let Q of E)if($.endsWith(Q))return!0;for(let Q of wJ)if($.endsWith(Q))return!0;return!1}catch{return!1}}function I2(J){if(!J)return null;let Z=J.trim().replace(/\/+$/,"");return hJ(Z)?Z:null}function yJ(J){try{let Z=new URL(J.trim()),$=C(Z.hostname);if(P.has($))return Z.protocol==="http:"||Z.protocol==="https:";return Z.protocol==="https:"}catch{return!1}}function fJ(J){if(!J)return null;let Z=J.trim().replace(/\/+$/,"");return yJ(Z)?Z:null}function _2(J,Z){try{let $=new URL(J.trim());if($.protocol!=="https:"&&!o($))return!1;let Q=C($.hostname);for(let X of Z){if(!X)continue;let W=new URL(X);if(Q===C(W.hostname))return!0}return s(J)}catch{return!1}}var mJ=/(?:\/(?:global|workspaces))?\/graphql$/i,gJ=1048576;function v(J){return J.trim().replace(/\/+$/,"").replace(mJ,"")}function a(J,Z){return`${v(J)}/${Z}/graphql`}function t(J){return J instanceof Error?J.message:String(J)}async function pJ(J,Z){let $=J.headers.get("content-length");if($){let z=Number.parseInt($,10);if(Number.isInteger(z)&&z>Z)throw Error(`Gateway response is too large (${z} bytes)`)}if(!J.body)return"";let Q=J.body.getReader(),X=[],W=0;try{while(!0){let{done:z,value:Y}=await Q.read();if(z)break;if(!Y)continue;if(W+=Y.byteLength,W>Z)throw await Q.cancel().catch(()=>{return}),Error(`Gateway response exceeds ${Z} bytes`);X.push(Y)}}finally{Q.releaseLock()}let K=new Uint8Array(W),V=0;for(let z of X)K.set(z,V),V+=z.byteLength;return new TextDecoder().decode(K)}class R{config=null;token=null;authInFlight=null;configGeneration=0;configure(J){let Z=v(U(J.globalGatewayUrl,"globalGatewayUrl")),$=J.workspaceGatewayUrl?v(U(J.workspaceGatewayUrl,"workspaceGatewayUrl")):void 0,Q=J.clientId.trim(),X=J.clientSecret.trim();if(!Z)throw Error("globalGatewayUrl is required");if(!Q)throw Error("clientId is required");if(!X)throw Error("clientSecret is required");this.configGeneration+=1,this.config={...J,globalGatewayUrl:Z,workspaceGatewayUrl:$,clientId:Q,clientSecret:X,scopes:J.scopes?.map((W)=>W.trim()).filter(Boolean),workspaceId:J.workspaceId?.trim()||void 0,organizationId:J.organizationId?.trim()||void 0},this.token=null,this.authInFlight=null,B().logger.info("gateway-client","Gateway client configured",{globalGatewayUrl:this.config.globalGatewayUrl,workspaceGatewayUrl:this.config.workspaceGatewayUrl,clientId:this.config.clientId})}isConfigured(){return this.config!==null}getConfig(){if(!this.config)return null;let{clientSecret:J,...Z}=this.config;return Z}async getAccessToken(){let{token:J,config:Z}=await this.ensureToken();return{token:J,workspaceGatewayUrl:Z.workspaceGatewayUrl??"",globalGatewayUrl:Z.globalGatewayUrl??"",workspaceId:Z.workspaceId??""}}async globalQuery(J,Z){return this.executeQuery("global",J,Z)}async workspaceQuery(J,Z){return this.executeQuery("workspaces",J,Z)}async lookupPeerAgent(J,Z){if(!this.isConfigured())return null;try{let Q=(await this.workspaceQuery(`query AgentNetworkLookup($targetAgentRecordId: ID!, $operation: String!) {
7
7
  vibecontrolsAgentNetworkLookup(targetAgentRecordId: $targetAgentRecordId, operation: $operation) {
8
8
  tunnelUrl
9
9
  peerApiKey
@@ -18,4 +18,4 @@ import{Zd as c,_d as i,ae as l,de as n}from"./index-q9dp55wv.js";import{fe as g}
18
18
  }
19
19
  }
20
20
  `,variables:{input:{clientId:J.clientId,clientSecret:J.clientSecret,scopes:J.scopes??[]}}});if(Q.errors?.length||!Q.data?.authenticateApp){let K=Q.errors?.[0]?.message??"Authentication failed";throw B().logger.error("gateway-client",`Authentication failed: ${K}`),Error(`Gateway authentication failed: ${K}`)}let X=Q.data.authenticateApp,W={accessToken:X.accessToken,expiresAt:Date.now()+X.expiresIn*1000,scopes:X.scopes};if(Z!==this.configGeneration||J!==this.config)throw Error("Gateway configuration changed during authentication");return this.token=W,B().logger.info("gateway-client","Authenticated successfully",{expiresIn:X.expiresIn,scopes:X.scopes}),W.accessToken}async postGraphQL(J,Z,$){let Q;try{Q=await fetch(J,{method:"POST",headers:Z,body:JSON.stringify($),signal:AbortSignal.timeout(15000)})}catch(X){throw Error(`Could not reach gateway at ${J}: ${t(X)}`,{cause:X})}try{let X=await pJ(Q,gJ),W={};if(X)try{W=JSON.parse(X)}catch{let K=X.slice(0,240).replace(/\s+/g," ");throw Error(`Gateway returned a non-JSON response (${Q.status} ${Q.statusText}) from ${J}${K?`: ${K}`:""}`)}if(!Q.ok){let K=W.errors?.[0]?.message??`${Q.status} ${Q.statusText}`;throw Error(`Gateway request failed at ${J}: ${K} (${Q.status})`)}return W}catch(X){if(X instanceof Error)throw X;throw Error(`Failed to process gateway response from ${J}: ${t(X)}`,{cause:X})}}}function S(){let J=d();if(J)return J.gatewayClient;return B().gatewayClient}var uJ=new Proxy({},{get(J,Z,$){let Q=S(),X=Q[Z];return typeof X==="function"?X.bind(Q):X},set(J,Z,$){let Q=S();return Q[Z]=$,!0},has(J,Z){return Z in S()}}),E2=uJ;
21
- export{oJ as wd,sJ as xd,aJ as yd,G as zd,U as Ad,O2 as Bd,vJ as Cd,k2 as Dd,I2 as Ed,fJ as Fd,_2 as Gd,v as Hd,R as Id,uJ as Jd,E2 as Kd,B2 as Ld,d as Md,j as Nd,AJ as Od,B as Pd,G2 as Qd,b2 as Rd};
21
+ export{oJ as Dd,sJ as Ed,aJ as Fd,G as Gd,U as Hd,O2 as Id,vJ as Jd,k2 as Kd,I2 as Ld,fJ as Md,_2 as Nd,v as Od,R as Pd,uJ as Qd,E2 as Rd,B2 as Sd,d as Td,j as Ud,AJ as Vd,B as Wd,G2 as Xd,b2 as Yd};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
2
  import{randomBytes as G,timingSafeEqual as J}from"crypto";var M="x-vc-internal-auth",z=G(32).toString("hex");function U(){return z}function V(F){let j=F.get(M);if(!j)return!1;let w=Buffer.from(j),x=Buffer.from(z);return w.length===x.length&&J(w,x)}
3
- export{M as Rb,U as Sb,V as Tb};
3
+ export{M as Vb,U as Wb,V as Xb};
@@ -1,4 +1,4 @@
1
1
  // @bun
2
2
  import{isAbsolute as S,join as Z,relative as v,resolve as H}from"path";import{existsSync as E,readFileSync as m}from"fs";import{homedir as u}from"os";import{existsSync as F,mkdirSync as P,readFileSync as V,renameSync as j,writeFileSync as w}from"fs";import{homedir as I}from"os";import{dirname as N,join as U,resolve as b}from"path";var Q=new Map;async function B(q,z){let J=Q.get(q)??Promise.resolve(),$,K=new Promise((W)=>{$=W});Q.set(q,J.then(()=>K));try{return await J,await z()}finally{if($(),Q.get(q)===J.then(()=>K));queueMicrotask(()=>{let W=Q.get(q);if(!W)return;Promise.race([W,new Promise((D)=>{D(void 0)})]).then(()=>{if(Q.get(q)===W)Q.delete(q)})})}}var A="agents-registry";async function s(q){return B(A,q)}function T(){return b(process.env.VIBECONTROLS_HOME??U(I(),".boff","vibecontrols"))}var C=2,k="default";function M(){return U(T(),"agents.json")}function _(){let q=M();if(!F(q))return null;try{let z=JSON.parse(V(q,"utf8"));if(z&&typeof z==="object"&&!Array.isArray(z)&&"instances"in z)return z;return null}catch{return null}}function X(){let q=_();if(!q)return{schemaVersion:C,instances:[]};return q}function Y(q){let z=M();P(N(z),{recursive:!0});let J=`${z}.${process.pid}.tmp`,$={...q,schemaVersion:C};w(J,`${JSON.stringify($,null,2)}
3
3
  `,{encoding:"utf8",mode:384}),j(J,z)}function o(){return X().instances}function a(q){let z=X();Y({...z,instances:q})}function O(){try{let z=X().defaultProfile;if(z&&typeof z==="string"&&z.length>0)return z}catch{}return k}function n(q){if(!q||typeof q!=="string")throw Error("setDefaultProfile: name is required");let z=X();Y({...z,defaultProfile:q})}var R=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/,p=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;function G(q){if(!R.test(q))throw Error("Invalid VIBECONTROLS_PROFILE. Use 1-128 characters: letters, numbers, dot, underscore, or dash.");return q}function h(){let q=process.env.VIBECONTROLS_PROFILE;if(q)return G(q);let z=O();return G(z)}function zq(q){if(!p.test(q))throw Error("Agent name must use 1-64 characters: letters, numbers, dot, underscore, or dash.");return q}function Jq(q,z){let J=v(H(q),H(z));return J===""||!!J&&!J.startsWith("..")&&!S(J)}function L(){let q=x(),z=h();return Z(q,"agents",z)}function Qq(){return Z(x(),"agents")}function Wq(){return Z(L(),"agent-db")}function x(){return H(process.env.VIBECONTROLS_HOME??Z(u(),".boff","vibecontrols"))}var y="https://registry.npmjs.org/";function Zq(){if(process.env.VIBECONTROLS_REGISTRY)return process.env.VIBECONTROLS_REGISTRY;try{let q=Z(L(),"config.json");if(E(q)){let z=JSON.parse(m(q,"utf8"));if(z.registry)return z.registry}}catch{}return y}
4
- export{B as Sd,s as Td,o as Ud,a as Vd,O as Wd,n as Xd,G as Yd,h as Zd,zq as _d,Jq as $d,L as ae,Qq as be,Wq as ce,x as de,Zq as ee};
4
+ export{B as Zd,s as _d,o as $d,a as ae,O as be,n as ce,G as de,h as ee,zq as fe,Jq as ge,L as he,Qq as ie,Wq as je,x as ke,Zq as le};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Tb as GY}from"./index-5dysvvjv.js";import{Vb as JY}from"./index-zaw78sxw.js";import{Sc as jY,Tc as k,od as l,qd as d}from"./index-sv4rzv3f.js";import{Md as HY,Nd as BY,Pd as V}from"./index-c4p1qcnn.js";import{Zd as P}from"./index-q9dp55wv.js";import{randomBytes as K,createHmac as g,timingSafeEqual as UY}from"crypto";var T=600,r=600,A=K(32),M="p2.";function S(Y){if(!Y.startsWith("/"))return`/${Y}`;return Y.length>1&&Y.endsWith("/")?Y.slice(0,-1):Y}var wY=/^\/terminal\/[A-Za-z0-9_-]{1,128}(?:\/.*)?$/,XY=/^\/ui\/[a-z0-9-]{1,64}(?:\/.*)?$/,NY=/^\/plan\/[A-Za-z0-9_-]{1,128}(?:\/.*)?$/,bY=/^\/git(?:\/.*)?$/,OY="/ws/logs",LY=/^\/code-server(?:\/.*)?$/,CY=/^\/api\/plugins\/[a-z0-9-]{1,64}\/ui(?:\/.*)?$/;function a(Y){if(typeof Y!=="string"||Y.length===0)return!1;if(Y.includes("\x00")||Y.includes(`
2
+ import{Xb as GY}from"./index-bv1z3fxw.js";import{Zb as JY}from"./index-e0jbxcn1.js";import{Wc as jY,Xc as k,sd as l,ud as d}from"./index-a9x5swye.js";import{Td as HY,Ud as BY,Wd as V}from"./index-axgp7ryd.js";import{ee as P}from"./index-c4zn91z3.js";import{randomBytes as K,createHmac as g,timingSafeEqual as UY}from"crypto";var T=600,r=600,A=K(32),M="p2.";function S(Y){if(!Y.startsWith("/"))return`/${Y}`;return Y.length>1&&Y.endsWith("/")?Y.slice(0,-1):Y}var wY=/^\/terminal\/[A-Za-z0-9_-]{1,128}(?:\/.*)?$/,XY=/^\/ui\/[a-z0-9-]{1,64}(?:\/.*)?$/,NY=/^\/plan\/[A-Za-z0-9_-]{1,128}(?:\/.*)?$/,bY=/^\/git(?:\/.*)?$/,OY="/ws/logs",LY=/^\/code-server(?:\/.*)?$/,CY=/^\/api\/plugins\/[a-z0-9-]{1,64}\/ui(?:\/.*)?$/;function a(Y){if(typeof Y!=="string"||Y.length===0)return!1;if(Y.includes("\x00")||Y.includes(`
3
3
  `)||Y.includes("|"))return!1;if(Y.includes(".."))return!1;if(new Set(["/","/api","/api/agent","/api/plugins","/api/profiles","/health","/metrics","/ws","/api/ai","/api/logs"]).has(Y))return!1;if(wY.test(Y))return!0;if(XY.test(Y))return!0;if(NY.test(Y))return!0;if(bY.test(Y))return!0;if(Y===OY)return!0;if(LY.test(Y))return!0;if(CY.test(Y))return!0;return!1}var DY=new Set(["*","GET","HEAD","POST","PUT","PATCH","DELETE","OPTIONS"]);function MY(Y){if(!Y||Y.length===0)return["*"];let Z=new Set,$=[];for(let Q of Y){if(typeof Q!=="string")continue;let W=Q.toUpperCase();if(!DY.has(W))throw Error(`invalid method: ${Q}`);if(!Z.has(W))Z.add(W),$.push(W)}if($.length===0)return["*"];return $.sort()}function i(Y,Z){if(Y.includes("*"))return!0;return Y.includes(Z.toUpperCase())}var KY=/^[A-Za-z0-9_-]{1,128}$/;function SY(Y){return typeof Y==="string"&&KY.test(Y)}function h(Y,Z,$){return g("sha256",A).update(`${Y}
4
4
  ${Z}
5
5
  ${$}`).digest("hex")}var y=new Map;function kY(Y){for(let[Z,$]of y)if($<=Y)y.delete(Z)}function t(Y,Z){let $=Date.parse(Z);if(!Number.isFinite($))return;y.set(Y,$)}function e(Y){return kY(Date.now()),y.has(Y)}function c(Y,Z,$,Q){return g("sha256",A).update(`v2
@@ -13,4 +13,4 @@ ${$}`).digest("hex")}function aY(Y,Z=u){if(!SY(Y))throw Error("invalid sid");let
13
13
  ${Y}
14
14
  ${Z}
15
15
  ${$}`).digest("hex")}function eY(Y,Z=f){if(!gY(Y))throw Error("invalid plugin name");let $=Math.min(Math.max(1,Math.floor(Z||f)||f),_Y),Q=new Date(Date.now()+$*1000).toISOString(),W=K(16).toString("hex"),z=$Y(Y,Q,W);return{token:`${x}${Q}|${Y}|${W}|${z}`,expiresAt:Q}}function YZ(Y,Z){if(!Y||typeof Y!=="string")return!1;if(!Y.startsWith(x))return!1;let Q=Y.slice(x.length).split("|");if(Q.length!==4)return!1;let[W,z,J,j]=Q;if(!W||!z||!J||!j)return!1;if(z!==Z)return!1;if(!C(W))return!1;let G=$Y(z,W,J);return L(G,j)}function AY(Y,Z){let $;if(Y instanceof Headers)$=Y.get("cookie")??Y.get("Cookie")??void 0;else $=Y.cookie??Y.Cookie??void 0;if(!$)return null;let Q=`vt_ui_${Z}`;for(let W of $.split(";")){let z=W.indexOf("=");if(z===-1)continue;if(W.slice(0,z).trim()!==Q)continue;return W.slice(z+1).trim()||null}return null}function ZZ(Y,Z){return AY(Y.headers,Z)}import{timingSafeEqual as PY}from"crypto";var lY=["/health","/ui","/code-server","/terminal","/plan","/git","/api/agent/status","/api/agent/version","/api/agent/identity","/api/agent/terminal-exchange","/api/agent/ui-exchange","/api/agent/ui-exchange-plugin","/metrics"];function QY(Y,Z){if(!Z||Z==="/")return!1;let $=Z.endsWith("/")?Z.slice(0,-1):Z;return Y===$||Y.startsWith(`${$}/`)}function uY(Y){let Z=Y.replace(/^\/api\/profiles\/[^/]+/,"/api");return Z==="/api"?"/":Z}function fY(Y){let Z=/^\/api\/profiles\/([^/]+)(?:\/|$)/.exec(Y);if(!Z)return null;let $=Z[1];if(!$)return null;return $}function WY(Y,Z){let $=[Y],Q=uY(Y);if(Q!==Y)$.push(Q);for(let W of $){if(lY.some((z)=>QY(W,z)))return!0;if(Z.some((z)=>QY(W,z)))return!0}return!1}function VY(){let Y=new Uint8Array(32);return crypto.getRandomValues(Y),`vcak_${Buffer.from(Y).toString("base64url")}`}var U=null;function n(){return`${P()}:static-api-key`}async function vZ(){let Y=process.env.AGENT_API_KEY;if(Y)return U=Y,Y;let Z=n(),$=await jY(Z);if($)return U=$,$;let Q=l({dir:V().dataDir})["static-api-key"];if(Q){try{await k(Z,Q)}catch(z){V().logger.warn("auth","could not persist legacy api key into secrets backend",{error:String(z)})}return U=Q,Q}let W=VY();return await k(Z,W),U=W,V().logger.info("auth","Generated and persisted new agent API key"),V().audit.emit("agent","apikey.minted",{profile:P(),via:"loadAgentApiKey"}),W}function q(){let Y=process.env.AGENT_API_KEY;if(Y)return Y;if(U!==null)return U;let Z=l()["static-api-key"];if(Z)return U=Z,Z;let $=VY();U=$;try{d({"static-api-key":$},{dir:V().dataDir,scope:V().name})}catch{}return k(n(),$).catch(()=>{}),$}async function UZ(Y){if(process.env.AGENT_API_KEY)throw Error("AGENT_API_KEY is pinned via the environment \u2014 cannot rotate the key at runtime. Update the env var and restart.");let Z=(Y??"").trim();if(!/^vcak_[A-Za-z0-9_-]{16,}$/.test(Z))throw Error("Invalid agent API key format (expected vcak_<base64url>).");U=Z,await k(n(),Z);try{d({"static-api-key":Z},{dir:V().dataDir,scope:V().name})}catch{}V().audit.emit("agent","apikey.rotated",{profile:P(),via:"reset-key"})}function mY(Y){let Z=Y["x-agent-api-key"]??Y["X-Agent-Api-Key"];if(Z)return Z;let $=Y.authorization??Y.Authorization;if($?.startsWith("Bearer "))return $.slice(7);return null}function xY(Y){return!1}function hY(Y,Z){let $=mY(Object.fromEntries(Y.headers.entries()));if($)return $;if(!xY(Z))return null;try{let Q=new URL(Y.url).searchParams.get("apiKey");if(Q)return Q}catch{}return null}function F(Y,Z){let $=Buffer.from(Y),Q=Buffer.from(Z);if($.length!==Q.length)return!1;try{return PY($,Q)}catch{return!1}}function wZ(Y){if(!Y)return!1;return F(Y,q())}async function cY(Y,Z){if(!Y)return!1;let $=fY(Z);if($){let Q=BY.get($);if(Q){try{if(await Q.keyVault.match(Y))return!0}catch{}if($===V().name){try{if(await V().keyVault.match(Y))return!0}catch{}return F(Y,q())}return!1}}try{if(await V().keyVault.match(Y))return!0}catch{}if(F(Y,q()))return!0;if(oY(Y)!==null)return!0;return!1}function oY(Y){if(!Y)return null;if(F(Y,q()))return{name:"default",scopes:new Set(["admin"])};let Z=HY()??V(),$=l({dir:Z.dataDir}),Q=Date.now();for(let W of $.apiKeys??[]){if(!F(Y,W.key))continue;if(W.notBefore){let z=Date.parse(W.notBefore);if(Number.isFinite(z)&&Q<z)return null}if(W.expiresAt){let z=Date.parse(W.expiresAt);if(Number.isFinite(z)&&Q>=z)return null}return{name:W.name,scopes:new Set(W.scopes)}}return null}function XZ(Y,Z){if(!Y)return!1;if(Y.scopes.has("admin"))return!0;return Z.some(($)=>Y.scopes.has($))}var X=null;function p(Y,Z){try{V().audit.emit("auth",Y,Z)}catch{V().logger.warn("auth.audit",Y,Z)}}function pY(Y){let Z=new Set(Y());if(X===null)for(let $ of Z)p("plugin.public_path.declared",{path:$});else{for(let $ of Z)if(!X.has($))p("plugin.public_path.added",{path:$});for(let $ of X)if(!Z.has($))p("plugin.public_path.removed",{path:$})}return X=Z,Z}function NZ(){X=null}function zY(Y){if(!Y)return[];if(X===null)return[...pY(Y)];return[...X]}function bZ(Y){let Z=q();return V().logger.info("auth",`Agent API key: ${Z.substring(0,8)}****${Z.substring(Z.length-4)}`),new JY({name:"plugin/auth"}).decorate("apiKey",Z).derive(async({request:$,path:Q})=>{let W=zY(Y),z;if(WY(Q,W))z=!0;else if(GY($.headers))z=!0;else{let J=o($,Q);if(J&&YY(J,Q,$.method))z=!0;else{let j=hY($,Q);z=await cY(j,Q)}}return{isAuthenticated:z}}).onBeforeHandle(({isAuthenticated:$,request:Q,path:W,set:z})=>{let J=zY(Y);if(!$&&!WY(W,J)){if(o(Q,W))return z.status=401,{error:"invalid iframe token"};return z.status=401,{error:"Unauthorized",message:"Invalid or missing API key"}}}).as("global")}
16
- export{SY as tb,nY as ub,sY as vb,YY as wb,FY as xb,rY as yb,o as zb,aY as Ab,iY as Bb,IY as Cb,tY as Db,gY as Eb,eY as Fb,YZ as Gb,ZZ as Hb,vZ as Ib,q as Jb,UZ as Kb,mY as Lb,wZ as Mb,oY as Nb,XZ as Ob,NZ as Pb,bZ as Qb};
16
+ export{SY as xb,nY as yb,sY as zb,YY as Ab,FY as Bb,rY as Cb,o as Db,aY as Eb,iY as Fb,IY as Gb,tY as Hb,gY as Ib,eY as Jb,YZ as Kb,ZZ as Lb,vZ as Mb,q as Nb,UZ as Ob,mY as Pb,wZ as Qb,oY as Rb,XZ as Sb,NZ as Tb,bZ as Ub};