@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,4 +1,4 @@
1
1
  // @bun
2
2
  import{isAbsolute as S,join as Z,relative as v,resolve as H}from"path";import{existsSync as E,readFileSync as m}from"fs";import{homedir as u}from"os";import{existsSync as F,mkdirSync as P,readFileSync as V,renameSync as j,writeFileSync as w}from"fs";import{homedir as I}from"os";import{dirname as N,join as U,resolve as b}from"path";var Q=new Map;async function B(q,z){let J=Q.get(q)??Promise.resolve(),$,K=new Promise((W)=>{$=W});Q.set(q,J.then(()=>K));try{return await J,await z()}finally{if($(),Q.get(q)===J.then(()=>K));queueMicrotask(()=>{let W=Q.get(q);if(!W)return;Promise.race([W,new Promise((D)=>{D(void 0)})]).then(()=>{if(Q.get(q)===W)Q.delete(q)})})}}var A="agents-registry";async function s(q){return B(A,q)}function T(){return b(process.env.VIBECONTROLS_HOME??U(I(),".boff","vibecontrols"))}var C=2,k="default";function M(){return U(T(),"agents.json")}function _(){let q=M();if(!F(q))return null;try{let z=JSON.parse(V(q,"utf8"));if(z&&typeof z==="object"&&!Array.isArray(z)&&"instances"in z)return z;return null}catch{return null}}function X(){let q=_();if(!q)return{schemaVersion:C,instances:[]};return q}function Y(q){let z=M();P(N(z),{recursive:!0});let J=`${z}.${process.pid}.tmp`,$={...q,schemaVersion:C};w(J,`${JSON.stringify($,null,2)}
3
3
  `,{encoding:"utf8",mode:384}),j(J,z)}function o(){return X().instances}function a(q){let z=X();Y({...z,instances:q})}function O(){try{let z=X().defaultProfile;if(z&&typeof z==="string"&&z.length>0)return z}catch{}return k}function n(q){if(!q||typeof q!=="string")throw Error("setDefaultProfile: name is required");let z=X();Y({...z,defaultProfile:q})}var R=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/,p=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;function G(q){if(!R.test(q))throw Error("Invalid VIBECONTROLS_PROFILE. Use 1-128 characters: letters, numbers, dot, underscore, or dash.");return q}function h(){let q=process.env.VIBECONTROLS_PROFILE;if(q)return G(q);let z=O();return G(z)}function zq(q){if(!p.test(q))throw Error("Agent name must use 1-64 characters: letters, numbers, dot, underscore, or dash.");return q}function Jq(q,z){let J=v(H(q),H(z));return J===""||!!J&&!J.startsWith("..")&&!S(J)}function L(){let q=x(),z=h();return Z(q,"agents",z)}function Qq(){return Z(x(),"agents")}function Wq(){return Z(L(),"agent-db")}function x(){return H(process.env.VIBECONTROLS_HOME??Z(u(),".boff","vibecontrols"))}var y="https://registry.npmjs.org/";function Zq(){if(process.env.VIBECONTROLS_REGISTRY)return process.env.VIBECONTROLS_REGISTRY;try{let q=Z(L(),"config.json");if(E(q)){let z=JSON.parse(m(q,"utf8"));if(z.registry)return z.registry}}catch{}return y}
