@vibecontrols/agent 2026.602.1 → 2026.602.3

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 (116) hide show
  1. package/dist/{agent-config-85pskv43.js → agent-config-4ppenhqp.js} +1 -1
  2. package/dist/{agent-ready-tracker-zp6p8e6f.js → agent-ready-tracker-kgs7td6t.js} +1 -1
  3. package/dist/app-9j2t5geq.js +2 -0
  4. package/dist/bootstrap-workspace-qgs6d5f0.js +2 -0
  5. package/dist/bootstrap.service-vg72w8pa.js +2 -0
  6. package/dist/{bridge-client-341r9rry.js → bridge-client-1fxza4p7.js} +1 -1
  7. package/dist/cli.js +1 -1
  8. package/dist/daemon-profile-gwdcqx0q.js +2 -0
  9. package/dist/esm-6f3dfn6v.js +2 -0
  10. package/dist/{finalize-retry-handle-registry-vv241fsq.js → finalize-retry-handle-registry-xnm9kxry.js} +1 -1
  11. package/dist/{finalize-retry-worker-xp1nhv3c.js → finalize-retry-worker-dvykrzed.js} +1 -1
  12. package/dist/gateway-client-9kwnmk89.js +2 -0
  13. package/dist/{getMachineId-bsd-a56s0v8c.js → getMachineId-bsd-753751sw.js} +1 -1
  14. package/dist/{getMachineId-darwin-w9k0yw9r.js → getMachineId-darwin-na1pranq.js} +1 -1
  15. package/dist/{getMachineId-linux-anh31jbf.js → getMachineId-linux-dmn0ncdm.js} +1 -1
  16. package/dist/{getMachineId-unsupported-5hv3pwca.js → getMachineId-unsupported-yv77j894.js} +1 -1
  17. package/dist/{getMachineId-win-njb8tery.js → getMachineId-win-9hmyqmm0.js} +1 -1
  18. package/dist/highlights-00fcgwwq.js +2 -0
  19. package/dist/highlights-23bc8zge.js +2 -0
  20. package/dist/highlights-4mhb2pb0.js +2 -0
  21. package/dist/highlights-q7w64nwb.js +2 -0
  22. package/dist/highlights-xwdw5xay.js +2 -0
  23. package/dist/{index-678rwfc0.js → index-0924jp9m.js} +1 -1
  24. package/dist/{index-c4xqp05z.js → index-11grwjm1.js} +41 -41
  25. package/dist/index-1evqt03m.js +11 -0
  26. package/dist/{index-z5a4yxzz.js → index-1mppacnx.js} +3 -3
  27. package/dist/{index-jw1k4vbk.js → index-4qq083yd.js} +1 -1
  28. package/dist/{index-d5ysy1yn.js → index-5dysvvjv.js} +1 -1
  29. package/dist/{index-n7qyrdr1.js → index-5wpck4aw.js} +1 -1
  30. package/dist/{index-mtm8cfyt.js → index-8053zege.js} +2 -2
  31. package/dist/{index-5mw3eshk.js → index-8nqp3a4d.js} +1 -1
  32. package/dist/{index-2xs9cvjn.js → index-8sdrhr3q.js} +2 -2
  33. package/dist/{index-6mprnf7p.js → index-97mq40rr.js} +1 -1
  34. package/dist/{index-1hnw0rhc.js → index-9f52em7g.js} +29 -29
  35. package/dist/{index-0cn9bv8z.js → index-a4854mwz.js} +1 -1
  36. package/dist/{index-g8zv1gta.js → index-atp2ayra.js} +1 -1
  37. package/dist/{index-xjzmb1pn.js → index-b6x6a4xp.js} +2 -2
  38. package/dist/{index-yy1mm8zs.js → index-c7554sg7.js} +1 -1
  39. package/dist/{index-2gsarrbn.js → index-d1xjj001.js} +1 -1
  40. package/dist/{index-h8a8s8sn.js → index-ebwwtwwc.js} +1 -1
  41. package/dist/{index-8sm0nkh8.js → index-ep3zb271.js} +1 -1
  42. package/dist/index-gxgftnbh.js +26 -0
  43. package/dist/{index-g2raeeh4.js → index-h74va4wd.js} +2 -2
  44. package/dist/{index-v9fx5wab.js → index-hvjqgb97.js} +1 -1
  45. package/dist/{index-g3ap3xpr.js → index-jdh30t6c.js} +4 -4
  46. package/dist/{index-9bqd8veb.js → index-js1xn4sq.js} +3 -3
  47. package/dist/{index-x1h8r7pr.js → index-kt5zxp42.js} +1 -1
  48. package/dist/{index-ssjmzqcz.js → index-n6bdbgb9.js} +1 -1
  49. package/dist/{index-rdp5xq4r.js → index-nrsqzcfc.js} +1 -1
  50. package/dist/index-p23tet7a.js +2 -0
  51. package/dist/{index-04n4qgvd.js → index-pgew6sge.js} +3 -3
  52. package/dist/{index-1zw3kea7.js → index-qwtspxw8.js} +1 -1
  53. package/dist/index-rqq0k5fc.js +16 -0
  54. package/dist/{index-6jq17k9s.js → index-rv6h14n8.js} +1 -1
  55. package/dist/{index-qfz9fy56.js → index-rw9x93zb.js} +1 -1
  56. package/dist/{index-dm6yjmgq.js → index-rzpaqrhx.js} +2 -2
  57. package/dist/{index-vdahdt49.js → index-tgrt61qr.js} +1 -1
  58. package/dist/{index-ef95xr4z.js → index-thammzct.js} +2 -2
  59. package/dist/{index-tp4y9jde.js → index-wccxsz72.js} +1 -1
  60. package/dist/{index-scsjyj4m.js → index-x649afed.js} +2 -2
  61. package/dist/{index-8kvc8ttn.js → index-xrs52f2c.js} +1 -1
  62. package/dist/{index-yrgm89r8.js → index-ydc0tk17.js} +1 -1
  63. package/dist/{index-0248afsn.js → index-z5s398n0.js} +1 -1
  64. package/dist/index.js +2 -2
  65. package/dist/injections-x3xya90r.js +2 -0
  66. package/dist/interactive-qc1j66mq.js +2 -0
  67. package/dist/key.cmd-972133dv.js +2 -0
  68. package/dist/log-shipper-hjnn1d5p.js +2 -0
  69. package/dist/{path-utils-35re7qf9.js → path-utils-hxdyv2zn.js} +1 -1
  70. package/dist/{plugin-system-c916v9an.js → plugin-system-8hby8x1m.js} +1 -1
  71. package/dist/prereqs-runner-27x3j1md.js +2 -0
  72. package/dist/profile-mount-8dc9jwt5.js +2 -0
  73. package/dist/prune-stale-shims-23y0stm8.js +2 -0
  74. package/dist/register-core-qcj272qh.js +2 -0
  75. package/dist/secondary-profile-attach-xkvpmm08.js +2 -0
  76. package/dist/subprocess-1nna3d3x.js +2 -0
  77. package/dist/telemetry-8jfdyt51.js +2 -0
  78. package/dist/tree-sitter-javascript-q22gvtms.js +2 -0
  79. package/dist/tree-sitter-markdown-pntsjzm3.js +2 -0
  80. package/dist/tree-sitter-markdown_inline-g1wzqf7k.js +2 -0
  81. package/dist/tree-sitter-typescript-m9yfes10.js +2 -0
  82. package/dist/tree-sitter-zig-jmh62j90.js +2 -0
  83. package/dist/tunnel-bootstrap-5wgt9a1h.js +2 -0
  84. package/package.json +1 -1
  85. package/dist/app-jeyyhz7s.js +0 -2
  86. package/dist/bootstrap-workspace-zpm20zez.js +0 -2
  87. package/dist/bootstrap.service-pjmnpxha.js +0 -2
  88. package/dist/daemon-profile-vas1vf2t.js +0 -2
  89. package/dist/esm-9fpye77x.js +0 -2
  90. package/dist/gateway-client-43gzvj5s.js +0 -2
  91. package/dist/highlights-8d9mgr01.js +0 -2
  92. package/dist/highlights-jwvdxm9x.js +0 -2
  93. package/dist/highlights-qbx2vnme.js +0 -2
  94. package/dist/highlights-r3m83kn9.js +0 -2
  95. package/dist/highlights-s7mqapt6.js +0 -2
  96. package/dist/index-01qzsnwd.js +0 -16
  97. package/dist/index-5t4t0avg.js +0 -26
  98. package/dist/index-hrdamx5j.js +0 -2
  99. package/dist/index-tmrbs96r.js +0 -11
  100. package/dist/injections-srewsjcz.js +0 -2
  101. package/dist/interactive-22ta89hc.js +0 -2
  102. package/dist/key.cmd-wgcq6kt8.js +0 -2
  103. package/dist/log-shipper-k24m8yw5.js +0 -2
  104. package/dist/prereqs-runner-ca4kt803.js +0 -2
  105. package/dist/profile-mount-npcknw6v.js +0 -2
  106. package/dist/prune-stale-shims-nkx9vq5m.js +0 -2
  107. package/dist/register-core-mbv4hrbv.js +0 -2
  108. package/dist/secondary-profile-attach-db5cr3e1.js +0 -2
  109. package/dist/subprocess-g9sk1ep9.js +0 -2
  110. package/dist/telemetry-tnq47dcs.js +0 -2
  111. package/dist/tree-sitter-javascript-3h25c6bs.js +0 -2
  112. package/dist/tree-sitter-markdown-3nemcjhe.js +0 -2
  113. package/dist/tree-sitter-markdown_inline-16ftwa53.js +0 -2
  114. package/dist/tree-sitter-typescript-f6mq6ze6.js +0 -2
  115. package/dist/tree-sitter-zig-s2trkm2d.js +0 -2
  116. package/dist/tunnel-bootstrap-2kg79ng8.js +0 -2
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{cb as Y,db as k}from"./index-52cp759f.js";import{Nd as W}from"./index-9bqd8veb.js";import{be as V}from"./index-0cn9bv8z.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;
2
+ import{cb as Y,db as k}from"./index-52cp759f.js";import{Od as W}from"./index-js1xn4sq.js";import{ce as V}from"./index-a4854mwz.js";import{createHash as g,randomUUID as x}from"crypto";import{existsSync as $,mkdirSync as L,readFileSync as O,writeFileSync as j}from"fs";import{join as K}from"path";import*as X from"os";var A="https://analytics.burdenoff.com/api/track",H="cd7d5ccc3667",w=200,f=10,B=30000,R=5000;function C(q){if(process.env.DO_NOT_TRACK==="1")return!1;let z=process.env.VIBECONTROLS_TELEMETRY?.toLowerCase();if(z==="on"||z==="true"||z==="1")return!0;if(z==="off"||z==="false"||z==="0")return!1;return q}class M{enabled=!1;persisted=!1;buffer=[];flushTimer=null;cachedAnonymousId=null;overflowWarned=!1;postFailureWarned=!1;initialized=!1;init(q){if(q?.persisted!==void 0)this.persisted=q.persisted;if(this.enabled=C(this.persisted),!this.initialized)this.initialized=!0,this.startFlushTimer()}setEnabled(q){let z=this.enabled;if(this.persisted=q,this.enabled=C(this.persisted),z&&!this.enabled)this.buffer=[],this.enqueueRaw("telemetry.disabled",{reason:"user_opt_out"}),this.flush()}emit(q,z={}){if(!this.enabled)return;let G={},J=!1;for(let[Z,N]of Object.entries(z)){if(Y(Z)){J=!0;continue}G[Z]=N}let Q=k(q,G);if(!Q.ok||!Q.sanitized){W().logger.warn("telemetry",`dropping event '${q}': ${Q.reason??"invalid"}`);return}this.enqueue(q,Q.sanitized)}enqueueRaw(q,z){this.enqueue(q,z)}enqueue(q,z){let G={site_id:H,event_name:q,properties:z,anonymous_id:this.getAnonymousId(),timestamp:new Date().toISOString()};if(this.buffer.length>=w){if(this.buffer.shift(),!this.overflowWarned)this.overflowWarned=!0,W().logger.warn("telemetry",`buffer overflow (cap=${w}) \u2014 dropping oldest events`)}if(this.buffer.push(G),this.buffer.length>=f)this.flush()}async flush(){if(this.buffer.length===0)return;let q=this.buffer.splice(0,this.buffer.length),z=new AbortController,G=setTimeout(()=>z.abort(),R);try{await fetch(A,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({events:q}),signal:z.signal})}catch(J){if(!this.postFailureWarned)this.postFailureWarned=!0,W().logger.warn("telemetry","shipper POST failed; dropping batch",{error:String(J)})}finally{clearTimeout(G)}}stop(){if(this.flushTimer)clearInterval(this.flushTimer),this.flushTimer=null;this.initialized=!1}_resetForTest(){this.stop(),this.enabled=!1,this.persisted=!1,this.buffer=[],this.cachedAnonymousId=null,this.overflowWarned=!1,this.postFailureWarned=!1}_bufferLength(){return this.buffer.length}_isEnabled(){return this.enabled}startFlushTimer(){if(this.flushTimer)return;if(this.flushTimer=setInterval(()=>{this.flush()},B),typeof this.flushTimer.unref==="function")this.flushTimer.unref()}getAnonymousId(){if(this.cachedAnonymousId)return this.cachedAnonymousId;let q=`${X.hostname()}${X.platform()}`,z=this.readOrCreateInstallId(),G=g("sha256").update(q+z).digest("hex");return this.cachedAnonymousId=G.slice(0,16),this.cachedAnonymousId}readOrCreateInstallId(){let q;try{q=V()}catch{q=K(process.cwd(),".boff","vibecontrols")}if(!$(q))try{L(q,{recursive:!0,mode:448})}catch{}let z=K(q,".install-id");if($(z))try{let J=O(z,"utf-8").trim();if(J)return J}catch{}let G=x();try{j(z,G,{mode:384})}catch{}return G}}var b=new M;
3
3
  export{b as bb};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{K as I}from"./index-2gsarrbn.js";import{Qb as G,Rb as D}from"./index-d5ysy1yn.js";import{Nd as H}from"./index-9bqd8veb.js";var j="prereqs-runner",q="plugin-mgr",v={status:null,install:null,satisfied:!0,pendingSudo:[],noProtocol:!0};function w(z,F){if(!z.apiPrefix)return null;return`${(z.apiPrefix.startsWith("/")?z.apiPrefix:`/${z.apiPrefix}`).replace(/\/+$/,"")}/prereqs${F}`}async function M(z,F,J){let Q=z.handle;if(typeof Q!=="function")return null;let Y=new Request(`http://agent.local${F}`,{method:J,headers:{"x-vc-profile-rewrite":"1",[G]:D()}}),K=await Q.call(z,Y);if(K.status===404)return null;if(!K.ok){let $=await K.text().catch(()=>"");throw Error(`prereqs ${J} ${F} \u2192 ${K.status} ${$}`)}return await K.json()}async function A(z,F,J,Q,Y={}){let K=w(z,"/status"),$=w(z,"/install");if(!K||!$)return v;let W=null;try{W=await M(J,K,"GET")}catch(V){H().logger.warn(j,`${z.name}: prereqs/status call failed`,{error:String(V)})}if(W===null)return v;if(W.satisfied||Y.skipInstall)return await x(Q,F,z.version,{status:W,install:null}),{status:W,install:null,satisfied:W.satisfied,pendingSudo:[],noProtocol:!1};let X=null;try{X=await M(J,$,"POST")}catch(V){H().logger.warn(j,`${z.name}: prereqs/install call failed`,{error:String(V)})}let B=W;try{let V=await M(J,K,"GET");if(V)B=V}catch{}if(await x(Q,F,z.version,{status:B,install:X}),X&&X.installed.length>0){let V=new Map;for(let Z of z.prerequisites??[])V.set(Z.name,Z.kind);I(F,X.installed.map((Z)=>({name:Z,kind:V.get(Z)??"binary"})))}return{status:B,install:X,satisfied:B.satisfied,pendingSudo:X?.pendingSudo??[],noProtocol:!1}}async function x(z,F,J,Q){if(!z)return;let Y=JSON.stringify({lastInstallAt:new Date().toISOString(),lastInstallVersion:J,satisfied:Q.status?.satisfied??!1,missing:Q.status?.missing??[],pendingSudo:Q.install?.pendingSudo??[]});try{await z.setPluginState(q,`prereqs:${F}`,Y)}catch(K){H().logger.warn(j,"Failed to persist prereq state",{packageName:F,error:String(K)})}}async function L(z,F){if(!z)return null;try{let J=await z.getPluginState(q,`prereqs:${F}`);return J?JSON.parse(J):null}catch{return null}}
