@vibecontrols/agent 2026.608.1 → 2026.820.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent-config-t242qh84.js +2 -0
- package/dist/{agent-ready-tracker-pyw7zrp0.js → agent-ready-tracker-y9wbqt6y.js} +1 -1
- package/dist/app-7rmybh7z.js +2 -0
- package/dist/autostart.cmd-arjjfy8k.js +2 -0
- package/dist/bootstrap-workspace-dvxqq79t.js +2 -0
- package/dist/bootstrap.service-3zpbgsg0.js +2 -0
- package/dist/bridge-client-emc7mttx.js +2 -0
- package/dist/cli.js +1 -1
- package/dist/daemon-profile-nbe3pww8.js +2 -0
- package/dist/esm-br6epktf.js +2 -0
- package/dist/{finalize-retry-handle-registry-xnm9kxry.js → finalize-retry-handle-registry-ndbsa6a3.js} +1 -1
- package/dist/{finalize-retry-worker-vfdskqb5.js → finalize-retry-worker-mfj115ek.js} +1 -1
- package/dist/gateway-client-dnjxwbnj.js +2 -0
- package/dist/{getMachineId-bsd-753751sw.js → getMachineId-bsd-gvxzt2gm.js} +1 -1
- package/dist/{getMachineId-darwin-na1pranq.js → getMachineId-darwin-g66tx8f2.js} +1 -1
- package/dist/{getMachineId-linux-dmn0ncdm.js → getMachineId-linux-f0mt4jq9.js} +1 -1
- package/dist/{getMachineId-unsupported-yv77j894.js → getMachineId-unsupported-bsmqnjcv.js} +1 -1
- package/dist/{getMachineId-win-9hmyqmm0.js → getMachineId-win-172fq57c.js} +1 -1
- package/dist/highlights-3g7x1wxx.js +2 -0
- package/dist/highlights-66pe672g.js +2 -0
- package/dist/highlights-78tmcgkr.js +2 -0
- package/dist/highlights-dhv8z6p7.js +2 -0
- package/dist/highlights-j95xsvt4.js +2 -0
- package/dist/index-014sfc8c.js +2 -0
- package/dist/{index-c7554sg7.js → index-149rjxa5.js} +1 -1
- package/dist/{index-rjhcmnx0.js → index-1hfchgm5.js} +1 -1
- package/dist/{index-08y76yzh.js → index-1xw2wxyf.js} +1 -1
- package/dist/{index-cv0xhb46.js → index-2244sbdx.js} +4 -4
- package/dist/{index-ebx79cc1.js → index-34g3tenj.js} +2 -2
- package/dist/{index-kt5zxp42.js → index-426ddch6.js} +1 -1
- package/dist/{index-bwt6c337.js → index-4beawmtx.js} +2 -2
- package/dist/{index-x649afed.js → index-4f3ac5nf.js} +2 -2
- package/dist/{index-e1bw1bwr.js → index-54mmh1eb.js} +1 -1
- package/dist/{index-85ke6hng.js → index-6nz3c1ys.js} +3 -3
- package/dist/{index-4qq083yd.js → index-73qwyf9q.js} +1 -1
- package/dist/{index-m9dpfyxb.js → index-81gn264d.js} +1 -1
- package/dist/{index-wetsgcyq.js → index-97r6ekww.js} +2 -2
- package/dist/{index-yas07mv9.js → index-a3mwtteb.js} +2 -2
- package/dist/index-a9x5swye.js +11 -0
- package/dist/{index-jrtsdm8f.js → index-at6z8tds.js} +2 -2
- package/dist/{index-xnr6t79p.js → index-axgp7ryd.js} +6 -6
- package/dist/{index-5dysvvjv.js → index-bv1z3fxw.js} +1 -1
- package/dist/{index-a4854mwz.js → index-c4zn91z3.js} +1 -1
- package/dist/{index-bfeekmyh.js → index-d384edvr.js} +2 -2
- package/dist/index-dpyv0pqb.js +26 -0
- package/dist/{index-pgew6sge.js → index-e0jbxcn1.js} +3 -3
- package/dist/{index-0ckffygp.js → index-ea42kfvk.js} +1 -1
- package/dist/{index-52cp759f.js → index-ekr40gvh.js} +1 -1
- package/dist/{index-68r2ex9d.js → index-ff8acg43.js} +2 -2
- package/dist/{index-zhyxdyk6.js → index-gmwpaz2a.js} +2 -2
- package/dist/{index-4wgjx8bf.js → index-hey6w5m0.js} +1 -1
- package/dist/{index-b5dhmybd.js → index-hwpmdq5z.js} +1 -1
- package/dist/{index-ep3zb271.js → index-hym4bq94.js} +1 -1
- package/dist/{index-6p3gcnxr.js → index-jnrqbhew.js} +2 -2
- package/dist/{index-eawbdgkb.js → index-jq7vqe4a.js} +1 -1
- package/dist/{index-qwtspxw8.js → index-m1bteh0j.js} +1 -1
- package/dist/{index-xrs52f2c.js → index-najxwhng.js} +1 -1
- package/dist/{index-97mq40rr.js → index-paxfq5k4.js} +1 -1
- package/dist/{index-z73x3sdf.js → index-r1v6p7vc.js} +1 -1
- package/dist/{index-4hn26x1h.js → index-rhcsaqc0.js} +2 -2
- package/dist/{index-rc79x8fw.js → index-rmh8pff5.js} +1 -1
- package/dist/{index-p9cgvp3x.js → index-sasygg1e.js} +1 -1
- package/dist/{index-thammzct.js → index-sj39bx7y.js} +2 -2
- package/dist/{index-t8tnkqxh.js → index-svtmb9t1.js} +2 -2
- package/dist/{index-8sdrhr3q.js → index-tcew34xr.js} +2 -2
- package/dist/index-vd3njzs5.js +116 -0
- package/dist/index-w893wd2g.js +130 -0
- package/dist/{index-8nqp3a4d.js → index-wj5hx7gq.js} +1 -1
- package/dist/{index-z2gbk1pn.js → index-wqwzfy0e.js} +2 -2
- package/dist/{index-41vve5br.js → index-xyfcpfec.js} +49 -49
- package/dist/{index-czrb2yd1.js → index-ywv7amgf.js} +1 -1
- package/dist/index.js +3 -3
- package/dist/injections-2pt7wmtk.js +2 -0
- package/dist/interactive-svpgqn7v.js +2 -0
- package/dist/key.cmd-m0zst9pm.js +2 -0
- package/dist/log-shipper-m9h3jxem.js +2 -0
- package/dist/{path-utils-hxdyv2zn.js → path-utils-rzsac4g6.js} +1 -1
- package/dist/plugin-system-jww7bh2a.js +2 -0
- package/dist/prereqs-runner-fhjjgzhw.js +2 -0
- package/dist/profile-mount-xchr4y5e.js +2 -0
- package/dist/prune-stale-shims-wttq2y0f.js +2 -0
- package/dist/register-core-n2kb3mhq.js +2 -0
- package/dist/secondary-profile-attach-yzwncw4f.js +2 -0
- package/dist/subprocess-chzm6zj2.js +2 -0
- package/dist/telemetry-h9pa43c9.js +2 -0
- package/dist/tree-sitter-javascript-jre8s337.js +2 -0
- package/dist/tree-sitter-markdown-3as64nwe.js +2 -0
- package/dist/tree-sitter-markdown_inline-rs74pnzp.js +2 -0
- package/dist/tree-sitter-typescript-dgsjhgb0.js +2 -0
- package/dist/tree-sitter-zig-p8cc70k0.js +2 -0
- package/dist/tunnel-bootstrap-6xm4w7dm.js +2 -0
- package/package.json +3 -4
- package/dist/agent-config-pxkfd7ec.js +0 -2
- package/dist/app-wj8qwk11.js +0 -2
- package/dist/bootstrap-workspace-1ff98st2.js +0 -2
- package/dist/bootstrap.service-vg72w8pa.js +0 -2
- package/dist/bridge-client-73z9c5nm.js +0 -2
- package/dist/daemon-profile-696722nr.js +0 -2
- package/dist/esm-6f3dfn6v.js +0 -2
- package/dist/gateway-client-xdy5g715.js +0 -2
- package/dist/highlights-00fcgwwq.js +0 -2
- package/dist/highlights-23bc8zge.js +0 -2
- package/dist/highlights-4mhb2pb0.js +0 -2
- package/dist/highlights-q7w64nwb.js +0 -2
- package/dist/highlights-xwdw5xay.js +0 -2
- package/dist/index-63ba5fb4.js +0 -11
- package/dist/index-84hfet2g.js +0 -26
- package/dist/index-ghz61a5p.js +0 -231
- package/dist/index-p23tet7a.js +0 -2
- package/dist/injections-x3xya90r.js +0 -2
- package/dist/interactive-qc1j66mq.js +0 -2
- package/dist/key.cmd-q8c7ywwd.js +0 -2
- package/dist/log-shipper-hjnn1d5p.js +0 -2
- package/dist/plugin-system-jegwkd9p.js +0 -2
- package/dist/prereqs-runner-t5jhqr7x.js +0 -2
- package/dist/profile-mount-m714p85h.js +0 -2
- package/dist/prune-stale-shims-23y0stm8.js +0 -2
- package/dist/register-core-r7fjpp4w.js +0 -2
- package/dist/secondary-profile-attach-kxg4xj2t.js +0 -2
- package/dist/subprocess-q2ky0ptw.js +0 -2
- package/dist/telemetry-jxfgrm61.js +0 -2
- package/dist/tree-sitter-javascript-q22gvtms.js +0 -2
- package/dist/tree-sitter-markdown-pntsjzm3.js +0 -2
- package/dist/tree-sitter-markdown_inline-g1wzqf7k.js +0 -2
- package/dist/tree-sitter-typescript-m9yfes10.js +0 -2
- package/dist/tree-sitter-zig-jmh62j90.js +0 -2
- package/dist/tunnel-bootstrap-zdczwezc.js +0 -2
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{o as E4,q as F4}from"./index-ywv7amgf.js";import{u as W5,v as R5,w as A5}from"./index-xyfcpfec.js";import{E as T4}from"./index-6jzsthh9.js";import{U as v5,da as a4,ea as L2,fa as E0,ga as n4,ha as s4,ia as J5,ja as i4,la as R2,ma as i2,na as r2,oa as A2}from"./index-34g3tenj.js";import{pa as h5,ua as P5,wa as R0}from"./index-a3mwtteb.js";import{za as g2}from"./index-ff8acg43.js";import{Aa as I5,Ba as w5,Ca as k5,Da as S5}from"./index-rhcsaqc0.js";import{Ea as q5}from"./index-hey6w5m0.js";import{Na as q0,_a as D5}from"./index-2244sbdx.js";import{$a as N2}from"./index-ea42kfvk.js";import{eb as y2}from"./index-rmh8pff5.js";import{ib as G5,jb as _5,kb as j5,lb as O5,mb as x5,nb as Y2,ob as U5,pb as M5,qb as T5,rb as E5,tb as C5}from"./index-jnrqbhew.js";import{Ab as H0,Bb as Z4,Cb as S2,Eb as J4,Ib as E2,Jb as V0,Kb as K5,Lb as F5,Mb as T0,Nb as G2,Pb as m,Qb as l,Rb as $5,Sb as Z5,Tb as L5,Ub as N5,xb as Q4,yb as c2,zb as $4}from"./index-d384edvr.js";import{Yb as W,Zb as v}from"./index-e0jbxcn1.js";import{Ad as o0,rd as V4,sd as t,td as t0,ud as m2,vd as b2,wd as f2,zd as e0}from"./index-a9x5swye.js";import{Dd as C0,Ed as H5,Fd as V5,Gd as B5,Hd as B2,Kd as _4,Ld as s2,Qd as g,Sd as I0,Td as b,Ud as s,Wd as V,Xd as B0}from"./index-axgp7ryd.js";import{$d as K0,Zd as r0,_d as W4,be as u2,ce as H4,ee as q2,fe as d,he as P2,je as C2,ke as F2,le as a2}from"./index-c4zn91z3.js";import{ne as c0,qe as y}from"./index-149rjxa5.js";var D0=typeof new Headers()?.toJSON==="function",y5=(Q)=>{if(D0)return Object.keys(Q.toJSON()).join(", ");let $="",Z=0;return Q.forEach((Y,X)=>{if(Z)$=$+", "+X;else $=X;Z++}),$},v0=(Q)=>{let{aot:$=!0,origin:Z=!0,methods:Y=!0,allowedHeaders:X=!0,exposeHeaders:J=!0,credentials:z=!0,maxAge:H=5,preflight:B=!0}=Q??{};if(Array.isArray(X))X=X.join(", ");if(Array.isArray(J))J=J.join(", ");let K=typeof Z==="boolean"?void 0:Array.isArray(Z)?Z:[Z],L=new v({name:"@elysiajs/cors",seed:Q,aot:$}),q=K?.some((I)=>I==="*"),C={};if(K){for(let I of K)if(typeof I==="string")C[I]=!0}let U=(I,N,x)=>{if(Array.isArray(I))return I.some((E)=>U(E,N,x));switch(typeof I){case"string":if(x in C)return!0;let E=x.indexOf("://");if(E!==-1)x=x.slice(E+3);return I===x;case"function":return I(N)===!0;case"object":if(I instanceof RegExp)return I.test(x)}return!1},G=(I,N)=>{if(Z===!0){I.headers.vary="*",I.headers["access-control-allow-origin"]=N.headers.get("Origin")||"*";return}if(q){I.headers.vary="*",I.headers["access-control-allow-origin"]="*";return}if(!K?.length)return;if(K.length){let x=N.headers.get("Origin")??"";for(let E=0;E<K.length;E++)if(U(K[E],N,x)===!0){I.headers.vary=Z?"Origin":"*",I.headers["access-control-allow-origin"]=x||"*";return}}I.headers.vary="Origin"},T=(I,N)=>{if(!N)return;if(Y===!0)return I.headers["access-control-allow-methods"]=N??"*";if(Y===!1||!Y?.length)return;if(Y==="*")return I.headers["access-control-allow-methods"]="*";if(!Array.isArray(Y))return I.headers["access-control-allow-methods"]=Y;I.headers["access-control-allow-methods"]=Y.join(", ")},R={};if(typeof J==="string")R["access-control-expose-headers"]=J;if(typeof X==="string")R["access-control-allow-headers"]=X;if(z===!0)R["access-control-allow-credentials"]="true";L.headers(R);function P({set:I,request:N,headers:x}){if(G(I,N),T(I,N.headers.get("access-control-request-method")),X===!0||J===!0){if(X===!0)I.headers["access-control-allow-headers"]=x["access-control-request-headers"];if(J===!0)I.headers["access-control-expose-headers"]=Object.keys(x).join(",")}if(H)I.headers["access-control-max-age"]=H.toString();return new Response(null,{status:204})}if(B)L.options("/",P).options("/*",P);return L.onRequest(function({set:N,request:x}){if(G(N,x),B&&x.method==="OPTIONS")return P({set:N,request:x,headers:D0?x.headers.toJSON():Object.fromEntries(x.headers.entries())});if(T(N,x.method),X===!0||J===!0){let E=y5(x.headers);if(X===!0)N.headers["access-control-allow-headers"]=E;if(J===!0)N.headers["access-control-expose-headers"]=E}})};var u5="/code-server";function h0(Q,$,Z=S2){let Y=Q.method.toUpperCase();if(Y!=="GET"&&Y!=="HEAD")return null;let X=new URL(Q.url),J=X.searchParams.get("vt");if(!J||!Z(J,u5,"GET"))return null;X.searchParams.delete("vt");let z=new Headers(Q.headers);return z.set("x-agent-api-key",$()),new Request(`${X.origin}${X.pathname}${X.search}`,{method:Q.method,headers:z})}import{createHash as f0}from"crypto";var z2="idempotency",m5=300000,P0=1e4,D2=new Map;function g5(Q,$,Z,Y){return f0("sha256").update(`${Q}|${$}|${Z}|${Y}`).digest("hex")}async function p5(Q,$){let Z=await Q.getPluginState(z2,$);if(!Z)return null;try{let Y=JSON.parse(Z);if(Y.expiresAt<Date.now())return await Q.deletePluginState(z2,$),null;return Y}catch{return null}}async function l5(Q,$,Z){await Q.setPluginState(z2,$,JSON.stringify(Z))}async function d5(Q){let $=await Q.getAllPluginState(z2),Z=Date.now(),Y=0,X=[];for(let J of $)try{if(JSON.parse(J.value).expiresAt<Z)await Q.deletePluginState(z2,J.key),Y+=1;else X.push({key:J.key,updatedAt:J.updatedAt})}catch{await Q.deletePluginState(z2,J.key),Y+=1}if(X.length>P0){X.sort((z,H)=>(z.updatedAt??"").localeCompare(H.updatedAt??""));let J=X.slice(0,X.length-P0);for(let z of J)await Q.deletePluginState(z2,z.key),Y+=1}if(Y>0)V().logger.info("idempotency",`Swept ${Y} expired/over-cap entries`)}var J0=null,n5=600000;function i5(Q){if(J0)return;J0=setInterval(()=>{let $=Q.getDb();if(!$)return;d5($).catch((Z)=>{V().logger.warn("idempotency","Sweep failed",{error:String(Z)})})},n5),J0.unref?.()}function b0(Q){return i5(Q),new v({name:"plugin/idempotency"}).onBeforeHandle(async({request:$,path:Z,set:Y,store:X})=>{if($.method!=="POST"&&$.method!=="PUT")return;let J=$.headers.get("x-idempotency-key")??$.headers.get("X-Idempotency-Key");if(!J)return;if(J.length<8||J.length>200)return Y.status=400,{error:"X-Idempotency-Key must be 8\u2013200 chars",code:"BAD_REQUEST"};let z=Q.getDb();if(!z)return;let H="no-body";try{let T=await $.clone().text();H=f0("sha256").update(T).digest("hex")}catch{}let B=g5($.method,Z,J,H),K=await p5(z,B);if(K){Y.status=K.status;let G=Y.headers??={};G["Content-Type"]=K.contentType,G["X-Idempotency-Replay"]="true",X.__idemReplay=K.body;try{return JSON.parse(K.body)}catch{return K.body}}let L=D2.get(B);if(L){let G=await L.catch(()=>null);if(G){Y.status=G.status;let T=Y.headers??={};T["Content-Type"]=G.contentType,T["X-Idempotency-Replay"]="true",X.__idemReplay=G.body;try{return JSON.parse(G.body)}catch{return G.body}}}let q,C,U=new Promise((G,T)=>{q=G,C=T});D2.set(B,U),X.__idemKey=B,X.__idemResolve=q,X.__idemReject=C}).onAfterHandle(async({response:$,set:Z,store:Y})=>{let X=Y.__idemKey;if(!X)return;let J=Y.__idemResolve,z=Q.getDb(),H=Z.status??200,B=typeof $==="string"?$:JSON.stringify($),L=Z.headers?.["Content-Type"]??"application/json",q={status:H,body:B,contentType:L,expiresAt:Date.now()+m5},C=H>=200&&H<300;try{if(z&&C)await l5(z,X,q)}catch(U){V().logger.warn("idempotency","Failed to persist response",{error:String(U)})}finally{try{J?.(C?q:null)}catch{}D2.delete(X)}}).onError(({store:$})=>{let Z=$.__idemKey;if(!Z)return;let Y=$.__idemReject;try{Y?.(Error("idempotency: handler errored"))}catch{}D2.delete(Z)}).as("global")}import u from"os";import{readFileSync as VQ}from"fs";import{join as BQ}from"path";var y0={enabled:!1,async scrape(){return`# vibecontrols agent metrics disabled (OTel SDK not initialised)
|
|
3
|
+
`},recordHttpRequest(){},setPluginsLoaded(){}},J2=null,v2=null;async function h2(Q){if(J2)return J2;if(v2)return v2;return v2=(async()=>{try{let{MeterProvider:$}=await import("./index-014sfc8c.js").then((m)=>c0(m.default,1)),{PrometheusExporter:Z,PrometheusSerializer:Y}=await import("./index-m1bteh0j.js").then((m)=>c0(m.default,1)),X=new Z({preventServerStart:!0}),J=new Y,H=new $({readers:[X]}).getMeter("vibecontrols-agent"),B=H.createGauge("vibecontrols_agent_info",{description:"Static info about the agent process; value is always 1."});H.createObservableGauge("vibecontrols_agent_uptime_seconds",{description:"Process uptime in seconds."}).addCallback((G)=>{G.observe(process.uptime())});let L=H.createCounter("vibecontrols_http_requests_total",{description:"Total HTTP requests handled by the agent, labelled by method, route, status."}),q={};H.createObservableGauge("vibecontrols_plugins_loaded",{description:"Plugins loaded by the agent, broken down by status (loaded, failed, etc.)."}).addCallback((G)=>{for(let[T,R]of Object.entries(q))G.observe(R,{status:T})}),B.record(1,{version:Q?.version??"unknown",profile:Q?.profile??"default"});let U={enabled:!0,async scrape(){let G=await X.collect();if(!G.resourceMetrics)return"";return J.serialize(G.resourceMetrics)},recordHttpRequest(G,T,R){L.add(1,{method:G,route:T,status:String(R)})},setPluginsLoaded(G){q={...G}}};return J2=U,V().logger.info("metrics","OTel Prometheus registry initialised"),U}catch($){return V().logger.warn("metrics","Failed to initialise OTel metrics; /metrics will return a stub body",{error:$ instanceof Error?$.message:String($)}),J2=y0,y0}})(),v2}function u0(Q,$,Z){if(!J2)return;J2.recordHttpRequest(Q,$,Z)}function m0(Q){if(!J2)return;J2.setPluginsLoaded(Q)}var o5=new Set(["127.0.0.1","::1"]),g0=!1;function a5(){if(g0)return;if(process.env.METRICS_ANONYMOUS_LOCALHOST==="true")g0=!0,V().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 s5(Q){let $=Q.replace(/^\[|\]$/g,"");if($.startsWith("::ffff:"))return $.slice(7);return $}function X0(Q,$){let Z=$?.requestIP(Q)?.address;if(!Z)return!1;return o5.has(s5(Z))}function p0(){return a5(),new v({name:"routes/metrics"}).get("/metrics",async({request:Q,server:$,set:Z})=>{if(!(process.env.METRICS_ANONYMOUS_LOCALHOST==="true"&&X0(Q,$))){let z=m(Object.fromEntries(Q.headers.entries()));if(!l(z))return Z.status=401,Z.headers["content-type"]="application/json",JSON.stringify({error:"Unauthorized",message:"Invalid or missing API key"})}let J=await(await h2()).scrape();return Z.headers["content-type"]="text/plain; version=0.0.4; charset=utf-8",J})}import{randomBytes as r5,timingSafeEqual as t5}from"crypto";import{chmodSync as e5,existsSync as l0,mkdirSync as QQ,readFileSync as $Q,unlinkSync as ZQ,writeFileSync as JQ}from"fs";import{dirname as XQ,join as YQ}from"path";var W2=null;function d0(){return YQ(P2(),"pairing-token")}function zQ(){return r5(32).toString("base64url")}function WQ(Q,$){let Z=Buffer.from(Q),Y=Buffer.from($);if(Z.length!==Y.length)return!1;try{return t5(Z,Y)}catch{return!1}}function M6(){if(W2)return W2;let Q=d0();try{if(l0(Q)){let Z=$Q(Q,"utf8").trim();if(Z.length>=32)return W2=Z,Z}}catch{}let $=zQ();try{QQ(XQ(Q),{recursive:!0}),JQ(Q,$,{encoding:"utf8"});try{e5(Q,384)}catch{}}catch(Z){}return W2=$,$}function Y0(Q){if(!Q)return!1;if(!W2)return!1;return WQ(Q,W2)}function n0(){W2=null;try{let Q=d0();if(l0(Q))ZQ(Q)}catch{}}function z0(Q){return Q["x-pairing-token"]??Q["X-Pairing-Token"]??null}var T2=null,M2=null,HQ=30000;function W0(Q,$={}){if($.isBootProfile===!1){i0();return}if(Q.globalGatewayUrl)process.env.VIBE_GLOBAL_GATEWAY_URL=Q.globalGatewayUrl;if(Q.workspaceGatewayUrl)process.env.VIBE_WORKSPACE_GATEWAY_URL=Q.workspaceGatewayUrl;if(Q.workspaceId)process.env.VIBE_WORKSPACE_ID=Q.workspaceId;if(Q.organizationId)process.env.VIBE_ORGANIZATION_ID=Q.organizationId;i0()}function i0(){T2=null}async function a0(){if(T2&&Date.now()-T2.at<HQ)return T2.result;if(M2)return M2;return M2=(async()=>{let Q;try{let $=await f2({strict:!0}),Z=o0($,{workspaceId:process.env.VIBE_WORKSPACE_ID,globalGatewayUrl:process.env.VIBE_GLOBAL_GATEWAY_URL,workspaceGatewayUrl:process.env.VIBE_WORKSPACE_GATEWAY_URL});Q=Z?{ok:!1,message:Z}:{ok:!0}}catch($){Q={ok:!0,message:`identity check skipped: ${$ instanceof Error?$.message:String($)}`}}return T2={at:Date.now(),result:Q},Q})().finally(()=>{M2=null}),M2}function s0(){let Q=b();return!Q||Q.name===V().name}function GQ(){let Q=u.hostname(),$=u.platform(),Z=u.arch(),Y=new Bun.CryptoHasher("sha256");return Y.update(`${Q}-${$}-${Z}`),Y.digest("hex").substring(0,16)}function KQ(){for(let Q of["..","../.."])try{let $=BQ(import.meta.dir,Q,"package.json"),Y=JSON.parse(VQ($,"utf8")).version;if(Y)return Y}catch{}return"0.0.0"}async function FQ(Q){let $=[],Z=Q.getProvider("tunnel");if(Z)$.push(Z);for(let Y of Q.listProvidersForType("tunnel")){let X=Q.getProviderByName("tunnel",Y.pluginName);if(X&&!$.includes(X))$.push(X)}for(let Y of $){if(!Y.getActiveTunnelUrl)continue;let X=await Y.getActiveTunnelUrl();if(X)return X}return null}function X4({serviceRegistry:Q,runFinalize:$,getDb:Z}){let Y=KQ(),X=GQ();return new v({prefix:"/api/agent"}).get("/identity",()=>({hostname:u.hostname(),platform:u.platform(),architecture:u.arch(),agentVersion:Y,agentInstanceId:t0()})).get("/version",()=>({version:Y,runtime:"bun",runtimeVersion:typeof Bun<"u"?Bun.version:"unknown"})).get("/api-key",({request:J,server:z,set:H})=>{if(!X0(J,z)){let K=m(Object.fromEntries(J.headers.entries()));if(!l(K))return H.status=401,{error:"Unauthorized",message:"Invalid or missing API key"}}return{apiKey:G2()}}).post("/iframe-token",({body:J,request:z,set:H})=>{let B=m(Object.fromEntries(z.headers.entries()));if(!l(B))return H.status=401,{error:"Unauthorized",message:"Invalid or missing API key"};try{if(Array.isArray(J.pathPrefixes)&&J.pathPrefixes.length>0)return $4({pathPrefixes:J.pathPrefixes,methods:J.methods},J.ttlSeconds??void 0);if(!J.pathPrefix)return H.status=400,{error:"BadRequest",message:"Provide either pathPrefix (string) or pathPrefixes (string[])"};return c2(J.pathPrefix,J.ttlSeconds??void 0)}catch(K){return H.status=400,{error:"BadRequest",message:K instanceof Error?K.message:String(K)}}},{body:W.Object({pathPrefix:W.Optional(W.String({minLength:1})),pathPrefixes:W.Optional(W.Array(W.String({minLength:1}),{minItems:1,maxItems:16})),methods:W.Optional(W.Array(W.String({minLength:1}),{minItems:1,maxItems:8})),ttlSeconds:W.Optional(W.Number())})}).post("/terminal-exchange",({body:J,set:z})=>{let{sid:H,token:B}=J;if(!H||!B)return z.status=400,{error:"BadRequest",message:"sid and token required"};if(!Q4(H))return z.status=400,{error:"BadRequest",message:"invalid sid"};let K=`/terminal/${H}`,L=Z4(B,K);if(!L.ok)return V().logger.warn("terminal-exchange","iframe token rejected",{sid:H,reason:L.reason}),z.status=401,{error:"Unauthorized",message:"invalid iframe token",code:L.reason==="expired"?"expired":L.reason==="replayed"?"replayed":"invalid"};let q=J4(H,600),C=`vt_term_${H}`;return z.headers["set-cookie"]=`${C}=${q.token}; HttpOnly; Secure; SameSite=None; Path=/terminal/${H}; Max-Age=600`,z.status=204,null},{body:W.Object({sid:W.String({minLength:1}),token:W.String({minLength:1})})}).post("/ui-exchange",({body:J,set:z})=>{let{plugin:H,token:B}=J;if(!H||!B)return z.status=400,{error:"BadRequest",message:"plugin and token required"};if(!E2(H))return z.status=400,{error:"BadRequest",message:"invalid plugin name"};let K=`/ui/${H}`;if(!H0(B,K))return z.status=401,{error:"Unauthorized",message:"invalid iframe token"};let L=V0(H,600),q=`vt_ui_${H}`;return z.headers["set-cookie"]=`${q}=${L.token}; HttpOnly; Secure; SameSite=None; Path=/ui/${H}/; Max-Age=600`,z.status=204,null},{body:W.Object({plugin:W.String({minLength:1}),token:W.String({minLength:1})})}).post("/ui-exchange-plugin",({body:J,set:z})=>{let{plugin:H,token:B}=J;if(!H||!B)return z.status=400,{error:"BadRequest",message:"plugin and token required"};if(!E2(H))return z.status=400,{error:"BadRequest",message:"invalid plugin name"};if(![`/api/plugins/${H}/ui`,`/${H}`].find((U)=>H0(B,U)))return z.status=401,{error:"Unauthorized",message:"invalid iframe token"};let q=V0(H,600),C=`vt_ui_${H}`;return z.headers["set-cookie"]=`${C}=${q.token}; HttpOnly; Secure; SameSite=None; Path=/api/plugins/${H}/ui/; Max-Age=600`,z.status=204,null},{body:W.Object({plugin:W.String({minLength:1}),token:W.String({minLength:1})})}).get("/system",({request:J,set:z})=>{let H=m(Object.fromEntries(J.headers.entries()));if(!l(H))return z.status=401,{error:"Unauthorized",message:"Invalid or missing API key"};return{machineId:X,hostname:u.hostname(),platform:u.platform(),arch:u.arch(),release:u.release(),cpus:u.cpus().length,totalMemory:u.totalmem(),freeMemory:u.freemem(),uptime:u.uptime(),bunVersion:typeof Bun<"u"?Bun.version:void 0,agentVersion:Y,homeDir:u.homedir(),cwd:process.cwd(),environment:"production"}}).get("/tunnel",async({request:J,set:z})=>{let H=Object.fromEntries(J.headers.entries()),B=l(m(H)),K=Y0(z0(H));if(!B&&!K)return z.status=401,{error:"Unauthorized",message:"Provide x-agent-api-key OR x-pairing-token to read tunnel URL"};let L=await FQ(Q);if(!L)return{tunnelUrl:null,message:"No tunnel provider registered"};return{tunnelUrl:L}}).get("/status",()=>{let J=["tunnel","session","ai"].filter((z)=>Q.hasProvider(z));return{state:V().getBootState(),status:V().getBootState(),version:Y,providers:J,timestamp:new Date().toISOString()}}).get("/gateway-auth",()=>({configured:g.isConfigured(),config:y2(g.getConfig()),state:V().getBootState()})).post("/retry-config",async({set:J})=>{let{getFinalizeRetryHandle:z}=await import("./finalize-retry-handle-registry-ndbsa6a3.js"),H=z();if(!H)return J.status=409,{ok:!1,error:"No finalize retry worker is active. The agent either never had cached credentials to retry with, or it already reached the ready state."};let B=await H.forceRetryNow();if(!B.ok)J.status=503;return{ok:B.ok,error:B.ok?void 0:B.error,state:V().getBootState(),worker:H.getState()}}).post("/gateway-auth",async({body:J,request:z,set:H})=>{let B=V().getBootState(),K=Object.fromEntries(z.headers.entries());if(B==="ready"){let N=m(K);if(!l(N))return H.status=401,{success:!1,state:B,error:"Unauthorized: API key required to reconfigure"}}else{let N=m(K),x=z0(K),E=l(N),D=Y0(x);if(!E&&!D)return H.status=401,{success:!1,state:B,error:"Unauthorized: provide x-agent-api-key OR x-pairing-token for bootstrap"}}let{clientId:L,clientSecret:q,workspaceId:C,globalGatewayUrl:U,workspaceGatewayUrl:G}=J;if(!L||!q||!C||!U||!G)return H.status=400,{success:!1,state:V().getBootState(),error:"clientId, clientSecret, workspaceId, globalGatewayUrl, and workspaceGatewayUrl are required"};let T,R;try{T=B2(U,"globalGatewayUrl"),R=B2(G,"workspaceGatewayUrl")}catch(N){return H.status=400,{success:!1,state:V().getBootState(),error:N instanceof Error?N.message:String(N)}}let P=await r0("gateway-auth:push",async()=>{let N=b()??V();{let x;try{x=await f2({dir:N.dataDir,scope:N.name,strict:!0})}catch(D){let h=D instanceof Error?D.message:String(D);return V().logger.error("preconfig","Could not read existing credentials \u2014 refusing the push rather than risk overwriting a live pairing",{error:h}),H.status=503,{success:!1,state:V().getBootState(),error:`Cannot verify this agent's current pairing (secrets backend unavailable: ${h}). Refusing the credential push so a live pairing is not overwritten. Retry once the secrets backend recovers.`,code:"IDENTITY_CHECK_UNAVAILABLE"}}let E=e0(x,{workspaceId:C,globalGatewayUrl:T,workspaceGatewayUrl:R});if(E&&J.force!==!0)return V().logger.warn("preconfig","Rejected a gateway-auth push that would hijack this agent's identity",{conflict:E}),H.status=409,{success:!1,state:V().getBootState(),error:E,code:"GATEWAY_IDENTITY_CONFLICT"};if(E)V().logger.warn("preconfig","Forced re-pair \u2014 overwriting an existing gateway identity",{conflict:E})}try{await b2({clientId:L,clientSecret:q,workspaceId:C,ownerUserId:J.ownerUserId,organizationId:J.organizationId,globalGatewayUrl:T,workspaceGatewayUrl:R,agentRecordId:J.agentRecordId,scopes:J.scopes,...J.storageAdapter?{storageAdapter:J.storageAdapter}:{},...J.storageOptions?{storageOptions:J.storageOptions}:{},...J.dbPath?{dbPath:J.dbPath}:{}},{dir:N.dataDir,scope:N.name})}catch(x){return H.status=500,{success:!1,state:V().getBootState(),error:`Failed to persist gateway credentials to secrets backend: ${x instanceof Error?x.message:String(x)}`}}return null});if(P)return P;let I=V().getBootState();if(I==="ready"){let N=Z();if(N){if(await N.setConfig("gateway-auth:clientId",L),await N.setConfig("gateway-auth:clientSecret",q),await N.setConfig("gateway-auth:workspaceId",C),J.organizationId)await N.setConfig("gateway-auth:organizationId",J.organizationId);if(await N.setConfig("gateway-auth:globalGatewayUrl",T),await N.setConfig("gateway-auth:workspaceGatewayUrl",R),J.agentRecordId)await N.setConfig("gateway-auth:agentRecordId",J.agentRecordId)}g.configure({globalGatewayUrl:T,workspaceGatewayUrl:R,clientId:L,clientSecret:q,workspaceId:C,organizationId:J.organizationId}),W0({workspaceId:C,organizationId:J.organizationId,globalGatewayUrl:T,workspaceGatewayUrl:R},{isBootProfile:s0()}),V().logger.info("preconfig","Gateway credentials re-configured (agent was already ready)");let x=!!(J.storageAdapter||J.storageOptions||J.dbPath);return{success:!0,state:I,message:x?"Gateway auth re-configured. Restart the agent (vibe restart) to apply the new storage configuration.":"Gateway auth re-configured"}}return V().logger.info("preconfig","Gateway credentials received \u2014 beginning finalize (background)"),n0(),W0({workspaceId:C,organizationId:J.organizationId,globalGatewayUrl:T,workspaceGatewayUrl:R},{isBootProfile:s0()}),$({clientId:L,clientSecret:q,workspaceId:C,organizationId:J.organizationId,globalGatewayUrl:T,workspaceGatewayUrl:R},{agentRecordId:J.agentRecordId,scopes:J.scopes}).catch((N)=>{V().logger.error("preconfig","Background finalize threw",{error:N instanceof Error?N.message:String(N)})}),H.status=202,{success:!0,state:V().getBootState(),agentRecordId:J.agentRecordId,message:"Gateway credentials accepted; finalize is running in the background. Poll /health/ready for completion."}},{body:W.Object({clientId:W.Optional(W.String()),clientSecret:W.Optional(W.String()),workspaceId:W.Optional(W.String()),ownerUserId:W.Optional(W.String()),organizationId:W.Optional(W.String()),globalGatewayUrl:W.Optional(W.String()),workspaceGatewayUrl:W.Optional(W.String()),scopes:W.Optional(W.Array(W.String())),agentRecordId:W.Optional(W.String()),storageAdapter:W.Optional(W.String()),storageOptions:W.Optional(W.Record(W.String(),W.String())),dbPath:W.Optional(W.String()),force:W.Optional(W.Boolean())})})}import{existsSync as $2,mkdirSync as LQ,rmSync as Y4,readdirSync as B4}from"fs";import{join as p2}from"path";function a(Q){return p2(F2(),"agents",d(Q))}function NQ(){let Q=p2(F2(),"agents");if(!$2(Q))return[];return B4(Q,{withFileTypes:!0}).filter(($)=>$.isDirectory()).map(($)=>$.name).filter(($)=>/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test($))}function G4(Q){return p2(F2(),"agents",d(Q))}function G0(Q){return t({dir:G4(Q)})}function z4(Q,$){return m2($,{dir:G4(Q),scope:d(Q)})}function K2(Q){let $=u2(),Z=K0().find((J)=>J.name===Q),Y=s.get(Q),X={name:Q,isDefault:Q===$,isRunning:Z?.status==="running",attached:Y!==void 0,bootState:Y?Y.getBootState():null,dataDir:Y?Y.dataDir:null};if(Z)X.port=Z.port,X.pid=Z.pid,X.startTime=Z.startTime;if($2(a(Q)))X.config=y2(G0(Q));return X}function K4(Q={}){let $=Q.serviceManagerFactory?Q.serviceManagerFactory():new g2;return new v({prefix:"/api/profiles"}).get("/",()=>{let Z=NQ(),Y=u2(),X=new Set(Z);return X.add(Y),[...X].sort().map((J)=>K2(J))}).post("/",async({body:Z,set:Y})=>{try{let X=d(Z.name),J=a(X);if($2(J))return Y.status=409,{error:"exists",message:`Profile '${X}' already exists.`};let z;if(Z.copyFrom){let H=d(Z.copyFrom);if(!$2(a(H)))return Y.status=400,{error:"copy-source-missing",message:`Profile '${H}' does not exist.`};z=G0(H),delete z["static-api-key"],delete z.agentRecordId,delete z.apiKeys}else z=V4();if(Z.gatewayUrl)z.globalGatewayUrl=Z.gatewayUrl;if(Z.workspaceGatewayUrl)z.workspaceGatewayUrl=Z.workspaceGatewayUrl;if(Z.clientId)z.clientId=Z.clientId;if(Z.clientSecret)z.clientSecret=Z.clientSecret;if(Z.workspaceId)z.workspaceId=Z.workspaceId;if(Z.organizationId)z.organizationId=Z.organizationId;LQ(J,{recursive:!0}),z4(X,z);try{B0(X)}catch(H){V().logger.warn("profile-mgmt",`In-process attach failed for '${X}'`,{error:String(H)})}if(V().logger.info("profile-mgmt",`Created profile '${X}' at ${J}`),Z.start){let H={name:X,port:Z.port??0,daemon:!0,dbPath:C2(),profile:X};await $.startDaemon(H)}return Y.status=201,K2(X)}catch(X){return Y.status=400,{error:"create-failed",message:X instanceof Error?X.message:String(X)}}},{body:W.Object({name:W.String(),gatewayUrl:W.Optional(W.String()),workspaceGatewayUrl:W.Optional(W.String()),clientId:W.Optional(W.String()),clientSecret:W.Optional(W.String()),workspaceId:W.Optional(W.String()),organizationId:W.Optional(W.String()),copyFrom:W.Optional(W.String()),start:W.Optional(W.Boolean()),port:W.Optional(W.Number())})}).get("/:name",({params:Z,set:Y})=>{try{let X=d(Z.name);if(!$2(a(X)))return Y.status=404,{error:"not-found",message:`No profile '${X}'.`};return K2(X)}catch(X){return Y.status=400,{error:"bad-request",message:X instanceof Error?X.message:String(X)}}},{params:W.Object({name:W.String()})}).put("/:name",({params:Z,body:Y,set:X})=>{try{let J=d(Z.name);if(!$2(a(J)))return X.status=404,{error:"not-found",message:`No profile '${J}'.`};let z=["static-api-key","apiKeys","agentRecordId"];for(let K of z)if(K in Y)return X.status=400,{error:"forbidden-field",message:`Field '${K}' is managed via dedicated commands (vibe key rotate / vibe profile create). It cannot be patched here.`};if("registry"in Y)return X.status=400,{error:"forbidden-field",message:"Field 'registry' cannot be patched via this endpoint. Use POST /api/agent/registry with operator confirmation (VIBE_ALLOW_REGISTRY_CHANGE=1) so the change is auditable."};let B={...G0(J),...Y};return z4(J,B),K2(J)}catch(J){return X.status=400,{error:"update-failed",message:J instanceof Error?J.message:String(J)}}},{params:W.Object({name:W.String()}),body:W.Record(W.String(),W.Any())}).delete("/:name",async({params:Z,body:Y,query:X,set:J})=>{try{let z=d(Z.name);if(z===u2())return J.status=409,{error:"is-default",message:`Cannot delete active default profile '${z}'. Switch to another profile first.`};let H=X?.purge==="true"||X?.purge==="1",B=$2(a(z)),K=s.has(z);if(!B&&!K)return J.status=404,{error:"not-found",message:`No profile '${z}'.`};if(B&&!H&&!Y?.confirm)return J.status=400,{error:"confirm-required",message:"Pass { confirm: true } in the body or `?purge=true` in the query to delete the on-disk dataDir (destructive)."};try{await $.stop(z)}catch{}try{await s.destroy(z)}catch(L){V().logger.warn("profile-mgmt",`In-process detach failed for '${z}'`,{error:String(L)})}if(B)if(Y?.keepConfig)for(let L of B4(a(z))){if(L==="config.json")continue;Y4(p2(a(z),L),{recursive:!0,force:!0})}else Y4(a(z),{recursive:!0,force:!0});return V().logger.info("profile-mgmt",`Deleted profile '${z}'`),{ok:!0,deleted:z,keptConfig:!!Y?.keepConfig,detached:K,purged:B}}catch(z){return J.status=400,{error:"delete-failed",message:z instanceof Error?z.message:String(z)}}},{params:W.Object({name:W.String()}),query:W.Optional(W.Object({purge:W.Optional(W.String())})),body:W.Optional(W.Object({confirm:W.Optional(W.Boolean()),keepConfig:W.Optional(W.Boolean())}))}).post("/:name/switch",async({params:Z,set:Y})=>{try{let X=d(Z.name);if(!$2(a(X)))return Y.status=404,{error:"not-found",message:`No profile '${X}'.`};return await W4(()=>H4(X)),V().logger.info("profile-mgmt",`Default profile switched to '${X}'`),{ok:!0,defaultProfile:X}}catch(X){return Y.status=400,{error:"switch-failed",message:X instanceof Error?X.message:String(X)}}},{params:W.Object({name:W.String()})}).post("/:name/start",async({params:Z,body:Y,set:X})=>{try{let J=d(Z.name);if(!$2(a(J)))return X.status=404,{error:"not-found",message:`No profile '${J}'.`};try{B0(J)}catch(H){V().logger.warn("profile-mgmt",`In-process attach failed for '${J}'`,{error:String(H)})}if(!K0().some((H)=>H.name===J&&H.status==="running")){let H={name:J,port:Y?.port??0,daemon:!0,dbPath:C2(),profile:J};await $.startDaemon(H)}return K2(J)}catch(J){return X.status=500,{error:"start-failed",message:J instanceof Error?J.message:String(J)}}},{params:W.Object({name:W.String()}),body:W.Optional(W.Object({port:W.Optional(W.Number())}))}).post("/:name/stop",async({params:Z,set:Y})=>{try{let X=d(Z.name);try{await $.stop(X)}catch{}try{await s.destroy(X)}catch(J){V().logger.warn("profile-mgmt",`In-process detach failed for '${X}'`,{error:String(J)})}return K2(X)}catch(X){return Y.status=500,{error:"stop-failed",message:X instanceof Error?X.message:String(X)}}},{params:W.Object({name:W.String()})})}function _Q(){let Q=process.memoryUsage(),$=process.resourceUsage(),Z=$.userCPUTime/1000,Y=$.systemCPUTime/1000,X=Z+Y,J=s.list().map((z)=>{let H;try{H=F4(z.spawnOwnerKey).length}catch{H=0}return{name:z.name,status:z.getBootState(),childPidCount:H,cpuMs:X,heapBytes:Q.heapUsed,dataDir:z.dataDir}});return{process:{pid:process.pid,uptimeSeconds:process.uptime(),cpuUserMs:Z,cpuSystemMs:Y,heapUsedBytes:Q.heapUsed,heapTotalBytes:Q.heapTotal,rssBytes:Q.rss},profiles:J,notes:{perProfileCpu:"deferred",perProfileHeap:"deferred"}}}function L4(){return new v({prefix:"/api/profile-stats"}).get("/",()=>_Q())}function I2(Q,$){return Promise.race([Q,new Promise((Z,Y)=>setTimeout(()=>Y(Error(`timeout after ${$}ms`)),$))])}function jQ(Q){let $=Q instanceof Error?Q.message:String(Q);return/ENOENT/.test($)||/no such file or directory/i.test($)}async function N4(Q){let Z=`__health__:probe:${typeof crypto<"u"&&typeof crypto.randomUUID==="function"?crypto.randomUUID():`${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`}`,Y=String(Date.now());if(await I2(Q.setConfig(Z,Y),2000),await I2(Q.getConfig(Z),2000)!==Y)throw Error("round-trip mismatch");try{await I2(Q.deleteConfig(Z),500)}catch{}}async function OQ(Q,$){if(!Q)return{ok:!1,message:"database not opened"};let Z=performance.now();try{return await N4(Q),{ok:!0,durationMs:performance.now()-Z}}catch(Y){if($&&jQ(Y))try{return(await import("fs")).mkdirSync($,{recursive:!0}),await N4(Q),{ok:!0,message:`recovered: dbPath ${$} was missing \u2014 recreated`,durationMs:performance.now()-Z}}catch(X){return{ok:!1,message:`ENOENT on dbPath ${$}: ${X instanceof Error?X.message:String(X)}`,durationMs:performance.now()-Z}}return{ok:!1,message:Y instanceof Error?Y.message:String(Y),durationMs:performance.now()-Z}}}async function xQ(Q){if(process.env.AGENT_TUNNEL==="false")return{ok:!0,message:"tunnel disabled via AGENT_TUNNEL=false"};if(!Q)return{ok:!1,message:"no service registry"};let $=Q.getProvider("tunnel"),Z=V().getBootState()==="awaiting-config";if(!$)return{ok:!1,message:Z?"agent is awaiting-config \u2014 POST OAuth credentials to /api/agent/gateway-auth to register tunnel provider":"no tunnel provider registered"};if(!$.getActiveTunnelUrl)return{ok:!0,message:`provider: ${$.name}`};try{let Y=await I2(Promise.resolve($.getActiveTunnelUrl()),2000),X=_4(Y);if(X)return{ok:!0,message:`provider: ${$.name} \u2014 ${X}`};if(Y)return{ok:!1,message:`provider: ${$.name} \u2014 reported an unusable tunnel URL (${Y})`};return{ok:!1,message:`provider: ${$.name} \u2014 no active tunnel (the agent is not reachable from outside; the provider is rebuilding it)`}}catch(Y){return{ok:!1,message:`provider: ${$.name} \u2014 tunnel status unavailable: ${Y instanceof Error?Y.message:String(Y)}`}}}function UQ(Q,$){if(!Q)return{ok:!1,message:"no service registry"};let Y=V().getBootState()==="awaiting-config";if($==="session"){let X=Q.getProvider("session");if(X)return{ok:!0,message:`provider: ${X.name}`};return{ok:!1,message:Y?"agent is awaiting-config \u2014 POST OAuth credentials to /api/agent/gateway-auth to register session provider":"no session provider registered"}}return{ok:!0}}async function MQ(Q){if(!Q)return{};let $={};for(let Z of Q.getAllPlugins()){let Y=Z.getHealth;if(typeof Y!=="function")continue;let X=performance.now();try{let J=await I2(Promise.resolve(Y.call(Z)),2000);$[Z.name]={ok:J?.ok!==!1,message:J?.message,durationMs:performance.now()-X}}catch(J){$[Z.name]={ok:!1,message:J instanceof Error?J.message:String(J),durationMs:performance.now()-X}}}return $}function j4(Q){let $=Q&&"serviceRegistry"in Q?Q:{serviceRegistry:Q};return new v({prefix:"/health"}).get("/",()=>{return{status:"ok",lifecycleState:$.serviceRegistry?.getService("agent","lifecycle")?.getState()??"running",bootState:V().getBootState(),timestamp:new Date().toISOString(),uptime:process.uptime()}}).get("/live",()=>({status:"ok"})).get("/ready",async({set:Z})=>{let X=$.serviceRegistry?.getService("agent","lifecycle")?.getState()??"running",J=V().getBootState(),z={};z.boot={ok:J==="ready",message:J==="ready"?void 0:`boot state ${J}`},z.lifecycle={ok:X==="running",message:X==="running"?void 0:`lifecycle ${X}`},z.db=await OQ($.getDb?.()??null,$.getDbPath?.()??null),z.tunnel=await xQ($.serviceRegistry),z.session=UQ($.serviceRegistry,"session"),z.identity=await a0();try{let{gatewayClient:G}=await import("./gateway-client-dnjxwbnj.js");if(!G.isConfigured())z.registration={ok:!0,message:"not configured"};else{let T=$.getDb?.()??null;if(T?await T.getConfig("gateway-auth:agentRecordId"):null)z.registration={ok:!0};else{let P=V().getDegradedReasons().some((I)=>I.plugin==="agent-registration");z.registration=P?{ok:!1,message:"agent failed to register with the workspace after retries"}:{ok:!0,message:"registering"}}}}catch(G){z.registration={ok:!0,message:`registration check skipped: ${G instanceof Error?G.message:String(G)}`}}let H=await MQ($.getPluginManager?.()??null),B=Object.values(z).every((G)=>G.ok)&&Object.values(H).every((G)=>G.ok);if(!B)Z.status=503;let K=J==="degraded"?V().getDegradedReasons():[],L=V().name,q={};for(let G of s.list())q[G.name]={bootState:G.getBootState(),ok:G.getBootState()==="ready",degradedReasons:G.getDegradedReasons()};let C=V().getLastFinalizeError(),U={status:B?"ok":"degraded",lifecycleState:X,bootState:J,daemon:{profile:L,bootState:J,ok:J==="ready"},profiles:q,components:z,plugins:H,degradedReasons:K,lastFinalizeError:C,timestamp:new Date().toISOString()};if(!B)V().logger.warn("health","Readiness probe failed",{components:z,plugins:H,bootState:J});return U})}var l2=0,O4=0;function x4(){return new v({name:"inflight-tracker"}).onRequest(()=>{l2+=1}).onAfterResponse(()=>{l2=Math.max(0,l2-1),O4+=1})}function U4(){return new v({prefix:"/api/stats"}).get("/inflight",()=>({inflight:Math.max(0,l2-1),totalServed:O4}))}var F0=Object.freeze(["code","code-insiders","codium","cursor","idea","pycharm","webstorm","goland","phpstorm","rubymine","clion","rider","zed","subl","vim","nvim","emacs","neovide","fleet","helix"]),TQ=new Set(F0),EQ=new Set(["--new-window","-n","--reuse-window","-r","--wait","-w","--add","--goto"]);function M4(Q){try{return Bun.which(Q)??null}catch{return null}}function C4(){return new v({prefix:"/api/editor"}).get("/allowlist",()=>({commands:[...F0]})).get("/detect",async()=>{let Q=F0.map((Y)=>[Y,M4(Y)]),$=[],Z={};for(let[Y,X]of Q)if(X)$.push(Y),Z[Y]=X;return{available:$,paths:Z}}).post("/open",async({body:Q,set:$})=>{let{command:Z,path:Y,args:X=[]}=Q;if(!TQ.has(Z))return $.status=400,{ok:!1,error:`Command '${Z}' is not in the IDE allowlist`};for(let H of X)if(typeof H!=="string"||!EQ.has(H))return $.status=400,{ok:!1,error:`Argument '${H}' is not in the flag allowlist`};let J;try{J=(await T4(Y,{mustExist:!0})).realPath}catch(H){return $.status=400,{ok:!1,error:`Invalid path: ${H instanceof Error?H.message:String(H)}`}}let z=M4(Z);if(!z)return $.status=404,{ok:!1,error:`'${Z}' is not installed or not on PATH on this agent`};try{let H=E4({owner:`editor:${Z}`,cmd:[z,...X,J],env:process.env,stdout:"ignore",stderr:"ignore",stdin:"ignore",meta:{command:Z,path:J}});return V().logger.info("editor",`Launched ${Z} on ${J}`,{pid:H.pid}),V().audit.emit("agent","editor.open",{command:Z,path:J,pid:H.pid}),{ok:!0,command:Z,resolvedPath:J,pid:H.pid}}catch(H){return $.status=500,{ok:!1,error:`Failed to spawn editor: ${H instanceof Error?H.message:String(H)}`}}},{body:W.Object({command:W.String({minLength:1,maxLength:40}),path:W.String({minLength:1,maxLength:4096}),args:W.Optional(W.Array(W.String({maxLength:32})))})})}var I4=Symbol.for("@vibecontrols/plugin-sdk:contextProviders@1");function CQ(){let Q=globalThis,$=Q[I4];if($)return $;let Z=new Map;return Q[I4]=Z,Z}function L0(){return Array.from(CQ().values())}function q4(){return(b()??V()).dataDir}function n(){let Q=t({dir:q4()});return{ownerUserId:Q.ownerUserId,workspaceId:Q.workspaceId}}function d2(){return t({dir:q4()}).agentRecordId}function R4(Q){if(!Q)return null;try{return new URL(Q).host}catch{return null}}async function A4(Q,$){let Z=Q.getPluginManager(),Y=Z?Z.getPluginDetails().map((H)=>({pluginName:H.pluginName,packageName:H.packageName,version:H.version,tags:H.tags??[]})):[],X=process.memoryUsage(),J=R4(Q.getTunnelHost?.()??null),z;try{z=L2(n()).map((H)=>({id:H.id,label:H.label,host:R4(H.tunnelUrl),agentRecordId:H.agentRecordId??null,permissions:H.permissions,canForward:H.permissions.includes("mesh:forward"),lastReachable:H.lastReachable??null}))}catch{z=[]}return{pluginName:"agent",description:"vibecontrols-agent runtime self-report",generatedAt:new Date().toISOString(),data:{profile:$.profile,vibeId:$.vibeId??null,runtime:{bunVersion:typeof Bun<"u"?Bun.version:null,nodeVersion:process.versions.node??null,platform:process.platform,arch:process.arch,pid:process.pid,uptimeSeconds:Math.round(process.uptime()),memory:{rssMB:Math.round(X.rss/1048576),heapUsedMB:Math.round(X.heapUsed/1048576)}},agent:{version:Q.getAgentVersion?.()??null,profileRegistered:q2(),tunnelHost:J},plugins:{count:Y.length,items:Y},mesh:{peerCount:z.length,peers:z}}}}var IQ=2000,w4=1000;async function qQ(Q,$){let Z,Y=new Promise((X,J)=>{Z=setTimeout(()=>J(Error(`timeout after ${$}ms`)),$)});try{return await Promise.race([Q,Y])}finally{if(Z)clearTimeout(Z)}}async function k4(Q,$){let Z=performance.now(),Y=Q.timeoutMs??IQ;try{let X=await qQ(Q.getContext($),Y);if(!X.generatedAt)X.generatedAt=new Date().toISOString();return{ok:!0,data:X,durationMs:Math.round(performance.now()-Z)}}catch(X){return{ok:!1,error:X.message??String(X),durationMs:Math.round(performance.now()-Z)}}}class N0{deps;inflight=new Map;constructor(Q){this.deps=Q}async aggregate(Q){let $=`${Q.profile}::${Q.vibeId??""}`,Z=this.inflight.get($);if(Z&&Date.now()-Z.ts<w4)return Z.promise;let Y=this.doAggregate(Q).finally(()=>{setTimeout(()=>{let X=this.inflight.get($);if(X&&X.promise===Y)this.inflight.delete($)},w4).unref?.()});return this.inflight.set($,{ts:Date.now(),promise:Y}),Y}async selfContext(Q){return A4(this.deps,Q)}async pluginContext(Q,$){let Z=L0().find((Y)=>Y.name===Q);if(!Z)return null;return k4(Z,$)}async pluginsContext(Q){let $=L0(),Z=await Promise.allSettled($.map((X)=>k4(X,Q))),Y={};return $.forEach((X,J)=>{let z=Z[J];if(z&&z.status==="fulfilled")Y[X.name]=z.value;else if(z&&z.status==="rejected")Y[X.name]={ok:!1,error:z.reason instanceof Error?z.reason.message:String(z.reason),durationMs:0}}),Y}async doAggregate(Q){let[$,Z]=await Promise.all([this.selfContext(Q),this.pluginsContext(Q)]);return{agent:$,plugins:Z}}}function n2(Q){let $=Q.vibeId;if(typeof $!=="string")return;let Z=$.trim();return Z.length>0&&Z.length<=128?Z:void 0}function S4(Q){let $=new N0(Q);return new v({prefix:"/api/agent/context"}).get("/",async({params:Z,query:Y})=>{let X=Z?.profile??"default",J=n2(Y);return $.aggregate({profile:X,vibeId:J})},{query:W.Object({vibeId:W.Optional(W.String())})}).get("/agent",async({params:Z,query:Y})=>{let X=Z?.profile??"default",J=n2(Y);return $.selfContext({profile:X,vibeId:J})},{query:W.Object({vibeId:W.Optional(W.String())})}).get("/plugins",async({params:Z,query:Y})=>{let X=Z?.profile??"default",J=n2(Y);return $.pluginsContext({profile:X,vibeId:J})},{query:W.Object({vibeId:W.Optional(W.String())})}).get("/plugins/:name",async({params:Z,query:Y,set:X})=>{let J=Z?.profile??"default",z=Z?.name;if(!z)return X.status=400,{error:"missing plugin name"};let H=n2(Y),B=await $.pluginContext(z,{profile:J,vibeId:H});if(!B)return X.status=404,{error:`no context provider registered under name "${z}"`};return B},{params:W.Object({name:W.String()}),query:W.Object({vibeId:W.Optional(W.String())})})}var Z2="autoupdate",RQ=86400000,D4=300000,AQ=900000,S={timer:null,running:!1,profile:"default",lastCheckAt:null,lastCheck:null,lastUpdateAt:null,lastUpdate:null,startedAt:null};function _0(){let Q=(process.env.VIBE_AUTOUPDATE??"").trim().toLowerCase();return Q==="0"||Q==="false"||Q==="off"||Q==="no"}function h4(){if(_0())return!1;try{return t().autoUpdate!==!1}catch{return!0}}function j0(){let Q=Number(process.env.VIBE_AUTOUPDATE_INTERVAL_MS);if(Number.isFinite(Q)&&Q>0)return Math.max(AQ,Q);return RQ}async function O0(Q){let $=V().logger;if(S.running)return{check:S.lastCheck??await v4(),update:null};S.running=!0;try{let Z=await R2();if(S.lastCheck=Z,S.lastCheckAt=new Date().toISOString(),Z.error)$.debug(Z2,`Update check failed: ${Z.error}`);else if(Z.hasUpdate)$.info(Z2,`New agent version available: ${Z.current} \u2192 ${Z.latest}`);let Y=Q?.force||h4();if(!Z.hasUpdate||!Y)return{check:Z,update:null};$.info(Z2,`Auto-updating ${Z.current} \u2192 ${Z.latest} (idle-gated restart)\u2026`);let X=await i2({restart:!0,name:S.profile,onLog:(J)=>$.info(Z2,J)});if(S.lastUpdate=X,S.lastUpdateAt=new Date().toISOString(),X.ok&&X.updated)$.info(Z2,`Auto-update applied: now ${X.current} (restart: ${X.restart}).`);else if(!X.ok)$.warn(Z2,`Auto-update failed: ${X.error}`);return{check:Z,update:X}}catch(Z){return $.warn(Z2,`Auto-update tick threw: ${Z instanceof Error?Z.message:String(Z)}`),{check:await v4(),update:null}}finally{S.running=!1}}async function v4(){if(S.lastCheck)return S.lastCheck;let Q=await R2();return S.lastCheck=Q,S.lastCheckAt=new Date().toISOString(),Q}function P4(Q){if(S.timer)clearTimeout(S.timer);S.timer=setTimeout(()=>{O0().finally(()=>{if(S.startedAt)P4(j0())})},Q),S.timer.unref?.()}function wQ(Q){let $=V().logger;if(S.profile=Q?.profile||process.env.VIBECONTROLS_PROFILE||"default",S.startedAt=new Date().toISOString(),_0()){$.info(Z2,"Autoupdate disabled via VIBE_AUTOUPDATE \u2014 not scheduling.");return}$.info(Z2,`Autoupdate scheduled (first check in ${Math.round(D4/60000)}m, then every ${Math.round(j0()/3600000)}h).`),P4(D4)}function v7(){if(S.timer)clearTimeout(S.timer),S.timer=null;S.startedAt=null}function f4(Q){if(m2({autoUpdate:Q}),Q&&!S.startedAt)wQ({profile:S.profile})}function x0(){let Q=!0;try{Q=t().autoUpdate!==!1}catch{}return{enabled:h4(),envKillSwitch:_0(),configEnabled:Q,scheduled:!!S.startedAt,intervalMs:j0(),profile:S.profile,startedAt:S.startedAt,lastCheckAt:S.lastCheckAt,lastCheck:S.lastCheck,lastUpdateAt:S.lastUpdateAt,lastUpdate:S.lastUpdate}}import{existsSync as b4}from"fs";import{join as c4}from"path";var kQ=600000,U0=1e6;function SQ(){let Q=N2(),$=Q.which("bun")??`bun${Q.executableSuffix}`,Z=c4(import.meta.dir,"cli.js");if(b4(Z))return{runner:$,prefix:[Z]};let Y=c4(import.meta.dir,"..","cli.ts");if(b4(Y))return{runner:$,prefix:[Y]};let X=Q.which("vibe");if(X)return{runner:X,prefix:[]};return null}function y4(Q){if(Q.length<=U0)return Q;return Q.slice(0,U0)+`
|
|
4
|
+
\u2026[output truncated at ${U0} bytes]`}async function o2(Q,$={}){let Z=SQ();if(!Z)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:Q,command:"(unresolved)"};let Y=[...Z.prefix,...Q],X=[Z.runner,...Y].join(" ");try{let J=Bun.spawn([Z.runner,...Y],{cwd:$.cwd,env:{...process.env,VIBE_AUTO_ACCEPT:"1",CI:"1",NO_COLOR:"1",...$.env},stdout:"pipe",stderr:"pipe"}),z=$.timeoutMs??kQ,H=!1,B=setTimeout(()=>{H=!0;try{J.kill()}catch{}},z),[K,L,q]=await Promise.all([new Response(J.stdout).text(),new Response(J.stderr).text(),J.exited]);return clearTimeout(B),{ok:!H&&q===0,exitCode:q,stdout:y4(K),stderr:y4(L),timedOut:H,argv:Q,command:X}}catch(J){return{ok:!1,exitCode:null,stdout:"",stderr:`Failed to spawn vibe CLI: ${J instanceof Error?J.message:String(J)}`,timedOut:!1,argv:Q,command:X}}}async function u4(){let{Command:Q}=await import("./esm-br6epktf.js"),{registerCoreCommands:$}=await import("./register-core-n2kb3mhq.js"),Z=new Q;Z.name("vibe").option("--json").option("--plain").option("-y, --yes").option("-p, --profile <name>");try{$(Z)}catch{}let Y=new Set(["nuke","kill","gc","stop","rollback","deploy"]),X=[];for(let J of Z.commands){let z=J.name();if(!z||z==="help")continue;X.push({name:z,description:J.description()||"",usage:J.usage()||"",options:J.options.map((H)=>({flags:H.flags,description:H.description||""})),group:"core",destructive:Y.has(z)})}return X.sort((J,z)=>J.name.localeCompare(z.name))}import{spawn as DQ}from"child_process";import{writeFileSync as vQ,mkdirSync as hQ}from"fs";import{tmpdir as PQ}from"os";import{join as m4}from"path";var fQ="@vibecontrols/agent";function g4(Q){let $=N2(),Z=$.which("bun")??`bun${$.executableSuffix}`,Y=$.which("npm")??`npm${$.executableSuffix}`,X=a2(),J=Q.delayMs??3000,z=Q.pids.filter((B)=>Number.isInteger(B)&&B>0),H=`// vibecontrols agent self-uninstall reaper (auto-generated)
|
|
5
|
+
const PIDS = ${JSON.stringify(z)};
|
|
6
|
+
const NPM = ${JSON.stringify(Y)};
|
|
7
|
+
const BUN = ${JSON.stringify(Z)};
|
|
8
|
+
const REGISTRY = ${JSON.stringify(X)};
|
|
9
|
+
const PKG = ${JSON.stringify(fQ)};
|
|
10
|
+
await Bun.sleep(${J});
|
|
11
|
+
for (const pid of PIDS) {
|
|
12
|
+
try { process.kill(pid, "SIGTERM"); } catch {}
|
|
13
|
+
}
|
|
14
|
+
await Bun.sleep(2500);
|
|
15
|
+
for (const pid of PIDS) {
|
|
16
|
+
try { process.kill(pid, "SIGKILL"); } catch {}
|
|
17
|
+
}
|
|
18
|
+
try { Bun.spawnSync([NPM, "uninstall", "-g", PKG, "--registry=" + REGISTRY], { stdout: "inherit", stderr: "inherit" }); } catch {}
|
|
19
|
+
try { Bun.spawnSync([BUN, "remove", "-g", PKG], { stdout: "inherit", stderr: "inherit" }); } catch {}
|
|
20
|
+
`;try{let B=m4(PQ(),"vibecontrols-uninstall");hQ(B,{recursive:!0});let K=m4(B,`reaper-${process.pid}.ts`);return vQ(K,H,{encoding:"utf8"}),DQ(Z,[K],{detached:!0,stdio:"ignore",windowsHide:!0}).unref(),V().logger.info("self-uninstall",`Scheduled detached uninstall reaper (pids=${z.join(",")}) at ${K}`),{ok:!0,scriptPath:K}}catch(B){return{ok:!1,scriptPath:null,error:B instanceof Error?B.message:String(B)}}}var bQ=new Set(["db","plugins-registry","logs","binaries","subprocs"]);async function p4(Q){let $=await u4();try{let Z=Q.getPluginManager?.();if(Z){let Y=new Set($.map((X)=>X.name));for(let X of Z.getPluginDetails()){let J=X.cliCommand;if(J&&!Y.has(J))Y.add(J),$.push({name:J,description:X.description||`${X.pluginName} plugin command`,usage:"",options:[],group:"plugin",destructive:!1})}}}catch{}return $.sort((Z,Y)=>Z.name.localeCompare(Y.name))}function l4(Q={}){return new v({name:"agent-maintenance"}).get("/api/agent/update/check",async()=>{return await R2()}).get("/api/agent/update/status",()=>{return x0()}).post("/api/agent/update",async({body:$})=>{return await i2({targetVersion:typeof $?.version==="string"?$.version:void 0,allowIncompatible:$?.allowIncompatible===!0,restart:$?.restart!==!1})},{body:W.Optional(W.Object({version:W.Optional(W.String()),allowIncompatible:W.Optional(W.Boolean()),restart:W.Optional(W.Boolean())}))}).post("/api/agent/update/config",({body:$})=>{return f4($.enabled),{ok:!0,status:x0()}},{body:W.Object({enabled:W.Boolean()})}).post("/api/agent/update/check-now",async({body:$})=>{return{ok:!0,...await O0({force:$?.force===!0})}},{body:W.Optional(W.Object({force:W.Optional(W.Boolean())}))}).get("/api/agent/commands",async()=>{let $=await p4(Q);return{commands:$,count:$.length}}).post("/api/agent/commands/run",async({body:$,set:Z})=>{let Y=Array.isArray($?.argv)?$.argv.filter((B)=>typeof B==="string"):[];if(Y.length===0)return Z.status=400,{ok:!1,error:"argv must be a non-empty string array"};let X=Y[0],J=await p4(Q),z=new Set(J.map((B)=>B.name));if(!z.has(X))return Z.status=400,{ok:!1,error:`Unknown or disallowed command: "${X}"`,allowed:[...z].sort()};return await o2(Y,{timeoutMs:typeof $?.timeoutMs==="number"?$.timeoutMs:void 0})},{body:W.Object({argv:W.Array(W.String()),timeoutMs:W.Optional(W.Number())})}).post("/api/agent/nuke",async({body:$,set:Z})=>{let Y=["nuke"];if($?.all)Y.push("--all");if($?.removeConfig)Y.push("--remove-config");if($?.dryRun)Y.push("--dry-run");if(typeof $?.removePlugins==="string"&&$.removePlugins)Y.push("--remove-plugins",$.removePlugins);if(typeof $?.keep==="string"&&$.keep){let z=$.keep.split(",").map((H)=>H.trim()).filter((H)=>H&&!bQ.has(H));if(z.length>0)return Z.status=400,{ok:!1,error:`Invalid --keep value(s): ${z.join(", ")}`};Y.push("--keep",$.keep)}Y.push("-y","--json");let X=await o2(Y),J=null;try{let z=X.stdout.trim().split(`
|
|
21
|
+
`).reverse().find((H)=>H.trim().startsWith("{"));if(z)J=JSON.parse(z)}catch{}return{...X,parsed:J}},{body:W.Optional(W.Object({all:W.Optional(W.Boolean()),removeConfig:W.Optional(W.Boolean()),removePlugins:W.Optional(W.String()),keep:W.Optional(W.String()),dryRun:W.Optional(W.Boolean())}))}).post("/api/agent/uninstall",async({body:$})=>{let Z=$?.dryRun===!0,Y=["nuke","--all","--remove-config","-y","--json"];if(Z)Y.push("--dry-run");let X=await o2(Y);if(Z)return{ok:X.ok,dryRun:!0,nuke:X,note:"Dry run \u2014 would nuke all state and uninstall @vibecontrols/agent."};let J=new Set([process.pid]);try{let H=new g2;for(let B of await H.listInstances())if(typeof B.pid==="number"&&B.pid>0)J.add(B.pid)}catch{}let z=g4({pids:[...J]});return{ok:X.ok&&z.ok,nuke:X,uninstallScheduled:z.ok,scriptPath:z.scriptPath,...z.error?{error:z.error}:{},note:"Agent state nuked; package self-uninstall scheduled \u2014 the daemon will stop and `@vibecontrols/agent` will be removed shortly."}},{body:W.Optional(W.Object({dryRun:W.Optional(W.Boolean())}))})}import{existsSync as gQ,readFileSync as pQ}from"fs";import{join as lQ}from"path";var cQ=`mutation AddAgentFromTunnel($input: AddAgentFromTunnelInput!) {
|
|
22
|
+
addVibecontrolsAgentFromTunnel(input: $input) { agent { id name } clientId success error }
|
|
23
|
+
}`,yQ=`mutation ReportAgentMeshLink($input: ReportAgentMeshLinkInput!) {
|
|
24
|
+
reportAgentMeshLink(input: $input) { id }
|
|
25
|
+
}`,d4="VIBE_BOOTSTRAP_JSON=";function uQ(Q){for(let Y of Q.split(/\r?\n/)){let X=Y.indexOf(d4);if(X>=0)try{return JSON.parse(Y.slice(X+d4.length))}catch{}}let $=Q.indexOf("{"),Z=Q.lastIndexOf("}");if($>=0&&Z>$)try{return JSON.parse(Q.slice($,Z+1))}catch{return null}return null}async function o4(Q,$){let Z=(L,q,C)=>$?.({step:L,status:q,message:C}),Y=i4(Q.permissions??["tunnel:read","session:list","plugin:list","diagnostics:read","mesh:forward"]);if(!Y.includes("mesh:forward"))Y.push("mesh:forward");let X=(L)=>({ok:!1,peerId:"",agentRecordId:null,tunnelUrl:null,permissions:Y,error:L}),J;try{J=r2(Q.target,{identityFile:Q.identityFile})}catch(L){return X(L instanceof Error?L.message:String(L))}let z=Q.label??J.id,H=Y.join(","),B,K='export PATH="$HOME/.bun/bin:$PATH"; ';try{if(!Q.connectExisting){Z("probe","running");let x=await J.probe();if(Z("probe","completed",`os=${x.os??"?"} arch=${x.arch??"?"}`),!x.bun){if(Q.installBun===!1)return X("Bun is required to run the agent but is not installed, and Bun auto-install was disabled.");Z("install-bun","running");let i=await J.run(["sh","-c",`curl -fsSL https://bun.sh/install | bash && echo 'export PATH="$HOME/.bun/bin:$PATH"' >> ~/.bashrc`],{timeoutMs:300000});if(i.code!==0)return Z("install-bun","failed",i.stderr.slice(0,400)),X("Bun auto-install failed.");let _2=await J.run(["sh","-c","$HOME/.bun/bin/bun --version 2>/dev/null"],{timeoutMs:1e4});if(_2.code===0&&_2.stdout.trim())x.bun="$HOME/.bun/bin/bun",Z("install-bun","completed",_2.stdout.trim());else return X("Bun installed but the binary is not reachable.")}Z("install-agent","running");let E=Q.version??"latest",D=Q.registry??"https://registry.npmjs.org/";if(!/^[A-Za-z0-9._@/^~>=<-]+$/.test(E))return Z("install-agent","failed","invalid version"),X(`Invalid agent version: ${E}`);if(!/^https?:\/\/[A-Za-z0-9._~:/?#@!$&'()*+,;=%-]+$/.test(D))return Z("install-agent","failed","invalid registry"),X(`Invalid registry URL: ${D}`);let h=await J.run(["sh","-c",`${K}npm_config_registry="${D}" bun install -g @vibecontrols/agent@${E} --no-cache`],{timeoutMs:600000});if(h.code!==0)return Z("install-agent","failed",h.stderr.slice(0,400)),X(`Agent install failed (exit ${h.code}).`);if(B=(await J.run(["sh","-c",`${K}vibe --version`],{timeoutMs:15000})).stdout.trim()||void 0,Z("install-agent","completed",B),Q.autostart)Z("autostart","running"),await J.run(["sh","-c",`${K}vibe autostart install`],{timeoutMs:60000}),Z("autostart","completed");if(Q.installPlugins?.length){Z("plugins","running");for(let i of Q.installPlugins)await J.run(["sh","-c",`${K}vibe plugin install ${i}`],{timeoutMs:300000});Z("plugins","completed")}Z("start","running"),await J.run(["sh","-c",`${K}vibe start`],{timeoutMs:60000}),Z("start","completed")}Z("bootstrap","running");let L=Q.expiresIn?` --expires-in ${Q.expiresIn}`:"",q=z.replace(/'/g,""),C=null;for(let x=0;x<15;x++){let E=`${K}vibe peer-bootstrap --json --emit-default-key --label '${q}' --scope ${H}${L} 2>/dev/null`,D=await J.run(["sh","-c",E],{timeoutMs:15000});if(D.code===0){let h=uQ(D.stdout);if(h&&typeof h.apiKey==="string"){C=h;break}}await new Promise((h)=>setTimeout(h,2000))}if(!C)return Z("bootstrap","failed","could not obtain peer-bootstrap bundle"),X("Remote peer-bootstrap did not return a credential bundle.");Z("bootstrap","completed");let U=n(),G=String(C.id),T=String(C.apiKey),R=s2(typeof C.tunnelUrl==="string"?C.tunnelUrl:null),P=typeof C.agentRecordId==="string"?C.agentRecordId:null;if(Q.onboardBackend!==!1&&g.isConfigured()&&R&&typeof C.fullDefaultApiKey==="string"){Z("onboard","running");let x=5,E="no agent returned";for(let D=0;D<x;D++){try{let i=(await g.workspaceQuery(cQ,{input:{tunnelUrl:R,apiKey:C.fullDefaultApiKey,name:z}})).data?.addVibecontrolsAgentFromTunnel;if(i?.agent?.id){P=i.agent.id,E="",Z("onboard","completed",`agent ${P}`);break}E=i?.error??"no agent returned"}catch(r){E=r instanceof Error?r.message:String(r)}if(!/unreachable|resolve hostname|timed out|timeout|ECONN|network|to fetch|50[234]/i.test(E)||D===x-1)break;Z("onboard","running",`retry ${D+1}/${x-1}: ${E.slice(0,80)}`),await new Promise((r)=>setTimeout(r,3000*(D+1)))}if(E)Z("onboard","failed",E)}else Z("onboard","skipped");Z("store-creds","running"),n4({id:G,label:z,tunnelUrl:R??"",apiKey:T,permissions:Y,addedAt:new Date().toISOString(),agentRecordId:P??void 0,workspaceId:(typeof C.workspaceId==="string"?C.workspaceId:U.workspaceId)??void 0,fingerprint:G,ownerUserId:U.ownerUserId,sshTarget:J.mode==="ssh"?Q.target:void 0,sshIdentityFile:Q.identityFile}),Z("store-creds","completed");let I=d2();if(Q.onboardBackend!==!1&&g.isConfigured()&&I&&P){Z("report-link","running");try{await g.workspaceQuery(yQ,{input:{sourceAgentRecordId:I,destinationAgentRecordId:P,label:z}}),Z("report-link","completed")}catch(x){Z("report-link","failed",x instanceof Error?x.message:String(x))}}else Z("report-link","skipped");let N=await A2(G,"/api/profiles/default/agent/identity",{operation:"post-deploy-probe"});return Z("probe-peer",N.ok?"completed":"failed",N.error??void 0),{ok:!0,peerId:G,agentRecordId:P,tunnelUrl:R,permissions:Y,remoteVersion:B}}catch(L){return X(L instanceof Error?L.message:String(L))}finally{await J.close().catch(()=>{})}}var M0='export PATH="$HOME/.bun/bin:$PATH"; ';function mQ(Q){let $=Q.indexOf("{"),Z=Q.lastIndexOf("}");if($>=0&&Z>$)try{let Y=JSON.parse(Q.slice($,Z+1));if(Y.tunnelUrl)return Y.tunnelUrl;if(Y.url&&Y.url.startsWith("https"))return Y.url}catch{}return null}async function r4(Q,$){let Z=(J,z,H)=>$?.({step:J,status:z,message:H}),Y=a4(Q);if(!Y)return{ok:!1,peerId:Q,tunnelUrl:null,error:`No peer with id ${Q}`};if(!Y.sshTarget)return{ok:!1,peerId:Q,tunnelUrl:null,error:"No SSH target stored for this peer \u2014 it wasn't SSH-deployed, so it can't be woken via SSH."};let X;try{X=r2(Y.sshTarget,{identityFile:Y.sshIdentityFile})}catch(J){return{ok:!1,peerId:Q,tunnelUrl:null,error:J instanceof Error?J.message:String(J)}}try{Z("ssh-restart","running",Y.sshTarget);let J=await X.run(["sh","-c",`${M0}vibe restart 2>/dev/null || ${M0}vibe start`],{timeoutMs:90000});if(J.code!==0)return Z("ssh-restart","failed",J.stderr.slice(0,300)),{ok:!1,peerId:Q,tunnelUrl:null,error:`Remote restart failed (exit ${J.code})`};Z("ssh-restart","completed"),Z("await-tunnel","running");let z=null;for(let H=0;H<15;H++){let B=await X.run(["sh","-c",`${M0}vibe url --json 2>/dev/null`],{timeoutMs:15000});if(B.code===0){let K=mQ(B.stdout),L=s2(K);if(L){z=L;break}}await new Promise((K)=>setTimeout(K,2000))}if(!z)return Z("await-tunnel","failed","no fresh tunnel after restart"),{ok:!1,peerId:Q,tunnelUrl:null,error:"Agent restarted but no fresh tunnel came up."};return Z("await-tunnel","completed",z),s4(Q,{tunnelUrl:z,lastReachable:new Date().toISOString()}),Z("update","completed"),{ok:!0,peerId:Q,tunnelUrl:z}}catch(J){return{ok:!1,peerId:Q,tunnelUrl:null,error:J instanceof Error?J.message:String(J)}}finally{await X.close().catch(()=>{})}}var dQ=Number(process.env.VIBECONTROLS_MESH_MAX_HOPS||"8");function t4(){return(b()??V()).name}function nQ(){return(b()??V()).dataDir}function e4(){try{let $=lQ(nQ(),"runtime.json");if(gQ($)){let Z=JSON.parse(pQ($,"utf8"));if(Z.port&&Number.isInteger(Z.port))return Z.port}}catch{}let Q=Number(process.env.PORT);return Number.isInteger(Q)&&Q>0?Q:3005}function iQ(Q){let $={};return Q.headers.forEach((Z,Y)=>{$[Y]=Z}),$}function X2(Q,$){let Z=m(iQ(Q));return Z5($5(Z),$)}function oQ(Q){let{apiKey:$,...Z}=Q;return{...Z,apiKey:"[REDACTED]"}}function Q5(Q){return typeof Q==="string"&&Q.startsWith("/api/")&&!Q.includes("..")&&!Q.includes("//")}var t2=new Map;function aQ(){let Q=Date.now()-3600000;for(let[$,Z]of t2)if(Z.completedAt&&Date.parse(Z.completedAt)<Q)t2.delete($)}function X5(){return new v({name:"agent-mesh"}).get("/api/mesh/peers",({request:Q,set:$})=>{if(!X2(Q,["read"]))return $.status=403,{error:"forbidden"};return{peers:L2(n()).map(oQ)}}).delete("/api/mesh/peers/:id",({request:Q,set:$,params:Z})=>{if(!X2(Q,["mutate"]))return $.status=403,{error:"forbidden"};if(!L2(n()).some((X)=>X.id===Z.id))return $.status=404,{error:"not found"};return{ok:J5(Z.id)}}).post("/api/mesh/peers/:id/call",async({request:Q,set:$,params:Z,body:Y})=>{if(!X2(Q,["mesh:forward"]))return $.status=403,{error:"forbidden"};let X=Y;if(!Q5(X.path))return $.status=400,{error:"invalid path"};if(!L2(n()).find((H)=>H.id===Z.id))return $.status=404,{error:"not found"};let z=await A2(Z.id,X.path,{method:X.method??"GET",body:X.body,operation:"mesh-call"});return{ok:z.ok,status:z.status,data:z.data,rotated:z.rotated,error:z.error}},{body:W.Object({method:W.Optional(W.String()),path:W.String(),body:W.Optional(W.Any())})}).post("/api/mesh/forward",async({request:Q,set:$,body:Z})=>{if(!X2(Q,["mesh:forward"]))return $.status=403,{error:"forbidden"};let Y=Z;if(!Y.request||!Q5(Y.request.path))return $.status=400,{error:"invalid request"};let X=(Y._hopCount??0)+1;if(X>dQ)return $.status=422,{error:"hop limit exceeded"};let J=n(),z=d2(),H=Y.hops??[];if(H.length===0){V().audit.emit("mesh","forward.terminal",{path:Y.request.path,method:Y.request.method??"GET"});let U=(Y.request.method??"GET").toUpperCase();try{let G=await fetch(`http://127.0.0.1:${e4()}${Y.request.path}`,{method:U,headers:{"x-agent-api-key":await T0(),...Y.request.body!==void 0?{"content-type":"application/json"}:{}},body:Y.request.body!==void 0?JSON.stringify(Y.request.body):void 0,signal:AbortSignal.timeout(60000)}),T=await G.text().catch(()=>""),R=null;try{R=T?JSON.parse(T):null}catch{R=null}return{ok:G.ok,status:G.status,data:R,text:T||null,error:G.ok?null:T||`status ${G.status}`}}catch(G){return $.status=502,{ok:!1,status:0,error:G instanceof Error?G.message:String(G)}}}let B=H[0],K=Y._traversed??[];if(B===z||K.includes(B))return $.status=422,{error:"cycle detected",at:B};let L=E0(B,J);if(!L)return $.status=403,{error:"next hop not in authorized boundary"};if(!L.permissions.includes("mesh:forward"))return $.status=403,{error:"peer lacks mesh:forward grant"};V().audit.emit("mesh","forward.hop",{nextId:B,remaining:H.length,hopCount:X});let q=encodeURIComponent(t4()),C=await A2(L.id,`/api/profiles/${q}/mesh/forward`,{method:"POST",operation:"mesh-forward",timeoutMs:60000,body:{hops:H.slice(1),request:Y.request,_traversed:[...K,z??"self"],_hopCount:X}});if(!C.ok)return $.status=502,{ok:!1,status:C.status,error:C.error,failedAtHop:B};return C.data},{body:W.Object({hops:W.Optional(W.Array(W.String())),request:W.Object({method:W.Optional(W.String()),path:W.String(),body:W.Optional(W.Any())}),_traversed:W.Optional(W.Array(W.String())),_hopCount:W.Optional(W.Number())})}).post("/api/mesh/deploy",({request:Q,set:$,body:Z})=>{if(!X2(Q,["admin"]))return $.status=403,{error:"forbidden"};aQ();let Y=Z,X=n(),J=crypto.randomUUID(),z={id:J,status:"running",steps:[],ownerUserId:X.ownerUserId,workspaceId:X.workspaceId,startedAt:new Date().toISOString()};return t2.set(J,z),o4({target:Y.target,permissions:Y.permissions,installPlugins:Y.installPlugins,autostart:Y.autostart,identityFile:Y.identityFile,label:Y.label,version:Y.version,connectExisting:Y.connectExisting},(H)=>{z.steps.push(H),Y2("mesh:deploy:progress",{jobId:J,step:H})}).then((H)=>{if(z.result=H,z.status=H.ok?"completed":"failed",!H.ok)z.error=H.error;z.completedAt=new Date().toISOString(),Y2(H.ok?"mesh:deploy:complete":"mesh:deploy:failed",{jobId:J,result:H})}).catch((H)=>{z.status="failed",z.error=H instanceof Error?H.message:String(H),z.completedAt=new Date().toISOString(),Y2("mesh:deploy:failed",{jobId:J,error:z.error})}),$.status=202,{jobId:J,status:"running"}},{body:W.Object({target:W.String(),permissions:W.Optional(W.Array(W.String())),installPlugins:W.Optional(W.Array(W.String())),autostart:W.Optional(W.Boolean()),identityFile:W.Optional(W.String()),label:W.Optional(W.String()),version:W.Optional(W.String()),connectExisting:W.Optional(W.Boolean())})}).get("/api/mesh/deploy/jobs/:id",({request:Q,set:$,params:Z})=>{if(!X2(Q,["read"]))return $.status=403,{error:"forbidden"};let Y=t2.get(Z.id),X=n();if(!Y||X.ownerUserId&&Y.ownerUserId&&Y.ownerUserId!==X.ownerUserId)return $.status=404,{error:"not found"};return Y}).post("/api/mesh/wake",async({request:Q,set:$,body:Z})=>{if(!X2(Q,["admin"]))return $.status=403,{error:"forbidden"};let Y=Z,X=E0(Y.targetAgentRecordId,n());if(!X)return $.status=404,{ok:!1,error:"peer not in authorized boundary"};V().audit.emit("mesh","wake.start",{peerId:X.id,agentRecordId:Y.targetAgentRecordId});let J=await r4(X.id,(z)=>Y2("mesh:wake:progress",{peerId:X.id,step:z}));if(!J.ok)$.status=502;return J},{body:W.Object({targetAgentRecordId:W.String()})}).post("/api/mesh/session",async({request:Q,set:$,body:Z})=>{if(!X2(Q,["mesh:forward","mutate"]))return $.status=403,{error:"forbidden"};let Y=Z,X=Y.sessionId&&/^[A-Za-z0-9_-]{1,128}$/.test(Y.sessionId)?Y.sessionId:crypto.randomUUID(),J=encodeURIComponent(t4()),z=await T0(),H=`http://127.0.0.1:${e4()}`,B=Y.command||"bash";try{let K=await fetch(`${H}/api/profiles/${J}/sessions/create`,{method:"POST",headers:{"x-agent-api-key":z,"content-type":"application/json"},body:JSON.stringify({sessionId:X,sessionName:`vc-mesh-${X.slice(0,8)}`,command:B,provider:"TERMINAL",...Y.vibeId?{projectId:Y.vibeId}:{}}),signal:AbortSignal.timeout(20000)});if(!K.ok)return $.status=502,{error:`session create returned ${K.status}: ${await K.text().catch(()=>"")}`};let L=await fetch(`${H}/api/profiles/${J}/sessions/${encodeURIComponent(X)}/terminal`,{method:"POST",headers:{"x-agent-api-key":z},signal:AbortSignal.timeout(20000)});if(!L.ok)return $.status=502,{error:`terminal start returned ${L.status}: ${await L.text().catch(()=>"")}`};let q=c2(`/terminal/${X}`,600);return V().audit.emit("mesh","session.created",{sessionId:X,kind:Y.kind??"TERMINAL"}),{connectionId:X,sessionId:X,capabilityToken:q.token,expiresAt:q.expiresAt}}catch(K){return $.status=502,{error:K instanceof Error?K.message:String(K)}}},{body:W.Object({sessionId:W.Optional(W.String()),kind:W.Optional(W.String()),cwd:W.Optional(W.String()),vibeId:W.Optional(W.String()),command:W.Optional(W.String())})})}var sQ=["/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 rQ(Q){return sQ.some(($)=>Q.startsWith($))}var tQ=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function eQ(Q){return Q.split("/").map(($)=>{if(!$)return $;if(/^\d+$/.test($))return":id";if(tQ.test($))return":id";if($.length>=24&&/^[A-Za-z0-9_-]+$/.test($))return":id";return $}).join("/")}async function L9(Q){let{port:$,host:Z,dbPath:Y,logLevel:X,corsOrigin:J}=Q,z=Y??C2();try{(await import("fs")).mkdirSync(z,{recursive:!0})}catch(F){throw V().logger.error("app","Failed to create dbPath dir at boot",{dbPath:z,error:String(F)}),Error(`Cannot create dbPath ${z}: ${F instanceof Error?F.message:String(F)}`,{cause:F})}if(X)V().logger.setLevel(X);(async()=>{let{logShipper:F}=await import("./log-shipper-m9h3jxem.js");F.init()})(),(async()=>{let F=await z5();await h2({version:F,profile:q2()})})();try{let{checkDependencies:F}=await import("./bootstrap.service-3zpbgsg0.js"),M=F(),j=M.filter((A)=>A.required&&!A.installed),w=M.filter((A)=>!A.required&&!A.installed);if(j.length>0)V().logger.error("app",`Missing required system deps: ${j.map((A)=>A.name).join(", ")}. Run \`vibe setup\` to install.`);if(w.length>0)V().logger.warn("app",`Missing optional system deps: ${w.map((A)=>A.name).join(", ")}. Some plugins may fail their prereqs check.`)}catch(F){V().logger.warn("app","Boot-time dependency check failed",{error:String(F)})}try{V().audit.runRetention()}catch(F){V().logger.warn("app","Audit-log retention sweep failed",{error:String(F)})}let H=new I5;P5(H,{port:$});let B="GET, POST, PUT, PATCH, DELETE, OPTIONS",K="Content-Type, x-agent-api-key, Authorization, x-requested-with",L=Array.isArray(J)?J:(J??"").split(",").map((F)=>F.trim()).filter(Boolean),q=new Set(["https://vibecontrols.com","https://app.vibecontrols.com","https://alphaapp.vibecontrols.com","https://burdenoff.com","https://app.burdenoff.com","https://alphaapp.burdenoff.com"]),C=(F)=>{try{let M=new URL(F);if(L.includes(F))return!0;if(L.includes("*"))return!1;return M.hostname==="localhost"||M.hostname==="127.0.0.1"||M.hostname==="0.0.0.0"||M.hostname.endsWith(".local.burdenoff.com")||q.has(M.origin)}catch{return!1}},U=null,G=null,T=null,R=null,P=!1,I=()=>[],N=null,x=null,E=null,D=5000,h=async(F,M)=>{let j=Date.now();try{await Promise.race([Promise.resolve(M()),new Promise((w,A)=>setTimeout(()=>A(Error(`shutdown phase ${F} exceeded ${D}ms`)),D))]),V().logger.info("app",`shutdown.phase ${F} complete`,{ms:Date.now()-j})}catch(w){V().logger.warn("app",`shutdown.phase ${F} failed`,{error:String(w),ms:Date.now()-j})}},r=async(F)=>{if(P)return;if(P=!0,V().logger.info("app","Agent shutdown starting",{reason:F?.reason??"shutdown"}),await h("plugins",async()=>{if(G)await G.dispatchServerStop(F)}),await h("bootstrap-tunnel",()=>R0()),await h("tracked-subprocesses",async()=>{let{killAllTracked:M}=await import("./subprocess-chzm6zj2.js");await M()}),F?.reason!=="reload")await h("db-close",async()=>{if(U)await U.close()});await h("http-listener",async()=>{try{await Promise.resolve(e.stop())}catch(M){V().logger.warn("app","Listener stop threw (already stopped or never started?)",{error:String(M)})}}),V().logger.info("app","Agent server stopped"),V().logger.close()},i=async(F,M)=>{if(V().getBootState()==="ready")return{ok:!0};if(E)return E;return E=(async()=>{V().setBootState("initializing");try{let j={...F,globalGatewayUrl:B2(F.globalGatewayUrl,"globalGatewayUrl"),workspaceGatewayUrl:B2(F.workspaceGatewayUrl,"workspaceGatewayUrl")},w=await R5(j),A=z,f=t({dir:V().dataDir}),p=f.storageAdapter??process.env.VIBE_STORAGE_ADAPTER??void 0,o=f.storageOptions,Q2=(_)=>{let O=(_ instanceof Error?_.message:String(_)).toLowerCase(),k=_&&typeof _==="object"&&"code"in _?String(_.code).toUpperCase():"";if(k==="EBUSY"||k==="EPERM"||k==="EACCES"||k==="EAGAIN"||k==="EMFILE"||k==="ENFILE"||k==="ETIMEDOUT"||k==="ECONNRESET"||k==="ECONNREFUSED"||O.includes("encryption key")||O.includes("fetch")&&O.includes("key")||O.includes("temporarily unavailable")||O.includes("resource busy"))return"transient";if(O.includes("auth tag")||O.includes("authentication tag")||O.includes("unable to authenticate data")||O.includes("bad decrypt")||O.includes("unsupported state")||O.includes("incorrect header check")||O.includes("invalid distance")||O.includes("incorrect data check")||O.includes("unexpected end of")||O.includes("unexpected token")||O.includes("json")&&(O.includes("parse")||O.includes("invalid"))||O.includes("truncated")||O.includes("malformed")||O.includes("corrupt"))return"corruption";return"unknown"},j2=()=>W5({dbPath:A,encryptionKey:w,adapterName:p,adapterOptions:o});try{U=await j2()}catch(_){let O=_,k=Q2(_),k2=[500,2000,8000];if(k==="transient"||k==="unknown"){V().logger.warn("app",`Storage open failed (${k}); will retry up to ${k2.length} times before quarantine`,{error:_ instanceof Error?_.message:String(_),path:A});for(let U2 of k2){await new Promise((c)=>setTimeout(c,U2));try{U=await j2(),O=null;break}catch(c){if(O=c,k=Q2(c),V().logger.warn("app",`Storage open retry failed (${k}) after ${U2}ms`,{error:c instanceof Error?c.message:String(c)}),k==="corruption")break}}}if(!U&&O){if(k!=="corruption"){let c=O instanceof Error?O.message:String(O);V().logger.error("app",`Storage open failed after retries with non-corruption error (${k}); refusing to quarantine valid data`,{error:c,path:A}),V().recordDegradedReason("storage",c);try{throw O}catch(V2){throw Error(`Storage open failed (${k}); agent is degraded: ${c}`,{cause:V2})}}let U2=O instanceof Error?O.message:String(O);V().logger.error("app","QUARANTINE: Storage file is corrupt \u2014 renaming and creating fresh DB",{errorClass:"corruption",error:U2,path:A});try{let c=await import("fs");if(c.existsSync(A)){let V2=new Date().toISOString().replace(/[:.]/g,"-"),S0=`${A}.broken-${V2}`;c.renameSync(A,S0),V().logger.warn("app",`Quarantined corrupt storage to ${S0} \u2014 fresh DB will be created`,{originalError:U2})}U=await j2()}catch(c){let V2=c instanceof Error?c.message:String(c);throw V().recordDegradedReason("storage",V2),Error(`Storage open failed twice (quarantine path); agent is degraded: ${V2}`,{cause:c})}}}if(!U)throw Error("Internal error: storage open recovery exited without an open database and without throwing");if(await b2({clientId:j.clientId,clientSecret:j.clientSecret,workspaceId:j.workspaceId,organizationId:j.organizationId,globalGatewayUrl:j.globalGatewayUrl,workspaceGatewayUrl:j.workspaceGatewayUrl,agentRecordId:M?.agentRecordId,scopes:M?.scopes},{dir:V().dataDir,scope:V().name}),await U.setConfig("gateway-auth:clientId",j.clientId),await U.setConfig("gateway-auth:clientSecret",j.clientSecret),await U.setConfig("gateway-auth:globalGatewayUrl",j.globalGatewayUrl),await U.setConfig("gateway-auth:workspaceGatewayUrl",j.workspaceGatewayUrl),await U.setConfig("gateway-auth:workspaceId",j.workspaceId),j.organizationId)await U.setConfig("gateway-auth:organizationId",j.organizationId);if(M?.agentRecordId)await U.setConfig("gateway-auth:agentRecordId",M.agentRecordId);H.db=U,await H.hydrateDefaultsFromDb(),G=new D5(U),await G.loadCorePlugins();try{await G.loadAll()}catch(_){V().logger.warn("app","Failed to load some external plugins",{error:String(_)})}let O2=v5(F2())??void 0,x2=process.env.VIBE_SKIP_AUTO_INSTALL==="1"||await U.getConfig("plugins:auto-install-disabled");if(x2!=="true"&&x2!==!0)try{let _=await G.ensureDefaultPlugins((O)=>V().logger.info("app",`[auto-install] ${O}`),[],O2);if(_.length>0)V().logger.info("app",`Auto-installed ${_.length} default plugin(s): ${_.map((O)=>O.packageName).join(", ")}`)}catch(_){V().logger.warn("app","Failed to auto-install default plugins",{error:String(_)})}V().logger.info("app",`Plugins loaded: ${G.getPluginDetails().length} total (${G.getPluginDetails().filter((_)=>_.isCore).length} core)`);try{let _=G.getPluginDetails(),O={loaded:_.filter((k)=>k.loaded).length,failed:_.filter((k)=>!k.loaded).length};m0(O)}catch{}let Q0={async get(_,O){return await U.getPluginState(_,O)??null},async set(_,O,k){await U.setPluginState(_,O,k)},async delete(_,O){return U.deletePluginState(_,O)},async list(_){return await U.getAllPluginState(_)},async deleteAll(_){return U.deleteAllPluginState(_)}},w2=await z5();T={storage:Q0,logger:V().logger,serviceRegistry:H,getProvider:(_)=>H.getProvider(_),getAgentBaseUrl:()=>process.env.AGENT_URL||`http://localhost:${$}`,getAgentVersion:()=>w2,validateApiKey:(_)=>l(_),setCodeServerSessionValidator:(_)=>{f5=_},broadcast:Y2,workspaceQuery:async(_,O)=>g.workspaceQuery(_,O),isGatewayConfigured:()=>g.isConfigured(),getAgentRecordId:async()=>await U.getConfig("gateway-auth:agentRecordId")??null,getWorkspaceId:async()=>await U.getConfig("gateway-auth:workspaceId")??null,getConfig:async(_)=>await U.getConfig(_)??void 0,getPluginRegistry:()=>a2(),getDataDir:()=>P2(),cliContributors:new q5,audit:{emit:(_,O)=>V().audit.emit("agent",_,O??{})},telemetry:{emit:(_,O)=>{import("./telemetry-h9pa43c9.js").then(({telemetryService:k})=>k.emit(_,O??{})).catch(()=>{})}},os:N2(),iframeBridge:S5()},g.configure({globalGatewayUrl:j.globalGatewayUrl,workspaceGatewayUrl:j.workspaceGatewayUrl,clientId:j.clientId,clientSecret:j.clientSecret,workspaceId:j.workspaceId,organizationId:j.organizationId});let H2={db:U,serviceRegistry:H,pluginManager:G,broadcast:Y2,hostServices:T};H2.app=e;let k0=!1,$0=()=>{let{routes:_,getPublicPaths:O,mountPlugin:k}=G5(G,H2);if(H2.mountPlugin=k,I=O,L5(),N=_,x=k5(G),G&&k0&&T)G.dispatchServerStart(N,T).catch((k2)=>V().logger.warn("app","Re-dispatch of onServerStart after plugin reload failed",{error:String(k2)}));k0=!0};H2.rebuildPluginSurfaces=$0,$0(),R=new A5(H,G,U,e,T,r),H.registerService("agent","lifecycle",R),V().attachServices({db:U,serviceRegistry:H,pluginManager:G,lifecycle:R,hostServices:T}),E5(V(),{rebuildPluginSurfaces:$0,mountPlugin:H2.mountPlugin,app:N});try{await V().keyVault.bindApiKey(G2())}catch(_){V().logger.warn("app","Failed to bind api key into daemon keyVault",{error:String(_)})}let Z0=[];try{let{failures:_}=await G.dispatchServerStart(N,T);for(let O of _)if(q0(O.plugin)||(O.packageName?q0(O.packageName):!1))Z0.push(O),V().recordDegradedReason(O.plugin,O.error);else V().logger.warn("app",`Non-critical plugin ${O.plugin} failed onServerStart; continuing`,{error:O.error})}catch(_){V().logger.warn("app","Error during plugin onServerStart dispatch",{error:String(_)})}try{await G.dispatchServerReady(e,T)}catch(_){V().logger.warn("app","Error during plugin onServerReady dispatch",{error:String(_)})}if(V().clearFinalizeError(),Z0.length>0)V().setBootState("degraded"),V().logger.error("app","Agent finalized but degraded \u2014 critical plugins failed",{failures:Z0.map((_)=>`${_.plugin}: ${_.error}`)});else V().setBootState("ready"),V().logger.info("app","Agent finalized \u2014 state=ready"),V().audit.emit("agent","gateway-auth.configured",{workspaceId:j.workspaceId,organizationId:j.organizationId,agentRecordId:M?.agentRecordId});return(async()=>{try{if(await G.provisionDefaultPrereqs(e,T,H2.mountPlugin,O2),V().logger.info("app","Default provider prerequisites provisioned"),(H.listProvidersForType("tunnel")??[]).some((k)=>k.pluginName!=="bootstrap")){let{tryHandoverBootstrapTunnel:k}=await import("./tunnel-bootstrap-6xm4w7dm.js");if(!k())R0();H.unregisterProvider("tunnel","bootstrap"),V().logger.info("app","Bootstrap tunnel handed over to the real tunnel provider")}}catch(_){V().logger.warn("app","Plugin prerequisite provisioning failed",{error:String(_)})}})(),{ok:!0}}catch(j){V().setBootState("awaiting-config");let w=j instanceof Error?j.message:String(j);if(V().recordFinalizeError(w),V().logger.error("app","Finalize failed",{error:w}),process.env.VIBE_STRICT_KEY_FETCH==="1")V().logger.error("app","VIBE_STRICT_KEY_FETCH=1 \u2192 aborting daemon (strict mode)",{error:w}),setTimeout(()=>process.exit(1),50);return{ok:!1,error:w}}finally{E=null}})(),E},_2=v0({origin:(F)=>{let M=F.headers.get("origin");return!!M&&C(M)},credentials:!0,allowedHeaders:K.split(",").map((F)=>F.trim()),methods:B.split(",").map((F)=>F.trim()),exposeHeaders:["content-type","content-length"],maxAge:86400,preflight:!0}),b5=10485760,A0=process.env.VIBECONTROLS_MAX_BODY_BYTES,e2=A0?Number.parseInt(A0,10):NaN,c5=Number.isFinite(e2)&&e2>0?e2:b5,w0={current:null},e=new v({serve:{maxRequestBodySize:c5}}).onRequest(({request:F,set:M})=>{let w=H5(F.headers)??C0();V5({requestId:w,startedAt:new Date().toISOString()});let A=M.headers??={};A["X-Request-Id"]=w}).onRequest(({request:F})=>{try{let M=new URL(F.url).pathname,w=/^\/api\/profiles\/([^/]+)(?:\/|$)/.exec(M)?.[1],A=w?s.get(w):null;I0(A??V())}catch{I0(V())}}).onRequest(({request:F,set:M})=>{let j=new URL(F.url).pathname;if(!j.startsWith("/api/"))return;if(j==="/api/profiles"||j.startsWith("/api/profiles/"))return;if(j==="/api/profile-stats"||j.startsWith("/api/profile-stats/"))return;let w=new URL(F.url);w.pathname=`/api/profiles/default${j.slice(4)}`;try{F.headers.set("x-vc-profile-rewrite","1"),F.headers.set("x-vc-profile-rewrite-target",w.pathname)}catch{}return}).derive(()=>({requestId:B5()??C0()})).use(_2).use(_5()).use(N5(()=>I())).use(b0({getDb:()=>b()?.db??U})).onBeforeHandle(({request:F,set:M})=>{let j=V().getBootState();if(j==="ready")return;let w=new URL(F.url).pathname;if(rQ(w))return;return M.status=503,{error:"Agent not yet configured",message:"Agent is in '"+j+"' state. POST credentials to /api/agent/gateway-auth to finalize.",state:j}}).onAfterHandle(({request:F,set:M})=>{let j=new URL(F.url).pathname,w=j==="/health"||j.startsWith("/api/logs/stream")||j.startsWith("/ui/")||j==="/ws/events"||j==="/api/sessions/health-check"||j.startsWith("/terminal/"),A=typeof M.status==="number"?M.status:200,f=w?"debug":A>=400?"warn":"info";V().logger[f]("http",`${F.method} ${j} \u2192 ${A}`,{method:F.method,path:j,statusCode:A});try{u0(F.method,eQ(j),A)}catch{}}).use(j4({serviceRegistry:H,getDb:()=>b()?.db??U,getDbPath:()=>z,getPluginManager:()=>b()?.pluginManager??G})).use(p0()).use(X4({serviceRegistry:H,runFinalize:(F,M)=>i(F,M),getDb:()=>b()?.db??U})).use(x4()).use(U4()).use(l4({getPluginManager:()=>b()?.pluginManager??G})).use(X5()).use(C4()).use(S4({getPluginManager:()=>b()?.pluginManager??G,getTunnelHost:()=>h5()?.url??null})).use(K4()).use(L4()).use(U5()).use(T5()).use(M5(H)).ws("/code-server/*",$6($)).all("/api/profiles/:name/*",async({params:F,request:M,set:j})=>{let w=M.method!=="GET"&&M.method!=="HEAD",A=w?await M.arrayBuffer():void 0,f=await C5(F.name,M,A);if(f&&f.status!==404)return f;let p=q2(),o=F.name;if(o!==p)return j.status=404,{error:"profile-mismatch",running:p,requested:o,hint:"This daemon serves a different profile. Call GET /api/profiles to discover the right tunnel."};let Q2=new URL(M.url),j2=Q2.pathname.replace(/^\/api\/profiles\/[^/]+/,"/api"),O2=new Headers(M.headers);O2.set("x-vc-profile-rewrite","1");let x2={method:M.method,headers:O2};if(w&&A!==void 0)x2.body=A;let Q0=new Request(`${Q2.origin}${j2}${Q2.search}`,x2),w2=w0.current;if(!w2)return new Response(JSON.stringify({error:"agent-not-ready"}),{status:503,headers:{"content-type":"application/json"}});return w2.handle(Q0)}).all("/api/*",async({request:F})=>{if(V().getBootState()!=="ready"||!N)return new Response(JSON.stringify({error:"Agent not yet configured",state:V().getBootState(),message:"Plugin routes are unavailable until the agent reaches state=ready. POST credentials to /api/agent/gateway-auth to finalize."}),{status:503,headers:{"content-type":"application/json"}});try{let M=new URL(F.url),j=/^\/api\/plugins\/([a-z0-9-]{1,64})\/ui(?:\/.*)?$/.exec(M.pathname);if(j&&F.method==="GET"){let w=j[1];if(E2(w)){let A=M.pathname.slice(`/api/plugins/${w}/ui`.length),f=A===""||A==="/",o=F.headers.get("sec-fetch-mode")==="navigate";if(f||o){let Q2=F5(F,w);if(!Q2||!K5(Q2,w))return new Response(w5(w,"/api/profiles/default/agent/ui-exchange-plugin"),{status:200,headers:{"content-type":"text/html; charset=utf-8","Content-Security-Policy":"frame-ancestors 'self' http://localhost:* http://127.0.0.1:* https://localhost:* https://127.0.0.1:* https://*.local.burdenoff.com https://vibecontrols.com https://*.vibecontrols.com https://burdenoff.com https://app.burdenoff.com https://alphaapp.burdenoff.com"}})}}}}catch{}return N.handle(F)}).all("/ui/*",async({request:F})=>{if(V().getBootState()!=="ready"||!x)return new Response("Plugin UI not yet available",{status:503});return x.handle(F)}).all("/code-server/*",async({request:F})=>{if(V().getBootState()!=="ready"||!N)return new Response("code-server not yet available",{status:503});let M=h0(F,G2);return N.handle(M??F)}).all("/plan/*",async({request:F})=>{if(V().getBootState()!=="ready"||!N)return new Response("plan provider not yet available",{status:503});return N.handle(F)});return w0.current=e,{app:e,async start(){e.listen({port:$,hostname:Z}),V().logger.info("app",`Agent server listening on ${Z}:${$}`);try{let F=(process.env.VIBECONTROLS_PROFILES??"").split(",").map((f)=>f.trim()).filter(Boolean),M=V().name,{getOrCreateProfile:j}=await import("./daemon-profile-nbe3pww8.js"),{attachSecondaryProfile:w}=await import("./secondary-profile-attach-yzwncw4f.js"),A=process.env.VIBE_STRICT_KEY_FETCH==="1";for(let f of F){if(f===M)continue;try{let p=j(f),o=await w(p);if(o.ok)V().logger.info("app",`Secondary profile '${f}' attached (db+services online)`);else if(A)throw Error(`attachServices for secondary profile '${f}' failed: ${o.error}`);else p.recordDegradedReason("attach",o.error??"unknown"),V().logger.warn("app",`Secondary profile '${f}' is degraded (no creds / attach failed)`,{error:o.error})}catch(p){if(A)throw V().logger.error("app",`--strict-key-fetch: secondary profile '${f}' attach failed; aborting`,{error:String(p)}),setTimeout(()=>process.exit(1),50),p;V().logger.warn("app",`Failed to attach secondary profile '${f}'`,{error:String(p)})}}}catch{}return e},stop:r,finalize:i,getState:()=>V().getBootState(),getLifecycle:()=>b()?.lifecycle??R,getDb:()=>b()?.db??U,getServiceRegistry:()=>b()?.serviceRegistry??H,getPluginManager:()=>b()?.pluginManager??G,getHostServices:()=>b()?.hostServices??T}}var f5=null;function Q6(Q,$){if(!Q)return null;let Z=Q.match(new RegExp(`(?:^|;\\s*)${$}=([^;]*)`));return Z?Z[1]:null}var Y5=j5(O5);function $6(Q){let X=(J)=>typeof J==="string"?Buffer.byteLength(J):J.byteLength;return{open(J){let z=J.data,H=m(z.headers??{})??m(z.request?Object.fromEntries(z.request.headers.entries()):{}),B=z.query?.vt,K=!!B&&S2(B,"/code-server","GET"),L,q=l(H);if(!q&&!K){let T=z.headers?.cookie??z.request?.headers.get("cookie")??null,R=Q6(T,"__vibe_cs_session");if(!R||!f5?.(R)){J.close(1008,"Unauthorized");return}L=`session:${R}`}else if(q)L="api-key";else L="vt";let C=J.remoteAddress??null,U=x5(C,z.headers);if(!Y5.accept(L,U,J)){V().logger.warn("code-server-ws",`code-server WS cap exceeded (key=${L}, ip=${U??"unknown"})`),J.close(1013,"too many connections");return}z._csCapKey=L,z._csRemoteIp=U;let G=V().name;fetch(`http://127.0.0.1:${Q}/api/profiles/${encodeURIComponent(G)}/code-server/status`,{headers:{"x-agent-api-key":G2()}}).then((T)=>T.json()).then((T)=>{if(z._csClosed)return;let R=T;if(!R.running||!R.port){J.close(1011,"code-server not running");return}let P=z.request?.url??"/code-server/",I;try{let E=new URL(P,`http://127.0.0.1:${R.port}`);I=(E.pathname.replace(/^\/code-server\/?/,"/")||"/")+E.search}catch{I="/"}let N=new WebSocket(`ws://127.0.0.1:${R.port}${I}`),x={upstream:N,ready:!1,buffer:[],bufferBytes:0,openTimer:setTimeout(()=>{try{N.close(1011,"upstream open timeout")}catch{}try{J.close(1011,"upstream open timeout")}catch{}},1e4)};z._csBridge=x,N.addEventListener("open",()=>{clearTimeout(x.openTimer),x.ready=!0;for(let E of x.buffer)N.send(E);x.buffer.length=0,x.bufferBytes=0}),N.addEventListener("message",(E)=>{try{let D=E.data;if(D instanceof ArrayBuffer)J.send(new Uint8Array(D));else if(D instanceof Blob)D.arrayBuffer().then((h)=>{try{J.send(new Uint8Array(h))}catch{}});else J.send(D)}catch{}}),N.addEventListener("close",(E)=>{clearTimeout(x.openTimer);try{J.close(E.code||1000,E.reason||"upstream closed")}catch{}}),N.addEventListener("error",()=>{clearTimeout(x.openTimer);try{J.close(1011,"upstream error")}catch{}})}).catch(()=>{J.close(1011,"Failed to query code-server status")})},message(J,z){let H=J.data?._csBridge;if(!H)return;let B;if(typeof z==="string")B=z;else if(z instanceof ArrayBuffer)B=z;else if(z instanceof Uint8Array||Buffer.isBuffer(z)){let K=new ArrayBuffer(z.byteLength);new Uint8Array(K).set(new Uint8Array(z.buffer,z.byteOffset,z.byteLength)),B=K}else if(typeof z==="object"&&z!==null)B=JSON.stringify(z);else B=String(z);if(H.upstream&&H.ready&&H.upstream.readyState===WebSocket.OPEN)try{H.upstream.send(B)}catch{}else{let K=X(B);if(H.buffer.length>=256||H.bufferBytes+K>1048576){try{H.upstream.close(1013,"buffer limit exceeded")}catch{}try{J.close(1013,"buffer limit exceeded")}catch{}return}H.buffer.push(B),H.bufferBytes+=K}},close(J){J.data._csClosed=!0;let z=J.data?._csBridge;if(z?.openTimer)clearTimeout(z.openTimer);if(z?.upstream&&z.upstream.readyState===WebSocket.OPEN)z.upstream.close(1000,"client disconnected");let H=J.data._csCapKey,B=J.data._csRemoteIp;if(H)Y5.release(H,B??null,J)}}}async function z5(){try{let{readFileSync:Q}=await import("fs"),{join:$,dirname:Z}=await import("path"),{fileURLToPath:Y}=await import("url"),X=Z(Y(import.meta.url));return JSON.parse(Q($(X,"..","package.json"),"utf8")).version||"1.0.0"}catch{return"1.0.0"}}
|
|
26
|
+
export{M6 as j,n0 as k,wQ as l,v7 as m,L9 as n};
|