4
- export{B as Qd,s as Rd,o as Sd,a as Td,O as Ud,n as Vd,G as Wd,h as Xd,zq as Yd,Jq as Zd,L as _d,Qq as $d,Wq as ae,x as be,Zq as ce};
4
+ export{B as Rd,s as Sd,o as Td,a as Ud,O as Vd,n as Wd,G as Xd,h as Yd,zq as Zd,Jq as _d,L as $d,Qq as ae,Wq as be,x as ce,Zq as de};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{va as D}from"./index-ssjmzqcz.js";import{Fa as U,Ha as M,Pa as R}from"./index-g3ap3xpr.js";import{Xa as I}from"./index-0ckffygp.js";import{Lc as b}from"./index-xjzmb1pn.js";import{Hd as x,Nd as u}from"./index-9bqd8veb.js";import{_d as V,ce as C}from"./index-0cn9bv8z.js";import{he as L}from"./index-yy1mm8zs.js";import{existsSync as g,readFileSync as E,unlinkSync as Wz,writeFileSync as A}from"fs";import{join as c}from"path";var l=".consent.json";function Oz(z){try{let J=E(q(z),"utf8"),G=JSON.parse(J);if(Array.isArray(G.abilities)&&G.abilities.length>0)return new Set(G.abilities)}catch{}return null}function Uz(z){try{let J=E(q(z),"utf8"),G=JSON.parse(J);if(Array.isArray(G.providers))return G.providers.filter((X)=>typeof X==="string")}catch{}return[]}function _z(z){let J=new Set;for(let G of z.split(",").map((X)=>X.trim()).filter(Boolean)){let X=R(G);if(X)J.add(X)}return[...J]}function q(z){return c(z,l)}function Nz(z,J){let G=J??new Set(U.filter((Q)=>Q.defaultSelected||Q.mandatory).map((Q)=>Q.key)),X=z.skipPluginInstall?[]:M(process.platform,G).filter((Q)=>!z.skipPlugins.includes(Q.packageName)&&!z.skipPlugins.includes(Q.pluginName)).map((Q)=>({packageName:Q.packageName,pluginName:Q.pluginName,reason:Q.description}));return{tools:[],plugins:X}}async function Fz(){let z=new Set(U.filter((G)=>G.defaultSelected||G.mandatory).map((G)=>G.key));for(let G of U)if(G.mandatory)z.add(G.key);if(!(Boolean(process.stdin.isTTY)&&process.env.VIBE_AUTO_ACCEPT!=="1"))return z;try{let{interactiveCheckboxes:G}=await import("./interactive-22ta89hc.js"),X=await G("Select the agent abilities to install",U.map((Q)=>({key:Q.key,label:Q.label,description:Q.description,mandatory:Q.mandatory})),z);if(X){for(let Q of U)if(Q.mandatory)X.add(Q.key);return X}return z}catch(G){process.stdout.write(`
2
+ import{va as D}from"./index-n6bdbgb9.js";import{Fa as U,Ha as M,Pa as R}from"./index-jdh30t6c.js";import{Xa as I}from"./index-0ckffygp.js";import{Mc as b}from"./index-b6x6a4xp.js";import{Id as x,Od as u}from"./index-js1xn4sq.js";import{$d as V,de as C}from"./index-a4854mwz.js";import{ie as L}from"./index-c7554sg7.js";import{existsSync as g,readFileSync as E,unlinkSync as Wz,writeFileSync as A}from"fs";import{join as c}from"path";var l=".consent.json";function Oz(z){try{let J=E(q(z),"utf8"),G=JSON.parse(J);if(Array.isArray(G.abilities)&&G.abilities.length>0)return new Set(G.abilities)}catch{}return null}function Uz(z){try{let J=E(q(z),"utf8"),G=JSON.parse(J);if(Array.isArray(G.providers))return G.providers.filter((X)=>typeof X==="string")}catch{}return[]}function _z(z){let J=new Set;for(let G of z.split(",").map((X)=>X.trim()).filter(Boolean)){let X=R(G);if(X)J.add(X)}return[...J]}function q(z){return c(z,l)}function Nz(z,J){let G=J??new Set(U.filter((Q)=>Q.defaultSelected||Q.mandatory).map((Q)=>Q.key)),X=z.skipPluginInstall?[]:M(process.platform,G).filter((Q)=>!z.skipPlugins.includes(Q.packageName)&&!z.skipPlugins.includes(Q.pluginName)).map((Q)=>({packageName:Q.packageName,pluginName:Q.pluginName,reason:Q.description}));return{tools:[],plugins:X}}async function Fz(){let z=new Set(U.filter((G)=>G.defaultSelected||G.mandatory).map((G)=>G.key));for(let G of U)if(G.mandatory)z.add(G.key);if(!(Boolean(process.stdin.isTTY)&&process.env.VIBE_AUTO_ACCEPT!=="1"))return z;try{let{interactiveCheckboxes:G}=await import("./interactive-qc1j66mq.js"),X=await G("Select the agent abilities to install",U.map((Q)=>({key:Q.key,label:Q.label,description:Q.description,mandatory:Q.mandatory})),z);if(X){for(let Q of U)if(Q.mandatory)X.add(Q.key);return X}return z}catch(G){process.stdout.write(`
3
3
  [vibe] Falling back to plain prompt \u2014 ${G instanceof Error?G.message:String(G)}
4
4
 
5
5
  `);let X=await d("Select the agent abilities to install",U.map((Q)=>({key:Q.key,label:Q.label,description:Q.description,mandatory:Q.mandatory})),z);if(X){for(let Q of U)if(Q.mandatory)X.add(Q.key);return X}return z}}async function d(z,J,G){let X=new Set(G);for(let Y of J)if(Y.mandatory)X.add(Y.key);let Q=()=>{process.stdout.write(`
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{Rc as M,nd as V}from"./index-g2raeeh4.js";import{Xd as H,be as G}from"./index-0cn9bv8z.js";import{existsSync as j,readFileSync as K}from"fs";import{join as z}from"path";var x="http://localhost:3005",_=new Set(["localhost","127.0.0.1","0.0.0.0","::1","[::1]"]);function N(I){return I.toLowerCase().replace(/^\[|\]$/g,"")}function O(I){try{let Q=new URL(I);return _.has(N(Q.hostname))}catch{return!1}}function B(I){let Q=new URL(I.trim());if(Q.protocol!=="http:"&&Q.protocol!=="https:")throw Error("Agent URL must use http or https");if(Q.username||Q.password)throw Error("Agent URL must not include credentials");let J=Q.toString().replace(/\/+$/,"");if(!O(J)&&process.env.VIBECONTROLS_ALLOW_REMOTE_AGENT_URL!=="1")throw Error("Refusing non-local agent URL. Set VIBECONTROLS_ALLOW_REMOTE_AGENT_URL=1 to target a remote/tunnel URL explicitly.");return J}function T(I){if(!Number.isInteger(I)||I<=0)return!1;try{return process.kill(I,0),!0}catch{return!1}}function D(){let I=z(G(),"agents.json");if(!j(I))return[];try{let Q=JSON.parse(K(I,"utf-8"));return(Array.isArray(Q)?Q:Q&&typeof Q==="object"&&Array.isArray(Q.instances)?Q.instances:[]).filter((W)=>!!W&&typeof W==="object"&&typeof W.name==="string"&&typeof W.port==="number")}catch{return[]}}function C(I){let J=D().find((W)=>W.name===I);if(!J||!J.port)return null;if(typeof J.pid==="number"&&!T(J.pid))return null;return{url:`http://localhost:${J.port}`,port:J.port}}function u(I){let Q=I?.agentUrl&&I.agentUrl!==x?I.agentUrl:void 0;if(Q)return B(Q);if(I?.profile){let J=C(I.profile);if(J)return J.url}if(process.env.AGENT_URL)return B(process.env.AGENT_URL);try{let J=S({}),W=C(J);if(W)return W.url}catch{}return B(x)}async function v(I){let Q=O(I);if(process.env.AGENT_API_KEY){if(Q||process.env.VIBECONTROLS_SEND_API_KEY_TO_REMOTE==="1")return process.env.AGENT_API_KEY;throw Error("Refusing to send AGENT_API_KEY to a non-local agent URL. Set VIBECONTROLS_SEND_API_KEY_TO_REMOTE=1 only if you trust the target.")}if(!Q)return;let J=await F(I);if(J)return J;let W=H(),X=await M(`${W}:static-api-key`);if(X)return X;return V()["static-api-key"]}async function F(I){try{let Q=encodeURIComponent(H()),J=new AbortController,W=setTimeout(()=>J.abort(),2000);try{let X=await fetch(`${I}/api/profiles/${Q}/agent/api-key`,{signal:J.signal});if(!X.ok)return;return(await X.json().catch(()=>null))?.apiKey||void 0}finally{clearTimeout(W)}}catch{return}}function S(I){if(I?.profile)return I.profile;if(process.env.VIBECONTROLS_PROFILE)return process.env.VIBECONTROLS_PROFILE;try{let Q=z(G(),"agents.json");if(j(Q)){let J=JSON.parse(K(Q,"utf-8")),W=J&&typeof J==="object"&&!Array.isArray(J)?J.defaultProfile:void 0;if(typeof W==="string"&&W.length>0)return W}}catch{}return"default"}async function q(I,Q,J={}){let W=await v(I),X={...J.body?{"Content-Type":"application/json"}:{},...W?{"x-agent-api-key":W}:{},...J.headers??{}},Y;try{Y=await fetch(`${I}${Q}`,{...J,headers:X})}catch(Z){let R=Z instanceof Error?Z.message:String(Z),k=/unable to connect|ECONNREFUSED|ENOTFOUND|EHOSTUNREACH|fetch failed/i.test(R);if(k&&O(I))throw Error(`Agent not reachable at ${I}. Is it running? Try 'vibe status' or 'vibe start'.`,{cause:Z});if(k)throw Error(`Agent not reachable at ${I}. ${R}`,{cause:Z});throw Z}let $=await Y.json().catch(()=>({}));return{ok:Y.ok,status:Y.status,data:$}}async function f(I,Q){let{ok:J,status:W,data:X}=await q(I,Q);if(!J){let Y=X?.error||X?.message||`Agent returned ${W}`;throw Error(String(Y))}return X}async function A(I,Q,J){let{ok:W,status:X,data:Y}=await q(I,Q,{method:"POST",body:J!=null?JSON.stringify(J):void 0});if(!W){let $=Y?.error||Y?.message||`Agent returned ${X}`;throw Error(String($))}return Y}async function m(I,Q,J){let{ok:W,status:X,data:Y}=await q(I,Q,{method:"PUT",body:J!=null?JSON.stringify(J):void 0});if(!W){let $=Y?.error||Y?.message||`Agent returned ${X}`;throw Error(String($))}return Y}async function h(I,Q){let{ok:J,status:W,data:X}=await q(I,Q,{method:"DELETE"});if(!J){let Y=X?.error||X?.message||`Agent returned ${W}`;throw Error(String(Y))}return X}
3
- export{O as Jc,u as Kc,v as Lc,S as Mc,f as Nc,A as Oc,m as Pc,h as Qc};
2
+ import{Sc as M,od as V}from"./index-h74va4wd.js";import{Yd as H,ce as G}from"./index-a4854mwz.js";import{existsSync as j,readFileSync as K}from"fs";import{join as z}from"path";var x="http://localhost:3005",_=new Set(["localhost","127.0.0.1","0.0.0.0","::1","[::1]"]);function N(I){return I.toLowerCase().replace(/^\[|\]$/g,"")}function O(I){try{let Q=new URL(I);return _.has(N(Q.hostname))}catch{return!1}}function B(I){let Q=new URL(I.trim());if(Q.protocol!=="http:"&&Q.protocol!=="https:")throw Error("Agent URL must use http or https");if(Q.username||Q.password)throw Error("Agent URL must not include credentials");let J=Q.toString().replace(/\/+$/,"");if(!O(J)&&process.env.VIBECONTROLS_ALLOW_REMOTE_AGENT_URL!=="1")throw Error("Refusing non-local agent URL. Set VIBECONTROLS_ALLOW_REMOTE_AGENT_URL=1 to target a remote/tunnel URL explicitly.");return J}function T(I){if(!Number.isInteger(I)||I<=0)return!1;try{return process.kill(I,0),!0}catch{return!1}}function D(){let I=z(G(),"agents.json");if(!j(I))return[];try{let Q=JSON.parse(K(I,"utf-8"));return(Array.isArray(Q)?Q:Q&&typeof Q==="object"&&Array.isArray(Q.instances)?Q.instances:[]).filter((W)=>!!W&&typeof W==="object"&&typeof W.name==="string"&&typeof W.port==="number")}catch{return[]}}function C(I){let J=D().find((W)=>W.name===I);if(!J||!J.port)return null;if(typeof J.pid==="number"&&!T(J.pid))return null;return{url:`http://localhost:${J.port}`,port:J.port}}function u(I){let Q=I?.agentUrl&&I.agentUrl!==x?I.agentUrl:void 0;if(Q)return B(Q);if(I?.profile){let J=C(I.profile);if(J)return J.url}if(process.env.AGENT_URL)return B(process.env.AGENT_URL);try{let J=S({}),W=C(J);if(W)return W.url}catch{}return B(x)}async function v(I){let Q=O(I);if(process.env.AGENT_API_KEY){if(Q||process.env.VIBECONTROLS_SEND_API_KEY_TO_REMOTE==="1")return process.env.AGENT_API_KEY;throw Error("Refusing to send AGENT_API_KEY to a non-local agent URL. Set VIBECONTROLS_SEND_API_KEY_TO_REMOTE=1 only if you trust the target.")}if(!Q)return;let J=await F(I);if(J)return J;let W=H(),X=await M(`${W}:static-api-key`);if(X)return X;return V()["static-api-key"]}async function F(I){try{let Q=encodeURIComponent(H()),J=new AbortController,W=setTimeout(()=>J.abort(),2000);try{let X=await fetch(`${I}/api/profiles/${Q}/agent/api-key`,{signal:J.signal});if(!X.ok)return;return(await X.json().catch(()=>null))?.apiKey||void 0}finally{clearTimeout(W)}}catch{return}}function S(I){if(I?.profile)return I.profile;if(process.env.VIBECONTROLS_PROFILE)return process.env.VIBECONTROLS_PROFILE;try{let Q=z(G(),"agents.json");if(j(Q)){let J=JSON.parse(K(Q,"utf-8")),W=J&&typeof J==="object"&&!Array.isArray(J)?J.defaultProfile:void 0;if(typeof W==="string"&&W.length>0)return W}}catch{}return"default"}async function q(I,Q,J={}){let W=await v(I),X={...J.body?{"Content-Type":"application/json"}:{},...W?{"x-agent-api-key":W}:{},...J.headers??{}},Y;try{Y=await fetch(`${I}${Q}`,{...J,headers:X})}catch(Z){let R=Z instanceof Error?Z.message:String(Z),k=/unable to connect|ECONNREFUSED|ENOTFOUND|EHOSTUNREACH|fetch failed/i.test(R);if(k&&O(I))throw Error(`Agent not reachable at ${I}. Is it running? Try 'vibe status' or 'vibe start'.`,{cause:Z});if(k)throw Error(`Agent not reachable at ${I}. ${R}`,{cause:Z});throw Z}let $=await Y.json().catch(()=>({}));return{ok:Y.ok,status:Y.status,data:$}}async function f(I,Q){let{ok:J,status:W,data:X}=await q(I,Q);if(!J){let Y=X?.error||X?.message||`Agent returned ${W}`;throw Error(String(Y))}return X}async function A(I,Q,J){let{ok:W,status:X,data:Y}=await q(I,Q,{method:"POST",body:J!=null?JSON.stringify(J):void 0});if(!W){let $=Y?.error||Y?.message||`Agent returned ${X}`;throw Error(String($))}return Y}async function m(I,Q,J){let{ok:W,status:X,data:Y}=await q(I,Q,{method:"PUT",body:J!=null?JSON.stringify(J):void 0});if(!W){let $=Y?.error||Y?.message||`Agent returned ${X}`;throw Error(String($))}return Y}async function h(I,Q){let{ok:J,status:W,data:X}=await q(I,Q,{method:"DELETE"});if(!J){let Y=X?.error||X?.message||`Agent returned ${W}`;throw Error(String(Y))}return X}
3
+ export{O as Kc,u as Lc,v as Mc,S as Nc,f as Oc,A as Pc,m as Qc,h as Rc};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
2
  var j=Object.create;var{getPrototypeOf:k,defineProperty:f,getOwnPropertyNames:l}=Object;var m=Object.prototype.hasOwnProperty;function n(a){return this[a]}var o,p,s=(a,b,c)=>{var g=a!=null&&typeof a==="object";if(g){var h=b?o??=new WeakMap:p??=new WeakMap,i=h.get(a);if(i)return i}c=a!=null?j(k(a)):{};let d=b||!a||!a.__esModule?f(c,"default",{value:a,enumerable:!0}):c;for(let e of l(a))if(!m.call(d,e))f(d,e,{get:n.bind(a,e),enumerable:!0});if(g)h.set(a,d);return d};var t=(a,b)=>()=>(b||a((b={exports:{}}).exports,b),b.exports);var q=(a)=>a;function r(a,b){this[a]=q.bind(null,b)}var u=(a,b)=>{for(var c in b)f(a,c,{get:b[c],enumerable:!0,configurable:!0,set:r.bind(b,c)})};var v=import.meta.require;
3
- export{s as ee,t as fe,u as ge,v as he};
3
+ export{s as fe,t as ge,u as he,v as ie};
@@ -1,4 +1,4 @@
1
1
  // @bun
2
- import{Nd as Q}from"./index-9bqd8veb.js";import{_d as K}from"./index-0cn9bv8z.js";import{existsSync as X,mkdirSync as C,readFileSync as G,renameSync as I,writeFileSync as M}from"fs";import{dirname as R,join as U}from"path";var V="prereqs-installed.json",W="prereqs-installed";function Y(q){return U(q??K(),V)}function Z(q){let v=Y(q);if(!X(v))return[];try{let z=JSON.parse(G(v,"utf8"));if(!Array.isArray(z))return[];return z.filter((B)=>!!B&&typeof B==="object"&&typeof B.name==="string"&&typeof B.pluginPackageName==="string")}catch(z){return Q().logger.warn(W,`Failed to read tracker at ${v}: ${z}`),[]}}function x(q,v){let z=Y(v),B=R(z);if(!X(B))C(B,{recursive:!0});let J=`${z}.${process.pid}.tmp`;M(J,`${JSON.stringify(q,null,2)}
2
+ import{Od as Q}from"./index-js1xn4sq.js";import{$d as K}from"./index-a4854mwz.js";import{existsSync as X,mkdirSync as C,readFileSync as G,renameSync as I,writeFileSync as M}from"fs";import{dirname as R,join as U}from"path";var V="prereqs-installed.json",W="prereqs-installed";function Y(q){return U(q??K(),V)}function Z(q){let v=Y(q);if(!X(v))return[];try{let z=JSON.parse(G(v,"utf8"));if(!Array.isArray(z))return[];return z.filter((B)=>!!B&&typeof B==="object"&&typeof B.name==="string"&&typeof B.pluginPackageName==="string")}catch(z){return Q().logger.warn(W,`Failed to read tracker at ${v}: ${z}`),[]}}function x(q,v){let z=Y(v),B=R(z);if(!X(B))C(B,{recursive:!0});let J=`${z}.${process.pid}.tmp`;M(J,`${JSON.stringify(q,null,2)}
3
3
  `,{encoding:"utf8",mode:384}),I(J,z)}function j(q,v){if(v.length===0)return;let B=Z().filter((H)=>!(H.pluginPackageName===q&&v.some((b)=>b.name===H.name))),J=new Date().toISOString(),$=v.map((H)=>({name:H.name,kind:H.kind,installedAt:J,pluginPackageName:q}));x([...B,...$])}function E(q){return Z(q)}
4
4
  export{j as K,E as L};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{E as A,G as N}from"./index-6jzsthh9.js";import{Tb as l,Ub as T}from"./index-04n4qgvd.js";import{ic as G,jc as D,kc as f}from"./index-5mw3eshk.js";import{Cc as y,pc as d,qc as r,rc as j,tc as J,uc as U,vc as w,xc as P,yc as v}from"./index-z5a4yxzz.js";import{Fc as E}from"./index-ef95xr4z.js";import{Kc as p,Mc as g,Nc as L,Oc as x,Pc as S,Qc as O}from"./index-xjzmb1pn.js";import"./index-g2raeeh4.js";import"./index-9bqd8veb.js";import"./index-0cn9bv8z.js";import"./index-jw1k4vbk.js";import"./index-yy1mm8zs.js";import{promises as R}from"fs";import C from"path";async function M(a){try{let n=await R.readdir(a);if(n.includes("package.json")){try{let i=JSON.parse(await R.readFile(C.join(a,"package.json"),"utf8")),o={...i.dependencies,...i.devDependencies};if(o.react||o["@types/react"])return"react";if(o.vue||o["@vue/cli"])return"vue";if(o.angular||o["@angular/core"])return"angular";if(o.next||o["@types/next"])return"nextjs";if(o.nuxt||o["@nuxt/core"])return"nuxtjs";if(o.svelte||o["@sveltejs/kit"])return"svelte";if(o.express||o.fastify||o.koa)return"nodejs-backend";if(o.electron)return"electron";if(o.vite)return"vite"}catch{}return"nodejs"}if(n.includes("setup.py")||n.includes("requirements.txt")||n.includes("pyproject.toml")||n.includes("Pipfile")){if(n.includes("manage.py"))return"django";if(n.includes("app.py"))return"flask";return"python"}if(n.includes("go.mod"))return"go";if(n.includes("Cargo.toml"))return"rust";if(n.includes("pom.xml"))return"maven";if(n.includes("build.gradle")||n.includes("build.gradle.kts"))return"gradle";if(n.includes("Gemfile"))return"ruby";if(n.includes("composer.json"))return"php";if(n.some((i)=>i.endsWith(".csproj")||i.endsWith(".sln")))return"dotnet";if(n.includes("CMakeLists.txt")||n.includes("Makefile"))return"cpp";if(n.includes("Package.swift"))return"swift";if(n.includes("pubspec.yaml"))return"flutter";if(n.some((i)=>i.endsWith(".tf")))return"terraform";if(n.includes("Dockerfile"))return"docker"}catch{}return}async function V(a){try{let n=["vite.config.ts","vite.config.js"];for(let i of n)try{let t=(await R.readFile(C.join(a,i),"utf-8")).match(/port:\s*(\d+)/);if(t)return parseInt(t[1],10)}catch{}}catch{}return}var Y=new Set([".git","node_modules","__pycache__",".venv","venv","dist","build"]),F=parseInt(process.env.VIBECONTROLS_GIT_SCAN_MAX_DEPTH??"8",10),z=parseInt(process.env.VIBECONTROLS_GIT_SCAN_MAX_DIRECTORIES??"5000",10);async function k(a,n,i,o={visited:0},t=0){let u=[];if(t>F||o.visited>=z)return u;o.visited+=1;try{let e=await N(a);if(e.some((c)=>c.name===".git"&&c.isDirectory())){if(u.push({path:a,name:C.basename(a),parentPath:i,isSubmodule:!!i,projectType:await M(a),vitePort:await V(a)}),!n)return u;i=a}for(let c of e)if(c.isDirectory()&&!c.isSymbolicLink()&&!Y.has(c.name)&&!c.name.startsWith(".")){let s=C.join(a,c.name),$=await k(s,n,i,o,t+1);u.push(...$)}}catch{}return u}function I(a){let{db:n}=a;return new T().get("/",async()=>{return{repositories:await n.getAllGitRepositories()}}).get("/:id",async({params:i,set:o})=>{let t=await n.getGitRepository(i.id);if(!t)return o.status=404,{error:"Repository not found"};return{repository:t}}).post("/scan",async({body:i,set:o})=>{try{let t=(await A(i.directory,{mustExist:!0})).path;if(!(await R.stat(t)).isDirectory())return o.status=400,{error:"Path is not a directory"};let e=await k(t,i.includeSubmodules??!0),m=[];for(let c of e){let s=await n.getGitRepositoryByPath(c.path);if(s)await n.updateGitRepository(s.id,c),m.push({...s,...c});else{let $=await n.createGitRepository({id:globalThis.crypto.randomUUID(),...c});m.push($)}}return{repositories:m,scannedPath:t,totalFound:m.length}}catch(t){return o.status=500,{error:"Failed to scan directory",details:String(t)}}},{body:l.Object({directory:l.String(),includeSubmodules:l.Optional(l.Boolean())})}).put("/:id",async({params:i,body:o,set:t})=>{if(!await n.getGitRepository(i.id))return t.status=404,{error:"Repository not found"};try{return await n.updateGitRepository(i.id,o),{success:!0}}catch(e){return t.status=500,{error:"Failed to update repository",details:String(e)}}},{body:l.Object({name:l.Optional(l.String()),projectType:l.Optional(l.String()),vitePort:l.Optional(l.Number())})}).delete("/:id",async({params:i,set:o})=>{if(!await n.getGitRepository(i.id))return o.status=404,{error:"Repository not found"};try{return await n.deleteGitRepository(i.id),{success:!0}}catch(u){return o.status=500,{error:"Failed to delete repository",details:String(u)}}}).post("/fix-hierarchy",async({set:i})=>{try{let o=await n.fixGitHierarchy(),t=await n.getAllGitRepositories();return{success:!0,fixed:o.fixed,total:t.length}}catch(o){return i.status=500,{error:"Failed to fix hierarchy",details:String(o)}}})}var h="http://localhost:3005";function q(a){let n=a.command("git").description("Manage git repositories");n.command("list").description("List discovered git repositories").option("--agent-url <url>","Agent URL",h).option("--json","Emit JSON").option("--plain","Force plain text output").action(async function(i){let o={...a.opts(),...i};try{let t=p(i),u=encodeURIComponent(g(o));await D({mode:G(o),fetchData:async()=>{return(await L(t,`/api/profiles/${u}/git`)).repositories||[]},plain:(e)=>{if(!e||e.length===0){J("No git repositories found.");return}U("Git Repositories"),P(e.map((m)=>({ID:y(m.id),Name:m.name||"-",Path:m.path||"-",Type:m.type||m.projectType||"-",Submodule:m.isSubmodule?"Yes":"No",Scanned:m.scannedAt?v(m.scannedAt):"-"})))},interactive:async(e)=>{if(!e||e.length===0){U("Git Repositories"),J("No git repositories found.");return}let m=e.map((c)=>({id:String(c.id),label:c.name||y(c.id),hint:c.type||c.projectType||"",detail:[`ID: ${c.id}`,`Name: ${c.name??"-"}`,`Path: ${c.path??"-"}`,`Type: ${c.type??c.projectType??"-"}`,`Submodule: ${c.isSubmodule?"Yes":"No"}`,`Scanned: ${c.scannedAt?v(c.scannedAt):"-"}`].join(`
2
+ import{E as A,G as N}from"./index-6jzsthh9.js";import{Ub as l,Vb as T}from"./index-pgew6sge.js";import{jc as G,kc as D,lc as f}from"./index-8nqp3a4d.js";import{Dc as y,qc as d,rc as r,sc as j,uc as J,vc as U,wc as w,yc as P,zc as v}from"./index-1mppacnx.js";import{Gc as E}from"./index-thammzct.js";import{Lc as p,Nc as g,Oc as L,Pc as x,Qc as S,Rc as O}from"./index-b6x6a4xp.js";import"./index-h74va4wd.js";import"./index-js1xn4sq.js";import"./index-a4854mwz.js";import"./index-4qq083yd.js";import"./index-c7554sg7.js";import{promises as R}from"fs";import C from"path";async function M(a){try{let n=await R.readdir(a);if(n.includes("package.json")){try{let i=JSON.parse(await R.readFile(C.join(a,"package.json"),"utf8")),o={...i.dependencies,...i.devDependencies};if(o.react||o["@types/react"])return"react";if(o.vue||o["@vue/cli"])return"vue";if(o.angular||o["@angular/core"])return"angular";if(o.next||o["@types/next"])return"nextjs";if(o.nuxt||o["@nuxt/core"])return"nuxtjs";if(o.svelte||o["@sveltejs/kit"])return"svelte";if(o.express||o.fastify||o.koa)return"nodejs-backend";if(o.electron)return"electron";if(o.vite)return"vite"}catch{}return"nodejs"}if(n.includes("setup.py")||n.includes("requirements.txt")||n.includes("pyproject.toml")||n.includes("Pipfile")){if(n.includes("manage.py"))return"django";if(n.includes("app.py"))return"flask";return"python"}if(n.includes("go.mod"))return"go";if(n.includes("Cargo.toml"))return"rust";if(n.includes("pom.xml"))return"maven";if(n.includes("build.gradle")||n.includes("build.gradle.kts"))return"gradle";if(n.includes("Gemfile"))return"ruby";if(n.includes("composer.json"))return"php";if(n.some((i)=>i.endsWith(".csproj")||i.endsWith(".sln")))return"dotnet";if(n.includes("CMakeLists.txt")||n.includes("Makefile"))return"cpp";if(n.includes("Package.swift"))return"swift";if(n.includes("pubspec.yaml"))return"flutter";if(n.some((i)=>i.endsWith(".tf")))return"terraform";if(n.includes("Dockerfile"))return"docker"}catch{}return}async function V(a){try{let n=["vite.config.ts","vite.config.js"];for(let i of n)try{let t=(await R.readFile(C.join(a,i),"utf-8")).match(/port:\s*(\d+)/);if(t)return parseInt(t[1],10)}catch{}}catch{}return}var Y=new Set([".git","node_modules","__pycache__",".venv","venv","dist","build"]),F=parseInt(process.env.VIBECONTROLS_GIT_SCAN_MAX_DEPTH??"8",10),z=parseInt(process.env.VIBECONTROLS_GIT_SCAN_MAX_DIRECTORIES??"5000",10);async function k(a,n,i,o={visited:0},t=0){let u=[];if(t>F||o.visited>=z)return u;o.visited+=1;try{let e=await N(a);if(e.some((c)=>c.name===".git"&&c.isDirectory())){if(u.push({path:a,name:C.basename(a),parentPath:i,isSubmodule:!!i,projectType:await M(a),vitePort:await V(a)}),!n)return u;i=a}for(let c of e)if(c.isDirectory()&&!c.isSymbolicLink()&&!Y.has(c.name)&&!c.name.startsWith(".")){let s=C.join(a,c.name),$=await k(s,n,i,o,t+1);u.push(...$)}}catch{}return u}function I(a){let{db:n}=a;return new T().get("/",async()=>{return{repositories:await n.getAllGitRepositories()}}).get("/:id",async({params:i,set:o})=>{let t=await n.getGitRepository(i.id);if(!t)return o.status=404,{error:"Repository not found"};return{repository:t}}).post("/scan",async({body:i,set:o})=>{try{let t=(await A(i.directory,{mustExist:!0})).path;if(!(await R.stat(t)).isDirectory())return o.status=400,{error:"Path is not a directory"};let e=await k(t,i.includeSubmodules??!0),m=[];for(let c of e){let s=await n.getGitRepositoryByPath(c.path);if(s)await n.updateGitRepository(s.id,c),m.push({...s,...c});else{let $=await n.createGitRepository({id:globalThis.crypto.randomUUID(),...c});m.push($)}}return{repositories:m,scannedPath:t,totalFound:m.length}}catch(t){return o.status=500,{error:"Failed to scan directory",details:String(t)}}},{body:l.Object({directory:l.String(),includeSubmodules:l.Optional(l.Boolean())})}).put("/:id",async({params:i,body:o,set:t})=>{if(!await n.getGitRepository(i.id))return t.status=404,{error:"Repository not found"};try{return await n.updateGitRepository(i.id,o),{success:!0}}catch(e){return t.status=500,{error:"Failed to update repository",details:String(e)}}},{body:l.Object({name:l.Optional(l.String()),projectType:l.Optional(l.String()),vitePort:l.Optional(l.Number())})}).delete("/:id",async({params:i,set:o})=>{if(!await n.getGitRepository(i.id))return o.status=404,{error:"Repository not found"};try{return await n.deleteGitRepository(i.id),{success:!0}}catch(u){return o.status=500,{error:"Failed to delete repository",details:String(u)}}}).post("/fix-hierarchy",async({set:i})=>{try{let o=await n.fixGitHierarchy(),t=await n.getAllGitRepositories();return{success:!0,fixed:o.fixed,total:t.length}}catch(o){return i.status=500,{error:"Failed to fix hierarchy",details:String(o)}}})}var h="http://localhost:3005";function q(a){let n=a.command("git").description("Manage git repositories");n.command("list").description("List discovered git repositories").option("--agent-url <url>","Agent URL",h).option("--json","Emit JSON").option("--plain","Force plain text output").action(async function(i){let o={...a.opts(),...i};try{let t=p(i),u=encodeURIComponent(g(o));await D({mode:G(o),fetchData:async()=>{return(await L(t,`/api/profiles/${u}/git`)).repositories||[]},plain:(e)=>{if(!e||e.length===0){J("No git repositories found.");return}U("Git Repositories"),P(e.map((m)=>({ID:y(m.id),Name:m.name||"-",Path:m.path||"-",Type:m.type||m.projectType||"-",Submodule:m.isSubmodule?"Yes":"No",Scanned:m.scannedAt?v(m.scannedAt):"-"})))},interactive:async(e)=>{if(!e||e.length===0){U("Git Repositories"),J("No git repositories found.");return}let m=e.map((c)=>({id:String(c.id),label:c.name||y(c.id),hint:c.type||c.projectType||"",detail:[`ID: ${c.id}`,`Name: ${c.name??"-"}`,`Path: ${c.path??"-"}`,`Type: ${c.type??c.projectType??"-"}`,`Submodule: ${c.isSubmodule?"Yes":"No"}`,`Scanned: ${c.scannedAt?v(c.scannedAt):"-"}`].join(`
3
3
  `)}));await E({title:`vibe git list \u2014 ${e.length} repo(s)`,rows:m})},json:(e)=>e.map((m)=>({id:m.id,name:m.name??null,path:m.path??null,type:m.type??m.projectType??null,isSubmodule:!!m.isSubmodule,scannedAt:m.scannedAt??null}))})}catch(t){d(r(t))}}),n.command("scan").description("Scan a directory for git repositories").requiredOption("--dir <directory>","Directory to scan").option("--depth <depth>","Scan depth","3").option("--agent-url <url>","Agent URL",h).option("--json","Emit JSON").action(async function(i){let o={...a.opts(),...i};try{let t=p(i),u=encodeURIComponent(g(o)),e=await x(t,`/api/profiles/${u}/git/scan`,{directory:i.dir,depth:parseInt(i.depth,10)});if(f(o,{ok:!0,found:e?.found??e?.repositories?.length??0}))return;if(j("Git scan completed."),e?.found!==void 0)w("Repositories found",e.found);if(e?.repositories)w("Repositories found",e.repositories.length)}catch(t){if(o.json){f(o,{ok:!1,error:r(t)});return}d(r(t))}}),n.command("update").description("Update a git repository entry").requiredOption("-i, --id <id>","Repository ID").option("--vite-port <port>","Vite dev server port").option("--project-type <type>","Project type").option("--agent-url <url>","Agent URL",h).option("--json","Emit JSON").action(async function(i){let o={...a.opts(),...i};try{let t=p(i),u=encodeURIComponent(g(o)),e={};if(i.vitePort)e.vitePort=parseInt(i.vitePort,10);if(i.projectType)e.projectType=i.projectType;if(await S(t,`/api/profiles/${u}/git/${i.id}`,e),f(o,{ok:!0,id:i.id}))return;j(`Repository ${y(i.id)} updated.`)}catch(t){if(o.json){f(o,{ok:!1,error:r(t)});return}d(r(t))}}),n.command("delete").description("Delete a git repository entry").requiredOption("-i, --id <id>","Repository ID").option("--agent-url <url>","Agent URL",h).option("--json","Emit JSON").action(async function(i){let o={...a.opts(),...i};try{let t=p(i),u=encodeURIComponent(g(o));if(await O(t,`/api/profiles/${u}/git/${i.id}`),f(o,{ok:!0,id:i.id}))return;j(`Repository ${y(i.id)} deleted.`)}catch(t){if(o.json){f(o,{ok:!1,error:r(t)});return}d(r(t))}}),n.command("fix-hierarchy").description("Fix repository parent-child hierarchy").option("--agent-url <url>","Agent URL",h).option("--json","Emit JSON").action(async function(i){let o={...a.opts(),...i};try{let t=p(i),u=encodeURIComponent(g(o)),e=await x(t,`/api/profiles/${u}/git/fix-hierarchy`,{});if(f(o,{ok:!0,fixed:e?.fixed??null}))return;if(j("Hierarchy fix completed."),e?.fixed!==void 0)w("Fixed",e.fixed)}catch(t){if(o.json){f(o,{ok:!1,error:r(t)});return}d(r(t))}})}function H(a,n){q(a)}function eo(a){return{name:"git",version:"2.2.0",description:"Git repository scanning, tracking, and hierarchy management",capabilities:{storage:"rw",subprocess:!0,audit:!0,telemetry:!0},tags:["backend","cli"],cliCommand:"git",apiPrefix:"/api/git",createRoutes:(n)=>I(n),onCliSetup:async(n,i)=>{H(n,i)}}}export{eo as createPlugin};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{fe as q,he as b}from"./index-yy1mm8zs.js";var z=q((f)=>{Object.defineProperty(f,"__esModule",{value:!0});f.execAsync=void 0;var v=b("child_process"),w=b("util");f.execAsync=w.promisify(v.exec)});
2
+ import{ge as q,ie as b}from"./index-c7554sg7.js";var z=q((f)=>{Object.defineProperty(f,"__esModule",{value:!0});f.execAsync=void 0;var v=b("child_process"),w=b("util");f.execAsync=w.promisify(v.exec)});
3
3
  export{z as f};
@@ -0,0 +1,26 @@
1
+ // @bun
2
+ import{o as F4,q as J4}from"./index-5wpck4aw.js";import{u as r4,v as U5,w as j5}from"./index-9f52em7g.js";import{E as K4}from"./index-6jzsthh9.js";import{$ as y4,Q as C5,aa as L2,ba as x0,ca as f4,da as u4,ea as i4,fa as b4,ha as E2,ia as l2,ja as o2,ka as I2}from"./index-atp2ayra.js";import{la as E5,qa as I5,sa as C0}from"./index-rw9x93zb.js";import{va as c2}from"./index-n6bdbgb9.js";import{wa as N5,xa as x5,ya as O5,za as M5}from"./index-wccxsz72.js";import{Aa as _5}from"./index-4wgjx8bf.js";import{Ja as T0,Wa as T5}from"./index-jdh30t6c.js";import{Xa as N2}from"./index-0ckffygp.js";import{ab as P2}from"./index-rc79x8fw.js";import{eb as $5,fb as W5,gb as z5,hb as H5,ib as G5,jb as Y2,kb as B5,lb as V5,mb as K5,nb as F5,pb as L5}from"./index-hvjqgb97.js";import{Ab as i0,Eb as M2,Fb as Y0,Gb as Z5,Hb as J5,Ib as j0,Jb as V2,Lb as m,Mb as l,Nb as d4,Ob as n4,Pb as X5,Qb as Y5,tb as l0,ub as v2,vb as d0,wb as X0,xb as n0,yb as R2}from"./index-rqq0k5fc.js";import{Ub as z,Vb as D}from"./index-pgew6sge.js";import{nd as e0,od as t,pd as p0,qd as b2,rd as h2}from"./index-h74va4wd.js";import{Ad as B2,Dd as i2,Id as g,Kd as M0,Ld as c,Md as s,Od as G,Pd as W0,wd as O0,xd as t4,yd as e4,zd as Q5}from"./index-js1xn4sq.js";import{$d as D2,Sd as r0,Td as H0,Vd as f2,Wd as t0,Yd as C2,Zd as d,be as T2,ce as F2,de as n2}from"./index-a4854mwz.js";import{fe as v0,ie as b}from"./index-c7554sg7.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],L=new D({name:"@elysiajs/cors",seed:$,aot:Z}),w=K?.some((N)=>N==="*"),E={};if(K){for(let N of K)if(typeof N==="string")E[N]=!0}let x=(N,T,O)=>{if(Array.isArray(N))return N.some((I)=>x(I,T,O));switch(typeof N){case"string":if(O in E)return!0;let I=O.indexOf("://");if(I!==-1)O=O.slice(I+3);return N===O;case"function":return N(T)===!0;case"object":if(N instanceof RegExp)return N.test(O)}return!1},V=(N,T)=>{if(Q===!0){N.headers.vary="*",N.headers["access-control-allow-origin"]=T.headers.get("Origin")||"*";return}if(w){N.headers.vary="*",N.headers["access-control-allow-origin"]="*";return}if(!K?.length)return;if(K.length){let O=T.headers.get("Origin")??"";for(let I=0;I<K.length;I++)if(x(K[I],T,O)===!0){N.headers.vary=Q?"Origin":"*",N.headers["access-control-allow-origin"]=O||"*";return}}N.headers.vary="Origin"},C=(N,T)=>{if(!T)return;if(Y===!0)return N.headers["access-control-allow-methods"]=T??"*";if(Y===!1||!Y?.length)return;if(Y==="*")return N.headers["access-control-allow-methods"]="*";if(!Array.isArray(Y))return N.headers["access-control-allow-methods"]=Y;N.headers["access-control-allow-methods"]=Y.join(", ")},q={};if(typeof J==="string")q["access-control-expose-headers"]=J;if(typeof X==="string")q["access-control-allow-headers"]=X;if(W===!0)q["access-control-allow-credentials"]="true";L.headers(q);function v({set:N,request:T,headers:O}){if(V(N,T),C(N,T.headers.get("access-control-request-method")),X===!0||J===!0){if(X===!0)N.headers["access-control-allow-headers"]=O["access-control-request-headers"];if(J===!0)N.headers["access-control-expose-headers"]=Object.keys(O).join(",")}if(H)N.headers["access-control-max-age"]=H.toString();return new Response(null,{status:204})}if(B)L.options("/",v).options("/*",v);return L.onRequest(function({set:T,request:O}){if(V(T,O),B&&O.method==="OPTIONS")return v({set:T,request:O,headers:R0?O.headers.toJSON():Object.fromEntries(O.headers.entries())});if(C(T,O.method),X===!0||J===!0){let I=A5(O.headers);if(X===!0)T.headers["access-control-allow-headers"]=I;if(J===!0)T.headers["access-control-expose-headers"]=I}})};var k5="/code-server";function k0($,Z,Q=R2){let Y=$.method.toUpperCase();if(Y!=="GET"&&Y!=="HEAD")return null;let X=new URL($.url),J=X.searchParams.get("vt");if(!J||!Q(J,k5,"GET"))return null;X.searchParams.delete("vt");let W=new Headers($.headers);return W.set("x-agent-api-key",Z()),new Request(`${X.origin}${X.pathname}${X.search}`,{method:$.method,headers:W})}import{createHash as D0}from"crypto";var W2="idempotency",S5=300000,S0=1e4,A2=new Map;function D5($,Z,Q,Y){return D0("sha256").update(`${$}|${Z}|${Q}|${Y}`).digest("hex")}async function h5($,Z){let Q=await $.getPluginState(W2,Z);if(!Q)return null;try{let Y=JSON.parse(Q);if(Y.expiresAt<Date.now())return await $.deletePluginState(W2,Z),null;return Y}catch{return null}}async function v5($,Z,Q){await $.setPluginState(W2,Z,JSON.stringify(Q))}async function P5($){let Z=await $.getAllPluginState(W2),Q=Date.now(),Y=0,X=[];for(let J of Z)try{if(JSON.parse(J.value).expiresAt<Q)await $.deletePluginState(W2,J.key),Y+=1;else X.push({key:J.key,updatedAt:J.updatedAt})}catch{await $.deletePluginState(W2,J.key),Y+=1}if(X.length>S0){X.sort((W,H)=>(W.updatedAt??"").localeCompare(H.updatedAt??""));let J=X.slice(0,X.length-S0);for(let W of J)await $.deletePluginState(W2,W.key),Y+=1}if(Y>0)G().logger.info("idempotency",`Swept ${Y} expired/over-cap entries`)}var Q0=null,f5=600000;function b5($){if(Q0)return;Q0=setInterval(()=>{let Z=$.getDb();if(!Z)return;P5(Z).catch((Q)=>{G().logger.warn("idempotency","Sweep failed",{error:String(Q)})})},f5),Q0.unref?.()}function h0($){return b5($),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 C=await Z.clone().text();H=D0("sha256").update(C).digest("hex")}catch{}let B=D5(Z.method,Q,J,H),K=await h5(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 L=A2.get(B);if(L){let V=await L.catch(()=>null);if(V){Y.status=V.status;let C=Y.headers??={};C["Content-Type"]=V.contentType,C["X-Idempotency-Replay"]="true",X.__idemReplay=V.body;try{return JSON.parse(V.body)}catch{return V.body}}}let w,E,x=new Promise((V,C)=>{w=V,E=C});A2.set(B,x),X.__idemKey=B,X.__idemResolve=w,X.__idemReject=E}).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),L=Q.headers?.["Content-Type"]??"application/json",w={status:H,body:B,contentType:L,expiresAt:Date.now()+S5},E=H>=200&&H<300;try{if(W&&E)await v5(W,X,w)}catch(x){G().logger.warn("idempotency","Failed to persist response",{error:String(x)})}finally{try{J?.(E?w:null)}catch{}A2.delete(X)}}).onError(({store:Z})=>{let Q=Z.__idemKey;if(!Q)return;let Y=Z.__idemReject;try{Y?.(Error("idempotency: handler errored"))}catch{}A2.delete(Q)}).as("global")}import u from"os";import{readFileSync as t5}from"fs";import{join as e5}from"path";var P0={enabled:!1,async scrape(){return`# vibecontrols agent metrics disabled (OTel SDK not initialised)
3
+ `},recordHttpRequest(){},setPluginsLoaded(){}},J2=null,k2=null;async function S2($){if(J2)return J2;if(k2)return k2;return k2=(async()=>{try{let{MeterProvider:Z}=await import("./index-p23tet7a.js").then((m)=>v0(m.default,1)),{PrometheusExporter:Q,PrometheusSerializer:Y}=await import("./index-qwtspxw8.js").then((m)=>v0(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 L=H.createCounter("vibecontrols_http_requests_total",{description:"Total HTTP requests handled by the agent, labelled by method, route, status."}),w={};H.createObservableGauge("vibecontrols_plugins_loaded",{description:"Plugins loaded by the agent, broken down by status (loaded, failed, etc.)."}).addCallback((V)=>{for(let[C,q]of Object.entries(w))V.observe(q,{status:C})}),B.record(1,{version:$?.version??"unknown",profile:$?.profile??"default"});let x={enabled:!0,async scrape(){let V=await X.collect();if(!V.resourceMetrics)return"";return J.serialize(V.resourceMetrics)},recordHttpRequest(V,C,q){L.add(1,{method:V,route:C,status:String(q)})},setPluginsLoaded(V){w={...V}}};return J2=x,G().logger.info("metrics","OTel Prometheus registry initialised"),x}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)}),J2=P0,P0}})(),k2}function f0($,Z,Q){if(!J2)return;J2.recordHttpRequest($,Z,Q)}function b0($){if(!J2)return;J2.setPluginsLoaded($)}var c5=new Set(["127.0.0.1","::1"]),c0=!1;function y5(){if(c0)return;if(process.env.METRICS_ANONYMOUS_LOCALHOST==="true")c0=!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 u5($){let Z=$.replace(/^\[|\]$/g,"");if(Z.startsWith("::ffff:"))return Z.slice(7);return Z}function $0($,Z){let Q=Z?.requestIP($)?.address;if(!Q)return!1;return c5.has(u5(Q))}function y0(){return y5(),new D({name:"routes/metrics"}).get("/metrics",async({request:$,server:Z,set:Q})=>{if(!(process.env.METRICS_ANONYMOUS_LOCALHOST==="true"&&$0($,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 S2()).scrape();return Q.headers["content-type"]="text/plain; version=0.0.4; charset=utf-8",J})}import{randomBytes as m5,timingSafeEqual as g5}from"crypto";import{chmodSync as p5,existsSync as u0,mkdirSync as l5,readFileSync as d5,unlinkSync as n5,writeFileSync as i5}from"fs";import{dirname as o5,join as a5}from"path";var z2=null;function m0(){return a5(D2(),"pairing-token")}function s5(){return m5(32).toString("base64url")}function r5($,Z){let Q=Buffer.from($),Y=Buffer.from(Z);if(Q.length!==Y.length)return!1;try{return g5(Q,Y)}catch{return!1}}function H6(){if(z2)return z2;let $=m0();try{if(u0($)){let Q=d5($,"utf8").trim();if(Q.length>=32)return z2=Q,Q}}catch{}let Z=s5();try{l5(o5($),{recursive:!0}),i5($,Z,{encoding:"utf8"});try{p5($,384)}catch{}}catch(Q){}return z2=Z,Z}function Z0($){if(!$)return!1;if(!z2)return!1;return r5($,z2)}function g0(){z2=null;try{let $=m0();if(u0($))n5($)}catch{}}function J0($){return $["x-pairing-token"]??$["X-Pairing-Token"]??null}function QQ(){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 $Q(){for(let $ of["..","../.."])try{let Z=e5(import.meta.dir,$,"package.json"),Y=JSON.parse(t5(Z,"utf8")).version;if(Y)return Y}catch{}return"0.0.0"}async function ZQ($){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 o0({serviceRegistry:$,runFinalize:Z,getDb:Q}){let Y=$Q(),X=QQ();return new D({prefix:"/api/agent"}).get("/identity",()=>({hostname:u.hostname(),platform:u.platform(),architecture:u.arch(),agentVersion:Y,agentInstanceId:p0()})).get("/version",()=>({version:Y,runtime:"bun",runtimeVersion:typeof Bun<"u"?Bun.version:"unknown"})).get("/api-key",({request:J,server:W,set:H})=>{if(!$0(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:V2()}}).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 d0({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 v2(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(!l0(H))return W.status=400,{error:"BadRequest",message:"invalid sid"};let K=`/terminal/${H}`,L=n0(B,K);if(!L.ok)return G().logger.warn("terminal-exchange","iframe token rejected",{sid:H,reason:L.reason}),W.status=401,{error:"Unauthorized",message:"invalid iframe token",code:L.reason==="expired"?"expired":L.reason==="replayed"?"replayed":"invalid"};let w=i0(H,600),E=`vt_term_${H}`;return W.headers["set-cookie"]=`${E}=${w.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(!M2(H))return W.status=400,{error:"BadRequest",message:"invalid plugin name"};let K=`/ui/${H}`;if(!X0(B,K))return W.status=401,{error:"Unauthorized",message:"invalid iframe token"};let L=Y0(H,600),w=`vt_ui_${H}`;return W.headers["set-cookie"]=`${w}=${L.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(!M2(H))return W.status=400,{error:"BadRequest",message:"invalid plugin name"};if(![`/api/plugins/${H}/ui`,`/${H}`].find((x)=>X0(B,x)))return W.status=401,{error:"Unauthorized",message:"invalid iframe token"};let w=Y0(H,600),E=`vt_ui_${H}`;return W.headers["set-cookie"]=`${E}=${w.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=Z0(J0(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 L=await ZQ($);if(!L)return{tunnelUrl:null,message:"No tunnel provider registered"};return{tunnelUrl:L}}).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:P2(g.getConfig()),state:G().getBootState()})).post("/retry-config",async({set:J})=>{let{getFinalizeRetryHandle:W}=await import("./finalize-retry-handle-registry-xnm9kxry.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 N=m(K);if(!l(N))return H.status=401,{success:!1,state:B,error:"Unauthorized: API key required to reconfigure"}}else{let N=m(K),T=J0(K),O=l(N),I=Z0(T);if(!O&&!I)return H.status=401,{success:!1,state:B,error:"Unauthorized: provide x-agent-api-key OR x-pairing-token for bootstrap"}}let{clientId:L,clientSecret:w,workspaceId:E,globalGatewayUrl:x,workspaceGatewayUrl:V}=J;if(!L||!w||!E||!x||!V)return H.status=400,{success:!1,state:G().getBootState(),error:"clientId, clientSecret, workspaceId, globalGatewayUrl, and workspaceGatewayUrl are required"};let C,q;try{C=B2(x,"globalGatewayUrl"),q=B2(V,"workspaceGatewayUrl")}catch(N){return H.status=400,{success:!1,state:G().getBootState(),error:N instanceof Error?N.message:String(N)}}{let N=c()??G();try{await h2({clientId:L,clientSecret:w,workspaceId:E,ownerUserId:J.ownerUserId,organizationId:J.organizationId,globalGatewayUrl:C,workspaceGatewayUrl:q,agentRecordId:J.agentRecordId,scopes:J.scopes,...J.storageAdapter?{storageAdapter:J.storageAdapter}:{},...J.storageOptions?{storageOptions:J.storageOptions}:{},...J.dbPath?{dbPath:J.dbPath}:{}},{dir:N.dataDir,scope:N.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 v=G().getBootState();if(v==="ready"){let N=Q();if(N){if(await N.setConfig("gateway-auth:clientId",L),await N.setConfig("gateway-auth:clientSecret",w),await N.setConfig("gateway-auth:workspaceId",E),J.organizationId)await N.setConfig("gateway-auth:organizationId",J.organizationId);if(await N.setConfig("gateway-auth:globalGatewayUrl",C),await N.setConfig("gateway-auth:workspaceGatewayUrl",q),J.agentRecordId)await N.setConfig("gateway-auth:agentRecordId",J.agentRecordId)}g.configure({globalGatewayUrl:C,workspaceGatewayUrl:q,clientId:L,clientSecret:w,workspaceId:E,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:v,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)"),g0(),Z({clientId:L,clientSecret:w,workspaceId:E,organizationId:J.organizationId,globalGatewayUrl:C,workspaceGatewayUrl:q},{agentRecordId:J.agentRecordId,scopes:J.scopes}).catch((N)=>{G().logger.error("preconfig","Background finalize threw",{error:N instanceof Error?N.message:String(N)})}),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 $2,mkdirSync as JQ,rmSync as a0,readdirSync as Q4}from"fs";import{join as y2}from"path";function a($){return y2(F2(),"agents",d($))}function XQ(){let $=y2(F2(),"agents");if(!$2($))return[];return Q4($,{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 $4($){return y2(F2(),"agents",d($))}function z0($){return t({dir:$4($)})}function s0($,Z){return b2(Z,{dir:$4($),scope:d($)})}function K2($){let Z=f2(),Q=H0().find((J)=>J.name===$),Y=s.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($2(a($)))X.config=P2(z0($));return X}function Z4($={}){let Z=$.serviceManagerFactory?$.serviceManagerFactory():new c2;return new D({prefix:"/api/profiles"}).get("/",()=>{let Q=XQ(),Y=f2(),X=new Set(Q);return X.add(Y),[...X].sort().map((J)=>K2(J))}).post("/",async({body:Q,set:Y})=>{try{let X=d(Q.name),J=a(X);if($2(J))return Y.status=409,{error:"exists",message:`Profile '${X}' already exists.`};let W;if(Q.copyFrom){let H=d(Q.copyFrom);if(!$2(a(H)))return Y.status=400,{error:"copy-source-missing",message:`Profile '${H}' does not exist.`};W=z0(H),delete W["static-api-key"],delete W.agentRecordId,delete W.apiKeys}else W=e0();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;JQ(J,{recursive:!0}),s0(X,W);try{W0(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:T2(),profile:X};await Z.startDaemon(H)}return Y.status=201,K2(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(!$2(a(X)))return Y.status=404,{error:"not-found",message:`No profile '${X}'.`};return K2(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(!$2(a(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={...z0(J),...Y};return s0(J,B),K2(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===f2())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=$2(a(W)),K=s.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 s.destroy(W)}catch(L){G().logger.warn("profile-mgmt",`In-process detach failed for '${W}'`,{error:String(L)})}if(B)if(Y?.keepConfig)for(let L of Q4(a(W))){if(L==="config.json")continue;a0(y2(a(W),L),{recursive:!0,force:!0})}else a0(a(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(!$2(a(X)))return Y.status=404,{error:"not-found",message:`No profile '${X}'.`};return await r0(()=>t0(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(!$2(a(J)))return X.status=404,{error:"not-found",message:`No profile '${J}'.`};try{W0(J)}catch(H){G().logger.warn("profile-mgmt",`In-process attach failed for '${J}'`,{error:String(H)})}if(!H0().some((H)=>H.name===J&&H.status==="running")){let H={name:J,port:Y?.port??0,daemon:!0,dbPath:T2(),profile:J};await Z.startDaemon(H)}return K2(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 s.destroy(X)}catch(J){G().logger.warn("profile-mgmt",`In-process detach failed for '${X}'`,{error:String(J)})}return K2(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 YQ(){let $=process.memoryUsage(),Z=process.resourceUsage(),Q=Z.userCPUTime/1000,Y=Z.systemCPUTime/1000,X=Q+Y,J=s.list().map((W)=>{let H;try{H=J4(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 X4(){return new D({prefix:"/api/profile-stats"}).get("/",()=>YQ())}function u2($,Z){return Promise.race([$,new Promise((Q,Y)=>setTimeout(()=>Y(Error(`timeout after ${Z}ms`)),Z))])}function WQ($){let Z=$ instanceof Error?$.message:String($);return/ENOENT/.test(Z)||/no such file or directory/i.test(Z)}async function Y4($){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 u2($.setConfig(Q,Y),2000),await u2($.getConfig(Q),2000)!==Y)throw Error("round-trip mismatch");try{await u2($.deleteConfig(Q),500)}catch{}}async function zQ($,Z){if(!$)return{ok:!1,message:"database not opened"};let Q=performance.now();try{return await Y4($),{ok:!0,durationMs:performance.now()-Q}}catch(Y){if(Z&&WQ(Y))try{return(await import("fs")).mkdirSync(Z,{recursive:!0}),await Y4($),{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 W4($,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 HQ($){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 u2(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 z4($){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 zQ(Z.getDb?.()??null,Z.getDbPath?.()??null),W.tunnel=W4(Z.serviceRegistry,"tunnel"),W.session=W4(Z.serviceRegistry,"session");try{let{gatewayClient:V}=await import("./gateway-client-9kwnmk89.js");if(!V.isConfigured())W.registration={ok:!0,message:"not configured"};else{let C=Z.getDb?.()??null;if(C?await C.getConfig("gateway-auth:agentRecordId"):null)W.registration={ok:!0};else{let v=G().getDegradedReasons().some((N)=>N.plugin==="agent-registration");W.registration=v?{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 HQ(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():[],L=G().name,w={};for(let V of s.list())w[V.name]={bootState:V.getBootState(),ok:V.getBootState()==="ready",degradedReasons:V.getDegradedReasons()};let E=G().getLastFinalizeError(),x={status:B?"ok":"degraded",lifecycleState:X,bootState:J,daemon:{profile:L,bootState:J,ok:J==="ready"},profiles:w,components:W,plugins:H,degradedReasons:K,lastFinalizeError:E,timestamp:new Date().toISOString()};if(!B)G().logger.warn("health","Readiness probe failed",{components:W,plugins:H,bootState:J});return x})}var m2=0,H4=0;function G4(){return new D({name:"inflight-tracker"}).onRequest(()=>{m2+=1}).onAfterResponse(()=>{m2=Math.max(0,m2-1),H4+=1})}function B4(){return new D({prefix:"/api/stats"}).get("/inflight",()=>({inflight:Math.max(0,m2-1),totalServed:H4}))}var G0=Object.freeze(["code","code-insiders","codium","cursor","idea","pycharm","webstorm","goland","phpstorm","rubymine","clion","rider","zed","subl","vim","nvim","emacs","neovide","fleet","helix"]),GQ=new Set(G0),BQ=new Set(["--new-window","-n","--reuse-window","-r","--wait","-w","--add","--goto"]);function V4($){try{return Bun.which($)??null}catch{return null}}function L4(){return new D({prefix:"/api/editor"}).get("/allowlist",()=>({commands:[...G0]})).get("/detect",async()=>{let $=G0.map((Y)=>[Y,V4(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(!GQ.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"||!BQ.has(H))return Z.status=400,{ok:!1,error:`Argument '${H}' is not in the flag allowlist`};let J;try{J=(await K4(Y,{mustExist:!0})).realPath}catch(H){return Z.status=400,{ok:!1,error:`Invalid path: ${H instanceof Error?H.message:String(H)}`}}let W=V4(Q);if(!W)return Z.status=404,{ok:!1,error:`'${Q}' is not installed or not on PATH on this agent`};try{let H=F4({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 N4=Symbol.for("@vibecontrols/plugin-sdk:contextProviders@1");function VQ(){let $=globalThis,Z=$[N4];if(Z)return Z;let Q=new Map;return $[N4]=Q,Q}function B0(){return Array.from(VQ().values())}function _4(){return(c()??G()).dataDir}function n(){let $=t({dir:_4()});return{ownerUserId:$.ownerUserId,workspaceId:$.workspaceId}}function g2(){return t({dir:_4()}).agentRecordId}function U4($){if(!$)return null;try{return new URL($).host}catch{return null}}async function j4($,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=U4($.getTunnelHost?.()??null),W;try{W=L2(n()).map((H)=>({id:H.id,label:H.label,host:U4(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:C2(),tunnelHost:J},plugins:{count:Y.length,items:Y},mesh:{peerCount:W.length,peers:W}}}}var KQ=2000,x4=1000;async function FQ($,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 O4($,Z){let Q=performance.now(),Y=$.timeoutMs??KQ;try{let X=await FQ($.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 V0{deps;inflight=new Map;constructor($){this.deps=$}async aggregate($){let Z=`${$.profile}::${$.vibeId??""}`,Q=this.inflight.get(Z);if(Q&&Date.now()-Q.ts<x4)return Q.promise;let Y=this.doAggregate($).finally(()=>{setTimeout(()=>{let X=this.inflight.get(Z);if(X&&X.promise===Y)this.inflight.delete(Z)},x4).unref?.()});return this.inflight.set(Z,{ts:Date.now(),promise:Y}),Y}async selfContext($){return j4(this.deps,$)}async pluginContext($,Z){let Q=B0().find((Y)=>Y.name===$);if(!Q)return null;return O4(Q,Z)}async pluginsContext($){let Z=B0(),Q=await Promise.allSettled(Z.map((X)=>O4(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 p2($){let Z=$.vibeId;if(typeof Z!=="string")return;let Q=Z.trim();return Q.length>0&&Q.length<=128?Q:void 0}function M4($){let Z=new V0($);return new D({prefix:"/api/agent/context"}).get("/",async({params:Q,query:Y})=>{let X=Q?.profile??"default",J=p2(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=p2(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=p2(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=p2(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 Z2="autoupdate",LQ=86400000,T4=300000,NQ=900000,S={timer:null,running:!1,profile:"default",lastCheckAt:null,lastCheck:null,lastUpdateAt:null,lastUpdate:null,startedAt:null};function K0(){let $=(process.env.VIBE_AUTOUPDATE??"").trim().toLowerCase();return $==="0"||$==="false"||$==="off"||$==="no"}function E4(){if(K0())return!1;try{return t().autoUpdate!==!1}catch{return!0}}function F0(){let $=Number(process.env.VIBE_AUTOUPDATE_INTERVAL_MS);if(Number.isFinite($)&&$>0)return Math.max(NQ,$);return LQ}async function L0($){let Z=G().logger;if(S.running)return{check:S.lastCheck??await C4(),update:null};S.running=!0;try{let Q=await E2();if(S.lastCheck=Q,S.lastCheckAt=new Date().toISOString(),Q.error)Z.debug(Z2,`Update check failed: ${Q.error}`);else if(Q.hasUpdate)Z.info(Z2,`New agent version available: ${Q.current} \u2192 ${Q.latest}`);let Y=$?.force||E4();if(!Q.hasUpdate||!Y)return{check:Q,update:null};Z.info(Z2,`Auto-updating ${Q.current} \u2192 ${Q.latest} (idle-gated restart)\u2026`);let X=await l2({restart:!0,name:S.profile,onLog:(J)=>Z.info(Z2,J)});if(S.lastUpdate=X,S.lastUpdateAt=new Date().toISOString(),X.ok&&X.updated)Z.info(Z2,`Auto-update applied: now ${X.current} (restart: ${X.restart}).`);else if(!X.ok)Z.warn(Z2,`Auto-update failed: ${X.error}`);return{check:Q,update:X}}catch(Q){return Z.warn(Z2,`Auto-update tick threw: ${Q instanceof Error?Q.message:String(Q)}`),{check:await C4(),update:null}}finally{S.running=!1}}async function C4(){if(S.lastCheck)return S.lastCheck;let $=await E2();return S.lastCheck=$,S.lastCheckAt=new Date().toISOString(),$}function I4($){if(S.timer)clearTimeout(S.timer);S.timer=setTimeout(()=>{L0().finally(()=>{if(S.startedAt)I4(F0())})},$),S.timer.unref?.()}function _Q($){let Z=G().logger;if(S.profile=$?.profile||process.env.VIBECONTROLS_PROFILE||"default",S.startedAt=new Date().toISOString(),K0()){Z.info(Z2,"Autoupdate disabled via VIBE_AUTOUPDATE \u2014 not scheduling.");return}Z.info(Z2,`Autoupdate scheduled (first check in ${Math.round(T4/60000)}m, then every ${Math.round(F0()/3600000)}h).`),I4(T4)}function L7(){if(S.timer)clearTimeout(S.timer),S.timer=null;S.startedAt=null}function w4($){if(b2({autoUpdate:$}),$&&!S.startedAt)_Q({profile:S.profile})}function N0(){let $=!0;try{$=t().autoUpdate!==!1}catch{}return{enabled:E4(),envKillSwitch:K0(),configEnabled:$,scheduled:!!S.startedAt,intervalMs:F0(),profile:S.profile,startedAt:S.startedAt,lastCheckAt:S.lastCheckAt,lastCheck:S.lastCheck,lastUpdateAt:S.lastUpdateAt,lastUpdate:S.lastUpdate}}import{existsSync as q4}from"fs";import{join as R4}from"path";var UQ=600000,_0=1e6;function jQ(){let $=N2(),Z=$.which("bun")??`bun${$.executableSuffix}`,Q=R4(import.meta.dir,"cli.js");if(q4(Q))return{runner:Z,prefix:[Q]};let Y=R4(import.meta.dir,"..","cli.ts");if(q4(Y))return{runner:Z,prefix:[Y]};let X=$.which("vibe");if(X)return{runner:X,prefix:[]};return null}function A4($){if($.length<=_0)return $;return $.slice(0,_0)+`
4
+ \u2026[output truncated at ${_0} bytes]`}async function d2($,Z={}){let Q=jQ();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??UQ,H=!1,B=setTimeout(()=>{H=!0;try{J.kill()}catch{}},W),[K,L,w]=await Promise.all([new Response(J.stdout).text(),new Response(J.stderr).text(),J.exited]);return clearTimeout(B),{ok:!H&&w===0,exitCode:w,stdout:A4(K),stderr:A4(L),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 k4(){let{Command:$}=await import("./esm-6f3dfn6v.js"),{registerCoreCommands:Z}=await import("./register-core-qcj272qh.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 xQ}from"child_process";import{writeFileSync as OQ,mkdirSync as MQ}from"fs";import{tmpdir as TQ}from"os";import{join as S4}from"path";var CQ="@vibecontrols/agent";function D4($){let Z=N2(),Q=Z.which("bun")??`bun${Z.executableSuffix}`,Y=Z.which("npm")??`npm${Z.executableSuffix}`,X=n2(),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(CQ)};
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=S4(TQ(),"vibecontrols-uninstall");MQ(B,{recursive:!0});let K=S4(B,`reaper-${process.pid}.ts`);return OQ(K,H,{encoding:"utf8"}),xQ(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 EQ=new Set(["db","plugins-registry","logs","binaries","subprocs"]);async function h4($){let Z=await k4();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 v4($={}){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 l2({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 w4(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 L0({force:Z?.force===!0})}},{body:z.Optional(z.Object({force:z.Optional(z.Boolean())}))}).get("/api/agent/commands",async()=>{let Z=await h4($);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 h4($),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 d2(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&&!EQ.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 d2(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 d2(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 c2;for(let B of await H.listInstances())if(typeof B.pid==="number"&&B.pid>0)J.add(B.pid)}catch{}let W=D4({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 AQ,readFileSync as kQ}from"fs";import{join as SQ}from"path";var IQ=`mutation AddAgentFromTunnel($input: AddAgentFromTunnelInput!) {
22
+ addVibecontrolsAgentFromTunnel(input: $input) { agent { id name } clientId success error }
23
+ }`,wQ=`mutation ReportAgentMeshLink($input: ReportAgentMeshLinkInput!) {
24
+ reportAgentMeshLink(input: $input) { id }
25
+ }`,P4="VIBE_BOOTSTRAP_JSON=";function qQ($){for(let Y of $.split(/\r?\n/)){let X=Y.indexOf(P4);if(X>=0)try{return JSON.parse(Y.slice(X+P4.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 c4($,Z){let Q=(L,w,E)=>Z?.({step:L,status:w,message:E}),Y=b4($.permissions??["tunnel:read","session:list","plugin:list","diagnostics:read","mesh:forward"]);if(!Y.includes("mesh:forward"))Y.push("mesh:forward");let X=(L)=>({ok:!1,peerId:"",agentRecordId:null,tunnelUrl:null,permissions:Y,error:L}),J;try{J=o2($.target,{identityFile:$.identityFile})}catch(L){return X(L instanceof Error?L.message:String(L))}let W=$.label??J.id,H=Y.join(","),B,K='export PATH="$HOME/.bun/bin:$PATH"; ';try{if(!$.connectExisting){Q("probe","running");let O=await J.probe();if(Q("probe","completed",`os=${O.os??"?"} arch=${O.arch??"?"}`),!O.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 i=await J.run(["sh","-c",`curl -fsSL https://bun.sh/install | bash && echo 'export PATH="$HOME/.bun/bin:$PATH"' >> ~/.bashrc`],{timeoutMs:300000});if(i.code!==0)return Q("install-bun","failed",i.stderr.slice(0,400)),X("Bun auto-install failed.");let _2=await J.run(["sh","-c","$HOME/.bun/bin/bun --version 2>/dev/null"],{timeoutMs:1e4});if(_2.code===0&&_2.stdout.trim())O.bun="$HOME/.bun/bin/bun",Q("install-bun","completed",_2.stdout.trim());else return X("Bun installed but the binary is not reachable.")}Q("install-agent","running");let I=$.version??"latest",h=$.registry??"https://registry.npmjs.org/";if(!/^[A-Za-z0-9._@/^~>=<-]+$/.test(I))return Q("install-agent","failed","invalid version"),X(`Invalid agent version: ${I}`);if(!/^https?:\/\/[A-Za-z0-9._~:/?#@!$&'()*+,;=%-]+$/.test(h))return Q("install-agent","failed","invalid registry"),X(`Invalid registry URL: ${h}`);let y=await J.run(["sh","-c",`${K}npm_config_registry="${h}" bun install -g @vibecontrols/agent@${I} --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 i of $.installPlugins)await J.run(["sh","-c",`${K}vibe plugin install ${i}`],{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 L=$.expiresIn?` --expires-in ${$.expiresIn}`:"",w=W.replace(/'/g,""),E=null;for(let O=0;O<15;O++){let I=`${K}vibe peer-bootstrap --json --emit-default-key --label '${w}' --scope ${H}${L} 2>/dev/null`,h=await J.run(["sh","-c",I],{timeoutMs:15000});if(h.code===0){let y=qQ(h.stdout);if(y&&typeof y.apiKey==="string"){E=y;break}}await new Promise((y)=>setTimeout(y,2000))}if(!E)return Q("bootstrap","failed","could not obtain peer-bootstrap bundle"),X("Remote peer-bootstrap did not return a credential bundle.");Q("bootstrap","completed");let x=n(),V=String(E.id),C=String(E.apiKey),q=i2(typeof E.tunnelUrl==="string"?E.tunnelUrl:null),v=typeof E.agentRecordId==="string"?E.agentRecordId:null;if($.onboardBackend!==!1&&g.isConfigured()&&q&&typeof E.fullDefaultApiKey==="string"){Q("onboard","running");let O=5,I="no agent returned";for(let h=0;h<O;h++){try{let i=(await g.workspaceQuery(IQ,{input:{tunnelUrl:q,apiKey:E.fullDefaultApiKey,name:W}})).data?.addVibecontrolsAgentFromTunnel;if(i?.agent?.id){v=i.agent.id,I="",Q("onboard","completed",`agent ${v}`);break}I=i?.error??"no agent returned"}catch(r){I=r instanceof Error?r.message:String(r)}if(!/unreachable|resolve hostname|timed out|timeout|ECONN|network|to fetch|50[234]/i.test(I)||h===O-1)break;Q("onboard","running",`retry ${h+1}/${O-1}: ${I.slice(0,80)}`),await new Promise((r)=>setTimeout(r,3000*(h+1)))}if(I)Q("onboard","failed",I)}else Q("onboard","skipped");Q("store-creds","running"),f4({id:V,label:W,tunnelUrl:q??"",apiKey:C,permissions:Y,addedAt:new Date().toISOString(),agentRecordId:v??void 0,workspaceId:(typeof E.workspaceId==="string"?E.workspaceId:x.workspaceId)??void 0,fingerprint:V,ownerUserId:x.ownerUserId,sshTarget:J.mode==="ssh"?$.target:void 0,sshIdentityFile:$.identityFile}),Q("store-creds","completed");let N=g2();if($.onboardBackend!==!1&&g.isConfigured()&&N&&v){Q("report-link","running");try{await g.workspaceQuery(wQ,{input:{sourceAgentRecordId:N,destinationAgentRecordId:v,label:W}}),Q("report-link","completed")}catch(O){Q("report-link","failed",O instanceof Error?O.message:String(O))}}else Q("report-link","skipped");let T=await I2(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:v,tunnelUrl:q,permissions:Y,remoteVersion:B}}catch(L){return X(L instanceof Error?L.message:String(L))}finally{await J.close().catch(()=>{})}}var U0='export PATH="$HOME/.bun/bin:$PATH"; ';function RQ($){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 m4($,Z){let Q=(J,W,H)=>Z?.({step:J,status:W,message:H}),Y=y4($);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=o2(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",`${U0}vibe restart 2>/dev/null || ${U0}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",`${U0}vibe url --json 2>/dev/null`],{timeoutMs:15000});if(B.code===0){let K=RQ(B.stdout),L=i2(K);if(L){W=L;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),u4($,{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 DQ=Number(process.env.VIBECONTROLS_MESH_MAX_HOPS||"8");function g4(){return(c()??G()).name}function hQ(){return(c()??G()).dataDir}function p4(){try{let Z=SQ(hQ(),"runtime.json");if(AQ(Z)){let Q=JSON.parse(kQ(Z,"utf8"));if(Q.port&&Number.isInteger(Q.port))return Q.port}}catch{}let $=Number(process.env.PORT);return Number.isInteger($)&&$>0?$:3005}function vQ($){let Z={};return $.headers.forEach((Q,Y)=>{Z[Y]=Q}),Z}function X2($,Z){let Q=m(vQ($));return n4(d4(Q),Z)}function PQ($){let{apiKey:Z,...Q}=$;return{...Q,apiKey:"[REDACTED]"}}function l4($){return typeof $==="string"&&$.startsWith("/api/")&&!$.includes("..")&&!$.includes("//")}var a2=new Map;function fQ(){let $=Date.now()-3600000;for(let[Z,Q]of a2)if(Q.completedAt&&Date.parse(Q.completedAt)<$)a2.delete(Z)}function o4(){return new D({name:"agent-mesh"}).get("/api/mesh/peers",({request:$,set:Z})=>{if(!X2($,["read"]))return Z.status=403,{error:"forbidden"};return{peers:L2(n()).map(PQ)}}).delete("/api/mesh/peers/:id",({request:$,set:Z,params:Q})=>{if(!X2($,["mutate"]))return Z.status=403,{error:"forbidden"};if(!L2(n()).some((X)=>X.id===Q.id))return Z.status=404,{error:"not found"};return{ok:i4(Q.id)}}).post("/api/mesh/peers/:id/call",async({request:$,set:Z,params:Q,body:Y})=>{if(!X2($,["mesh:forward"]))return Z.status=403,{error:"forbidden"};let X=Y;if(!l4(X.path))return Z.status=400,{error:"invalid path"};if(!L2(n()).find((H)=>H.id===Q.id))return Z.status=404,{error:"not found"};let W=await I2(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(!X2($,["mesh:forward"]))return Z.status=403,{error:"forbidden"};let Y=Q;if(!Y.request||!l4(Y.request.path))return Z.status=400,{error:"invalid request"};let X=(Y._hopCount??0)+1;if(X>DQ)return Z.status=422,{error:"hop limit exceeded"};let J=n(),W=g2(),H=Y.hops??[];if(H.length===0){G().audit.emit("mesh","forward.terminal",{path:Y.request.path,method:Y.request.method??"GET"});let x=(Y.request.method??"GET").toUpperCase();try{let V=await fetch(`http://127.0.0.1:${p4()}${Y.request.path}`,{method:x,headers:{"x-agent-api-key":await j0(),...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)}),C=await V.text().catch(()=>""),q=null;try{q=C?JSON.parse(C):null}catch{q=null}return{ok:V.ok,status:V.status,data:q,text:C||null,error:V.ok?null:C||`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 L=x0(B,J);if(!L)return Z.status=403,{error:"next hop not in authorized boundary"};if(!L.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 w=encodeURIComponent(g4()),E=await I2(L.id,`/api/profiles/${w}/mesh/forward`,{method:"POST",operation:"mesh-forward",timeoutMs:60000,body:{hops:H.slice(1),request:Y.request,_traversed:[...K,W??"self"],_hopCount:X}});if(!E.ok)return Z.status=502,{ok:!1,status:E.status,error:E.error,failedAtHop:B};return E.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(!X2($,["admin"]))return Z.status=403,{error:"forbidden"};fQ();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 a2.set(J,W),c4({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),Y2("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(),Y2(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(),Y2("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(!X2($,["read"]))return Z.status=403,{error:"forbidden"};let Y=a2.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(!X2($,["admin"]))return Z.status=403,{error:"forbidden"};let Y=Q,X=x0(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 m4(X.id,(W)=>Y2("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(!X2($,["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(g4()),W=await j0(),H=`http://127.0.0.1:${p4()}`,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 L=await fetch(`${H}/api/profiles/${J}/sessions/${encodeURIComponent(X)}/terminal`,{method:"POST",headers:{"x-agent-api-key":W},signal:AbortSignal.timeout(20000)});if(!L.ok)return Z.status=502,{error:`terminal start returned ${L.status}: ${await L.text().catch(()=>"")}`};let w=v2(`/terminal/${X}`,600);return G().audit.emit("mesh","session.created",{sessionId:X,kind:Y.kind??"TERMINAL"}),{connectionId:X,sessionId:X,capabilityToken:w.token,expiresAt:w.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 bQ=["/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 cQ($){return bQ.some((Z)=>$.startsWith(Z))}var yQ=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function uQ($){return $.split("/").map((Z)=>{if(!Z)return Z;if(/^\d+$/.test(Z))return":id";if(yQ.test(Z))return":id";if(Z.length>=24&&/^[A-Za-z0-9_-]+$/.test(Z))return":id";return Z}).join("/")}async function a8($){let{port:Z,host:Q,dbPath:Y,logLevel:X,corsOrigin:J}=$,W=Y??T2();try{(await import("fs")).mkdirSync(W,{recursive:!0})}catch(F){throw G().logger.error("app","Failed to create dbPath dir at boot",{dbPath:W,error:String(F)}),Error(`Cannot create dbPath ${W}: ${F instanceof Error?F.message:String(F)}`,{cause:F})}if(X)G().logger.setLevel(X);(async()=>{let{logShipper:F}=await import("./log-shipper-hjnn1d5p.js");F.init()})(),(async()=>{let F=await s4();await S2({version:F,profile:C2()})})();try{let{checkDependencies:F}=await import("./bootstrap.service-vg72w8pa.js"),M=F(),U=M.filter((R)=>R.required&&!R.installed),A=M.filter((R)=>!R.required&&!R.installed);if(U.length>0)G().logger.error("app",`Missing required system deps: ${U.map((R)=>R.name).join(", ")}. Run \`vibe setup\` to install.`);if(A.length>0)G().logger.warn("app",`Missing optional system deps: ${A.map((R)=>R.name).join(", ")}. Some plugins may fail their prereqs check.`)}catch(F){G().logger.warn("app","Boot-time dependency check failed",{error:String(F)})}try{G().audit.runRetention()}catch(F){G().logger.warn("app","Audit-log retention sweep failed",{error:String(F)})}let H=new N5;I5(H,{port:Z});let B="GET, POST, PUT, PATCH, DELETE, OPTIONS",K="Content-Type, x-agent-api-key, Authorization, x-requested-with",L=Array.isArray(J)?J:(J??"").split(",").map((F)=>F.trim()).filter(Boolean),w=new Set(["https://vibecontrols.com","https://app.vibecontrols.com","https://alphaapp.vibecontrols.com","https://burdenoff.com","https://app.burdenoff.com","https://alphaapp.burdenoff.com"]),E=(F)=>{try{let M=new URL(F);if(L.includes(F))return!0;if(L.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")||w.has(M.origin)}catch{return!1}},x=null,V=null,C=null,q=null,v=!1,N=()=>[],T=null,O=null,I=null,h=5000,y=async(F,M)=>{let U=Date.now();try{await Promise.race([Promise.resolve(M()),new Promise((A,R)=>setTimeout(()=>R(Error(`shutdown phase ${F} exceeded ${h}ms`)),h))]),G().logger.info("app",`shutdown.phase ${F} complete`,{ms:Date.now()-U})}catch(A){G().logger.warn("app",`shutdown.phase ${F} failed`,{error:String(A),ms:Date.now()-U})}},r=async(F)=>{if(v)return;if(v=!0,G().logger.info("app","Agent shutdown starting",{reason:F?.reason??"shutdown"}),await y("plugins",async()=>{if(V)await V.dispatchServerStop(F)}),await y("bootstrap-tunnel",()=>C0()),await y("tracked-subprocesses",async()=>{let{killAllTracked:M}=await import("./subprocess-1nna3d3x.js");await M()}),F?.reason!=="reload")await y("db-close",async()=>{if(x)await x.close()});await y("http-listener",async()=>{try{await Promise.resolve(e.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()},i=async(F,M)=>{if(G().getBootState()==="ready")return{ok:!0};if(I)return I;return I=(async()=>{G().setBootState("initializing");try{let U={...F,globalGatewayUrl:B2(F.globalGatewayUrl,"globalGatewayUrl"),workspaceGatewayUrl:B2(F.workspaceGatewayUrl,"workspaceGatewayUrl")},A=await U5(U),R=W,P=t({dir:G().dataDir}),p=P.storageAdapter??process.env.VIBE_STORAGE_ADAPTER??void 0,o=P.storageOptions,Q2=(_)=>{let j=(_ instanceof Error?_.message:String(_)).toLowerCase(),k=_&&typeof _==="object"&&"code"in _?String(_.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"},U2=()=>r4({dbPath:R,encryptionKey:A,adapterName:p,adapterOptions:o});try{x=await U2()}catch(_){let j=_,k=Q2(_),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:_ instanceof Error?_.message:String(_),path:R});for(let O2 of q2){await new Promise((f)=>setTimeout(f,O2));try{x=await U2(),j=null;break}catch(f){if(j=f,k=Q2(f),G().logger.warn("app",`Storage open retry failed (${k}) after ${O2}ms`,{error:f instanceof Error?f.message:String(f)}),k==="corruption")break}}}if(!x&&j){if(k!=="corruption"){let f=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:f,path:R}),G().recordDegradedReason("storage",f);try{throw j}catch(G2){throw Error(`Storage open failed (${k}); agent is degraded: ${f}`,{cause:G2})}}let O2=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:O2,path:R});try{let f=await import("fs");if(f.existsSync(R)){let G2=new Date().toISOString().replace(/[:.]/g,"-"),q0=`${R}.broken-${G2}`;f.renameSync(R,q0),G().logger.warn("app",`Quarantined corrupt storage to ${q0} \u2014 fresh DB will be created`,{originalError:O2})}x=await U2()}catch(f){let G2=f instanceof Error?f.message:String(f);throw G().recordDegradedReason("storage",G2),Error(`Storage open failed twice (quarantine path); agent is degraded: ${G2}`,{cause:f})}}}if(!x)throw Error("Internal error: storage open recovery exited without an open database and without throwing");if(await h2({clientId:U.clientId,clientSecret:U.clientSecret,workspaceId:U.workspaceId,organizationId:U.organizationId,globalGatewayUrl:U.globalGatewayUrl,workspaceGatewayUrl:U.workspaceGatewayUrl,agentRecordId:M?.agentRecordId,scopes:M?.scopes},{dir:G().dataDir,scope:G().name}),await x.setConfig("gateway-auth:clientId",U.clientId),await x.setConfig("gateway-auth:clientSecret",U.clientSecret),await x.setConfig("gateway-auth:globalGatewayUrl",U.globalGatewayUrl),await x.setConfig("gateway-auth:workspaceGatewayUrl",U.workspaceGatewayUrl),await x.setConfig("gateway-auth:workspaceId",U.workspaceId),U.organizationId)await x.setConfig("gateway-auth:organizationId",U.organizationId);if(M?.agentRecordId)await x.setConfig("gateway-auth:agentRecordId",M.agentRecordId);H.db=x,await H.hydrateDefaultsFromDb(),V=new T5(x),await V.loadCorePlugins();try{await V.loadAll()}catch(_){G().logger.warn("app","Failed to load some external plugins",{error:String(_)})}let j2=C5(F2())??void 0,x2=process.env.VIBE_SKIP_AUTO_INSTALL==="1"||await x.getConfig("plugins:auto-install-disabled");if(x2!=="true"&&x2!==!0)try{let _=await V.ensureDefaultPlugins((j)=>G().logger.info("app",`[auto-install] ${j}`),[],j2);if(_.length>0)G().logger.info("app",`Auto-installed ${_.length} default plugin(s): ${_.map((j)=>j.packageName).join(", ")}`)}catch(_){G().logger.warn("app","Failed to auto-install default plugins",{error:String(_)})}G().logger.info("app",`Plugins loaded: ${V.getPluginDetails().length} total (${V.getPluginDetails().filter((_)=>_.isCore).length} core)`);try{let _=V.getPluginDetails(),j={loaded:_.filter((k)=>k.loaded).length,failed:_.filter((k)=>!k.loaded).length};b0(j)}catch{}let r2={async get(_,j){return await x.getPluginState(_,j)??null},async set(_,j,k){await x.setPluginState(_,j,k)},async delete(_,j){return x.deletePluginState(_,j)},async list(_){return await x.getAllPluginState(_)},async deleteAll(_){return x.deleteAllPluginState(_)}},w2=await s4();C={storage:r2,logger:G().logger,serviceRegistry:H,getProvider:(_)=>H.getProvider(_),getAgentBaseUrl:()=>process.env.AGENT_URL||`http://localhost:${Z}`,getAgentVersion:()=>w2,validateApiKey:(_)=>l(_),setCodeServerSessionValidator:(_)=>{w5=_},broadcast:Y2,workspaceQuery:async(_,j)=>g.workspaceQuery(_,j),isGatewayConfigured:()=>g.isConfigured(),getAgentRecordId:async()=>await x.getConfig("gateway-auth:agentRecordId")??null,getWorkspaceId:async()=>await x.getConfig("gateway-auth:workspaceId")??null,getConfig:async(_)=>await x.getConfig(_)??void 0,getPluginRegistry:()=>n2(),getDataDir:()=>D2(),cliContributors:new _5,audit:{emit:(_,j)=>G().audit.emit("agent",_,j??{})},telemetry:{emit:(_,j)=>{import("./telemetry-8jfdyt51.js").then(({telemetryService:k})=>k.emit(_,j??{})).catch(()=>{})}},os:N2(),iframeBridge:M5()},g.configure({globalGatewayUrl:U.globalGatewayUrl,workspaceGatewayUrl:U.workspaceGatewayUrl,clientId:U.clientId,clientSecret:U.clientSecret,workspaceId:U.workspaceId,organizationId:U.organizationId});let H2={db:x,serviceRegistry:H,pluginManager:V,broadcast:Y2,hostServices:C};H2.app=e;let w0=!1,t2=()=>{let{routes:_,getPublicPaths:j,mountPlugin:k}=$5(V,H2);if(H2.mountPlugin=k,N=j,X5(),T=_,O=O5(V),V&&w0&&C)V.dispatchServerStart(T,C).catch((q2)=>G().logger.warn("app","Re-dispatch of onServerStart after plugin reload failed",{error:String(q2)}));w0=!0};H2.rebuildPluginSurfaces=t2,t2(),q=new j5(H,V,x,e,C,r),H.registerService("agent","lifecycle",q),G().attachServices({db:x,serviceRegistry:H,pluginManager:V,lifecycle:q,hostServices:C}),F5(G(),{rebuildPluginSurfaces:t2,mountPlugin:H2.mountPlugin});try{await G().keyVault.bindApiKey(V2())}catch(_){G().logger.warn("app","Failed to bind api key into daemon keyVault",{error:String(_)})}let e2=[];try{let{failures:_}=await V.dispatchServerStart(T,C);for(let j of _)if(T0(j.plugin)||(j.packageName?T0(j.packageName):!1))e2.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(_){G().logger.warn("app","Error during plugin onServerStart dispatch",{error:String(_)})}try{await V.dispatchServerReady(e,C)}catch(_){G().logger.warn("app","Error during plugin onServerReady dispatch",{error:String(_)})}if(G().clearFinalizeError(),e2.length>0)G().setBootState("degraded"),G().logger.error("app","Agent finalized but degraded \u2014 critical plugins failed",{failures:e2.map((_)=>`${_.plugin}: ${_.error}`)});else G().setBootState("ready"),G().logger.info("app","Agent finalized \u2014 state=ready"),G().audit.emit("agent","gateway-auth.configured",{workspaceId:U.workspaceId,organizationId:U.organizationId,agentRecordId:M?.agentRecordId});return(async()=>{try{if(await V.provisionDefaultPrereqs(e,C,H2.mountPlugin,j2),G().logger.info("app","Default provider prerequisites provisioned"),(H.listProvidersForType("tunnel")??[]).some((k)=>k.pluginName!=="bootstrap")){let{tryHandoverBootstrapTunnel:k}=await import("./tunnel-bootstrap-5wgt9a1h.js");if(!k())C0();H.unregisterProvider("tunnel","bootstrap"),G().logger.info("app","Bootstrap tunnel handed over to the real tunnel provider")}}catch(_){G().logger.warn("app","Plugin prerequisite provisioning failed",{error:String(_)})}})(),{ok:!0}}catch(U){G().setBootState("awaiting-config");let A=U instanceof Error?U.message:String(U);if(G().recordFinalizeError(A),G().logger.error("app","Finalize failed",{error:A}),process.env.VIBE_STRICT_KEY_FETCH==="1")G().logger.error("app","VIBE_STRICT_KEY_FETCH=1 \u2192 aborting daemon (strict mode)",{error:A}),setTimeout(()=>process.exit(1),50);return{ok:!1,error:A}}finally{I=null}})(),I},_2=A0({origin:(F)=>{let M=F.headers.get("origin");return!!M&&E(M)},credentials:!0,allowedHeaders:K.split(",").map((F)=>F.trim()),methods:B.split(",").map((F)=>F.trim()),exposeHeaders:["content-type","content-length"],maxAge:86400,preflight:!0}),q5=10485760,E0=process.env.VIBECONTROLS_MAX_BODY_BYTES,s2=E0?Number.parseInt(E0,10):NaN,R5=Number.isFinite(s2)&&s2>0?s2:q5,I0={current:null},e=new D({serve:{maxRequestBodySize:R5}}).onRequest(({request:F,set:M})=>{let A=t4(F.headers)??O0();e4({requestId:A,startedAt:new Date().toISOString()});let R=M.headers??={};R["X-Request-Id"]=A}).onRequest(({request:F})=>{try{let M=new URL(F.url).pathname,A=/^\/api\/profiles\/([^/]+)(?:\/|$)/.exec(M)?.[1],R=A?s.get(A):null;M0(R??G())}catch{M0(G())}}).onRequest(({request:F,set:M})=>{let U=new URL(F.url).pathname;if(!U.startsWith("/api/"))return;if(U==="/api/profiles"||U.startsWith("/api/profiles/"))return;if(U==="/api/profile-stats"||U.startsWith("/api/profile-stats/"))return;let A=new URL(F.url);A.pathname=`/api/profiles/default${U.slice(4)}`;try{F.headers.set("x-vc-profile-rewrite","1"),F.headers.set("x-vc-profile-rewrite-target",A.pathname)}catch{}return}).derive(()=>({requestId:Q5()??O0()})).use(_2).use(W5()).use(Y5(()=>N())).use(h0({getDb:()=>c()?.db??x})).onBeforeHandle(({request:F,set:M})=>{let U=G().getBootState();if(U==="ready")return;let A=new URL(F.url).pathname;if(cQ(A))return;return M.status=503,{error:"Agent not yet configured",message:"Agent is in '"+U+"' state. POST credentials to /api/agent/gateway-auth to finalize.",state:U}}).onAfterHandle(({request:F,set:M})=>{let U=new URL(F.url).pathname,A=U==="/health"||U.startsWith("/api/logs/stream")||U.startsWith("/ui/")||U==="/ws/events"||U==="/api/sessions/health-check"||U.startsWith("/terminal/"),R=typeof M.status==="number"?M.status:200,P=A?"debug":R>=400?"warn":"info";G().logger[P]("http",`${F.method} ${U} \u2192 ${R}`,{method:F.method,path:U,statusCode:R});try{f0(F.method,uQ(U),R)}catch{}}).use(z4({serviceRegistry:H,getDb:()=>c()?.db??x,getDbPath:()=>W,getPluginManager:()=>c()?.pluginManager??V})).use(y0()).use(o0({serviceRegistry:H,runFinalize:(F,M)=>i(F,M),getDb:()=>c()?.db??x})).use(G4()).use(B4()).use(v4({getPluginManager:()=>c()?.pluginManager??V})).use(o4()).use(L4()).use(M4({getPluginManager:()=>c()?.pluginManager??V,getTunnelHost:()=>E5()?.url??null})).use(Z4()).use(X4()).use(B5()).use(K5()).use(V5(H)).ws("/code-server/*",gQ(Z)).all("/api/profiles/:name/*",async({params:F,request:M,set:U})=>{let A=M.method!=="GET"&&M.method!=="HEAD",R=A?await M.arrayBuffer():void 0,P=await L5(F.name,M,R);if(P&&P.status!==404)return P;let p=C2(),o=F.name;if(o!==p)return U.status=404,{error:"profile-mismatch",running:p,requested:o,hint:"This daemon serves a different profile. Call GET /api/profiles to discover the right tunnel."};let Q2=new URL(M.url),U2=Q2.pathname.replace(/^\/api\/profiles\/[^/]+/,"/api"),j2=new Headers(M.headers);j2.set("x-vc-profile-rewrite","1");let x2={method:M.method,headers:j2};if(A&&R!==void 0)x2.body=R;let r2=new Request(`${Q2.origin}${U2}${Q2.search}`,x2),w2=I0.current;if(!w2)return new Response(JSON.stringify({error:"agent-not-ready"}),{status:503,headers:{"content-type":"application/json"}});return w2.handle(r2)}).all("/api/*",async({request:F})=>{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(F.url),U=/^\/api\/plugins\/([a-z0-9-]{1,64})\/ui(?:\/.*)?$/.exec(M.pathname);if(U&&F.method==="GET"){let A=U[1];if(M2(A)){let R=M.pathname.slice(`/api/plugins/${A}/ui`.length),P=R===""||R==="/",o=F.headers.get("sec-fetch-mode")==="navigate";if(P||o){let Q2=J5(F,A);if(!Q2||!Z5(Q2,A))return new Response(x5(A,"/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(F)}).all("/ui/*",async({request:F})=>{if(G().getBootState()!=="ready"||!O)return new Response("Plugin UI not yet available",{status:503});return O.handle(F)}).all("/code-server/*",async({request:F})=>{if(G().getBootState()!=="ready"||!T)return new Response("code-server not yet available",{status:503});let M=k0(F,V2);return T.handle(M??F)}).all("/plan/*",async({request:F})=>{if(G().getBootState()!=="ready"||!T)return new Response("plan provider not yet available",{status:503});return T.handle(F)});return I0.current=e,{app:e,async start(){e.listen({port:Z,hostname:Q}),G().logger.info("app",`Agent server listening on ${Q}:${Z}`);try{let F=(process.env.VIBECONTROLS_PROFILES??"").split(",").map((P)=>P.trim()).filter(Boolean),M=G().name,{getOrCreateProfile:U}=await import("./daemon-profile-gwdcqx0q.js"),{attachSecondaryProfile:A}=await import("./secondary-profile-attach-xkvpmm08.js"),R=process.env.VIBE_STRICT_KEY_FETCH==="1";for(let P of F){if(P===M)continue;try{let p=U(P),o=await A(p);if(o.ok)G().logger.info("app",`Secondary profile '${P}' attached (db+services online)`);else if(R)throw Error(`attachServices for secondary profile '${P}' failed: ${o.error}`);else p.recordDegradedReason("attach",o.error??"unknown"),G().logger.warn("app",`Secondary profile '${P}' is degraded (no creds / attach failed)`,{error:o.error})}catch(p){if(R)throw G().logger.error("app",`--strict-key-fetch: secondary profile '${P}' attach failed; aborting`,{error:String(p)}),setTimeout(()=>process.exit(1),50),p;G().logger.warn("app",`Failed to attach secondary profile '${P}'`,{error:String(p)})}}}catch{}return e},stop:r,finalize:i,getState:()=>G().getBootState(),getLifecycle:()=>c()?.lifecycle??q,getDb:()=>c()?.db??x,getServiceRegistry:()=>c()?.serviceRegistry??H,getPluginManager:()=>c()?.pluginManager??V,getHostServices:()=>c()?.hostServices??C}}var w5=null;function mQ($,Z){if(!$)return null;let Q=$.match(new RegExp(`(?:^|;\\s*)${Z}=([^;]*)`));return Q?Q[1]:null}var a4=z5(H5);function gQ($){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&&R2(B,"/code-server","GET"),L,w=l(H);if(!w&&!K){let C=W.headers?.cookie??W.request?.headers.get("cookie")??null,q=mQ(C,"__vibe_cs_session");if(!q||!w5?.(q)){J.close(1008,"Unauthorized");return}L=`session:${q}`}else if(w)L="api-key";else L="vt";let E=J.remoteAddress??null,x=G5(E,W.headers);if(!a4.accept(L,x,J)){G().logger.warn("code-server-ws",`code-server WS cap exceeded (key=${L}, ip=${x??"unknown"})`),J.close(1013,"too many connections");return}W._csCapKey=L,W._csRemoteIp=x;let V=G().name;fetch(`http://127.0.0.1:${$}/api/profiles/${encodeURIComponent(V)}/code-server/status`,{headers:{"x-agent-api-key":V2()}}).then((C)=>C.json()).then((C)=>{if(W._csClosed)return;let q=C;if(!q.running||!q.port){J.close(1011,"code-server not running");return}let v=W.request?.url??"/code-server/",N;try{let I=new URL(v,`http://127.0.0.1:${q.port}`);N=(I.pathname.replace(/^\/code-server\/?/,"/")||"/")+I.search}catch{N="/"}let T=new WebSocket(`ws://127.0.0.1:${q.port}${N}`),O={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=O,T.addEventListener("open",()=>{clearTimeout(O.openTimer),O.ready=!0;for(let I of O.buffer)T.send(I);O.buffer.length=0,O.bufferBytes=0}),T.addEventListener("message",(I)=>{try{let h=I.data;if(h instanceof ArrayBuffer)J.send(new Uint8Array(h));else if(h instanceof Blob)h.arrayBuffer().then((y)=>{try{J.send(new Uint8Array(y))}catch{}});else J.send(h)}catch{}}),T.addEventListener("close",(I)=>{clearTimeout(O.openTimer);try{J.close(I.code||1000,I.reason||"upstream closed")}catch{}}),T.addEventListener("error",()=>{clearTimeout(O.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)a4.release(H,B??null,J)}}}async function s4(){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{H6 as j,g0 as k,_Q as l,L7 as m,a8 as n};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Nd as p}from"./index-9bqd8veb.js";import{Qd as K,Xd as Mq,_d as wq,be as j}from"./index-0cn9bv8z.js";import{existsSync as G,mkdirSync as u,readdirSync as mq,readFileSync as B,renameSync as P,rmSync as oq,writeFileSync as D}from"fs";import{dirname as k,join as v}from"path";import{randomUUID as pq}from"crypto";import{existsSync as b,mkdirSync as d,readFileSync as Zq,renameSync as Jq,unlinkSync as Tq,writeFileSync as F}from"fs";import{dirname as E,join as V}from"path";import{spawnSync as r}from"child_process";import{hostname as Lq,networkInterfaces as xq,platform as Xq,userInfo as Cq}from"os";import{createCipheriv as Fq,createDecipheriv as Nq,pbkdf2Sync as Aq,randomBytes as Rq}from"crypto";var n="secrets:fallback",Wq="secrets:index",t=10,uq=100,a=new Map;function Hq(q,Q){let $=`${q}:${Q}`,z=(a.get($)??0)+1;if(a.set($,z),z<=t)return!0;return(z-t)%uq===0}var C="vibecontrols-agent",Yq=".libsecret-install-attempted",jq="secrets.json";function Pq(){return globalThis.Bun?.secrets??null}class S{api;kind="bun-secrets";constructor(q){this.api=q}async get(q){return this.api.get({service:C,name:q})}async set(q,Q){await this.api.set({service:C,name:q,value:Q}),await yq(q)}async delete(q){let Q=await this.api.delete({service:C,name:q});return await lq(q),Q}async list(q){return Eq(q)}}var Gq=".secrets-encrypted-v1",kq=1e5,vq=32,Iq="sha256",L=null,e=null;function _q(){let q=xq();for(let Q of Object.values(q)){if(!Q)continue;for(let $ of Q){let z=$?.mac;if(z&&z!=="00:00:00:00:00:00")return z}}return"no-mac"}function qq(){if(e!==null)return e;let q;try{q=Cq().username||"unknown"}catch{q=process.env.USER||process.env.USERNAME||"unknown"}return`${Lq()}|${q}|${_q()}`}function Vq(){if(L)return L;let q=`vibecontrols-agent::${qq()}`;return L=Aq(q,qq(),kq,vq,Iq),L}function Qq(q){let Q=Rq(12),$=Fq("aes-256-gcm",Vq(),Q),z=Buffer.concat([$.update(q,"utf8"),$.final()]),Z=$.getAuthTag();return`${Q.toString("hex")}:${Z.toString("hex")}:${z.toString("hex")}`}function hq(q){let Q=q.split(":");if(Q.length!==3)return!1;let[$,z,Z]=Q;return/^[0-9a-f]+$/i.test($)&&$.length===24&&/^[0-9a-f]+$/i.test(z)&&z.length===32&&/^[0-9a-f]*$/i.test(Z)}function gq(q){if(!hq(q))return null;try{let[Q,$,z]=q.split(":"),Z=Nq("aes-256-gcm",Vq(),Buffer.from(Q,"hex"));return Z.setAuthTag(Buffer.from($,"hex")),Buffer.concat([Z.update(Buffer.from(z,"hex")),Z.final()]).toString("utf8")}catch{return null}}class Kq{kind="json-fallback";path;constructor(){this.path=V(j(),jq)}async get(q){let{plain:Q}=this.readWithMigration(),$=Q[q];return typeof $==="string"?$:null}async set(q,Q){await K(n,async()=>{let{encrypted:$}=this.readWithMigration();$[q]=Qq(Q),this.writeEncrypted($)})}async delete(q){return K(n,async()=>{let{encrypted:Q}=this.readWithMigration();if(!(q in Q))return!1;return delete Q[q],this.writeEncrypted(Q),!0})}async list(q){let{encrypted:Q}=this.readWithMigration(),$=Object.keys(Q);return(q?$.filter((Z)=>Z.startsWith(q)):$).sort().map((Z)=>({name:Z}))}readWithMigration(){if(!b(this.path))return{encrypted:{},plain:{}};let q;try{q=Zq(this.path,"utf8")}catch{return{encrypted:{},plain:{}}}let Q;try{Q=JSON.parse(q)}catch{return{encrypted:{},plain:{}}}if(!Q||typeof Q!=="object"||Array.isArray(Q))return{encrypted:{},plain:{}};let $={},z={},Z=!1;for(let[J,X]of Object.entries(Q)){if(typeof X!=="string")continue;let Y=gq(X);if(Y!==null){$[J]=X,z[J]=Y;continue}$[J]=Qq(X),z[J]=X,Z=!0}if(Z)try{this.writeEncrypted($),this.writeMarker()}catch{}return{encrypted:$,plain:z}}writeEncrypted(q){d(E(this.path),{recursive:!0});let Q=`${this.path}.${process.pid}.tmp`;if(F(Q,`${JSON.stringify(q,null,2)}
2
+ import{Od as p}from"./index-js1xn4sq.js";import{$d as wq,Rd as K,Yd as Mq,ce as j}from"./index-a4854mwz.js";import{existsSync as G,mkdirSync as u,readdirSync as mq,readFileSync as B,renameSync as P,rmSync as oq,writeFileSync as D}from"fs";import{dirname as k,join as v}from"path";import{randomUUID as pq}from"crypto";import{existsSync as b,mkdirSync as d,readFileSync as Zq,renameSync as Jq,unlinkSync as Tq,writeFileSync as F}from"fs";import{dirname as E,join as V}from"path";import{spawnSync as r}from"child_process";import{hostname as Lq,networkInterfaces as xq,platform as Xq,userInfo as Cq}from"os";import{createCipheriv as Fq,createDecipheriv as Nq,pbkdf2Sync as Aq,randomBytes as Rq}from"crypto";var n="secrets:fallback",Wq="secrets:index",t=10,uq=100,a=new Map;function Hq(q,Q){let $=`${q}:${Q}`,z=(a.get($)??0)+1;if(a.set($,z),z<=t)return!0;return(z-t)%uq===0}var C="vibecontrols-agent",Yq=".libsecret-install-attempted",jq="secrets.json";function Pq(){return globalThis.Bun?.secrets??null}class S{api;kind="bun-secrets";constructor(q){this.api=q}async get(q){return this.api.get({service:C,name:q})}async set(q,Q){await this.api.set({service:C,name:q,value:Q}),await yq(q)}async delete(q){let Q=await this.api.delete({service:C,name:q});return await lq(q),Q}async list(q){return Eq(q)}}var Gq=".secrets-encrypted-v1",kq=1e5,vq=32,Iq="sha256",L=null,e=null;function _q(){let q=xq();for(let Q of Object.values(q)){if(!Q)continue;for(let $ of Q){let z=$?.mac;if(z&&z!=="00:00:00:00:00:00")return z}}return"no-mac"}function qq(){if(e!==null)return e;let q;try{q=Cq().username||"unknown"}catch{q=process.env.USER||process.env.USERNAME||"unknown"}return`${Lq()}|${q}|${_q()}`}function Vq(){if(L)return L;let q=`vibecontrols-agent::${qq()}`;return L=Aq(q,qq(),kq,vq,Iq),L}function Qq(q){let Q=Rq(12),$=Fq("aes-256-gcm",Vq(),Q),z=Buffer.concat([$.update(q,"utf8"),$.final()]),Z=$.getAuthTag();return`${Q.toString("hex")}:${Z.toString("hex")}:${z.toString("hex")}`}function hq(q){let Q=q.split(":");if(Q.length!==3)return!1;let[$,z,Z]=Q;return/^[0-9a-f]+$/i.test($)&&$.length===24&&/^[0-9a-f]+$/i.test(z)&&z.length===32&&/^[0-9a-f]*$/i.test(Z)}function gq(q){if(!hq(q))return null;try{let[Q,$,z]=q.split(":"),Z=Nq("aes-256-gcm",Vq(),Buffer.from(Q,"hex"));return Z.setAuthTag(Buffer.from($,"hex")),Buffer.concat([Z.update(Buffer.from(z,"hex")),Z.final()]).toString("utf8")}catch{return null}}class Kq{kind="json-fallback";path;constructor(){this.path=V(j(),jq)}async get(q){let{plain:Q}=this.readWithMigration(),$=Q[q];return typeof $==="string"?$:null}async set(q,Q){await K(n,async()=>{let{encrypted:$}=this.readWithMigration();$[q]=Qq(Q),this.writeEncrypted($)})}async delete(q){return K(n,async()=>{let{encrypted:Q}=this.readWithMigration();if(!(q in Q))return!1;return delete Q[q],this.writeEncrypted(Q),!0})}async list(q){let{encrypted:Q}=this.readWithMigration(),$=Object.keys(Q);return(q?$.filter((Z)=>Z.startsWith(q)):$).sort().map((Z)=>({name:Z}))}readWithMigration(){if(!b(this.path))return{encrypted:{},plain:{}};let q;try{q=Zq(this.path,"utf8")}catch{return{encrypted:{},plain:{}}}let Q;try{Q=JSON.parse(q)}catch{return{encrypted:{},plain:{}}}if(!Q||typeof Q!=="object"||Array.isArray(Q))return{encrypted:{},plain:{}};let $={},z={},Z=!1;for(let[J,X]of Object.entries(Q)){if(typeof X!=="string")continue;let Y=gq(X);if(Y!==null){$[J]=X,z[J]=Y;continue}$[J]=Qq(X),z[J]=X,Z=!0}if(Z)try{this.writeEncrypted($),this.writeMarker()}catch{}return{encrypted:$,plain:z}}writeEncrypted(q){d(E(this.path),{recursive:!0});let Q=`${this.path}.${process.pid}.tmp`;if(F(Q,`${JSON.stringify(q,null,2)}
3
3
  `,{mode:384}),Jq(Q,this.path),!b(this.markerPath()))this.writeMarker()}markerPath(){return V(E(this.path),Gq)}writeMarker(){try{F(this.markerPath(),`${new Date().toISOString()}
4
4
  `,{mode:384})}catch{}}}var fq=".secrets-index.json";function m(){return V(j(),fq)}function o(){let q=m();if(!b(q))return new Set;try{let Q=Zq(q,"utf8"),$=JSON.parse(Q);if(Array.isArray($))return new Set($.filter((z)=>typeof z==="string"))}catch{}return new Set}function Uq(q){let Q=m();d(E(Q),{recursive:!0});let $=`${Q}.${process.pid}.tmp`;F($,`${JSON.stringify([...q].sort(),null,2)}
5
5
  `,{mode:384}),Jq($,Q)}async function yq(q){await K(Wq,()=>{let Q=o();if(Q.has(q))return;Q.add(q),Uq(Q)})}async function lq(q){await K(Wq,()=>{let Q=o();if(!Q.delete(q))return;Uq(Q)})}function Eq(q){let $=[...o()];return(q?$.filter((Z)=>Z.startsWith(q)):$).sort().map((Z)=>({name:Z}))}function Sq(){if(Xq()!=="linux")return{ok:!1};if(process.env.CI==="true")return{ok:!1,warning:"CI/test environment detected; using JSON fallback"};if(process.env.VIBE_SKIP_LIBSECRET_INSTALL==="1")return{ok:!1,warning:"VIBE_SKIP_LIBSECRET_INSTALL=1 set; using JSON fallback"};let q=j(),Q=V(q,Yq);if(b(Q))return{ok:!1,warning:"previous attempt failed; not retrying"};try{d(q,{recursive:!0}),F(Q,`${new Date().toISOString()}
@@ -8,4 +8,4 @@ import{Nd as p}from"./index-9bqd8veb.js";import{Qd as K,Xd as Mq,_d as wq,be as
8
8
  `,{mode:384}),P(X,z),Z}function FQ(q){let Q=g(q);if(!G(Q))return!1;return oq(Q,{force:!0}),!0}function qQ(q,Q={}){let $=Oq[q];return{schemaVersion:M,globalGatewayUrl:$.globalGatewayUrl,workspaceGatewayUrl:$.workspaceGatewayUrl,...Q}}function QQ(){let q={created:[],activeWritten:null};for(let Q of Object.keys(Oq))if(!G(g(Q)))eq(Q,qQ(Q)),q.created.push(Q);if(!G(c()))tq(O),q.activeWritten=O;return q}function $Q(){return{..._}}function s(q){let Q=q?.dir??wq();return v(Q,"config.json")}function zQ(){return{..._}}function NQ(q={}){let Q=$Q();return{schemaVersion:M,globalGatewayUrl:Q.globalGatewayUrl,workspaceGatewayUrl:Q.workspaceGatewayUrl,...q}}function f(q){try{let Q=JSON.parse(q);if(Q&&typeof Q==="object")return Q}catch{}return{}}function i(q){let Q=s(q);if(!G(Q))return{};let $;try{$=f(B(Q,"utf8"))}catch{return{}}if(($.schemaVersion??0)>=M)return $;for(let Z of sq){if(Z.from<($.schemaVersion??0))continue;$=Z.apply($),$.schemaVersion=Z.to}if($.schemaVersion!==M)$.schemaVersion=M;try{D(Q,JSON.stringify($,null,2),{mode:384})}catch{}return $}function AQ(q){let Q=i(q);if(Q.agentInstanceId)return Q.agentInstanceId;let $=pq();return ZQ({agentInstanceId:$},q),$}function ZQ(q,Q){let $=s(Q);u(k($),{recursive:!0});let z=G($)?f(B($,"utf8")):{},Z={...z},J={...z};for(let W of T)delete J[W];let X=Q?.scope??I();for(let[W,H]of Object.entries(q)){if(H===void 0||H==="")continue;if(Z[W]=H,bq(W)&&typeof H==="string"){R(w(X,W),H).catch(()=>{});continue}J[W]=H}let Y=`${$}.${process.pid}.tmp`;return D(Y,`${JSON.stringify(J,null,2)}
9
9
  `,{mode:384}),P(Y,$),Z}async function RQ(q,Q){let $=s(Q);return K(cq($),async()=>{u(k($),{recursive:!0});let z=G($)?f(B($,"utf8")):{},Z={...z},J={...z};for(let H of T)delete J[H];let X=Q?.scope??I(),Y=[];for(let[H,U]of Object.entries(q)){if(U===void 0||U==="")continue;if(Z[H]=U,bq(H)&&typeof U==="string"){Y.push(R(w(X,H),U));continue}J[H]=U}await Promise.all(Y);let W=`${$}.${process.pid}.tmp`;return D(W,`${JSON.stringify(J,null,2)}
10
10
  `,{mode:384}),P(W,$),Z})}async function uQ(q){let Q=i(q?{dir:q.dir}:void 0),$=q?.scope??I();for(let z of T){if(Q[z])continue;try{let Z=await A(w($,z));if(Z)Q[z]=Z}catch{}}return Q}function JQ(){return aq(nq())}function PQ(){try{QQ()}catch{}let q=JQ(),Q=i(),$={...q,...Q},z=(J,X)=>{if(!process.env[J]&&X)process.env[J]=X};z("VIBE_WORKSPACE_ID",$.workspaceId),z("VIBE_ORGANIZATION_ID",$.organizationId);let Z=zQ();return z("VIBE_GLOBAL_GATEWAY_URL",$.globalGatewayUrl??Z.globalGatewayUrl),z("VIBE_WORKSPACE_GATEWAY_URL",$.workspaceGatewayUrl??Z.workspaceGatewayUrl),z("VIBE_STORAGE_ADAPTER",$.storageAdapter),z("VIBECONTROLS_PLUGIN_INSTALL_SCOPE",$.pluginInstallScope),$}async function kQ(){let q=($,z)=>{if(!process.env[$]&&z)process.env[$]=z},Q=I();try{let $=await A(w(Q,"clientId"));q("VIBE_CLIENT_ID",$??void 0)}catch{}try{let $=await A(w(Q,"clientSecret"));q("VIBE_CLIENT_SECRET",$??void 0)}catch{}}
11
- export{A as Rc,R as Sc,UQ as Tc,MQ as Uc,M as Vc,Oq as Wc,xQ as Xc,O as Yc,h as Zc,Dq as _c,c as $c,g as ad,nq as bd,tq as cd,CQ as dd,aq as ed,eq as fd,FQ as gd,qQ as hd,QQ as id,$Q as jd,s as kd,zQ as ld,NQ as md,i as nd,AQ as od,ZQ as pd,RQ as qd,uQ as rd,JQ as sd,PQ as td,kQ as ud};
11
+ export{A as Sc,R as Tc,UQ as Uc,MQ as Vc,M as Wc,Oq as Xc,xQ as Yc,O as Zc,h as _c,Dq as $c,c as ad,g as bd,nq as cd,tq as dd,CQ as ed,aq as fd,eq as gd,FQ as hd,qQ as id,QQ as jd,$Q as kd,s as ld,zQ as md,NQ as nd,i as od,AQ as pd,ZQ as qd,RQ as rd,uQ as sd,JQ as td,PQ as ud,kQ as vd};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Bb as k,Cb as a,Db as y,Kb as T,Lb as x,tb as r,yb as v}from"./index-01qzsnwd.js";import{Ub as B}from"./index-04n4qgvd.js";import{Jd as e,Nd as j}from"./index-9bqd8veb.js";function w(Q,J){let $=new B,Z=[],G=new Set;function Y(z){return z.endsWith("/")&&z!=="/"?z.slice(0,-1):z}function U(z,H){if(!H.startsWith("/"))return null;if(H==="/"||H.includes("..")||H.includes("*"))return null;let F=Y(z),X=Y(`${F}${H}`);if(X===F||!X.startsWith(`${F}/`))return null;return X}function V(z){if(!z.createRoutes)return!1;if(G.has(z.name))return!1;let H=z.apiPrefix||`/api/${z.name}`;try{let F=z.createRoutes(J);if(j().logger.info("plugin-router",`Plugin '${z.name}' registered routes`,{prefix:H}),$.use(new B({prefix:H}).derive(()=>({pluginContext:{chain:[z.name],parentPlugin:void 0,activePlugin:z.name}})).use(F)),z.publicPaths)for(let X of z.publicPaths){let K=U(H,X);if(!K){j().logger.warn("plugin-router",`Ignoring unsafe public path from plugin '${z.name}'`,{publicPath:X,prefix:H});continue}Z.push(K)}return G.add(z.name),!0}catch(F){return j().logger.error("plugin-router",`Failed to mount routes for plugin '${z.name}'`,{error:String(F)}),!1}}for(let z of Q.getAllPlugins())V(z);return{routes:$,getPublicPaths:()=>[...Z],mountPlugin:V}}import{EventEmitter as VJ}from"events";var u=1e4;function L(Q,J){let $=process.env[Q];if(!$)return J;let Z=Number.parseInt($,10);return Number.isFinite(Z)&&Z>0?Z:J}function ZJ(){return[{name:"health",match:(Q)=>Q.startsWith("/health"),perMinute:L("VIBECONTROLS_RATELIMIT_HEALTH",1000)},{name:"gateway-auth",match:(Q)=>Q.startsWith("/api/agent/gateway-auth"),perMinute:L("VIBECONTROLS_RATELIMIT_GATEWAY_AUTH",10)},{name:"plugin-install",match:(Q)=>Q.startsWith("/api/plugins/install"),perMinute:L("VIBECONTROLS_RATELIMIT_PLUGIN_INSTALL",5)},{name:"alias-exec",match:(Q)=>/^\/api\/aliases\/[^/]+\/execute/.test(Q),perMinute:L("VIBECONTROLS_RATELIMIT_ALIAS_EXEC",30)},{name:"api",match:(Q)=>Q.startsWith("/api/"),perMinute:L("VIBECONTROLS_RATELIMIT_API",100)}]}function $J(Q,J,$){for(let Z of Q)if(Z.match(J,$))return Z;return null}function R(Q){if(!Q)return!1;return Q==="127.0.0.1"||Q==="::1"||Q==="::ffff:127.0.0.1"||Q.startsWith("127.")}function GJ(Q=Date.now){let J=new Map,$=(Z,G)=>{J.delete(Z),J.set(Z,G)};return{take(Z,G,Y){let U=Q(),V=J.get(Z);if(!V)V={tokens:G,lastRefillMs:U,capacity:G,refillPerSec:Y};else{let H=(U-V.lastRefillMs)/1000;V.tokens=Math.min(G,V.tokens+H*Y),V.lastRefillMs=U,V.capacity=G,V.refillPerSec=Y}let z=V.tokens>=1;if(z)V.tokens-=1;if($(Z,V),J.size>u){let H=J.keys();while(J.size>u){let F=H.next();if(F.done)break;J.delete(F.value)}}return z},retryAfterSec(Z){let G=J.get(Z);if(!G)return 1;if(G.refillPerSec<=0)return 60;let Y=1-G.tokens;if(Y<=0)return 0;return Math.max(1,Math.ceil(Y/G.refillPerSec))},size(){return J.size},reset(){J.clear()}}}function SJ(Q={}){let J=Q.classes??ZJ(),$=Q.store??GJ();return new B({name:"plugin/rate-limit"}).onRequest(({request:Z,set:G,server:Y})=>{let U;try{U=Y?.requestIP(Z)?.address??null}catch{U=null}if(R(U))return;let V=new URL(Z.url),z=$J(J,V.pathname,Z.method);if(!z)return;let F=`${U??"unknown"}|${z.name}`,X=z.perMinute/60;if(!$.take(F,z.perMinute,X)){let K=$.retryAfterSec(F);G.status=429;let P=G.headers??={};return P["Retry-After"]=String(K),{error:"rate_limited",message:`Too many requests for ${z.name}; retry after ${K}s.`,retryAfterSec:K}}}).as("global")}var YJ=(()=>{let Q=process.env.VIBECONTROLS_WS_MAX_PER_IP,J=Q?Number.parseInt(Q,10):NaN;return Number.isFinite(J)&&J>0?J:5})();function C(Q=YJ){let J=new Map;return{accept($,Z){if(R($))return!0;let G=$??"unknown",Y=J.get(G);if(!Y)Y=new Set,J.set(G,Y);if(Y.size>=Q)return!1;return Y.add(Z),!0},release($,Z){if(R($))return;let G=$??"unknown",Y=J.get(G);if(!Y)return;if(Y.delete(Z),Y.size===0)J.delete(G)},size($){let Z=$??"unknown";return J.get(Z)?.size??0}}}function c(Q){let J=new Set,$=new Map,Z=new Map;return{accept(G,Y,U){if(J.size>=Q.maxGlobal)return!1;let V=$.get(G)??new Set;if(V.size>=Q.maxPerKey)return!1;let z=Y??"unknown";if(!R(Y)){let H=Z.get(z)??new Set;if(H.size>=Q.maxPerIp)return!1;H.add(U),Z.set(z,H)}return J.add(U),V.add(U),$.set(G,V),!0},release(G,Y,U){J.delete(U);let V=$.get(G);if(V){if(V.delete(U),V.size===0)$.delete(G)}if(!R(Y)){let z=Y??"unknown",H=Z.get(z);if(H){if(H.delete(U),H.size===0)Z.delete(z)}}},globalCount(){return J.size},keyCount(G){return $.get(G)?.size??0}}}function _(Q,J){let $=process.env[Q];if(!$)return J;let Z=Number.parseInt($,10);return Number.isFinite(Z)&&Z>0?Z:J}var m={maxGlobal:_("VIBE_TERMINAL_WS_MAX_GLOBAL",64),maxPerKey:_("VIBE_TERMINAL_WS_MAX_PER_SESSION",4),maxPerIp:_("VIBE_TERMINAL_WS_MAX_PER_IP",16)},LJ={maxGlobal:_("VIBE_CODE_SERVER_WS_MAX_GLOBAL",64),maxPerKey:_("VIBE_CODE_SERVER_WS_MAX_PER_SESSION",8),maxPerIp:_("VIBE_CODE_SERVER_WS_MAX_PER_IP",16)};function UJ(Q){if(!Q)return new Set;let J=new Set;for(let $ of Q.split(",")){let Z=$.trim();if(Z)J.add(Z)}return J}var D=null;function zJ(){let Q=process.env.VIBE_TRUSTED_PROXIES;if(!D||D.raw!==Q)D={raw:Q,set:UJ(Q)};return D.set}function E(Q,J){let $=zJ();if(!!Q&&(R(Q)||$.has(Q))&&J){let G=J["x-forwarded-for"];if(G){let U=G.split(",")[0]?.trim();if(U)return U}let Y=J["x-real-ip"];if(Y)return Y}return Q}var d=C(),h=new VJ;h.setMaxListeners(100);function b(Q,J){let $={type:Q,payload:J,timestamp:new Date().toISOString()};h.emit("ws:event",$)}var p=(()=>{let Q=process.env.VIBECONTROLS_MAX_WS_CLIENTS,J=Q?Number.parseInt(Q,10):NaN;return Number.isFinite(J)&&J>0?J:200})(),HJ=(()=>{let Q=process.env.VIBECONTROLS_MAX_WS_BUFFER_PER_CLIENT,J=Q?Number.parseInt(Q,10):NaN;return Number.isFinite(J)&&J>0?J:100})();function XJ(){let Q=new Set;return h.on("ws:event",(J)=>{let $=JSON.stringify(J);for(let Z of Q){if(Z.pendingSends>=HJ){if(Z.drops+=1,Z.drops===1||Z.drops%100===0)j().logger.warn("ws-events",`Dropping events for slow client (${Z.drops} dropped)`);continue}try{Z.send($)}catch{}}}),new B().ws("/ws/events",{open(J){if(Q.size>=p){j().logger.warn("ws-events",`MAX_WS_CLIENTS exceeded (${Q.size}/${p}); refusing new connection`),J.close(1013,"Server overloaded");return}let $=J.data,Z=T($.headers??{});if(!x(Z)){J.close(1008,"Unauthorized: invalid or missing API key");return}let G=J.remoteAddress??null,Y=E(G,$.headers);if(!d.accept(Y??null,J)){J.close(1008,"too many connections");return}J._remoteIp=Y??null;let U={ws:J,channels:new Set,pendingSends:0,drops:0,send:(V)=>{U.pendingSends+=1;try{J.send(V)}finally{queueMicrotask(()=>{U.pendingSends=Math.max(0,U.pendingSends-1)})}}};Q.add(U),J._client=U,j().logger.debug("ws-events","Client connected",{id:String(J.id||"unknown")}),J.send(JSON.stringify({type:"connected",timestamp:new Date().toISOString()}))},message(J,$){try{let Z=typeof $==="string"?JSON.parse($):$;switch(Z.type){case"subscribe":{let G=J._client;if(G)G.channels.add(Z.channel);j().logger.debug("ws-events",`Subscribed to ${Z.channel}`);break}case"unsubscribe":{let G=J._client;if(G)G.channels.delete(Z.channel);j().logger.debug("ws-events",`Unsubscribed from ${Z.channel}`);break}case"ping":J.send(JSON.stringify({type:"pong",timestamp:new Date().toISOString()}));break;default:j().logger.debug("ws-events",`Unknown message type: ${Z.type}`)}}catch{j().logger.warn("ws-events","Failed to parse incoming message")}},close(J){let $=J._client;if($)Q.delete($);let Z=J._remoteIp;d.release(Z??null,J),j().logger.debug("ws-events","Client disconnected")}})}var g=c(m),FJ=256,jJ=1048576,KJ=1e4;async function l(Q,J,$,Z,G,Y){let U={};for(let[z,H]of Object.entries(G))if(H&&!["host","connection"].includes(z.toLowerCase()))U[z]=H;let V={method:Z,headers:U};if(Z!=="GET"&&Z!=="HEAD"&&Y)V.body=typeof Y==="string"?Y:JSON.stringify(Y);return fetch(`http://${Q}:${J}${$}`,V)}async function I(Q,J){let $=Q.listProvidersForType("session");for(let{pluginName:Z}of $){let G=Q.getProviderByName("session",Z);if(!G)continue;let Y=await G.getTerminalInfo(J);if(!Y)continue;try{process.kill(Y.pid,0)}catch{continue}let U=Y;return{host:U.host??"127.0.0.1",port:Y.port,wsPath:U.wsPath??"/ws",subprotocols:U.subprotocols??["tty"]}}return null}var M=new Map,NJ=0,q=new Map,o=30000;function A(Q){g.release(Q.sessionId,Q.remoteIp,Q.capRef)}function BJ(Q){return typeof Q==="string"?Buffer.byteLength(Q):Q.byteLength}function n(Q){let J=new Headers(Q.headers);return J.set("Permissions-Policy","clipboard-read=(self), clipboard-write=(self)"),J.delete("X-Frame-Options"),new Response(Q.body,{status:Q.status,headers:J})}function i(Q){return`<!doctype html>
2
+ import{Bb as k,Cb as a,Db as y,Lb as T,Mb as x,tb as r,yb as v}from"./index-rqq0k5fc.js";import{Vb as B}from"./index-pgew6sge.js";import{Kd as e,Od as j}from"./index-js1xn4sq.js";function w(Q,J){let $=new B,Z=[],G=new Set;function Y(z){return z.endsWith("/")&&z!=="/"?z.slice(0,-1):z}function U(z,H){if(!H.startsWith("/"))return null;if(H==="/"||H.includes("..")||H.includes("*"))return null;let F=Y(z),X=Y(`${F}${H}`);if(X===F||!X.startsWith(`${F}/`))return null;return X}function V(z){if(!z.createRoutes)return!1;if(G.has(z.name))return!1;let H=z.apiPrefix||`/api/${z.name}`;try{let F=z.createRoutes(J);if(j().logger.info("plugin-router",`Plugin '${z.name}' registered routes`,{prefix:H}),$.use(new B({prefix:H}).derive(()=>({pluginContext:{chain:[z.name],parentPlugin:void 0,activePlugin:z.name}})).use(F)),z.publicPaths)for(let X of z.publicPaths){let K=U(H,X);if(!K){j().logger.warn("plugin-router",`Ignoring unsafe public path from plugin '${z.name}'`,{publicPath:X,prefix:H});continue}Z.push(K)}return G.add(z.name),!0}catch(F){return j().logger.error("plugin-router",`Failed to mount routes for plugin '${z.name}'`,{error:String(F)}),!1}}for(let z of Q.getAllPlugins())V(z);return{routes:$,getPublicPaths:()=>[...Z],mountPlugin:V}}import{EventEmitter as VJ}from"events";var u=1e4;function L(Q,J){let $=process.env[Q];if(!$)return J;let Z=Number.parseInt($,10);return Number.isFinite(Z)&&Z>0?Z:J}function ZJ(){return[{name:"health",match:(Q)=>Q.startsWith("/health"),perMinute:L("VIBECONTROLS_RATELIMIT_HEALTH",1000)},{name:"gateway-auth",match:(Q)=>Q.startsWith("/api/agent/gateway-auth"),perMinute:L("VIBECONTROLS_RATELIMIT_GATEWAY_AUTH",10)},{name:"plugin-install",match:(Q)=>Q.startsWith("/api/plugins/install"),perMinute:L("VIBECONTROLS_RATELIMIT_PLUGIN_INSTALL",5)},{name:"alias-exec",match:(Q)=>/^\/api\/aliases\/[^/]+\/execute/.test(Q),perMinute:L("VIBECONTROLS_RATELIMIT_ALIAS_EXEC",30)},{name:"api",match:(Q)=>Q.startsWith("/api/"),perMinute:L("VIBECONTROLS_RATELIMIT_API",100)}]}function $J(Q,J,$){for(let Z of Q)if(Z.match(J,$))return Z;return null}function R(Q){if(!Q)return!1;return Q==="127.0.0.1"||Q==="::1"||Q==="::ffff:127.0.0.1"||Q.startsWith("127.")}function GJ(Q=Date.now){let J=new Map,$=(Z,G)=>{J.delete(Z),J.set(Z,G)};return{take(Z,G,Y){let U=Q(),V=J.get(Z);if(!V)V={tokens:G,lastRefillMs:U,capacity:G,refillPerSec:Y};else{let H=(U-V.lastRefillMs)/1000;V.tokens=Math.min(G,V.tokens+H*Y),V.lastRefillMs=U,V.capacity=G,V.refillPerSec=Y}let z=V.tokens>=1;if(z)V.tokens-=1;if($(Z,V),J.size>u){let H=J.keys();while(J.size>u){let F=H.next();if(F.done)break;J.delete(F.value)}}return z},retryAfterSec(Z){let G=J.get(Z);if(!G)return 1;if(G.refillPerSec<=0)return 60;let Y=1-G.tokens;if(Y<=0)return 0;return Math.max(1,Math.ceil(Y/G.refillPerSec))},size(){return J.size},reset(){J.clear()}}}function SJ(Q={}){let J=Q.classes??ZJ(),$=Q.store??GJ();return new B({name:"plugin/rate-limit"}).onRequest(({request:Z,set:G,server:Y})=>{let U;try{U=Y?.requestIP(Z)?.address??null}catch{U=null}if(R(U))return;let V=new URL(Z.url),z=$J(J,V.pathname,Z.method);if(!z)return;let F=`${U??"unknown"}|${z.name}`,X=z.perMinute/60;if(!$.take(F,z.perMinute,X)){let K=$.retryAfterSec(F);G.status=429;let P=G.headers??={};return P["Retry-After"]=String(K),{error:"rate_limited",message:`Too many requests for ${z.name}; retry after ${K}s.`,retryAfterSec:K}}}).as("global")}var YJ=(()=>{let Q=process.env.VIBECONTROLS_WS_MAX_PER_IP,J=Q?Number.parseInt(Q,10):NaN;return Number.isFinite(J)&&J>0?J:5})();function C(Q=YJ){let J=new Map;return{accept($,Z){if(R($))return!0;let G=$??"unknown",Y=J.get(G);if(!Y)Y=new Set,J.set(G,Y);if(Y.size>=Q)return!1;return Y.add(Z),!0},release($,Z){if(R($))return;let G=$??"unknown",Y=J.get(G);if(!Y)return;if(Y.delete(Z),Y.size===0)J.delete(G)},size($){let Z=$??"unknown";return J.get(Z)?.size??0}}}function c(Q){let J=new Set,$=new Map,Z=new Map;return{accept(G,Y,U){if(J.size>=Q.maxGlobal)return!1;let V=$.get(G)??new Set;if(V.size>=Q.maxPerKey)return!1;let z=Y??"unknown";if(!R(Y)){let H=Z.get(z)??new Set;if(H.size>=Q.maxPerIp)return!1;H.add(U),Z.set(z,H)}return J.add(U),V.add(U),$.set(G,V),!0},release(G,Y,U){J.delete(U);let V=$.get(G);if(V){if(V.delete(U),V.size===0)$.delete(G)}if(!R(Y)){let z=Y??"unknown",H=Z.get(z);if(H){if(H.delete(U),H.size===0)Z.delete(z)}}},globalCount(){return J.size},keyCount(G){return $.get(G)?.size??0}}}function _(Q,J){let $=process.env[Q];if(!$)return J;let Z=Number.parseInt($,10);return Number.isFinite(Z)&&Z>0?Z:J}var m={maxGlobal:_("VIBE_TERMINAL_WS_MAX_GLOBAL",64),maxPerKey:_("VIBE_TERMINAL_WS_MAX_PER_SESSION",4),maxPerIp:_("VIBE_TERMINAL_WS_MAX_PER_IP",16)},LJ={maxGlobal:_("VIBE_CODE_SERVER_WS_MAX_GLOBAL",64),maxPerKey:_("VIBE_CODE_SERVER_WS_MAX_PER_SESSION",8),maxPerIp:_("VIBE_CODE_SERVER_WS_MAX_PER_IP",16)};function UJ(Q){if(!Q)return new Set;let J=new Set;for(let $ of Q.split(",")){let Z=$.trim();if(Z)J.add(Z)}return J}var D=null;function zJ(){let Q=process.env.VIBE_TRUSTED_PROXIES;if(!D||D.raw!==Q)D={raw:Q,set:UJ(Q)};return D.set}function E(Q,J){let $=zJ();if(!!Q&&(R(Q)||$.has(Q))&&J){let G=J["x-forwarded-for"];if(G){let U=G.split(",")[0]?.trim();if(U)return U}let Y=J["x-real-ip"];if(Y)return Y}return Q}var d=C(),h=new VJ;h.setMaxListeners(100);function b(Q,J){let $={type:Q,payload:J,timestamp:new Date().toISOString()};h.emit("ws:event",$)}var p=(()=>{let Q=process.env.VIBECONTROLS_MAX_WS_CLIENTS,J=Q?Number.parseInt(Q,10):NaN;return Number.isFinite(J)&&J>0?J:200})(),HJ=(()=>{let Q=process.env.VIBECONTROLS_MAX_WS_BUFFER_PER_CLIENT,J=Q?Number.parseInt(Q,10):NaN;return Number.isFinite(J)&&J>0?J:100})();function XJ(){let Q=new Set;return h.on("ws:event",(J)=>{let $=JSON.stringify(J);for(let Z of Q){if(Z.pendingSends>=HJ){if(Z.drops+=1,Z.drops===1||Z.drops%100===0)j().logger.warn("ws-events",`Dropping events for slow client (${Z.drops} dropped)`);continue}try{Z.send($)}catch{}}}),new B().ws("/ws/events",{open(J){if(Q.size>=p){j().logger.warn("ws-events",`MAX_WS_CLIENTS exceeded (${Q.size}/${p}); refusing new connection`),J.close(1013,"Server overloaded");return}let $=J.data,Z=T($.headers??{});if(!x(Z)){J.close(1008,"Unauthorized: invalid or missing API key");return}let G=J.remoteAddress??null,Y=E(G,$.headers);if(!d.accept(Y??null,J)){J.close(1008,"too many connections");return}J._remoteIp=Y??null;let U={ws:J,channels:new Set,pendingSends:0,drops:0,send:(V)=>{U.pendingSends+=1;try{J.send(V)}finally{queueMicrotask(()=>{U.pendingSends=Math.max(0,U.pendingSends-1)})}}};Q.add(U),J._client=U,j().logger.debug("ws-events","Client connected",{id:String(J.id||"unknown")}),J.send(JSON.stringify({type:"connected",timestamp:new Date().toISOString()}))},message(J,$){try{let Z=typeof $==="string"?JSON.parse($):$;switch(Z.type){case"subscribe":{let G=J._client;if(G)G.channels.add(Z.channel);j().logger.debug("ws-events",`Subscribed to ${Z.channel}`);break}case"unsubscribe":{let G=J._client;if(G)G.channels.delete(Z.channel);j().logger.debug("ws-events",`Unsubscribed from ${Z.channel}`);break}case"ping":J.send(JSON.stringify({type:"pong",timestamp:new Date().toISOString()}));break;default:j().logger.debug("ws-events",`Unknown message type: ${Z.type}`)}}catch{j().logger.warn("ws-events","Failed to parse incoming message")}},close(J){let $=J._client;if($)Q.delete($);let Z=J._remoteIp;d.release(Z??null,J),j().logger.debug("ws-events","Client disconnected")}})}var g=c(m),FJ=256,jJ=1048576,KJ=1e4;async function l(Q,J,$,Z,G,Y){let U={};for(let[z,H]of Object.entries(G))if(H&&!["host","connection"].includes(z.toLowerCase()))U[z]=H;let V={method:Z,headers:U};if(Z!=="GET"&&Z!=="HEAD"&&Y)V.body=typeof Y==="string"?Y:JSON.stringify(Y);return fetch(`http://${Q}:${J}${$}`,V)}async function I(Q,J){let $=Q.listProvidersForType("session");for(let{pluginName:Z}of $){let G=Q.getProviderByName("session",Z);if(!G)continue;let Y=await G.getTerminalInfo(J);if(!Y)continue;try{process.kill(Y.pid,0)}catch{continue}let U=Y;return{host:U.host??"127.0.0.1",port:Y.port,wsPath:U.wsPath??"/ws",subprotocols:U.subprotocols??["tty"]}}return null}var M=new Map,NJ=0,q=new Map,o=30000;function A(Q){g.release(Q.sessionId,Q.remoteIp,Q.capRef)}function BJ(Q){return typeof Q==="string"?Buffer.byteLength(Q):Q.byteLength}function n(Q){let J=new Headers(Q.headers);return J.set("Permissions-Policy","clipboard-read=(self), clipboard-write=(self)"),J.delete("X-Frame-Options"),new Response(Q.body,{status:Q.status,headers:J})}function i(Q){return`<!doctype html>
3
3
  <html>
4
4
  <head>
5
5
  <meta charset="utf-8">