2
+ import{K as I}from"./index-d1xjj001.js";import{Rb as G,Sb as D}from"./index-5dysvvjv.js";import{Od as H}from"./index-js1xn4sq.js";var j="prereqs-runner",q="plugin-mgr",v={status:null,install:null,satisfied:!0,pendingSudo:[],noProtocol:!0};function w(z,F){if(!z.apiPrefix)return null;return`${(z.apiPrefix.startsWith("/")?z.apiPrefix:`/${z.apiPrefix}`).replace(/\/+$/,"")}/prereqs${F}`}async function M(z,F,J){let Q=z.handle;if(typeof Q!=="function")return null;let Y=new Request(`http://agent.local${F}`,{method:J,headers:{"x-vc-profile-rewrite":"1",[G]:D()}}),K=await Q.call(z,Y);if(K.status===404)return null;if(!K.ok){let $=await K.text().catch(()=>"");throw Error(`prereqs ${J} ${F} \u2192 ${K.status} ${$}`)}return await K.json()}async function A(z,F,J,Q,Y={}){let K=w(z,"/status"),$=w(z,"/install");if(!K||!$)return v;let W=null;try{W=await M(J,K,"GET")}catch(V){H().logger.warn(j,`${z.name}: prereqs/status call failed`,{error:String(V)})}if(W===null)return v;if(W.satisfied||Y.skipInstall)return await x(Q,F,z.version,{status:W,install:null}),{status:W,install:null,satisfied:W.satisfied,pendingSudo:[],noProtocol:!1};let X=null;try{X=await M(J,$,"POST")}catch(V){H().logger.warn(j,`${z.name}: prereqs/install call failed`,{error:String(V)})}let B=W;try{let V=await M(J,K,"GET");if(V)B=V}catch{}if(await x(Q,F,z.version,{status:B,install:X}),X&&X.installed.length>0){let V=new Map;for(let Z of z.prerequisites??[])V.set(Z.name,Z.kind);I(F,X.installed.map((Z)=>({name:Z,kind:V.get(Z)??"binary"})))}return{status:B,install:X,satisfied:B.satisfied,pendingSudo:X?.pendingSudo??[],noProtocol:!1}}async function x(z,F,J,Q){if(!z)return;let Y=JSON.stringify({lastInstallAt:new Date().toISOString(),lastInstallVersion:J,satisfied:Q.status?.satisfied??!1,missing:Q.status?.missing??[],pendingSudo:Q.install?.pendingSudo??[]});try{await z.setPluginState(q,`prereqs:${F}`,Y)}catch(K){H().logger.warn(j,"Failed to persist prereq state",{packageName:F,error:String(K)})}}async function L(z,F){if(!z)return null;try{let J=await z.getPluginState(q,`prereqs:${F}`);return J?JSON.parse(J):null}catch{return null}}
3
3
  export{A as d,L as e};
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
- import{j as o,k as r,l as t,m as e,n as XQ}from"./index-5t4t0avg.js";import"./index-n7qyrdr1.js";import{t as QQ}from"./index-6jq17k9s.js";import"./index-1hnw0rhc.js";import"./index-6jzsthh9.js";import"./index-g8zv1gta.js";import"./index-qfz9fy56.js";import"./index-ssjmzqcz.js";import"./index-tp4y9jde.js";import"./index-4wgjx8bf.js";import{Da as a}from"./index-g3ap3xpr.js";import"./index-0ckffygp.js";import"./index-rc79x8fw.js";import{bb as W}from"./index-yrgm89r8.js";import"./index-52cp759f.js";import"./index-v9fx5wab.js";import{Ib as s,Jb as i}from"./index-01qzsnwd.js";import"./index-d5ysy1yn.js";import"./index-04n4qgvd.js";import"./index-xjzmb1pn.js";import{Rc as p,Sc as v,nd as C,td as l,ud as n}from"./index-g2raeeh4.js";import{Nd as q}from"./index-9bqd8veb.js";import{Xd as D,_d as S,ae as g,be as M}from"./index-0cn9bv8z.js";import"./index-jw1k4vbk.js";import{he as B}from"./index-yy1mm8zs.js";import{isAbsolute as MQ}from"path";import{existsSync as V,mkdirSync as y,readFileSync as _Q,readdirSync as P,renameSync as BQ,unlinkSync as DQ,writeFileSync as f}from"fs";import{dirname as d,join as F}from"path";var GQ=".secrets-migrated-v1",IQ=["static-api-key","clientId","clientSecret"];function WQ(Q,H){return`${Q}:${H}`}function c(){return F(M(),GQ)}function TQ(){let Q=c();y(d(Q),{recursive:!0}),f(Q,`${new Date().toISOString()}
3
+ import{j as o,k as r,l as t,m as e,n as XQ}from"./index-gxgftnbh.js";import"./index-5wpck4aw.js";import{t as QQ}from"./index-rv6h14n8.js";import"./index-9f52em7g.js";import"./index-6jzsthh9.js";import"./index-atp2ayra.js";import"./index-rw9x93zb.js";import"./index-n6bdbgb9.js";import"./index-wccxsz72.js";import"./index-4wgjx8bf.js";import{Da as a}from"./index-jdh30t6c.js";import"./index-0ckffygp.js";import"./index-rc79x8fw.js";import{bb as W}from"./index-ydc0tk17.js";import"./index-52cp759f.js";import"./index-hvjqgb97.js";import{Ib as s,Jb as i}from"./index-rqq0k5fc.js";import"./index-5dysvvjv.js";import"./index-pgew6sge.js";import"./index-b6x6a4xp.js";import{Sc as p,Tc as v,od as C,ud as l,vd as n}from"./index-h74va4wd.js";import{Od as q}from"./index-js1xn4sq.js";import{$d as S,Yd as D,be as g,ce as M}from"./index-a4854mwz.js";import"./index-4qq083yd.js";import{ie as B}from"./index-c7554sg7.js";import{isAbsolute as MQ}from"path";import{existsSync as V,mkdirSync as y,readFileSync as _Q,readdirSync as P,renameSync as BQ,unlinkSync as DQ,writeFileSync as f}from"fs";import{dirname as d,join as F}from"path";var GQ=".secrets-migrated-v1",IQ=["static-api-key","clientId","clientSecret"];function WQ(Q,H){return`${Q}:${H}`}function c(){return F(M(),GQ)}function TQ(){let Q=c();y(d(Q),{recursive:!0}),f(Q,`${new Date().toISOString()}
4
4
  `,{mode:384})}function JQ(Q){if(!V(Q))return null;try{let H=_Q(Q,"utf8"),X=JSON.parse(H);if(X&&typeof X==="object"&&!Array.isArray(X))return X}catch{}return null}function VQ(Q,H){y(d(Q),{recursive:!0});let X=`${Q}.${process.pid}.tmp`;f(X,`${JSON.stringify(H,null,2)}
5
- `,{mode:384}),BQ(X,Q)}function FQ(){let Q=M(),H=F(Q,"agents");if(!V(H))return[];let X=[],L;try{L=P(H)}catch{return[]}for(let Y of L){let z=F(H,Y,"config.json");if(!V(z))continue;X.push({path:z,scope:Y})}return X}function jQ(){let Q=M(),H=F(Q,"profiles");if(!V(H))return[];let X=[],L;try{L=P(H)}catch{return[]}for(let Y of L){if(!Y.endsWith(".json"))continue;X.push({path:F(H,Y),scope:Y.slice(0,-5)})}return X}async function KQ(Q,H){let X=JQ(Q);if(!X)return 0;let L=0;for(let Y of IQ){let z=X[Y];if(typeof z!=="string"||z.length===0)continue;let _=WQ(H,Y);try{await v(_,z),delete X[Y],L++,q().logger.info("secrets-migrator","migrated field",{path:Q,scope:H,key:Y})}catch(G){q().logger.warn("secrets-migrator","failed to migrate field",{path:Q,scope:H,key:Y,error:String(G)})}}if(L>0)VQ(Q,X);return L}async function m(){let Q={alreadyMigrated:!1,fieldsMoved:0,filesUpdated:0};if(V(c()))return Q.alreadyMigrated=!0,Q;let H=[...FQ(),...jQ()];for(let X of H){let L;try{L=await KQ(X.path,X.scope)}catch(Y){q().logger.warn("secrets-migrator","skipping target after error",{path:X.path,error:String(Y)});continue}if(L>0)Q.fieldsMoved+=L,Q.filesUpdated++}try{TQ()}catch(X){q().logger.warn("secrets-migrator","failed to drop migration marker",{error:String(X)})}if(Q.fieldsMoved>0)q().logger.info("secrets-migrator","migration complete",{fieldsMoved:Q.fieldsMoved,filesUpdated:Q.filesUpdated});return Q}{let Q=JSON.parse.bind(JSON);JSON.parse=(L,Y)=>{try{return Q(L,Y)}catch(z){if(typeof L==="string"&&L.endsWith("}}"))try{return Q(L.slice(0,-1),Y)}catch{}throw z}};let X=globalThis.Request?.prototype;if(X&&typeof X.json==="function"){let L=X.json;X.json=async function(){let z=await this.text();if(!z)return;try{return Q(z)}catch{if(z.endsWith("}}"))try{return Q(z.slice(0,-1))}catch{}let _=new Request("http://shim/",{method:"POST",body:z});return L.call(_)}}}}QQ();l();if(!process.env.VIBECONTROLS_DATA_DIR)process.env.VIBECONTROLS_DATA_DIR=S();if(typeof Bun>"u")console.error("ERROR: VibeControls Agent requires Bun runtime."),console.error("Install Bun: https://bun.sh"),process.exit(1);function UQ(Q){if(Q==="default")return 3005;let H=2166136261;for(let X=0;X<Q.length;X++)H=Math.imul(H^Q.charCodeAt(X),16777619);return 3100+Math.abs(H)%300}var E=(()=>{try{return D()}catch{return"default"}})(),A=Number.parseInt(process.env.PORT||String(UQ(E)),10),U=Number.isInteger(A)&&A>0?A:3005,R=process.env.HOST||"0.0.0.0",RQ=(()=>{let Q=process.env.DB_PATH;if(!Q)return;if(MQ(Q))return Q;console.warn(`[boot] Ignoring relative DB_PATH=${Q} (cwd=${process.cwd()}). Use an absolute path or unset to fall back to ${g()}.`);return})(),x=process.env.AGENT_API_KEY||void 0,CQ=process.env.LOG_LEVEL||"info",EQ=process.env.CORS_ORIGIN||void 0;async function wQ(){try{await m()}catch($){q().logger.warn("server","secrets migration encountered an error",{error:String($)})}let Q=C()["static-api-key"],H=(()=>{try{return D()}catch{return"default"}})(),X=Q??await p(`${H}:static-api-key`),L=!x&&!X;await s(),await n();let Y=process.env.VIBE_CLIENT_ID,z=process.env.VIBE_CLIENT_SECRET,_=process.env.VIBE_GLOBAL_GATEWAY_URL,G=process.env.VIBE_WORKSPACE_GATEWAY_URL,b=process.env.VIBE_WORKSPACE_ID,ZQ=!!Y&&!!z&&!!_&&!!G&&!!b;q().logger.info("server","Starting VibeControls Agent...",{runtime:"bun",bunVersion:Bun.version,port:U,host:R,env:"production"});try{let $=C(),Z=$["telemetry.enabled"]===!0||$["telemetry.enabled"]==="true";W.init({persisted:Z});let N=Date.now();W.emit("agent.started",{version:process.env.npm_package_version??"unknown",profile:E,platform:process.platform}),process.__vibe_started_at=N}catch{}let j=Math.max(1,Number.parseInt(process.env.VIBECONTROLS_AGENT_BOOT_RETRIES??"10",10)||10),$Q=($)=>{let Z=String($?.message??$).toLowerCase();return Z.includes("syntax")||Z.includes("cannot find module")||Z.includes("module not found")||Z.includes("typeerror")||Z.includes("config schema")||Z.includes("invalid config")||Z.includes("corrupt")||Z.includes("eaccess")||Z.includes("eperm")},O=null,I=0;while(!O){I++;try{O=await XQ({port:U,host:R,dbPath:RQ,apiKey:x,logLevel:CQ,corsOrigin:EQ}),await O.start();try{let $=await import("fs"),Z=`${S()}/runtime.json`;$.writeFileSync(Z,JSON.stringify({pid:process.pid,port:U,host:R,profile:E,startedAt:new Date().toISOString(),version:a()},null,2));let N=()=>{try{if($.existsSync(Z))$.unlinkSync(Z)}catch{}};process.once("SIGTERM",N),process.once("SIGINT",N),process.once("exit",N)}catch($){q().logger.warn("server","Could not write runtime.json",{error:String($)})}}catch($){let Z=$Q($);if(q().logger.error("server","Failed to start agent server",{attempt:I,maxBootAttempts:j,fatal:Z,error:String($)}),Z||I>=j)console.error(`\u274C Failed to start VibeControls Agent (attempt ${I}/${j}, fatal=${Z}):`,$),process.exit(1);let N=Math.min(30000,1000*2**Math.min(5,I-1)),J=Math.floor(Math.random()*500),K=N+J;console.warn(`\u26A0\uFE0F Agent boot attempt ${I}/${j} failed (transient), retrying in ${Math.round(K/1000)}s...`),await new Promise((k)=>setTimeout(k,K)),O=null}}let h=O.getServiceRegistry().getProvider("tunnel"),T=null;if(h?.getActiveTunnelUrl)for(let $=0;$<30;$++){if(T=await h.getActiveTunnelUrl(),T)break;await new Promise((Z)=>setTimeout(Z,1000))}if(!T){let{sanitizeEnvSuffix:$}=await import("./tunnel-bootstrap-2kg79ng8.js"),{getVibecontrolsProfile:Z}=await import("./path-utils-35re7qf9.js"),N=$(Z());T=process.env[`AGENT_TUNNEL_URL_${N}`]??process.env.AGENT_TUNNEL_URL??null}let HQ=C(),LQ=x||i()||HQ["static-api-key"]||"",w=q().getBootState(),YQ=w==="ready"?null:o();if(w==="ready")r();kQ({port:U,host:R,tunnelUrl:T,apiKey:LQ,revealApiKey:L||process.env.AGENT_PRINT_API_KEY==="1",state:w,pairingToken:YQ});try{t({profile:E})}catch($){q().logger.warn("server","Could not start autoupdate",{error:String($)})}let{existsSync:NQ,unlinkSync:qQ}=await import("fs"),{tmpdir:zQ}=await import("os"),{join:OQ}=await import("path"),u=async($)=>{q().logger.info("server",`Received ${$}, shutting down...`),e();try{let N=process.__vibe_started_at??Date.now();W.emit("agent.stopped",{uptime_s:Math.round((Date.now()-N)/1000),reason:$}),await W.flush(),W.stop()}catch{}let Z=O.getLifecycle();if($==="SIGTERM"){let N=OQ(zQ(),`.boff-vibecontrols-kill-${process.pid}`);if(NQ(N)){try{qQ(N)}catch{}if(q().logger.info("server","Kill-intent flag detected \u2014 full shutdown"),Z)await Z.kill();else await O.stop({reason:"shutdown"}),process.exit(0)}else if(q().logger.info("server","No kill flag \u2014 treating as hot-reload (soft stop)"),Z)await Z.softStop();else await O.stop({reason:"reload"})}else if(Z)await Z.kill();else await O.stop({reason:"shutdown"}),process.exit(0)};if(process.on("SIGINT",()=>u("SIGINT")),process.on("SIGTERM",()=>u("SIGTERM")),ZQ){let $=(()=>{let Z=process.env.VIBECONTROLS_FINALIZE_TIMEOUT_MS,N=Z?Number.parseInt(Z,10):NaN;return Number.isFinite(N)&&N>0?N:300000})();q().logger.info("server",`VIBE_* env vars detected \u2014 running inline finalize (timeout ${Math.round($/1000)}s)`),(async()=>{let Z={clientId:Y,clientSecret:z,workspaceId:b,globalGatewayUrl:_,workspaceGatewayUrl:G};try{let N=await Promise.race([O.finalize(Z),new Promise((J)=>setTimeout(()=>J({ok:!1,error:`inline finalize timed out after ${Math.round($/1000)}s`}),$))]);if(!N.ok){q().logger.warn("server","Inline finalize failed \u2014 agent stays awaiting-config. Background retry worker will keep trying.",{error:N.error});let{startFinalizeRetryWorker:J}=await import("./finalize-retry-worker-xp1nhv3c.js"),{setFinalizeRetryHandle:K}=await import("./finalize-retry-handle-registry-vv241fsq.js"),k=J({trigger:()=>O.finalize(Z)});K(k)}}catch(N){q().logger.error("server","Inline finalize threw",{error:String(N)})}})()}else q().logger.info("server","Agent is awaiting gateway credentials. Add it on the VibeControls platform using the tunnel URL and API key shown above.")}function kQ(Q){let X=(G)=>("\u2551 "+G).padEnd(65)+"\u2551",L="\u2560"+"\u2550".repeat(64)+"\u2563",Y="\u2554"+"\u2550".repeat(64)+"\u2557",z="\u255A"+"\u2550".repeat(64)+"\u255D",_=Q.revealApiKey?Q.apiKey:Q.apiKey?`${Q.apiKey.substring(0,8)}****${Q.apiKey.substring(Q.apiKey.length-4)}`:"(none)";if(console.log(""),console.log(Y),console.log(X("VibeControls Agent")),console.log(L),console.log(X(`State: ${Q.state}`)),console.log(X(`Agent URL: http://${Q.host}:${Q.port}`)),console.log(X(`API Key: ${_}`)),console.log(X(`Tunnel URL: ${Q.tunnelUrl??"(none)"}`)),Q.pairingToken)console.log(X(`Pairing: ${Q.pairingToken}`)),console.log(X(" (send as x-pairing-token on bootstrap)"));if(console.log(L),console.log(X(`Health: http://localhost:${Q.port}/health`)),console.log(X(`Status: http://localhost:${Q.port}/api/agent/status`)),console.log(z),!Q.revealApiKey)console.log(" (Set AGENT_PRINT_API_KEY=1 to print the API key in full.)");console.log("")}wQ();
5
+ `,{mode:384}),BQ(X,Q)}function FQ(){let Q=M(),H=F(Q,"agents");if(!V(H))return[];let X=[],L;try{L=P(H)}catch{return[]}for(let Y of L){let z=F(H,Y,"config.json");if(!V(z))continue;X.push({path:z,scope:Y})}return X}function jQ(){let Q=M(),H=F(Q,"profiles");if(!V(H))return[];let X=[],L;try{L=P(H)}catch{return[]}for(let Y of L){if(!Y.endsWith(".json"))continue;X.push({path:F(H,Y),scope:Y.slice(0,-5)})}return X}async function KQ(Q,H){let X=JQ(Q);if(!X)return 0;let L=0;for(let Y of IQ){let z=X[Y];if(typeof z!=="string"||z.length===0)continue;let _=WQ(H,Y);try{await v(_,z),delete X[Y],L++,q().logger.info("secrets-migrator","migrated field",{path:Q,scope:H,key:Y})}catch(G){q().logger.warn("secrets-migrator","failed to migrate field",{path:Q,scope:H,key:Y,error:String(G)})}}if(L>0)VQ(Q,X);return L}async function m(){let Q={alreadyMigrated:!1,fieldsMoved:0,filesUpdated:0};if(V(c()))return Q.alreadyMigrated=!0,Q;let H=[...FQ(),...jQ()];for(let X of H){let L;try{L=await KQ(X.path,X.scope)}catch(Y){q().logger.warn("secrets-migrator","skipping target after error",{path:X.path,error:String(Y)});continue}if(L>0)Q.fieldsMoved+=L,Q.filesUpdated++}try{TQ()}catch(X){q().logger.warn("secrets-migrator","failed to drop migration marker",{error:String(X)})}if(Q.fieldsMoved>0)q().logger.info("secrets-migrator","migration complete",{fieldsMoved:Q.fieldsMoved,filesUpdated:Q.filesUpdated});return Q}{let Q=JSON.parse.bind(JSON);JSON.parse=(L,Y)=>{try{return Q(L,Y)}catch(z){if(typeof L==="string"&&L.endsWith("}}"))try{return Q(L.slice(0,-1),Y)}catch{}throw z}};let X=globalThis.Request?.prototype;if(X&&typeof X.json==="function"){let L=X.json;X.json=async function(){let z=await this.text();if(!z)return;try{return Q(z)}catch{if(z.endsWith("}}"))try{return Q(z.slice(0,-1))}catch{}let _=new Request("http://shim/",{method:"POST",body:z});return L.call(_)}}}}QQ();l();if(!process.env.VIBECONTROLS_DATA_DIR)process.env.VIBECONTROLS_DATA_DIR=S();if(typeof Bun>"u")console.error("ERROR: VibeControls Agent requires Bun runtime."),console.error("Install Bun: https://bun.sh"),process.exit(1);function UQ(Q){if(Q==="default")return 3005;let H=2166136261;for(let X=0;X<Q.length;X++)H=Math.imul(H^Q.charCodeAt(X),16777619);return 3100+Math.abs(H)%300}var E=(()=>{try{return D()}catch{return"default"}})(),A=Number.parseInt(process.env.PORT||String(UQ(E)),10),U=Number.isInteger(A)&&A>0?A:3005,R=process.env.HOST||"0.0.0.0",RQ=(()=>{let Q=process.env.DB_PATH;if(!Q)return;if(MQ(Q))return Q;console.warn(`[boot] Ignoring relative DB_PATH=${Q} (cwd=${process.cwd()}). Use an absolute path or unset to fall back to ${g()}.`);return})(),x=process.env.AGENT_API_KEY||void 0,CQ=process.env.LOG_LEVEL||"info",EQ=process.env.CORS_ORIGIN||void 0;async function wQ(){try{await m()}catch($){q().logger.warn("server","secrets migration encountered an error",{error:String($)})}let Q=C()["static-api-key"],H=(()=>{try{return D()}catch{return"default"}})(),X=Q??await p(`${H}:static-api-key`),L=!x&&!X;await s(),await n();let Y=process.env.VIBE_CLIENT_ID,z=process.env.VIBE_CLIENT_SECRET,_=process.env.VIBE_GLOBAL_GATEWAY_URL,G=process.env.VIBE_WORKSPACE_GATEWAY_URL,b=process.env.VIBE_WORKSPACE_ID,ZQ=!!Y&&!!z&&!!_&&!!G&&!!b;q().logger.info("server","Starting VibeControls Agent...",{runtime:"bun",bunVersion:Bun.version,port:U,host:R,env:"production"});try{let $=C(),Z=$["telemetry.enabled"]===!0||$["telemetry.enabled"]==="true";W.init({persisted:Z});let N=Date.now();W.emit("agent.started",{version:process.env.npm_package_version??"unknown",profile:E,platform:process.platform}),process.__vibe_started_at=N}catch{}let j=Math.max(1,Number.parseInt(process.env.VIBECONTROLS_AGENT_BOOT_RETRIES??"10",10)||10),$Q=($)=>{let Z=String($?.message??$).toLowerCase();return Z.includes("syntax")||Z.includes("cannot find module")||Z.includes("module not found")||Z.includes("typeerror")||Z.includes("config schema")||Z.includes("invalid config")||Z.includes("corrupt")||Z.includes("eaccess")||Z.includes("eperm")},O=null,I=0;while(!O){I++;try{O=await XQ({port:U,host:R,dbPath:RQ,apiKey:x,logLevel:CQ,corsOrigin:EQ}),await O.start();try{let $=await import("fs"),Z=`${S()}/runtime.json`;$.writeFileSync(Z,JSON.stringify({pid:process.pid,port:U,host:R,profile:E,startedAt:new Date().toISOString(),version:a()},null,2));let N=()=>{try{if($.existsSync(Z))$.unlinkSync(Z)}catch{}};process.once("SIGTERM",N),process.once("SIGINT",N),process.once("exit",N)}catch($){q().logger.warn("server","Could not write runtime.json",{error:String($)})}}catch($){let Z=$Q($);if(q().logger.error("server","Failed to start agent server",{attempt:I,maxBootAttempts:j,fatal:Z,error:String($)}),Z||I>=j)console.error(`\u274C Failed to start VibeControls Agent (attempt ${I}/${j}, fatal=${Z}):`,$),process.exit(1);let N=Math.min(30000,1000*2**Math.min(5,I-1)),J=Math.floor(Math.random()*500),K=N+J;console.warn(`\u26A0\uFE0F Agent boot attempt ${I}/${j} failed (transient), retrying in ${Math.round(K/1000)}s...`),await new Promise((k)=>setTimeout(k,K)),O=null}}let h=O.getServiceRegistry().getProvider("tunnel"),T=null;if(h?.getActiveTunnelUrl)for(let $=0;$<30;$++){if(T=await h.getActiveTunnelUrl(),T)break;await new Promise((Z)=>setTimeout(Z,1000))}if(!T){let{sanitizeEnvSuffix:$}=await import("./tunnel-bootstrap-5wgt9a1h.js"),{getVibecontrolsProfile:Z}=await import("./path-utils-hxdyv2zn.js"),N=$(Z());T=process.env[`AGENT_TUNNEL_URL_${N}`]??process.env.AGENT_TUNNEL_URL??null}let HQ=C(),LQ=x||i()||HQ["static-api-key"]||"",w=q().getBootState(),YQ=w==="ready"?null:o();if(w==="ready")r();kQ({port:U,host:R,tunnelUrl:T,apiKey:LQ,revealApiKey:L||process.env.AGENT_PRINT_API_KEY==="1",state:w,pairingToken:YQ});try{t({profile:E})}catch($){q().logger.warn("server","Could not start autoupdate",{error:String($)})}let{existsSync:NQ,unlinkSync:qQ}=await import("fs"),{tmpdir:zQ}=await import("os"),{join:OQ}=await import("path"),u=async($)=>{q().logger.info("server",`Received ${$}, shutting down...`),e();try{let N=process.__vibe_started_at??Date.now();W.emit("agent.stopped",{uptime_s:Math.round((Date.now()-N)/1000),reason:$}),await W.flush(),W.stop()}catch{}let Z=O.getLifecycle();if($==="SIGTERM"){let N=OQ(zQ(),`.boff-vibecontrols-kill-${process.pid}`);if(NQ(N)){try{qQ(N)}catch{}if(q().logger.info("server","Kill-intent flag detected \u2014 full shutdown"),Z)await Z.kill();else await O.stop({reason:"shutdown"}),process.exit(0)}else if(q().logger.info("server","No kill flag \u2014 treating as hot-reload (soft stop)"),Z)await Z.softStop();else await O.stop({reason:"reload"})}else if(Z)await Z.kill();else await O.stop({reason:"shutdown"}),process.exit(0)};if(process.on("SIGINT",()=>u("SIGINT")),process.on("SIGTERM",()=>u("SIGTERM")),ZQ){let $=(()=>{let Z=process.env.VIBECONTROLS_FINALIZE_TIMEOUT_MS,N=Z?Number.parseInt(Z,10):NaN;return Number.isFinite(N)&&N>0?N:300000})();q().logger.info("server",`VIBE_* env vars detected \u2014 running inline finalize (timeout ${Math.round($/1000)}s)`),(async()=>{let Z={clientId:Y,clientSecret:z,workspaceId:b,globalGatewayUrl:_,workspaceGatewayUrl:G};try{let N=await Promise.race([O.finalize(Z),new Promise((J)=>setTimeout(()=>J({ok:!1,error:`inline finalize timed out after ${Math.round($/1000)}s`}),$))]);if(!N.ok){q().logger.warn("server","Inline finalize failed \u2014 agent stays awaiting-config. Background retry worker will keep trying.",{error:N.error});let{startFinalizeRetryWorker:J}=await import("./finalize-retry-worker-dvykrzed.js"),{setFinalizeRetryHandle:K}=await import("./finalize-retry-handle-registry-xnm9kxry.js"),k=J({trigger:()=>O.finalize(Z)});K(k)}}catch(N){q().logger.error("server","Inline finalize threw",{error:String(N)})}})()}else q().logger.info("server","Agent is awaiting gateway credentials. Add it on the VibeControls platform using the tunnel URL and API key shown above.")}function kQ(Q){let X=(G)=>("\u2551 "+G).padEnd(65)+"\u2551",L="\u2560"+"\u2550".repeat(64)+"\u2563",Y="\u2554"+"\u2550".repeat(64)+"\u2557",z="\u255A"+"\u2550".repeat(64)+"\u255D",_=Q.revealApiKey?Q.apiKey:Q.apiKey?`${Q.apiKey.substring(0,8)}****${Q.apiKey.substring(Q.apiKey.length-4)}`:"(none)";if(console.log(""),console.log(Y),console.log(X("VibeControls Agent")),console.log(L),console.log(X(`State: ${Q.state}`)),console.log(X(`Agent URL: http://${Q.host}:${Q.port}`)),console.log(X(`API Key: ${_}`)),console.log(X(`Tunnel URL: ${Q.tunnelUrl??"(none)"}`)),Q.pairingToken)console.log(X(`Pairing: ${Q.pairingToken}`)),console.log(X(" (send as x-pairing-token on bootstrap)"));if(console.log(L),console.log(X(`Health: http://localhost:${Q.port}/health`)),console.log(X(`Status: http://localhost:${Q.port}/api/agent/status`)),console.log(z),!Q.revealApiKey)console.log(" (Set AGENT_PRINT_API_KEY=1 to print the API key in full.)");console.log("")}wQ();
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import"./index-c7554sg7.js";var t="./injections-73j83es3.scm";export{t as default};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{Fc as a,Gc as b,Hc as c,Ic as d,Jc as e}from"./index-thammzct.js";import"./index-c7554sg7.js";export{a as stripAnsi,b as interactiveTable,d as interactiveSelect,c as interactiveDetail,e as interactiveCheckboxes};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{Wb as a,Xb as b}from"./index-rzpaqrhx.js";import"./index-8sdrhr3q.js";import"./index-8nqp3a4d.js";import"./index-1mppacnx.js";import"./index-thammzct.js";import"./index-b6x6a4xp.js";import"./index-h74va4wd.js";import"./index-js1xn4sq.js";import"./index-a4854mwz.js";import"./index-4qq083yd.js";import"./index-c7554sg7.js";export{a as resolveDefaultApiKey,b as register};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{ee as a}from"./index-4qq083yd.js";import"./index-c7554sg7.js";export{a as logShipper};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{$d as f,Wd as a,Xd as b,Yd as c,Zd as d,_d as e,ae as g,be as h,ce as i}from"./index-0cn9bv8z.js";import"./index-yy1mm8zs.js";export{c as validateAgentName,d as isPathInside,f as getVibecontrolsProfilesDir,b as getVibecontrolsProfile,h as getVibecontrolsProductDir,e as getVibecontrolsDir,g as getProfileDataDir,i as getPluginRegistry,a as assertValidProfile};
2
+ import{$d as e,Xd as a,Yd as b,Zd as c,_d as d,ae as f,be as g,ce as h,de as i}from"./index-a4854mwz.js";import"./index-c7554sg7.js";export{c as validateAgentName,d as isPathInside,f as getVibecontrolsProfilesDir,b as getVibecontrolsProfile,h as getVibecontrolsProductDir,e as getVibecontrolsDir,g as getProfileDataDir,i as getPluginRegistry,a as assertValidProfile};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{Ga as a,Ia as b,Qa as c,Ra as d,Sa as e,Ta as f,Ua as g,Va as h,Wa as i}from"./index-g3ap3xpr.js";import"./index-0ckffygp.js";import"./index-9bqd8veb.js";import"./index-0cn9bv8z.js";import"./index-jw1k4vbk.js";import"./index-yy1mm8zs.js";export{f as validatePluginPackageName,c as getRegistryAllowlist,e as getPluginPackageRoot,g as getInstallScope,d as assertRegistryAllowed,b as TRUSTED_PACKAGES,i as PluginManager,h as DEFAULT_PLUGINS,a as CORE_PLUGIN_NAMES};
2
+ import{Ga as a,Ia as b,Qa as c,Ra as d,Sa as e,Ta as f,Ua as g,Va as h,Wa as i}from"./index-jdh30t6c.js";import"./index-0ckffygp.js";import"./index-js1xn4sq.js";import"./index-a4854mwz.js";import"./index-4qq083yd.js";import"./index-c7554sg7.js";export{f as validatePluginPackageName,c as getRegistryAllowlist,e as getPluginPackageRoot,g as getInstallScope,d as assertRegistryAllowed,b as TRUSTED_PACKAGES,i as PluginManager,h as DEFAULT_PLUGINS,a as CORE_PLUGIN_NAMES};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{d as a,e as b}from"./index-z5s398n0.js";import"./index-d1xjj001.js";import"./index-5dysvvjv.js";import"./index-js1xn4sq.js";import"./index-a4854mwz.js";import"./index-4qq083yd.js";import"./index-c7554sg7.js";export{a as runPluginPrereqs,b as readPrereqState};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{nb as a,ob as b,pb as c,qb as d,rb as e,sb as f}from"./index-hvjqgb97.js";import"./index-rqq0k5fc.js";import"./index-5dysvvjv.js";import"./index-pgew6sge.js";import"./index-h74va4wd.js";import"./index-js1xn4sq.js";import"./index-a4854mwz.js";import"./index-4qq083yd.js";import"./index-c7554sg7.js";export{b as unmountProfileRoutes,a as mountProfileRoutes,c as dispatchProfileRequest,f as __setMountForTests,e as __resetProfileMountsForTests,d as __listMountedProfilesForTests};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{H as a}from"./index-mxc61yr1.js";import"./index-c7554sg7.js";export{a as pruneStaleBunBinShims};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{J as a}from"./index-11grwjm1.js";import"./index-d1xjj001.js";import"./index-b5dhmybd.js";import"./index-e1bw1bwr.js";import"./index-atp2ayra.js";import"./index-rw9x93zb.js";import"./index-n6bdbgb9.js";import"./index-4wgjx8bf.js";import"./index-jdh30t6c.js";import"./index-0ckffygp.js";import"./index-rc79x8fw.js";import"./index-ydc0tk17.js";import"./index-52cp759f.js";import"./index-rqq0k5fc.js";import"./index-5dysvvjv.js";import"./index-pgew6sge.js";import"./index-8nqp3a4d.js";import"./index-1mppacnx.js";import"./index-thammzct.js";import"./index-b6x6a4xp.js";import"./index-h74va4wd.js";import"./index-js1xn4sq.js";import"./index-a4854mwz.js";import"./index-4qq083yd.js";import"./index-c7554sg7.js";export{a as registerCoreCommands};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{x as a}from"./index-9f52em7g.js";import"./index-wccxsz72.js";import"./index-4wgjx8bf.js";import"./index-jdh30t6c.js";import"./index-0ckffygp.js";import"./index-hvjqgb97.js";import"./index-rqq0k5fc.js";import"./index-5dysvvjv.js";import"./index-pgew6sge.js";import"./index-h74va4wd.js";import"./index-js1xn4sq.js";import"./index-a4854mwz.js";import"./index-4qq083yd.js";import"./index-c7554sg7.js";export{a as attachSecondaryProfile};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{o as a,p as b,q as c,r as d,s as e}from"./index-5wpck4aw.js";import"./index-0ckffygp.js";import"./index-js1xn4sq.js";import"./index-a4854mwz.js";import"./index-4qq083yd.js";import"./index-c7554sg7.js";export{a as spawnTracked,c as listTrackedByOwner,b as listTracked,d as killTracked,e as killAllTracked};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{bb as a}from"./index-ydc0tk17.js";import"./index-52cp759f.js";import"./index-js1xn4sq.js";import"./index-a4854mwz.js";import"./index-4qq083yd.js";import"./index-c7554sg7.js";export{a as telemetryService};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import"./index-c7554sg7.js";var l="./tree-sitter-javascript-nd0q4pe9.wasm";export{l as default};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import"./index-c7554sg7.js";var F="./tree-sitter-markdown-411r6y9b.wasm";export{F as default};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import"./index-c7554sg7.js";var E="./tree-sitter-markdown_inline-j5349f42.wasm";export{E as default};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import"./index-c7554sg7.js";var h="./tree-sitter-typescript-zxjzwt75.wasm";export{h as default};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import"./index-c7554sg7.js";var A="./tree-sitter-zig-e78zbjpm.wasm";export{A as default};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{pa as a,qa as b,ra as c,sa as d,ta as e,ua as f}from"./index-rw9x93zb.js";import"./index-0ckffygp.js";import"./index-ydc0tk17.js";import"./index-52cp759f.js";import"./index-js1xn4sq.js";import"./index-a4854mwz.js";import"./index-4qq083yd.js";import"./index-c7554sg7.js";export{c as tryHandoverBootstrapTunnel,d as stopBootstrapTunnel,b as startBootstrapTunnel,a as sanitizeEnvSuffix,f as reapOrphanTunnelsForProfile,e as getBootstrapTunnelUrl};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vibecontrols/agent",
3
- "version": "2026.602.1",
3
+ "version": "2026.602.3",
4
4
  "main": "./dist/index.js",
5
5
  "type": "module",
6
6
  "bin": {
@@ -1,2 +0,0 @@
1
- // @bun
2
- import{n as a}from"./index-5t4t0avg.js";import"./index-n7qyrdr1.js";import"./index-1hnw0rhc.js";import"./index-6jzsthh9.js";import"./index-g8zv1gta.js";import"./index-qfz9fy56.js";import"./index-ssjmzqcz.js";import"./index-tp4y9jde.js";import"./index-4wgjx8bf.js";import"./index-g3ap3xpr.js";import"./index-0ckffygp.js";import"./index-rc79x8fw.js";import"./index-yrgm89r8.js";import"./index-52cp759f.js";import"./index-v9fx5wab.js";import"./index-01qzsnwd.js";import"./index-d5ysy1yn.js";import"./index-04n4qgvd.js";import"./index-xjzmb1pn.js";import"./index-g2raeeh4.js";import"./index-9bqd8veb.js";import"./index-0cn9bv8z.js";import"./index-jw1k4vbk.js";import"./index-yy1mm8zs.js";export{a as createApp};
@@ -1,2 +0,0 @@
1
- // @bun
2
- import{t as a}from"./index-6jq17k9s.js";import"./index-9bqd8veb.js";import"./index-0cn9bv8z.js";import"./index-jw1k4vbk.js";import"./index-yy1mm8zs.js";export{a as bootstrapWorkspace};
@@ -1,2 +0,0 @@
1
- // @bun
2
- import{O as a,P as b}from"./index-e1bw1bwr.js";import"./index-yy1mm8zs.js";export{b as installDependencies,a as checkDependencies};
@@ -1,2 +0,0 @@
1
- // @bun
2
- import{Ld as a,Md as b,Nd as c,Od as d,Pd as e}from"./index-9bqd8veb.js";import"./index-0cn9bv8z.js";import"./index-jw1k4vbk.js";import"./index-yy1mm8zs.js";export{a as profileRegistry,d as getOrCreateProfile,c as getDaemonProfile,b as ensureDaemonProfile,e as __resetDaemonProfileForTests};
@@ -1,2 +0,0 @@
1
- // @bun
2
- import{$b as e,Xb as a,Yb as b,Zb as c,_b as d,ac as f,bc as g,cc as h,dc as i,ec as j,fc as k}from"./index-2xs9cvjn.js";import"./index-yy1mm8zs.js";export{a as program,d as createOption,b as createCommand,c as createArgument,j as Option,g as InvalidOptionArgumentError,f as InvalidArgumentError,k as Help,e as CommanderError,h as Command,i as Argument};
@@ -1,2 +0,0 @@
1
- // @bun
2
- import{Fd as a,Gd as b,Hd as c,Id as d}from"./index-9bqd8veb.js";import"./index-0cn9bv8z.js";import"./index-jw1k4vbk.js";import"./index-yy1mm8zs.js";export{a as normalizeGatewayUrl,c as gatewayClient,d as default,b as GatewayClient};
@@ -1,2 +0,0 @@
1
- // @bun
2
- import"./index-yy1mm8zs.js";var a="./highlights-x6tmsnaa.scm";export{a as default};
@@ -1,2 +0,0 @@
1
- // @bun
2
- import"./index-yy1mm8zs.js";var t="./highlights-r812a2qc.scm";export{t as default};
@@ -1,2 +0,0 @@
1
- // @bun
2
- import"./index-yy1mm8zs.js";var r="./highlights-eq9cgrbb.scm";export{r as default};
@@ -1,2 +0,0 @@
1
- // @bun
2
- import"./index-yy1mm8zs.js";var n="./highlights-hk7bwhj4.scm";export{n as default};
@@ -1,2 +0,0 @@
1
- // @bun
2
- import"./index-yy1mm8zs.js";var t="./highlights-ghv9g403.scm";export{t as default};
@@ -1,16 +0,0 @@
1
- // @bun
2
- import{Sb as jY}from"./index-d5ysy1yn.js";import{Ub as WY}from"./index-04n4qgvd.js";import{Rc as zY,Sc as A,nd as P,pd as JY}from"./index-g2raeeh4.js";import{Kd as HY,Ld as wY,Nd as V}from"./index-9bqd8veb.js";import{Xd as p}from"./index-0cn9bv8z.js";import{randomBytes as M,createHmac as E,timingSafeEqual as vY}from"crypto";var R=600,n=600,g=M(32),K="p2.";function S(Y){if(!Y.startsWith("/"))return`/${Y}`;return Y.length>1&&Y.endsWith("/")?Y.slice(0,-1):Y}var UY=/^\/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 s(Y){if(typeof Y!=="string"||Y.length===0)return!1;if(Y.includes("\x00")||Y.includes(`
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(UY.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 KY(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 r(Y,Z){if(Y.includes("*"))return!0;return Y.includes(Z.toUpperCase())}var MY=/^[A-Za-z0-9_-]{1,128}$/;function SY(Y){return typeof Y==="string"&&MY.test(Y)}function x(Y,Z,$){return E("sha256",g).update(`${Y}
4
- ${Z}
5
- ${$}`).digest("hex")}var y=new Map;function kY(Y){for(let[Z,$]of y)if($<=Y)y.delete(Z)}function a(Y,Z){let $=Date.parse(Z);if(!Number.isFinite($))return;y.set(Y,$)}function i(Y){return kY(Date.now()),y.has(Y)}function h(Y,Z,$,Q){return E("sha256",g).update(`v2
6
- ${Y}
7
- ${Z}
8
- ${$}
9
- ${Q}`).digest("hex")}function T(Y){return Buffer.from(Y,"utf8").toString("base64").replace(/=+$/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function I(Y){try{let Z=Y.replace(/-/g,"+").replace(/_/g,"/"),$=Z.length%4===0?Z:Z+"=".repeat(4-Z.length%4);return Buffer.from($,"base64").toString("utf8")}catch{return null}}var d=16;function qY(Y){if(Y.length>d)throw Error(`pathPrefixes exceeds maximum count (${Y.length} > ${d})`);let Z=new Set,$=[];for(let Q of Y){if(!Q||typeof Q!=="string")continue;if(Q.includes("..")||Q.includes("\x00"))throw Error("invalid pathPrefix");let W=S(Q);if(!s(W))throw Error(`pathPrefix '${W}' is not an allowed iframe surface`);if(!Z.has(W))Z.add(W),$.push(W)}return $.sort()}function nY(Y,Z=R){if(!Y||typeof Y!=="string")throw Error("pathPrefix is required");if(Y.includes("..")||Y.includes("\x00"))throw Error("invalid pathPrefix");let $=Math.min(Math.max(1,Math.floor(Z||R)),n),Q=S(Y);if(!s(Q))throw Error(`pathPrefix '${Q}' is not an allowed iframe surface`);let W=new Date(Date.now()+$*1000).toISOString(),z=M(16).toString("hex"),J=x(Q,W,z);return{token:`${W}|${z}|${J}`,expiresAt:W}}function sY(Y,Z=R){if(!Y||!Array.isArray(Y.pathPrefixes)||Y.pathPrefixes.length===0)throw Error("pathPrefixes is required");let $=qY(Y.pathPrefixes);if($.length===0)throw Error("pathPrefixes is required");let Q=KY(Y.methods),W=Math.min(Math.max(1,Math.floor(Z||R)),n),z=new Date(Date.now()+W*1000).toISOString(),J=M(16).toString("hex"),j=T(JSON.stringify($)),G=T(JSON.stringify(Q)),H=`${K}${j}.${G}`,w=h(j,G,z,J);return{token:`${z}|${J}|${H}|${w}`,expiresAt:z}}function L(Y,Z){if(Y.length!==Z.length)return!1;try{return vY(Buffer.from(Y,"hex"),Buffer.from(Z,"hex"))}catch{return!1}}function _(Y,Z){let $=S(Z);return Y===$||Y.startsWith(`${$}/`)}function t(Y,Z,$="*"){return FY(Y,Z,$).ok}function FY(Y,Z,$="*"){if(!Y||typeof Y!=="string")return{ok:!1,reason:"missing"};let Q=Y.split("|");if(Q.length===3)return RY(Q,Z);if(Q.length===4)return yY(Q,Z,$);return{ok:!1,reason:"malformed"}}function RY(Y,Z){let[$,Q,W]=Y;if(!$||!Q||!W)return{ok:!1,reason:"malformed"};if(!C($))return{ok:!1,reason:"expired"};let z=Z.split("/").filter(Boolean),J=["/"],j="";for(let G of z)j+=`/${G}`,J.push(j);for(let G of J){let H=x(S(G),$,Q);if(L(H,W)){if(!_(Z,G))return{ok:!1,reason:"path_mismatch"};if(i(Q))return{ok:!1,reason:"replayed"};return a(Q,$),{ok:!0}}}return{ok:!1,reason:"bad_signature"}}function yY(Y,Z,$){let[Q,W,z,J]=Y;if(!Q||!W||!z||!J)return{ok:!1,reason:"malformed"};if(!z.startsWith(K))return{ok:!1,reason:"malformed"};if(!C(Q))return{ok:!1,reason:"expired"};let G=z.slice(K.length).split("."),H=G[0]??"",w=G[1]??T(JSON.stringify(["*"]));if(!H)return{ok:!1,reason:"malformed"};let N=h(H,w,Q,W);if(!L(N,J))return{ok:!1,reason:"bad_signature"};let F=I(H);if(F===null)return{ok:!1,reason:"malformed"};let b;try{b=JSON.parse(F)}catch{return{ok:!1,reason:"malformed"}}if(!Array.isArray(b))return{ok:!1,reason:"malformed"};let O=I(w),D=["*"];if(O!==null)try{let B=JSON.parse(O);if(Array.isArray(B)&&B.every((v)=>typeof v==="string"))D=B}catch{return{ok:!1,reason:"malformed"}}if($!=="*"&&!r(D,$))return{ok:!1,reason:"method_mismatch"};for(let B of b){if(typeof B!=="string")continue;if(_(Z,B)){if(i(W))return{ok:!1,reason:"replayed"};return a(W,Q),{ok:!0}}}return{ok:!1,reason:"path_mismatch"}}function rY(Y,Z,$="*"){if(!Y||typeof Y!=="string")return!1;let Q=Y.split("|");if(Q.length===3){let[W,z,J]=Q;if(!W||!z||!J)return!1;if(!C(W))return!1;let j=Z.split("/").filter(Boolean),G=["/"],H="";for(let w of j)H+=`/${w}`,G.push(H);for(let w of G){let N=x(S(w),W,z);if(L(N,J))return _(Z,w)}return!1}if(Q.length===4){let[W,z,J,j]=Q;if(!W||!z||!J||!j)return!1;if(!J.startsWith(K))return!1;if(!C(W))return!1;let H=J.slice(K.length).split("."),w=H[0]??"",N=H[1]??T(JSON.stringify(["*"]));if(!w)return!1;let F=h(w,N,W,z);if(!L(F,j))return!1;let b=I(w);if(b===null)return!1;let O;try{O=JSON.parse(b)}catch{return!1}if(!Array.isArray(O))return!1;let D=I(N),B=["*"];if(D!==null)try{let v=JSON.parse(D);if(Array.isArray(v)&&v.every((BY)=>typeof BY==="string"))B=v}catch{return!1}if($!=="*"&&!r(B,$))return!1;for(let v of O){if(typeof v!=="string")continue;if(_(Z,v))return!0}return!1}return!1}function C(Y){let Z=Date.parse(Y);return Number.isFinite(Z)&&Date.now()<Z}function c(Y,Z){let $=Y.headers.get("x-vibe-iframe-token")??Y.headers.get("X-Vibe-Iframe-Token");if($)return $;try{let Q=new URL(Y.url).searchParams.get("vt");if(Q)return Q}catch{}return null}var u="tc1|",l=600,TY=600;function e(Y,Z,$){return E("sha256",g).update(`tc1
10
- ${Y}
11
- ${Z}
12
- ${$}`).digest("hex")}function aY(Y,Z=l){if(!SY(Y))throw Error("invalid sid");let $=Math.min(Math.max(1,Math.floor(Z||l)||l),TY),Q=new Date(Date.now()+$*1000).toISOString(),W=M(16).toString("hex"),z=e(Y,Q,W);return{token:`${u}${Q}|${Y}|${W}|${z}`,expiresAt:Q}}function iY(Y,Z){if(!Y||typeof Y!=="string")return!1;if(!Y.startsWith(u))return!1;let Q=Y.slice(u.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=e(z,W,J);return L(G,j)}function IY(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_term_${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 tY(Y,Z){return IY(Y.headers,Z)}var f="uc1|",m=600,_Y=600,EY=/^[a-z0-9-]{1,64}$/;function gY(Y){return typeof Y==="string"&&EY.test(Y)}function YY(Y,Z,$){return E("sha256",g).update(`uc1
13
- ${Y}
14
- ${Z}
15
- ${$}`).digest("hex")}function eY(Y,Z=m){if(!gY(Y))throw Error("invalid plugin name");let $=Math.min(Math.max(1,Math.floor(Z||m)||m),_Y),Q=new Date(Date.now()+$*1000).toISOString(),W=M(16).toString("hex"),z=YY(Y,Q,W);return{token:`${f}${Q}|${Y}|${W}|${z}`,expiresAt:Q}}function YZ(Y,Z){if(!Y||typeof Y!=="string")return!1;if(!Y.startsWith(f))return!1;let Q=Y.slice(f.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=YY(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 ZY(Y,Z){if(!Z||Z==="/")return!1;let $=Z.endsWith("/")?Z.slice(0,-1):Z;return Y===$||Y.startsWith(`${$}/`)}function mY(Y){let Z=Y.replace(/^\/api\/profiles\/[^/]+/,"/api");return Z==="/api"?"/":Z}function uY(Y){let Z=/^\/api\/profiles\/([^/]+)(?:\/|$)/.exec(Y);if(!Z)return null;let $=Z[1];if(!$)return null;return $}function $Y(Y,Z){let $=[Y],Q=mY(Y);if(Q!==Y)$.push(Q);for(let W of $){if(lY.some((z)=>ZY(W,z)))return!0;if(Z.some((z)=>ZY(W,z)))return!0}return!1}function GY(){let Y=new Uint8Array(32);return crypto.getRandomValues(Y),`vcak_${Buffer.from(Y).toString("base64url")}`}var U=null;function VY(){return`${p()}:static-api-key`}async function BZ(){let Y=process.env.AGENT_API_KEY;if(Y)return U=Y,Y;let Z=VY(),$=await zY(Z);if($)return U=$,$;let Q=P({dir:V().dataDir})["static-api-key"];if(Q){try{await A(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=GY();return await A(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 k(){let Y=process.env.AGENT_API_KEY;if(Y)return Y;if(U!==null)return U;let Z=P()["static-api-key"];if(Z)return U=Z,Z;let $=GY();U=$;try{JY({"static-api-key":$},{dir:V().dataDir,scope:V().name})}catch{}return A(VY(),$).catch(()=>{}),$}function fY(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 $=fY(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 q(Y,Z){let $=Buffer.from(Y),Q=Buffer.from(Z);if($.length!==Q.length)return!1;try{return PY($,Q)}catch{return!1}}function vZ(Y){if(!Y)return!1;return q(Y,k())}async function cY(Y,Z){if(!Y)return!1;let $=uY(Z);if($){let Q=wY.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 q(Y,k())}return!1}}try{if(await V().keyVault.match(Y))return!0}catch{}if(q(Y,k()))return!0;if(oY(Y)!==null)return!0;return!1}function oY(Y){if(!Y)return null;if(q(Y,k()))return{name:"default",scopes:new Set(["admin"])};let Z=HY()??V(),$=P({dir:Z.dataDir}),Q=Date.now();for(let W of $.apiKeys??[]){if(!q(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 UZ(Y,Z){if(!Y)return!1;if(Y.scopes.has("admin"))return!0;return Z.some(($)=>Y.scopes.has($))}var X=null;function o(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)o("plugin.public_path.declared",{path:$});else{for(let $ of Z)if(!X.has($))o("plugin.public_path.added",{path:$});for(let $ of X)if(!Z.has($))o("plugin.public_path.removed",{path:$})}return X=Z,Z}function XZ(){X=null}function QY(Y){if(!Y)return[];if(X===null)return[...pY(Y)];return[...X]}function NZ(Y){let Z=k();return V().logger.info("auth",`Agent API key: ${Z.substring(0,8)}****${Z.substring(Z.length-4)}`),new WY({name:"plugin/auth"}).decorate("apiKey",Z).derive(async({request:$,path:Q})=>{let W=QY(Y),z;if($Y(Q,W))z=!0;else if(jY($.headers))z=!0;else{let J=c($,Q);if(J&&t(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=QY(Y);if(!$&&!$Y(W,J)){if(c(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,t as wb,FY as xb,rY as yb,c 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,BZ as Ib,k as Jb,fY as Kb,vZ as Lb,oY as Mb,UZ as Nb,XZ as Ob,NZ as Pb};
@@ -1,26 +0,0 @@
1
- // @bun
2
- import{o as V4,q as $4}from"./index-n7qyrdr1.js";import{u as a4,v as L5,w as O5}from"./index-1hnw0rhc.js";import{E as B4}from"./index-6jzsthh9.js";import{$ as b4,Q as T5,aa as K2,ba as j0,ca as v4,da as y4,ea as d4,fa as P4,ha as E2,ia as g2,ja as n2,ka as C2}from"./index-g8zv1gta.js";import{la as E5,qa as C5,sa as T0}from"./index-qfz9fy56.js";import{va as f2}from"./index-ssjmzqcz.js";import{wa as N5,xa as j5,ya as U5,za as x5}from"./index-tp4y9jde.js";import{Aa as F5}from"./index-4wgjx8bf.js";import{Ja as M0,Wa as M5}from"./index-g3ap3xpr.js";import{Xa as _2}from"./index-0ckffygp.js";import{ab as h2}from"./index-rc79x8fw.js";import{eb as e4,fb as Y5,gb as W5,hb as z5,ib as H5,jb as J2,kb as G5,lb as B5,mb as V5,nb as K5,pb as _5}from"./index-v9fx5wab.js";import{Ab as d0,Eb as U2,Fb as X0,Gb as $5,Hb as Z5,Ib as O0,Jb as x2,Kb as m,Lb as l,Mb as p4,Nb as l4,Ob as J5,Pb as X5,tb as g0,ub as D2,vb as p0,wb as J0,xb as l0,yb as Q5}from"./index-01qzsnwd.js";import{Tb as z,Ub as D}from"./index-04n4qgvd.js";import{md as r0,nd as s,od as m0,pd as P2,qd as S2}from"./index-g2raeeh4.js";import{Cd as d2,Hd as g,Jd as x0,Kd as b,Ld as a,Nd as G,Od as Y0,vd as U0,wd as s4,xd as r4,yd as t4,zd as G2}from"./index-9bqd8veb.js";import{Rd as a0,Sd as z0,Ud as v2,Vd as s0,Xd as T2,Yd as d,_d as k2,ae as M2,be as V2,ce as l2}from"./index-0cn9bv8z.js";import{ee as D0,he as f}from"./index-yy1mm8zs.js";var R0=typeof new Headers()?.toJSON==="function",A5=($)=>{if(R0)return Object.keys($.toJSON()).join(", ");let Z="",Q=0;return $.forEach((Y,X)=>{if(Q)Z=Z+", "+X;else Z=X;Q++}),Z},A0=($)=>{let{aot:Z=!0,origin:Q=!0,methods:Y=!0,allowedHeaders:X=!0,exposeHeaders:J=!0,credentials:W=!0,maxAge:H=5,preflight:B=!0}=$??{};if(Array.isArray(X))X=X.join(", ");if(Array.isArray(J))J=J.join(", ");let K=typeof Q==="boolean"?void 0:Array.isArray(Q)?Q:[Q],N=new D({name:"@elysiajs/cors",seed:$,aot:Z}),I=K?.some((F)=>F==="*"),C={};if(K){for(let F of K)if(typeof F==="string")C[F]=!0}let U=(F,T,x)=>{if(Array.isArray(F))return F.some((q)=>U(q,T,x));switch(typeof F){case"string":if(x in C)return!0;let q=x.indexOf("://");if(q!==-1)x=x.slice(q+3);return F===x;case"function":return F(T)===!0;case"object":if(F instanceof RegExp)return F.test(x)}return!1},V=(F,T)=>{if(Q===!0){F.headers.vary="*",F.headers["access-control-allow-origin"]=T.headers.get("Origin")||"*";return}if(I){F.headers.vary="*",F.headers["access-control-allow-origin"]="*";return}if(!K?.length)return;if(K.length){let x=T.headers.get("Origin")??"";for(let q=0;q<K.length;q++)if(U(K[q],T,x)===!0){F.headers.vary=Q?"Origin":"*",F.headers["access-control-allow-origin"]=x||"*";return}}F.headers.vary="Origin"},E=(F,T)=>{if(!T)return;if(Y===!0)return F.headers["access-control-allow-methods"]=T??"*";if(Y===!1||!Y?.length)return;if(Y==="*")return F.headers["access-control-allow-methods"]="*";if(!Array.isArray(Y))return F.headers["access-control-allow-methods"]=Y;F.headers["access-control-allow-methods"]=Y.join(", ")},R={};if(typeof J==="string")R["access-control-expose-headers"]=J;if(typeof X==="string")R["access-control-allow-headers"]=X;if(W===!0)R["access-control-allow-credentials"]="true";N.headers(R);function h({set:F,request:T,headers:x}){if(V(F,T),E(F,T.headers.get("access-control-request-method")),X===!0||J===!0){if(X===!0)F.headers["access-control-allow-headers"]=x["access-control-request-headers"];if(J===!0)F.headers["access-control-expose-headers"]=Object.keys(x).join(",")}if(H)F.headers["access-control-max-age"]=H.toString();return new Response(null,{status:204})}if(B)N.options("/",h).options("/*",h);return N.onRequest(function({set:T,request:x}){if(V(T,x),B&&x.method==="OPTIONS")return h({set:T,request:x,headers:R0?x.headers.toJSON():Object.fromEntries(x.headers.entries())});if(E(T,x.method),X===!0||J===!0){let q=A5(x.headers);if(X===!0)T.headers["access-control-allow-headers"]=q;if(J===!0)T.headers["access-control-expose-headers"]=q}})};import{createHash as k0}from"crypto";var Y2="idempotency",w5=300000,w0=1e4,R2=new Map;function k5($,Z,Q,Y){return k0("sha256").update(`${$}|${Z}|${Q}|${Y}`).digest("hex")}async function S5($,Z){let Q=await $.getPluginState(Y2,Z);if(!Q)return null;try{let Y=JSON.parse(Q);if(Y.expiresAt<Date.now())return await $.deletePluginState(Y2,Z),null;return Y}catch{return null}}async function D5($,Z,Q){await $.setPluginState(Y2,Z,JSON.stringify(Q))}async function h5($){let Z=await $.getAllPluginState(Y2),Q=Date.now(),Y=0,X=[];for(let J of Z)try{if(JSON.parse(J.value).expiresAt<Q)await $.deletePluginState(Y2,J.key),Y+=1;else X.push({key:J.key,updatedAt:J.updatedAt})}catch{await $.deletePluginState(Y2,J.key),Y+=1}if(X.length>w0){X.sort((W,H)=>(W.updatedAt??"").localeCompare(H.updatedAt??""));let J=X.slice(0,X.length-w0);for(let W of J)await $.deletePluginState(Y2,W.key),Y+=1}if(Y>0)G().logger.info("idempotency",`Swept ${Y} expired/over-cap entries`)}var e2=null,v5=600000;function P5($){if(e2)return;e2=setInterval(()=>{let Z=$.getDb();if(!Z)return;h5(Z).catch((Q)=>{G().logger.warn("idempotency","Sweep failed",{error:String(Q)})})},v5),e2.unref?.()}function S0($){return P5($),new D({name:"plugin/idempotency"}).onBeforeHandle(async({request:Z,path:Q,set:Y,store:X})=>{if(Z.method!=="POST"&&Z.method!=="PUT")return;let J=Z.headers.get("x-idempotency-key")??Z.headers.get("X-Idempotency-Key");if(!J)return;if(J.length<8||J.length>200)return Y.status=400,{error:"X-Idempotency-Key must be 8\u2013200 chars",code:"BAD_REQUEST"};let W=$.getDb();if(!W)return;let H="no-body";try{let E=await Z.clone().text();H=k0("sha256").update(E).digest("hex")}catch{}let B=k5(Z.method,Q,J,H),K=await S5(W,B);if(K){Y.status=K.status;let V=Y.headers??={};V["Content-Type"]=K.contentType,V["X-Idempotency-Replay"]="true",X.__idemReplay=K.body;try{return JSON.parse(K.body)}catch{return K.body}}let N=R2.get(B);if(N){let V=await N.catch(()=>null);if(V){Y.status=V.status;let E=Y.headers??={};E["Content-Type"]=V.contentType,E["X-Idempotency-Replay"]="true",X.__idemReplay=V.body;try{return JSON.parse(V.body)}catch{return V.body}}}let I,C,U=new Promise((V,E)=>{I=V,C=E});R2.set(B,U),X.__idemKey=B,X.__idemResolve=I,X.__idemReject=C}).onAfterHandle(async({response:Z,set:Q,store:Y})=>{let X=Y.__idemKey;if(!X)return;let J=Y.__idemResolve,W=$.getDb(),H=Q.status??200,B=typeof Z==="string"?Z:JSON.stringify(Z),N=Q.headers?.["Content-Type"]??"application/json",I={status:H,body:B,contentType:N,expiresAt:Date.now()+w5},C=H>=200&&H<300;try{if(W&&C)await D5(W,X,I)}catch(U){G().logger.warn("idempotency","Failed to persist response",{error:String(U)})}finally{try{J?.(C?I:null)}catch{}R2.delete(X)}}).onError(({store:Z})=>{let Q=Z.__idemKey;if(!Q)return;let Y=Z.__idemReject;try{Y?.(Error("idempotency: handler errored"))}catch{}R2.delete(Q)}).as("global")}import u from"os";import{readFileSync as s5}from"fs";import{join as r5}from"path";var h0={enabled:!1,async scrape(){return`# vibecontrols agent metrics disabled (OTel SDK not initialised)
3
- `},recordHttpRequest(){},setPluginsLoaded(){}},$2=null,A2=null;async function w2($){if($2)return $2;if(A2)return A2;return A2=(async()=>{try{let{MeterProvider:Z}=await import("./index-hrdamx5j.js").then((m)=>D0(m.default,1)),{PrometheusExporter:Q,PrometheusSerializer:Y}=await import("./index-1zw3kea7.js").then((m)=>D0(m.default,1)),X=new Q({preventServerStart:!0}),J=new Y,H=new Z({readers:[X]}).getMeter("vibecontrols-agent"),B=H.createGauge("vibecontrols_agent_info",{description:"Static info about the agent process; value is always 1."});H.createObservableGauge("vibecontrols_agent_uptime_seconds",{description:"Process uptime in seconds."}).addCallback((V)=>{V.observe(process.uptime())});let N=H.createCounter("vibecontrols_http_requests_total",{description:"Total HTTP requests handled by the agent, labelled by method, route, status."}),I={};H.createObservableGauge("vibecontrols_plugins_loaded",{description:"Plugins loaded by the agent, broken down by status (loaded, failed, etc.)."}).addCallback((V)=>{for(let[E,R]of Object.entries(I))V.observe(R,{status:E})}),B.record(1,{version:$?.version??"unknown",profile:$?.profile??"default"});let U={enabled:!0,async scrape(){let V=await X.collect();if(!V.resourceMetrics)return"";return J.serialize(V.resourceMetrics)},recordHttpRequest(V,E,R){N.add(1,{method:V,route:E,status:String(R)})},setPluginsLoaded(V){I={...V}}};return $2=U,G().logger.info("metrics","OTel Prometheus registry initialised"),U}catch(Z){return G().logger.warn("metrics","Failed to initialise OTel metrics; /metrics will return a stub body",{error:Z instanceof Error?Z.message:String(Z)}),$2=h0,h0}})(),A2}function v0($,Z,Q){if(!$2)return;$2.recordHttpRequest($,Z,Q)}function P0($){if(!$2)return;$2.setPluginsLoaded($)}var f5=new Set(["127.0.0.1","::1"]),f0=!1;function b5(){if(f0)return;if(process.env.METRICS_ANONYMOUS_LOCALHOST==="true")f0=!0,G().logger.warn("metrics","METRICS_ANONYMOUS_LOCALHOST=true \u2014 /metrics is open to TCP loopback peers without an API key. Prefer issuing a scoped API key for your scraper.")}function y5($){let Z=$.replace(/^\[|\]$/g,"");if(Z.startsWith("::ffff:"))return Z.slice(7);return Z}function Q0($,Z){let Q=Z?.requestIP($)?.address;if(!Q)return!1;return f5.has(y5(Q))}function b0(){return b5(),new D({name:"routes/metrics"}).get("/metrics",async({request:$,server:Z,set:Q})=>{if(!(process.env.METRICS_ANONYMOUS_LOCALHOST==="true"&&Q0($,Z))){let W=m(Object.fromEntries($.headers.entries()));if(!l(W))return Q.status=401,Q.headers["content-type"]="application/json",JSON.stringify({error:"Unauthorized",message:"Invalid or missing API key"})}let J=await(await w2()).scrape();return Q.headers["content-type"]="text/plain; version=0.0.4; charset=utf-8",J})}import{randomBytes as c5,timingSafeEqual as u5}from"crypto";import{chmodSync as m5,existsSync as y0,mkdirSync as g5,readFileSync as p5,unlinkSync as l5,writeFileSync as d5}from"fs";import{dirname as n5,join as i5}from"path";var W2=null;function c0(){return i5(k2(),"pairing-token")}function o5(){return c5(32).toString("base64url")}function a5($,Z){let Q=Buffer.from($),Y=Buffer.from(Z);if(Q.length!==Y.length)return!1;try{return u5(Q,Y)}catch{return!1}}function X6(){if(W2)return W2;let $=c0();try{if(y0($)){let Q=p5($,"utf8").trim();if(Q.length>=32)return W2=Q,Q}}catch{}let Z=o5();try{g5(n5($),{recursive:!0}),d5($,Z,{encoding:"utf8"});try{m5($,384)}catch{}}catch(Q){}return W2=Z,Z}function $0($){if(!$)return!1;if(!W2)return!1;return a5($,W2)}function u0(){W2=null;try{let $=c0();if(y0($))l5($)}catch{}}function Z0($){return $["x-pairing-token"]??$["X-Pairing-Token"]??null}function t5(){let $=u.hostname(),Z=u.platform(),Q=u.arch(),Y=new Bun.CryptoHasher("sha256");return Y.update(`${$}-${Z}-${Q}`),Y.digest("hex").substring(0,16)}function e5(){for(let $ of["..","../.."])try{let Z=r5(import.meta.dir,$,"package.json"),Y=JSON.parse(s5(Z,"utf8")).version;if(Y)return Y}catch{}return"0.0.0"}async function QQ($){let Z=[],Q=$.getProvider("tunnel");if(Q)Z.push(Q);for(let Y of $.listProvidersForType("tunnel")){let X=$.getProviderByName("tunnel",Y.pluginName);if(X&&!Z.includes(X))Z.push(X)}for(let Y of Z){if(!Y.getActiveTunnelUrl)continue;let X=await Y.getActiveTunnelUrl();if(X)return X}return null}function n0({serviceRegistry:$,runFinalize:Z,getDb:Q}){let Y=e5(),X=t5();return new D({prefix:"/api/agent"}).get("/identity",()=>({hostname:u.hostname(),platform:u.platform(),architecture:u.arch(),agentVersion:Y,agentInstanceId:m0()})).get("/version",()=>({version:Y,runtime:"bun",runtimeVersion:typeof Bun<"u"?Bun.version:"unknown"})).get("/api-key",({request:J,server:W,set:H})=>{if(!Q0(J,W)){let K=m(Object.fromEntries(J.headers.entries()));if(!l(K))return H.status=401,{error:"Unauthorized",message:"Invalid or missing API key"}}return{apiKey:x2()}}).post("/iframe-token",({body:J,request:W,set:H})=>{let B=m(Object.fromEntries(W.headers.entries()));if(!l(B))return H.status=401,{error:"Unauthorized",message:"Invalid or missing API key"};try{if(Array.isArray(J.pathPrefixes)&&J.pathPrefixes.length>0)return p0({pathPrefixes:J.pathPrefixes,methods:J.methods},J.ttlSeconds??void 0);if(!J.pathPrefix)return H.status=400,{error:"BadRequest",message:"Provide either pathPrefix (string) or pathPrefixes (string[])"};return D2(J.pathPrefix,J.ttlSeconds??void 0)}catch(K){return H.status=400,{error:"BadRequest",message:K instanceof Error?K.message:String(K)}}},{body:z.Object({pathPrefix:z.Optional(z.String({minLength:1})),pathPrefixes:z.Optional(z.Array(z.String({minLength:1}),{minItems:1,maxItems:16})),methods:z.Optional(z.Array(z.String({minLength:1}),{minItems:1,maxItems:8})),ttlSeconds:z.Optional(z.Number())})}).post("/terminal-exchange",({body:J,set:W})=>{let{sid:H,token:B}=J;if(!H||!B)return W.status=400,{error:"BadRequest",message:"sid and token required"};if(!g0(H))return W.status=400,{error:"BadRequest",message:"invalid sid"};let K=`/terminal/${H}`,N=l0(B,K);if(!N.ok)return G().logger.warn("terminal-exchange","iframe token rejected",{sid:H,reason:N.reason}),W.status=401,{error:"Unauthorized",message:"invalid iframe token",code:N.reason==="expired"?"expired":N.reason==="replayed"?"replayed":"invalid"};let I=d0(H,600),C=`vt_term_${H}`;return W.headers["set-cookie"]=`${C}=${I.token}; HttpOnly; Secure; SameSite=None; Path=/terminal/${H}; Max-Age=600`,W.status=204,null},{body:z.Object({sid:z.String({minLength:1}),token:z.String({minLength:1})})}).post("/ui-exchange",({body:J,set:W})=>{let{plugin:H,token:B}=J;if(!H||!B)return W.status=400,{error:"BadRequest",message:"plugin and token required"};if(!U2(H))return W.status=400,{error:"BadRequest",message:"invalid plugin name"};let K=`/ui/${H}`;if(!J0(B,K))return W.status=401,{error:"Unauthorized",message:"invalid iframe token"};let N=X0(H,600),I=`vt_ui_${H}`;return W.headers["set-cookie"]=`${I}=${N.token}; HttpOnly; Secure; SameSite=None; Path=/ui/${H}/; Max-Age=600`,W.status=204,null},{body:z.Object({plugin:z.String({minLength:1}),token:z.String({minLength:1})})}).post("/ui-exchange-plugin",({body:J,set:W})=>{let{plugin:H,token:B}=J;if(!H||!B)return W.status=400,{error:"BadRequest",message:"plugin and token required"};if(!U2(H))return W.status=400,{error:"BadRequest",message:"invalid plugin name"};if(![`/api/plugins/${H}/ui`,`/${H}`].find((U)=>J0(B,U)))return W.status=401,{error:"Unauthorized",message:"invalid iframe token"};let I=X0(H,600),C=`vt_ui_${H}`;return W.headers["set-cookie"]=`${C}=${I.token}; HttpOnly; Secure; SameSite=None; Path=/api/plugins/${H}/ui/; Max-Age=600`,W.status=204,null},{body:z.Object({plugin:z.String({minLength:1}),token:z.String({minLength:1})})}).get("/system",({request:J,set:W})=>{let H=m(Object.fromEntries(J.headers.entries()));if(!l(H))return W.status=401,{error:"Unauthorized",message:"Invalid or missing API key"};return{machineId:X,hostname:u.hostname(),platform:u.platform(),arch:u.arch(),release:u.release(),cpus:u.cpus().length,totalMemory:u.totalmem(),freeMemory:u.freemem(),uptime:u.uptime(),bunVersion:typeof Bun<"u"?Bun.version:void 0,agentVersion:Y,homeDir:u.homedir(),cwd:process.cwd(),environment:"production"}}).get("/tunnel",async({request:J,set:W})=>{let H=Object.fromEntries(J.headers.entries()),B=l(m(H)),K=$0(Z0(H));if(!B&&!K)return W.status=401,{error:"Unauthorized",message:"Provide x-agent-api-key OR x-pairing-token to read tunnel URL"};let N=await QQ($);if(!N)return{tunnelUrl:null,message:"No tunnel provider registered"};return{tunnelUrl:N}}).get("/status",()=>{let J=["tunnel","session","ai"].filter((W)=>$.hasProvider(W));return{state:G().getBootState(),status:G().getBootState(),version:Y,providers:J,timestamp:new Date().toISOString()}}).get("/gateway-auth",()=>({configured:g.isConfigured(),config:h2(g.getConfig()),state:G().getBootState()})).post("/retry-config",async({set:J})=>{let{getFinalizeRetryHandle:W}=await import("./finalize-retry-handle-registry-vv241fsq.js"),H=W();if(!H)return J.status=409,{ok:!1,error:"No finalize retry worker is active. The agent either never had cached credentials to retry with, or it already reached the ready state."};let B=await H.forceRetryNow();if(!B.ok)J.status=503;return{ok:B.ok,error:B.ok?void 0:B.error,state:G().getBootState(),worker:H.getState()}}).post("/gateway-auth",async({body:J,request:W,set:H})=>{let B=G().getBootState(),K=Object.fromEntries(W.headers.entries());if(B==="ready"){let F=m(K);if(!l(F))return H.status=401,{success:!1,state:B,error:"Unauthorized: API key required to reconfigure"}}else{let F=m(K),T=Z0(K),x=l(F),q=$0(T);if(!x&&!q)return H.status=401,{success:!1,state:B,error:"Unauthorized: provide x-agent-api-key OR x-pairing-token for bootstrap"}}let{clientId:N,clientSecret:I,workspaceId:C,globalGatewayUrl:U,workspaceGatewayUrl:V}=J;if(!N||!I||!C||!U||!V)return H.status=400,{success:!1,state:G().getBootState(),error:"clientId, clientSecret, workspaceId, globalGatewayUrl, and workspaceGatewayUrl are required"};let E,R;try{E=G2(U,"globalGatewayUrl"),R=G2(V,"workspaceGatewayUrl")}catch(F){return H.status=400,{success:!1,state:G().getBootState(),error:F instanceof Error?F.message:String(F)}}{let F=b()??G();try{await S2({clientId:N,clientSecret:I,workspaceId:C,ownerUserId:J.ownerUserId,organizationId:J.organizationId,globalGatewayUrl:E,workspaceGatewayUrl:R,agentRecordId:J.agentRecordId,scopes:J.scopes,...J.storageAdapter?{storageAdapter:J.storageAdapter}:{},...J.storageOptions?{storageOptions:J.storageOptions}:{},...J.dbPath?{dbPath:J.dbPath}:{}},{dir:F.dataDir,scope:F.name})}catch(T){return H.status=500,{success:!1,state:G().getBootState(),error:`Failed to persist gateway credentials to secrets backend: ${T instanceof Error?T.message:String(T)}`}}}let h=G().getBootState();if(h==="ready"){let F=Q();if(F){if(await F.setConfig("gateway-auth:clientId",N),await F.setConfig("gateway-auth:clientSecret",I),await F.setConfig("gateway-auth:workspaceId",C),J.organizationId)await F.setConfig("gateway-auth:organizationId",J.organizationId);if(await F.setConfig("gateway-auth:globalGatewayUrl",E),await F.setConfig("gateway-auth:workspaceGatewayUrl",R),J.agentRecordId)await F.setConfig("gateway-auth:agentRecordId",J.agentRecordId)}g.configure({globalGatewayUrl:E,workspaceGatewayUrl:R,clientId:N,clientSecret:I,workspaceId:C,organizationId:J.organizationId}),G().logger.info("preconfig","Gateway credentials re-configured (agent was already ready)");let T=!!(J.storageAdapter||J.storageOptions||J.dbPath);return{success:!0,state:h,message:T?"Gateway auth re-configured. Restart the agent (vibe restart) to apply the new storage configuration.":"Gateway auth re-configured"}}return G().logger.info("preconfig","Gateway credentials received \u2014 beginning finalize (background)"),u0(),Z({clientId:N,clientSecret:I,workspaceId:C,organizationId:J.organizationId,globalGatewayUrl:E,workspaceGatewayUrl:R},{agentRecordId:J.agentRecordId,scopes:J.scopes}).catch((F)=>{G().logger.error("preconfig","Background finalize threw",{error:F instanceof Error?F.message:String(F)})}),H.status=202,{success:!0,state:G().getBootState(),agentRecordId:J.agentRecordId,message:"Gateway credentials accepted; finalize is running in the background. Poll /health/ready for completion."}},{body:z.Object({clientId:z.Optional(z.String()),clientSecret:z.Optional(z.String()),workspaceId:z.Optional(z.String()),ownerUserId:z.Optional(z.String()),organizationId:z.Optional(z.String()),globalGatewayUrl:z.Optional(z.String()),workspaceGatewayUrl:z.Optional(z.String()),scopes:z.Optional(z.Array(z.String())),agentRecordId:z.Optional(z.String()),storageAdapter:z.Optional(z.String()),storageOptions:z.Optional(z.Record(z.String(),z.String())),dbPath:z.Optional(z.String())})})}import{existsSync as e,mkdirSync as $Q,rmSync as i0,readdirSync as t0}from"fs";import{join as b2}from"path";function o($){return b2(V2(),"agents",d($))}function ZQ(){let $=b2(V2(),"agents");if(!e($))return[];return t0($,{withFileTypes:!0}).filter((Z)=>Z.isDirectory()).map((Z)=>Z.name).filter((Z)=>/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(Z))}function e0($){return b2(V2(),"agents",d($))}function W0($){return s({dir:e0($)})}function o0($,Z){return P2(Z,{dir:e0($),scope:d($)})}function B2($){let Z=v2(),Q=z0().find((J)=>J.name===$),Y=a.get($),X={name:$,isDefault:$===Z,isRunning:Q?.status==="running",attached:Y!==void 0,bootState:Y?Y.getBootState():null,dataDir:Y?Y.dataDir:null};if(Q)X.port=Q.port,X.pid=Q.pid,X.startTime=Q.startTime;if(e(o($)))X.config=h2(W0($));return X}function Q4($={}){let Z=$.serviceManagerFactory?$.serviceManagerFactory():new f2;return new D({prefix:"/api/profiles"}).get("/",()=>{let Q=ZQ(),Y=v2(),X=new Set(Q);return X.add(Y),[...X].sort().map((J)=>B2(J))}).post("/",async({body:Q,set:Y})=>{try{let X=d(Q.name),J=o(X);if(e(J))return Y.status=409,{error:"exists",message:`Profile '${X}' already exists.`};let W;if(Q.copyFrom){let H=d(Q.copyFrom);if(!e(o(H)))return Y.status=400,{error:"copy-source-missing",message:`Profile '${H}' does not exist.`};W=W0(H),delete W["static-api-key"],delete W.agentRecordId,delete W.apiKeys}else W=r0();if(Q.gatewayUrl)W.globalGatewayUrl=Q.gatewayUrl;if(Q.workspaceGatewayUrl)W.workspaceGatewayUrl=Q.workspaceGatewayUrl;if(Q.clientId)W.clientId=Q.clientId;if(Q.clientSecret)W.clientSecret=Q.clientSecret;if(Q.workspaceId)W.workspaceId=Q.workspaceId;if(Q.organizationId)W.organizationId=Q.organizationId;$Q(J,{recursive:!0}),o0(X,W);try{Y0(X)}catch(H){G().logger.warn("profile-mgmt",`In-process attach failed for '${X}'`,{error:String(H)})}if(G().logger.info("profile-mgmt",`Created profile '${X}' at ${J}`),Q.start){let H={name:X,port:Q.port??0,daemon:!0,dbPath:M2(),profile:X};await Z.startDaemon(H)}return Y.status=201,B2(X)}catch(X){return Y.status=400,{error:"create-failed",message:X instanceof Error?X.message:String(X)}}},{body:z.Object({name:z.String(),gatewayUrl:z.Optional(z.String()),workspaceGatewayUrl:z.Optional(z.String()),clientId:z.Optional(z.String()),clientSecret:z.Optional(z.String()),workspaceId:z.Optional(z.String()),organizationId:z.Optional(z.String()),copyFrom:z.Optional(z.String()),start:z.Optional(z.Boolean()),port:z.Optional(z.Number())})}).get("/:name",({params:Q,set:Y})=>{try{let X=d(Q.name);if(!e(o(X)))return Y.status=404,{error:"not-found",message:`No profile '${X}'.`};return B2(X)}catch(X){return Y.status=400,{error:"bad-request",message:X instanceof Error?X.message:String(X)}}},{params:z.Object({name:z.String()})}).put("/:name",({params:Q,body:Y,set:X})=>{try{let J=d(Q.name);if(!e(o(J)))return X.status=404,{error:"not-found",message:`No profile '${J}'.`};let W=["static-api-key","apiKeys","agentRecordId"];for(let K of W)if(K in Y)return X.status=400,{error:"forbidden-field",message:`Field '${K}' is managed via dedicated commands (vibe key rotate / vibe profile create). It cannot be patched here.`};if("registry"in Y)return X.status=400,{error:"forbidden-field",message:"Field 'registry' cannot be patched via this endpoint. Use POST /api/agent/registry with operator confirmation (VIBE_ALLOW_REGISTRY_CHANGE=1) so the change is auditable."};let B={...W0(J),...Y};return o0(J,B),B2(J)}catch(J){return X.status=400,{error:"update-failed",message:J instanceof Error?J.message:String(J)}}},{params:z.Object({name:z.String()}),body:z.Record(z.String(),z.Any())}).delete("/:name",async({params:Q,body:Y,query:X,set:J})=>{try{let W=d(Q.name);if(W===v2())return J.status=409,{error:"is-default",message:`Cannot delete active default profile '${W}'. Switch to another profile first.`};let H=X?.purge==="true"||X?.purge==="1",B=e(o(W)),K=a.has(W);if(!B&&!K)return J.status=404,{error:"not-found",message:`No profile '${W}'.`};if(B&&!H&&!Y?.confirm)return J.status=400,{error:"confirm-required",message:"Pass { confirm: true } in the body or `?purge=true` in the query to delete the on-disk dataDir (destructive)."};try{await Z.stop(W)}catch{}try{await a.destroy(W)}catch(N){G().logger.warn("profile-mgmt",`In-process detach failed for '${W}'`,{error:String(N)})}if(B)if(Y?.keepConfig)for(let N of t0(o(W))){if(N==="config.json")continue;i0(b2(o(W),N),{recursive:!0,force:!0})}else i0(o(W),{recursive:!0,force:!0});return G().logger.info("profile-mgmt",`Deleted profile '${W}'`),{ok:!0,deleted:W,keptConfig:!!Y?.keepConfig,detached:K,purged:B}}catch(W){return J.status=400,{error:"delete-failed",message:W instanceof Error?W.message:String(W)}}},{params:z.Object({name:z.String()}),query:z.Optional(z.Object({purge:z.Optional(z.String())})),body:z.Optional(z.Object({confirm:z.Optional(z.Boolean()),keepConfig:z.Optional(z.Boolean())}))}).post("/:name/switch",async({params:Q,set:Y})=>{try{let X=d(Q.name);if(!e(o(X)))return Y.status=404,{error:"not-found",message:`No profile '${X}'.`};return await a0(()=>s0(X)),G().logger.info("profile-mgmt",`Default profile switched to '${X}'`),{ok:!0,defaultProfile:X}}catch(X){return Y.status=400,{error:"switch-failed",message:X instanceof Error?X.message:String(X)}}},{params:z.Object({name:z.String()})}).post("/:name/start",async({params:Q,body:Y,set:X})=>{try{let J=d(Q.name);if(!e(o(J)))return X.status=404,{error:"not-found",message:`No profile '${J}'.`};try{Y0(J)}catch(H){G().logger.warn("profile-mgmt",`In-process attach failed for '${J}'`,{error:String(H)})}if(!z0().some((H)=>H.name===J&&H.status==="running")){let H={name:J,port:Y?.port??0,daemon:!0,dbPath:M2(),profile:J};await Z.startDaemon(H)}return B2(J)}catch(J){return X.status=500,{error:"start-failed",message:J instanceof Error?J.message:String(J)}}},{params:z.Object({name:z.String()}),body:z.Optional(z.Object({port:z.Optional(z.Number())}))}).post("/:name/stop",async({params:Q,set:Y})=>{try{let X=d(Q.name);try{await Z.stop(X)}catch{}try{await a.destroy(X)}catch(J){G().logger.warn("profile-mgmt",`In-process detach failed for '${X}'`,{error:String(J)})}return B2(X)}catch(X){return Y.status=500,{error:"stop-failed",message:X instanceof Error?X.message:String(X)}}},{params:z.Object({name:z.String()})})}function JQ(){let $=process.memoryUsage(),Z=process.resourceUsage(),Q=Z.userCPUTime/1000,Y=Z.systemCPUTime/1000,X=Q+Y,J=a.list().map((W)=>{let H;try{H=$4(W.spawnOwnerKey).length}catch{H=0}return{name:W.name,status:W.getBootState(),childPidCount:H,cpuMs:X,heapBytes:$.heapUsed,dataDir:W.dataDir}});return{process:{pid:process.pid,uptimeSeconds:process.uptime(),cpuUserMs:Q,cpuSystemMs:Y,heapUsedBytes:$.heapUsed,heapTotalBytes:$.heapTotal,rssBytes:$.rss},profiles:J,notes:{perProfileCpu:"deferred",perProfileHeap:"deferred"}}}function Z4(){return new D({prefix:"/api/profile-stats"}).get("/",()=>JQ())}function y2($,Z){return Promise.race([$,new Promise((Q,Y)=>setTimeout(()=>Y(Error(`timeout after ${Z}ms`)),Z))])}function XQ($){let Z=$ instanceof Error?$.message:String($);return/ENOENT/.test(Z)||/no such file or directory/i.test(Z)}async function J4($){let Q=`__health__:probe:${typeof crypto<"u"&&typeof crypto.randomUUID==="function"?crypto.randomUUID():`${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`}`,Y=String(Date.now());if(await y2($.setConfig(Q,Y),2000),await y2($.getConfig(Q),2000)!==Y)throw Error("round-trip mismatch");try{await y2($.deleteConfig(Q),500)}catch{}}async function YQ($,Z){if(!$)return{ok:!1,message:"database not opened"};let Q=performance.now();try{return await J4($),{ok:!0,durationMs:performance.now()-Q}}catch(Y){if(Z&&XQ(Y))try{return(await import("fs")).mkdirSync(Z,{recursive:!0}),await J4($),{ok:!0,message:`recovered: dbPath ${Z} was missing \u2014 recreated`,durationMs:performance.now()-Q}}catch(X){return{ok:!1,message:`ENOENT on dbPath ${Z}: ${X instanceof Error?X.message:String(X)}`,durationMs:performance.now()-Q}}return{ok:!1,message:Y instanceof Error?Y.message:String(Y),durationMs:performance.now()-Q}}}function X4($,Z){if(!$)return{ok:!1,message:"no service registry"};let Y=G().getBootState()==="awaiting-config";if(Z==="tunnel"){let X=$.getProvider("tunnel");if(!X&&process.env.AGENT_TUNNEL==="false")return{ok:!0,message:"tunnel disabled via AGENT_TUNNEL=false"};if(X)return{ok:!0,message:`provider: ${X.name}`};return{ok:!1,message:Y?"agent is awaiting-config \u2014 POST OAuth credentials to /api/agent/gateway-auth to register tunnel provider":"no tunnel provider registered"}}if(Z==="session"){let X=$.getProvider("session");if(X)return{ok:!0,message:`provider: ${X.name}`};return{ok:!1,message:Y?"agent is awaiting-config \u2014 POST OAuth credentials to /api/agent/gateway-auth to register session provider":"no session provider registered"}}return{ok:!0}}async function WQ($){if(!$)return{};let Z={};for(let Q of $.getAllPlugins()){let Y=Q.getHealth;if(typeof Y!=="function")continue;let X=performance.now();try{let J=await y2(Promise.resolve(Y.call(Q)),2000);Z[Q.name]={ok:J?.ok!==!1,message:J?.message,durationMs:performance.now()-X}}catch(J){Z[Q.name]={ok:!1,message:J instanceof Error?J.message:String(J),durationMs:performance.now()-X}}}return Z}function Y4($){let Z=$&&"serviceRegistry"in $?$:{serviceRegistry:$};return new D({prefix:"/health"}).get("/",()=>{return{status:"ok",lifecycleState:Z.serviceRegistry?.getService("agent","lifecycle")?.getState()??"running",bootState:G().getBootState(),timestamp:new Date().toISOString(),uptime:process.uptime()}}).get("/live",()=>({status:"ok"})).get("/ready",async({set:Q})=>{let X=Z.serviceRegistry?.getService("agent","lifecycle")?.getState()??"running",J=G().getBootState(),W={};W.boot={ok:J==="ready",message:J==="ready"?void 0:`boot state ${J}`},W.lifecycle={ok:X==="running",message:X==="running"?void 0:`lifecycle ${X}`},W.db=await YQ(Z.getDb?.()??null,Z.getDbPath?.()??null),W.tunnel=X4(Z.serviceRegistry,"tunnel"),W.session=X4(Z.serviceRegistry,"session");try{let{gatewayClient:V}=await import("./gateway-client-43gzvj5s.js");if(!V.isConfigured())W.registration={ok:!0,message:"not configured"};else{let E=Z.getDb?.()??null;if(E?await E.getConfig("gateway-auth:agentRecordId"):null)W.registration={ok:!0};else{let h=G().getDegradedReasons().some((F)=>F.plugin==="agent-registration");W.registration=h?{ok:!1,message:"agent failed to register with the workspace after retries"}:{ok:!0,message:"registering"}}}}catch(V){W.registration={ok:!0,message:`registration check skipped: ${V instanceof Error?V.message:String(V)}`}}let H=await WQ(Z.getPluginManager?.()??null),B=Object.values(W).every((V)=>V.ok)&&Object.values(H).every((V)=>V.ok);if(!B)Q.status=503;let K=J==="degraded"?G().getDegradedReasons():[],N=G().name,I={};for(let V of a.list())I[V.name]={bootState:V.getBootState(),ok:V.getBootState()==="ready",degradedReasons:V.getDegradedReasons()};let C=G().getLastFinalizeError(),U={status:B?"ok":"degraded",lifecycleState:X,bootState:J,daemon:{profile:N,bootState:J,ok:J==="ready"},profiles:I,components:W,plugins:H,degradedReasons:K,lastFinalizeError:C,timestamp:new Date().toISOString()};if(!B)G().logger.warn("health","Readiness probe failed",{components:W,plugins:H,bootState:J});return U})}var c2=0,W4=0;function z4(){return new D({name:"inflight-tracker"}).onRequest(()=>{c2+=1}).onAfterResponse(()=>{c2=Math.max(0,c2-1),W4+=1})}function H4(){return new D({prefix:"/api/stats"}).get("/inflight",()=>({inflight:Math.max(0,c2-1),totalServed:W4}))}var H0=Object.freeze(["code","code-insiders","codium","cursor","idea","pycharm","webstorm","goland","phpstorm","rubymine","clion","rider","zed","subl","vim","nvim","emacs","neovide","fleet","helix"]),zQ=new Set(H0),HQ=new Set(["--new-window","-n","--reuse-window","-r","--wait","-w","--add","--goto"]);function G4($){try{return Bun.which($)??null}catch{return null}}function K4(){return new D({prefix:"/api/editor"}).get("/allowlist",()=>({commands:[...H0]})).get("/detect",async()=>{let $=H0.map((Y)=>[Y,G4(Y)]),Z=[],Q={};for(let[Y,X]of $)if(X)Z.push(Y),Q[Y]=X;return{available:Z,paths:Q}}).post("/open",async({body:$,set:Z})=>{let{command:Q,path:Y,args:X=[]}=$;if(!zQ.has(Q))return Z.status=400,{ok:!1,error:`Command '${Q}' is not in the IDE allowlist`};for(let H of X)if(typeof H!=="string"||!HQ.has(H))return Z.status=400,{ok:!1,error:`Argument '${H}' is not in the flag allowlist`};let J;try{J=(await B4(Y,{mustExist:!0})).realPath}catch(H){return Z.status=400,{ok:!1,error:`Invalid path: ${H instanceof Error?H.message:String(H)}`}}let W=G4(Q);if(!W)return Z.status=404,{ok:!1,error:`'${Q}' is not installed or not on PATH on this agent`};try{let H=V4({owner:`editor:${Q}`,cmd:[W,...X,J],env:process.env,stdout:"ignore",stderr:"ignore",stdin:"ignore",meta:{command:Q,path:J}});return G().logger.info("editor",`Launched ${Q} on ${J}`,{pid:H.pid}),G().audit.emit("agent","editor.open",{command:Q,path:J,pid:H.pid}),{ok:!0,command:Q,resolvedPath:J,pid:H.pid}}catch(H){return Z.status=500,{ok:!1,error:`Failed to spawn editor: ${H instanceof Error?H.message:String(H)}`}}},{body:z.Object({command:z.String({minLength:1,maxLength:40}),path:z.String({minLength:1,maxLength:4096}),args:z.Optional(z.Array(z.String({maxLength:32})))})})}var _4=Symbol.for("@vibecontrols/plugin-sdk:contextProviders@1");function GQ(){let $=globalThis,Z=$[_4];if(Z)return Z;let Q=new Map;return $[_4]=Q,Q}function G0(){return Array.from(GQ().values())}function N4(){return(b()??G()).dataDir}function n(){let $=s({dir:N4()});return{ownerUserId:$.ownerUserId,workspaceId:$.workspaceId}}function u2(){return s({dir:N4()}).agentRecordId}function F4($){if(!$)return null;try{return new URL($).host}catch{return null}}async function L4($,Z){let Q=$.getPluginManager(),Y=Q?Q.getPluginDetails().map((H)=>({pluginName:H.pluginName,packageName:H.packageName,version:H.version,tags:H.tags??[]})):[],X=process.memoryUsage(),J=F4($.getTunnelHost?.()??null),W;try{W=K2(n()).map((H)=>({id:H.id,label:H.label,host:F4(H.tunnelUrl),agentRecordId:H.agentRecordId??null,permissions:H.permissions,canForward:H.permissions.includes("mesh:forward"),lastReachable:H.lastReachable??null}))}catch{W=[]}return{pluginName:"agent",description:"vibecontrols-agent runtime self-report",generatedAt:new Date().toISOString(),data:{profile:Z.profile,vibeId:Z.vibeId??null,runtime:{bunVersion:typeof Bun<"u"?Bun.version:null,nodeVersion:process.versions.node??null,platform:process.platform,arch:process.arch,pid:process.pid,uptimeSeconds:Math.round(process.uptime()),memory:{rssMB:Math.round(X.rss/1048576),heapUsedMB:Math.round(X.heapUsed/1048576)}},agent:{version:$.getAgentVersion?.()??null,profileRegistered:T2(),tunnelHost:J},plugins:{count:Y.length,items:Y},mesh:{peerCount:W.length,peers:W}}}}var BQ=2000,O4=1000;async function VQ($,Z){let Q,Y=new Promise((X,J)=>{Q=setTimeout(()=>J(Error(`timeout after ${Z}ms`)),Z)});try{return await Promise.race([$,Y])}finally{if(Q)clearTimeout(Q)}}async function j4($,Z){let Q=performance.now(),Y=$.timeoutMs??BQ;try{let X=await VQ($.getContext(Z),Y);if(!X.generatedAt)X.generatedAt=new Date().toISOString();return{ok:!0,data:X,durationMs:Math.round(performance.now()-Q)}}catch(X){return{ok:!1,error:X.message??String(X),durationMs:Math.round(performance.now()-Q)}}}class B0{deps;inflight=new Map;constructor($){this.deps=$}async aggregate($){let Z=`${$.profile}::${$.vibeId??""}`,Q=this.inflight.get(Z);if(Q&&Date.now()-Q.ts<O4)return Q.promise;let Y=this.doAggregate($).finally(()=>{setTimeout(()=>{let X=this.inflight.get(Z);if(X&&X.promise===Y)this.inflight.delete(Z)},O4).unref?.()});return this.inflight.set(Z,{ts:Date.now(),promise:Y}),Y}async selfContext($){return L4(this.deps,$)}async pluginContext($,Z){let Q=G0().find((Y)=>Y.name===$);if(!Q)return null;return j4(Q,Z)}async pluginsContext($){let Z=G0(),Q=await Promise.allSettled(Z.map((X)=>j4(X,$))),Y={};return Z.forEach((X,J)=>{let W=Q[J];if(W&&W.status==="fulfilled")Y[X.name]=W.value;else if(W&&W.status==="rejected")Y[X.name]={ok:!1,error:W.reason instanceof Error?W.reason.message:String(W.reason),durationMs:0}}),Y}async doAggregate($){let[Z,Q]=await Promise.all([this.selfContext($),this.pluginsContext($)]);return{agent:Z,plugins:Q}}}function m2($){let Z=$.vibeId;if(typeof Z!=="string")return;let Q=Z.trim();return Q.length>0&&Q.length<=128?Q:void 0}function U4($){let Z=new B0($);return new D({prefix:"/api/agent/context"}).get("/",async({params:Q,query:Y})=>{let X=Q?.profile??"default",J=m2(Y);return Z.aggregate({profile:X,vibeId:J})},{query:z.Object({vibeId:z.Optional(z.String())})}).get("/agent",async({params:Q,query:Y})=>{let X=Q?.profile??"default",J=m2(Y);return Z.selfContext({profile:X,vibeId:J})},{query:z.Object({vibeId:z.Optional(z.String())})}).get("/plugins",async({params:Q,query:Y})=>{let X=Q?.profile??"default",J=m2(Y);return Z.pluginsContext({profile:X,vibeId:J})},{query:z.Object({vibeId:z.Optional(z.String())})}).get("/plugins/:name",async({params:Q,query:Y,set:X})=>{let J=Q?.profile??"default",W=Q?.name;if(!W)return X.status=400,{error:"missing plugin name"};let H=m2(Y),B=await Z.pluginContext(W,{profile:J,vibeId:H});if(!B)return X.status=404,{error:`no context provider registered under name "${W}"`};return B},{params:z.Object({name:z.String()}),query:z.Object({vibeId:z.Optional(z.String())})})}var Q2="autoupdate",KQ=86400000,x4=300000,_Q=900000,S={timer:null,running:!1,profile:"default",lastCheckAt:null,lastCheck:null,lastUpdateAt:null,lastUpdate:null,startedAt:null};function V0(){let $=(process.env.VIBE_AUTOUPDATE??"").trim().toLowerCase();return $==="0"||$==="false"||$==="off"||$==="no"}function T4(){if(V0())return!1;try{return s().autoUpdate!==!1}catch{return!0}}function K0(){let $=Number(process.env.VIBE_AUTOUPDATE_INTERVAL_MS);if(Number.isFinite($)&&$>0)return Math.max(_Q,$);return KQ}async function _0($){let Z=G().logger;if(S.running)return{check:S.lastCheck??await M4(),update:null};S.running=!0;try{let Q=await E2();if(S.lastCheck=Q,S.lastCheckAt=new Date().toISOString(),Q.error)Z.debug(Q2,`Update check failed: ${Q.error}`);else if(Q.hasUpdate)Z.info(Q2,`New agent version available: ${Q.current} \u2192 ${Q.latest}`);let Y=$?.force||T4();if(!Q.hasUpdate||!Y)return{check:Q,update:null};Z.info(Q2,`Auto-updating ${Q.current} \u2192 ${Q.latest} (idle-gated restart)\u2026`);let X=await g2({restart:!0,name:S.profile,onLog:(J)=>Z.info(Q2,J)});if(S.lastUpdate=X,S.lastUpdateAt=new Date().toISOString(),X.ok&&X.updated)Z.info(Q2,`Auto-update applied: now ${X.current} (restart: ${X.restart}).`);else if(!X.ok)Z.warn(Q2,`Auto-update failed: ${X.error}`);return{check:Q,update:X}}catch(Q){return Z.warn(Q2,`Auto-update tick threw: ${Q instanceof Error?Q.message:String(Q)}`),{check:await M4(),update:null}}finally{S.running=!1}}async function M4(){if(S.lastCheck)return S.lastCheck;let $=await E2();return S.lastCheck=$,S.lastCheckAt=new Date().toISOString(),$}function E4($){if(S.timer)clearTimeout(S.timer);S.timer=setTimeout(()=>{_0().finally(()=>{if(S.startedAt)E4(K0())})},$),S.timer.unref?.()}function NQ($){let Z=G().logger;if(S.profile=$?.profile||process.env.VIBECONTROLS_PROFILE||"default",S.startedAt=new Date().toISOString(),V0()){Z.info(Q2,"Autoupdate disabled via VIBE_AUTOUPDATE \u2014 not scheduling.");return}Z.info(Q2,`Autoupdate scheduled (first check in ${Math.round(x4/60000)}m, then every ${Math.round(K0()/3600000)}h).`),E4(x4)}function B7(){if(S.timer)clearTimeout(S.timer),S.timer=null;S.startedAt=null}function C4($){if(P2({autoUpdate:$}),$&&!S.startedAt)NQ({profile:S.profile})}function N0(){let $=!0;try{$=s().autoUpdate!==!1}catch{}return{enabled:T4(),envKillSwitch:V0(),configEnabled:$,scheduled:!!S.startedAt,intervalMs:K0(),profile:S.profile,startedAt:S.startedAt,lastCheckAt:S.lastCheckAt,lastCheck:S.lastCheck,lastUpdateAt:S.lastUpdateAt,lastUpdate:S.lastUpdate}}import{existsSync as I4}from"fs";import{join as q4}from"path";var FQ=600000,F0=1e6;function LQ(){let $=_2(),Z=$.which("bun")??`bun${$.executableSuffix}`,Q=q4(import.meta.dir,"cli.js");if(I4(Q))return{runner:Z,prefix:[Q]};let Y=q4(import.meta.dir,"..","cli.ts");if(I4(Y))return{runner:Z,prefix:[Y]};let X=$.which("vibe");if(X)return{runner:X,prefix:[]};return null}function R4($){if($.length<=F0)return $;return $.slice(0,F0)+`
4
- \u2026[output truncated at ${F0} bytes]`}async function p2($,Z={}){let Q=LQ();if(!Q)return{ok:!1,exitCode:null,stdout:"",stderr:"Could not locate the vibe CLI to execute (no dist/cli.js, source, or PATH entry).",timedOut:!1,argv:$,command:"(unresolved)"};let Y=[...Q.prefix,...$],X=[Q.runner,...Y].join(" ");try{let J=Bun.spawn([Q.runner,...Y],{cwd:Z.cwd,env:{...process.env,VIBE_AUTO_ACCEPT:"1",CI:"1",NO_COLOR:"1",...Z.env},stdout:"pipe",stderr:"pipe"}),W=Z.timeoutMs??FQ,H=!1,B=setTimeout(()=>{H=!0;try{J.kill()}catch{}},W),[K,N,I]=await Promise.all([new Response(J.stdout).text(),new Response(J.stderr).text(),J.exited]);return clearTimeout(B),{ok:!H&&I===0,exitCode:I,stdout:R4(K),stderr:R4(N),timedOut:H,argv:$,command:X}}catch(J){return{ok:!1,exitCode:null,stdout:"",stderr:`Failed to spawn vibe CLI: ${J instanceof Error?J.message:String(J)}`,timedOut:!1,argv:$,command:X}}}async function A4(){let{Command:$}=await import("./esm-9fpye77x.js"),{registerCoreCommands:Z}=await import("./register-core-mbv4hrbv.js"),Q=new $;Q.name("vibe").option("--json").option("--plain").option("-y, --yes").option("-p, --profile <name>");try{Z(Q)}catch{}let Y=new Set(["nuke","kill","gc","stop","rollback","deploy"]),X=[];for(let J of Q.commands){let W=J.name();if(!W||W==="help")continue;X.push({name:W,description:J.description()||"",usage:J.usage()||"",options:J.options.map((H)=>({flags:H.flags,description:H.description||""})),group:"core",destructive:Y.has(W)})}return X.sort((J,W)=>J.name.localeCompare(W.name))}import{spawn as OQ}from"child_process";import{writeFileSync as jQ,mkdirSync as UQ}from"fs";import{tmpdir as xQ}from"os";import{join as w4}from"path";var MQ="@vibecontrols/agent";function k4($){let Z=_2(),Q=Z.which("bun")??`bun${Z.executableSuffix}`,Y=Z.which("npm")??`npm${Z.executableSuffix}`,X=l2(),J=$.delayMs??3000,W=$.pids.filter((B)=>Number.isInteger(B)&&B>0),H=`// vibecontrols agent self-uninstall reaper (auto-generated)
5
- const PIDS = ${JSON.stringify(W)};
6
- const NPM = ${JSON.stringify(Y)};
7
- const BUN = ${JSON.stringify(Q)};
8
- const REGISTRY = ${JSON.stringify(X)};
9
- const PKG = ${JSON.stringify(MQ)};
10
- await Bun.sleep(${J});
11
- for (const pid of PIDS) {
12
- try { process.kill(pid, "SIGTERM"); } catch {}
13
- }
14
- await Bun.sleep(2500);
15
- for (const pid of PIDS) {
16
- try { process.kill(pid, "SIGKILL"); } catch {}
17
- }
18
- try { Bun.spawnSync([NPM, "uninstall", "-g", PKG, "--registry=" + REGISTRY], { stdout: "inherit", stderr: "inherit" }); } catch {}
19
- try { Bun.spawnSync([BUN, "remove", "-g", PKG], { stdout: "inherit", stderr: "inherit" }); } catch {}
20
- `;try{let B=w4(xQ(),"vibecontrols-uninstall");UQ(B,{recursive:!0});let K=w4(B,`reaper-${process.pid}.ts`);return jQ(K,H,{encoding:"utf8"}),OQ(Q,[K],{detached:!0,stdio:"ignore",windowsHide:!0}).unref(),G().logger.info("self-uninstall",`Scheduled detached uninstall reaper (pids=${W.join(",")}) at ${K}`),{ok:!0,scriptPath:K}}catch(B){return{ok:!1,scriptPath:null,error:B instanceof Error?B.message:String(B)}}}var TQ=new Set(["db","plugins-registry","logs","binaries","subprocs"]);async function S4($){let Z=await A4();try{let Q=$.getPluginManager?.();if(Q){let Y=new Set(Z.map((X)=>X.name));for(let X of Q.getPluginDetails()){let J=X.cliCommand;if(J&&!Y.has(J))Y.add(J),Z.push({name:J,description:X.description||`${X.pluginName} plugin command`,usage:"",options:[],group:"plugin",destructive:!1})}}}catch{}return Z.sort((Q,Y)=>Q.name.localeCompare(Y.name))}function D4($={}){return new D({name:"agent-maintenance"}).get("/api/agent/update/check",async()=>{return await E2()}).get("/api/agent/update/status",()=>{return N0()}).post("/api/agent/update",async({body:Z})=>{return await g2({targetVersion:typeof Z?.version==="string"?Z.version:void 0,allowIncompatible:Z?.allowIncompatible===!0,restart:Z?.restart!==!1})},{body:z.Optional(z.Object({version:z.Optional(z.String()),allowIncompatible:z.Optional(z.Boolean()),restart:z.Optional(z.Boolean())}))}).post("/api/agent/update/config",({body:Z})=>{return C4(Z.enabled),{ok:!0,status:N0()}},{body:z.Object({enabled:z.Boolean()})}).post("/api/agent/update/check-now",async({body:Z})=>{return{ok:!0,...await _0({force:Z?.force===!0})}},{body:z.Optional(z.Object({force:z.Optional(z.Boolean())}))}).get("/api/agent/commands",async()=>{let Z=await S4($);return{commands:Z,count:Z.length}}).post("/api/agent/commands/run",async({body:Z,set:Q})=>{let Y=Array.isArray(Z?.argv)?Z.argv.filter((B)=>typeof B==="string"):[];if(Y.length===0)return Q.status=400,{ok:!1,error:"argv must be a non-empty string array"};let X=Y[0],J=await S4($),W=new Set(J.map((B)=>B.name));if(!W.has(X))return Q.status=400,{ok:!1,error:`Unknown or disallowed command: "${X}"`,allowed:[...W].sort()};return await p2(Y,{timeoutMs:typeof Z?.timeoutMs==="number"?Z.timeoutMs:void 0})},{body:z.Object({argv:z.Array(z.String()),timeoutMs:z.Optional(z.Number())})}).post("/api/agent/nuke",async({body:Z,set:Q})=>{let Y=["nuke"];if(Z?.all)Y.push("--all");if(Z?.removeConfig)Y.push("--remove-config");if(Z?.dryRun)Y.push("--dry-run");if(typeof Z?.removePlugins==="string"&&Z.removePlugins)Y.push("--remove-plugins",Z.removePlugins);if(typeof Z?.keep==="string"&&Z.keep){let W=Z.keep.split(",").map((H)=>H.trim()).filter((H)=>H&&!TQ.has(H));if(W.length>0)return Q.status=400,{ok:!1,error:`Invalid --keep value(s): ${W.join(", ")}`};Y.push("--keep",Z.keep)}Y.push("-y","--json");let X=await p2(Y),J=null;try{let W=X.stdout.trim().split(`
21
- `).reverse().find((H)=>H.trim().startsWith("{"));if(W)J=JSON.parse(W)}catch{}return{...X,parsed:J}},{body:z.Optional(z.Object({all:z.Optional(z.Boolean()),removeConfig:z.Optional(z.Boolean()),removePlugins:z.Optional(z.String()),keep:z.Optional(z.String()),dryRun:z.Optional(z.Boolean())}))}).post("/api/agent/uninstall",async({body:Z})=>{let Q=Z?.dryRun===!0,Y=["nuke","--all","--remove-config","-y","--json"];if(Q)Y.push("--dry-run");let X=await p2(Y);if(Q)return{ok:X.ok,dryRun:!0,nuke:X,note:"Dry run \u2014 would nuke all state and uninstall @vibecontrols/agent."};let J=new Set([process.pid]);try{let H=new f2;for(let B of await H.listInstances())if(typeof B.pid==="number"&&B.pid>0)J.add(B.pid)}catch{}let W=k4({pids:[...J]});return{ok:X.ok&&W.ok,nuke:X,uninstallScheduled:W.ok,scriptPath:W.scriptPath,...W.error?{error:W.error}:{},note:"Agent state nuked; package self-uninstall scheduled \u2014 the daemon will stop and `@vibecontrols/agent` will be removed shortly."}},{body:z.Optional(z.Object({dryRun:z.Optional(z.Boolean())}))})}import{existsSync as RQ,readFileSync as AQ}from"fs";import{join as wQ}from"path";var EQ=`mutation AddAgentFromTunnel($input: AddAgentFromTunnelInput!) {
22
- addVibecontrolsAgentFromTunnel(input: $input) { agent { id name } clientId success error }
23
- }`,CQ=`mutation ReportAgentMeshLink($input: ReportAgentMeshLinkInput!) {
24
- reportAgentMeshLink(input: $input) { id }
25
- }`,h4="VIBE_BOOTSTRAP_JSON=";function IQ($){for(let Y of $.split(/\r?\n/)){let X=Y.indexOf(h4);if(X>=0)try{return JSON.parse(Y.slice(X+h4.length))}catch{}}let Z=$.indexOf("{"),Q=$.lastIndexOf("}");if(Z>=0&&Q>Z)try{return JSON.parse($.slice(Z,Q+1))}catch{return null}return null}async function f4($,Z){let Q=(N,I,C)=>Z?.({step:N,status:I,message:C}),Y=P4($.permissions??["tunnel:read","session:list","plugin:list","diagnostics:read","mesh:forward"]);if(!Y.includes("mesh:forward"))Y.push("mesh:forward");let X=(N)=>({ok:!1,peerId:"",agentRecordId:null,tunnelUrl:null,permissions:Y,error:N}),J;try{J=n2($.target,{identityFile:$.identityFile})}catch(N){return X(N instanceof Error?N.message:String(N))}let W=$.label??J.id,H=Y.join(","),B,K='export PATH="$HOME/.bun/bin:$PATH"; ';try{if(!$.connectExisting){Q("probe","running");let x=await J.probe();if(Q("probe","completed",`os=${x.os??"?"} arch=${x.arch??"?"}`),!x.bun){if($.installBun===!1)return X("Bun is required to run the agent but is not installed, and Bun auto-install was disabled.");Q("install-bun","running");let X2=await J.run(["sh","-c",`curl -fsSL https://bun.sh/install | bash && echo 'export PATH="$HOME/.bun/bin:$PATH"' >> ~/.bashrc`],{timeoutMs:300000});if(X2.code!==0)return Q("install-bun","failed",X2.stderr.slice(0,400)),X("Bun auto-install failed.");let N2=await J.run(["sh","-c","$HOME/.bun/bin/bun --version 2>/dev/null"],{timeoutMs:1e4});if(N2.code===0&&N2.stdout.trim())x.bun="$HOME/.bun/bin/bun",Q("install-bun","completed",N2.stdout.trim());else return X("Bun installed but the binary is not reachable.")}Q("install-agent","running");let q=$.version??"latest",c=$.registry??"https://registry.npmjs.org/";if(!/^[A-Za-z0-9._@/^~>=<-]+$/.test(q))return Q("install-agent","failed","invalid version"),X(`Invalid agent version: ${q}`);if(!/^https?:\/\/[A-Za-z0-9._~:/?#@!$&'()*+,;=%-]+$/.test(c))return Q("install-agent","failed","invalid registry"),X(`Invalid registry URL: ${c}`);let y=await J.run(["sh","-c",`${K}npm_config_registry="${c}" bun install -g @vibecontrols/agent@${q} --no-cache`],{timeoutMs:600000});if(y.code!==0)return Q("install-agent","failed",y.stderr.slice(0,400)),X(`Agent install failed (exit ${y.code}).`);if(B=(await J.run(["sh","-c",`${K}vibe --version`],{timeoutMs:15000})).stdout.trim()||void 0,Q("install-agent","completed",B),$.autostart)Q("autostart","running"),await J.run(["sh","-c",`${K}vibe autostart install`],{timeoutMs:60000}),Q("autostart","completed");if($.installPlugins?.length){Q("plugins","running");for(let X2 of $.installPlugins)await J.run(["sh","-c",`${K}vibe plugin install ${X2}`],{timeoutMs:300000});Q("plugins","completed")}Q("start","running"),await J.run(["sh","-c",`${K}vibe start`],{timeoutMs:60000}),Q("start","completed")}Q("bootstrap","running");let N=$.expiresIn?` --expires-in ${$.expiresIn}`:"",I=W.replace(/'/g,""),C=null;for(let x=0;x<15;x++){let q=`${K}vibe peer-bootstrap --json --emit-default-key --label '${I}' --scope ${H}${N} 2>/dev/null`,c=await J.run(["sh","-c",q],{timeoutMs:15000});if(c.code===0){let y=IQ(c.stdout);if(y&&typeof y.apiKey==="string"){C=y;break}}await new Promise((y)=>setTimeout(y,2000))}if(!C)return Q("bootstrap","failed","could not obtain peer-bootstrap bundle"),X("Remote peer-bootstrap did not return a credential bundle.");Q("bootstrap","completed");let U=n(),V=String(C.id),E=String(C.apiKey),R=d2(typeof C.tunnelUrl==="string"?C.tunnelUrl:null),h=typeof C.agentRecordId==="string"?C.agentRecordId:null;if($.onboardBackend!==!1&&g.isConfigured()&&R&&typeof C.fullDefaultApiKey==="string"){Q("onboard","running");try{let q=(await g.workspaceQuery(EQ,{input:{tunnelUrl:R,apiKey:C.fullDefaultApiKey,name:W}})).data?.addVibecontrolsAgentFromTunnel;if(q?.agent?.id)h=q.agent.id,Q("onboard","completed",`agent ${h}`);else Q("onboard","failed",q?.error??"no agent returned")}catch(x){Q("onboard","failed",x instanceof Error?x.message:String(x))}}else Q("onboard","skipped");Q("store-creds","running"),v4({id:V,label:W,tunnelUrl:R??"",apiKey:E,permissions:Y,addedAt:new Date().toISOString(),agentRecordId:h??void 0,workspaceId:(typeof C.workspaceId==="string"?C.workspaceId:U.workspaceId)??void 0,fingerprint:V,ownerUserId:U.ownerUserId,sshTarget:J.mode==="ssh"?$.target:void 0,sshIdentityFile:$.identityFile}),Q("store-creds","completed");let F=u2();if($.onboardBackend!==!1&&g.isConfigured()&&F&&h){Q("report-link","running");try{await g.workspaceQuery(CQ,{input:{sourceAgentRecordId:F,destinationAgentRecordId:h,label:W}}),Q("report-link","completed")}catch(x){Q("report-link","failed",x instanceof Error?x.message:String(x))}}else Q("report-link","skipped");let T=await C2(V,"/api/profiles/default/agent/identity",{operation:"post-deploy-probe"});return Q("probe-peer",T.ok?"completed":"failed",T.error??void 0),{ok:!0,peerId:V,agentRecordId:h,tunnelUrl:R,permissions:Y,remoteVersion:B}}catch(N){return X(N instanceof Error?N.message:String(N))}finally{await J.close().catch(()=>{})}}var L0='export PATH="$HOME/.bun/bin:$PATH"; ';function qQ($){let Z=$.indexOf("{"),Q=$.lastIndexOf("}");if(Z>=0&&Q>Z)try{let Y=JSON.parse($.slice(Z,Q+1));if(Y.tunnelUrl)return Y.tunnelUrl;if(Y.url&&Y.url.startsWith("https"))return Y.url}catch{}return null}async function c4($,Z){let Q=(J,W,H)=>Z?.({step:J,status:W,message:H}),Y=b4($);if(!Y)return{ok:!1,peerId:$,tunnelUrl:null,error:`No peer with id ${$}`};if(!Y.sshTarget)return{ok:!1,peerId:$,tunnelUrl:null,error:"No SSH target stored for this peer \u2014 it wasn't SSH-deployed, so it can't be woken via SSH."};let X;try{X=n2(Y.sshTarget,{identityFile:Y.sshIdentityFile})}catch(J){return{ok:!1,peerId:$,tunnelUrl:null,error:J instanceof Error?J.message:String(J)}}try{Q("ssh-restart","running",Y.sshTarget);let J=await X.run(["sh","-c",`${L0}vibe restart 2>/dev/null || ${L0}vibe start`],{timeoutMs:90000});if(J.code!==0)return Q("ssh-restart","failed",J.stderr.slice(0,300)),{ok:!1,peerId:$,tunnelUrl:null,error:`Remote restart failed (exit ${J.code})`};Q("ssh-restart","completed"),Q("await-tunnel","running");let W=null;for(let H=0;H<15;H++){let B=await X.run(["sh","-c",`${L0}vibe url --json 2>/dev/null`],{timeoutMs:15000});if(B.code===0){let K=qQ(B.stdout),N=d2(K);if(N){W=N;break}}await new Promise((K)=>setTimeout(K,2000))}if(!W)return Q("await-tunnel","failed","no fresh tunnel after restart"),{ok:!1,peerId:$,tunnelUrl:null,error:"Agent restarted but no fresh tunnel came up."};return Q("await-tunnel","completed",W),y4($,{tunnelUrl:W,lastReachable:new Date().toISOString()}),Q("update","completed"),{ok:!0,peerId:$,tunnelUrl:W}}catch(J){return{ok:!1,peerId:$,tunnelUrl:null,error:J instanceof Error?J.message:String(J)}}finally{await X.close().catch(()=>{})}}var kQ=Number(process.env.VIBECONTROLS_MESH_MAX_HOPS||"8");function u4(){return(b()??G()).name}function SQ(){return(b()??G()).dataDir}function m4(){try{let Z=wQ(SQ(),"runtime.json");if(RQ(Z)){let Q=JSON.parse(AQ(Z,"utf8"));if(Q.port&&Number.isInteger(Q.port))return Q.port}}catch{}let $=Number(process.env.PORT);return Number.isInteger($)&&$>0?$:3005}function DQ($){let Z={};return $.headers.forEach((Q,Y)=>{Z[Y]=Q}),Z}function Z2($,Z){let Q=m(DQ($));return l4(p4(Q),Z)}function hQ($){let{apiKey:Z,...Q}=$;return{...Q,apiKey:"[REDACTED]"}}function g4($){return typeof $==="string"&&$.startsWith("/api/")&&!$.includes("..")&&!$.includes("//")}var i2=new Map;function vQ(){let $=Date.now()-3600000;for(let[Z,Q]of i2)if(Q.completedAt&&Date.parse(Q.completedAt)<$)i2.delete(Z)}function n4(){return new D({name:"agent-mesh"}).get("/api/mesh/peers",({request:$,set:Z})=>{if(!Z2($,["read"]))return Z.status=403,{error:"forbidden"};return{peers:K2(n()).map(hQ)}}).delete("/api/mesh/peers/:id",({request:$,set:Z,params:Q})=>{if(!Z2($,["mutate"]))return Z.status=403,{error:"forbidden"};if(!K2(n()).some((X)=>X.id===Q.id))return Z.status=404,{error:"not found"};return{ok:d4(Q.id)}}).post("/api/mesh/peers/:id/call",async({request:$,set:Z,params:Q,body:Y})=>{if(!Z2($,["mesh:forward"]))return Z.status=403,{error:"forbidden"};let X=Y;if(!g4(X.path))return Z.status=400,{error:"invalid path"};if(!K2(n()).find((H)=>H.id===Q.id))return Z.status=404,{error:"not found"};let W=await C2(Q.id,X.path,{method:X.method??"GET",body:X.body,operation:"mesh-call"});return{ok:W.ok,status:W.status,data:W.data,rotated:W.rotated,error:W.error}},{body:z.Object({method:z.Optional(z.String()),path:z.String(),body:z.Optional(z.Any())})}).post("/api/mesh/forward",async({request:$,set:Z,body:Q})=>{if(!Z2($,["mesh:forward"]))return Z.status=403,{error:"forbidden"};let Y=Q;if(!Y.request||!g4(Y.request.path))return Z.status=400,{error:"invalid request"};let X=(Y._hopCount??0)+1;if(X>kQ)return Z.status=422,{error:"hop limit exceeded"};let J=n(),W=u2(),H=Y.hops??[];if(H.length===0){G().audit.emit("mesh","forward.terminal",{path:Y.request.path,method:Y.request.method??"GET"});let U=(Y.request.method??"GET").toUpperCase();try{let V=await fetch(`http://127.0.0.1:${m4()}${Y.request.path}`,{method:U,headers:{"x-agent-api-key":await O0(),...Y.request.body!==void 0?{"content-type":"application/json"}:{}},body:Y.request.body!==void 0?JSON.stringify(Y.request.body):void 0,signal:AbortSignal.timeout(60000)}),E=await V.text().catch(()=>""),R=null;try{R=E?JSON.parse(E):null}catch{R=null}return{ok:V.ok,status:V.status,data:R,text:E||null,error:V.ok?null:E||`status ${V.status}`}}catch(V){return Z.status=502,{ok:!1,status:0,error:V instanceof Error?V.message:String(V)}}}let B=H[0],K=Y._traversed??[];if(B===W||K.includes(B))return Z.status=422,{error:"cycle detected",at:B};let N=j0(B,J);if(!N)return Z.status=403,{error:"next hop not in authorized boundary"};if(!N.permissions.includes("mesh:forward"))return Z.status=403,{error:"peer lacks mesh:forward grant"};G().audit.emit("mesh","forward.hop",{nextId:B,remaining:H.length,hopCount:X});let I=encodeURIComponent(u4()),C=await C2(N.id,`/api/profiles/${I}/mesh/forward`,{method:"POST",operation:"mesh-forward",timeoutMs:60000,body:{hops:H.slice(1),request:Y.request,_traversed:[...K,W??"self"],_hopCount:X}});if(!C.ok)return Z.status=502,{ok:!1,status:C.status,error:C.error,failedAtHop:B};return C.data},{body:z.Object({hops:z.Optional(z.Array(z.String())),request:z.Object({method:z.Optional(z.String()),path:z.String(),body:z.Optional(z.Any())}),_traversed:z.Optional(z.Array(z.String())),_hopCount:z.Optional(z.Number())})}).post("/api/mesh/deploy",({request:$,set:Z,body:Q})=>{if(!Z2($,["admin"]))return Z.status=403,{error:"forbidden"};vQ();let Y=Q,X=n(),J=crypto.randomUUID(),W={id:J,status:"running",steps:[],ownerUserId:X.ownerUserId,workspaceId:X.workspaceId,startedAt:new Date().toISOString()};return i2.set(J,W),f4({target:Y.target,permissions:Y.permissions,installPlugins:Y.installPlugins,autostart:Y.autostart,identityFile:Y.identityFile,label:Y.label,version:Y.version,connectExisting:Y.connectExisting},(H)=>{W.steps.push(H),J2("mesh:deploy:progress",{jobId:J,step:H})}).then((H)=>{if(W.result=H,W.status=H.ok?"completed":"failed",!H.ok)W.error=H.error;W.completedAt=new Date().toISOString(),J2(H.ok?"mesh:deploy:complete":"mesh:deploy:failed",{jobId:J,result:H})}).catch((H)=>{W.status="failed",W.error=H instanceof Error?H.message:String(H),W.completedAt=new Date().toISOString(),J2("mesh:deploy:failed",{jobId:J,error:W.error})}),Z.status=202,{jobId:J,status:"running"}},{body:z.Object({target:z.String(),permissions:z.Optional(z.Array(z.String())),installPlugins:z.Optional(z.Array(z.String())),autostart:z.Optional(z.Boolean()),identityFile:z.Optional(z.String()),label:z.Optional(z.String()),version:z.Optional(z.String()),connectExisting:z.Optional(z.Boolean())})}).get("/api/mesh/deploy/jobs/:id",({request:$,set:Z,params:Q})=>{if(!Z2($,["read"]))return Z.status=403,{error:"forbidden"};let Y=i2.get(Q.id),X=n();if(!Y||X.ownerUserId&&Y.ownerUserId&&Y.ownerUserId!==X.ownerUserId)return Z.status=404,{error:"not found"};return Y}).post("/api/mesh/wake",async({request:$,set:Z,body:Q})=>{if(!Z2($,["admin"]))return Z.status=403,{error:"forbidden"};let Y=Q,X=j0(Y.targetAgentRecordId,n());if(!X)return Z.status=404,{ok:!1,error:"peer not in authorized boundary"};G().audit.emit("mesh","wake.start",{peerId:X.id,agentRecordId:Y.targetAgentRecordId});let J=await c4(X.id,(W)=>J2("mesh:wake:progress",{peerId:X.id,step:W}));if(!J.ok)Z.status=502;return J},{body:z.Object({targetAgentRecordId:z.String()})}).post("/api/mesh/session",async({request:$,set:Z,body:Q})=>{if(!Z2($,["mesh:forward","mutate"]))return Z.status=403,{error:"forbidden"};let Y=Q,X=Y.sessionId&&/^[A-Za-z0-9_-]{1,128}$/.test(Y.sessionId)?Y.sessionId:crypto.randomUUID(),J=encodeURIComponent(u4()),W=await O0(),H=`http://127.0.0.1:${m4()}`,B=Y.command||"bash";try{let K=await fetch(`${H}/api/profiles/${J}/sessions/create`,{method:"POST",headers:{"x-agent-api-key":W,"content-type":"application/json"},body:JSON.stringify({sessionId:X,sessionName:`vc-mesh-${X.slice(0,8)}`,command:B,provider:"TERMINAL",...Y.vibeId?{projectId:Y.vibeId}:{}}),signal:AbortSignal.timeout(20000)});if(!K.ok)return Z.status=502,{error:`session create returned ${K.status}: ${await K.text().catch(()=>"")}`};let N=await fetch(`${H}/api/profiles/${J}/sessions/${encodeURIComponent(X)}/terminal`,{method:"POST",headers:{"x-agent-api-key":W},signal:AbortSignal.timeout(20000)});if(!N.ok)return Z.status=502,{error:`terminal start returned ${N.status}: ${await N.text().catch(()=>"")}`};let I=D2(`/terminal/${X}`,600);return G().audit.emit("mesh","session.created",{sessionId:X,kind:Y.kind??"TERMINAL"}),{connectionId:X,sessionId:X,capabilityToken:I.token,expiresAt:I.expiresAt}}catch(K){return Z.status=502,{error:K instanceof Error?K.message:String(K)}}},{body:z.Object({sessionId:z.Optional(z.String()),kind:z.Optional(z.String()),cwd:z.Optional(z.String()),vibeId:z.Optional(z.String()),command:z.Optional(z.String())})})}var PQ=["/health","/api/agent/status","/api/agent/version","/api/agent/identity","/api/agent/api-key","/api/agent/tunnel","/api/agent/system","/api/agent/gateway-auth","/api/stats","/metrics","/api/profiles","/api/profile-stats"];function fQ($){return PQ.some((Z)=>$.startsWith(Z))}var bQ=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function yQ($){return $.split("/").map((Z)=>{if(!Z)return Z;if(/^\d+$/.test(Z))return":id";if(bQ.test(Z))return":id";if(Z.length>=24&&/^[A-Za-z0-9_-]+$/.test(Z))return":id";return Z}).join("/")}async function l8($){let{port:Z,host:Q,dbPath:Y,logLevel:X,corsOrigin:J}=$,W=Y??M2();try{(await import("fs")).mkdirSync(W,{recursive:!0})}catch(_){throw G().logger.error("app","Failed to create dbPath dir at boot",{dbPath:W,error:String(_)}),Error(`Cannot create dbPath ${W}: ${_ instanceof Error?_.message:String(_)}`,{cause:_})}if(X)G().logger.setLevel(X);(async()=>{let{logShipper:_}=await import("./log-shipper-k24m8yw5.js");_.init()})(),(async()=>{let _=await o4();await w2({version:_,profile:T2()})})();try{let{checkDependencies:_}=await import("./bootstrap.service-pjmnpxha.js"),M=_(),O=M.filter((A)=>A.required&&!A.installed),w=M.filter((A)=>!A.required&&!A.installed);if(O.length>0)G().logger.error("app",`Missing required system deps: ${O.map((A)=>A.name).join(", ")}. Run \`vibe setup\` to install.`);if(w.length>0)G().logger.warn("app",`Missing optional system deps: ${w.map((A)=>A.name).join(", ")}. Some plugins may fail their prereqs check.`)}catch(_){G().logger.warn("app","Boot-time dependency check failed",{error:String(_)})}try{G().audit.runRetention()}catch(_){G().logger.warn("app","Audit-log retention sweep failed",{error:String(_)})}let H=new N5;C5(H,{port:Z});let B="GET, POST, PUT, PATCH, DELETE, OPTIONS",K="Content-Type, x-agent-api-key, Authorization, x-requested-with",N=Array.isArray(J)?J:(J??"").split(",").map((_)=>_.trim()).filter(Boolean),I=new Set(["https://vibecontrols.com","https://app.vibecontrols.com","https://alphaapp.vibecontrols.com","https://burdenoff.com","https://app.burdenoff.com","https://alphaapp.burdenoff.com"]),C=(_)=>{try{let M=new URL(_);if(N.includes(_))return!0;if(N.includes("*"))return!1;return M.hostname==="localhost"||M.hostname==="127.0.0.1"||M.hostname==="0.0.0.0"||M.hostname.endsWith(".local.burdenoff.com")||I.has(M.origin)}catch{return!1}},U=null,V=null,E=null,R=null,h=!1,F=()=>[],T=null,x=null,q=null,c=5000,y=async(_,M)=>{let O=Date.now();try{await Promise.race([Promise.resolve(M()),new Promise((w,A)=>setTimeout(()=>A(Error(`shutdown phase ${_} exceeded ${c}ms`)),c))]),G().logger.info("app",`shutdown.phase ${_} complete`,{ms:Date.now()-O})}catch(w){G().logger.warn("app",`shutdown.phase ${_} failed`,{error:String(w),ms:Date.now()-O})}},o2=async(_)=>{if(h)return;if(h=!0,G().logger.info("app","Agent shutdown starting",{reason:_?.reason??"shutdown"}),await y("plugins",async()=>{if(V)await V.dispatchServerStop(_)}),await y("bootstrap-tunnel",()=>T0()),await y("tracked-subprocesses",async()=>{let{killAllTracked:M}=await import("./subprocess-g9sk1ep9.js");await M()}),_?.reason!=="reload")await y("db-close",async()=>{if(U)await U.close()});await y("http-listener",async()=>{try{await Promise.resolve(r.stop())}catch(M){G().logger.warn("app","Listener stop threw (already stopped or never started?)",{error:String(M)})}}),G().logger.info("app","Agent server stopped"),G().logger.close()},X2=async(_,M)=>{if(G().getBootState()==="ready")return{ok:!0};if(q)return q;return q=(async()=>{G().setBootState("initializing");try{let O={..._,globalGatewayUrl:G2(_.globalGatewayUrl,"globalGatewayUrl"),workspaceGatewayUrl:G2(_.workspaceGatewayUrl,"workspaceGatewayUrl")},w=await L5(O),A=W,v=s({dir:G().dataDir}),p=v.storageAdapter??process.env.VIBE_STORAGE_ADAPTER??void 0,i=v.storageOptions,t=(L)=>{let j=(L instanceof Error?L.message:String(L)).toLowerCase(),k=L&&typeof L==="object"&&"code"in L?String(L.code).toUpperCase():"";if(k==="EBUSY"||k==="EPERM"||k==="EACCES"||k==="EAGAIN"||k==="EMFILE"||k==="ENFILE"||k==="ETIMEDOUT"||k==="ECONNRESET"||k==="ECONNREFUSED"||j.includes("encryption key")||j.includes("fetch")&&j.includes("key")||j.includes("temporarily unavailable")||j.includes("resource busy"))return"transient";if(j.includes("auth tag")||j.includes("authentication tag")||j.includes("unable to authenticate data")||j.includes("bad decrypt")||j.includes("unsupported state")||j.includes("incorrect header check")||j.includes("invalid distance")||j.includes("incorrect data check")||j.includes("unexpected end of")||j.includes("unexpected token")||j.includes("json")&&(j.includes("parse")||j.includes("invalid"))||j.includes("truncated")||j.includes("malformed")||j.includes("corrupt"))return"corruption";return"unknown"},F2=()=>a4({dbPath:A,encryptionKey:w,adapterName:p,adapterOptions:i});try{U=await F2()}catch(L){let j=L,k=t(L),q2=[500,2000,8000];if(k==="transient"||k==="unknown"){G().logger.warn("app",`Storage open failed (${k}); will retry up to ${q2.length} times before quarantine`,{error:L instanceof Error?L.message:String(L),path:A});for(let j2 of q2){await new Promise((P)=>setTimeout(P,j2));try{U=await F2(),j=null;break}catch(P){if(j=P,k=t(P),G().logger.warn("app",`Storage open retry failed (${k}) after ${j2}ms`,{error:P instanceof Error?P.message:String(P)}),k==="corruption")break}}}if(!U&&j){if(k!=="corruption"){let P=j instanceof Error?j.message:String(j);G().logger.error("app",`Storage open failed after retries with non-corruption error (${k}); refusing to quarantine valid data`,{error:P,path:A}),G().recordDegradedReason("storage",P);try{throw j}catch(H2){throw Error(`Storage open failed (${k}); agent is degraded: ${P}`,{cause:H2})}}let j2=j instanceof Error?j.message:String(j);G().logger.error("app","QUARANTINE: Storage file is corrupt \u2014 renaming and creating fresh DB",{errorClass:"corruption",error:j2,path:A});try{let P=await import("fs");if(P.existsSync(A)){let H2=new Date().toISOString().replace(/[:.]/g,"-"),q0=`${A}.broken-${H2}`;P.renameSync(A,q0),G().logger.warn("app",`Quarantined corrupt storage to ${q0} \u2014 fresh DB will be created`,{originalError:j2})}U=await F2()}catch(P){let H2=P instanceof Error?P.message:String(P);throw G().recordDegradedReason("storage",H2),Error(`Storage open failed twice (quarantine path); agent is degraded: ${H2}`,{cause:P})}}}if(!U)throw Error("Internal error: storage open recovery exited without an open database and without throwing");if(await S2({clientId:O.clientId,clientSecret:O.clientSecret,workspaceId:O.workspaceId,organizationId:O.organizationId,globalGatewayUrl:O.globalGatewayUrl,workspaceGatewayUrl:O.workspaceGatewayUrl,agentRecordId:M?.agentRecordId,scopes:M?.scopes},{dir:G().dataDir,scope:G().name}),await U.setConfig("gateway-auth:clientId",O.clientId),await U.setConfig("gateway-auth:clientSecret",O.clientSecret),await U.setConfig("gateway-auth:globalGatewayUrl",O.globalGatewayUrl),await U.setConfig("gateway-auth:workspaceGatewayUrl",O.workspaceGatewayUrl),await U.setConfig("gateway-auth:workspaceId",O.workspaceId),O.organizationId)await U.setConfig("gateway-auth:organizationId",O.organizationId);if(M?.agentRecordId)await U.setConfig("gateway-auth:agentRecordId",M.agentRecordId);H.db=U,await H.hydrateDefaultsFromDb(),V=new M5(U),await V.loadCorePlugins();try{await V.loadAll()}catch(L){G().logger.warn("app","Failed to load some external plugins",{error:String(L)})}let L2=T5(V2())??void 0,O2=process.env.VIBE_SKIP_AUTO_INSTALL==="1"||await U.getConfig("plugins:auto-install-disabled");if(O2!=="true"&&O2!==!0)try{let L=await V.ensureDefaultPlugins((j)=>G().logger.info("app",`[auto-install] ${j}`),[],L2);if(L.length>0)G().logger.info("app",`Auto-installed ${L.length} default plugin(s): ${L.map((j)=>j.packageName).join(", ")}`)}catch(L){G().logger.warn("app","Failed to auto-install default plugins",{error:String(L)})}G().logger.info("app",`Plugins loaded: ${V.getPluginDetails().length} total (${V.getPluginDetails().filter((L)=>L.isCore).length} core)`);try{let L=V.getPluginDetails(),j={loaded:L.filter((k)=>k.loaded).length,failed:L.filter((k)=>!k.loaded).length};P0(j)}catch{}let s2={async get(L,j){return await U.getPluginState(L,j)??null},async set(L,j,k){await U.setPluginState(L,j,k)},async delete(L,j){return U.deletePluginState(L,j)},async list(L){return await U.getAllPluginState(L)},async deleteAll(L){return U.deleteAllPluginState(L)}},I2=await o4();E={storage:s2,logger:G().logger,serviceRegistry:H,getProvider:(L)=>H.getProvider(L),getAgentBaseUrl:()=>process.env.AGENT_URL||`http://localhost:${Z}`,getAgentVersion:()=>I2,validateApiKey:(L)=>l(L),setCodeServerSessionValidator:(L)=>{I5=L},broadcast:J2,workspaceQuery:async(L,j)=>g.workspaceQuery(L,j),isGatewayConfigured:()=>g.isConfigured(),getAgentRecordId:async()=>await U.getConfig("gateway-auth:agentRecordId")??null,getWorkspaceId:async()=>await U.getConfig("gateway-auth:workspaceId")??null,getConfig:async(L)=>await U.getConfig(L)??void 0,getPluginRegistry:()=>l2(),getDataDir:()=>k2(),cliContributors:new F5,audit:{emit:(L,j)=>G().audit.emit("agent",L,j??{})},telemetry:{emit:(L,j)=>{import("./telemetry-tnq47dcs.js").then(({telemetryService:k})=>k.emit(L,j??{})).catch(()=>{})}},os:_2(),iframeBridge:x5()},g.configure({globalGatewayUrl:O.globalGatewayUrl,workspaceGatewayUrl:O.workspaceGatewayUrl,clientId:O.clientId,clientSecret:O.clientSecret,workspaceId:O.workspaceId,organizationId:O.organizationId});let z2={db:U,serviceRegistry:H,pluginManager:V,broadcast:J2,hostServices:E};z2.app=r;let I0=!1,r2=()=>{let{routes:L,getPublicPaths:j,mountPlugin:k}=e4(V,z2);if(z2.mountPlugin=k,F=j,J5(),T=L,x=U5(V),V&&I0&&E)V.dispatchServerStart(T,E).catch((q2)=>G().logger.warn("app","Re-dispatch of onServerStart after plugin reload failed",{error:String(q2)}));I0=!0};z2.rebuildPluginSurfaces=r2,r2(),R=new O5(H,V,U,r,E,o2),H.registerService("agent","lifecycle",R),G().attachServices({db:U,serviceRegistry:H,pluginManager:V,lifecycle:R,hostServices:E}),K5(G(),{rebuildPluginSurfaces:r2,mountPlugin:z2.mountPlugin});try{await G().keyVault.bindApiKey(x2())}catch(L){G().logger.warn("app","Failed to bind api key into daemon keyVault",{error:String(L)})}let t2=[];try{let{failures:L}=await V.dispatchServerStart(T,E);for(let j of L)if(M0(j.plugin)||(j.packageName?M0(j.packageName):!1))t2.push(j),G().recordDegradedReason(j.plugin,j.error);else G().logger.warn("app",`Non-critical plugin ${j.plugin} failed onServerStart; continuing`,{error:j.error})}catch(L){G().logger.warn("app","Error during plugin onServerStart dispatch",{error:String(L)})}try{await V.dispatchServerReady(r,E)}catch(L){G().logger.warn("app","Error during plugin onServerReady dispatch",{error:String(L)})}if(G().clearFinalizeError(),t2.length>0)G().setBootState("degraded"),G().logger.error("app","Agent finalized but degraded \u2014 critical plugins failed",{failures:t2.map((L)=>`${L.plugin}: ${L.error}`)});else G().setBootState("ready"),G().logger.info("app","Agent finalized \u2014 state=ready"),G().audit.emit("agent","gateway-auth.configured",{workspaceId:O.workspaceId,organizationId:O.organizationId,agentRecordId:M?.agentRecordId});return(async()=>{try{if(await V.provisionDefaultPrereqs(r,E,z2.mountPlugin,L2),G().logger.info("app","Default provider prerequisites provisioned"),(H.listProvidersForType("tunnel")??[]).some((k)=>k.pluginName!=="bootstrap")){let{tryHandoverBootstrapTunnel:k}=await import("./tunnel-bootstrap-2kg79ng8.js");if(!k())T0();H.unregisterProvider("tunnel","bootstrap"),G().logger.info("app","Bootstrap tunnel handed over to the real tunnel provider")}}catch(L){G().logger.warn("app","Plugin prerequisite provisioning failed",{error:String(L)})}})(),{ok:!0}}catch(O){G().setBootState("awaiting-config");let w=O instanceof Error?O.message:String(O);if(G().recordFinalizeError(w),G().logger.error("app","Finalize failed",{error:w}),process.env.VIBE_STRICT_KEY_FETCH==="1")G().logger.error("app","VIBE_STRICT_KEY_FETCH=1 \u2192 aborting daemon (strict mode)",{error:w}),setTimeout(()=>process.exit(1),50);return{ok:!1,error:w}}finally{q=null}})(),q},N2=A0({origin:(_)=>{let M=_.headers.get("origin");return!!M&&C(M)},credentials:!0,allowedHeaders:K.split(",").map((_)=>_.trim()),methods:B.split(",").map((_)=>_.trim()),exposeHeaders:["content-type","content-length"],maxAge:86400,preflight:!0}),q5=10485760,E0=process.env.VIBECONTROLS_MAX_BODY_BYTES,a2=E0?Number.parseInt(E0,10):NaN,R5=Number.isFinite(a2)&&a2>0?a2:q5,C0={current:null},r=new D({serve:{maxRequestBodySize:R5}}).onRequest(({request:_,set:M})=>{let w=s4(_.headers)??U0();r4({requestId:w,startedAt:new Date().toISOString()});let A=M.headers??={};A["X-Request-Id"]=w}).onRequest(({request:_})=>{try{let M=new URL(_.url).pathname,w=/^\/api\/profiles\/([^/]+)(?:\/|$)/.exec(M)?.[1],A=w?a.get(w):null;x0(A??G())}catch{x0(G())}}).onRequest(({request:_,set:M})=>{let O=new URL(_.url).pathname;if(!O.startsWith("/api/"))return;if(O==="/api/profiles"||O.startsWith("/api/profiles/"))return;if(O==="/api/profile-stats"||O.startsWith("/api/profile-stats/"))return;let w=new URL(_.url);w.pathname=`/api/profiles/default${O.slice(4)}`;try{_.headers.set("x-vc-profile-rewrite","1"),_.headers.set("x-vc-profile-rewrite-target",w.pathname)}catch{}return}).derive(()=>({requestId:t4()??U0()})).use(N2).use(Y5()).use(X5(()=>F())).use(S0({getDb:()=>b()?.db??U})).onBeforeHandle(({request:_,set:M})=>{let O=G().getBootState();if(O==="ready")return;let w=new URL(_.url).pathname;if(fQ(w))return;return M.status=503,{error:"Agent not yet configured",message:"Agent is in '"+O+"' state. POST credentials to /api/agent/gateway-auth to finalize.",state:O}}).onAfterHandle(({request:_,set:M})=>{let O=new URL(_.url).pathname,w=O==="/health"||O.startsWith("/api/logs/stream")||O.startsWith("/ui/")||O==="/ws/events"||O==="/api/sessions/health-check"||O.startsWith("/terminal/"),A=typeof M.status==="number"?M.status:200,v=w?"debug":A>=400?"warn":"info";G().logger[v]("http",`${_.method} ${O} \u2192 ${A}`,{method:_.method,path:O,statusCode:A});try{v0(_.method,yQ(O),A)}catch{}}).use(Y4({serviceRegistry:H,getDb:()=>b()?.db??U,getDbPath:()=>W,getPluginManager:()=>b()?.pluginManager??V})).use(b0()).use(n0({serviceRegistry:H,runFinalize:(_,M)=>X2(_,M),getDb:()=>b()?.db??U})).use(z4()).use(H4()).use(D4({getPluginManager:()=>b()?.pluginManager??V})).use(n4()).use(K4()).use(U4({getPluginManager:()=>b()?.pluginManager??V,getTunnelHost:()=>E5()?.url??null})).use(Q4()).use(Z4()).use(G5()).use(V5()).use(B5(H)).ws("/code-server/*",uQ(Z)).all("/api/profiles/:name/*",async({params:_,request:M,set:O})=>{let w=M.method!=="GET"&&M.method!=="HEAD",A=w?await M.arrayBuffer():void 0,v=await _5(_.name,M,A);if(v&&v.status!==404)return v;let p=T2(),i=_.name;if(i!==p)return O.status=404,{error:"profile-mismatch",running:p,requested:i,hint:"This daemon serves a different profile. Call GET /api/profiles to discover the right tunnel."};let t=new URL(M.url),F2=t.pathname.replace(/^\/api\/profiles\/[^/]+/,"/api"),L2=new Headers(M.headers);L2.set("x-vc-profile-rewrite","1");let O2={method:M.method,headers:L2};if(w&&A!==void 0)O2.body=A;let s2=new Request(`${t.origin}${F2}${t.search}`,O2),I2=C0.current;if(!I2)return new Response(JSON.stringify({error:"agent-not-ready"}),{status:503,headers:{"content-type":"application/json"}});return I2.handle(s2)}).all("/api/*",async({request:_})=>{if(G().getBootState()!=="ready"||!T)return new Response(JSON.stringify({error:"Agent not yet configured",state:G().getBootState(),message:"Plugin routes are unavailable until the agent reaches state=ready. POST credentials to /api/agent/gateway-auth to finalize."}),{status:503,headers:{"content-type":"application/json"}});try{let M=new URL(_.url),O=/^\/api\/plugins\/([a-z0-9-]{1,64})\/ui(?:\/.*)?$/.exec(M.pathname);if(O&&_.method==="GET"){let w=O[1];if(U2(w)){let A=M.pathname.slice(`/api/plugins/${w}/ui`.length),v=A===""||A==="/",i=_.headers.get("sec-fetch-mode")==="navigate";if(v||i){let t=Z5(_,w);if(!t||!$5(t,w))return new Response(j5(w,"/api/profiles/default/agent/ui-exchange-plugin"),{status:200,headers:{"content-type":"text/html; charset=utf-8","Content-Security-Policy":"frame-ancestors 'self' http://localhost:* http://127.0.0.1:* https://localhost:* https://127.0.0.1:* https://*.local.burdenoff.com https://vibecontrols.com https://*.vibecontrols.com https://burdenoff.com https://app.burdenoff.com https://alphaapp.burdenoff.com"}})}}}}catch{}return T.handle(_)}).all("/ui/*",async({request:_})=>{if(G().getBootState()!=="ready"||!x)return new Response("Plugin UI not yet available",{status:503});return x.handle(_)}).all("/code-server/*",async({request:_})=>{if(G().getBootState()!=="ready"||!T)return new Response("code-server not yet available",{status:503});return T.handle(_)}).all("/plan/*",async({request:_})=>{if(G().getBootState()!=="ready"||!T)return new Response("plan provider not yet available",{status:503});return T.handle(_)});return C0.current=r,{app:r,async start(){r.listen({port:Z,hostname:Q}),G().logger.info("app",`Agent server listening on ${Q}:${Z}`);try{let _=(process.env.VIBECONTROLS_PROFILES??"").split(",").map((v)=>v.trim()).filter(Boolean),M=G().name,{getOrCreateProfile:O}=await import("./daemon-profile-vas1vf2t.js"),{attachSecondaryProfile:w}=await import("./secondary-profile-attach-db5cr3e1.js"),A=process.env.VIBE_STRICT_KEY_FETCH==="1";for(let v of _){if(v===M)continue;try{let p=O(v),i=await w(p);if(i.ok)G().logger.info("app",`Secondary profile '${v}' attached (db+services online)`);else if(A)throw Error(`attachServices for secondary profile '${v}' failed: ${i.error}`);else p.recordDegradedReason("attach",i.error??"unknown"),G().logger.warn("app",`Secondary profile '${v}' is degraded (no creds / attach failed)`,{error:i.error})}catch(p){if(A)throw G().logger.error("app",`--strict-key-fetch: secondary profile '${v}' attach failed; aborting`,{error:String(p)}),setTimeout(()=>process.exit(1),50),p;G().logger.warn("app",`Failed to attach secondary profile '${v}'`,{error:String(p)})}}}catch{}return r},stop:o2,finalize:X2,getState:()=>G().getBootState(),getLifecycle:()=>b()?.lifecycle??R,getDb:()=>b()?.db??U,getServiceRegistry:()=>b()?.serviceRegistry??H,getPluginManager:()=>b()?.pluginManager??V,getHostServices:()=>b()?.hostServices??E}}var I5=null;function cQ($,Z){if(!$)return null;let Q=$.match(new RegExp(`(?:^|;\\s*)${Z}=([^;]*)`));return Q?Q[1]:null}var i4=W5(z5);function uQ($){let X=(J)=>typeof J==="string"?Buffer.byteLength(J):J.byteLength;return{open(J){let W=J.data,H=m(W.headers??{})??m(W.request?Object.fromEntries(W.request.headers.entries()):{}),B=W.query?.vt,K=!!B&&Q5(B,"/code-server","GET"),N,I=l(H);if(!I&&!K){let E=W.headers?.cookie??W.request?.headers.get("cookie")??null,R=cQ(E,"__vibe_cs_session");if(!R||!I5?.(R)){J.close(1008,"Unauthorized");return}N=`session:${R}`}else if(I)N="api-key";else N="vt";let C=J.remoteAddress??null,U=H5(C,W.headers);if(!i4.accept(N,U,J)){G().logger.warn("code-server-ws",`code-server WS cap exceeded (key=${N}, ip=${U??"unknown"})`),J.close(1013,"too many connections");return}W._csCapKey=N,W._csRemoteIp=U;let V=G().name;fetch(`http://127.0.0.1:${$}/api/profiles/${encodeURIComponent(V)}/code-server/status`,{headers:{"x-agent-api-key":x2()}}).then((E)=>E.json()).then((E)=>{if(W._csClosed)return;let R=E;if(!R.running||!R.port){J.close(1011,"code-server not running");return}let h=W.request?.url??"/code-server/",F;try{let q=new URL(h,`http://127.0.0.1:${R.port}`);F=(q.pathname.replace(/^\/code-server\/?/,"/")||"/")+q.search}catch{F="/"}let T=new WebSocket(`ws://127.0.0.1:${R.port}${F}`),x={upstream:T,ready:!1,buffer:[],bufferBytes:0,openTimer:setTimeout(()=>{try{T.close(1011,"upstream open timeout")}catch{}try{J.close(1011,"upstream open timeout")}catch{}},1e4)};W._csBridge=x,T.addEventListener("open",()=>{clearTimeout(x.openTimer),x.ready=!0;for(let q of x.buffer)T.send(q);x.buffer.length=0,x.bufferBytes=0}),T.addEventListener("message",(q)=>{try{let c=q.data;if(c instanceof ArrayBuffer)J.send(new Uint8Array(c));else if(c instanceof Blob)c.arrayBuffer().then((y)=>{try{J.send(new Uint8Array(y))}catch{}});else J.send(c)}catch{}}),T.addEventListener("close",(q)=>{clearTimeout(x.openTimer);try{J.close(q.code||1000,q.reason||"upstream closed")}catch{}}),T.addEventListener("error",()=>{clearTimeout(x.openTimer);try{J.close(1011,"upstream error")}catch{}})}).catch(()=>{J.close(1011,"Failed to query code-server status")})},message(J,W){let H=J.data?._csBridge;if(!H)return;let B;if(typeof W==="string")B=W;else if(W instanceof ArrayBuffer)B=W;else if(W instanceof Uint8Array||Buffer.isBuffer(W)){let K=new ArrayBuffer(W.byteLength);new Uint8Array(K).set(new Uint8Array(W.buffer,W.byteOffset,W.byteLength)),B=K}else if(typeof W==="object"&&W!==null)B=JSON.stringify(W);else B=String(W);if(H.upstream&&H.ready&&H.upstream.readyState===WebSocket.OPEN)try{H.upstream.send(B)}catch{}else{let K=X(B);if(H.buffer.length>=256||H.bufferBytes+K>1048576){try{H.upstream.close(1013,"buffer limit exceeded")}catch{}try{J.close(1013,"buffer limit exceeded")}catch{}return}H.buffer.push(B),H.bufferBytes+=K}},close(J){J.data._csClosed=!0;let W=J.data?._csBridge;if(W?.openTimer)clearTimeout(W.openTimer);if(W?.upstream&&W.upstream.readyState===WebSocket.OPEN)W.upstream.close(1000,"client disconnected");let H=J.data._csCapKey,B=J.data._csRemoteIp;if(H)i4.release(H,B??null,J)}}}async function o4(){try{let{readFileSync:$}=await import("fs"),{join:Z,dirname:Q}=await import("path"),{fileURLToPath:Y}=await import("url"),X=Q(Y(import.meta.url));return JSON.parse($(Z(X,"..","package.json"),"utf8")).version||"1.0.0"}catch{return"1.0.0"}}
26
- export{X6 as j,u0 as k,NQ as l,B7 as m,l8 as n};
@@ -1,2 +0,0 @@
1
- // @bun
2
- import{c as a}from"./index-8kvc8ttn.js";import"./index-x1h8r7pr.js";import"./index-yy1mm8zs.js";export default a();