@vibecontrols/agent 2026.902.1 → 2026.1125.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.
- package/dist/agent-config-v9d7gcz0.js +2 -0
- package/dist/agent-ready-tracker-mewxehg9.js +2 -0
- package/dist/app-a95wetk5.js +2 -0
- package/dist/autostart.cmd-ahet7b1t.js +2 -0
- package/dist/bootstrap-workspace-3pb8qjsh.js +2 -0
- package/dist/bootstrap.service-9m7m1ksa.js +2 -0
- package/dist/bridge-client-xvqy3n15.js +2 -0
- package/dist/cli.js +2 -2
- package/dist/daemon-profile-sg8fp50z.js +2 -0
- package/dist/finalize-retry-handle-registry-z9mbbjmj.js +2 -0
- package/dist/finalize-retry-worker-az74f2qv.js +2 -0
- package/dist/gateway-client-ermpz52n.js +2 -0
- package/dist/getMachineId-bsd-4w1wmcjv.js +2 -0
- package/dist/getMachineId-darwin-kejwz8w5.js +3 -0
- package/dist/getMachineId-linux-mpm53wat.js +2 -0
- package/dist/getMachineId-unsupported-54seyw5v.js +2 -0
- package/dist/getMachineId-win-cva7ghz9.js +2 -0
- package/dist/highlights-3nz7pbkh.js +2 -0
- package/dist/highlights-6dgztt5d.js +2 -0
- package/dist/highlights-jq0g1547.js +2 -0
- package/dist/highlights-yc7cwzcr.js +2 -0
- package/dist/highlights-z2sw1kpq.js +2 -0
- package/dist/index-01fp85ft.js +171 -0
- package/dist/index-0gmhd3hs.js +4 -0
- package/dist/index-0qjbnyg4.js +21 -0
- package/dist/index-2r6cmxxz.js +9 -0
- package/dist/index-2vcxt38h.js +3 -0
- package/dist/index-4527yp1c.js +178 -0
- package/dist/index-4z1y39jt.js +3 -0
- package/dist/index-5021rk8n.js +3 -0
- package/dist/index-652f9scs.js +4 -0
- package/dist/index-75hk5q9s.js +13 -0
- package/dist/index-76m37yd8.js +22 -0
- package/dist/index-7f2k4g6q.js +8 -0
- package/dist/index-7gk1x74m.js +15 -0
- package/dist/index-7wben1jx.js +3 -0
- package/dist/index-8rbhm4g8.js +7 -0
- package/dist/index-9xrhb68w.js +14 -0
- package/dist/index-a0vx2zyx.js +3 -0
- package/dist/index-akk3rxnn.js +4 -0
- package/dist/index-b3v08awy.js +3 -0
- package/dist/index-byerrz46.js +3 -0
- package/dist/index-c4whjk5r.js +3 -0
- package/dist/index-cy97asyh.js +133 -0
- package/dist/index-d59kp6zr.js +3 -0
- package/dist/index-ec08v08h.js +116 -0
- package/dist/index-g08z6z5v.js +5 -0
- package/dist/index-gaztfvyz.js +158 -0
- package/dist/index-gnb8xw13.js +83 -0
- package/dist/index-haww9jpq.js +27 -0
- package/dist/index-hsrt2v87.js +2 -0
- package/dist/index-jmx5awkj.js +3 -0
- package/dist/index-jnxjjx2y.js +3 -0
- package/dist/index-kwhx023z.js +11 -0
- package/dist/index-mmx2kp76.js +16 -0
- package/dist/index-ne8q0a64.js +26 -0
- package/dist/index-nzfqdhsx.js +11 -0
- package/dist/index-qe3xpt41.js +3 -0
- package/dist/index-qfxwk38p.js +82 -0
- package/dist/index-ss5gez2p.js +2 -0
- package/dist/index-t5cfkz1e.js +4 -0
- package/dist/index-t6p4szqx.js +5 -0
- package/dist/index-tahaxp6n.js +3 -0
- package/dist/index-v16qz1fa.js +3 -0
- package/dist/index-v35k2y31.js +17 -0
- package/dist/index-vtsd74g0.js +9 -0
- package/dist/index-w0m3jm0s.js +408 -0
- package/dist/index-w4jqdhc2.js +5 -0
- package/dist/index-xtd0j8ve.js +3 -0
- package/dist/index-ywnfz6nm.js +3 -0
- package/dist/index.js +3 -3
- package/dist/injections-h25c1fmk.js +2 -0
- package/dist/interactive-vbz68zh5.js +2 -0
- package/dist/key.cmd-f6rjvjy8.js +2 -0
- package/dist/log-shipper-0erbwn0q.js +2 -0
- package/dist/path-utils-r4df8d3w.js +2 -0
- package/dist/plugin-system-zj50tg4k.js +2 -0
- package/dist/prereqs-runner-gca0bytz.js +2 -0
- package/dist/profile-mount-s4mc1x18.js +2 -0
- package/dist/prune-stale-shims-4nqtv0xt.js +2 -0
- package/dist/register-core-vng5hdga.js +2 -0
- package/dist/secondary-profile-attach-pyqqf4ny.js +2 -0
- package/dist/subprocess-4gg77skg.js +2 -0
- package/dist/telemetry-nmtywcba.js +2 -0
- package/dist/tree-sitter-javascript-rfadfcwb.js +2 -0
- package/dist/tree-sitter-markdown-gkyb2qez.js +2 -0
- package/dist/tree-sitter-markdown_inline-xzttqkvb.js +2 -0
- package/dist/tree-sitter-typescript-4z897028.js +2 -0
- package/dist/tree-sitter-zig-y6n7djp6.js +2 -0
- package/dist/tunnel-bootstrap-zwyzxrkt.js +2 -0
- package/package.json +10 -9
- package/dist/agent-config-5b0avmy6.js +0 -2
- package/dist/agent-ready-tracker-ez6r9djg.js +0 -2
- package/dist/app-mhms2gs0.js +0 -2
- package/dist/autostart.cmd-4zb9xhj0.js +0 -2
- package/dist/bootstrap-workspace-t5fyq07m.js +0 -2
- package/dist/bootstrap.service-nxhkrsf1.js +0 -2
- package/dist/bridge-client-bgkr7bcn.js +0 -2
- package/dist/daemon-profile-j2wt35x8.js +0 -2
- package/dist/esm-n9r8p5n2.js +0 -2
- package/dist/finalize-retry-handle-registry-fvm4gm8s.js +0 -2
- package/dist/finalize-retry-worker-wb8wj1yw.js +0 -2
- package/dist/gateway-client-6dqagbg4.js +0 -2
- package/dist/getMachineId-bsd-fgatzdd7.js +0 -2
- package/dist/getMachineId-darwin-gt8j2jw2.js +0 -3
- package/dist/getMachineId-linux-bcz4rr1x.js +0 -2
- package/dist/getMachineId-unsupported-079qwwb4.js +0 -2
- package/dist/getMachineId-win-2hk4e8bg.js +0 -2
- package/dist/highlights-0gfz787m.js +0 -2
- package/dist/highlights-86sbx76f.js +0 -2
- package/dist/highlights-n55f5jnk.js +0 -2
- package/dist/highlights-tbmszdr7.js +0 -2
- package/dist/highlights-wm2cs773.js +0 -2
- package/dist/index-06es0fmw.js +0 -10
- package/dist/index-0d4wfjbt.js +0 -171
- package/dist/index-29fmptfn.js +0 -13
- package/dist/index-2q2jadag.js +0 -11
- package/dist/index-2sn36kaj.js +0 -7
- package/dist/index-3p4n7nwg.js +0 -83
- package/dist/index-3tf12pw3.js +0 -3
- package/dist/index-54mmh1eb.js +0 -4
- package/dist/index-6jzsthh9.js +0 -3
- package/dist/index-7wejfjj9.js +0 -5
- package/dist/index-8q19ryt2.js +0 -28
- package/dist/index-8xh8m2z7.js +0 -8
- package/dist/index-98gr644s.js +0 -116
- package/dist/index-a8n6s2ae.js +0 -2
- package/dist/index-b16y8wyz.js +0 -15
- package/dist/index-bv1z3fxw.js +0 -3
- package/dist/index-cs78wq6y.js +0 -3
- package/dist/index-df19rrbe.js +0 -5
- package/dist/index-dx9hjdp4.js +0 -178
- package/dist/index-ea42kfvk.js +0 -5
- package/dist/index-ekr40gvh.js +0 -3
- package/dist/index-evnbrmdf.js +0 -4
- package/dist/index-f2asckf0.js +0 -26
- package/dist/index-ggxs7nwz.js +0 -3
- package/dist/index-gz5t0vvc.js +0 -4
- package/dist/index-hey6w5m0.js +0 -3
- package/dist/index-hp8jrj6j.js +0 -3
- package/dist/index-hrfkzecw.js +0 -3
- package/dist/index-hwpmdq5z.js +0 -4
- package/dist/index-hz5cy6vz.js +0 -11
- package/dist/index-jbxh0ffn.js +0 -407
- package/dist/index-js2r0men.js +0 -9
- package/dist/index-k3jkzj3k.js +0 -9
- package/dist/index-kteawn2b.js +0 -3
- package/dist/index-mbhq916m.js +0 -3
- package/dist/index-mxc61yr1.js +0 -3
- package/dist/index-qdbxvcwr.js +0 -17
- package/dist/index-qqq9qyy6.js +0 -21
- package/dist/index-rmh8pff5.js +0 -3
- package/dist/index-sspydg85.js +0 -15
- package/dist/index-tk81f249.js +0 -3
- package/dist/index-vjdg5qb2.js +0 -2
- package/dist/index-vkrf8kzp.js +0 -158
- package/dist/index-vnxqna70.js +0 -16
- package/dist/index-w7gctzhm.js +0 -83
- package/dist/index-wj5hx7gq.js +0 -4
- package/dist/index-x4eaagvr.js +0 -3
- package/dist/index-xjr60th0.js +0 -3
- package/dist/index-xtbppqnv.js +0 -3
- package/dist/index-y42xsgr6.js +0 -133
- package/dist/index-zr9rmjyp.js +0 -3
- package/dist/injections-2g0zh0bq.js +0 -2
- package/dist/interactive-08vyaapn.js +0 -2
- package/dist/key.cmd-642xcxb4.js +0 -2
- package/dist/log-shipper-9xfnjwr6.js +0 -2
- package/dist/path-utils-g449hqvm.js +0 -2
- package/dist/plugin-system-gpzcch00.js +0 -2
- package/dist/prereqs-runner-re9f51fp.js +0 -2
- package/dist/profile-mount-txvgkaz8.js +0 -2
- package/dist/prune-stale-shims-vs6a07tb.js +0 -2
- package/dist/register-core-ma4kse87.js +0 -2
- package/dist/secondary-profile-attach-m9x9e7py.js +0 -2
- package/dist/subprocess-zcgpccp1.js +0 -2
- package/dist/telemetry-k6em3vy2.js +0 -2
- package/dist/tree-sitter-javascript-qh90w7td.js +0 -2
- package/dist/tree-sitter-markdown-favzteb6.js +0 -2
- package/dist/tree-sitter-markdown_inline-x2726t9j.js +0 -2
- package/dist/tree-sitter-typescript-m7ep8z1h.js +0 -2
- package/dist/tree-sitter-zig-3vsxg5wh.js +0 -2
- package/dist/tunnel-bootstrap-y8dczezc.js +0 -2
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{r,E}from"./index-w0m3jm0s.js";import{Jt,Wt,bt}from"./index-4527yp1c.js";import{ri,Ki,Qi,St,z,Vt,fr,T,ue,rt,Ct,Fe,Yt,R,O,I,ee,C,se,Tt,B,N,e,it}from"./index-0qjbnyg4.js";import{ht,W}from"./index-g08z6z5v.js";import{ar,be,Ar,Nt,Ke,Ur,we,Pi,de,mt,Xe,ze,qe,K,k,V,ur,Di,Ni,Li}from"./index-mmx2kp76.js";import{pe,Vr,et,Zr,w,Jr,M,Gt,X,$t,Wr,Xr,zr,ei}from"./index-kwhx023z.js";import{sr,Oi,or,Bi,Ue,ge,Nr,Lr,kr,pt,vr}from"./index-qfxwk38p.js";import{He,te,rr,Rr,ir,at,Ve,At,Fr,Ye,Ne,Rt,Ze,Le,Je,We,ct,ut,lt,gt,dt,Ft,Ot,Bt,me}from"./index-v35k2y31.js";import{_r,yr}from"./index-tahaxp6n.js";import{oe}from"./index-jnxjjx2y.js";import{Ir}from"./index-2vcxt38h.js";import{Ge,Cr,gi,Be}from"./index-c4whjk5r.js";import{D}from"./index-75hk5q9s.js";import{Te,Ee,Br,xi,ke}from"./index-gnb8xw13.js";import{b}from"./index-w4jqdhc2.js";import{L}from"./index-b3v08awy.js";import{P}from"./index-a0vx2zyx.js";var Dr=typeof new Headers()?.toJSON==="function",Xn=(t)=>{if(Dr)return Object.keys(t.toJSON()).join(", ");let n="",o=0;return t.forEach((s,i)=>{if(o)n=n+", "+i;else n=i;o++}),n},Mr=(t)=>{let{aot:n=!0,origin:o=!0,methods:s=!0,allowedHeaders:i=!0,exposeHeaders:a=!0,credentials:l=!0,maxAge:c=5,preflight:u=!0}=t??{};if(Array.isArray(i))i=i.join(", ");if(Array.isArray(a))a=a.join(", ");let f=typeof o==="boolean"?void 0:Array.isArray(o)?o:[o],m=new E({name:"@elysiajs/cors",seed:t,aot:n}),_=f?.some((G)=>G==="*"),q={};if(f){for(let G of f)if(typeof G==="string")q[G]=!0}let Z=(G,x,p)=>{if(Array.isArray(G))return G.some((j)=>Z(j,x,p));switch(typeof G){case"string":if(p in q)return!0;let j=p.indexOf("://");if(j!==-1)p=p.slice(j+3);return G===p;case"function":return G(x)===!0;case"object":if(G instanceof RegExp)return G.test(p)}return!1},g=(G,x)=>{if(o===!0){G.headers.vary="*",G.headers["access-control-allow-origin"]=x.headers.get("Origin")||"*";return}if(_){G.headers.vary="*",G.headers["access-control-allow-origin"]="*";return}if(!f?.length)return;if(f.length){let p=x.headers.get("Origin")??"";for(let j=0;j<f.length;j++)if(Z(f[j],x,p)===!0){G.headers.vary=o?"Origin":"*",G.headers["access-control-allow-origin"]=p||"*";return}}G.headers.vary="Origin"},S=(G,x)=>{if(!x)return;if(s===!0)return G.headers["access-control-allow-methods"]=x??"*";if(s===!1||!s?.length)return;if(s==="*")return G.headers["access-control-allow-methods"]="*";if(!Array.isArray(s))return G.headers["access-control-allow-methods"]=s;G.headers["access-control-allow-methods"]=s.join(", ")},A={};if(typeof a==="string")A["access-control-expose-headers"]=a;if(typeof i==="string")A["access-control-allow-headers"]=i;if(l===!0)A["access-control-allow-credentials"]="true";m.headers(A);function ne({set:G,request:x,headers:p}){if(g(G,x),S(G,x.headers.get("access-control-request-method")),i===!0||a===!0){if(i===!0)G.headers["access-control-allow-headers"]=p["access-control-request-headers"];if(a===!0)G.headers["access-control-expose-headers"]=Object.keys(p).join(",")}if(c)G.headers["access-control-max-age"]=c.toString();return new Response(null,{status:204})}if(u)m.options("/",ne).options("/*",ne);return m.onRequest(function({set:x,request:p}){if(g(x,p),u&&p.method==="OPTIONS")return ne({set:x,request:p,headers:Dr?p.headers.toJSON():Object.fromEntries(p.headers.entries())});if(S(x,p.method),i===!0||a===!0){let j=Xn(p.headers);if(i===!0)x.headers["access-control-allow-headers"]=j;if(a===!0)x.headers["access-control-expose-headers"]=j}})};var Qn="/code-server";function $r(t,n,o=we){let s=t.method.toUpperCase();if(s!=="GET"&&s!=="HEAD")return null;let i=new URL(t.url),a=i.searchParams.get("vt");if(!a||!o(a,Qn,"GET"))return null;i.searchParams.delete("vt");let l=new Headers(t.headers);return l.set("x-agent-api-key",n()),new Request(`${i.origin}${i.pathname}${i.search}`,{method:t.method,headers:l})}import{createHash as jr}from"crypto";var _e="idempotency",Zn=300000,Gr=1e4,It=new Map;function eo(t,n,o,s){return jr("sha256").update(`${t}|${n}|${o}|${s}`).digest("hex")}async function to(t,n){let o=await t.getPluginState(_e,n);if(!o)return null;try{let s=JSON.parse(o);if(s.expiresAt<Date.now())return await t.deletePluginState(_e,n),null;return s}catch{return null}}async function ro(t,n,o){await t.setPluginState(_e,n,JSON.stringify(o))}async function no(t){let n=await t.getAllPluginState(_e),o=Date.now(),s=0,i=[];for(let a of n)try{if(JSON.parse(a.value).expiresAt<o)await t.deletePluginState(_e,a.key),s+=1;else i.push({key:a.key,updatedAt:a.updatedAt})}catch{await t.deletePluginState(_e,a.key),s+=1}if(i.length>Gr){i.sort((l,c)=>(l.updatedAt??"").localeCompare(c.updatedAt??""));let a=i.slice(0,i.length-Gr);for(let l of a)await t.deletePluginState(_e,l.key),s+=1}if(s>0)e().logger.info("idempotency",`Swept ${s} expired/over-cap entries`)}var Xt=null,oo=600000;function ao(t){if(Xt)return;Xt=setInterval(()=>{let n=t.getDb();if(!n)return;no(n).catch((o)=>{e().logger.warn("idempotency","Sweep failed",{error:String(o)})})},oo),Xt.unref?.()}function Hr(t){return ao(t),new E({name:"plugin/idempotency"}).onBeforeHandle(async({request:n,path:o,set:s,store:i})=>{if(n.method!=="POST"&&n.method!=="PUT")return;let a=n.headers.get("x-idempotency-key")??n.headers.get("X-Idempotency-Key");if(!a)return;if(a.length<8||a.length>200)return s.status=400,{error:"X-Idempotency-Key must be 8\u2013200 chars",code:"BAD_REQUEST"};let l=t.getDb();if(!l)return;let c="no-body";try{let S=await n.clone().text();c=jr("sha256").update(S).digest("hex")}catch{}let u=eo(n.method,o,a,c),f=await to(l,u);if(f){s.status=f.status;let g=s.headers??={};g["Content-Type"]=f.contentType,g["X-Idempotency-Replay"]="true",i.__idemReplay=f.body;try{return JSON.parse(f.body)}catch{return f.body}}let m=It.get(u);if(m){let g=await m.catch(()=>null);if(g){s.status=g.status;let S=s.headers??={};S["Content-Type"]=g.contentType,S["X-Idempotency-Replay"]="true",i.__idemReplay=g.body;try{return JSON.parse(g.body)}catch{return g.body}}}let _,q,Z=new Promise((g,S)=>{_=g,q=S});It.set(u,Z),i.__idemKey=u,i.__idemResolve=_,i.__idemReject=q}).onAfterHandle(async({response:n,set:o,store:s})=>{let i=s.__idemKey;if(!i)return;let a=s.__idemResolve,l=t.getDb(),c=o.status??200,u=typeof n==="string"?n:JSON.stringify(n),m=o.headers?.["Content-Type"]??"application/json",_={status:c,body:u,contentType:m,expiresAt:Date.now()+Zn},q=c>=200&&c<300;try{if(l&&q)await ro(l,i,_)}catch(Z){e().logger.warn("idempotency","Failed to persist response",{error:String(Z)})}finally{try{a?.(q?_:null)}catch{}It.delete(i)}}).onError(({store:n})=>{let o=n.__idemKey;if(!o)return;let s=n.__idemReject;try{s?.(Error("idempotency: handler errored"))}catch{}It.delete(o)}).as("global")}import fe from"os";import{readFileSync as bo}from"fs";import{join as So}from"path";import{randomBytes as io,timingSafeEqual as so}from"crypto";import{chmodSync as lo,existsSync as qr,mkdirSync as co,readFileSync as uo,unlinkSync as go,writeFileSync as po}from"fs";import{dirname as fo,join as mo}from"path";var $e=null;function Kr(){return mo(I(),"pairing-token")}function yo(){return io(32).toString("base64url")}function ho(t,n){let o=Buffer.from(t),s=Buffer.from(n);if(o.length!==s.length)return!1;try{return so(o,s)}catch{return!1}}function oi(){if($e)return $e;let t=Kr();try{if(qr(t)){let o=uo(t,"utf8").trim();if(o.length>=32)return $e=o,o}}catch{}let n=yo();try{co(fo(t),{recursive:!0}),po(t,n,{encoding:"utf8"});try{lo(t,384)}catch{}}catch(o){}return $e=n,n}function Qt(t){if(!t)return!1;if(!$e)return!1;return ho(t,$e)}function Zt(){$e=null;try{let t=Kr();if(qr(t))go(t)}catch{}}function er(t){return t["x-pairing-token"]??t["X-Pairing-Token"]??null}var wt=null,yt=null,wo=30000;function tr(t,n={}){if(n.isBootProfile===!1){Yr();return}if(t.globalGatewayUrl)process.env.VIBE_GLOBAL_GATEWAY_URL=t.globalGatewayUrl;if(t.workspaceGatewayUrl)process.env.VIBE_WORKSPACE_GATEWAY_URL=t.workspaceGatewayUrl;if(t.workspaceId)process.env.VIBE_WORKSPACE_ID=t.workspaceId;if(t.organizationId)process.env.VIBE_ORGANIZATION_ID=t.organizationId;Yr()}function Yr(){wt=null}async function Qr(){if(wt&&Date.now()-wt.at<wo)return wt.result;if(yt)return yt;return yt=(async()=>{let t;try{let n=await X({strict:!0}),o=zr(n,{workspaceId:process.env.VIBE_WORKSPACE_ID,globalGatewayUrl:process.env.VIBE_GLOBAL_GATEWAY_URL,workspaceGatewayUrl:process.env.VIBE_WORKSPACE_GATEWAY_URL});t=o?{ok:!1,message:o}:{ok:!0}}catch(n){t={ok:!0,message:`identity check skipped: ${n instanceof Error?n.message:String(n)}`}}return wt={at:Date.now(),result:t},t})().finally(()=>{yt=null}),yt}function nr(){let t=B();return!t||t.name===e().name}function vo(){let t=fe.hostname(),n=fe.platform(),o=fe.arch(),s=new Bun.CryptoHasher("sha256");return s.update(`${t}-${n}-${o}`),s.digest("hex").substring(0,16)}function ko(){for(let t of["..","../.."])try{let n=So(import.meta.dir,t,"package.json"),s=JSON.parse(bo(n,"utf8")).version;if(s)return s}catch{}return"0.0.0"}async function Po(t){let n=[],o=t.getProvider("tunnel");if(o)n.push(o);for(let s of t.listProvidersForType("tunnel")){let i=t.getProviderByName("tunnel",s.pluginName);if(i&&!n.includes(i))n.push(i)}for(let s of n){if(!s.getActiveTunnelUrl)continue;let i=await s.getActiveTunnelUrl();if(i)return i}return null}function en({serviceRegistry:t,runFinalize:n,getDb:o}){let s=ko(),i=vo();return new E({prefix:"/api/agent"}).get("/identity",()=>({hostname:fe.hostname(),platform:fe.platform(),architecture:fe.arch(),agentVersion:s,agentInstanceId:Jr()})).get("/version",()=>({version:s,runtime:"bun",runtimeVersion:typeof Bun<"u"?Bun.version:"unknown"})).get("/api-key",({request:a,set:l})=>{if(Ge(a))return l.status=403,{error:"Forbidden",message:"Browser requests are not permitted on /api/agent/api-key"};let c=k(Object.fromEntries(a.headers.entries()));if(!V(c))return l.status=401,{error:"Unauthorized",message:"Invalid or missing API key"};return{apiKey:K()}}).post("/iframe-token",({body:a,request:l,set:c})=>{let u=k(Object.fromEntries(l.headers.entries()));if(!V(u))return c.status=401,{error:"Unauthorized",message:"Invalid or missing API key"};try{if(Array.isArray(a.pathPrefixes)&&a.pathPrefixes.length>0)return Nt({pathPrefixes:a.pathPrefixes,methods:a.methods},a.ttlSeconds??void 0);if(!a.pathPrefix)return c.status=400,{error:"BadRequest",message:"Provide either pathPrefix (string) or pathPrefixes (string[])"};return Ar(a.pathPrefix,a.ttlSeconds??void 0)}catch(f){return c.status=400,{error:"BadRequest",message:f instanceof Error?f.message:String(f)}}},{body:r.Object({pathPrefix:r.Optional(r.String({minLength:1})),pathPrefixes:r.Optional(r.Array(r.String({minLength:1}),{minItems:1,maxItems:16})),methods:r.Optional(r.Array(r.String({minLength:1}),{minItems:1,maxItems:8})),ttlSeconds:r.Optional(r.Number())})}).post("/terminal-exchange",({body:a,set:l})=>{let{sid:c,token:u}=a;if(!c||!u)return l.status=400,{error:"BadRequest",message:"sid and token required"};if(!be(c))return l.status=400,{error:"BadRequest",message:"invalid sid"};let f=`/terminal/${c}`,m=Ur(u,f);if(!m.ok)return e().logger.warn("terminal-exchange","iframe token rejected",{sid:c,reason:m.reason}),l.status=401,{error:"Unauthorized",message:"invalid iframe token",code:m.reason==="expired"?"expired":m.reason==="replayed"?"replayed":"invalid"};let _=Pi(c,600),q=`vt_term_${c}`;return l.headers["set-cookie"]=`${q}=${_.token}; HttpOnly; Secure; SameSite=None; Path=/terminal/${c}; Max-Age=600`,l.status=204,null},{body:r.Object({sid:r.String({minLength:1}),token:r.String({minLength:1})})}).post("/ui-exchange",({body:a,set:l})=>{let{plugin:c,token:u}=a;if(!c||!u)return l.status=400,{error:"BadRequest",message:"plugin and token required"};if(!de(c))return l.status=400,{error:"BadRequest",message:"invalid plugin name"};let f=`/ui/${c}`;if(!Ke(u,f))return l.status=401,{error:"Unauthorized",message:"invalid iframe token"};let m=mt(c,600),_=`vt_ui_${c}`;return l.headers["set-cookie"]=`${_}=${m.token}; HttpOnly; Secure; SameSite=None; Path=/ui/${c}/; Max-Age=600`,l.status=204,null},{body:r.Object({plugin:r.String({minLength:1}),token:r.String({minLength:1})})}).post("/ui-exchange-plugin",({body:a,set:l})=>{let{plugin:c,token:u}=a;if(!c||!u)return l.status=400,{error:"BadRequest",message:"plugin and token required"};if(!de(c))return l.status=400,{error:"BadRequest",message:"invalid plugin name"};if(![`/api/plugins/${c}/ui`,`/${c}`].find((Z)=>Ke(u,Z)))return l.status=401,{error:"Unauthorized",message:"invalid iframe token"};let _=mt(c,600),q=`vt_ui_${c}`;return l.headers["set-cookie"]=`${q}=${_.token}; HttpOnly; Secure; SameSite=None; Path=/api/plugins/${c}/ui/; Max-Age=600`,l.status=204,null},{body:r.Object({plugin:r.String({minLength:1}),token:r.String({minLength:1})})}).get("/system",({request:a,set:l})=>{let c=k(Object.fromEntries(a.headers.entries()));if(!V(c))return l.status=401,{error:"Unauthorized",message:"Invalid or missing API key"};return{machineId:i,hostname:fe.hostname(),platform:fe.platform(),arch:fe.arch(),release:fe.release(),cpus:fe.cpus().length,totalMemory:fe.totalmem(),freeMemory:fe.freemem(),uptime:fe.uptime(),bunVersion:typeof Bun<"u"?Bun.version:void 0,agentVersion:s,homeDir:fe.homedir(),cwd:process.cwd(),environment:"production"}}).get("/tunnel",async({request:a,set:l})=>{let c=Object.fromEntries(a.headers.entries()),u=V(k(c)),f=Qt(er(c));if(!u&&!f)return l.status=401,{error:"Unauthorized",message:"Provide x-agent-api-key OR x-pairing-token to read tunnel URL"};let m=await Po(t);if(!m)return{tunnelUrl:null,message:"No tunnel provider registered"};return{tunnelUrl:m}}).get("/status",()=>{let a=["tunnel","session","ai"].filter((l)=>t.hasProvider(l));return{state:e().getBootState(),status:e().getBootState(),version:s,providers:a,timestamp:new Date().toISOString()}}).get("/gateway-auth",()=>({configured:T.isConfigured(),config:L(T.getConfig()),state:e().getBootState()})).post("/retry-config",async({set:a})=>{let{getFinalizeRetryHandle:l}=await import("./finalize-retry-handle-registry-z9mbbjmj.js"),c=l();if(!c)return a.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 u=await c.forceRetryNow();if(!u.ok)a.status=503;return{ok:u.ok,error:u.ok?void 0:u.error,state:e().getBootState(),worker:c.getState()}}).post("/gateway-auth",async({body:a,request:l,set:c})=>{let u=e().getBootState(),f=Object.fromEntries(l.headers.entries());if(u==="ready"){let p=k(f);if(!V(p))return c.status=401,{success:!1,state:u,error:"Unauthorized: API key required to reconfigure"}}else{let p=k(f),j=er(f),J=V(p),re=Qt(j);if(!J&&!re)return c.status=401,{success:!1,state:u,error:"Unauthorized: provide x-agent-api-key OR x-pairing-token for bootstrap"}}let{clientId:m,clientSecret:_,workspaceId:q,globalGatewayUrl:Z,workspaceGatewayUrl:g}=a;if(!m||!_||!q||!Z||!g)return c.status=400,{success:!1,state:e().getBootState(),error:"clientId, clientSecret, workspaceId, globalGatewayUrl, and workspaceGatewayUrl are required"};let S,A;try{S=z(Z,"globalGatewayUrl"),A=z(g,"workspaceGatewayUrl")}catch(p){return c.status=400,{success:!1,state:e().getBootState(),error:p instanceof Error?p.message:String(p)}}let ne,G=await ue("gateway-auth:push",async()=>{let p=B()??e();{let J;try{J=await X({dir:p.dataDir,scope:p.name,strict:!0})}catch(le){let Ce=le instanceof Error?le.message:String(le);return e().logger.error("preconfig","Could not read existing credentials \u2014 refusing the push rather than risk overwriting a live pairing",{error:Ce}),c.status=503,{success:!1,state:e().getBootState(),error:`Cannot verify this agent's current pairing (secrets backend unavailable: ${Ce}). Refusing the credential push so a live pairing is not overwritten. Retry once the secrets backend recovers.`,code:"IDENTITY_CHECK_UNAVAILABLE"}}let re=Wr(J,{workspaceId:q,globalGatewayUrl:S,workspaceGatewayUrl:A});if(re&&a.force!==!0)return e().logger.warn("preconfig","Rejected a gateway-auth push that would hijack this agent's identity",{conflict:re}),c.status=409,{success:!1,state:e().getBootState(),error:re,code:"GATEWAY_IDENTITY_CONFLICT"};if(re)e().logger.warn("preconfig","Forced re-pair \u2014 overwriting an existing gateway identity",{conflict:re})}let j=null;{let J=nr()?pe():p.name,re;try{re=Vr(J)}catch(ye){let xe=ye instanceof Error?ye.message:String(ye);return e().logger.error("preconfig",`Could not read profile "${J}" \u2014 refusing the push rather than assume it declares nothing`,{error:xe}),c.status=503,{success:!1,state:e().getBootState(),error:`Cannot read profile "${J}" to verify this push targets the right environment (${xe}). Refusing the credential push so a foreign environment is not accepted by default. Repair or remove the profile file and retry.`,code:"PROFILE_CHECK_UNAVAILABLE"}}let le=ei(),Ce={globalGatewayUrl:le.globalGatewayUrl??re.globalGatewayUrl,workspaceGatewayUrl:le.workspaceGatewayUrl??re.workspaceGatewayUrl},ae=Xr(Ce,{workspaceId:q,globalGatewayUrl:S,workspaceGatewayUrl:A},J);if(ae&&a.force!==!0)return e().logger.warn("preconfig","Rejected a gateway-auth push that contradicts the active profile",{profileConflict:ae}),c.status=409,{success:!1,state:e().getBootState(),error:ae,code:"PROFILE_ENVIRONMENT_CONFLICT"};if(ae)j={name:J,cfg:{...re,globalGatewayUrl:S,workspaceGatewayUrl:A,workspaceId:void 0}},e().logger.warn("preconfig",`Forced repoint accepted \u2014 profile "${J}" will be updated to match the pushed environment`,{profileConflict:ae})}try{await Gt({clientId:m,clientSecret:_,workspaceId:q,ownerUserId:a.ownerUserId,organizationId:a.organizationId,globalGatewayUrl:S,workspaceGatewayUrl:A,agentRecordId:a.agentRecordId,scopes:a.scopes,pairedIdentity:$t({workspaceId:q,globalGatewayUrl:S,workspaceGatewayUrl:A,agentRecordId:a.agentRecordId}),...a.storageAdapter?{storageAdapter:a.storageAdapter}:{},...a.storageOptions?{storageOptions:a.storageOptions}:{},...a.dbPath?{dbPath:a.dbPath}:{}},{dir:p.dataDir,scope:p.name})}catch(J){return c.status=500,{success:!1,state:e().getBootState(),error:`Failed to persist gateway credentials to secrets backend: ${J instanceof Error?J.message:String(J)}`}}if(j)try{et(j.name,j.cfg),e().logger.warn("preconfig",`Profile "${j.name}" repointed to the pushed environment`)}catch(J){let re=J instanceof Error?J.message:String(J);ne=`Credentials were accepted, but profile "${j.name}" could not be updated (${re}). It still describes the previous environment \u2014 `+"run `vibe profile use` / fix the profile file so config and profile agree.",e().logger.error("preconfig",`Forced repoint accepted but profile "${j.name}" could not be updated \u2014 profile and config.json now disagree`,{error:re})}return null});if(G)return G;let x=e().getBootState();if(x==="ready"){let p=o();if(p){if(await p.setConfig("gateway-auth:clientId",m),await p.setConfig("gateway-auth:clientSecret",_),await p.setConfig("gateway-auth:workspaceId",q),a.organizationId)await p.setConfig("gateway-auth:organizationId",a.organizationId);if(await p.setConfig("gateway-auth:globalGatewayUrl",S),await p.setConfig("gateway-auth:workspaceGatewayUrl",A),a.agentRecordId)await p.setConfig("gateway-auth:agentRecordId",a.agentRecordId)}T.configure({globalGatewayUrl:S,workspaceGatewayUrl:A,clientId:m,clientSecret:_,workspaceId:q,organizationId:a.organizationId}),tr({workspaceId:q,organizationId:a.organizationId,globalGatewayUrl:S,workspaceGatewayUrl:A},{isBootProfile:nr()}),e().logger.info("preconfig","Gateway credentials re-configured (agent was already ready)");let j=!!(a.storageAdapter||a.storageOptions||a.dbPath);return{success:!0,state:x,message:j?"Gateway auth re-configured. Restart the agent (vibe restart) to apply the new storage configuration.":"Gateway auth re-configured",...ne?{warning:ne}:{}}}return e().logger.info("preconfig","Gateway credentials received \u2014 beginning finalize (background)"),Zt(),tr({workspaceId:q,organizationId:a.organizationId,globalGatewayUrl:S,workspaceGatewayUrl:A},{isBootProfile:nr()}),n({clientId:m,clientSecret:_,workspaceId:q,organizationId:a.organizationId,globalGatewayUrl:S,workspaceGatewayUrl:A},{agentRecordId:a.agentRecordId,scopes:a.scopes}).catch((p)=>{e().logger.error("preconfig","Background finalize threw",{error:p instanceof Error?p.message:String(p)})}),c.status=202,{success:!0,state:e().getBootState(),agentRecordId:a.agentRecordId,message:"Gateway credentials accepted; finalize is running in the background. Poll /health/ready for completion.",...ne?{warning:ne}:{}}},{body:r.Object({clientId:r.Optional(r.String()),clientSecret:r.Optional(r.String()),workspaceId:r.Optional(r.String()),ownerUserId:r.Optional(r.String()),organizationId:r.Optional(r.String()),globalGatewayUrl:r.Optional(r.String()),workspaceGatewayUrl:r.Optional(r.String()),scopes:r.Optional(r.Array(r.String())),agentRecordId:r.Optional(r.String()),storageAdapter:r.Optional(r.String()),storageOptions:r.Optional(r.Record(r.String(),r.String())),dbPath:r.Optional(r.String()),force:r.Optional(r.Boolean())})})}import{existsSync as Ie,mkdirSync as Ro,rmSync as tn,readdirSync as nn}from"fs";import{join as Et}from"path";function Pe(t){return Et(C(),"agents",O(t))}function Ao(){let t=Et(C(),"agents");if(!Ie(t))return[];return nn(t,{withFileTypes:!0}).filter((n)=>n.isDirectory()).map((n)=>n.name).filter((n)=>/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(n))}function on(t){return Et(C(),"agents",O(t))}function lr(t){return w({dir:on(t)})}function rn(t,n){return M(n,{dir:on(t),scope:O(t)})}function tt(t){let n=Fe(),o=Ct().find((a)=>a.name===t),s=N.get(t),i={name:t,isDefault:t===n,isRunning:o?.status==="running",attached:s!==void 0,bootState:s?s.getBootState():null,dataDir:s?s.dataDir:null};if(o)i.port=o.port,i.pid=o.pid,i.startTime=o.startTime;if(Ie(Pe(t)))i.config=L(lr(t));return i}function an(t={}){let n=t.serviceManagerFactory?t.serviceManagerFactory():new D;return new E({prefix:"/api/profiles"}).get("/",()=>{let o=Ao(),s=Fe(),i=new Set(o);return i.add(s),[...i].sort().map((a)=>tt(a))}).post("/",async({body:o,set:s})=>{try{let i=O(o.name),a=Pe(i);if(Ie(a))return s.status=409,{error:"exists",message:`Profile '${i}' already exists.`};let l;if(o.copyFrom){let c=O(o.copyFrom);if(!Ie(Pe(c)))return s.status=400,{error:"copy-source-missing",message:`Profile '${c}' does not exist.`};l=lr(c),delete l["static-api-key"],delete l.agentRecordId,delete l.apiKeys,delete l.pairedIdentity,delete l.workspaceId,delete l.organizationId}else l=Zr();if(o.gatewayUrl)l.globalGatewayUrl=o.gatewayUrl;if(o.workspaceGatewayUrl)l.workspaceGatewayUrl=o.workspaceGatewayUrl;if(o.clientId)l.clientId=o.clientId;if(o.clientSecret)l.clientSecret=o.clientSecret;if(o.workspaceId)l.workspaceId=o.workspaceId;if(o.organizationId)l.organizationId=o.organizationId;Ro(a,{recursive:!0}),rn(i,l);try{it(i)}catch(c){e().logger.warn("profile-mgmt",`In-process attach failed for '${i}'`,{error:String(c)})}if(e().logger.info("profile-mgmt",`Created profile '${i}' at ${a}`),o.start){let c={name:i,port:o.port??0,daemon:!0,dbPath:ee(),profile:i};await n.startDaemon(c)}return s.status=201,tt(i)}catch(i){return s.status=400,{error:"create-failed",message:i instanceof Error?i.message:String(i)}}},{body:r.Object({name:r.String(),gatewayUrl:r.Optional(r.String()),workspaceGatewayUrl:r.Optional(r.String()),clientId:r.Optional(r.String()),clientSecret:r.Optional(r.String()),workspaceId:r.Optional(r.String()),organizationId:r.Optional(r.String()),copyFrom:r.Optional(r.String()),start:r.Optional(r.Boolean()),port:r.Optional(r.Number())})}).get("/:name",({params:o,set:s})=>{try{let i=O(o.name);if(!Ie(Pe(i)))return s.status=404,{error:"not-found",message:`No profile '${i}'.`};return tt(i)}catch(i){return s.status=400,{error:"bad-request",message:i instanceof Error?i.message:String(i)}}},{params:r.Object({name:r.String()})}).put("/:name",({params:o,body:s,set:i})=>{try{let a=O(o.name);if(!Ie(Pe(a)))return i.status=404,{error:"not-found",message:`No profile '${a}'.`};let l=["static-api-key","apiKeys","agentRecordId","pairedIdentity"];for(let f of l)if(f in s)return i.status=400,{error:"forbidden-field",message:`Field '${f}' is managed via dedicated commands (vibe key rotate / vibe profile create). It cannot be patched here.`};if("registry"in s)return i.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 u={...lr(a),...s};return rn(a,u),tt(a)}catch(a){return i.status=400,{error:"update-failed",message:a instanceof Error?a.message:String(a)}}},{params:r.Object({name:r.String()}),body:r.Record(r.String(),r.Any())}).delete("/:name",async({params:o,body:s,query:i,set:a})=>{try{let l=O(o.name);if(l===Fe())return a.status=409,{error:"is-default",message:`Cannot delete active default profile '${l}'. Switch to another profile first.`};let c=i?.purge==="true"||i?.purge==="1",u=Ie(Pe(l)),f=N.has(l);if(!u&&!f)return a.status=404,{error:"not-found",message:`No profile '${l}'.`};if(u&&!c&&!s?.confirm)return a.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 n.stop(l)}catch{}try{await N.destroy(l)}catch(m){e().logger.warn("profile-mgmt",`In-process detach failed for '${l}'`,{error:String(m)})}if(u)if(s?.keepConfig)for(let m of nn(Pe(l))){if(m==="config.json")continue;tn(Et(Pe(l),m),{recursive:!0,force:!0})}else tn(Pe(l),{recursive:!0,force:!0});return e().logger.info("profile-mgmt",`Deleted profile '${l}'`),{ok:!0,deleted:l,keptConfig:!!s?.keepConfig,detached:f,purged:u}}catch(l){return a.status=400,{error:"delete-failed",message:l instanceof Error?l.message:String(l)}}},{params:r.Object({name:r.String()}),query:r.Optional(r.Object({purge:r.Optional(r.String())})),body:r.Optional(r.Object({confirm:r.Optional(r.Boolean()),keepConfig:r.Optional(r.Boolean())}))}).post("/:name/switch",async({params:o,set:s})=>{try{let i=O(o.name);if(!Ie(Pe(i)))return s.status=404,{error:"not-found",message:`No profile '${i}'.`};return await rt(()=>Yt(i)),e().logger.info("profile-mgmt",`Default profile switched to '${i}'`),{ok:!0,defaultProfile:i}}catch(i){return s.status=400,{error:"switch-failed",message:i instanceof Error?i.message:String(i)}}},{params:r.Object({name:r.String()})}).post("/:name/start",async({params:o,body:s,set:i})=>{try{let a=O(o.name);if(!Ie(Pe(a)))return i.status=404,{error:"not-found",message:`No profile '${a}'.`};try{it(a)}catch(c){e().logger.warn("profile-mgmt",`In-process attach failed for '${a}'`,{error:String(c)})}if(!Ct().some((c)=>c.name===a&&c.status==="running")){let c={name:a,port:s?.port??0,daemon:!0,dbPath:ee(),profile:a};await n.startDaemon(c)}return tt(a)}catch(a){return i.status=500,{error:"start-failed",message:a instanceof Error?a.message:String(a)}}},{params:r.Object({name:r.String()}),body:r.Optional(r.Object({port:r.Optional(r.Number())}))}).post("/:name/stop",async({params:o,set:s})=>{try{let i=O(o.name);try{await n.stop(i)}catch{}try{await N.destroy(i)}catch(a){e().logger.warn("profile-mgmt",`In-process detach failed for '${i}'`,{error:String(a)})}return tt(i)}catch(i){return s.status=500,{error:"stop-failed",message:i instanceof Error?i.message:String(i)}}},{params:r.Object({name:r.String()})})}function Io(){let t=process.memoryUsage(),n=process.resourceUsage(),o=n.userCPUTime/1000,s=n.systemCPUTime/1000,i=o+s,a=N.list().map((l)=>{let c;try{c=yr(l.spawnOwnerKey).length}catch{c=0}return{name:l.name,status:l.getBootState(),childPidCount:c,cpuMs:i,heapBytes:t.heapUsed,dataDir:l.dataDir}});return{process:{pid:process.pid,uptimeSeconds:process.uptime(),cpuUserMs:o,cpuSystemMs:s,heapUsedBytes:t.heapUsed,heapTotalBytes:t.heapTotal,rssBytes:t.rss},profiles:a,notes:{perProfileCpu:"deferred",perProfileHeap:"deferred"}}}function sn(){return new E({prefix:"/api/profile-stats"}).get("/",()=>Io())}function vt(t,n){return Promise.race([t,new Promise((o,s)=>setTimeout(()=>s(Error(`timeout after ${n}ms`)),n))])}function Eo(t){let n=t instanceof Error?t.message:String(t);return/ENOENT/.test(n)||/no such file or directory/i.test(n)}async function ln(t){let o=`__health__:probe:${typeof crypto<"u"&&typeof crypto.randomUUID==="function"?crypto.randomUUID():`${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`}`,s=String(Date.now());if(await vt(t.setConfig(o,s),2000),await vt(t.getConfig(o),2000)!==s)throw Error("round-trip mismatch");try{await vt(t.deleteConfig(o),500)}catch{}}async function Oo(t,n){if(!t)return{ok:!1,message:"database not opened"};let o=performance.now();try{return await ln(t),{ok:!0,durationMs:performance.now()-o}}catch(s){if(n&&Eo(s))try{let i=await import("fs");return i.mkdirSync(n,{recursive:!0}),await ln(t),{ok:!0,message:`recovered: dbPath ${n} was missing \u2014 recreated`,durationMs:performance.now()-o}}catch(i){return{ok:!1,message:`ENOENT on dbPath ${n}: ${i instanceof Error?i.message:String(i)}`,durationMs:performance.now()-o}}return{ok:!1,message:s instanceof Error?s.message:String(s),durationMs:performance.now()-o}}}async function Co(t){if(process.env.AGENT_TUNNEL==="false")return{ok:!0,message:"tunnel disabled via AGENT_TUNNEL=false"};if(!t)return{ok:!1,message:"no service registry"};let n=t.getProvider("tunnel"),o=e().getBootState()==="awaiting-config";if(!n)return{ok:!1,message:o?"agent is awaiting-config \u2014 POST OAuth credentials to /api/agent/gateway-auth to register tunnel provider":"no tunnel provider registered"};if(!n.getActiveTunnelUrl)return{ok:!0,message:`provider: ${n.name}`};try{let s=await vt(Promise.resolve(n.getActiveTunnelUrl()),2000),i=Vt(s);if(i)return{ok:!0,message:`provider: ${n.name} \u2014 ${i}`};if(s)return{ok:!1,message:`provider: ${n.name} \u2014 reported an unusable tunnel URL (${s})`};return{ok:!1,message:`provider: ${n.name} \u2014 no active tunnel (the agent is not reachable from outside; the provider is rebuilding it)`}}catch(s){return{ok:!1,message:`provider: ${n.name} \u2014 tunnel status unavailable: ${s instanceof Error?s.message:String(s)}`}}}function To(t,n){if(!t)return{ok:!1,message:"no service registry"};let s=e().getBootState()==="awaiting-config";if(n==="session"){let i=t.getProvider("session");if(i)return{ok:!0,message:`provider: ${i.name}`};return{ok:!1,message:s?"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 Uo(t){if(!t)return{};let n={};for(let o of t.getAllPlugins()){let s=o.getHealth;if(typeof s!=="function")continue;let i=performance.now();try{let a=await vt(Promise.resolve(s.call(o)),2000);n[o.name]={ok:a?.ok!==!1,message:a?.message,durationMs:performance.now()-i}}catch(a){n[o.name]={ok:!1,message:a instanceof Error?a.message:String(a),durationMs:performance.now()-i}}}return n}function cn(t){let n=t&&"serviceRegistry"in t?t:{serviceRegistry:t};return new E({prefix:"/health"}).get("/",()=>({status:"ok",lifecycleState:n.serviceRegistry?.getService("agent","lifecycle")?.getState()??"running",bootState:e().getBootState(),timestamp:new Date().toISOString(),uptime:process.uptime()})).get("/live",()=>({status:"ok"})).get("/ready",async({set:o})=>{let i=n.serviceRegistry?.getService("agent","lifecycle")?.getState()??"running",a=e().getBootState(),l={};l.boot={ok:a==="ready",message:a==="ready"?void 0:`boot state ${a}`},l.lifecycle={ok:i==="running",message:i==="running"?void 0:`lifecycle ${i}`},l.db=await Oo(n.getDb?.()??null,n.getDbPath?.()??null),l.tunnel=await Co(n.serviceRegistry),l.session=To(n.serviceRegistry,"session"),l.identity=await Qr();try{let{gatewayClient:g}=await import("./gateway-client-ermpz52n.js");if(!g.isConfigured())l.registration={ok:!0,message:"not configured"};else{let S=n.getDb?.()??null;if(S?await S.getConfig("gateway-auth:agentRecordId"):null)l.registration={ok:!0};else{let ne=e().getDegradedReasons().some((G)=>G.plugin==="agent-registration");l.registration=ne?{ok:!1,message:"agent failed to register with the workspace after retries"}:{ok:!0,message:"registering"}}}}catch(g){l.registration={ok:!0,message:`registration check skipped: ${g instanceof Error?g.message:String(g)}`}}let c=await Uo(n.getPluginManager?.()??null),u=Object.values(l).every((g)=>g.ok)&&Object.values(c).every((g)=>g.ok);if(!u)o.status=503;let f=a==="degraded"?e().getDegradedReasons():[],m=e().name,_={};for(let g of N.list())_[g.name]={bootState:g.getBootState(),ok:g.getBootState()==="ready",degradedReasons:g.getDegradedReasons()};let q=e().getLastFinalizeError(),Z={status:u?"ok":"degraded",lifecycleState:i,bootState:a,daemon:{profile:m,bootState:a,ok:a==="ready"},profiles:_,components:l,plugins:c,degradedReasons:f,lastFinalizeError:q,timestamp:new Date().toISOString()};if(!u)e().logger.warn("health","Readiness probe failed",{components:l,plugins:c,bootState:a});return Z})}var Ut=0,un=0;function dn(){return new E({name:"inflight-tracker"}).onRequest(()=>{Ut+=1}).onAfterResponse(()=>{Ut=Math.max(0,Ut-1),un+=1})}function gn(){return new E({prefix:"/api/stats"}).get("/inflight",()=>({inflight:Math.max(0,Ut-1),totalServed:un}))}var pn={enabled:!1,async scrape(){return`# vibecontrols agent metrics disabled (OTel SDK not initialised)
|
|
3
|
+
`},recordHttpRequest(){},setPluginsLoaded(){}},De=null,xt=null;async function Dt(t){if(De)return De;if(xt)return xt;return xt=(async()=>{try{let{MeterProvider:n}=await import("./index-9xrhb68w.js"),{PrometheusExporter:o,PrometheusSerializer:s}=await import("./index-76m37yd8.js").then((m)=>P(m.default,1)),i=new o({preventServerStart:!0}),a=new s,c=new n({readers:[i]}).getMeter("vibecontrols-agent"),u=c.createGauge("vibecontrols_agent_info",{description:"Static info about the agent process; value is always 1."});c.createObservableGauge("vibecontrols_agent_uptime_seconds",{description:"Process uptime in seconds."}).addCallback((g)=>{g.observe(process.uptime())});let m=c.createCounter("vibecontrols_http_requests_total",{description:"Total HTTP requests handled by the agent, labelled by method, route, status."}),_={};c.createObservableGauge("vibecontrols_plugins_loaded",{description:"Plugins loaded by the agent, broken down by status (loaded, failed, etc.)."}).addCallback((g)=>{for(let[S,A]of Object.entries(_))g.observe(A,{status:S})}),u.record(1,{version:t?.version??"unknown",profile:t?.profile??"default"});let Z={enabled:!0,async scrape(){let g=await i.collect();if(!g.resourceMetrics)return"";return a.serialize(g.resourceMetrics)},recordHttpRequest(g,S,A){m.add(1,{method:g,route:S,status:String(A)})},setPluginsLoaded(g){_={...g}}};return De=Z,e().logger.info("metrics","OTel Prometheus registry initialised"),Z}catch(n){return e().logger.warn("metrics","Failed to initialise OTel metrics; /metrics will return a stub body",{error:n instanceof Error?n.message:String(n)}),De=pn,pn}})(),xt}function fn(t,n,o){if(!De)return;De.recordHttpRequest(t,n,o)}function mn(t){if(!De)return;De.setPluginsLoaded(t)}var yn=!1;function xo(){if(yn)return;if(process.env.METRICS_ANONYMOUS_LOCALHOST==="true")yn=!0,e().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 Do(t,n){return Be(t,n)}function hn(){return xo(),new E({name:"routes/metrics"}).get("/metrics",async({request:t,server:n,set:o})=>{if(!(process.env.METRICS_ANONYMOUS_LOCALHOST==="true"&&Do(t,n))){let l=k(Object.fromEntries(t.headers.entries()));if(!V(l))return o.status=401,o.headers["content-type"]="application/json",JSON.stringify({error:"Unauthorized",message:"Invalid or missing API key"})}let a=await(await Dt()).scrape();return o.headers["content-type"]="text/plain; version=0.0.4; charset=utf-8",a})}var cr=Object.freeze(["code","code-insiders","codium","cursor","idea","pycharm","webstorm","goland","phpstorm","rubymine","clion","rider","zed","subl","vim","nvim","emacs","neovide","fleet","helix"]),Mo=new Set(cr),_o=new Set(["--new-window","-n","--reuse-window","-r","--wait","-w","--add","--goto"]);function wn(t){try{return Bun.which(t)??null}catch{return null}}function bn(){return new E({prefix:"/api/editor"}).get("/allowlist",()=>({commands:[...cr]})).get("/detect",async()=>{let t=cr.map((s)=>[s,wn(s)]),n=[],o={};for(let[s,i]of t)if(i)n.push(s),o[s]=i;return{available:n,paths:o}}).post("/open",async({body:t,set:n})=>{let{command:o,path:s,args:i=[]}=t;if(!Mo.has(o))return n.status=400,{ok:!1,error:`Command '${o}' is not in the IDE allowlist`};for(let c of i)if(typeof c!=="string"||!_o.has(c))return n.status=400,{ok:!1,error:`Argument '${c}' is not in the flag allowlist`};let a;try{a=(await oe(s,{mustExist:!0})).realPath}catch(c){return n.status=400,{ok:!1,error:`Invalid path: ${c instanceof Error?c.message:String(c)}`}}let l=wn(o);if(!l)return n.status=404,{ok:!1,error:`'${o}' is not installed or not on PATH on this agent`};try{let c=_r({owner:`editor:${o}`,cmd:[l,...i,a],env:process.env,stdout:"ignore",stderr:"ignore",stdin:"ignore",meta:{command:o,path:a}});return e().logger.info("editor",`Launched ${o} on ${a}`,{pid:c.pid}),e().audit.emit("agent","editor.open",{command:o,path:a,pid:c.pid}),{ok:!0,command:o,resolvedPath:a,pid:c.pid}}catch(c){return n.status=500,{ok:!1,error:`Failed to spawn editor: ${c instanceof Error?c.message:String(c)}`}}},{body:r.Object({command:r.String({minLength:1,maxLength:40}),path:r.String({minLength:1,maxLength:4096}),args:r.Optional(r.Array(r.String({maxLength:32})))})})}function Sn(){return(B()??e()).dataDir}function Se(){let t=w({dir:Sn()});return{ownerUserId:t.ownerUserId,workspaceId:t.workspaceId}}function Mt(){return w({dir:Sn()}).agentRecordId}function vn(t){if(!t)return null;try{return new URL(t).host}catch{return null}}async function kn(t,n){let o=t.getPluginManager(),s=o?o.getPluginDetails().map((c)=>({pluginName:c.pluginName,packageName:c.packageName,version:c.version,tags:c.tags??[]})):[],i=process.memoryUsage(),a=vn(t.getTunnelHost?.()??null),l;try{l=At(Se()).map((c)=>({id:c.id,label:c.label,host:vn(c.tunnelUrl),agentRecordId:c.agentRecordId??null,permissions:c.permissions,canForward:c.permissions.includes("mesh:forward"),lastReachable:c.lastReachable??null}))}catch{l=[]}return{pluginName:"agent",description:"vibecontrols-agent runtime self-report",generatedAt:new Date().toISOString(),data:{profile:n.profile,vibeId:n.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(i.rss/1048576),heapUsedMB:Math.round(i.heapUsed/1048576)}},agent:{version:t.getAgentVersion?.()??null,profileRegistered:R(),tunnelHost:a},plugins:{count:s.length,items:s},mesh:{peerCount:l.length,peers:l}}}}var Bo=2000,Pn=1000;async function $o(t,n){let o,s=new Promise((i,a)=>{o=setTimeout(()=>a(Error(`timeout after ${n}ms`)),n)});try{return await Promise.race([t,s])}finally{if(o)clearTimeout(o)}}async function Rn(t,n){let o=performance.now(),s=t.timeoutMs??Bo;try{let i=await $o(t.getContext(n),s);if(!i.generatedAt)i.generatedAt=new Date().toISOString();return{ok:!0,data:i,durationMs:Math.round(performance.now()-o)}}catch(i){return{ok:!1,error:i.message??String(i),durationMs:Math.round(performance.now()-o)}}}class dr{deps;inflight=new Map;constructor(t){this.deps=t}async aggregate(t){let n=`${t.profile}::${t.vibeId??""}`,o=this.inflight.get(n);if(o&&Date.now()-o.ts<Pn)return o.promise;let s=this.doAggregate(t).finally(()=>{setTimeout(()=>{let i=this.inflight.get(n);if(i&&i.promise===s)this.inflight.delete(n)},Pn).unref?.()});return this.inflight.set(n,{ts:Date.now(),promise:s}),s}async selfContext(t){return kn(this.deps,t)}async pluginContext(t,n){let o=Ir().find((s)=>s.name===t);if(!o)return null;return Rn(o,n)}async pluginsContext(t){let n=Ir(),o=await Promise.allSettled(n.map((i)=>Rn(i,t))),s={};return n.forEach((i,a)=>{let l=o[a];if(l&&l.status==="fulfilled")s[i.name]=l.value;else if(l&&l.status==="rejected")s[i.name]={ok:!1,error:l.reason instanceof Error?l.reason.message:String(l.reason),durationMs:0}}),s}async doAggregate(t){let[n,o]=await Promise.all([this.selfContext(t),this.pluginsContext(t)]);return{agent:n,plugins:o}}}function _t(t){let n=t.vibeId;if(typeof n!=="string")return;let o=n.trim();return o.length>0&&o.length<=128?o:void 0}function An(t){let n=new dr(t);return new E({prefix:"/api/agent/context"}).get("/",async({params:o,query:s})=>{let i=o?.profile??"default",a=_t(s);return n.aggregate({profile:i,vibeId:a})},{query:r.Object({vibeId:r.Optional(r.String())})}).get("/agent",async({params:o,query:s})=>{let i=o?.profile??"default",a=_t(s);return n.selfContext({profile:i,vibeId:a})},{query:r.Object({vibeId:r.Optional(r.String())})}).get("/plugins",async({params:o,query:s})=>{let i=o?.profile??"default",a=_t(s);return n.pluginsContext({profile:i,vibeId:a})},{query:r.Object({vibeId:r.Optional(r.String())})}).get("/plugins/:name",async({params:o,query:s,set:i})=>{let a=o?.profile??"default",l=o?.name;if(!l)return i.status=400,{error:"missing plugin name"};let c=_t(s),u=await n.pluginContext(l,{profile:a,vibeId:c});if(!u)return i.status=404,{error:`no context provider registered under name "${l}"`};return u},{params:r.Object({name:r.String()}),query:r.Object({vibeId:r.Optional(r.String())})})}var Oe="autoupdate",No=86400000,In=300000,Lo=900000,Q={timer:null,running:!1,profile:"default",lastCheckAt:null,lastCheck:null,lastUpdateAt:null,lastUpdate:null,startedAt:null};function gr(){let t=(process.env.VIBE_AUTOUPDATE??"").trim().toLowerCase();return t==="0"||t==="false"||t==="off"||t==="no"}function On(){if(gr())return!1;try{return w().autoUpdate!==!1}catch{return!0}}function pr(){let t=Number(process.env.VIBE_AUTOUPDATE_INTERVAL_MS);if(Number.isFinite(t)&&t>0)return Math.max(Lo,t);return No}async function hr(t){let n=e().logger;if(Q.running)return{check:Q.lastCheck??await En(),update:null};Q.running=!0;try{let o=await Le();if(Q.lastCheck=o,Q.lastCheckAt=new Date().toISOString(),o.error)n.debug(Oe,`Update check failed: ${o.error}`);else if(o.hasUpdate)n.info(Oe,`New agent version available: ${o.current} \u2192 ${o.latest}`);let s=t?.force||On();if(!o.hasUpdate||!s)return{check:o,update:null};n.info(Oe,`Auto-updating ${o.current} \u2192 ${o.latest} (idle-gated restart)\u2026`);let i=await Je({restart:!0,name:Q.profile,onLog:(a)=>n.info(Oe,a)});if(Q.lastUpdate=i,Q.lastUpdateAt=new Date().toISOString(),i.ok&&i.updated)n.info(Oe,`Auto-update applied: now ${i.current} (restart: ${i.restart}).`);else if(!i.ok)n.warn(Oe,`Auto-update failed: ${i.error}`);return{check:o,update:i}}catch(o){return n.warn(Oe,`Auto-update tick threw: ${o instanceof Error?o.message:String(o)}`),{check:await En(),update:null}}finally{Q.running=!1}}async function En(){if(Q.lastCheck)return Q.lastCheck;let t=await Le();return Q.lastCheck=t,Q.lastCheckAt=new Date().toISOString(),t}function Cn(t){if(Q.timer)clearTimeout(Q.timer);Q.timer=setTimeout(()=>{hr().finally(()=>{if(Q.startedAt)Cn(pr())})},t),Q.timer.unref?.()}function mr(t){let n=e().logger;if(Q.profile=t?.profile||process.env.VIBECONTROLS_PROFILE||"default",Q.startedAt=new Date().toISOString(),gr()){n.info(Oe,"Autoupdate disabled via VIBE_AUTOUPDATE \u2014 not scheduling.");return}n.info(Oe,`Autoupdate scheduled (first check in ${Math.round(In/60000)}m, then every ${Math.round(pr()/3600000)}h).`),Cn(In)}function ai(){if(Q.timer)clearTimeout(Q.timer),Q.timer=null;Q.startedAt=null}function Tn(t){if(M({autoUpdate:t}),t&&!Q.startedAt)mr({profile:Q.profile})}function wr(){let t=!0;try{t=w().autoUpdate!==!1}catch{}return{enabled:On(),envKillSwitch:gr(),configEnabled:t,scheduled:!!Q.startedAt,intervalMs:pr(),profile:Q.profile,startedAt:Q.startedAt,lastCheckAt:Q.lastCheckAt,lastCheck:Q.lastCheck,lastUpdateAt:Q.lastUpdateAt,lastUpdate:Q.lastUpdate}}import{existsSync as Un}from"fs";import{join as xn}from"path";var Go=600000,br=1e6;function jo(){let t=b(),n=t.which("bun")??`bun${t.executableSuffix}`,o=xn(import.meta.dir,"cli.js");if(Un(o))return{runner:n,prefix:[o]};let s=xn(import.meta.dir,"..","cli.ts");if(Un(s))return{runner:n,prefix:[s]};let i=t.which("vibe");if(i)return{runner:i,prefix:[]};return null}function Dn(t){if(t.length<=br)return t;return t.slice(0,br)+`
|
|
4
|
+
\u2026[output truncated at ${br} bytes]`}async function Lt(t,n={}){let o=jo();if(!o)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:t,command:"(unresolved)"};let s=[...o.prefix,...t],i=[o.runner,...s].join(" ");try{let a=Bun.spawn([o.runner,...s],{cwd:n.cwd,env:{...process.env,VIBE_AUTO_ACCEPT:"1",CI:"1",NO_COLOR:"1",...n.env},stdout:"pipe",stderr:"pipe"}),l=n.timeoutMs??Go,c=!1,u=setTimeout(()=>{c=!0;try{a.kill()}catch{}},l),[f,m,_]=await Promise.all([new Response(a.stdout).text(),new Response(a.stderr).text(),a.exited]);return clearTimeout(u),{ok:!c&&_===0,exitCode:_,stdout:Dn(f),stderr:Dn(m),timedOut:c,argv:t,command:i}}catch(a){return{ok:!1,exitCode:null,stdout:"",stderr:`Failed to spawn vibe CLI: ${a instanceof Error?a.message:String(a)}`,timedOut:!1,argv:t,command:i}}}async function Mn(){let{Command:t}=await import("./index-ss5gez2p.js"),{registerCoreCommands:n}=await import("./register-core-vng5hdga.js"),o=new t;o.name("vibe").option("--json").option("--plain").option("-y, --yes").option("-p, --profile <name>");try{n(o)}catch{}let s=new Set(["nuke","kill","gc","stop","rollback","deploy"]),i=[];for(let a of o.commands){let l=a.name();if(!l||l==="help")continue;i.push({name:l,description:a.description()||"",usage:a.usage()||"",options:a.options.map((c)=>({flags:c.flags,description:c.description||""})),group:"core",destructive:s.has(l)})}return i.sort((a,l)=>a.name.localeCompare(l.name))}import{spawn as Fo}from"child_process";import{writeFileSync as Ho,mkdirSync as zo}from"fs";import{tmpdir as Vo}from"os";import{join as _n}from"path";var qo="@vibecontrols/agent";function Bn(t){let n=b(),o=n.which("bun")??`bun${n.executableSuffix}`,s=n.which("npm")??`npm${n.executableSuffix}`,i=se(),a=t.delayMs??3000,l=t.pids.filter((u)=>Number.isInteger(u)&&u>0),c=`// vibecontrols agent self-uninstall reaper (auto-generated)
|
|
5
|
+
const PIDS = ${JSON.stringify(l)};
|
|
6
|
+
const NPM = ${JSON.stringify(s)};
|
|
7
|
+
const BUN = ${JSON.stringify(o)};
|
|
8
|
+
const REGISTRY = ${JSON.stringify(i)};
|
|
9
|
+
const PKG = ${JSON.stringify(qo)};
|
|
10
|
+
await Bun.sleep(${a});
|
|
11
|
+
for (const pid of PIDS) {
|
|
12
|
+
try { process.kill(pid, "SIGTERM"); } catch {}
|
|
13
|
+
}
|
|
14
|
+
await Bun.sleep(2500);
|
|
15
|
+
for (const pid of PIDS) {
|
|
16
|
+
try { process.kill(pid, "SIGKILL"); } catch {}
|
|
17
|
+
}
|
|
18
|
+
try { Bun.spawnSync([NPM, "uninstall", "-g", PKG, "--registry=" + REGISTRY], { stdout: "inherit", stderr: "inherit" }); } catch {}
|
|
19
|
+
try { Bun.spawnSync([BUN, "remove", "-g", PKG], { stdout: "inherit", stderr: "inherit" }); } catch {}
|
|
20
|
+
`;try{let u=_n(Vo(),"vibecontrols-uninstall");zo(u,{recursive:!0});let f=_n(u,`reaper-${process.pid}.ts`);return Ho(f,c,{encoding:"utf8"}),Fo(o,[f],{detached:!0,stdio:"ignore",windowsHide:!0}).unref(),e().logger.info("self-uninstall",`Scheduled detached uninstall reaper (pids=${l.join(",")}) at ${f}`),{ok:!0,scriptPath:f}}catch(u){return{ok:!1,scriptPath:null,error:u instanceof Error?u.message:String(u)}}}var Ko=new Set(["db","plugins-registry","logs","binaries","subprocs"]);async function $n(t){let n=await Mn();try{let o=t.getPluginManager?.();if(o){let s=new Set(n.map((i)=>i.name));for(let i of o.getPluginDetails()){let a=i.cliCommand;if(a&&!s.has(a))s.add(a),n.push({name:a,description:i.description||`${i.pluginName} plugin command`,usage:"",options:[],group:"plugin",destructive:!1})}}}catch{}return n.sort((o,s)=>o.name.localeCompare(s.name))}function Nn(t={}){return new E({name:"agent-maintenance"}).get("/api/agent/update/check",async()=>await Le()).get("/api/agent/update/status",()=>wr()).post("/api/agent/update",async({body:n})=>await Je({targetVersion:typeof n?.version==="string"?n.version:void 0,allowIncompatible:n?.allowIncompatible===!0,restart:n?.restart!==!1}),{body:r.Optional(r.Object({version:r.Optional(r.String()),allowIncompatible:r.Optional(r.Boolean()),restart:r.Optional(r.Boolean())}))}).post("/api/agent/update/config",({body:n})=>(Tn(n.enabled),{ok:!0,status:wr()}),{body:r.Object({enabled:r.Boolean()})}).post("/api/agent/update/check-now",async({body:n})=>({ok:!0,...await hr({force:n?.force===!0})}),{body:r.Optional(r.Object({force:r.Optional(r.Boolean())}))}).get("/api/agent/commands",async()=>{let n=await $n(t);return{commands:n,count:n.length}}).post("/api/agent/commands/run",async({body:n,set:o})=>{let s=Array.isArray(n?.argv)?n.argv.filter((u)=>typeof u==="string"):[];if(s.length===0)return o.status=400,{ok:!1,error:"argv must be a non-empty string array"};let i=s[0],a=await $n(t),l=new Set(a.map((u)=>u.name));if(!l.has(i))return o.status=400,{ok:!1,error:`Unknown or disallowed command: "${i}"`,allowed:[...l].sort()};return await Lt(s,{timeoutMs:typeof n?.timeoutMs==="number"?n.timeoutMs:void 0})},{body:r.Object({argv:r.Array(r.String()),timeoutMs:r.Optional(r.Number())})}).post("/api/agent/nuke",async({body:n,set:o})=>{let s=["nuke"];if(n?.all)s.push("--all");if(n?.removeConfig)s.push("--remove-config");if(n?.dryRun)s.push("--dry-run");if(typeof n?.removePlugins==="string"&&n.removePlugins)s.push("--remove-plugins",n.removePlugins);if(typeof n?.keep==="string"&&n.keep){let l=n.keep.split(",").map((c)=>c.trim()).filter((c)=>c&&!Ko.has(c));if(l.length>0)return o.status=400,{ok:!1,error:`Invalid --keep value(s): ${l.join(", ")}`};s.push("--keep",n.keep)}s.push("-y","--json");let i=await Lt(s),a=null;try{let l=i.stdout.trim().split(`
|
|
21
|
+
`).reverse().find((c)=>c.trim().startsWith("{"));if(l)a=JSON.parse(l)}catch{}return{...i,parsed:a}},{body:r.Optional(r.Object({all:r.Optional(r.Boolean()),removeConfig:r.Optional(r.Boolean()),removePlugins:r.Optional(r.String()),keep:r.Optional(r.String()),dryRun:r.Optional(r.Boolean())}))}).post("/api/agent/uninstall",async({body:n})=>{let o=n?.dryRun===!0,s=["nuke","--all","--remove-config","-y","--json"];if(o)s.push("--dry-run");let i=await Lt(s);if(o)return{ok:i.ok,dryRun:!0,nuke:i,note:"Dry run \u2014 would nuke all state and uninstall @vibecontrols/agent."};let a=new Set([process.pid]);try{let c=new D;for(let u of await c.listInstances())if(typeof u.pid==="number"&&u.pid>0)a.add(u.pid)}catch{}let l=Bn({pids:[...a]});return{ok:i.ok&&l.ok,nuke:i,uninstallScheduled:l.ok,scriptPath:l.scriptPath,...l.error?{error:l.error}:{},note:"Agent state nuked; package self-uninstall scheduled \u2014 the daemon will stop and `@vibecontrols/agent` will be removed shortly."}},{body:r.Optional(r.Object({dryRun:r.Optional(r.Boolean())}))})}import{existsSync as Qo,readFileSync as Zo}from"fs";import{join as ea}from"path";var Wo=`mutation AddAgentFromTunnel($input: AddAgentFromTunnelInput!) {
|
|
22
|
+
addVibecontrolsAgentFromTunnel(input: $input) { agent { id name } clientId success error }
|
|
23
|
+
}`,Jo=`mutation ReportAgentMeshLink($input: ReportAgentMeshLinkInput!) {
|
|
24
|
+
reportAgentMeshLink(input: $input) { id }
|
|
25
|
+
}`,Ln="VIBE_BOOTSTRAP_JSON=";function Yo(t){for(let s of t.split(/\r?\n/)){let i=s.indexOf(Ln);if(i>=0)try{return JSON.parse(s.slice(i+Ln.length))}catch{}}let n=t.indexOf("{"),o=t.lastIndexOf("}");if(n>=0&&o>n)try{return JSON.parse(t.slice(n,o+1))}catch{return null}return null}async function Gn(t,n){let o=(m,_,q)=>n?.({step:m,status:_,message:q}),s=Ze(t.permissions??["tunnel:read","session:list","plugin:list","diagnostics:read","mesh:forward"]);if(!s.includes("mesh:forward"))s.push("mesh:forward");let i=(m)=>({ok:!1,peerId:"",agentRecordId:null,tunnelUrl:null,permissions:s,error:m}),a;try{a=We(t.target,{identityFile:t.identityFile})}catch(m){return i(m instanceof Error?m.message:String(m))}let l=t.label??a.id,c=s.join(","),u,f='export PATH="$HOME/.bun/bin:$PATH"; ';try{if(!t.connectExisting){o("probe","running");let x=await a.probe();if(o("probe","completed",`os=${x.os??"?"} arch=${x.arch??"?"}`),!x.bun){if(t.installBun===!1)return i("Bun is required to run the agent but is not installed, and Bun auto-install was disabled.");o("install-bun","running");let ae=await a.run(["sh","-c",`curl -fsSL https://bun.sh/install | bash && echo 'export PATH="$HOME/.bun/bin:$PATH"' >> ~/.bashrc`],{timeoutMs:300000});if(ae.code!==0)return o("install-bun","failed",ae.stderr.slice(0,400)),i("Bun auto-install failed.");let ye=await a.run(["sh","-c","$HOME/.bun/bin/bun --version 2>/dev/null"],{timeoutMs:1e4});if(ye.code===0&&ye.stdout.trim())x.bun="$HOME/.bun/bin/bun",o("install-bun","completed",ye.stdout.trim());else return i("Bun installed but the binary is not reachable.")}o("install-agent","running");let p=t.version??"latest",j=t.registry??"https://registry.npmjs.org/",J,re;try{J=ct(p)}catch(ae){return o("install-agent","failed","invalid version"),i(ae instanceof Error?ae.message:String(ae))}try{re=ut(j)}catch(ae){return o("install-agent","failed","invalid registry"),i(ae instanceof Error?ae.message:String(ae))}let le=await a.run(Ft(re,J),{timeoutMs:600000});if(le.code!==0)return o("install-agent","failed",le.stderr.slice(0,400)),i(`Agent install failed (exit ${le.code}).`);if(u=(await a.run(["sh","-c",`${f}vibe --version`],{timeoutMs:15000})).stdout.trim()||void 0,o("install-agent","completed",u),t.autostart)o("autostart","running"),await a.run(["sh","-c",`${f}vibe autostart install`],{timeoutMs:60000}),o("autostart","completed");if(t.installPlugins?.length){o("plugins","running");for(let ae of t.installPlugins){let ye;try{ye=lt(ae)}catch(xe){return o("plugins","failed","invalid plugin package"),i(xe instanceof Error?xe.message:String(xe))}await a.run(Ot(ye),{timeoutMs:300000})}o("plugins","completed")}o("start","running"),await a.run(["sh","-c",`${f}vibe start`],{timeoutMs:60000}),o("start","completed")}o("bootstrap","running");let m;try{let x=dt(l),p=t.expiresIn?gt(t.expiresIn):void 0;m=Bt({label:x,scope:c,expiresIn:p,json:!0,emitDefaultKey:!0})}catch(x){return o("bootstrap","failed","invalid bootstrap arguments"),i(x instanceof Error?x.message:String(x))}let _=null;for(let x=0;x<15;x++){let p=await a.run(m,{timeoutMs:15000});if(p.code===0){let j=Yo(p.stdout);if(j&&typeof j.apiKey==="string"){_=j;break}}await new Promise((j)=>setTimeout(j,2000))}if(!_)return o("bootstrap","failed","could not obtain peer-bootstrap bundle"),i("Remote peer-bootstrap did not return a credential bundle.");o("bootstrap","completed");let q=Se(),Z=String(_.id),g=String(_.apiKey),S=fr(typeof _.tunnelUrl==="string"?_.tunnelUrl:null),A=typeof _.agentRecordId==="string"?_.agentRecordId:null;if(t.onboardBackend!==!1&&T.isConfigured()&&S&&typeof _.fullDefaultApiKey==="string"){o("onboard","running");let x=5,p="no agent returned";for(let j=0;j<x;j++){try{let le=(await T.workspaceQuery(Wo,{input:{tunnelUrl:S,apiKey:_.fullDefaultApiKey,name:l}})).data?.addVibecontrolsAgentFromTunnel;if(le?.agent?.id){A=le.agent.id,p="",o("onboard","completed",`agent ${A}`);break}p=le?.error??"no agent returned"}catch(re){p=re instanceof Error?re.message:String(re)}if(!/unreachable|resolve hostname|timed out|timeout|ECONN|network|to fetch|50[234]/i.test(p)||j===x-1)break;o("onboard","running",`retry ${j+1}/${x-1}: ${p.slice(0,80)}`),await new Promise((re)=>setTimeout(re,3000*(j+1)))}if(p)o("onboard","failed",p)}else o("onboard","skipped");o("store-creds","running"),Ye({id:Z,label:l,tunnelUrl:S??"",apiKey:g,permissions:s,addedAt:new Date().toISOString(),agentRecordId:A??void 0,workspaceId:(typeof _.workspaceId==="string"?_.workspaceId:q.workspaceId)??void 0,fingerprint:Z,ownerUserId:q.ownerUserId,sshTarget:a.mode==="ssh"?t.target:void 0,sshIdentityFile:t.identityFile}),o("store-creds","completed");let ne=Mt();if(t.onboardBackend!==!1&&T.isConfigured()&&ne&&A){o("report-link","running");try{await T.workspaceQuery(Jo,{input:{sourceAgentRecordId:ne,destinationAgentRecordId:A,label:l}}),o("report-link","completed")}catch(x){o("report-link","failed",x instanceof Error?x.message:String(x))}}else o("report-link","skipped");let G=await me(Z,"/api/profiles/default/agent/identity",{operation:"post-deploy-probe"});return o("probe-peer",G.ok?"completed":"failed",G.error??void 0),{ok:!0,peerId:Z,agentRecordId:A,tunnelUrl:S,permissions:s,remoteVersion:u}}catch(m){return i(m instanceof Error?m.message:String(m))}finally{await a.close().catch(()=>{})}}var Sr='export PATH="$HOME/.bun/bin:$PATH"; ';function Xo(t){let n=t.indexOf("{"),o=t.lastIndexOf("}");if(n>=0&&o>n)try{let s=JSON.parse(t.slice(n,o+1));if(s.tunnelUrl)return s.tunnelUrl;if(s.url&&s.url.startsWith("https"))return s.url}catch{}return null}async function jn(t,n){let o=(a,l,c)=>n?.({step:a,status:l,message:c}),s=Ve(t);if(!s)return{ok:!1,peerId:t,tunnelUrl:null,error:`No peer with id ${t}`};if(!s.sshTarget)return{ok:!1,peerId:t,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 i;try{i=We(s.sshTarget,{identityFile:s.sshIdentityFile})}catch(a){return{ok:!1,peerId:t,tunnelUrl:null,error:a instanceof Error?a.message:String(a)}}try{o("ssh-restart","running",s.sshTarget);let a=await i.run(["sh","-c",`${Sr}vibe restart 2>/dev/null || ${Sr}vibe start`],{timeoutMs:90000});if(a.code!==0)return o("ssh-restart","failed",a.stderr.slice(0,300)),{ok:!1,peerId:t,tunnelUrl:null,error:`Remote restart failed (exit ${a.code})`};o("ssh-restart","completed"),o("await-tunnel","running");let l=null;for(let c=0;c<15;c++){let u=await i.run(["sh","-c",`${Sr}vibe url --json 2>/dev/null`],{timeoutMs:15000});if(u.code===0){let f=Xo(u.stdout),m=fr(f);if(m){l=m;break}}await new Promise((f)=>setTimeout(f,2000))}if(!l)return o("await-tunnel","failed","no fresh tunnel after restart"),{ok:!1,peerId:t,tunnelUrl:null,error:"Agent restarted but no fresh tunnel came up."};return o("await-tunnel","completed",l),Ne(t,{tunnelUrl:l,lastReachable:new Date().toISOString()}),o("update","completed"),{ok:!0,peerId:t,tunnelUrl:l}}catch(a){return{ok:!1,peerId:t,tunnelUrl:null,error:a instanceof Error?a.message:String(a)}}finally{await i.close().catch(()=>{})}}var ta=Number(process.env.VIBECONTROLS_MESH_MAX_HOPS||"8");function Fn(){return(B()??e()).name}function ra(){return(B()??e()).dataDir}function Hn(){try{let n=ea(ra(),"runtime.json");if(Qo(n)){let o=JSON.parse(Zo(n,"utf8"));if(o.port&&Number.isInteger(o.port))return o.port}}catch{}let t=Number(process.env.PORT);return Number.isInteger(t)&&t>0?t:3005}function Vn(t){let n={};return t.headers.forEach((o,s)=>{n[s]=o}),n}function Me(t,n){let o=k(Vn(t));return Di(ur(o),n)}function na(t){let{apiKey:n,...o}=t;return{...o,apiKey:"[REDACTED]"}}function zn(t){return typeof t==="string"&&t.startsWith("/api/")&&!t.includes("..")&&!t.includes("//")}var jt=new Map;function oa(){let t=Date.now()-3600000;for(let[n,o]of jt)if(o.completedAt&&Date.parse(o.completedAt)<t)jt.delete(n)}function qn(){return new E({name:"agent-mesh"}).get("/api/mesh/peers",({request:t,set:n})=>{if(!Me(t,["read"]))return n.status=403,{error:"forbidden"};return{peers:At(Se()).map(na)}}).delete("/api/mesh/peers/:id",({request:t,set:n,params:o})=>{if(!Me(t,["mutate"]))return n.status=403,{error:"forbidden"};if(!At(Se()).some((i)=>i.id===o.id))return n.status=404,{error:"not found"};return{ok:Rt(o.id)}}).post("/api/mesh/peers/:id/call",async({request:t,set:n,params:o,body:s})=>{if(!Me(t,["mesh:forward"]))return n.status=403,{error:"forbidden"};let i=s;if(!zn(i.path))return n.status=400,{error:"invalid path"};if(!At(Se()).find((c)=>c.id===o.id))return n.status=404,{error:"not found"};let l=await me(o.id,i.path,{method:i.method??"GET",body:i.body,operation:"mesh-call"});return{ok:l.ok,status:l.status,data:l.data,rotated:l.rotated,error:l.error}},{body:r.Object({method:r.Optional(r.String()),path:r.String(),body:r.Optional(r.Any())})}).post("/api/mesh/forward",async({request:t,set:n,body:o})=>{if(!Me(t,["mesh:forward"]))return n.status=403,{error:"forbidden"};let s=o;if(!s.request||!zn(s.request.path))return n.status=400,{error:"invalid request"};let i=(s._hopCount??0)+1;if(i>ta)return n.status=422,{error:"hop limit exceeded"};let a=Se(),l=Mt(),c=s.hops??[];if(c.length===0){let Z=ur(k(Vn(t))),g=(s.request.method??"GET").toUpperCase();if(!Z||!ar(Z.scopes,g,s.request.path))return e().audit.emit("mesh","forward.denied",{path:s.request.path,method:g}),n.status=403,{error:"forbidden"};e().audit.emit("mesh","forward.terminal",{path:s.request.path,method:s.request.method??"GET"});let S=(s.request.method??"GET").toUpperCase();try{let A=await fetch(`http://127.0.0.1:${Hn()}${s.request.path}`,{method:S,headers:{"x-agent-api-key":await qe(),...s.request.body!==void 0?{"content-type":"application/json"}:{}},body:s.request.body!==void 0?JSON.stringify(s.request.body):void 0,signal:AbortSignal.timeout(60000)}),ne=await A.text().catch(()=>""),G=null;try{G=ne?JSON.parse(ne):null}catch{G=null}return{ok:A.ok,status:A.status,data:G,text:ne||null,error:A.ok?null:ne||`status ${A.status}`}}catch(A){return n.status=502,{ok:!1,status:0,error:A instanceof Error?A.message:String(A)}}}let u=c[0],f=s._traversed??[];if(u===l||f.includes(u))return n.status=422,{error:"cycle detected",at:u};let m=Fr(u,a);if(!m)return n.status=403,{error:"next hop not in authorized boundary"};if(!m.permissions.includes("mesh:forward"))return n.status=403,{error:"peer lacks mesh:forward grant"};e().audit.emit("mesh","forward.hop",{nextId:u,remaining:c.length,hopCount:i});let _=encodeURIComponent(Fn()),q=await me(m.id,`/api/profiles/${_}/mesh/forward`,{method:"POST",operation:"mesh-forward",timeoutMs:60000,body:{hops:c.slice(1),request:s.request,_traversed:[...f,l??"self"],_hopCount:i}});if(!q.ok)return n.status=502,{ok:!1,status:q.status,error:q.error,failedAtHop:u};return q.data},{body:r.Object({hops:r.Optional(r.Array(r.String())),request:r.Object({method:r.Optional(r.String()),path:r.String(),body:r.Optional(r.Any())}),_traversed:r.Optional(r.Array(r.String())),_hopCount:r.Optional(r.Number())})}).post("/api/mesh/deploy",({request:t,set:n,body:o})=>{if(!Me(t,["admin"]))return n.status=403,{error:"forbidden"};oa();let s=o,i=Se(),a=crypto.randomUUID(),l={id:a,status:"running",steps:[],ownerUserId:i.ownerUserId,workspaceId:i.workspaceId,startedAt:new Date().toISOString()};return jt.set(a,l),Gn({target:s.target,permissions:s.permissions,installPlugins:s.installPlugins,autostart:s.autostart,identityFile:s.identityFile,label:s.label,version:s.version,connectExisting:s.connectExisting},(c)=>{l.steps.push(c),ge("mesh:deploy:progress",{jobId:a,step:c})}).then((c)=>{if(l.result=c,l.status=c.ok?"completed":"failed",!c.ok)l.error=c.error;l.completedAt=new Date().toISOString(),ge(c.ok?"mesh:deploy:complete":"mesh:deploy:failed",{jobId:a,result:c})}).catch((c)=>{l.status="failed",l.error=c instanceof Error?c.message:String(c),l.completedAt=new Date().toISOString(),ge("mesh:deploy:failed",{jobId:a,error:l.error})}),n.status=202,{jobId:a,status:"running"}},{body:r.Object({target:r.String(),permissions:r.Optional(r.Array(r.String())),installPlugins:r.Optional(r.Array(r.String())),autostart:r.Optional(r.Boolean()),identityFile:r.Optional(r.String()),label:r.Optional(r.String()),version:r.Optional(r.String()),connectExisting:r.Optional(r.Boolean())})}).get("/api/mesh/deploy/jobs/:id",({request:t,set:n,params:o})=>{if(!Me(t,["read"]))return n.status=403,{error:"forbidden"};let s=jt.get(o.id),i=Se();if(!s||i.ownerUserId&&s.ownerUserId&&s.ownerUserId!==i.ownerUserId)return n.status=404,{error:"not found"};return s}).post("/api/mesh/wake",async({request:t,set:n,body:o})=>{if(!Me(t,["admin"]))return n.status=403,{error:"forbidden"};let s=o,i=Fr(s.targetAgentRecordId,Se());if(!i)return n.status=404,{ok:!1,error:"peer not in authorized boundary"};e().audit.emit("mesh","wake.start",{peerId:i.id,agentRecordId:s.targetAgentRecordId});let a=await jn(i.id,(l)=>ge("mesh:wake:progress",{peerId:i.id,step:l}));if(!a.ok)n.status=502;return a},{body:r.Object({targetAgentRecordId:r.String()})}).post("/api/mesh/session",async({request:t,set:n,body:o})=>{if(!Me(t,["mesh:forward","mutate"]))return n.status=403,{error:"forbidden"};let s=o,i=s.sessionId&&/^[A-Za-z0-9_-]{1,128}$/.test(s.sessionId)?s.sessionId:crypto.randomUUID(),a=encodeURIComponent(Fn()),l=await qe(),c=`http://127.0.0.1:${Hn()}`,u=s.command||"bash";try{let f=await fetch(`${c}/api/profiles/${a}/sessions/create`,{method:"POST",headers:{"x-agent-api-key":l,"content-type":"application/json"},body:JSON.stringify({sessionId:i,sessionName:`vc-mesh-${i.slice(0,8)}`,command:u,provider:"TERMINAL",...s.vibeId?{projectId:s.vibeId}:{}}),signal:AbortSignal.timeout(20000)});if(!f.ok)return n.status=502,{error:`session create returned ${f.status}: ${await f.text().catch(()=>"")}`};let m=await fetch(`${c}/api/profiles/${a}/sessions/${encodeURIComponent(i)}/terminal`,{method:"POST",headers:{"x-agent-api-key":l},signal:AbortSignal.timeout(20000)});if(!m.ok)return n.status=502,{error:`terminal start returned ${m.status}: ${await m.text().catch(()=>"")}`};let _=Ar(`/terminal/${i}`,600);return e().audit.emit("mesh","session.created",{sessionId:i,kind:s.kind??"TERMINAL"}),{connectionId:i,sessionId:i,capabilityToken:_.token,expiresAt:_.expiresAt}}catch(f){return n.status=502,{error:f instanceof Error?f.message:String(f)}}},{body:r.Object({sessionId:r.Optional(r.String()),kind:r.Optional(r.String()),cwd:r.Optional(r.String()),vibeId:r.Optional(r.String()),command:r.Optional(r.String())})})}var aa=["/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 ia(t){return aa.some((n)=>t.startsWith(n))}var sa=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function la(t){return t.split("/").map((n)=>{if(!n)return n;if(/^\d+$/.test(n))return":id";if(sa.test(n))return":id";if(n.length>=24&&/^[A-Za-z0-9_-]+$/.test(n))return":id";return n}).join("/")}async function Er(t){let{port:n,host:o,dbPath:s,logLevel:i,corsOrigin:a}=t,l=s??ee();try{let d=await import("fs");d.mkdirSync(l,{recursive:!0})}catch(d){throw e().logger.error("app","Failed to create dbPath dir at boot",{dbPath:l,error:String(d)}),Error(`Cannot create dbPath ${l}: ${d instanceof Error?d.message:String(d)}`,{cause:d})}if(i)e().logger.setLevel(i);(async()=>{let{logShipper:d}=await import("./log-shipper-0erbwn0q.js");d.init()})(),(async()=>{let d=await Wn();await Dt({version:d,profile:R()})})();try{let{checkDependencies:d}=await import("./bootstrap.service-9m7m1ksa.js"),U=d(),y=U.filter((H)=>H.required&&!H.installed),F=U.filter((H)=>!H.required&&!H.installed);if(y.length>0)e().logger.error("app",`Missing required system deps: ${y.map((H)=>H.name).join(", ")}. Run \`vibe setup\` to install.`);if(F.length>0)e().logger.warn("app",`Missing optional system deps: ${F.map((H)=>H.name).join(", ")}. Some plugins may fail their prereqs check.`)}catch(d){e().logger.warn("app","Boot-time dependency check failed",{error:String(d)})}try{e().audit.runRetention()}catch(d){e().logger.warn("app","Audit-log retention sweep failed",{error:String(d)})}let c=new Te;Rr(c,{port:n});let u="GET, POST, PUT, PATCH, DELETE, OPTIONS",f="Content-Type, x-agent-api-key, Authorization, x-requested-with",m=Array.isArray(a)?a:(a??"").split(",").map((d)=>d.trim()).filter(Boolean),_=(d)=>gi(d,{configuredOrigins:m,devPorts:t.devCorsPorts}),q=()=>{let d=R(),U=rr(d);return[process.env.AGENT_TUNNEL_URL,process.env[`AGENT_TUNNEL_URL_${U}`],at(),te()?.url]},Z=async()=>{let d=[],U=[],y=c.getProvider("tunnel");if(y)U.push(y);for(let F of c.listProvidersForType("tunnel")){let H=c.getProviderByName("tunnel",F.pluginName);if(H&&!U.includes(H))U.push(H)}for(let F of U){if(!F.getActiveTunnelUrl)continue;try{let H=await F.getActiveTunnelUrl();if(H)d.push(H)}catch{}}return d},g=null,S=null,A=null,ne=null,G=!1,x=()=>[],p=null,j=null,J=null,re=5000,le=async(d,U)=>{let y=Date.now();try{await Promise.race([Promise.resolve(U()),new Promise((F,H)=>setTimeout(()=>H(Error(`shutdown phase ${d} exceeded ${re}ms`)),re))]),e().logger.info("app",`shutdown.phase ${d} complete`,{ms:Date.now()-y})}catch(F){e().logger.warn("app",`shutdown.phase ${d} failed`,{error:String(F),ms:Date.now()-y})}},Ce=async(d)=>{if(G)return;if(G=!0,e().logger.info("app","Agent shutdown starting",{reason:d?.reason??"shutdown"}),await le("plugins",async()=>{if(S)await S.dispatchServerStop(d)}),await le("bootstrap-tunnel",()=>ir()),await le("tracked-subprocesses",async()=>{let{killAllTracked:U}=await import("./subprocess-4gg77skg.js");await U()}),d?.reason!=="reload")await le("db-close",async()=>{if(g)await g.close()});await le("http-listener",async()=>{try{await Promise.resolve(Re.stop())}catch(U){e().logger.warn("app","Listener stop threw (already stopped or never started?)",{error:String(U)})}}),e().logger.info("app","Agent server stopped"),e().logger.close()},ae=async(d,U)=>{if(e().getBootState()==="ready")return{ok:!0};if(J)return J;return J=(async()=>{e().setBootState("initializing");try{let y={...d,globalGatewayUrl:z(d.globalGatewayUrl,"globalGatewayUrl"),workspaceGatewayUrl:z(d.workspaceGatewayUrl,"workspaceGatewayUrl")},F=await Wt(y),H=l,ce=w({dir:e().dataDir}),he=ce.storageAdapter??process.env.VIBE_STORAGE_ADAPTER??void 0,ve=ce.storageOptions,Ae=(h)=>{let v=(h instanceof Error?h.message:String(h)).toLowerCase(),Y=h&&typeof h==="object"&&"code"in h?String(h.code).toUpperCase():"";if(Y==="EBUSY"||Y==="EPERM"||Y==="EACCES"||Y==="EAGAIN"||Y==="EMFILE"||Y==="ENFILE"||Y==="ETIMEDOUT"||Y==="ECONNRESET"||Y==="ECONNREFUSED"||v.includes("encryption key")||v.includes("fetch")&&v.includes("key")||v.includes("temporarily unavailable")||v.includes("resource busy"))return"transient";if(v.includes("auth tag")||v.includes("authentication tag")||v.includes("unable to authenticate data")||v.includes("bad decrypt")||v.includes("unsupported state")||v.includes("incorrect header check")||v.includes("invalid distance")||v.includes("incorrect data check")||v.includes("unexpected end of")||v.includes("unexpected token")||v.includes("json")&&(v.includes("parse")||v.includes("invalid"))||v.includes("truncated")||v.includes("malformed")||v.includes("corrupt"))return"corruption";return"unknown"},nt=()=>Jt({dbPath:H,encryptionKey:F,adapterName:he,adapterOptions:ve});try{g=await nt()}catch(h){let v=h,Y=Ae(h),Pt=[500,2000,8000];if(Y==="transient"||Y==="unknown"){e().logger.warn("app",`Storage open failed (${Y}); will retry up to ${Pt.length} times before quarantine`,{error:h instanceof Error?h.message:String(h),path:H});for(let ft of Pt){await new Promise((ie)=>setTimeout(ie,ft));try{g=await nt(),v=null;break}catch(ie){if(v=ie,Y=Ae(ie),e().logger.warn("app",`Storage open retry failed (${Y}) after ${ft}ms`,{error:ie instanceof Error?ie.message:String(ie)}),Y==="corruption")break}}}if(!g&&v){if(Y!=="corruption"){let ie=v instanceof Error?v.message:String(v);e().logger.error("app",`Storage open failed after retries with non-corruption error (${Y}); refusing to quarantine valid data`,{error:ie,path:H}),e().recordDegradedReason("storage",ie);try{throw v}catch(Qe){throw Error(`Storage open failed (${Y}); agent is degraded: ${ie}`,{cause:Qe})}}let ft=v instanceof Error?v.message:String(v);e().logger.error("app","QUARANTINE: Storage file is corrupt \u2014 renaming and creating fresh DB",{errorClass:"corruption",error:ft,path:H});try{let ie=await import("fs");if(ie.existsSync(H)){let Qe=new Date().toISOString().replace(/[:.]/g,"-"),xr=`${H}.broken-${Qe}`;ie.renameSync(H,xr),e().logger.warn("app",`Quarantined corrupt storage to ${xr} \u2014 fresh DB will be created`,{originalError:ft})}g=await nt()}catch(ie){let Qe=ie instanceof Error?ie.message:String(ie);throw e().recordDegradedReason("storage",Qe),Error(`Storage open failed twice (quarantine path); agent is degraded: ${Qe}`,{cause:ie})}}}if(!g)throw Error("Internal error: storage open recovery exited without an open database and without throwing");if(await Gt({clientId:y.clientId,clientSecret:y.clientSecret,workspaceId:y.workspaceId,organizationId:y.organizationId,globalGatewayUrl:y.globalGatewayUrl,workspaceGatewayUrl:y.workspaceGatewayUrl,agentRecordId:U?.agentRecordId,scopes:U?.scopes,pairedIdentity:$t({workspaceId:y.workspaceId,globalGatewayUrl:y.globalGatewayUrl,workspaceGatewayUrl:y.workspaceGatewayUrl,agentRecordId:U?.agentRecordId})},{dir:e().dataDir,scope:e().name}),await g.setConfig("gateway-auth:clientId",y.clientId),await g.setConfig("gateway-auth:clientSecret",y.clientSecret),await g.setConfig("gateway-auth:globalGatewayUrl",y.globalGatewayUrl),await g.setConfig("gateway-auth:workspaceGatewayUrl",y.workspaceGatewayUrl),await g.setConfig("gateway-auth:workspaceId",y.workspaceId),y.organizationId)await g.setConfig("gateway-auth:organizationId",y.organizationId);if(U?.agentRecordId)await g.setConfig("gateway-auth:agentRecordId",U.agentRecordId);c.db=g,await c.hydrateDefaultsFromDb(),S=new W(g),await S.loadCorePlugins();try{await S.loadAll()}catch(h){e().logger.warn("app","Failed to load some external plugins",{error:String(h)})}let ot=He(C())??void 0,st=process.env.VIBE_SKIP_AUTO_INSTALL==="1"||await g.getConfig("plugins:auto-install-disabled");if(st!=="true"&&st!==!0)try{let h=await S.ensureDefaultPlugins((v)=>e().logger.info("app",`[auto-install] ${v}`),[],ot);if(h.length>0)e().logger.info("app",`Auto-installed ${h.length} default plugin(s): ${h.map((v)=>v.packageName).join(", ")}`)}catch(h){e().logger.warn("app","Failed to auto-install default plugins",{error:String(h)})}e().logger.info("app",`Plugins loaded: ${S.getPluginDetails().length} total (${S.getPluginDetails().filter((h)=>h.isCore).length} core)`);try{let h=S.getPluginDetails(),v={loaded:h.filter((Y)=>Y.loaded).length,failed:h.filter((Y)=>!Y.loaded).length};mn(v)}catch{}let zt={async get(h,v){return await g.getPluginState(h,v)??null},async set(h,v,Y){await g.setPluginState(h,v,Y)},async delete(h,v){return g.deletePluginState(h,v)},async list(h){return await g.getAllPluginState(h)},async deleteAll(h){return g.deleteAllPluginState(h)}},kt=await Wn();A={storage:zt,logger:e().logger,serviceRegistry:c,getProvider:(h)=>c.getProvider(h),getAgentBaseUrl:()=>process.env.AGENT_URL||`http://localhost:${n}`,getAgentVersion:()=>kt,validateApiKey:(h)=>V(h),setCodeServerSessionValidator:(h)=>{Jn=h},broadcast:ge,workspaceQuery:async(h,v)=>T.workspaceQuery(h,v),isGatewayConfigured:()=>T.isConfigured(),getAgentRecordId:async()=>await g.getConfig("gateway-auth:agentRecordId")??null,getWorkspaceId:async()=>await g.getConfig("gateway-auth:workspaceId")??null,getConfig:async(h)=>await g.getConfig(h)??void 0,getPluginRegistry:()=>se(),getDataDir:()=>I(),cliContributors:new Ee,audit:{emit:(h,v)=>e().audit.emit("agent",h,v??{})},telemetry:{emit:(h,v)=>{import("./telemetry-nmtywcba.js").then(({telemetryService:Y})=>Y.emit(h,v??{})).catch(()=>{})}},os:b(),iframeBridge:ke()},T.configure({globalGatewayUrl:y.globalGatewayUrl,workspaceGatewayUrl:y.workspaceGatewayUrl,clientId:y.clientId,clientSecret:y.clientSecret,workspaceId:y.workspaceId,organizationId:y.organizationId});let je={db:g,serviceRegistry:c,pluginManager:S,broadcast:ge,hostServices:A};je.app=Re;let Tr=!1,qt=()=>{let{routes:h,getPublicPaths:v,mountPlugin:Y}=sr(S,je);if(je.mountPlugin=Y,x=v,Ni(),p=h,j=xi(S),S&&Tr&&A)S.dispatchServerStart(p,A).catch((Pt)=>e().logger.warn("app","Re-dispatch of onServerStart after plugin reload failed",{error:String(Pt)}));Tr=!0};je.rebuildPluginSurfaces=qt,qt(),ne=new bt(c,S,g,Re,A,Ce),c.registerService("agent","lifecycle",ne),e().attachServices({db:g,serviceRegistry:c,pluginManager:S,lifecycle:ne,hostServices:A}),pt(e(),{rebuildPluginSurfaces:qt,mountPlugin:je.mountPlugin,app:p});try{await e().keyVault.bindApiKey(K())}catch(h){e().logger.warn("app","Failed to bind api key into daemon keyVault",{error:String(h)})}let Kt=[];try{let{failures:h}=await S.dispatchServerStart(p,A);for(let v of h)if(ht(v.plugin)||(v.packageName?ht(v.packageName):!1))Kt.push(v),e().recordDegradedReason(v.plugin,v.error);else e().logger.warn("app",`Non-critical plugin ${v.plugin} failed onServerStart; continuing`,{error:v.error})}catch(h){e().logger.warn("app","Error during plugin onServerStart dispatch",{error:String(h)})}try{await S.dispatchServerReady(Re,A)}catch(h){e().logger.warn("app","Error during plugin onServerReady dispatch",{error:String(h)})}if(e().clearFinalizeError(),Kt.length>0)e().setBootState("degraded"),e().logger.error("app","Agent finalized but degraded \u2014 critical plugins failed",{failures:Kt.map((h)=>`${h.plugin}: ${h.error}`)});else e().setBootState("ready"),e().logger.info("app","Agent finalized \u2014 state=ready"),e().audit.emit("agent","gateway-auth.configured",{workspaceId:y.workspaceId,organizationId:y.organizationId,agentRecordId:U?.agentRecordId});return(async()=>{try{if(await S.provisionDefaultPrereqs(Re,A,je.mountPlugin,ot),e().logger.info("app","Default provider prerequisites provisioned"),(c.listProvidersForType("tunnel")??[]).some((Y)=>Y.pluginName!=="bootstrap")){let{tryHandoverBootstrapTunnel:Y}=await import("./tunnel-bootstrap-zwyzxrkt.js");if(!Y())ir();c.unregisterProvider("tunnel","bootstrap"),e().logger.info("app","Bootstrap tunnel handed over to the real tunnel provider")}}catch(h){e().logger.warn("app","Plugin prerequisite provisioning failed",{error:String(h)})}})(),{ok:!0}}catch(y){e().setBootState("awaiting-config");let F=y instanceof Error?y.message:String(y);if(e().recordFinalizeError(F),e().logger.error("app","Finalize failed",{error:F}),process.env.VIBE_STRICT_KEY_FETCH==="1")e().logger.error("app","VIBE_STRICT_KEY_FETCH=1 \u2192 aborting daemon (strict mode)",{error:F}),setTimeout(()=>process.exit(1),50);return{ok:!1,error:F}}finally{J=null}})(),J},ye=Mr({origin:(d)=>{let U=d.headers.get("origin");return!!U&&_(U)},credentials:!0,allowedHeaders:f.split(",").map((d)=>d.trim()),methods:u.split(",").map((d)=>d.trim()),exposeHeaders:["content-type","content-length"],maxAge:86400,preflight:!0}),xe=10485760,Pr=process.env.VIBECONTROLS_MAX_BODY_BYTES,Ht=Pr?Number.parseInt(Pr,10):NaN,Yn=Number.isFinite(Ht)&&Ht>0?Ht:xe,Or={current:null},Re=new E({serve:{maxRequestBodySize:Yn}}).onRequest(async({request:d})=>{let U={port:n,allowedHosts:t.allowedHosts,tunnelUrls:q()},y=Cr(d,U);if(!y&&c.hasProvider("tunnel")){let F=await Z();if(F.length>0)y=Cr(d,{...U,tunnelUrls:[...U.tunnelUrls,...F]})}if(!y)return new Response(JSON.stringify({error:"Forbidden",message:"Invalid or disallowed Host header"}),{status:403,headers:{"content-type":"application/json"}});try{let F=new URL(d.url).pathname;if((F==="/api/agent/api-key"||/^\/api\/profiles\/[^/]+\/agent\/api-key(?:\/|$)/.test(F))&&Ge(d))return new Response(JSON.stringify({error:"Forbidden",message:"Browser requests are not permitted on /api/agent/api-key"}),{status:403,headers:{"content-type":"application/json"}})}catch{}}).onRequest(({request:d,set:U})=>{let F=Ki(d.headers)??ri();Qi({requestId:F,startedAt:new Date().toISOString()});let H=U.headers??={};H["X-Request-Id"]=F}).onRequest(({request:d})=>{try{let U=new URL(d.url).pathname,F=/^\/api\/profiles\/([^/]+)(?:\/|$)/.exec(U)?.[1],H=F?N.get(F):null;Tt(H??e())}catch{Tt(e())}}).onRequest(({request:d,set:U})=>{let y=new URL(d.url).pathname;if(!y.startsWith("/api/"))return;if(y==="/api/profiles"||y.startsWith("/api/profiles/"))return;if(y==="/api/profile-stats"||y.startsWith("/api/profile-stats/"))return;let F=new URL(d.url);F.pathname=`/api/profiles/default${y.slice(4)}`;try{d.headers.set("x-vc-profile-rewrite","1"),d.headers.set("x-vc-profile-rewrite-target",F.pathname)}catch{}return}).derive(()=>({requestId:St()??ri()})).use(ye).use(Oi()).use(Li(()=>x())).use(Hr({getDb:()=>B()?.db??g})).onBeforeHandle(({request:d,set:U})=>{let y=e().getBootState();if(y==="ready")return;let F=new URL(d.url).pathname;if(ia(F))return;return U.status=503,{error:"Agent not yet configured",message:"Agent is in '"+y+"' state. POST credentials to /api/agent/gateway-auth to finalize.",state:y}}).onAfterHandle(({request:d,set:U})=>{let y=new URL(d.url).pathname,F=y==="/health"||y.startsWith("/api/logs/stream")||y.startsWith("/ui/")||y==="/ws/events"||y==="/api/sessions/health-check"||y.startsWith("/terminal/"),H=typeof U.status==="number"?U.status:200,ce=F?"debug":H>=400?"warn":"info";e().logger[ce]("http",`${d.method} ${y} \u2192 ${H}`,{method:d.method,path:y,statusCode:H});try{fn(d.method,la(y),H)}catch{}}).use(cn({serviceRegistry:c,getDb:()=>B()?.db??g,getDbPath:()=>l,getPluginManager:()=>B()?.pluginManager??S})).use(hn()).use(en({serviceRegistry:c,runFinalize:(d,U)=>ae(d,U),getDb:()=>B()?.db??g})).use(dn()).use(gn()).use(Nn({getPluginManager:()=>B()?.pluginManager??S})).use(qn()).use(bn()).use(An({getPluginManager:()=>B()?.pluginManager??S,getTunnelHost:()=>te()?.url??null})).use(an()).use(sn()).use(Nr()).use(kr()).use(Lr(c)).ws("/code-server/*",ua(n)).all("/api/profiles/:name/*",async({params:d,request:U,set:y})=>{let F=U.method!=="GET"&&U.method!=="HEAD",H=F?await U.arrayBuffer():void 0,ce=await vr(d.name,U,H);if(ce&&ce.status!==404)return ce;let he=R(),ve=d.name;if(ve!==he)return y.status=404,{error:"profile-mismatch",running:he,requested:ve,hint:"This daemon serves a different profile. Call GET /api/profiles to discover the right tunnel."};let Ae=new URL(U.url),nt=Ae.pathname.replace(/^\/api\/profiles\/[^/]+/,"/api"),ot=new Headers(U.headers);ot.set("x-vc-profile-rewrite","1");let st={method:U.method,headers:ot};if(F&&H!==void 0)st.body=H;let zt=new Request(`${Ae.origin}${nt}${Ae.search}`,st),kt=Or.current;if(!kt)return new Response(JSON.stringify({error:"agent-not-ready"}),{status:503,headers:{"content-type":"application/json"}});return kt.handle(zt)}).all("/api/*",async({request:d})=>{if(e().getBootState()!=="ready"||!p)return new Response(JSON.stringify({error:"Agent not yet configured",state:e().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 U=new URL(d.url),y=/^\/api\/plugins\/([a-z0-9-]{1,64})\/ui(?:\/.*)?$/.exec(U.pathname);if(y&&d.method==="GET"){let F=y[1];if(de(F)){let H=U.pathname.slice(`/api/plugins/${F}/ui`.length),ce=H===""||H==="/",ve=d.headers.get("sec-fetch-mode")==="navigate";if(ce||ve){let Ae=ze(d,F);if(!Ae||!Xe(Ae,F))return new Response(Br(F,"/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 p.handle(d)}).all("/ui/*",async({request:d})=>{if(e().getBootState()!=="ready"||!j)return new Response("Plugin UI not yet available",{status:503});return j.handle(d)}).all("/code-server/*",async({request:d})=>{if(e().getBootState()!=="ready"||!p)return new Response("code-server not yet available",{status:503});let U=$r(d,K);return p.handle(U??d)}).all("/plan/*",async({request:d})=>{if(e().getBootState()!=="ready"||!p)return new Response("plan provider not yet available",{status:503});return p.handle(d)});return Or.current=Re,{app:Re,async start(){Re.listen({port:n,hostname:o}),e().logger.info("app",`Agent server listening on ${o}:${n}`);try{let d=(process.env.VIBECONTROLS_PROFILES??"").split(",").map((ce)=>ce.trim()).filter(Boolean),U=e().name,{getOrCreateProfile:y}=await import("./daemon-profile-sg8fp50z.js"),{attachSecondaryProfile:F}=await import("./secondary-profile-attach-pyqqf4ny.js"),H=process.env.VIBE_STRICT_KEY_FETCH==="1";for(let ce of d){if(ce===U)continue;try{let he=y(ce),ve=await F(he);if(ve.ok)e().logger.info("app",`Secondary profile '${ce}' attached (db+services online)`);else if(H)throw Error(`attachServices for secondary profile '${ce}' failed: ${ve.error}`);else he.recordDegradedReason("attach",ve.error??"unknown"),e().logger.warn("app",`Secondary profile '${ce}' is degraded (no creds / attach failed)`,{error:ve.error})}catch(he){if(H)throw e().logger.error("app",`--strict-key-fetch: secondary profile '${ce}' attach failed; aborting`,{error:String(he)}),setTimeout(()=>process.exit(1),50),he;e().logger.warn("app",`Failed to attach secondary profile '${ce}'`,{error:String(he)})}}}catch{}return Re},stop:Ce,finalize:ae,getState:()=>e().getBootState(),getLifecycle:()=>B()?.lifecycle??ne,getDb:()=>B()?.db??g,getServiceRegistry:()=>B()?.serviceRegistry??c,getPluginManager:()=>B()?.pluginManager??S,getHostServices:()=>B()?.hostServices??A}}var Jn=null;function ca(t,n){if(!t)return null;let o=t.match(new RegExp(`(?:^|;\\s*)${n}=([^;]*)`));return o?o[1]:null}var Kn=or(Bi);function ua(t){let i=(a)=>typeof a==="string"?Buffer.byteLength(a):a.byteLength;return{open(a){let l=a.data,c=k(l.headers??{})??k(l.request?Object.fromEntries(l.request.headers.entries()):{}),u=l.query?.vt,f=!!u&&we(u,"/code-server","GET"),m,_=V(c);if(!_&&!f){let S=l.headers?.cookie??l.request?.headers.get("cookie")??null,A=ca(S,"__vibe_cs_session");if(!A||!Jn?.(A)){a.close(1008,"Unauthorized");return}m=`session:${A}`}else if(_)m="api-key";else m="vt";let q=a.remoteAddress??null,Z=Ue(q,l.headers);if(!Kn.accept(m,Z,a)){e().logger.warn("code-server-ws",`code-server WS cap exceeded (key=${m}, ip=${Z??"unknown"})`),a.close(1013,"too many connections");return}l._csCapKey=m,l._csRemoteIp=Z;let g=e().name;fetch(`http://127.0.0.1:${t}/api/profiles/${encodeURIComponent(g)}/code-server/status`,{headers:{"x-agent-api-key":K()}}).then((S)=>S.json()).then((S)=>{if(l._csClosed)return;let A=S;if(!A.running||!A.port){a.close(1011,"code-server not running");return}let ne=l.request?.url??"/code-server/",G;try{let j=new URL(ne,`http://127.0.0.1:${A.port}`);G=(j.pathname.replace(/^\/code-server\/?/,"/")||"/")+j.search}catch{G="/"}let x=new WebSocket(`ws://127.0.0.1:${A.port}${G}`),p={upstream:x,ready:!1,buffer:[],bufferBytes:0,openTimer:setTimeout(()=>{try{x.close(1011,"upstream open timeout")}catch{}try{a.close(1011,"upstream open timeout")}catch{}},1e4)};l._csBridge=p,x.addEventListener("open",()=>{clearTimeout(p.openTimer),p.ready=!0;for(let j of p.buffer)x.send(j);p.buffer.length=0,p.bufferBytes=0}),x.addEventListener("message",(j)=>{try{let J=j.data;if(J instanceof ArrayBuffer)a.send(new Uint8Array(J));else if(J instanceof Blob)J.arrayBuffer().then((re)=>{try{a.send(new Uint8Array(re))}catch{}});else a.send(J)}catch{}}),x.addEventListener("close",(j)=>{clearTimeout(p.openTimer);try{a.close(j.code||1000,j.reason||"upstream closed")}catch{}}),x.addEventListener("error",()=>{clearTimeout(p.openTimer);try{a.close(1011,"upstream error")}catch{}})}).catch(()=>{a.close(1011,"Failed to query code-server status")})},message(a,l){let c=a.data?._csBridge;if(!c)return;let u;if(typeof l==="string")u=l;else if(l instanceof ArrayBuffer)u=l;else if(l instanceof Uint8Array||Buffer.isBuffer(l)){let f=new ArrayBuffer(l.byteLength);new Uint8Array(f).set(new Uint8Array(l.buffer,l.byteOffset,l.byteLength)),u=f}else if(typeof l==="object"&&l!==null)u=JSON.stringify(l);else u=String(l);if(c.upstream&&c.ready&&c.upstream.readyState===WebSocket.OPEN)try{c.upstream.send(u)}catch{}else{let f=i(u);if(c.buffer.length>=256||c.bufferBytes+f>1048576){try{c.upstream.close(1013,"buffer limit exceeded")}catch{}try{a.close(1013,"buffer limit exceeded")}catch{}return}c.buffer.push(u),c.bufferBytes+=f}},close(a){a.data._csClosed=!0;let l=a.data?._csBridge;if(l?.openTimer)clearTimeout(l.openTimer);if(l?.upstream&&l.upstream.readyState===WebSocket.OPEN)l.upstream.close(1000,"client disconnected");let c=a.data._csCapKey,u=a.data._csRemoteIp;if(c)Kn.release(c,u??null,a)}}}async function Wn(){try{let{readFileSync:t}=await import("fs"),{join:n,dirname:o}=await import("path"),{fileURLToPath:s}=await import("url"),i=o(s(import.meta.url));return JSON.parse(t(n(i,"..","package.json"),"utf8")).version||"1.0.0"}catch{return"1.0.0"}}
|
|
26
|
+
export{oi,Zt,mr,ai,Er};
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{r,E}from"./index-w0m3jm0s.js";import{Me,st}from"./index-652f9scs.js";import{T,R,si,I,ne,B,e}from"./index-0qjbnyg4.js";import{M}from"./index-kwhx023z.js";import"./index-5021rk8n.js";import{be,Nt,K,Mi,k,V}from"./index-mmx2kp76.js";import{i,d,s,A,l,o,g,n,c,F,v,Gr,Qe,G}from"./index-7f2k4g6q.js";import{U}from"./index-vtsd74g0.js";import{jr}from"./index-d59kp6zr.js";import{ci,ui,li}from"./index-4527yp1c.js";import"./index-g08z6z5v.js";import"./index-qfxwk38p.js";import{Ge,Be,Pe}from"./index-c4whjk5r.js";import{mi}from"./index-akk3rxnn.js";import{D}from"./index-75hk5q9s.js";import{Pt}from"./index-gnb8xw13.js";import{L}from"./index-b3v08awy.js";import{ve}from"./index-4z1y39jt.js";import{_,y,u}from"./index-t5cfkz1e.js";import{f,Re,m,S,q}from"./index-byerrz46.js";function re(b){let{name:O,onInit:w,onShutdown:a,onNuke:p,telemetryEventName:t,skipPlatforms:h}=b;return{onServerStart:async(P,C)=>{if(h&&h.includes(process.platform)){process.stderr.write(`[${O}] skipping init on unsupported platform '${process.platform}'
|
|
3
|
+
`);return}if(w)await w(C);if(t)C.telemetry?.emit(t,{plugin:O})},onServerStop:async(P)=>{if(a)await a(P)},onNuke:async(P,C)=>{if(p)return p(P,C)}}}var ie=class{logger;source;constructor(b,O){this.logger=b,this.source=O}info(b,O){this.logger?.info?.(this.source,b,O)}warn(b,O){this.logger?.warn?.(this.source,b,O)}error(b,O){this.logger?.error?.(this.source,b,O)}debug(b,O){this.logger?.debug?.(this.source,b,O)}};import{existsSync as qe,rmSync as Je,statSync as We}from"fs";import{resolve as ze}from"path";function ae(b=I()){let O=[],w=ze(b),a=ne();if(!si(a,w))throw Error("Refusing to reset a path outside the agents directory");if(qe(w)&&We(w).isDirectory())Je(w,{recursive:!0,force:!0}),O.push(w);return{removed:O,agentDir:w}}var X="alias",ce=/^[a-zA-Z0-9_-]{1,64}$/,le=16384,ue=256,me=1024,Ye=new Set(["help","start","stop","restart","kill","list","status","setup","update","completion","autostart","export","import","diagnostics","nuke","doctor","log-level","gc","deploy","network","profile","peer-bootstrap","gateway-auth","info","key","system","url","health","notify","tunnel","session","git","config","log","plugin","ai","audit","alias","run"]);class H extends Error{code;constructor(b,O){super(O);this.code=b,this.name="AliasValidationError"}}class Q extends Error{constructor(b){super(`alias '${b}' already exists`);this.name="AliasConflictError"}}class W extends Error{constructor(b){super(`alias '${b}' not found`);this.name="AliasNotFoundError"}}function Xe(b){if(typeof b!=="string"||!ce.test(b))throw new H("invalid_name",`alias name must match ${ce} (got '${b}')`);if(Ye.has(b))throw new H("reserved_name",`alias name '${b}' is reserved`)}function ge(b){if(typeof b!=="string"||b.length===0)throw new H("invalid_command","alias command must be a non-empty string");if(b.length>le)throw new H("command_too_long",`alias command exceeds ${le} bytes`)}function pe(b){if(b===void 0)return;if(typeof b!=="string")throw new H("invalid_description","alias description must be a string");if(b.length>ue)throw new H("description_too_long",`alias description exceeds ${ue} chars`)}function fe(b){if(b===void 0||b===null||b==="")return;if(typeof b!=="string")throw new H("invalid_cwd","alias cwd must be a string");if(b.length>me)throw new H("cwd_too_long",`alias cwd exceeds ${me} chars`);if(b.includes("\x00"))throw new H("invalid_cwd","alias cwd must not contain NUL bytes")}function Ze(b){if(!b)return;try{return JSON.parse(b)}catch{return}}async function se(b){let O=await b.getAllPluginState(X),w=[];for(let a of O){let p=Ze(a.value);if(p)w.push(p)}return w.sort((a,p)=>a.name.localeCompare(p.name)),w}async function z(b,O){return(await se(b)).find((a)=>a.name===O)}function de(b){if(b===void 0||b===null)return null;let O=b.trim();return O===""?null:O}async function he(b,O){if(Xe(O.name),ge(O.command),pe(O.description),fe(O.cwd),await z(b,O.name))throw new Q(O.name);let a=new Date().toISOString(),p={id:crypto.randomUUID(),name:O.name,command:O.command,description:O.description,cwd:de(O.cwd),profile:R(),createdAt:a,updatedAt:a};return await b.setPluginState(X,p.id,JSON.stringify(p)),p}async function ye(b,O,w){let a=await z(b,O);if(!a)throw new W(O);if(w.command!==void 0)ge(w.command);if(w.description!==void 0)pe(w.description);if(w.cwd!==void 0)fe(w.cwd);let p={...a,command:w.command??a.command,description:w.description!==void 0?w.description:a.description,cwd:w.cwd!==void 0?de(w.cwd):a.cwd,updatedAt:new Date().toISOString()};return await b.setPluginState(X,p.id,JSON.stringify(p)),p}async function we(b,O){let w=await z(b,O);if(!w)throw new W(O);await b.deletePluginState(X,w.id)}function Z(){let b=B()??e();return{dir:b.dataDir,scope:b.name}}function Se(b){let{serviceRegistry:O,db:w}=b;return new E().get("/api-key",({request:a,set:p})=>{if(Ge(a))return p.status=403,{error:"Forbidden",message:"Browser requests are not permitted on /api/agent/api-key"};let t=k(Object.fromEntries(a.headers.entries()));if(!V(t))return p.status=401,{error:"Unauthorized",message:"Invalid or missing API key"};return{apiKey:K()}}).post("/reset-key",async({body:a,set:p})=>{let t=a.apiKey;if(!t||typeof t!=="string")return p.status=400,{error:"Missing required field: apiKey"};try{return await Mi(t),await e().keyVault.bindApiKey(t),e().logger.info("auth","Adopted backend-rotated agent API key via /reset-key"),{success:!0}}catch(h){return p.status=400,{error:"reset-key failed",message:h instanceof Error?h.message:String(h)}}},{body:r.Object({apiKey:r.String()})}).get("/audit",({query:a})=>{let p=a,t=p.limit?Math.min(5000,Math.max(1,Number.parseInt(p.limit,10)||100)):100,h=e().audit.listEvents({since:p.since,limit:t,event:p.event});return{events:h,count:h.length}},{query:r.Object({since:r.Optional(r.String()),limit:r.Optional(r.String()),event:r.Optional(r.String())})}).get("/setup/check",()=>{let a=Me();return{ready:a.filter((t)=>t.required).every((t)=>t.installed),dependencies:a}}).post("/setup/install",async({request:a,server:p,set:t})=>{let h=await Pe(a,"VIBECONTROLS_ALLOW_REMOTE_SETUP_INSTALL",p);if(h)return t.status=403,{error:"Forbidden",message:h};return await st()}).get("/url",async()=>{let a=O.getProvider("tunnel"),p=a&&a.getActiveTunnelUrl?await a.getActiveTunnelUrl():null,t=`http://localhost:${process.env.PORT||3005}`;return{url:p||t,tunnelUrl:p,localUrl:t,source:p?"tunnel":"local"}}).get("/lifecycle/state",()=>({state:O.getService("agent","lifecycle")?.getState()??"running"})).post("/lifecycle/stop",async({set:a})=>{let p=O.getService("agent","lifecycle");if(!p)return a.status=500,{error:"Lifecycle manager not initialized"};return await p.stop(),{state:"stopped"}}).post("/lifecycle/start",async({set:a})=>{let p=O.getService("agent","lifecycle");if(!p)return a.status=500,{error:"Lifecycle manager not initialized"};return await p.start(),{state:"running"}}).post("/lifecycle/kill",async({set:a})=>{let p=O.getService("agent","lifecycle");if(!p)return a.status=500,{error:"Lifecycle manager not initialized"};return setTimeout(()=>p.kill(),100),{state:"killing"}}).post("/log-level",async({body:a,request:p,server:t,set:h})=>{let P=await Pe(p,"VIBECONTROLS_ALLOW_REMOTE_LOG_LEVEL",t);if(P)return h.status=403,{error:"Forbidden",message:P};let C=String(a.level??"").toLowerCase();if(!["debug","info","warn","error"].includes(C))return h.status=400,{error:"Invalid level",message:"level must be debug | info | warn | error"};return e().logger.setLevel(C),e().logger.info("agent",`Log level set to ${C} via API`),{ok:!0,level:C}},{body:r.Object({level:r.String()})}).post("/reset",async({body:a,request:p,server:t,set:h})=>{if(!a.confirm)return h.status=400,{error:"Reset confirmation required",message:"Send { confirm: true } to reset local agent state."};let P=await Pe(p,"VIBECONTROLS_ALLOW_REMOTE_RESET",t);if(P)return h.status=403,{error:"Forbidden",message:P};let C=O.getService("agent","lifecycle");try{if(C)await C.prepareForReset()}catch(Y){e().logger.warn("agent","prepareForReset failed during reset \u2014 proceeding to wipe anyway",{error:String(Y)})}try{T.configure({globalGatewayUrl:"",workspaceGatewayUrl:void 0,clientId:"",clientSecret:"",workspaceId:void 0})}catch{}await w.close();let{removed:x,agentDir:N}=ae();e().logger.info("agent","Reset wiped local agent state",{agentDir:N,removed:x});let j=new Uint8Array(32);crypto.getRandomValues(j);let J=`vcak_${Buffer.from(j).toString("base64url")}`;return M({"static-api-key":J},Z()),e().setBootState("awaiting-config"),h.status=200,{success:!0,state:"awaiting-config",...Be(p,t)||process.env.VIBECONTROLS_RETURN_RESET_API_KEY==="1"?{newApiKey:J}:{},agentDir:N,removed:x}},{body:r.Object({confirm:r.Boolean()})}).post("/sessions/:sessionId/share",async({params:a,body:p,server:t,request:h,set:P})=>{if(!Be(h,t)&&process.env.VIBECONTROLS_ALLOW_REMOTE_SESSION_SHARE!=="1")return P.status=403,{error:"Forbidden",message:"Session-share mint must come from a local request unless VIBECONTROLS_ALLOW_REMOTE_SESSION_SHARE=1."};if(!be(a.sessionId))return P.status=400,{error:"BadRequest",message:"invalid sessionId"};let C=et(p?.expiresIn)??1800000,x=crypto.randomUUID(),N=new Uint8Array(32);crypto.getRandomValues(N);let j=`vcak_${Buffer.from(N).toString("base64url")}`,J=new Date(Date.now()+C).toISOString(),oe=[...(await import("./agent-config-v9d7gcz0.js")).readAgentConfig({dir:Z().dir}).apiKeys??[],{id:x,name:`session-share:${a.sessionId}:${p?.label??"viewer"}`,key:j,scopes:["read"],expiresAt:J,createdAt:new Date().toISOString()}];(await import("./agent-config-v9d7gcz0.js")).writeAgentConfig({apiKeys:oe},Z());let Y=O.getProvider("tunnel"),_e=(Y&&Y.getActiveTunnelUrl?await Y.getActiveTunnelUrl():null)??`http://localhost:${process.env.PORT||3005}`,je=Nt({pathPrefixes:[`/terminal/${a.sessionId}`],methods:["GET"]},Math.min(600,Math.floor(C/1000))),He=`${_e.replace(/\/$/,"")}/terminal/${encodeURIComponent(a.sessionId)}/#vt=${encodeURIComponent(je.token)}`;return e().logger.info("session-share","Minted share credential",{sessionId:a.sessionId,keyId:x,expiresAt:J}),{ok:!0,keyId:x,apiKey:j,joinUrl:He,sessionId:a.sessionId,expiresAt:J}},{params:r.Object({sessionId:r.String()}),body:r.Optional(r.Object({permissions:r.Optional(r.Array(r.String())),expiresIn:r.Optional(r.String()),label:r.Optional(r.String())}))}).get("/aliases",async()=>({aliases:await se(w)})).get("/aliases/:name",async({params:a,set:p})=>{let t=await z(w,a.name);if(!t)return p.status=404,{error:"Alias not found"};return t},{params:r.Object({name:r.String()})}).post("/aliases",async({body:a,set:p})=>{try{let t=await he(w,a);return p.status=201,t}catch(t){if(t instanceof Q)return p.status=409,{error:"Alias already exists",message:t.message};if(t instanceof H)return p.status=400,{error:t.code,message:t.message};throw t}},{body:r.Object({name:r.String(),command:r.String(),description:r.Optional(r.String()),cwd:r.Optional(r.Union([r.String(),r.Null()]))})}).put("/aliases/:name",async({params:a,body:p,set:t})=>{try{return await ye(w,a.name,p)}catch(h){if(h instanceof W)return t.status=404,{error:"Alias not found"};if(h instanceof H)return t.status=400,{error:h.code,message:h.message};throw h}},{params:r.Object({name:r.String()}),body:r.Object({command:r.Optional(r.String()),description:r.Optional(r.String()),cwd:r.Optional(r.Union([r.String(),r.Null()]))})}).delete("/aliases/:name",async({params:a,set:p})=>{try{return await we(w,a.name),p.status=204,null}catch(t){if(t instanceof W)return p.status=404,{error:"Alias not found"};throw t}},{params:r.Object({name:r.String()})}).post("/aliases/:name/execute",async({params:a,body:p,set:t})=>{let h=await z(w,a.name);if(!h)return t.status=404,{error:"Alias not found"};let P=p?.args??[],C=await mi(h,P);e().audit.emit("agent","alias.executed",{exit_code:C.exit_code});let x=ve("alias.executed",{exit_code:C.exit_code});if(!x.ok)e().logger.debug("alias",`telemetry validate failed: ${x.reason}`);if(C.timed_out)t.status=408;return{exit_code:C.exit_code,stdout:C.stdout,stderr:C.stderr,duration_ms:C.duration_ms,truncated:C.truncated,cwd:C.cwd}},{params:r.Object({name:r.String()}),body:r.Optional(r.Object({args:r.Optional(r.Array(r.String()))}))}).post("/sessions/share/:keyId/revoke",async({params:a,server:p,request:t,set:h})=>{if(!Be(t,p)&&process.env.VIBECONTROLS_ALLOW_REMOTE_SESSION_SHARE!=="1")return h.status=403,{error:"Forbidden"};let P=await import("./agent-config-v9d7gcz0.js"),C=Z(),x=P.readAgentConfig({dir:C.dir}),N=(x.apiKeys??[]).length,j=(x.apiKeys??[]).filter((J)=>J.id!==a.keyId);if(j.length===N)return h.status=404,{error:"No such share key"};return P.writeAgentConfig({apiKeys:j},C),{ok:!0,revoked:a.keyId}},{params:r.Object({keyId:r.String()})})}function et(b){if(!b)return null;let O=/^(\d+)([smhdw]?)$/.exec(b.trim());if(!O)return null;let w=Number(O[1]),a=O[2]||"m";return a==="s"?w*1000:a==="m"?w*60000:a==="h"?w*3600000:a==="d"?w*86400000:w*7*86400000}var tt="http://localhost:3005";function Ae(b){b.command("health").description("Check health of a VibeControls agent instance").option("-n, --name <name>","Agent instance name").option("--agent-url <url>","Agent URL",tt).option("--json","Emit JSON").option("--plain","Force plain text output").action(async function(O){try{let w={...b.opts(),...O};await y({mode:_(w),fetchData:async()=>{if(w.name){let t=await new D().checkHealth(w.name);return{mode:"named",agentUrl:f(w),name:w.name,healthy:t.healthy,details:t.details??{}}}let a=f(w);try{let p=await S(a,"/health");return{mode:"url",agentUrl:a,healthy:!0,details:p}}catch(p){return{mode:"url",agentUrl:a,healthy:!1,details:{status:"unhealthy",...p instanceof Error?{error:A(p)}:{}}}}},plain:(a)=>{if(g("Agent Health"),c(),a.mode==="named"){if(!a.healthy){s(`Agent instance ${i.bold(a.name??"")} is not responding.`);return}let p=a.details;if(n("Instance",a.name??""),n("Status",G(p.status??"healthy")),p.uptime!==void 0)n("Uptime",`${p.uptime}s`);if(p.checks){c(),o(`${d.info} Health checks:`);for(let[t,h]of Object.entries(p.checks)){let P=h.status==="healthy"?d.success:d.error;n(` ${P} ${t}`,G(h.status))}}}else{if(n("URL",a.agentUrl),n("Status",G(a.details.status??"unhealthy")),a.details.version)n("Version",a.details.version);if(a.details.uptime!==void 0)n("Uptime",`${a.details.uptime}s`);if(a.details.timestamp)n("Timestamp",a.details.timestamp);if(a.details.checks){c(),o(`${d.info} Health checks:`);for(let[p,t]of Object.entries(a.details.checks)){let h=t.status==="healthy"?d.success:d.error;n(` ${h} ${p}`,G(t.status))}}}if(c(),a.healthy)l(`${d.success} Agent is healthy.`)},interactive:async(a)=>{let p=[];if(a.mode==="named")p.push(`Instance: ${a.name??""}`);else p.push(`URL: ${a.agentUrl}`);if(p.push(`Status: ${G(a.details.status??(a.healthy?"healthy":"unhealthy"))}`),a.details.version)p.push(`Version: ${a.details.version}`);if(a.details.uptime!==void 0)p.push(`Uptime: ${a.details.uptime}s`);if(a.details.timestamp)p.push(`Time: ${a.details.timestamp}`);if(a.details.checks){p.push(""),p.push("Checks:");for(let[t,h]of Object.entries(a.details.checks))p.push(` ${t}: ${h.status}`)}await U({title:"Agent Health",body:p.join(`
|
|
4
|
+
`),footer:"press q to exit"})},json:(a)=>({mode:a.mode,agentUrl:a.agentUrl,name:a.name??null,healthy:a.healthy,details:a.details})})}catch(w){s(`Health check failed: ${A(w)}`)}})}import{platform as nt,arch as rt,release as it,hostname as ot,cpus as at,totalmem as ct}from"os";var lt="http://localhost:3005";function $e(b){b.command("info").description("Show local and remote VibeControls agent information").option("--agent-url <url>","Agent URL",lt).option("--json","Emit JSON").option("--plain","Force plain text output").action(async function(O){try{let w={...b.opts(),...O},a=f(w),p=encodeURIComponent(m(w));await y({mode:_(w),fetchData:async()=>{let t={hostname:ot(),platform:nt(),arch:rt(),release:it(),cpus:at().length,totalMemory:ct(),nodeVersion:process.version,bunVersion:process.versions.bun};try{let h=await S(a,`/api/profiles/${p}/agent/version`);return{local:t,agentUrl:a,remote:h}}catch(h){return{local:t,agentUrl:a,remote:null,remoteError:h instanceof Error?A(h):String(h)}}},plain:(t)=>{if(g("VibeControls Agent Info"),c(),o(`${d.info} Local System`),n("Hostname",t.local.hostname),n("Platform",`${t.local.platform} ${t.local.arch}`),n("OS Release",t.local.release),n("CPUs",String(t.local.cpus)),n("Total Memory",Qe(t.local.totalMemory)),n("Node.js",t.local.nodeVersion),t.local.bunVersion)n("Bun",t.local.bunVersion);if(c(),o(`${d.info} Remote Agent`),n("URL",t.agentUrl),t.remote){if(n("Version",i.bold(t.remote.version)),t.remote.build)n("Build",t.remote.build);if(t.remote.commit)n("Commit",t.remote.commit);if(t.remote.nodeVersion)n("Node.js (remote)",t.remote.nodeVersion);if(t.remote.bunVersion)n("Bun (remote)",t.remote.bunVersion)}else n("Status",i.dim("not reachable"));c()},interactive:async(t)=>{let h=[];if(h.push("Local System"),h.push(` Hostname: ${t.local.hostname}`),h.push(` Platform: ${t.local.platform} ${t.local.arch}`),h.push(` OS Release: ${t.local.release}`),h.push(` CPUs: ${t.local.cpus}`),h.push(` Total Memory: ${Qe(t.local.totalMemory)}`),h.push(` Node.js: ${t.local.nodeVersion}`),t.local.bunVersion)h.push(` Bun: ${t.local.bunVersion}`);if(h.push(""),h.push("Remote Agent"),h.push(` URL: ${t.agentUrl}`),t.remote){if(h.push(` Version: ${t.remote.version}`),t.remote.build)h.push(` Build: ${t.remote.build}`);if(t.remote.commit)h.push(` Commit: ${t.remote.commit}`);if(t.remote.nodeVersion)h.push(` Node.js: ${t.remote.nodeVersion} (remote)`);if(t.remote.bunVersion)h.push(` Bun: ${t.remote.bunVersion} (remote)`)}else h.push(" Status: not reachable");await U({title:"VibeControls Agent Info",body:h.join(`
|
|
5
|
+
`),footer:"press q to exit"})},json:(t)=>({local:t.local,agentUrl:t.agentUrl,remote:t.remote,remoteError:t.remoteError??null})})}catch(w){s(`Failed to get info: ${A(w)}`)}})}var ut="http://localhost:3005";function ke(b){b.command("system").description("Show system information for a running VibeControls agent").option("--agent-url <url>","Agent URL",ut).option("--json","Emit JSON").option("--plain","Force plain text output").action(async function(O){try{let w={...b.opts(),...O},a=f(w),p=encodeURIComponent(m(w));await y({mode:_(w),fetchData:()=>S(a,`/api/profiles/${p}/agent/system`),plain:(t)=>{if(g("Agent System Information"),c(),o(`${d.info} Agent`),n("Version",i.bold(t.agentVersion)),t.bunVersion)n("Bun",t.bunVersion);if(t.environment)n("Environment",t.environment);n("Uptime",Gr(t.uptime)),c(),o(`${d.info} Platform`),n("OS",`${t.platform} ${t.arch}`),n("Hostname",t.hostname),n("Release",t.release),c(),o(`${d.info} Resources`),n("CPUs",String(t.cpus)),n("Total Memory",Qe(t.totalMemory)),n("Free Memory",Qe(t.freeMemory)),c(),o(`${d.info} Paths`),n("Home",t.homeDir),n("CWD",t.cwd),c()},interactive:async(t)=>{let h=["Agent",` Version: ${t.agentVersion}`,...t.bunVersion?[` Bun: ${t.bunVersion}`]:[],...t.environment?[` Environment: ${t.environment}`]:[],` Uptime: ${Gr(t.uptime)}`,"","Platform",` OS: ${t.platform} ${t.arch}`,` Hostname: ${t.hostname}`,` Release: ${t.release}`,"","Resources",` CPUs: ${t.cpus}`,` Total Mem: ${Qe(t.totalMemory)}`,` Free Mem: ${Qe(t.freeMemory)}`,"","Paths",` Home: ${t.homeDir}`,` CWD: ${t.cwd}`];await U({title:"Agent System Information",body:h.join(`
|
|
6
|
+
`),footer:"press q to exit"})}})}catch(w){s(`Failed to get system info: ${A(w)}`)}})}var mt="http://localhost:3005";async function Ie(b){try{let O=await fetch(`${b}/health/ready`);if(O.status===200||O.status===503)return await O.json();return{healthy:!1,status:O.status}}catch{return{healthy:!1,error:"unreachable"}}}async function Oe(b,O){try{let w=await Re(b);if(!w)return null;let a=await fetch(`${b}/api/profiles/${O}/agent/api-key`,{headers:{"x-agent-api-key":w}});if(!a.ok)return w;return(await a.json()).apiKey??w}catch{return null}}async function gt(b,O){try{return await S(b,`/api/profiles/${O}/plugins`)}catch{return null}}function ee(b){let O=b??{};if(O.error==="unreachable")return i.red("unreachable");if(typeof O.status==="number"&&O.status>=400)return i.red(`http ${O.status}`);let w=typeof O.status==="string"?O.status:"",a=typeof O.bootState==="string"?O.bootState:"";if(w==="ok"&&a==="ready")return i.green("ready");if(a==="awaiting-config")return i.yellow("awaiting-config");if(a==="initializing")return i.yellow("initializing");if(a==="degraded"||w==="degraded")return i.red(`degraded${a?` (${a})`:""}`);if(O.healthy===!1)return i.red("unhealthy");return i.green("healthy")}function pt(b){let w=(b??{}).lastFinalizeError;if(!w||typeof w!=="object")return null;let a=w;if(typeof a.message!=="string"||typeof a.at!=="string")return null;return{message:a.message,at:a.at,attempt:typeof a.attempt==="number"?a.attempt:void 0}}function Ue(b){let O=b??{},w=typeof O.bootState==="string"?O.bootState:"";if(w!=="awaiting-config"&&w!=="degraded")return null;let a=[],p=pt(b);if(p)if(a.push(`${i.gray("\xB7")} Last error: ${i.red(p.message)}`),p.attempt!==void 0)a.push(`${i.gray("\xB7")} Background retry: attempt ${p.attempt}`);else a.push(`${i.gray("\xB7")} Last seen: ${p.at}`);if(w==="awaiting-config")a.push(`${i.gray("\xB7")} Force retry now: ${i.bold("vibe retry-config")}`);return a.push(`${i.gray("\xB7")} Full trace: ${i.bold("vibe logs --since 10m")}`),a.join(`
|
|
7
|
+
`)}async function ft(b,O){let w={agentUrl:O},a=b.jsonKey??b.title.toLowerCase(),p;try{p=await b.render(w)}catch(h){p=i.red(`error (${h.message})`)}let t=null;if(b.json)try{t=await b.json(w)}catch{t=null}return{title:b.title,jsonKey:a,text:p,json:t}}async function Ee(b){let w=Pt().getStatusSections();return Promise.all(w.map((a)=>ft(a,b)))}function Ce(b){b.command("status").description("Show comprehensive status of VibeControls agent instance(s)").option("-n, --name <name>","Agent instance name").option("--agent-url <url>","Agent URL",mt).option("--profile <name>","Target a specific profile by name").option("--json","Emit JSON").option("--plain","Force plain text output").action(async function(O){try{let w={...b.opts(),...O},a=new D;await y({mode:_(w),fetchData:async()=>{if(w.name){let P=await a.getStatus(w.name);if(!P)return{kind:"instance",agentUrl:f(w),instance:null,contributed:[]};let C=P.status==="running"&&P.port?`http://localhost:${P.port}`:f(w);if(P.status!=="running")return{kind:"instance",agentUrl:C,instance:P,contributed:[]};let x=encodeURIComponent(m({profile:P.name})),[N,j,J,te]=await Promise.all([Ie(C),Oe(C,x),gt(C,x),Ee(C)]);return{kind:"instance",agentUrl:C,instance:P,health:N,apiKey:j,plugins:J,contributed:te}}let p=await a.listInstances(),t=p.filter((P)=>P.status==="running"),h=await Promise.all(t.map(async(P)=>{let C=`http://localhost:${P.port}`,x=encodeURIComponent(m({profile:P.name})),[N,j,J]=await Promise.all([Ie(C),Oe(C,x),Ee(C)]);return{name:P.name,agentUrl:C,health:N,apiKey:j,contributed:J}}));return{kind:"overview",instances:p,perRunning:h}},plain:(p)=>{if(p.kind==="instance"){if(!p.instance){s(`Agent instance ${i.bold(w.name??"")} not found.`);return}let h=p.instance;if(g(`Agent Status: ${h.name}`),n("Name",h.name),n("Status",G(h.status)),n("PID",h.pid?String(h.pid):i.dim("n/a")),n("Port",h.port?String(h.port):i.dim("n/a")),n("Host",h.config?.host||i.dim("n/a")),n("Database",h.config?.dbPath||i.dim("n/a")),h.startTime)n("Started",v(h.startTime));if(h.status==="running"){c(),n("Health",ee(p.health));let P=Ue(p.health);if(P)c(),console.log(P),c();let C=p.health?.uptime;if(C)n("Uptime",String(C));if(n("API Key",p.apiKey??i.dim("(unavailable)")),p.plugins){let x=p.plugins.plugins??[],N=x.filter((j)=>j.isCore).length;n("Plugins",`${x.length} total (${N} core, ${x.length-N} external)`)}else n("Plugins",i.dim("(unable to fetch)"));for(let x of p.contributed){if(x.text===null)continue;n(x.title,x.text)}}c();return}if(g("Agent Instances"),c(),!p.instances||p.instances.length===0){o(`${d.info} No agent instances found.`),o(`Run ${i.bold("vibe start")} to start an agent.`);return}let t=p.instances.map((h)=>({Name:h.name,Status:G(h.status),PID:h.pid||"-",Port:h.port||"-",Started:h.startTime?v(h.startTime):"-"}));F(t),c();for(let h of p.perRunning){c(),g(`Quick Status: ${h.name}`),n("Health",ee(h.health));let P=Ue(h.health);if(P)c(),console.log(P),c();n("API Key",h.apiKey??i.dim("(unavailable)"));for(let C of h.contributed){if(C.text===null)continue;n(C.title,C.text)}}c(),o(`${d.info} ${p.instances.length} instance(s) found. Use ${i.bold("vibe status -n <name>")} for full details.`)},interactive:async(p)=>{let t=[];if(p.kind==="instance"){if(!p.instance)t.push(`Agent instance "${w.name??""}" not found.`);else{let h=p.instance;if(t.push(`Name: ${h.name}`),t.push(`Status: ${G(h.status)}`),t.push(`PID: ${h.pid??"n/a"}`),t.push(`Port: ${h.port??"n/a"}`),t.push(`Host: ${h.config?.host??"n/a"}`),t.push(`Database: ${h.config?.dbPath??"n/a"}`),h.startTime)t.push(`Started: ${v(h.startTime)}`);if(h.status==="running"){if(t.push(""),t.push(`Health: ${ee(p.health)}`),t.push(`API Key: ${p.apiKey??"(unavailable)"}`),p.plugins){let P=p.plugins.plugins??[],C=P.filter((x)=>x.isCore).length;t.push(`Plugins: ${P.length} (${C} core, ${P.length-C} external)`)}for(let P of p.contributed){if(P.text===null)continue;t.push(`${P.title.padEnd(9)} ${P.text}`)}}}await U({title:`vibe status${w.name?` \u2014 ${w.name}`:""}`,body:t.join(`
|
|
8
|
+
`),footer:"press q to exit"});return}if(!p.instances||p.instances.length===0)t.push("No agent instances found."),t.push("Run `vibe start` to start an agent.");else for(let h of p.instances){t.push(`${i.bold(h.name)} ${G(h.status)}`),t.push(` PID: ${h.pid??"-"}`),t.push(` Port: ${h.port??"-"}`),t.push(` Started: ${h.startTime?v(h.startTime):"-"}`);let P=p.perRunning.find((C)=>C.name===h.name);if(P){t.push(` Health: ${ee(P.health)}`);for(let C of P.contributed){if(C.text===null)continue;t.push(` ${C.title.padEnd(9)} ${C.text}`)}}t.push("")}await U({title:`vibe status \u2014 ${p.instances.length} instance(s)`,body:t.join(`
|
|
9
|
+
`),footer:"press q to exit"})},json:(p)=>{let t=(h)=>Object.fromEntries(h.map((P)=>[P.jsonKey,P.json]));if(p.kind==="instance"){if(!p.instance)return{instance:null};let h={instance:{name:p.instance.name,status:p.instance.status,pid:p.instance.pid,port:p.instance.port,host:p.instance.config?.host,dbPath:p.instance.config?.dbPath,startTime:p.instance.startTime}};if(p.instance.status==="running")h.health=p.health??null,h.plugins=p.plugins??null,Object.assign(h,t(p.contributed));return h}return{instances:p.instances.map((h)=>({name:h.name,status:h.status,pid:h.pid,port:h.port,startTime:h.startTime})),perRunning:p.perRunning.map((h)=>({name:h.name,health:h.health??null,...t(h.contributed)}))}}})}catch(w){let a=w instanceof Error?A(w):String(w);s(`Failed to get status: ${a}`)}})}var dt="http://localhost:3005";function xe(b){b.command("url").description("Show the active URL for a running VibeControls agent").option("--agent-url <url>","Agent URL",dt).option("--json","Emit JSON").option("--plain","Force plain text output").action(async(O)=>{try{let w={...b.opts(),...O},a=f(O),p=encodeURIComponent(m(w));await y({mode:_(w),fetchData:()=>S(a,`/api/profiles/${p}/agent/url`),plain:(t)=>{if(g("Agent URL"),c(),n("Active URL",i.bold(t.url)),n("Local URL",t.localUrl),t.tunnelUrl)n("Tunnel URL",i.cyan(t.tunnelUrl));if(n("Mode",t.isTunnel?`${d.running} Tunnel active`:`${d.info} Local only`),c(),t.isTunnel)o(`${d.info} Agent is accessible via tunnel at ${i.bold(t.tunnelUrl)}`);else o(`${d.info} Agent is running locally at ${i.bold(t.localUrl)}`)},interactive:async(t)=>{let h=[` Active URL: ${t.url}`,` Local URL: ${t.localUrl}`,` Tunnel URL: ${t.tunnelUrl??"-"}`,` Mode: ${t.isTunnel?"Tunnel active":"Local only"}`];await U({title:"Agent URL",body:h.join(`
|
|
10
|
+
`)})},json:(t)=>L(t)})}catch(w){s(`Failed to get URL: ${w.message}`)}})}var Le="http://localhost:3005";function Ne(b){let O=b.command("gateway-auth").description("Manage gateway authentication for VibeControls agent");O.command("configure").description("Configure gateway authentication credentials").requiredOption("--global-url <url>","Global gateway URL").requiredOption("--workspace-url <url>","Workspace gateway URL").requiredOption("--client-id <id>","OAuth client ID").requiredOption("--client-secret <secret>","OAuth client secret").option("--workspace-id <id>","Workspace ID for auto-report").option("--agent-record-id <id>","Existing backend agent record ID").option("--agent-url <url>","Agent URL",Le).option("--json","Emit JSON result").action(async(w)=>{try{let a={...b.opts(),...w},p=f(w),t=encodeURIComponent(m(a)),h=await q(p,`/api/profiles/${t}/agent/gateway-auth`,{globalGatewayUrl:w.globalUrl,workspaceGatewayUrl:w.workspaceUrl,clientId:w.clientId,clientSecret:w.clientSecret,workspaceId:w.workspaceId,agentRecordId:w.agentRecordId});if(u(a,{ok:!!h.success,message:h.message??null,globalGatewayUrl:w.globalUrl,workspaceGatewayUrl:w.workspaceUrl,clientId:w.clientId,workspaceId:w.workspaceId??null,agentRecordId:w.agentRecordId??null}))return;if(g("Configure Gateway Authentication"),c(),o(`${d.info} Sending gateway auth configuration...`),c(),h.success){if(l(`${d.success} Gateway authentication configured successfully.`),c(),n("Global URL",w.globalUrl),n("Workspace URL",w.workspaceUrl),n("Client ID",w.clientId),n("Client Secret",i.dim("********")),w.workspaceId)n("Workspace ID",w.workspaceId);if(w.agentRecordId)n("Agent Record ID",w.agentRecordId)}else s(h.message||"Failed to configure gateway authentication.");c()}catch(a){s(`Failed to configure gateway auth: ${a instanceof Error?A(a):String(a)}`)}}),O.command("status").description("Check gateway authentication status").option("--agent-url <url>","Agent URL",Le).option("--json","Emit JSON").option("--plain","Force plain text output").action(async(w)=>{try{let a={...b.opts(),...w},p=f(w),t=encodeURIComponent(m(a));await y({mode:_(a),fetchData:()=>S(p,`/api/profiles/${t}/agent/gateway-auth`),plain:(h)=>{if(g("Gateway Authentication Status"),c(),n("Configured",h.configured?`${d.success} ${i.green("Yes")}`:`${d.error} ${i.red("No")}`),h.configured){if(n("Global URL",h.config?.globalGatewayUrl||i.dim("n/a")),n("Workspace URL",h.config?.workspaceGatewayUrl||i.dim("n/a")),n("Client ID",h.config?.clientId||i.dim("n/a")),h.config?.workspaceId)n("Workspace ID",h.config.workspaceId)}else c(),o(`${d.info} Run ${i.bold("vibe gateway-auth configure")} to set up gateway authentication.`);c()},interactive:async(h)=>{let P=h.configured?[" Configured: yes",` Global URL: ${h.config?.globalGatewayUrl??"n/a"}`,` Workspace URL: ${h.config?.workspaceGatewayUrl??"n/a"}`,` Client ID: ${h.config?.clientId??"n/a"}`,` Workspace ID: ${h.config?.workspaceId??"-"}`]:[" Configured: no",""," Run `vibe gateway-auth configure` to set up."];await U({title:"Gateway Authentication Status",body:P.join(`
|
|
11
|
+
`)})},json:(h)=>L(h)})}catch(a){s(`Failed to get gateway auth status: ${a instanceof Error?A(a):String(a)}`)}})}function Te(b,O){Ae(b),$e(b),jr(b),ke(b),Ce(b),xe(b),Ne(b)}var De="agent";function Or(b){let O=null,w=re({name:De,onShutdown:()=>{ui(),ci()}});return{name:De,version:"2.3.0",description:"Core agent identity, system info, setup, gateway authentication, and auto-report",capabilities:{storage:"rw",secrets:"rw",gateway:!0,broadcast:!0,audit:!0,telemetry:!0},tags:["backend","cli"],cliCommand:"agent",apiPrefix:"/api/agent",publicPaths:["/identity","/tunnel"],createRoutes:(a)=>(O=a.db,Se(a)),onCliSetup:async(a,p)=>{Te(a,p)},onServerReady:async(a,p)=>{if(O){let t=a,h=(typeof t.decorator?.apiKey==="string"?t.decorator.apiKey:void 0)??(typeof t.store?.apiKey==="string"?t.store.apiKey:void 0)??"unknown",P=new ie(p.logger,"agent-plugin");li(O,p.serviceRegistry,h).catch((C)=>{P.warn(`Auto-report background task failed: ${C}`)})}},onServerStop:w.onServerStop}}export{Or as createPlugin};
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{E}from"./index-w0m3jm0s.js";import{Tt,e}from"./index-0qjbnyg4.js";import{be,we,cr,Kr,Qr,k,V}from"./index-mmx2kp76.js";function sr(n,t){let s=new E,r=[],o=new Set;function i(l){return l.endsWith("/")&&l!=="/"?l.slice(0,-1):l}function a(l,u){if(!u.startsWith("/"))return null;if(u==="/"||u.includes("..")||u.includes("*"))return null;let f=i(l),d=i(`${f}${u}`);if(d===f||!d.startsWith(`${f}/`))return null;return d}function c(l){if(!l.createRoutes)return!1;if(o.has(l.name))return!1;let u=l.apiPrefix||`/api/${l.name}`;try{let f=l.createRoutes(n.routeDepsFor(l,t));if(e().logger.info("plugin-router",`Plugin '${l.name}' registered routes`,{prefix:u}),s.use(new E({prefix:u}).derive(()=>({pluginContext:{chain:[l.name],parentPlugin:void 0,activePlugin:l.name}})).use(f)),l.publicPaths)for(let d of l.publicPaths){let g=a(u,d);if(!g){e().logger.warn("plugin-router",`Ignoring unsafe public path from plugin '${l.name}'`,{publicPath:d,prefix:u});continue}r.push(g)}return o.add(l.name),!0}catch(f){return e().logger.error("plugin-router",`Failed to mount routes for plugin '${l.name}'`,{error:String(f)}),!1}}for(let l of n.getAllPlugins())c(l);return{routes:s,getPublicPaths:()=>[...r],mountPlugin:c}}var M=1e4;function R(n,t){let s=process.env[n];if(!s)return t;let r=Number.parseInt(s,10);return Number.isFinite(r)&&r>0?r:t}function G(){return[{name:"health",match:(n)=>n.startsWith("/health"),perMinute:R("VIBECONTROLS_RATELIMIT_HEALTH",1000)},{name:"gateway-auth",match:(n)=>n.startsWith("/api/agent/gateway-auth"),perMinute:R("VIBECONTROLS_RATELIMIT_GATEWAY_AUTH",10)},{name:"plugin-install",match:(n)=>n.startsWith("/api/plugins/install"),perMinute:R("VIBECONTROLS_RATELIMIT_PLUGIN_INSTALL",5)},{name:"alias-exec",match:(n)=>/^\/api\/aliases\/[^/]+\/execute/.test(n),perMinute:R("VIBECONTROLS_RATELIMIT_ALIAS_EXEC",30)},{name:"api",match:(n)=>n.startsWith("/api/"),perMinute:R("VIBECONTROLS_RATELIMIT_API",100)}]}function H(n,t,s){for(let r of n)if(r.match(t,s))return r;return null}function S(n){if(!n)return!1;return n==="127.0.0.1"||n==="::1"||n==="::ffff:127.0.0.1"||n.startsWith("127.")}function K(n=Date.now){let t=new Map,s=(r,o)=>{t.delete(r),t.set(r,o)};return{take(r,o,i){let a=n(),c=t.get(r);if(!c)c={tokens:o,lastRefillMs:a,capacity:o,refillPerSec:i};else{let u=(a-c.lastRefillMs)/1000;c.tokens=Math.min(o,c.tokens+u*i),c.lastRefillMs=a,c.capacity=o,c.refillPerSec=i}let l=c.tokens>=1;if(l)c.tokens-=1;if(s(r,c),t.size>M){let u=t.keys();while(t.size>M){let f=u.next();if(f.done)break;t.delete(f.value)}}return l},retryAfterSec(r){let o=t.get(r);if(!o)return 1;if(o.refillPerSec<=0)return 60;let i=1-o.tokens;if(i<=0)return 0;return Math.max(1,Math.ceil(i/o.refillPerSec))},size(){return t.size},reset(){t.clear()}}}function Oi(n={}){let t=n.classes??G(),s=n.store??K();return new E({name:"plugin/rate-limit"}).onRequest(({request:r,set:o,server:i})=>{let a;try{a=i?.requestIP(r)?.address??null}catch{a=null}if(S(a))return;let c=new URL(r.url),l=H(t,c.pathname,r.method);if(!l)return;let f=`${a??"unknown"}|${l.name}`,d=l.perMinute/60;if(!s.take(f,l.perMinute,d)){let g=s.retryAfterSec(f);o.status=429;let T=o.headers??={};return T["Retry-After"]=String(g),{error:"rate_limited",message:`Too many requests for ${l.name}; retry after ${g}s.`,retryAfterSec:g}}}).as("global")}var J=(()=>{let n=process.env.VIBECONTROLS_WS_MAX_PER_IP,t=n?Number.parseInt(n,10):NaN;return Number.isFinite(t)&&t>0?t:5})();function P(n=J){let t=new Map;return{accept(s,r){if(S(s))return!0;let o=s??"unknown",i=t.get(o);if(!i)i=new Set,t.set(o,i);if(i.size>=n)return!1;return i.add(r),!0},release(s,r){if(S(s))return;let o=s??"unknown",i=t.get(o);if(!i)return;if(i.delete(r),i.size===0)t.delete(o)},size(s){let r=s??"unknown";return t.get(r)?.size??0}}}function or(n){let t=new Set,s=new Map,r=new Map;return{accept(o,i,a){if(t.size>=n.maxGlobal)return!1;let c=s.get(o)??new Set;if(c.size>=n.maxPerKey)return!1;let l=i??"unknown";if(!S(i)){let u=r.get(l)??new Set;if(u.size>=n.maxPerIp)return!1;u.add(a),r.set(l,u)}return t.add(a),c.add(a),s.set(o,c),!0},release(o,i,a){t.delete(a);let c=s.get(o);if(c){if(c.delete(a),c.size===0)s.delete(o)}if(!S(i)){let l=i??"unknown",u=r.get(l);if(u){if(u.delete(a),u.size===0)r.delete(l)}}},globalCount(){return t.size},keyCount(o){return s.get(o)?.size??0}}}function w(n,t){let s=process.env[n];if(!s)return t;let r=Number.parseInt(s,10);return Number.isFinite(r)&&r>0?r:t}var N={maxGlobal:w("VIBE_TERMINAL_WS_MAX_GLOBAL",64),maxPerKey:w("VIBE_TERMINAL_WS_MAX_PER_SESSION",4),maxPerIp:w("VIBE_TERMINAL_WS_MAX_PER_IP",16)},Bi={maxGlobal:w("VIBE_CODE_SERVER_WS_MAX_GLOBAL",64),maxPerKey:w("VIBE_CODE_SERVER_WS_MAX_PER_SESSION",8),maxPerIp:w("VIBE_CODE_SERVER_WS_MAX_PER_IP",16)};function Y(n){if(!n)return new Set;let t=new Set;for(let s of n.split(",")){let r=s.trim();if(r)t.add(r)}return t}var v=null;function Q(){let n=process.env.VIBE_TRUSTED_PROXIES;if(!v||v.raw!==n)v={raw:n,set:Y(n)};return v.set}function Ue(n,t){let s=Q();if(!!n&&(S(n)||s.has(n))&&t){let o=t["x-forwarded-for"];if(o){let a=o.split(",")[0]?.trim();if(a)return a}let i=t["x-real-ip"];if(i)return i}return n}import{EventEmitter as Z}from"events";var O=P(),_=new Z;_.setMaxListeners(100);function ge(n,t){let s={type:n,payload:t,timestamp:new Date().toISOString()};_.emit("ws:event",s)}var B=(()=>{let n=process.env.VIBECONTROLS_MAX_WS_CLIENTS,t=n?Number.parseInt(n,10):NaN;return Number.isFinite(t)&&t>0?t:200})(),ee=(()=>{let n=process.env.VIBECONTROLS_MAX_WS_BUFFER_PER_CLIENT,t=n?Number.parseInt(n,10):NaN;return Number.isFinite(t)&&t>0?t:100})();function Nr(){let n=new Set;return _.on("ws:event",(t)=>{let s=JSON.stringify(t);for(let r of n){if(r.pendingSends>=ee){if(r.drops+=1,r.drops===1||r.drops%100===0)e().logger.warn("ws-events",`Dropping events for slow client (${r.drops} dropped)`);continue}try{r.send(s)}catch{}}}),new E().ws("/ws/events",{open(t){if(n.size>=B){e().logger.warn("ws-events",`MAX_WS_CLIENTS exceeded (${n.size}/${B}); refusing new connection`),t.close(1013,"Server overloaded");return}let s=t.data,r=k(s.headers??{});if(!V(r)){t.close(1008,"Unauthorized: invalid or missing API key");return}let o=t.remoteAddress??null,i=Ue(o,s.headers);if(!O.accept(i??null,t)){t.close(1008,"too many connections");return}t._remoteIp=i??null;let a={ws:t,channels:new Set,pendingSends:0,drops:0,send:(c)=>{a.pendingSends+=1;try{t.send(c)}finally{queueMicrotask(()=>{a.pendingSends=Math.max(0,a.pendingSends-1)})}}};n.add(a),t._client=a,e().logger.debug("ws-events","Client connected",{id:String(t.id||"unknown")}),t.send(JSON.stringify({type:"connected",timestamp:new Date().toISOString()}))},message(t,s){try{let r=typeof s==="string"?JSON.parse(s):s;switch(r.type){case"subscribe":{let o=t._client;if(o)o.channels.add(r.channel);e().logger.debug("ws-events",`Subscribed to ${r.channel}`);break}case"unsubscribe":{let o=t._client;if(o)o.channels.delete(r.channel);e().logger.debug("ws-events",`Unsubscribed from ${r.channel}`);break}case"ping":t.send(JSON.stringify({type:"pong",timestamp:new Date().toISOString()}));break;default:e().logger.debug("ws-events",`Unknown message type: ${r.type}`)}}catch{e().logger.warn("ws-events","Failed to parse incoming message")}},close(t){let s=t._client;if(s)n.delete(s);let r=t._remoteIp;O.release(r??null,t),e().logger.debug("ws-events","Client disconnected")}})}var x=or(N),te=256,ne=1048576,re=1e4;async function W(n,t,s,r,o,i){let a={};for(let[l,u]of Object.entries(o))if(u&&!["host","connection"].includes(l.toLowerCase()))a[l]=u;let c={method:r,headers:a};if(r!=="GET"&&r!=="HEAD"&&i)c.body=typeof i==="string"?i:JSON.stringify(i);return fetch(`http://${n}:${t}${s}`,c)}async function C(n,t){let s=n.listProvidersForType("session");for(let{pluginName:r}of s){let o=n.getProviderByName("session",r);if(!o)continue;let i=await o.getTerminalInfo(t);if(!i)continue;try{process.kill(i.pid,0)}catch{continue}let a=i;return{host:a.host??"127.0.0.1",port:i.port,wsPath:a.wsPath??"/ws",subprotocols:a.subprotocols??["tty"]}}return null}var m=new Map,se=0,I=new Map,D=30000;function b(n){x.release(n.sessionId,n.remoteIp,n.capRef)}function oe(n){return typeof n==="string"?Buffer.byteLength(n):n.byteLength}function U(n){let t=new Headers(n.headers);return t.set("Permissions-Policy","clipboard-read=(self), clipboard-write=(self)"),t.delete("X-Frame-Options"),new Response(n.body,{status:n.status,headers:t})}function F(n){return`<!doctype html>
|
|
3
|
+
<html>
|
|
4
|
+
<head>
|
|
5
|
+
<meta charset="utf-8">
|
|
6
|
+
<title>Loading terminal\u2026</title>
|
|
7
|
+
<style>
|
|
8
|
+
body { font: 14px/1.4 system-ui, -apple-system, sans-serif; color: #ccc; background: #111; padding: 2rem; }
|
|
9
|
+
.err { color: #f88; }
|
|
10
|
+
</style>
|
|
11
|
+
</head>
|
|
12
|
+
<body>
|
|
13
|
+
<p id="status">Loading terminal\u2026</p>
|
|
14
|
+
<script>
|
|
15
|
+
(async () => {
|
|
16
|
+
const SID = '${n.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}';
|
|
17
|
+
const statusEl = document.getElementById('status');
|
|
18
|
+
function fail(msg) {
|
|
19
|
+
statusEl.textContent = msg;
|
|
20
|
+
statusEl.className = 'err';
|
|
21
|
+
}
|
|
22
|
+
// Ask the parent window for a fresh capability mint. The microfe
|
|
23
|
+
// hosts the iframe and owns the GraphQL connection to mint a new
|
|
24
|
+
// TERMINAL_SESSION capability. Reply shape: { type: 'vt-token',
|
|
25
|
+
// token: string } or { type: 'vt-token-failed', reason: string }.
|
|
26
|
+
function requestFreshToken() {
|
|
27
|
+
if (window.parent === window) return; // standalone open, no parent
|
|
28
|
+
window.parent.postMessage({ type: 'vt-token-request', sid: SID }, '*');
|
|
29
|
+
}
|
|
30
|
+
const m = location.hash.match(/[#&]vt=([^&]+)/);
|
|
31
|
+
if (!m) { fail('Missing terminal token'); return; }
|
|
32
|
+
const token = decodeURIComponent(m[1]);
|
|
33
|
+
// Use the canonical profile-scoped URL form so the request works on:
|
|
34
|
+
// - agents that still enforce 410-Gone on bare /api/* (older code)
|
|
35
|
+
// - agents with the bare-path fallback (newer code) \u2014 bare and
|
|
36
|
+
// profile-scoped paths both route to the same handler
|
|
37
|
+
// We don't know which profile the session was created under at
|
|
38
|
+
// render time, so we default to 'default'. The cookie-shim is
|
|
39
|
+
// process-scoped (signing secret is the same regardless of which
|
|
40
|
+
// profile path the exchange came through), so this is safe.
|
|
41
|
+
const exchangeUrl = '/api/profiles/default/agent/terminal-exchange';
|
|
42
|
+
let r;
|
|
43
|
+
try {
|
|
44
|
+
r = await fetch(exchangeUrl, {
|
|
45
|
+
method: 'POST',
|
|
46
|
+
headers: { 'content-type': 'application/json' },
|
|
47
|
+
credentials: 'include',
|
|
48
|
+
body: JSON.stringify({ sid: SID, token: token })
|
|
49
|
+
});
|
|
50
|
+
} catch (e) {
|
|
51
|
+
fail('Terminal authentication failed: network error');
|
|
52
|
+
return;
|
|
53
|
+
}
|
|
54
|
+
if (!r.ok) {
|
|
55
|
+
// Parse the agent's reason code (added in the agent route for
|
|
56
|
+
// diagnostics). On 'expired'/'replayed' the right move is to ask
|
|
57
|
+
// the host frame for a fresh token rather than dead-ending.
|
|
58
|
+
let code = 'invalid';
|
|
59
|
+
try {
|
|
60
|
+
const body = await r.json();
|
|
61
|
+
if (body && typeof body.code === 'string') code = body.code;
|
|
62
|
+
} catch { /* response had no JSON body */ }
|
|
63
|
+
if (code === 'expired' || code === 'replayed') {
|
|
64
|
+
statusEl.textContent = 'Refreshing terminal token...';
|
|
65
|
+
requestFreshToken();
|
|
66
|
+
// The host frame is expected to update the iframe src with a
|
|
67
|
+
// fresh #vt= hash, which causes a fresh navigation. No
|
|
68
|
+
// further action here.
|
|
69
|
+
return;
|
|
70
|
+
}
|
|
71
|
+
if (code === 'expired') fail('Terminal token expired \u2014 please refresh');
|
|
72
|
+
else if (code === 'replayed') fail('Terminal token already used \u2014 please refresh');
|
|
73
|
+
else fail('Terminal authentication failed');
|
|
74
|
+
return;
|
|
75
|
+
}
|
|
76
|
+
const url = new URL(location.href);
|
|
77
|
+
url.hash = '';
|
|
78
|
+
location.replace(url.toString());
|
|
79
|
+
})();
|
|
80
|
+
</script>
|
|
81
|
+
</body>
|
|
82
|
+
</html>`}function Lr(n){return new E().all("/terminal/:sessionId",async({params:t,request:s,set:r})=>{let o=t.sessionId,i=Qr(s,o);if(!i||!cr(i,o)){if(s.method==="GET")return r.status=200,r.headers["content-type"]="text/html; charset=utf-8",F(o);return r.status=401,{error:"Unauthorized: terminal cookie required"}}let a=await C(n,o);if(!a)return r.status=502,{error:"Terminal not running for this session"};let c=await W(a.host,a.port,"/",s.method,Object.fromEntries(Object.entries(s.headers).map(([l,u])=>[l,u])));return r.status=c.status,U(c)}).all("/terminal/:sessionId/*",async({params:t,request:s,set:r})=>{let o=t.sessionId,i=t["*"]||"",a=Qr(s,o);if(!a||!cr(a,o)){if(s.method==="GET"&&(i===""||i==="/"))return r.status=200,r.headers["content-type"]="text/html; charset=utf-8",F(o);return r.status=401,{error:"Unauthorized: terminal cookie required"}}let c=await C(n,o);if(!c)return r.status=502,{error:"Terminal not running for this session"};let l=await W(c.host,c.port,`/${i}`,s.method,Object.fromEntries(Object.entries(s.headers).map(([u,f])=>[u,f])));return r.status=l.status,U(l)}).ws("/terminal/:sessionId/ws",{open(t){let s=t.data,r=s.params?.sessionId;if(!r){t.close(1008,"Missing sessionId");return}if(!be(r)){t.close(1008,"Invalid sessionId");return}let o=Kr(s.headers??{},r),i=!!o&&cr(o,r),a=s.query?.vt,c=!!a&&we(a,`/terminal/${r}`,"GET");if(!i&&!c){t.close(1008,"Unauthorized: invalid or missing terminal credentials");return}let l=t.remoteAddress??null,u=Ue(l,s.headers),f=`bridge-${++se}`;if(s._bridgeId=f,!x.accept(r,u,f)){e().logger.warn("terminal-ws",`Terminal WS cap exceeded for session ${r} (ip=${u??"unknown"})`),t.close(1013,"too many connections");return}s._remoteIp=u;let d={upstream:null,upstreamReady:!1,buffer:[],bufferBytes:0,openTimer:null,sessionId:r,remoteIp:u,capRef:f};m.set(f,d),e().logger.debug("terminal-ws",`Client connected for session ${r} (${f})`),C(n,r).then((g)=>{if(m.get(f)!==d)return;if(!g){let h=I.get(r)??0,p=Date.now();if(I.size>50){let L=p-D*2;for(let[j,q]of I)if(q<L)I.delete(j)}if(p-h>D)e().logger.warn("terminal-ws",`No terminal running for session ${r}`),I.set(r,p);b(d),m.delete(f),t.close(1011,"No terminal running");return}let T=`ws://${g.host}:${g.port}${g.wsPath}`,y=new WebSocket(T,g.subprotocols);d.upstream=y,d.openTimer=setTimeout(()=>{b(d),m.delete(f);try{y.close(1011,"upstream open timeout")}catch{}try{t.close(1011,"Upstream open timeout")}catch{}},re),y.addEventListener("open",()=>{if(d.openTimer)clearTimeout(d.openTimer),d.openTimer=null;d.upstreamReady=!0,e().logger.debug("terminal-ws",`Bridge established \u2192 port ${g.port}, buffered=${d.buffer.length}`,{sessionId:r});for(let h of d.buffer)y.send(h);d.buffer.length=0,d.bufferBytes=0}),y.addEventListener("message",(h)=>{try{let p=h.data;if(p instanceof ArrayBuffer)t.send(new Uint8Array(p));else if(p instanceof Blob)p.arrayBuffer().then((L)=>{try{t.send(new Uint8Array(L))}catch{}});else t.send(p)}catch(p){e().logger.error("terminal-ws",`Failed to forward upstream\u2192client: ${p}`,{sessionId:r})}}),y.addEventListener("close",(h)=>{if(d.openTimer)clearTimeout(d.openTimer),d.openTimer=null;e().logger.debug("terminal-ws",`Upstream closed (code=${h.code})`,{sessionId:r}),b(d),m.delete(f);try{t.close(1000,"Upstream closed")}catch{}}),y.addEventListener("error",(h)=>{if(d.openTimer)clearTimeout(d.openTimer),d.openTimer=null;e().logger.error("terminal-ws","Upstream error",{sessionId:r}),b(d),m.delete(f);try{t.close(1011,"Upstream error")}catch{}})}).catch((g)=>{b(d),m.delete(f),e().logger.warn("terminal-ws","Failed to resolve terminal endpoint",{sessionId:r,error:String(g)});try{t.close(1011,"Failed to resolve terminal")}catch{}})},message(t,s){let o=t.data._bridgeId;if(!o)return;let i=m.get(o);if(!i)return;let a;if(typeof s==="string")a=s;else if(s instanceof ArrayBuffer)a=s;else if(s instanceof Uint8Array||Buffer.isBuffer(s)){let c=new ArrayBuffer(s.byteLength);new Uint8Array(c).set(new Uint8Array(s.buffer,s.byteOffset,s.byteLength)),a=c}else if(typeof s==="object"&&s!==null)a=JSON.stringify(s);else a=String(s);if(i.upstream&&i.upstreamReady&&i.upstream.readyState===WebSocket.OPEN)try{i.upstream.send(a)}catch(c){e().logger.error("terminal-ws",`Failed to forward client\u2192upstream: ${c}`,{sessionId:i.sessionId})}else{let c=oe(a);if(i.buffer.length>=te||i.bufferBytes+c>ne){b(i),m.delete(o);try{t.close(1013,"Terminal buffer limit exceeded")}catch{}return}i.buffer.push(a),i.bufferBytes+=c}},close(t){let s=t.data,r=s._bridgeId,o=s.params?.sessionId;if(e().logger.debug("terminal-ws","Client disconnected",{sessionId:o}),r){let i=m.get(r);if(i?.upstream&&i.upstream.readyState===WebSocket.OPEN)i.upstream.close(1000,"Client disconnected");if(i?.openTimer)clearTimeout(i.openTimer);if(i)b(i);m.delete(r)}if(o&&r)x.release(o,s._remoteIp??null,r)}})}var z=P(),X={debug:0,info:1,warn:2,error:3};function ie(n){return n==="debug"||n==="info"||n==="warn"||n==="error"?n:null}function kr(){return new E().ws("/ws/logs",{open(n){let t=n.data,s=k(t.headers??{}),r=t.query?.vt,o=V(s),i=!!r&&we(r,"/ws/logs","GET");if(!o&&!i){n.close(1008,"Unauthorized: invalid or missing credentials");return}let a=n.remoteAddress??null,c=Ue(a,t.headers);if(!z.accept(c??null,n)){n.close(1008,"too many connections");return}n._remoteIp=c??null,e().logger.info("ws-logs","Log stream client connected");let l={minLevel:"info",source:""};n._filters=l;let u=(f)=>{let d=n._filters;if(X[f.level]<X[d.minLevel])return;if(d.source&&!f.source.includes(d.source))return;try{n.send(JSON.stringify(f))}catch{}};e().logger.on("log",u),n._logHandler=u,n.send(JSON.stringify({type:"connected",timestamp:new Date().toISOString()}))},message(n,t){try{let s=typeof t==="string"?JSON.parse(t):t;if(s.type==="filter"){let r=n._filters,o=ie(s.level);if(o)r.minLevel=o;if(typeof s.source==="string")r.source=s.source.slice(0,128);n.send(JSON.stringify({type:"filter-updated",filters:r}))}}catch{}},close(n){let t=n._logHandler;if(t)e().logger.removeListener("log",t);let s=n._remoteIp;z.release(s??null,n),e().logger.info("ws-logs","Log stream client disconnected")}})}var A=new Map;function pt(n,t){if(!n.db||!n.serviceRegistry||!n.pluginManager)throw Error(`mountProfileRoutes: profile '${n.name}' has no attached services`);let s={db:n.db,serviceRegistry:n.serviceRegistry,pluginManager:n.pluginManager,broadcast:ge,hostServices:n.hostServices??void 0,rebuildPluginSurfaces:t?.rebuildPluginSurfaces,mountPlugin:t?.mountPlugin,app:t?.app},{routes:r}=sr(n.pluginManager,s);A.set(n.name,{ctx:n,router:r})}function Wi(n){return A.delete(n)}async function vr(n,t,s){let r=A.get(n);if(!r)return null;Tt(r.ctx);let o=new URL(t.url),a=`/api${o.pathname.replace(/^\/api\/profiles\/[^/]+/,"")}${o.search}`,c=new Headers(t.headers),l={method:t.method,headers:c};if(t.method!=="GET"&&t.method!=="HEAD")if(s!==void 0)l.body=s;else l.body=t.body,l.duplex="half";let u=new Request(`${o.origin}${a}`,l);return r.router.handle(u)}export{sr,Oi,or,Bi,Ue,ge,Nr,Lr,kr,pt,Wi,vr};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
function Se(){return!!process.stdout.isTTY&&!!process.stdin.isTTY}async function Ie(t,e=!1){if(!Se())return e;let n=e?"[Y/n]":"[y/N]";return process.stdout.write(` ${t} ${n} `),new Promise((r)=>{let o=process.stdin;o.setRawMode?.(!0),o.resume(),o.setEncoding("utf8");let a=(s)=>{o.removeListener("data",a),o.setRawMode?.(!1),o.pause();let i=s.trim().toLowerCase();if(console.log(i||(e?"y":"n")),i==="")r(e);else r(i==="y")};o.on("data",a)})}function _(t){if(t.json)return"json";if(t.plain)return"plain";if(t.interactive)return"interactive";return"auto"}function p(){return!!process.env.CI||!!process.env.NO_COLOR||process.env.TERM==="dumb"}async function y(t){let e=await t.fetchData(),n=t.mode??"auto";if(n==="json"){let o=t.json?t.json(e):e;process.stdout.write(`${JSON.stringify(o,null,2)}
|
|
3
|
+
`);return}if(n==="plain"){await t.plain(e);return}if((n==="interactive"||Se()&&!p())&&!!t.interactive&&t.interactive)try{await t.interactive(e);return}catch{}await t.plain(e)}function u(t,e){if(!t.json)return!1;return process.stdout.write(`${JSON.stringify(e,null,2)}
|
|
4
|
+
`),!0}async function vt(t,e,n=!1){if(t.yes===!0||t.json===!0||!Se())return!0;return Ie(e,n)}export{Se,Ie,_,y,u,vt};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{r,E}from"./index-w0m3jm0s.js";import{zt,Tr,oe,di,wt}from"./index-jnxjjx2y.js";import{Gi,T}from"./index-0qjbnyg4.js";import"./index-kwhx023z.js";import{s,A,l,o,g,F,v,G,H}from"./index-7f2k4g6q.js";import{Q}from"./index-vtsd74g0.js";import{Pe}from"./index-c4whjk5r.js";import{b}from"./index-w4jqdhc2.js";import{_,y,u}from"./index-t5cfkz1e.js";import{Kt,f,m,S,q}from"./index-byerrz46.js";import{promises as C}from"fs";import W from"path";import K from"os";function I(a,t){let n=Number.parseInt(process.env[a]??"",10);return Number.isInteger(n)&&n>0?n:t}var V=I("VIBECONTROLS_MAX_CONCURRENT_TASKS",4),X=I("VIBECONTROLS_MAX_TASK_OUTPUT_BYTES",1048576),z=new Set(["bash","sh","zsh","python","python3","node","bun","powershell","pwsh","cmd"]);async function Y(a,t){if(!a.command)throw Error("Command is required");let n=a.cwd?(await oe(a.cwd,{mustExist:!0})).path:process.cwd(),e=Bun.spawn(b().shellArgv(a.command),{cwd:n,env:{...process.env,...a.env},stdout:"pipe",stderr:"pipe"}),i=!1,d;if(t&&t>0)d=setTimeout(()=>{i=!0,e.kill()},t);let[w,c]=await Promise.all([x(e.stdout,()=>e.kill()),x(e.stderr,()=>e.kill())]),p=await e.exited;if(d)clearTimeout(d);if(i)throw Error(`Command timed out after ${t}ms`);return{stdout:w,stderr:c,exitCode:p}}async function Z(a,t){if(!a.script)throw Error("Script is required");let n=b().platform==="win32",e=a.interpreter||(n?"powershell":"bash");if(!z.has(e)||e.includes("/"))throw Error(`Interpreter '${e}' is not allowed`);let i=a.cwd?(await oe(a.cwd,{mustExist:!0})).path:process.cwd(),d=K.tmpdir(),w=e==="powershell"||e==="pwsh"?"ps1":e==="cmd"?"cmd":"sh",c=W.join(d,`vibecontrols-script-${globalThis.crypto.randomUUID()}.${w}`);await C.writeFile(c,a.script,{mode:448});try{let p=a.env?{...process.env,...a.env}:process.env,k=e==="powershell"||e==="pwsh"?[e,"-NoProfile","-ExecutionPolicy","Bypass","-File",c]:e==="cmd"?["cmd","/c",c]:[e,c],h=Bun.spawn(k,{cwd:i,env:p,stdout:"pipe",stderr:"pipe"}),R=!1,O;if(t&&t>0)O=setTimeout(()=>{R=!0,h.kill()},t);let[M,j]=await Promise.all([x(h.stdout,()=>h.kill()),x(h.stderr,()=>h.kill())]),B=await h.exited;if(O)clearTimeout(O);if(R)throw Error(`Script timed out after ${t}ms`);return{stdout:M,stderr:j,exitCode:B}}finally{await C.unlink(c).catch(()=>{})}}async function x(a,t){let n=new TextDecoder,e="",i=0,d=!1;for await(let w of a){if(i+=w.byteLength,i>X){if(!d)d=!0,t(),e+=`
|
|
3
|
+
[output truncated: task output limit exceeded]
|
|
4
|
+
`;continue}e+=n.decode(w,{stream:!0})}return e+=n.decode(),e}async function tt(a){if(!a.path)throw Error("Path is required");switch(a.operation){case"read":{let t=(await oe(a.path,{mustExist:!0})).path;if(zt(t))throw Error("Access to sensitive files not allowed");return await di(t),{content:await C.readFile(t,"utf-8"),path:t}}case"write":{if(!a.content)throw Error("Content is required for write operation");let t=(await oe(a.path,{forWrite:!0})).path;if(Tr(t)||zt(t))throw Error("Write access to sensitive files not allowed");return await C.writeFile(t,a.content),{success:!0,path:t}}case"delete":{let t=(await oe(a.path,{mustExist:!0})).path;if(Tr(t)||zt(t))throw Error("Delete access to this path is not allowed");return await C.unlink(t),{success:!0,path:t}}case"exists":try{let t=(await oe(a.path)).path;return await C.access(t),{exists:!0,path:t}}catch{return{exists:!1}}case"list":{let t=(await oe(a.path,{mustExist:!0})).path;return{files:(await wt(t)).map((e)=>e.name),path:t}}default:throw Error(`Unknown file operation: ${a.operation}`)}}async function et(a,t,n,e){try{let i=await a.getTask(t.id);if(i&&i.status!=="pending")return;await a.updateTask(t.id,{status:"running"});let d=JSON.parse(t.payload),w,c;switch(t.type){case"command":{let h=await Y(d,e?.timeout);w=h,c=h.exitCode;break}case"script":{let h=await Z(d,e?.timeout);w=h,c=h.exitCode;break}case"file_operation":w=await tt(d);break;default:throw Error(`Unknown task type: ${t.type}`)}let p=c!==void 0&&c!==0,k=p?"failed":"completed";if(await a.updateTask(t.id,{status:k,result:JSON.stringify(w),...c!==void 0&&{exitCode:c},...p&&{error:`Process exited with code ${c}`}}),e?.callbackUrl)L(e.callbackUrl,{agentTaskId:t.id,status:k,result:w,exitCode:c,...p&&{error:`Process exited with code ${c}`}})}catch(i){let d=i instanceof Error?i.message:String(i);try{await a.updateTask(t.id,{status:"failed",error:d})}catch(w){console.warn(`[task] failed to mark task ${t.id} as failed: ${w instanceof Error?w.message:String(w)}`)}if(e?.callbackUrl)L(e.callbackUrl,{agentTaskId:t.id,status:"failed",error:d})}finally{n.active=Math.max(0,n.active-1)}}function L(a,t){fetch(a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),signal:AbortSignal.timeout(1e4)}).catch(()=>{})}function N(a){let{db:t}=a,n={active:0};return new E().get("/",async({query:e})=>{if(e.status==="pending")return{tasks:await t.getPendingTasks()};return{tasks:await t.getAllTasks()}}).get("/:id",async({params:e,set:i})=>{let d=await t.getTask(e.id);if(!d)return i.status=404,{error:"Task not found"};return{task:d}}).post("/legacy",async({body:e,set:i})=>{try{return{task:await t.createTask({id:globalThis.crypto.randomUUID(),type:"file_operation",status:"completed",payload:JSON.stringify({operation:"exists",path:process.cwd(),meta:e}),result:JSON.stringify({legacy:!0,note:"Legacy doctor-script task accepted (no-op)."})})}}catch(d){return i.status=500,{error:"Failed to create task",details:String(d)}}},{body:r.Any()}).post("/",async({body:e,request:i,server:d,set:w})=>{let c=e;if(c&&typeof c==="object"&&!c.type&&!c.payload&&(c.title||c.description||c.command))try{return{task:await t.createTask({id:globalThis.crypto.randomUUID(),type:"file_operation",status:"completed",payload:JSON.stringify({operation:"exists",path:process.cwd(),meta:c}),result:JSON.stringify({legacy:!0,note:"Legacy doctor-script task accepted (no-op)."})})}}catch(k){return w.status=500,{error:"Failed to create task",details:String(k)}}let p=e;try{if(p.type==="command"||p.type==="script"){let h=await Pe(i,"VIBECONTROLS_ALLOW_REMOTE_SHELL_TASK",d,{getConfig:(R)=>t.getConfig(R)});if(h)return w.status=403,{error:"Forbidden",message:h}}else if(p.type==="file_operation"&&["write","delete"].includes(String(p.payload?.operation??""))){let h=await Pe(i,"VIBECONTROLS_ALLOW_REMOTE_FILE_TASK",d,{getConfig:(R)=>t.getConfig(R)});if(h)return w.status=403,{error:"Forbidden",message:h}}if(n.active>=V)return w.status=429,{error:"Too many tasks are already running"};if(n.active+=1,p.callbackUrl&&!Gi(p.callbackUrl,(()=>{let h=T.getConfig();return[h?.globalGatewayUrl,h?.workspaceGatewayUrl]})()))return n.active=Math.max(0,n.active-1),w.status=400,{error:"callbackUrl is not allowed"};let k=await t.createTask({id:globalThis.crypto.randomUUID(),type:p.type,status:"pending",payload:JSON.stringify(p.payload),...p.calendarTaskId&&{calendarTaskId:p.calendarTaskId},...p.timeout&&{timeout:p.timeout}});return et(t,k,n,{timeout:p.timeout,callbackUrl:p.callbackUrl}),{task:k}}catch(k){return n.active=Math.max(0,n.active-1),w.status=500,{error:"Failed to create task",details:String(k)}}},{body:r.Any()}).post("/:id/cancel",async({params:e,set:i})=>{let d=await t.getTask(e.id);if(!d)return i.status=404,{error:"Task not found"};if(d.status!=="pending")return i.status=400,{error:"Only pending tasks can be cancelled"};return await t.updateTask(e.id,{status:"failed",error:"Task cancelled by user"}),{success:!0}}).delete("/:id",async({params:e,set:i})=>{let d=await t.getTask(e.id);if(!d)return i.status=404,{error:"Task not found"};if(d.status==="pending")await t.updateTask(e.id,{status:"failed",error:"Task cancelled via DELETE"});return{success:!0,status:d.status}})}var P="http://localhost:3005";function U(a){return`/api/profiles/${encodeURIComponent(m(a))}/tasks`}function D(a){let t=a.command("task").description("Manage background tasks");t.command("list").description("List tasks").option("--status <status>","Filter by status").option("--profile <name>","Profile name (overrides default resolution)").option("--agent-url <url>","Agent URL",P).option("--json","Emit JSON").option("--plain","Force plain text output").action(async function(n){let e={...a.opts(),...n};try{let i=f(n),d=U(e),w=n.status?`${d}/?status=${encodeURIComponent(n.status)}`:`${d}/`;await y({mode:_(e),fetchData:async()=>(await S(i,w)).tasks||[],plain:(c)=>{if(!c||c.length===0){o("No tasks found.");return}g("Tasks"),F(c.map((p)=>({ID:H(p.id),Type:p.type||"-",Status:G(p.status),Created:p.createdAt?v(p.createdAt):"-"})))},interactive:async(c)=>{if(!c||c.length===0){g("Tasks"),o("No tasks found.");return}let p=c.map((k)=>({id:String(k.id),label:k.type||H(k.id),hint:k.status||"",detail:[`ID: ${k.id}`,`Type: ${k.type??"-"}`,`Status: ${G(k.status)}`,`Created: ${k.createdAt?v(k.createdAt):"-"}`].join(`
|
|
5
|
+
`)}));await Q({title:`vibe task list \u2014 ${c.length} task(s)`,rows:p})},json:(c)=>c.map((p)=>({id:p.id,type:p.type??null,status:p.status??null,createdAt:p.createdAt??null}))})}catch(i){s(A(i))}}),t.command("run").description("Run a new task").requiredOption("-c, --command <cmd>","Command to run").option("--cwd <dir>","Working directory").option("--profile <name>","Profile name (overrides default resolution)").option("--agent-url <url>","Agent URL",P).option("--json","Emit JSON").action(async function(n){let e={...a.opts(),...n};try{let i=f(n);if(!Kt(i)&&process.env.VIBECONTROLS_ALLOW_REMOTE_SHELL_TASK!=="1"){if(e.json){u(e,{ok:!1,error:"Remote shell task refused without env override"});return}s("Refusing to create a shell task on a remote agent URL. Set VIBECONTROLS_ALLOW_REMOTE_SHELL_TASK=1 only if you trust the target.");return}let d={command:n.command};if(n.cwd)d.cwd=n.cwd;let w=U(e),c=await q(i,`${w}/`,{type:"command",payload:d}),p=c?.task?.id||c?.id||c?.taskId;if(u(e,{ok:!0,id:p}))return;if(!p){s("Task created but no ID returned by the agent");return}l(`Task created: ${H(p)}`)}catch(i){if(e.json){u(e,{ok:!1,error:A(i)});return}s(A(i))}}),t.command("cancel").description("Cancel a running task").requiredOption("-i, --id <id>","Task ID").option("--profile <name>","Profile name (overrides default resolution)").option("--agent-url <url>","Agent URL",P).option("--json","Emit JSON").action(async function(n){let e={...a.opts(),...n};try{let i=f(n),d=U(e);if(await q(i,`${d}/${n.id}/cancel`,{}),u(e,{ok:!0,id:n.id}))return;l(`Task ${H(n.id)} cancelled.`)}catch(i){if(e.json){u(e,{ok:!1,error:A(i)});return}s(A(i))}})}function J(a,t){D(a)}function Tt(a){return{name:"task",version:"2.2.0",description:"Background task execution \u2014 commands, scripts, file operations",capabilities:{storage:"rw",subprocess:!0,audit:!0,telemetry:!0},tags:["backend","cli"],cliCommand:"task",apiPrefix:"/api/tasks",createRoutes:(t)=>N(t),onCliSetup:async(t,n)=>{J(t,n)}}}export{Tt as createPlugin};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{e}from"./index-0qjbnyg4.js";import{b}from"./index-w4jqdhc2.js";var a=5000,i=new Map,d=1;function c(r){return`${r}#${d++}`}function _r(r){let n=Bun.spawn(r.cmd,{env:r.env,cwd:r.cwd,stdout:r.stdout??"pipe",stderr:r.stderr??"pipe",stdin:r.stdin??"pipe",...b().processGroupSpawnOpts()}),t={id:c(r.owner),owner:r.owner,pid:n.pid??null,startedAt:new Date().toISOString(),proc:n,meta:r.meta};return i.set(t.id,t),n.exited.finally(()=>{i.delete(t.id)}),t}function yr(r){return[...i.values()].filter((n)=>n.owner===r)}async function l(r,n){let t=b(),s=Date.now()+n;while(Date.now()<s){if(!t.isProcessAlive(r))return!0;await new Promise((o)=>setTimeout(o,100))}return!t.isProcessAlive(r)}async function p(r,n="SIGTERM"){let t=r.pid;if(t==null)return;let s=b();if(s.killProcessTree(t,n),await l(t,a))return;s.killProcessTree(t,"SIGKILL")}async function Yi(){let r=[...i.values()];if(r.length===0)return{reaped:0};return e().logger.info("subprocess",`Reaping ${r.length} tracked child process(es)`,{owners:[...new Set(r.map((n)=>n.owner))]}),await Promise.all(r.map((n)=>p(n))),i.clear(),{reaped:r.length}}
|
|
3
|
+
export{_r,yr,Yi};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{e}from"./index-0qjbnyg4.js";import{Et,kt}from"./index-5021rk8n.js";import{hi}from"./index-0gmhd3hs.js";var g="prereqs-runner",R="plugin-mgr",d={status:null,install:null,satisfied:!0,pendingSudo:[],noProtocol:!0};function q(t,r){if(!t.apiPrefix)return null;return`${(t.apiPrefix.startsWith("/")?t.apiPrefix:`/${t.apiPrefix}`).replace(/\/+$/,"")}/prereqs${r}`}async function c(t,r,s){let l=t.handle;if(typeof l!=="function")return null;let u=new Request(`http://agent.local${r}`,{method:s,headers:{"x-vc-profile-rewrite":"1",[Et]:kt()}}),n=await l.call(t,u);if(n.status===404)return null;if(!n.ok){let P=await n.text().catch(()=>"");throw Error(`prereqs ${s} ${r} \u2192 ${n.status} ${P}`)}return await n.json()}async function xt(t,r,s,l,u={}){let n=q(t,"/status"),P=q(t,"/install");if(!n||!P)return d;let a=null;try{a=await c(s,n,"GET")}catch(i){e().logger.warn(g,`${t.name}: prereqs/status call failed`,{error:String(i)})}if(a===null)return d;if(a.satisfied||u.skipInstall)return await S(l,r,t.version,{status:a,install:null}),{status:a,install:null,satisfied:a.satisfied,pendingSudo:[],noProtocol:!1};let o=null;try{o=await c(s,P,"POST")}catch(i){e().logger.warn(g,`${t.name}: prereqs/install call failed`,{error:String(i)})}let p=a;try{let i=await c(s,n,"GET");if(i)p=i}catch{}if(await S(l,r,t.version,{status:p,install:o}),o&&o.installed.length>0){let i=new Map;for(let f of t.prerequisites??[])i.set(f.name,f.kind);hi(r,o.installed.map((f)=>({name:f,kind:i.get(f)??"binary"})))}return{status:p,install:o,satisfied:p.satisfied,pendingSudo:o?.pendingSudo??[],noProtocol:!1}}async function S(t,r,s,l){if(!t)return;let u=JSON.stringify({lastInstallAt:new Date().toISOString(),lastInstallVersion:s,satisfied:l.status?.satisfied??!1,missing:l.status?.missing??[],pendingSudo:l.install?.pendingSudo??[]});try{await t.setPluginState(R,`prereqs:${r}`,u)}catch(n){e().logger.warn(g,"Failed to persist prereq state",{packageName:r,error:String(n)})}}async function pr(t,r){if(!t)return null;try{let s=await t.getPluginState(R,`prereqs:${r}`);return s?JSON.parse(s):null}catch{return null}}
|
|
3
|
+
export{xt,pr};
|