@vibecontrols/agent 2026.602.7 → 2026.814.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. package/dist/{agent-config-pxkfd7ec.js → agent-config-hzzh97dn.js} +1 -1
  2. package/dist/{agent-ready-tracker-pyw7zrp0.js → agent-ready-tracker-gx1yqwjk.js} +1 -1
  3. package/dist/app-k3dex7x4.js +2 -0
  4. package/dist/bootstrap-workspace-dg1e3fp6.js +2 -0
  5. package/dist/bootstrap.service-nbhhd4pa.js +2 -0
  6. package/dist/bridge-client-zye1vz1y.js +2 -0
  7. package/dist/cli.js +1 -1
  8. package/dist/daemon-profile-ryakpcbx.js +2 -0
  9. package/dist/{esm-6f3dfn6v.js → esm-cg5tnbkd.js} +1 -1
  10. package/dist/{finalize-retry-handle-registry-xnm9kxry.js → finalize-retry-handle-registry-kzfqhvwv.js} +1 -1
  11. package/dist/{finalize-retry-worker-vfdskqb5.js → finalize-retry-worker-74wxbdsh.js} +1 -1
  12. package/dist/gateway-client-8y9yd0ch.js +2 -0
  13. package/dist/{getMachineId-bsd-753751sw.js → getMachineId-bsd-65jabrgp.js} +1 -1
  14. package/dist/{getMachineId-darwin-na1pranq.js → getMachineId-darwin-yykv9khr.js} +1 -1
  15. package/dist/{getMachineId-linux-dmn0ncdm.js → getMachineId-linux-w09acg2n.js} +1 -1
  16. package/dist/{getMachineId-unsupported-yv77j894.js → getMachineId-unsupported-dwr7bb60.js} +1 -1
  17. package/dist/{getMachineId-win-9hmyqmm0.js → getMachineId-win-0wkw4jek.js} +1 -1
  18. package/dist/highlights-5wfvq2xq.js +2 -0
  19. package/dist/highlights-fdyzf5xj.js +2 -0
  20. package/dist/highlights-g5bek66n.js +2 -0
  21. package/dist/highlights-scv26t06.js +2 -0
  22. package/dist/highlights-tx5ed845.js +2 -0
  23. package/dist/{index-thammzct.js → index-0s81cfpe.js} +1 -1
  24. package/dist/{index-wetsgcyq.js → index-13xxbf03.js} +1 -1
  25. package/dist/{index-rjhcmnx0.js → index-16czz4df.js} +1 -1
  26. package/dist/{index-kt5zxp42.js → index-1ptfacy9.js} +1 -1
  27. package/dist/{index-xrs52f2c.js → index-2bjqvapr.js} +1 -1
  28. package/dist/{index-x0xv3rpa.js → index-2gwc485c.js} +1 -1
  29. package/dist/{index-n1222y6a.js → index-2jxqpj7r.js} +9 -9
  30. package/dist/{index-5mnyfrck.js → index-4gt22c81.js} +1 -1
  31. package/dist/{index-jrtsdm8f.js → index-53qthjhb.js} +1 -1
  32. package/dist/{index-m9dpfyxb.js → index-5s2zc91f.js} +1 -1
  33. package/dist/{index-cfa3pgh5.js → index-5wsfsj88.js} +3 -3
  34. package/dist/{index-z73x3sdf.js → index-7vwefvxd.js} +1 -1
  35. package/dist/{index-p9cgvp3x.js → index-8k78bp4w.js} +1 -1
  36. package/dist/{index-bfeekmyh.js → index-9g3vxhby.js} +1 -1
  37. package/dist/{index-z40ptwv4.js → index-c0fgge10.js} +2 -2
  38. package/dist/{index-xnr6t79p.js → index-c4p1qcnn.js} +6 -6
  39. package/dist/{index-85ke6hng.js → index-c975k3pk.js} +2 -2
  40. package/dist/{index-t8tnkqxh.js → index-e2dqz3tw.js} +1 -1
  41. package/dist/{index-8sdrhr3q.js → index-g9fthh7a.js} +1 -1
  42. package/dist/{index-c7554sg7.js → index-gb5bnx7a.js} +1 -1
  43. package/dist/{index-qwtspxw8.js → index-gx53t38f.js} +1 -1
  44. package/dist/{index-97mq40rr.js → index-jb3v3b39.js} +1 -1
  45. package/dist/{index-zhyxdyk6.js → index-jqfsvf8f.js} +1 -1
  46. package/dist/{index-9bdbnx8f.js → index-jrxbbb7p.js} +49 -49
  47. package/dist/{index-6p3gcnxr.js → index-m2kkd6t6.js} +1 -1
  48. package/dist/{index-08y76yzh.js → index-nj7bvgws.js} +1 -1
  49. package/dist/{index-4qq083yd.js → index-ntj6ymk8.js} +1 -1
  50. package/dist/index-nwh7j7ap.js +2 -0
  51. package/dist/{index-c6xa5nd4.js → index-pc05r6fd.js} +1 -1
  52. package/dist/{index-a4854mwz.js → index-q9dp55wv.js} +1 -1
  53. package/dist/{index-ep3zb271.js → index-qzhvhyvq.js} +1 -1
  54. package/dist/{index-2nq63va3.js → index-r49hb09r.js} +2 -2
  55. package/dist/{index-63ba5fb4.js → index-sv4rzv3f.js} +1 -1
  56. package/dist/{index-ekzav1nc.js → index-tcwmw7ed.js} +5 -5
  57. package/dist/{index-eawbdgkb.js → index-wd2ak0q4.js} +1 -1
  58. package/dist/{index-x649afed.js → index-wndzw5pk.js} +2 -2
  59. package/dist/{index-czrb2yd1.js → index-zabjc8f2.js} +1 -1
  60. package/dist/{index-pgew6sge.js → index-zaw78sxw.js} +2 -2
  61. package/dist/{index-yas07mv9.js → index-zb7nfmts.js} +1 -1
  62. package/dist/index.js +2 -2
  63. package/dist/injections-agpjxatz.js +2 -0
  64. package/dist/interactive-ewe5szk5.js +2 -0
  65. package/dist/key.cmd-xefsd8p4.js +2 -0
  66. package/dist/log-shipper-4h1k4kp6.js +2 -0
  67. package/dist/{path-utils-hxdyv2zn.js → path-utils-cg1gsy4m.js} +1 -1
  68. package/dist/{plugin-system-f47jdx66.js → plugin-system-ksatnqp4.js} +1 -1
  69. package/dist/prereqs-runner-6yf1e5e3.js +2 -0
  70. package/dist/profile-mount-13qvjqbg.js +2 -0
  71. package/dist/prune-stale-shims-t6kdd2an.js +2 -0
  72. package/dist/register-core-9k4zxnsg.js +2 -0
  73. package/dist/secondary-profile-attach-42x68g0c.js +2 -0
  74. package/dist/subprocess-6m8bja6s.js +2 -0
  75. package/dist/telemetry-mq37zapd.js +2 -0
  76. package/dist/tree-sitter-javascript-emqv64wx.js +2 -0
  77. package/dist/tree-sitter-markdown-v98rp3y1.js +2 -0
  78. package/dist/tree-sitter-markdown_inline-5gq03gn2.js +2 -0
  79. package/dist/tree-sitter-typescript-gr7ymg9w.js +2 -0
  80. package/dist/tree-sitter-zig-59q80fch.js +2 -0
  81. package/dist/tunnel-bootstrap-50fm2wt8.js +2 -0
  82. package/package.json +4 -5
  83. package/dist/app-5asxkthh.js +0 -2
  84. package/dist/bootstrap-workspace-1ff98st2.js +0 -2
  85. package/dist/bootstrap.service-vg72w8pa.js +0 -2
  86. package/dist/bridge-client-73z9c5nm.js +0 -2
  87. package/dist/daemon-profile-696722nr.js +0 -2
  88. package/dist/gateway-client-xdy5g715.js +0 -2
  89. package/dist/highlights-00fcgwwq.js +0 -2
  90. package/dist/highlights-23bc8zge.js +0 -2
  91. package/dist/highlights-4mhb2pb0.js +0 -2
  92. package/dist/highlights-q7w64nwb.js +0 -2
  93. package/dist/highlights-xwdw5xay.js +0 -2
  94. package/dist/index-p23tet7a.js +0 -2
  95. package/dist/injections-x3xya90r.js +0 -2
  96. package/dist/interactive-qc1j66mq.js +0 -2
  97. package/dist/key.cmd-q8c7ywwd.js +0 -2
  98. package/dist/log-shipper-hjnn1d5p.js +0 -2
  99. package/dist/prereqs-runner-t5jhqr7x.js +0 -2
  100. package/dist/profile-mount-m714p85h.js +0 -2
  101. package/dist/prune-stale-shims-23y0stm8.js +0 -2
  102. package/dist/register-core-2t9dmbnp.js +0 -2
  103. package/dist/secondary-profile-attach-s5z9dppt.js +0 -2
  104. package/dist/subprocess-q2ky0ptw.js +0 -2
  105. package/dist/telemetry-jxfgrm61.js +0 -2
  106. package/dist/tree-sitter-javascript-q22gvtms.js +0 -2
  107. package/dist/tree-sitter-markdown-pntsjzm3.js +0 -2
  108. package/dist/tree-sitter-markdown_inline-g1wzqf7k.js +0 -2
  109. package/dist/tree-sitter-typescript-m9yfes10.js +0 -2
  110. package/dist/tree-sitter-zig-jmh62j90.js +0 -2
  111. package/dist/tunnel-bootstrap-zdczwezc.js +0 -2
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Da as D}from"./index-cfa3pgh5.js";import{Xa as V}from"./index-0ckffygp.js";import{$d as A,Sd as _,Td as w,Ud as x,Vd as N,Wd as j,Zd as X,ce as I}from"./index-a4854mwz.js";import{ie as S}from"./index-c7554sg7.js";import{existsSync as $,readdirSync as v,readFileSync as O,writeFileSync as M,mkdirSync as E,openSync as T,closeSync as b,unlinkSync as R}from"fs";import{join as Q}from"path";import{tmpdir as F}from"os";import{spawn as h}from"child_process";class P{registryPath;logsDir;productDir;constructor(){let q=I();this.productDir=q,this.registryPath=Q(q,"agents.json");let z=A();this.logsDir=Q(z,"logs"),E(q,{recursive:!0}),E(z,{recursive:!0}),E(this.logsDir,{recursive:!0})}async startDaemon(q){return X(q.name),this.withInstanceLock(q.name,async()=>{let z=await this.findProcessByName(q.name);if(z&&z.status==="running"){let U=z.version,W=D();if(U===W){console.log(`\u26A0\uFE0F Agent '${q.name}' is already running on port ${z.port}`);return}console.log(`\uD83D\uDD04 Agent '${q.name}' is running an older build (${U??"unknown"} \u2192 ${W}) \u2014 restarting to apply the update`);try{await this.stopInternal(q.name)}catch(Z){console.log(`\u26A0\uFE0F Could not cleanly stop the stale daemon (${Z instanceof Error?Z.message:String(Z)}); proceeding to start the new build`)}}let B=Q(this.logsDir,`${q.name}.log`),C=T(B,"a"),H=Q(import.meta.dir,"index.js"),G=Q(import.meta.dir,"..","index.ts"),L=$(H)?H:G,K=h(process.execPath,["run",L],{detached:!0,windowsHide:!0,stdio:["ignore",C,C],env:{...process.env,VIBECONTROLS_PROFILE:q.profile||"default",PORT:q.port.toString(),DB_PATH:q.dbPath,NODE_ENV:"production",AGENT_LOG_FILE:B}});K.on("error",()=>{}),b(C),await new Promise((U)=>setTimeout(U,2000));let J=K.pid;if(!(J!==void 0&&await this.isProcessRunning(J))){let U="";try{U=O(B,"utf8").split(/\r?\n/).filter((k)=>k.trim()).slice(-25).join(`
2
+ import{Da as D}from"./index-5wsfsj88.js";import{Xa as V}from"./index-0ckffygp.js";import{Td as _,Ud as w,Vd as x,Wd as N,Xd as j,_d as X,ae as A,de as I}from"./index-q9dp55wv.js";import{je as S}from"./index-gb5bnx7a.js";import{existsSync as $,readdirSync as v,readFileSync as O,writeFileSync as M,mkdirSync as E,openSync as T,closeSync as b,unlinkSync as R}from"fs";import{join as Q}from"path";import{tmpdir as F}from"os";import{spawn as h}from"child_process";class P{registryPath;logsDir;productDir;constructor(){let q=I();this.productDir=q,this.registryPath=Q(q,"agents.json");let z=A();this.logsDir=Q(z,"logs"),E(q,{recursive:!0}),E(z,{recursive:!0}),E(this.logsDir,{recursive:!0})}async startDaemon(q){return X(q.name),this.withInstanceLock(q.name,async()=>{let z=await this.findProcessByName(q.name);if(z&&z.status==="running"){let U=z.version,W=D();if(U===W){console.log(`\u26A0\uFE0F Agent '${q.name}' is already running on port ${z.port}`);return}console.log(`\uD83D\uDD04 Agent '${q.name}' is running an older build (${U??"unknown"} \u2192 ${W}) \u2014 restarting to apply the update`);try{await this.stopInternal(q.name)}catch(Z){console.log(`\u26A0\uFE0F Could not cleanly stop the stale daemon (${Z instanceof Error?Z.message:String(Z)}); proceeding to start the new build`)}}let B=Q(this.logsDir,`${q.name}.log`),C=T(B,"a"),H=Q(import.meta.dir,"index.js"),G=Q(import.meta.dir,"..","index.ts"),L=$(H)?H:G,K=h(process.execPath,["run",L],{detached:!0,windowsHide:!0,stdio:["ignore",C,C],env:{...process.env,VIBECONTROLS_PROFILE:q.profile||"default",PORT:q.port.toString(),DB_PATH:q.dbPath,NODE_ENV:"production",AGENT_LOG_FILE:B}});K.on("error",()=>{}),b(C),await new Promise((U)=>setTimeout(U,2000));let J=K.pid;if(!(J!==void 0&&await this.isProcessRunning(J))){let U="";try{U=O(B,"utf8").split(/\r?\n/).filter((k)=>k.trim()).slice(-25).join(`
3
3
  `)}catch{}let W=`See ${B}`;throw Error(U?`Failed to start agent '${q.name}'. ${W}
4
4
  --- last log lines ---
5
5
  ${U}`:`Failed to start agent '${q.name}'. ${W}`)}K.unref(),await this.saveProcessInfo(q.name,J,q),console.log(`\uD83D\uDE80 Agent '${q.name}' started (PID: ${J}, Port: ${q.port})`)})}async stop(q){return X(q),this.withInstanceLock(q,()=>this.stopInternal(q))}async stopInternal(q){let z=await this.findProcessByName(q);if(!z||z.status!=="running"){console.log(`\u26A0\uFE0F Agent '${q}' is not running`);return}try{if(process.kill(z.pid,"SIGTERM"),await new Promise((C)=>setTimeout(C,3000)),await this.isProcessRunning(z.pid))process.kill(z.pid,"SIGKILL");await this.updateProcessStatus(q,"stopped"),console.log(`\u2705 Agent '${q}' stopped (tunnel + API key preserved)`)}catch(B){throw Error(`Failed to stop agent '${q}': ${B}`,{cause:B})}}async restart(q,z){X(q),X(z.name);let B=await this.findProcessByName(q);if(B&&B.status==="running")await this.stop(q);await this.startDaemon(z),console.log(`\uD83D\uDD04 Agent '${q}' restarted (tunnel + API key preserved)`)}async kill(q){return X(q),this.withInstanceLock(q,async()=>{let z=await this.findProcessByName(q);if(!z||z.status!=="running"){console.log(`\u26A0\uFE0F Agent '${q}' is not running`);return}let B=Q(F(),`.boff-vibecontrols-kill-${z.pid}`);try{await Bun.write(B,"kill")}catch{}try{process.kill(z.pid,"SIGTERM"),await new Promise((H)=>setTimeout(H,5000))}catch{}if(await this.isProcessRunning(z.pid))await this.killProcessTree(z.pid);await this.updateProcessStatus(q,"stopped"),console.log(`\uD83D\uDC80 Agent '${q}' killed (tunnel + state torn down)`)})}async getStatus(q){return X(q),this.findProcessByName(q)}discoverRuntimeInstances(){let q=Q(this.productDir,"agents");if(!$(q))return[];let z;try{z=v(q,{withFileTypes:!0}).filter((C)=>C.isDirectory()).map((C)=>C.name)}catch{return[]}let B=[];for(let C of z){let H=Q(q,C,"runtime.json");if(!$(H))continue;try{let G=JSON.parse(O(H,"utf8"));if(typeof G.pid!=="number"||typeof G.port!=="number")continue;let L=G.profile||C;try{X(L)}catch{continue}B.push({name:L,pid:G.pid,port:G.port,config:{name:L,port:G.port,daemon:!0,dbPath:Q(q,C,"agent-db"),host:G.host,profile:L},startTime:G.startedAt??new Date(0).toISOString(),status:"unknown",version:G.version})}catch{}}return B}async getStatusAll(){let q=this.loadRegistry(),z=new Set(q.map((G)=>G.name)),B=[...q];for(let G of this.discoverRuntimeInstances())if(!z.has(G.name))B.push(G);let C=[];for(let G of B){let L=await this.isManagedProcessRunning(G);if(!z.has(G.name)&&!L)continue;C.push({...G,status:L?"running":"stopped"})}let H=C.filter((G)=>G.status==="running"&&!z.has(G.name));if(H.length>0)try{await _(()=>{let G=this.loadRegistry(),L=new Set(G.map((J)=>J.name)),K=H.filter((J)=>!L.has(J.name));if(K.length>0)this.saveRegistry([...G,...K.map((J)=>({...J,status:"running"}))])})}catch{}return C}async listInstances(){return this.getStatusAll()}getDefaultProfile(){return N()}setDefaultProfile(q){j(X(q))}async showLogs(q,z){X(q);let B=Q(this.logsDir,`${q}.log`);if(!$(B)){console.log(`No logs found for agent '${q}'`);return}if(z.follow)try{let C=async(J)=>{let Y=await Bun.file(B).text(),W=Y.split(`
@@ -1,12 +1,12 @@
1
1
  // @bun
2
- import{o as F4,q as J4}from"./index-czrb2yd1.js";import{u as r4,v as U5,w as j5}from"./index-9bdbnx8f.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-5mnyfrck.js";import{la as E5,qa as I5,sa as C0}from"./index-yas07mv9.js";import{va as c2}from"./index-x0xv3rpa.js";import{wa as N5,xa as x5,ya as O5,za as M5}from"./index-c6xa5nd4.js";import{Aa as _5}from"./index-4wgjx8bf.js";import{Ja as T0,Wa as T5}from"./index-cfa3pgh5.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-6p3gcnxr.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-bfeekmyh.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-63ba5fb4.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-xnr6t79p.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-xdy5g715.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-2t9dmbnp.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)
2
+ import{o as F4,q as J4}from"./index-zabjc8f2.js";import{u as r4,v as U5,w as j5}from"./index-jrxbbb7p.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 m4,ea as i4,fa as b4,ha as I2,ia as l2,ja as o2,ka as w2}from"./index-4gt22c81.js";import{la as E5,qa as I5,sa as C0}from"./index-zb7nfmts.js";import{va as y2}from"./index-2gwc485c.js";import{wa as N5,xa as x5,ya as O5,za as M5}from"./index-pc05r6fd.js";import{Aa as _5}from"./index-4wgjx8bf.js";import{Ja as T0,Wa as T5}from"./index-5wsfsj88.js";import{Xa as N2}from"./index-0ckffygp.js";import{ab as f2}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-m2kkd6t6.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 u,Mb as l,Nb as d4,Ob as n4,Pb as X5,Qb as Y5,tb as l0,ub as P2,vb as d0,wb as X0,xb as n0,yb as A2}from"./index-9g3vxhby.js";import{Ub as z,Vb as D}from"./index-zaw78sxw.js";import{nd as e0,od as t,pd as p0,qd as c2,rd as v2}from"./index-sv4rzv3f.js";import{Ad as B2,Dd as W4,Ed as i2,Jd as g,Ld as M0,Md as c,Nd as s,Pd as G,Qd as W0,wd as O0,xd as t4,yd as e4,zd as Q5}from"./index-c4p1qcnn.js";import{Td as r0,Ud as H0,Wd as b2,Xd as t0,Zd as E2,_d as d,ae as h2,ce as T2,de as F2,ee as n2}from"./index-q9dp55wv.js";import{ge as v0,je as b}from"./index-gb5bnx7a.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=A2){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,k2=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=k2.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});k2.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{}k2.delete(X)}}).onError(({store:Z})=>{let Q=Z.__idemKey;if(!Q)return;let Y=Z.__idemReject;try{Y?.(Error("idempotency: handler errored"))}catch{}k2.delete(Q)}).as("global")}import m 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,S2=null;async function D2($){if(J2)return J2;if(S2)return S2;return S2=(async()=>{try{let{MeterProvider:Z}=await import("./index-nwh7j7ap.js").then((m)=>v0(m.default,1)),{PrometheusExporter:Q,PrometheusSerializer:Y}=await import("./index-gx53t38f.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}})(),S2}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 m5($){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(m5(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=u(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 D2()).scrape();return Q.headers["content-type"]="text/plain; version=0.0.4; charset=utf-8",J})}import{randomBytes as u5,timingSafeEqual as g5}from"crypto";import{chmodSync as p5,existsSync as m0,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 u0(){return a5(h2(),"pairing-token")}function s5(){return u5(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 B6(){if(z2)return z2;let $=u0();try{if(m0($)){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 $=u0();if(m0($))n5($)}catch{}}function J0($){return $["x-pairing-token"]??$["X-Pairing-Token"]??null}function QQ(){let $=m.hostname(),Z=m.platform(),Q=m.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:m.hostname(),platform:m.platform(),architecture:m.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=u(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=u(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 P2(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=u(Object.fromEntries(J.headers.entries()));if(!l(H))return W.status=401,{error:"Unauthorized",message:"Invalid or missing API key"};return{machineId:X,hostname:m.hostname(),platform:m.platform(),arch:m.arch(),release:m.release(),cpus:m.cpus().length,totalMemory:m.totalmem(),freeMemory:m.freemem(),uptime:m.uptime(),bunVersion:typeof Bun<"u"?Bun.version:void 0,agentVersion:Y,homeDir:m.homedir(),cwd:process.cwd(),environment:"production"}}).get("/tunnel",async({request:J,set:W})=>{let H=Object.fromEntries(J.headers.entries()),B=l(u(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:f2(g.getConfig()),state:G().getBootState()})).post("/retry-config",async({set:J})=>{let{getFinalizeRetryHandle:W}=await import("./finalize-retry-handle-registry-kzfqhvwv.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=u(K);if(!l(N))return H.status=401,{success:!1,state:B,error:"Unauthorized: API key required to reconfigure"}}else{let N=u(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 v2({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 m2}from"path";function a($){return m2(F2(),"agents",d($))}function XQ(){let $=m2(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 m2(F2(),"agents",d($))}function z0($){return t({dir:$4($)})}function s0($,Z){return c2(Z,{dir:$4($),scope:d($)})}function K2($){let Z=b2(),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=f2(z0($));return X}function Z4($={}){let Z=$.serviceManagerFactory?$.serviceManagerFactory():new y2;return new D({prefix:"/api/profiles"}).get("/",()=>{let Q=XQ(),Y=b2(),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===b2())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(m2(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 C2($,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 C2($.setConfig(Q,Y),2000),await C2($.getConfig(Q),2000)!==Y)throw Error("round-trip mismatch");try{await C2($.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}}}async function HQ($){if(process.env.AGENT_TUNNEL==="false")return{ok:!0,message:"tunnel disabled via AGENT_TUNNEL=false"};if(!$)return{ok:!1,message:"no service registry"};let Z=$.getProvider("tunnel"),Q=G().getBootState()==="awaiting-config";if(!Z)return{ok:!1,message:Q?"agent is awaiting-config \u2014 POST OAuth credentials to /api/agent/gateway-auth to register tunnel provider":"no tunnel provider registered"};if(!Z.getActiveTunnelUrl)return{ok:!0,message:`provider: ${Z.name}`};try{let Y=await C2(Promise.resolve(Z.getActiveTunnelUrl()),2000),X=W4(Y);if(X)return{ok:!0,message:`provider: ${Z.name} \u2014 ${X}`};if(Y)return{ok:!1,message:`provider: ${Z.name} \u2014 reported an unusable tunnel URL (${Y})`};return{ok:!1,message:`provider: ${Z.name} \u2014 no active tunnel (the agent is not reachable from outside; the provider is rebuilding it)`}}catch(Y){return{ok:!1,message:`provider: ${Z.name} \u2014 tunnel status unavailable: ${Y instanceof Error?Y.message:String(Y)}`}}}function GQ($,Z){if(!$)return{ok:!1,message:"no service registry"};let Y=G().getBootState()==="awaiting-config";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 BQ($){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 C2(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=await HQ(Z.serviceRegistry),W.session=GQ(Z.serviceRegistry,"session");try{let{gatewayClient:V}=await import("./gateway-client-8y9yd0ch.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 BQ(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 u2=0,H4=0;function G4(){return new D({name:"inflight-tracker"}).onRequest(()=>{u2+=1}).onAfterResponse(()=>{u2=Math.max(0,u2-1),H4+=1})}function B4(){return new D({prefix:"/api/stats"}).get("/inflight",()=>({inflight:Math.max(0,u2-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"]),VQ=new Set(G0),KQ=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(!VQ.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"||!KQ.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 FQ(){let $=globalThis,Z=$[N4];if(Z)return Z;let Q=new Map;return $[N4]=Q,Q}function B0(){return Array.from(FQ().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:E2(),tunnelHost:J},plugins:{count:Y.length,items:Y},mesh:{peerCount:W.length,peers:W}}}}var LQ=2000,x4=1000;async function NQ($,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??LQ;try{let X=await NQ($.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",_Q=86400000,T4=300000,UQ=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(UQ,$);return _Q}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 I2();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 I2();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 jQ($){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 U7(){if(S.timer)clearTimeout(S.timer),S.timer=null;S.startedAt=null}function w4($){if(c2({autoUpdate:$}),$&&!S.startedAt)jQ({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 xQ=600000,_0=1e6;function OQ(){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=OQ();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??xQ,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-cg5tnbkd.js"),{registerCoreCommands:Z}=await import("./register-core-9k4zxnsg.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 MQ}from"child_process";import{writeFileSync as TQ,mkdirSync as CQ}from"fs";import{tmpdir as EQ}from"os";import{join as S4}from"path";var IQ="@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
5
  const PIDS = ${JSON.stringify(W)};
6
6
  const NPM = ${JSON.stringify(Y)};
7
7
  const BUN = ${JSON.stringify(Q)};
8
8
  const REGISTRY = ${JSON.stringify(X)};
9
- const PKG = ${JSON.stringify(CQ)};
9
+ const PKG = ${JSON.stringify(IQ)};
10
10
  await Bun.sleep(${J});
11
11
  for (const pid of PIDS) {
12
12
  try { process.kill(pid, "SIGTERM"); } catch {}
@@ -17,10 +17,10 @@ for (const pid of PIDS) {
17
17
  }
18
18
  try { Bun.spawnSync([NPM, "uninstall", "-g", PKG, "--registry=" + REGISTRY], { stdout: "inherit", stderr: "inherit" }); } catch {}
19
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!) {
20
+ `;try{let B=S4(EQ(),"vibecontrols-uninstall");CQ(B,{recursive:!0});let K=S4(B,`reaper-${process.pid}.ts`);return TQ(K,H,{encoding:"utf8"}),MQ(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 wQ=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 I2()}).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&&!wQ.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 y2;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 SQ,readFileSync as DQ}from"fs";import{join as hQ}from"path";var qQ=`mutation AddAgentFromTunnel($input: AddAgentFromTunnelInput!) {
22
22
  addVibecontrolsAgentFromTunnel(input: $input) { agent { id name } clientId success error }
23
- }`,wQ=`mutation ReportAgentMeshLink($input: ReportAgentMeshLinkInput!) {
23
+ }`,RQ=`mutation ReportAgentMeshLink($input: ReportAgentMeshLinkInput!) {
24
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-q2ky0ptw.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-jxfgrm61.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,app:T});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-zdczwezc.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-696722nr.js"),{attachSecondaryProfile:A}=await import("./secondary-profile-attach-s5z9dppt.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};
25
+ }`,P4="VIBE_BOOTSTRAP_JSON=";function AQ($){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=AQ(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(qQ,{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(RQ,{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 w2(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 kQ($){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 u4($,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=kQ(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),m4($,{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 vQ=Number(process.env.VIBECONTROLS_MESH_MAX_HOPS||"8");function g4(){return(c()??G()).name}function PQ(){return(c()??G()).dataDir}function p4(){try{let Z=hQ(PQ(),"runtime.json");if(SQ(Z)){let Q=JSON.parse(DQ(Z,"utf8"));if(Q.port&&Number.isInteger(Q.port))return Q.port}}catch{}let $=Number(process.env.PORT);return Number.isInteger($)&&$>0?$:3005}function fQ($){let Z={};return $.headers.forEach((Q,Y)=>{Z[Y]=Q}),Z}function X2($,Z){let Q=u(fQ($));return n4(d4(Q),Z)}function bQ($){let{apiKey:Z,...Q}=$;return{...Q,apiKey:"[REDACTED]"}}function l4($){return typeof $==="string"&&$.startsWith("/api/")&&!$.includes("..")&&!$.includes("//")}var a2=new Map;function cQ(){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(bQ)}}).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 w2(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>vQ)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 w2(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"};cQ();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 u4(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=P2(`/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 yQ=["/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 mQ($){return yQ.some((Z)=>$.startsWith(Z))}var uQ=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function gQ($){return $.split("/").map((Z)=>{if(!Z)return Z;if(/^\d+$/.test(Z))return":id";if(uQ.test(Z))return":id";if(Z.length>=24&&/^[A-Za-z0-9_-]+$/.test(Z))return":id";return Z}).join("/")}async function t8($){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-4h1k4kp6.js");F.init()})(),(async()=>{let F=await s4();await D2({version:F,profile:E2()})})();try{let{checkDependencies:F}=await import("./bootstrap.service-nbhhd4pa.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-6m8bja6s.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(_),R2=[500,2000,8000];if(k==="transient"||k==="unknown"){G().logger.warn("app",`Storage open failed (${k}); will retry up to ${R2.length} times before quarantine`,{error:_ instanceof Error?_.message:String(_),path:R});for(let O2 of R2){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 v2({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(_)}},q2=await s4();C={storage:r2,logger:G().logger,serviceRegistry:H,getProvider:(_)=>H.getProvider(_),getAgentBaseUrl:()=>process.env.AGENT_URL||`http://localhost:${Z}`,getAgentVersion:()=>q2,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:()=>h2(),cliContributors:new _5,audit:{emit:(_,j)=>G().audit.emit("agent",_,j??{})},telemetry:{emit:(_,j)=>{import("./telemetry-mq37zapd.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((R2)=>G().logger.warn("app","Re-dispatch of onServerStart after plugin reload failed",{error:String(R2)}));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,app:T});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-50fm2wt8.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(mQ(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,gQ(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/*",lQ(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=E2(),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),q2=I0.current;if(!q2)return new Response(JSON.stringify({error:"agent-not-ready"}),{status:503,headers:{"content-type":"application/json"}});return q2.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-ryakpcbx.js"),{attachSecondaryProfile:A}=await import("./secondary-profile-attach-42x68g0c.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 pQ($,Z){if(!$)return null;let Q=$.match(new RegExp(`(?:^|;\\s*)${Z}=([^;]*)`));return Q?Q[1]:null}var a4=z5(H5);function lQ($){let X=(J)=>typeof J==="string"?Buffer.byteLength(J):J.byteLength;return{open(J){let W=J.data,H=u(W.headers??{})??u(W.request?Object.fromEntries(W.request.headers.entries()):{}),B=W.query?.vt,K=!!B&&A2(B,"/code-server","GET"),L,w=l(H);if(!w&&!K){let C=W.headers?.cookie??W.request?.headers.get("cookie")??null,q=pQ(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{B6 as j,g0 as k,jQ as l,U7 as m,t8 as n};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{va as D}from"./index-x0xv3rpa.js";import{Fa as U,Ha as M,Pa as R}from"./index-cfa3pgh5.js";import{Xa as I}from"./index-0ckffygp.js";import{Mc as b}from"./index-t8tnkqxh.js";import{Id as x,Od as u}from"./index-xnr6t79p.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(`
2
+ import{va as D}from"./index-2gwc485c.js";import{Fa as U,Ha as M,Pa as R}from"./index-5wsfsj88.js";import{Xa as I}from"./index-0ckffygp.js";import{Mc as b}from"./index-e2dqz3tw.js";import{Jd as x,Pd as u}from"./index-c4p1qcnn.js";import{ae as V,ee as C}from"./index-q9dp55wv.js";import{je as L}from"./index-gb5bnx7a.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-ewe5szk5.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{cb as Y,db as k}from"./index-52cp759f.js";import{Od as W}from"./index-xnr6t79p.js";import{ce as V}from"./index-a4854mwz.js";import{createHash as g,randomUUID as x}from"crypto";import{existsSync as $,mkdirSync as L,readFileSync as O,writeFileSync as j}from"fs";import{join as K}from"path";import*as X from"os";var A="https://analytics.burdenoff.com/api/track",H="cd7d5ccc3667",w=200,f=10,B=30000,R=5000;function C(q){if(process.env.DO_NOT_TRACK==="1")return!1;let z=process.env.VIBECONTROLS_TELEMETRY?.toLowerCase();if(z==="on"||z==="true"||z==="1")return!0;if(z==="off"||z==="false"||z==="0")return!1;return q}class M{enabled=!1;persisted=!1;buffer=[];flushTimer=null;cachedAnonymousId=null;overflowWarned=!1;postFailureWarned=!1;initialized=!1;init(q){if(q?.persisted!==void 0)this.persisted=q.persisted;if(this.enabled=C(this.persisted),!this.initialized)this.initialized=!0,this.startFlushTimer()}setEnabled(q){let z=this.enabled;if(this.persisted=q,this.enabled=C(this.persisted),z&&!this.enabled)this.buffer=[],this.enqueueRaw("telemetry.disabled",{reason:"user_opt_out"}),this.flush()}emit(q,z={}){if(!this.enabled)return;let G={},J=!1;for(let[Z,N]of Object.entries(z)){if(Y(Z)){J=!0;continue}G[Z]=N}let Q=k(q,G);if(!Q.ok||!Q.sanitized){W().logger.warn("telemetry",`dropping event '${q}': ${Q.reason??"invalid"}`);return}this.enqueue(q,Q.sanitized)}enqueueRaw(q,z){this.enqueue(q,z)}enqueue(q,z){let G={site_id:H,event_name:q,properties:z,anonymous_id:this.getAnonymousId(),timestamp:new Date().toISOString()};if(this.buffer.length>=w){if(this.buffer.shift(),!this.overflowWarned)this.overflowWarned=!0,W().logger.warn("telemetry",`buffer overflow (cap=${w}) \u2014 dropping oldest events`)}if(this.buffer.push(G),this.buffer.length>=f)this.flush()}async flush(){if(this.buffer.length===0)return;let q=this.buffer.splice(0,this.buffer.length),z=new AbortController,G=setTimeout(()=>z.abort(),R);try{await fetch(A,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({events:q}),signal:z.signal})}catch(J){if(!this.postFailureWarned)this.postFailureWarned=!0,W().logger.warn("telemetry","shipper POST failed; dropping batch",{error:String(J)})}finally{clearTimeout(G)}}stop(){if(this.flushTimer)clearInterval(this.flushTimer),this.flushTimer=null;this.initialized=!1}_resetForTest(){this.stop(),this.enabled=!1,this.persisted=!1,this.buffer=[],this.cachedAnonymousId=null,this.overflowWarned=!1,this.postFailureWarned=!1}_bufferLength(){return this.buffer.length}_isEnabled(){return this.enabled}startFlushTimer(){if(this.flushTimer)return;if(this.flushTimer=setInterval(()=>{this.flush()},B),typeof this.flushTimer.unref==="function")this.flushTimer.unref()}getAnonymousId(){if(this.cachedAnonymousId)return this.cachedAnonymousId;let q=`${X.hostname()}${X.platform()}`,z=this.readOrCreateInstallId(),G=g("sha256").update(q+z).digest("hex");return this.cachedAnonymousId=G.slice(0,16),this.cachedAnonymousId}readOrCreateInstallId(){let q;try{q=V()}catch{q=K(process.cwd(),".boff","vibecontrols")}if(!$(q))try{L(q,{recursive:!0,mode:448})}catch{}let z=K(q,".install-id");if($(z))try{let J=O(z,"utf-8").trim();if(J)return J}catch{}let G=x();try{j(z,G,{mode:384})}catch{}return G}}var b=new M;
2
+ import{cb as Y,db as k}from"./index-52cp759f.js";import{Pd as W}from"./index-c4p1qcnn.js";import{de as V}from"./index-q9dp55wv.js";import{createHash as g,randomUUID as x}from"crypto";import{existsSync as $,mkdirSync as L,readFileSync as O,writeFileSync as j}from"fs";import{join as K}from"path";import*as X from"os";var A="https://analytics.burdenoff.com/api/track",H="cd7d5ccc3667",w=200,f=10,B=30000,R=5000;function C(q){if(process.env.DO_NOT_TRACK==="1")return!1;let z=process.env.VIBECONTROLS_TELEMETRY?.toLowerCase();if(z==="on"||z==="true"||z==="1")return!0;if(z==="off"||z==="false"||z==="0")return!1;return q}class M{enabled=!1;persisted=!1;buffer=[];flushTimer=null;cachedAnonymousId=null;overflowWarned=!1;postFailureWarned=!1;initialized=!1;init(q){if(q?.persisted!==void 0)this.persisted=q.persisted;if(this.enabled=C(this.persisted),!this.initialized)this.initialized=!0,this.startFlushTimer()}setEnabled(q){let z=this.enabled;if(this.persisted=q,this.enabled=C(this.persisted),z&&!this.enabled)this.buffer=[],this.enqueueRaw("telemetry.disabled",{reason:"user_opt_out"}),this.flush()}emit(q,z={}){if(!this.enabled)return;let G={},J=!1;for(let[Z,N]of Object.entries(z)){if(Y(Z)){J=!0;continue}G[Z]=N}let Q=k(q,G);if(!Q.ok||!Q.sanitized){W().logger.warn("telemetry",`dropping event '${q}': ${Q.reason??"invalid"}`);return}this.enqueue(q,Q.sanitized)}enqueueRaw(q,z){this.enqueue(q,z)}enqueue(q,z){let G={site_id:H,event_name:q,properties:z,anonymous_id:this.getAnonymousId(),timestamp:new Date().toISOString()};if(this.buffer.length>=w){if(this.buffer.shift(),!this.overflowWarned)this.overflowWarned=!0,W().logger.warn("telemetry",`buffer overflow (cap=${w}) \u2014 dropping oldest events`)}if(this.buffer.push(G),this.buffer.length>=f)this.flush()}async flush(){if(this.buffer.length===0)return;let q=this.buffer.splice(0,this.buffer.length),z=new AbortController,G=setTimeout(()=>z.abort(),R);try{await fetch(A,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({events:q}),signal:z.signal})}catch(J){if(!this.postFailureWarned)this.postFailureWarned=!0,W().logger.warn("telemetry","shipper POST failed; dropping batch",{error:String(J)})}finally{clearTimeout(G)}}stop(){if(this.flushTimer)clearInterval(this.flushTimer),this.flushTimer=null;this.initialized=!1}_resetForTest(){this.stop(),this.enabled=!1,this.persisted=!1,this.buffer=[],this.cachedAnonymousId=null,this.overflowWarned=!1,this.postFailureWarned=!1}_bufferLength(){return this.buffer.length}_isEnabled(){return this.enabled}startFlushTimer(){if(this.flushTimer)return;if(this.flushTimer=setInterval(()=>{this.flush()},B),typeof this.flushTimer.unref==="function")this.flushTimer.unref()}getAnonymousId(){if(this.cachedAnonymousId)return this.cachedAnonymousId;let q=`${X.hostname()}${X.platform()}`,z=this.readOrCreateInstallId(),G=g("sha256").update(q+z).digest("hex");return this.cachedAnonymousId=G.slice(0,16),this.cachedAnonymousId}readOrCreateInstallId(){let q;try{q=V()}catch{q=K(process.cwd(),".boff","vibecontrols")}if(!$(q))try{L(q,{recursive:!0,mode:448})}catch{}let z=K(q,".install-id");if($(z))try{let J=O(z,"utf-8").trim();if(J)return J}catch{}let G=x();try{j(z,G,{mode:384})}catch{}return G}}var b=new M;
3
3
  export{b as bb};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{E as A,G as N}from"./index-6jzsthh9.js";import{Ub as l,Vb as T}from"./index-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-85ke6hng.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-t8tnkqxh.js";import"./index-63ba5fb4.js";import"./index-xnr6t79p.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(`
2
+ import{E as A,G as N}from"./index-6jzsthh9.js";import{Ub as l,Vb as T}from"./index-zaw78sxw.js";import{jc as G,kc as D,lc as f}from"./index-8nqp3a4d.js";import{Dc as y,qc as d,rc as r,sc as j,uc as J,vc as U,wc as w,yc as P,zc as v}from"./index-c975k3pk.js";import{Gc as E}from"./index-0s81cfpe.js";import{Lc as p,Nc as g,Oc as L,Pc as x,Qc as S,Rc as O}from"./index-e2dqz3tw.js";import"./index-sv4rzv3f.js";import"./index-c4p1qcnn.js";import"./index-q9dp55wv.js";import"./index-ntj6ymk8.js";import"./index-gb5bnx7a.js";import{promises as R}from"fs";import C from"path";async function M(a){try{let n=await R.readdir(a);if(n.includes("package.json")){try{let i=JSON.parse(await R.readFile(C.join(a,"package.json"),"utf8")),o={...i.dependencies,...i.devDependencies};if(o.react||o["@types/react"])return"react";if(o.vue||o["@vue/cli"])return"vue";if(o.angular||o["@angular/core"])return"angular";if(o.next||o["@types/next"])return"nextjs";if(o.nuxt||o["@nuxt/core"])return"nuxtjs";if(o.svelte||o["@sveltejs/kit"])return"svelte";if(o.express||o.fastify||o.koa)return"nodejs-backend";if(o.electron)return"electron";if(o.vite)return"vite"}catch{}return"nodejs"}if(n.includes("setup.py")||n.includes("requirements.txt")||n.includes("pyproject.toml")||n.includes("Pipfile")){if(n.includes("manage.py"))return"django";if(n.includes("app.py"))return"flask";return"python"}if(n.includes("go.mod"))return"go";if(n.includes("Cargo.toml"))return"rust";if(n.includes("pom.xml"))return"maven";if(n.includes("build.gradle")||n.includes("build.gradle.kts"))return"gradle";if(n.includes("Gemfile"))return"ruby";if(n.includes("composer.json"))return"php";if(n.some((i)=>i.endsWith(".csproj")||i.endsWith(".sln")))return"dotnet";if(n.includes("CMakeLists.txt")||n.includes("Makefile"))return"cpp";if(n.includes("Package.swift"))return"swift";if(n.includes("pubspec.yaml"))return"flutter";if(n.some((i)=>i.endsWith(".tf")))return"terraform";if(n.includes("Dockerfile"))return"docker"}catch{}return}async function V(a){try{let n=["vite.config.ts","vite.config.js"];for(let i of n)try{let t=(await R.readFile(C.join(a,i),"utf-8")).match(/port:\s*(\d+)/);if(t)return parseInt(t[1],10)}catch{}}catch{}return}var Y=new Set([".git","node_modules","__pycache__",".venv","venv","dist","build"]),F=parseInt(process.env.VIBECONTROLS_GIT_SCAN_MAX_DEPTH??"8",10),z=parseInt(process.env.VIBECONTROLS_GIT_SCAN_MAX_DIRECTORIES??"5000",10);async function k(a,n,i,o={visited:0},t=0){let u=[];if(t>F||o.visited>=z)return u;o.visited+=1;try{let e=await N(a);if(e.some((c)=>c.name===".git"&&c.isDirectory())){if(u.push({path:a,name:C.basename(a),parentPath:i,isSubmodule:!!i,projectType:await M(a),vitePort:await V(a)}),!n)return u;i=a}for(let c of e)if(c.isDirectory()&&!c.isSymbolicLink()&&!Y.has(c.name)&&!c.name.startsWith(".")){let s=C.join(a,c.name),$=await k(s,n,i,o,t+1);u.push(...$)}}catch{}return u}function I(a){let{db:n}=a;return new T().get("/",async()=>{return{repositories:await n.getAllGitRepositories()}}).get("/:id",async({params:i,set:o})=>{let t=await n.getGitRepository(i.id);if(!t)return o.status=404,{error:"Repository not found"};return{repository:t}}).post("/scan",async({body:i,set:o})=>{try{let t=(await A(i.directory,{mustExist:!0})).path;if(!(await R.stat(t)).isDirectory())return o.status=400,{error:"Path is not a directory"};let e=await k(t,i.includeSubmodules??!0),m=[];for(let c of e){let s=await n.getGitRepositoryByPath(c.path);if(s)await n.updateGitRepository(s.id,c),m.push({...s,...c});else{let $=await n.createGitRepository({id:globalThis.crypto.randomUUID(),...c});m.push($)}}return{repositories:m,scannedPath:t,totalFound:m.length}}catch(t){return o.status=500,{error:"Failed to scan directory",details:String(t)}}},{body:l.Object({directory:l.String(),includeSubmodules:l.Optional(l.Boolean())})}).put("/:id",async({params:i,body:o,set:t})=>{if(!await n.getGitRepository(i.id))return t.status=404,{error:"Repository not found"};try{return await n.updateGitRepository(i.id,o),{success:!0}}catch(e){return t.status=500,{error:"Failed to update repository",details:String(e)}}},{body:l.Object({name:l.Optional(l.String()),projectType:l.Optional(l.String()),vitePort:l.Optional(l.Number())})}).delete("/:id",async({params:i,set:o})=>{if(!await n.getGitRepository(i.id))return o.status=404,{error:"Repository not found"};try{return await n.deleteGitRepository(i.id),{success:!0}}catch(u){return o.status=500,{error:"Failed to delete repository",details:String(u)}}}).post("/fix-hierarchy",async({set:i})=>{try{let o=await n.fixGitHierarchy(),t=await n.getAllGitRepositories();return{success:!0,fixed:o.fixed,total:t.length}}catch(o){return i.status=500,{error:"Failed to fix hierarchy",details:String(o)}}})}var h="http://localhost:3005";function q(a){let n=a.command("git").description("Manage git repositories");n.command("list").description("List discovered git repositories").option("--agent-url <url>","Agent URL",h).option("--json","Emit JSON").option("--plain","Force plain text output").action(async function(i){let o={...a.opts(),...i};try{let t=p(i),u=encodeURIComponent(g(o));await D({mode:G(o),fetchData:async()=>{return(await L(t,`/api/profiles/${u}/git`)).repositories||[]},plain:(e)=>{if(!e||e.length===0){J("No git repositories found.");return}U("Git Repositories"),P(e.map((m)=>({ID:y(m.id),Name:m.name||"-",Path:m.path||"-",Type:m.type||m.projectType||"-",Submodule:m.isSubmodule?"Yes":"No",Scanned:m.scannedAt?v(m.scannedAt):"-"})))},interactive:async(e)=>{if(!e||e.length===0){U("Git Repositories"),J("No git repositories found.");return}let m=e.map((c)=>({id:String(c.id),label:c.name||y(c.id),hint:c.type||c.projectType||"",detail:[`ID: ${c.id}`,`Name: ${c.name??"-"}`,`Path: ${c.path??"-"}`,`Type: ${c.type??c.projectType??"-"}`,`Submodule: ${c.isSubmodule?"Yes":"No"}`,`Scanned: ${c.scannedAt?v(c.scannedAt):"-"}`].join(`
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};