@vibecontrols/agent 2026.602.2 → 2026.602.4
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-85pskv43.js → agent-config-4ppenhqp.js} +1 -1
- package/dist/{agent-ready-tracker-zp6p8e6f.js → agent-ready-tracker-kgs7td6t.js} +1 -1
- package/dist/app-8qe1gw9z.js +2 -0
- package/dist/bootstrap-workspace-qgs6d5f0.js +2 -0
- package/dist/bootstrap.service-vg72w8pa.js +2 -0
- package/dist/{bridge-client-341r9rry.js → bridge-client-1fxza4p7.js} +1 -1
- package/dist/cli.js +1 -1
- package/dist/daemon-profile-gwdcqx0q.js +2 -0
- package/dist/esm-6f3dfn6v.js +2 -0
- package/dist/{finalize-retry-handle-registry-vv241fsq.js → finalize-retry-handle-registry-xnm9kxry.js} +1 -1
- package/dist/{finalize-retry-worker-xp1nhv3c.js → finalize-retry-worker-dvykrzed.js} +1 -1
- package/dist/gateway-client-9kwnmk89.js +2 -0
- package/dist/{getMachineId-bsd-a56s0v8c.js → getMachineId-bsd-753751sw.js} +1 -1
- package/dist/{getMachineId-darwin-w9k0yw9r.js → getMachineId-darwin-na1pranq.js} +1 -1
- package/dist/{getMachineId-linux-anh31jbf.js → getMachineId-linux-dmn0ncdm.js} +1 -1
- package/dist/{getMachineId-unsupported-5hv3pwca.js → getMachineId-unsupported-yv77j894.js} +1 -1
- package/dist/{getMachineId-win-njb8tery.js → getMachineId-win-9hmyqmm0.js} +1 -1
- package/dist/highlights-00fcgwwq.js +2 -0
- package/dist/highlights-23bc8zge.js +2 -0
- package/dist/highlights-4mhb2pb0.js +2 -0
- package/dist/highlights-q7w64nwb.js +2 -0
- package/dist/highlights-xwdw5xay.js +2 -0
- package/dist/{index-678rwfc0.js → index-0924jp9m.js} +1 -1
- package/dist/{index-z5a4yxzz.js → index-1mppacnx.js} +3 -3
- package/dist/{index-g8zv1gta.js → index-1zf3r23y.js} +1 -1
- package/dist/{index-jw1k4vbk.js → index-4qq083yd.js} +1 -1
- package/dist/index-5amvpjqx.js +11 -0
- package/dist/{index-d5ysy1yn.js → index-5dysvvjv.js} +1 -1
- package/dist/{index-n7qyrdr1.js → index-5wpck4aw.js} +1 -1
- package/dist/{index-5mw3eshk.js → index-8nqp3a4d.js} +1 -1
- package/dist/{index-2xs9cvjn.js → index-8sdrhr3q.js} +2 -2
- package/dist/{index-6mprnf7p.js → index-97mq40rr.js} +1 -1
- package/dist/{index-0cn9bv8z.js → index-a4854mwz.js} +1 -1
- package/dist/{index-tp4y9jde.js → index-a9ejdv22.js} +1 -1
- package/dist/{index-fzzwprvk.js → index-aq81xmn0.js} +5 -5
- package/dist/{index-xjzmb1pn.js → index-b6x6a4xp.js} +2 -2
- package/dist/{index-yy1mm8zs.js → index-c7554sg7.js} +1 -1
- package/dist/{index-mtm8cfyt.js → index-ca5c245v.js} +2 -2
- package/dist/{index-2gsarrbn.js → index-d1xjj001.js} +1 -1
- package/dist/{index-h8a8s8sn.js → index-ebwwtwwc.js} +1 -1
- package/dist/{index-8sm0nkh8.js → index-ep3zb271.js} +1 -1
- package/dist/{index-g2raeeh4.js → index-h74va4wd.js} +2 -2
- package/dist/{index-v9fx5wab.js → index-hvjqgb97.js} +1 -1
- package/dist/{index-9bqd8veb.js → index-js1xn4sq.js} +3 -3
- package/dist/{index-x1h8r7pr.js → index-kt5zxp42.js} +1 -1
- package/dist/{index-ssjmzqcz.js → index-nmk7cbj5.js} +1 -1
- package/dist/{index-rdp5xq4r.js → index-nrsqzcfc.js} +1 -1
- package/dist/index-p23tet7a.js +2 -0
- package/dist/{index-04n4qgvd.js → index-pgew6sge.js} +3 -3
- package/dist/{index-1zw3kea7.js → index-qwtspxw8.js} +1 -1
- package/dist/index-qzwphe3q.js +26 -0
- package/dist/index-rqq0k5fc.js +16 -0
- package/dist/{index-6jq17k9s.js → index-rv6h14n8.js} +1 -1
- package/dist/{index-qfz9fy56.js → index-rw9x93zb.js} +1 -1
- package/dist/{index-dm6yjmgq.js → index-rzpaqrhx.js} +2 -2
- package/dist/{index-g3ap3xpr.js → index-s2xpdnsj.js} +4 -4
- package/dist/{index-vdahdt49.js → index-tgrt61qr.js} +1 -1
- package/dist/{index-ef95xr4z.js → index-thammzct.js} +2 -2
- package/dist/{index-scsjyj4m.js → index-x649afed.js} +2 -2
- package/dist/{index-8kvc8ttn.js → index-xrs52f2c.js} +1 -1
- package/dist/{index-yrgm89r8.js → index-ydc0tk17.js} +1 -1
- package/dist/{index-1hnw0rhc.js → index-ytgmhxsj.js} +31 -31
- package/dist/{index-0248afsn.js → index-z5s398n0.js} +1 -1
- package/dist/index.js +2 -2
- package/dist/injections-x3xya90r.js +2 -0
- package/dist/interactive-qc1j66mq.js +2 -0
- package/dist/key.cmd-972133dv.js +2 -0
- package/dist/log-shipper-hjnn1d5p.js +2 -0
- package/dist/{path-utils-35re7qf9.js → path-utils-hxdyv2zn.js} +1 -1
- package/dist/{plugin-system-c916v9an.js → plugin-system-cwznxqx5.js} +1 -1
- package/dist/prereqs-runner-27x3j1md.js +2 -0
- package/dist/profile-mount-8dc9jwt5.js +2 -0
- package/dist/prune-stale-shims-23y0stm8.js +2 -0
- package/dist/register-core-0d4adnqp.js +2 -0
- package/dist/secondary-profile-attach-qk5tde9n.js +2 -0
- package/dist/subprocess-1nna3d3x.js +2 -0
- package/dist/telemetry-8jfdyt51.js +2 -0
- package/dist/tree-sitter-javascript-q22gvtms.js +2 -0
- package/dist/tree-sitter-markdown-pntsjzm3.js +2 -0
- package/dist/tree-sitter-markdown_inline-g1wzqf7k.js +2 -0
- package/dist/tree-sitter-typescript-m9yfes10.js +2 -0
- package/dist/tree-sitter-zig-jmh62j90.js +2 -0
- package/dist/tunnel-bootstrap-5wgt9a1h.js +2 -0
- package/package.json +1 -1
- package/dist/app-y4yzq7yw.js +0 -2
- package/dist/bootstrap-workspace-zpm20zez.js +0 -2
- package/dist/bootstrap.service-pjmnpxha.js +0 -2
- package/dist/daemon-profile-vas1vf2t.js +0 -2
- package/dist/esm-9fpye77x.js +0 -2
- package/dist/gateway-client-43gzvj5s.js +0 -2
- package/dist/highlights-8d9mgr01.js +0 -2
- package/dist/highlights-jwvdxm9x.js +0 -2
- package/dist/highlights-qbx2vnme.js +0 -2
- package/dist/highlights-r3m83kn9.js +0 -2
- package/dist/highlights-s7mqapt6.js +0 -2
- package/dist/index-01qzsnwd.js +0 -16
- package/dist/index-hrdamx5j.js +0 -2
- package/dist/index-tmrbs96r.js +0 -11
- package/dist/index-z2yjbq9a.js +0 -26
- package/dist/injections-srewsjcz.js +0 -2
- package/dist/interactive-22ta89hc.js +0 -2
- package/dist/key.cmd-wgcq6kt8.js +0 -2
- package/dist/log-shipper-k24m8yw5.js +0 -2
- package/dist/prereqs-runner-ca4kt803.js +0 -2
- package/dist/profile-mount-npcknw6v.js +0 -2
- package/dist/prune-stale-shims-nkx9vq5m.js +0 -2
- package/dist/register-core-xhrk6ay5.js +0 -2
- package/dist/secondary-profile-attach-db5cr3e1.js +0 -2
- package/dist/subprocess-g9sk1ep9.js +0 -2
- package/dist/telemetry-tnq47dcs.js +0 -2
- package/dist/tree-sitter-javascript-3h25c6bs.js +0 -2
- package/dist/tree-sitter-markdown-3nemcjhe.js +0 -2
- package/dist/tree-sitter-markdown_inline-16ftwa53.js +0 -2
- package/dist/tree-sitter-typescript-f6mq6ze6.js +0 -2
- package/dist/tree-sitter-zig-s2trkm2d.js +0 -2
- package/dist/tunnel-bootstrap-2kg79ng8.js +0 -2
package/dist/index-z2yjbq9a.js
DELETED
|
@@ -1,26 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{o as B4,q as $4}from"./index-n7qyrdr1.js";import{u as a4,v as N5,w as j5}from"./index-1hnw0rhc.js";import{E as V4}from"./index-6jzsthh9.js";import{$ as b4,Q as T5,aa as F2,ba as U0,ca as v4,da as y4,ea as d4,fa as P4,ha as C2,ia as p2,ja as i2,ka as I2}from"./index-g8zv1gta.js";import{la as E5,qa as C5,sa as T0}from"./index-qfz9fy56.js";import{va as b2}from"./index-ssjmzqcz.js";import{wa as _5,xa as U5,ya as x5,za as O5}from"./index-tp4y9jde.js";import{Aa as L5}from"./index-4wgjx8bf.js";import{Ja as M0,Wa as M5}from"./index-g3ap3xpr.js";import{Xa as _2}from"./index-0ckffygp.js";import{ab as v2}from"./index-rc79x8fw.js";import{eb as e4,fb as Y5,gb as W5,hb as z5,ib as H5,jb as Y2,kb as G5,lb as V5,mb as B5,nb as K5,pb as F5}from"./index-v9fx5wab.js";import{Ab as d0,Eb as O2,Fb as X0,Gb as $5,Hb as Z5,Ib as j0,Jb as M2,Kb as m,Lb as l,Mb as p4,Nb as l4,Ob as J5,Pb as X5,tb as g0,ub as h2,vb as p0,wb as J0,xb as l0,yb as Q5}from"./index-01qzsnwd.js";import{Tb as z,Ub as D}from"./index-04n4qgvd.js";import{md as r0,nd as t,od as m0,pd as f2,qd as D2}from"./index-g2raeeh4.js";import{Cd as n2,Hd as g,Jd as O0,Kd as y,Ld as s,Nd as G,Od as Y0,vd as x0,wd as s4,xd as r4,yd as t4,zd as V2}from"./index-9bqd8veb.js";import{Rd as a0,Sd as z0,Ud as P2,Vd as s0,Xd as E2,Yd as d,_d as S2,ae as T2,be as K2,ce as d2}from"./index-0cn9bv8z.js";import{ee as D0,he as b}from"./index-yy1mm8zs.js";var w0=typeof new Headers()?.toJSON==="function",R5=($)=>{if(w0)return Object.keys($.toJSON()).join(", ");let Z="",Q=0;return $.forEach((Y,X)=>{if(Q)Z=Z+", "+X;else Z=X;Q++}),Z},R0=($)=>{let{aot:Z=!0,origin:Q=!0,methods:Y=!0,allowedHeaders:X=!0,exposeHeaders:J=!0,credentials:W=!0,maxAge:H=5,preflight:V=!0}=$??{};if(Array.isArray(X))X=X.join(", ");if(Array.isArray(J))J=J.join(", ");let K=typeof Q==="boolean"?void 0:Array.isArray(Q)?Q:[Q],_=new D({name:"@elysiajs/cors",seed:$,aot:Z}),q=K?.some((L)=>L==="*"),C={};if(K){for(let L of K)if(typeof L==="string")C[L]=!0}let x=(L,T,O)=>{if(Array.isArray(L))return L.some((I)=>x(I,T,O));switch(typeof L){case"string":if(O in C)return!0;let I=O.indexOf("://");if(I!==-1)O=O.slice(I+3);return L===O;case"function":return L(T)===!0;case"object":if(L instanceof RegExp)return L.test(O)}return!1},B=(L,T)=>{if(Q===!0){L.headers.vary="*",L.headers["access-control-allow-origin"]=T.headers.get("Origin")||"*";return}if(q){L.headers.vary="*",L.headers["access-control-allow-origin"]="*";return}if(!K?.length)return;if(K.length){let O=T.headers.get("Origin")??"";for(let I=0;I<K.length;I++)if(x(K[I],T,O)===!0){L.headers.vary=Q?"Origin":"*",L.headers["access-control-allow-origin"]=O||"*";return}}L.headers.vary="Origin"},E=(L,T)=>{if(!T)return;if(Y===!0)return L.headers["access-control-allow-methods"]=T??"*";if(Y===!1||!Y?.length)return;if(Y==="*")return L.headers["access-control-allow-methods"]="*";if(!Array.isArray(Y))return L.headers["access-control-allow-methods"]=Y;L.headers["access-control-allow-methods"]=Y.join(", ")},w={};if(typeof J==="string")w["access-control-expose-headers"]=J;if(typeof X==="string")w["access-control-allow-headers"]=X;if(W===!0)w["access-control-allow-credentials"]="true";_.headers(w);function v({set:L,request:T,headers:O}){if(B(L,T),E(L,T.headers.get("access-control-request-method")),X===!0||J===!0){if(X===!0)L.headers["access-control-allow-headers"]=O["access-control-request-headers"];if(J===!0)L.headers["access-control-expose-headers"]=Object.keys(O).join(",")}if(H)L.headers["access-control-max-age"]=H.toString();return new Response(null,{status:204})}if(V)_.options("/",v).options("/*",v);return _.onRequest(function({set:T,request:O}){if(B(T,O),V&&O.method==="OPTIONS")return v({set:T,request:O,headers:w0?O.headers.toJSON():Object.fromEntries(O.headers.entries())});if(E(T,O.method),X===!0||J===!0){let I=R5(O.headers);if(X===!0)T.headers["access-control-allow-headers"]=I;if(J===!0)T.headers["access-control-expose-headers"]=I}})};import{createHash as k0}from"crypto";var W2="idempotency",A5=300000,A0=1e4,R2=new Map;function k5($,Z,Q,Y){return k0("sha256").update(`${$}|${Z}|${Q}|${Y}`).digest("hex")}async function S5($,Z){let Q=await $.getPluginState(W2,Z);if(!Q)return null;try{let Y=JSON.parse(Q);if(Y.expiresAt<Date.now())return await $.deletePluginState(W2,Z),null;return Y}catch{return null}}async function D5($,Z,Q){await $.setPluginState(W2,Z,JSON.stringify(Q))}async function h5($){let Z=await $.getAllPluginState(W2),Q=Date.now(),Y=0,X=[];for(let J of Z)try{if(JSON.parse(J.value).expiresAt<Q)await $.deletePluginState(W2,J.key),Y+=1;else X.push({key:J.key,updatedAt:J.updatedAt})}catch{await $.deletePluginState(W2,J.key),Y+=1}if(X.length>A0){X.sort((W,H)=>(W.updatedAt??"").localeCompare(H.updatedAt??""));let J=X.slice(0,X.length-A0);for(let W of J)await $.deletePluginState(W2,W.key),Y+=1}if(Y>0)G().logger.info("idempotency",`Swept ${Y} expired/over-cap entries`)}var e2=null,v5=600000;function P5($){if(e2)return;e2=setInterval(()=>{let Z=$.getDb();if(!Z)return;h5(Z).catch((Q)=>{G().logger.warn("idempotency","Sweep failed",{error:String(Q)})})},v5),e2.unref?.()}function S0($){return P5($),new D({name:"plugin/idempotency"}).onBeforeHandle(async({request:Z,path:Q,set:Y,store:X})=>{if(Z.method!=="POST"&&Z.method!=="PUT")return;let J=Z.headers.get("x-idempotency-key")??Z.headers.get("X-Idempotency-Key");if(!J)return;if(J.length<8||J.length>200)return Y.status=400,{error:"X-Idempotency-Key must be 8\u2013200 chars",code:"BAD_REQUEST"};let W=$.getDb();if(!W)return;let H="no-body";try{let E=await Z.clone().text();H=k0("sha256").update(E).digest("hex")}catch{}let V=k5(Z.method,Q,J,H),K=await S5(W,V);if(K){Y.status=K.status;let B=Y.headers??={};B["Content-Type"]=K.contentType,B["X-Idempotency-Replay"]="true",X.__idemReplay=K.body;try{return JSON.parse(K.body)}catch{return K.body}}let _=R2.get(V);if(_){let B=await _.catch(()=>null);if(B){Y.status=B.status;let E=Y.headers??={};E["Content-Type"]=B.contentType,E["X-Idempotency-Replay"]="true",X.__idemReplay=B.body;try{return JSON.parse(B.body)}catch{return B.body}}}let q,C,x=new Promise((B,E)=>{q=B,C=E});R2.set(V,x),X.__idemKey=V,X.__idemResolve=q,X.__idemReject=C}).onAfterHandle(async({response:Z,set:Q,store:Y})=>{let X=Y.__idemKey;if(!X)return;let J=Y.__idemResolve,W=$.getDb(),H=Q.status??200,V=typeof Z==="string"?Z:JSON.stringify(Z),_=Q.headers?.["Content-Type"]??"application/json",q={status:H,body:V,contentType:_,expiresAt:Date.now()+A5},C=H>=200&&H<300;try{if(W&&C)await D5(W,X,q)}catch(x){G().logger.warn("idempotency","Failed to persist response",{error:String(x)})}finally{try{J?.(C?q:null)}catch{}R2.delete(X)}}).onError(({store:Z})=>{let Q=Z.__idemKey;if(!Q)return;let Y=Z.__idemReject;try{Y?.(Error("idempotency: handler errored"))}catch{}R2.delete(Q)}).as("global")}import u from"os";import{readFileSync as s5}from"fs";import{join as r5}from"path";var h0={enabled:!1,async scrape(){return`# vibecontrols agent metrics disabled (OTel SDK not initialised)
|
|
3
|
-
`},recordHttpRequest(){},setPluginsLoaded(){}},J2=null,A2=null;async function k2($){if(J2)return J2;if(A2)return A2;return A2=(async()=>{try{let{MeterProvider:Z}=await import("./index-hrdamx5j.js").then((m)=>D0(m.default,1)),{PrometheusExporter:Q,PrometheusSerializer:Y}=await import("./index-1zw3kea7.js").then((m)=>D0(m.default,1)),X=new Q({preventServerStart:!0}),J=new Y,H=new Z({readers:[X]}).getMeter("vibecontrols-agent"),V=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((B)=>{B.observe(process.uptime())});let _=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((B)=>{for(let[E,w]of Object.entries(q))B.observe(w,{status:E})}),V.record(1,{version:$?.version??"unknown",profile:$?.profile??"default"});let x={enabled:!0,async scrape(){let B=await X.collect();if(!B.resourceMetrics)return"";return J.serialize(B.resourceMetrics)},recordHttpRequest(B,E,w){_.add(1,{method:B,route:E,status:String(w)})},setPluginsLoaded(B){q={...B}}};return J2=x,G().logger.info("metrics","OTel Prometheus registry initialised"),x}catch(Z){return G().logger.warn("metrics","Failed to initialise OTel metrics; /metrics will return a stub body",{error:Z instanceof Error?Z.message:String(Z)}),J2=h0,h0}})(),A2}function v0($,Z,Q){if(!J2)return;J2.recordHttpRequest($,Z,Q)}function P0($){if(!J2)return;J2.setPluginsLoaded($)}var f5=new Set(["127.0.0.1","::1"]),f0=!1;function b5(){if(f0)return;if(process.env.METRICS_ANONYMOUS_LOCALHOST==="true")f0=!0,G().logger.warn("metrics","METRICS_ANONYMOUS_LOCALHOST=true \u2014 /metrics is open to TCP loopback peers without an API key. Prefer issuing a scoped API key for your scraper.")}function y5($){let Z=$.replace(/^\[|\]$/g,"");if(Z.startsWith("::ffff:"))return Z.slice(7);return Z}function Q0($,Z){let Q=Z?.requestIP($)?.address;if(!Q)return!1;return f5.has(y5(Q))}function b0(){return b5(),new D({name:"routes/metrics"}).get("/metrics",async({request:$,server:Z,set:Q})=>{if(!(process.env.METRICS_ANONYMOUS_LOCALHOST==="true"&&Q0($,Z))){let W=m(Object.fromEntries($.headers.entries()));if(!l(W))return Q.status=401,Q.headers["content-type"]="application/json",JSON.stringify({error:"Unauthorized",message:"Invalid or missing API key"})}let J=await(await k2()).scrape();return Q.headers["content-type"]="text/plain; version=0.0.4; charset=utf-8",J})}import{randomBytes as c5,timingSafeEqual as u5}from"crypto";import{chmodSync as m5,existsSync as y0,mkdirSync as g5,readFileSync as p5,unlinkSync as l5,writeFileSync as d5}from"fs";import{dirname as n5,join as i5}from"path";var z2=null;function c0(){return i5(S2(),"pairing-token")}function o5(){return c5(32).toString("base64url")}function a5($,Z){let Q=Buffer.from($),Y=Buffer.from(Z);if(Q.length!==Y.length)return!1;try{return u5(Q,Y)}catch{return!1}}function X6(){if(z2)return z2;let $=c0();try{if(y0($)){let Q=p5($,"utf8").trim();if(Q.length>=32)return z2=Q,Q}}catch{}let Z=o5();try{g5(n5($),{recursive:!0}),d5($,Z,{encoding:"utf8"});try{m5($,384)}catch{}}catch(Q){}return z2=Z,Z}function $0($){if(!$)return!1;if(!z2)return!1;return a5($,z2)}function u0(){z2=null;try{let $=c0();if(y0($))l5($)}catch{}}function Z0($){return $["x-pairing-token"]??$["X-Pairing-Token"]??null}function t5(){let $=u.hostname(),Z=u.platform(),Q=u.arch(),Y=new Bun.CryptoHasher("sha256");return Y.update(`${$}-${Z}-${Q}`),Y.digest("hex").substring(0,16)}function e5(){for(let $ of["..","../.."])try{let Z=r5(import.meta.dir,$,"package.json"),Y=JSON.parse(s5(Z,"utf8")).version;if(Y)return Y}catch{}return"0.0.0"}async function QQ($){let Z=[],Q=$.getProvider("tunnel");if(Q)Z.push(Q);for(let Y of $.listProvidersForType("tunnel")){let X=$.getProviderByName("tunnel",Y.pluginName);if(X&&!Z.includes(X))Z.push(X)}for(let Y of Z){if(!Y.getActiveTunnelUrl)continue;let X=await Y.getActiveTunnelUrl();if(X)return X}return null}function n0({serviceRegistry:$,runFinalize:Z,getDb:Q}){let Y=e5(),X=t5();return new D({prefix:"/api/agent"}).get("/identity",()=>({hostname:u.hostname(),platform:u.platform(),architecture:u.arch(),agentVersion:Y,agentInstanceId:m0()})).get("/version",()=>({version:Y,runtime:"bun",runtimeVersion:typeof Bun<"u"?Bun.version:"unknown"})).get("/api-key",({request:J,server:W,set:H})=>{if(!Q0(J,W)){let K=m(Object.fromEntries(J.headers.entries()));if(!l(K))return H.status=401,{error:"Unauthorized",message:"Invalid or missing API key"}}return{apiKey:M2()}}).post("/iframe-token",({body:J,request:W,set:H})=>{let V=m(Object.fromEntries(W.headers.entries()));if(!l(V))return H.status=401,{error:"Unauthorized",message:"Invalid or missing API key"};try{if(Array.isArray(J.pathPrefixes)&&J.pathPrefixes.length>0)return p0({pathPrefixes:J.pathPrefixes,methods:J.methods},J.ttlSeconds??void 0);if(!J.pathPrefix)return H.status=400,{error:"BadRequest",message:"Provide either pathPrefix (string) or pathPrefixes (string[])"};return h2(J.pathPrefix,J.ttlSeconds??void 0)}catch(K){return H.status=400,{error:"BadRequest",message:K instanceof Error?K.message:String(K)}}},{body:z.Object({pathPrefix:z.Optional(z.String({minLength:1})),pathPrefixes:z.Optional(z.Array(z.String({minLength:1}),{minItems:1,maxItems:16})),methods:z.Optional(z.Array(z.String({minLength:1}),{minItems:1,maxItems:8})),ttlSeconds:z.Optional(z.Number())})}).post("/terminal-exchange",({body:J,set:W})=>{let{sid:H,token:V}=J;if(!H||!V)return W.status=400,{error:"BadRequest",message:"sid and token required"};if(!g0(H))return W.status=400,{error:"BadRequest",message:"invalid sid"};let K=`/terminal/${H}`,_=l0(V,K);if(!_.ok)return G().logger.warn("terminal-exchange","iframe token rejected",{sid:H,reason:_.reason}),W.status=401,{error:"Unauthorized",message:"invalid iframe token",code:_.reason==="expired"?"expired":_.reason==="replayed"?"replayed":"invalid"};let q=d0(H,600),C=`vt_term_${H}`;return W.headers["set-cookie"]=`${C}=${q.token}; HttpOnly; Secure; SameSite=None; Path=/terminal/${H}; Max-Age=600`,W.status=204,null},{body:z.Object({sid:z.String({minLength:1}),token:z.String({minLength:1})})}).post("/ui-exchange",({body:J,set:W})=>{let{plugin:H,token:V}=J;if(!H||!V)return W.status=400,{error:"BadRequest",message:"plugin and token required"};if(!O2(H))return W.status=400,{error:"BadRequest",message:"invalid plugin name"};let K=`/ui/${H}`;if(!J0(V,K))return W.status=401,{error:"Unauthorized",message:"invalid iframe token"};let _=X0(H,600),q=`vt_ui_${H}`;return W.headers["set-cookie"]=`${q}=${_.token}; HttpOnly; Secure; SameSite=None; Path=/ui/${H}/; Max-Age=600`,W.status=204,null},{body:z.Object({plugin:z.String({minLength:1}),token:z.String({minLength:1})})}).post("/ui-exchange-plugin",({body:J,set:W})=>{let{plugin:H,token:V}=J;if(!H||!V)return W.status=400,{error:"BadRequest",message:"plugin and token required"};if(!O2(H))return W.status=400,{error:"BadRequest",message:"invalid plugin name"};if(![`/api/plugins/${H}/ui`,`/${H}`].find((x)=>J0(V,x)))return W.status=401,{error:"Unauthorized",message:"invalid iframe token"};let q=X0(H,600),C=`vt_ui_${H}`;return W.headers["set-cookie"]=`${C}=${q.token}; HttpOnly; Secure; SameSite=None; Path=/api/plugins/${H}/ui/; Max-Age=600`,W.status=204,null},{body:z.Object({plugin:z.String({minLength:1}),token:z.String({minLength:1})})}).get("/system",({request:J,set:W})=>{let H=m(Object.fromEntries(J.headers.entries()));if(!l(H))return W.status=401,{error:"Unauthorized",message:"Invalid or missing API key"};return{machineId:X,hostname:u.hostname(),platform:u.platform(),arch:u.arch(),release:u.release(),cpus:u.cpus().length,totalMemory:u.totalmem(),freeMemory:u.freemem(),uptime:u.uptime(),bunVersion:typeof Bun<"u"?Bun.version:void 0,agentVersion:Y,homeDir:u.homedir(),cwd:process.cwd(),environment:"production"}}).get("/tunnel",async({request:J,set:W})=>{let H=Object.fromEntries(J.headers.entries()),V=l(m(H)),K=$0(Z0(H));if(!V&&!K)return W.status=401,{error:"Unauthorized",message:"Provide x-agent-api-key OR x-pairing-token to read tunnel URL"};let _=await QQ($);if(!_)return{tunnelUrl:null,message:"No tunnel provider registered"};return{tunnelUrl:_}}).get("/status",()=>{let J=["tunnel","session","ai"].filter((W)=>$.hasProvider(W));return{state:G().getBootState(),status:G().getBootState(),version:Y,providers:J,timestamp:new Date().toISOString()}}).get("/gateway-auth",()=>({configured:g.isConfigured(),config:v2(g.getConfig()),state:G().getBootState()})).post("/retry-config",async({set:J})=>{let{getFinalizeRetryHandle:W}=await import("./finalize-retry-handle-registry-vv241fsq.js"),H=W();if(!H)return J.status=409,{ok:!1,error:"No finalize retry worker is active. The agent either never had cached credentials to retry with, or it already reached the ready state."};let V=await H.forceRetryNow();if(!V.ok)J.status=503;return{ok:V.ok,error:V.ok?void 0:V.error,state:G().getBootState(),worker:H.getState()}}).post("/gateway-auth",async({body:J,request:W,set:H})=>{let V=G().getBootState(),K=Object.fromEntries(W.headers.entries());if(V==="ready"){let L=m(K);if(!l(L))return H.status=401,{success:!1,state:V,error:"Unauthorized: API key required to reconfigure"}}else{let L=m(K),T=Z0(K),O=l(L),I=$0(T);if(!O&&!I)return H.status=401,{success:!1,state:V,error:"Unauthorized: provide x-agent-api-key OR x-pairing-token for bootstrap"}}let{clientId:_,clientSecret:q,workspaceId:C,globalGatewayUrl:x,workspaceGatewayUrl:B}=J;if(!_||!q||!C||!x||!B)return H.status=400,{success:!1,state:G().getBootState(),error:"clientId, clientSecret, workspaceId, globalGatewayUrl, and workspaceGatewayUrl are required"};let E,w;try{E=V2(x,"globalGatewayUrl"),w=V2(B,"workspaceGatewayUrl")}catch(L){return H.status=400,{success:!1,state:G().getBootState(),error:L instanceof Error?L.message:String(L)}}{let L=y()??G();try{await D2({clientId:_,clientSecret:q,workspaceId:C,ownerUserId:J.ownerUserId,organizationId:J.organizationId,globalGatewayUrl:E,workspaceGatewayUrl:w,agentRecordId:J.agentRecordId,scopes:J.scopes,...J.storageAdapter?{storageAdapter:J.storageAdapter}:{},...J.storageOptions?{storageOptions:J.storageOptions}:{},...J.dbPath?{dbPath:J.dbPath}:{}},{dir:L.dataDir,scope:L.name})}catch(T){return H.status=500,{success:!1,state:G().getBootState(),error:`Failed to persist gateway credentials to secrets backend: ${T instanceof Error?T.message:String(T)}`}}}let v=G().getBootState();if(v==="ready"){let L=Q();if(L){if(await L.setConfig("gateway-auth:clientId",_),await L.setConfig("gateway-auth:clientSecret",q),await L.setConfig("gateway-auth:workspaceId",C),J.organizationId)await L.setConfig("gateway-auth:organizationId",J.organizationId);if(await L.setConfig("gateway-auth:globalGatewayUrl",E),await L.setConfig("gateway-auth:workspaceGatewayUrl",w),J.agentRecordId)await L.setConfig("gateway-auth:agentRecordId",J.agentRecordId)}g.configure({globalGatewayUrl:E,workspaceGatewayUrl:w,clientId:_,clientSecret:q,workspaceId:C,organizationId:J.organizationId}),G().logger.info("preconfig","Gateway credentials re-configured (agent was already ready)");let T=!!(J.storageAdapter||J.storageOptions||J.dbPath);return{success:!0,state:v,message:T?"Gateway auth re-configured. Restart the agent (vibe restart) to apply the new storage configuration.":"Gateway auth re-configured"}}return G().logger.info("preconfig","Gateway credentials received \u2014 beginning finalize (background)"),u0(),Z({clientId:_,clientSecret:q,workspaceId:C,organizationId:J.organizationId,globalGatewayUrl:E,workspaceGatewayUrl:w},{agentRecordId:J.agentRecordId,scopes:J.scopes}).catch((L)=>{G().logger.error("preconfig","Background finalize threw",{error:L instanceof Error?L.message:String(L)})}),H.status=202,{success:!0,state:G().getBootState(),agentRecordId:J.agentRecordId,message:"Gateway credentials accepted; finalize is running in the background. Poll /health/ready for completion."}},{body:z.Object({clientId:z.Optional(z.String()),clientSecret:z.Optional(z.String()),workspaceId:z.Optional(z.String()),ownerUserId:z.Optional(z.String()),organizationId:z.Optional(z.String()),globalGatewayUrl:z.Optional(z.String()),workspaceGatewayUrl:z.Optional(z.String()),scopes:z.Optional(z.Array(z.String())),agentRecordId:z.Optional(z.String()),storageAdapter:z.Optional(z.String()),storageOptions:z.Optional(z.Record(z.String(),z.String())),dbPath:z.Optional(z.String())})})}import{existsSync as $2,mkdirSync as $Q,rmSync as i0,readdirSync as t0}from"fs";import{join as y2}from"path";function a($){return y2(K2(),"agents",d($))}function ZQ(){let $=y2(K2(),"agents");if(!$2($))return[];return t0($,{withFileTypes:!0}).filter((Z)=>Z.isDirectory()).map((Z)=>Z.name).filter((Z)=>/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(Z))}function e0($){return y2(K2(),"agents",d($))}function W0($){return t({dir:e0($)})}function o0($,Z){return f2(Z,{dir:e0($),scope:d($)})}function B2($){let Z=P2(),Q=z0().find((J)=>J.name===$),Y=s.get($),X={name:$,isDefault:$===Z,isRunning:Q?.status==="running",attached:Y!==void 0,bootState:Y?Y.getBootState():null,dataDir:Y?Y.dataDir:null};if(Q)X.port=Q.port,X.pid=Q.pid,X.startTime=Q.startTime;if($2(a($)))X.config=v2(W0($));return X}function Q4($={}){let Z=$.serviceManagerFactory?$.serviceManagerFactory():new b2;return new D({prefix:"/api/profiles"}).get("/",()=>{let Q=ZQ(),Y=P2(),X=new Set(Q);return X.add(Y),[...X].sort().map((J)=>B2(J))}).post("/",async({body:Q,set:Y})=>{try{let X=d(Q.name),J=a(X);if($2(J))return Y.status=409,{error:"exists",message:`Profile '${X}' already exists.`};let W;if(Q.copyFrom){let H=d(Q.copyFrom);if(!$2(a(H)))return Y.status=400,{error:"copy-source-missing",message:`Profile '${H}' does not exist.`};W=W0(H),delete W["static-api-key"],delete W.agentRecordId,delete W.apiKeys}else W=r0();if(Q.gatewayUrl)W.globalGatewayUrl=Q.gatewayUrl;if(Q.workspaceGatewayUrl)W.workspaceGatewayUrl=Q.workspaceGatewayUrl;if(Q.clientId)W.clientId=Q.clientId;if(Q.clientSecret)W.clientSecret=Q.clientSecret;if(Q.workspaceId)W.workspaceId=Q.workspaceId;if(Q.organizationId)W.organizationId=Q.organizationId;$Q(J,{recursive:!0}),o0(X,W);try{Y0(X)}catch(H){G().logger.warn("profile-mgmt",`In-process attach failed for '${X}'`,{error:String(H)})}if(G().logger.info("profile-mgmt",`Created profile '${X}' at ${J}`),Q.start){let H={name:X,port:Q.port??0,daemon:!0,dbPath:T2(),profile:X};await Z.startDaemon(H)}return Y.status=201,B2(X)}catch(X){return Y.status=400,{error:"create-failed",message:X instanceof Error?X.message:String(X)}}},{body:z.Object({name:z.String(),gatewayUrl:z.Optional(z.String()),workspaceGatewayUrl:z.Optional(z.String()),clientId:z.Optional(z.String()),clientSecret:z.Optional(z.String()),workspaceId:z.Optional(z.String()),organizationId:z.Optional(z.String()),copyFrom:z.Optional(z.String()),start:z.Optional(z.Boolean()),port:z.Optional(z.Number())})}).get("/:name",({params:Q,set:Y})=>{try{let X=d(Q.name);if(!$2(a(X)))return Y.status=404,{error:"not-found",message:`No profile '${X}'.`};return B2(X)}catch(X){return Y.status=400,{error:"bad-request",message:X instanceof Error?X.message:String(X)}}},{params:z.Object({name:z.String()})}).put("/:name",({params:Q,body:Y,set:X})=>{try{let J=d(Q.name);if(!$2(a(J)))return X.status=404,{error:"not-found",message:`No profile '${J}'.`};let W=["static-api-key","apiKeys","agentRecordId"];for(let K of W)if(K in Y)return X.status=400,{error:"forbidden-field",message:`Field '${K}' is managed via dedicated commands (vibe key rotate / vibe profile create). It cannot be patched here.`};if("registry"in Y)return X.status=400,{error:"forbidden-field",message:"Field 'registry' cannot be patched via this endpoint. Use POST /api/agent/registry with operator confirmation (VIBE_ALLOW_REGISTRY_CHANGE=1) so the change is auditable."};let V={...W0(J),...Y};return o0(J,V),B2(J)}catch(J){return X.status=400,{error:"update-failed",message:J instanceof Error?J.message:String(J)}}},{params:z.Object({name:z.String()}),body:z.Record(z.String(),z.Any())}).delete("/:name",async({params:Q,body:Y,query:X,set:J})=>{try{let W=d(Q.name);if(W===P2())return J.status=409,{error:"is-default",message:`Cannot delete active default profile '${W}'. Switch to another profile first.`};let H=X?.purge==="true"||X?.purge==="1",V=$2(a(W)),K=s.has(W);if(!V&&!K)return J.status=404,{error:"not-found",message:`No profile '${W}'.`};if(V&&!H&&!Y?.confirm)return J.status=400,{error:"confirm-required",message:"Pass { confirm: true } in the body or `?purge=true` in the query to delete the on-disk dataDir (destructive)."};try{await Z.stop(W)}catch{}try{await s.destroy(W)}catch(_){G().logger.warn("profile-mgmt",`In-process detach failed for '${W}'`,{error:String(_)})}if(V)if(Y?.keepConfig)for(let _ of t0(a(W))){if(_==="config.json")continue;i0(y2(a(W),_),{recursive:!0,force:!0})}else i0(a(W),{recursive:!0,force:!0});return G().logger.info("profile-mgmt",`Deleted profile '${W}'`),{ok:!0,deleted:W,keptConfig:!!Y?.keepConfig,detached:K,purged:V}}catch(W){return J.status=400,{error:"delete-failed",message:W instanceof Error?W.message:String(W)}}},{params:z.Object({name:z.String()}),query:z.Optional(z.Object({purge:z.Optional(z.String())})),body:z.Optional(z.Object({confirm:z.Optional(z.Boolean()),keepConfig:z.Optional(z.Boolean())}))}).post("/:name/switch",async({params:Q,set:Y})=>{try{let X=d(Q.name);if(!$2(a(X)))return Y.status=404,{error:"not-found",message:`No profile '${X}'.`};return await a0(()=>s0(X)),G().logger.info("profile-mgmt",`Default profile switched to '${X}'`),{ok:!0,defaultProfile:X}}catch(X){return Y.status=400,{error:"switch-failed",message:X instanceof Error?X.message:String(X)}}},{params:z.Object({name:z.String()})}).post("/:name/start",async({params:Q,body:Y,set:X})=>{try{let J=d(Q.name);if(!$2(a(J)))return X.status=404,{error:"not-found",message:`No profile '${J}'.`};try{Y0(J)}catch(H){G().logger.warn("profile-mgmt",`In-process attach failed for '${J}'`,{error:String(H)})}if(!z0().some((H)=>H.name===J&&H.status==="running")){let H={name:J,port:Y?.port??0,daemon:!0,dbPath:T2(),profile:J};await Z.startDaemon(H)}return B2(J)}catch(J){return X.status=500,{error:"start-failed",message:J instanceof Error?J.message:String(J)}}},{params:z.Object({name:z.String()}),body:z.Optional(z.Object({port:z.Optional(z.Number())}))}).post("/:name/stop",async({params:Q,set:Y})=>{try{let X=d(Q.name);try{await Z.stop(X)}catch{}try{await s.destroy(X)}catch(J){G().logger.warn("profile-mgmt",`In-process detach failed for '${X}'`,{error:String(J)})}return B2(X)}catch(X){return Y.status=500,{error:"stop-failed",message:X instanceof Error?X.message:String(X)}}},{params:z.Object({name:z.String()})})}function JQ(){let $=process.memoryUsage(),Z=process.resourceUsage(),Q=Z.userCPUTime/1000,Y=Z.systemCPUTime/1000,X=Q+Y,J=s.list().map((W)=>{let H;try{H=$4(W.spawnOwnerKey).length}catch{H=0}return{name:W.name,status:W.getBootState(),childPidCount:H,cpuMs:X,heapBytes:$.heapUsed,dataDir:W.dataDir}});return{process:{pid:process.pid,uptimeSeconds:process.uptime(),cpuUserMs:Q,cpuSystemMs:Y,heapUsedBytes:$.heapUsed,heapTotalBytes:$.heapTotal,rssBytes:$.rss},profiles:J,notes:{perProfileCpu:"deferred",perProfileHeap:"deferred"}}}function Z4(){return new D({prefix:"/api/profile-stats"}).get("/",()=>JQ())}function c2($,Z){return Promise.race([$,new Promise((Q,Y)=>setTimeout(()=>Y(Error(`timeout after ${Z}ms`)),Z))])}function XQ($){let Z=$ instanceof Error?$.message:String($);return/ENOENT/.test(Z)||/no such file or directory/i.test(Z)}async function J4($){let Q=`__health__:probe:${typeof crypto<"u"&&typeof crypto.randomUUID==="function"?crypto.randomUUID():`${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`}`,Y=String(Date.now());if(await c2($.setConfig(Q,Y),2000),await c2($.getConfig(Q),2000)!==Y)throw Error("round-trip mismatch");try{await c2($.deleteConfig(Q),500)}catch{}}async function YQ($,Z){if(!$)return{ok:!1,message:"database not opened"};let Q=performance.now();try{return await J4($),{ok:!0,durationMs:performance.now()-Q}}catch(Y){if(Z&&XQ(Y))try{return(await import("fs")).mkdirSync(Z,{recursive:!0}),await J4($),{ok:!0,message:`recovered: dbPath ${Z} was missing \u2014 recreated`,durationMs:performance.now()-Q}}catch(X){return{ok:!1,message:`ENOENT on dbPath ${Z}: ${X instanceof Error?X.message:String(X)}`,durationMs:performance.now()-Q}}return{ok:!1,message:Y instanceof Error?Y.message:String(Y),durationMs:performance.now()-Q}}}function X4($,Z){if(!$)return{ok:!1,message:"no service registry"};let Y=G().getBootState()==="awaiting-config";if(Z==="tunnel"){let X=$.getProvider("tunnel");if(!X&&process.env.AGENT_TUNNEL==="false")return{ok:!0,message:"tunnel disabled via AGENT_TUNNEL=false"};if(X)return{ok:!0,message:`provider: ${X.name}`};return{ok:!1,message:Y?"agent is awaiting-config \u2014 POST OAuth credentials to /api/agent/gateway-auth to register tunnel provider":"no tunnel provider registered"}}if(Z==="session"){let X=$.getProvider("session");if(X)return{ok:!0,message:`provider: ${X.name}`};return{ok:!1,message:Y?"agent is awaiting-config \u2014 POST OAuth credentials to /api/agent/gateway-auth to register session provider":"no session provider registered"}}return{ok:!0}}async function WQ($){if(!$)return{};let Z={};for(let Q of $.getAllPlugins()){let Y=Q.getHealth;if(typeof Y!=="function")continue;let X=performance.now();try{let J=await c2(Promise.resolve(Y.call(Q)),2000);Z[Q.name]={ok:J?.ok!==!1,message:J?.message,durationMs:performance.now()-X}}catch(J){Z[Q.name]={ok:!1,message:J instanceof Error?J.message:String(J),durationMs:performance.now()-X}}}return Z}function Y4($){let Z=$&&"serviceRegistry"in $?$:{serviceRegistry:$};return new D({prefix:"/health"}).get("/",()=>{return{status:"ok",lifecycleState:Z.serviceRegistry?.getService("agent","lifecycle")?.getState()??"running",bootState:G().getBootState(),timestamp:new Date().toISOString(),uptime:process.uptime()}}).get("/live",()=>({status:"ok"})).get("/ready",async({set:Q})=>{let X=Z.serviceRegistry?.getService("agent","lifecycle")?.getState()??"running",J=G().getBootState(),W={};W.boot={ok:J==="ready",message:J==="ready"?void 0:`boot state ${J}`},W.lifecycle={ok:X==="running",message:X==="running"?void 0:`lifecycle ${X}`},W.db=await YQ(Z.getDb?.()??null,Z.getDbPath?.()??null),W.tunnel=X4(Z.serviceRegistry,"tunnel"),W.session=X4(Z.serviceRegistry,"session");try{let{gatewayClient:B}=await import("./gateway-client-43gzvj5s.js");if(!B.isConfigured())W.registration={ok:!0,message:"not configured"};else{let E=Z.getDb?.()??null;if(E?await E.getConfig("gateway-auth:agentRecordId"):null)W.registration={ok:!0};else{let v=G().getDegradedReasons().some((L)=>L.plugin==="agent-registration");W.registration=v?{ok:!1,message:"agent failed to register with the workspace after retries"}:{ok:!0,message:"registering"}}}}catch(B){W.registration={ok:!0,message:`registration check skipped: ${B instanceof Error?B.message:String(B)}`}}let H=await WQ(Z.getPluginManager?.()??null),V=Object.values(W).every((B)=>B.ok)&&Object.values(H).every((B)=>B.ok);if(!V)Q.status=503;let K=J==="degraded"?G().getDegradedReasons():[],_=G().name,q={};for(let B of s.list())q[B.name]={bootState:B.getBootState(),ok:B.getBootState()==="ready",degradedReasons:B.getDegradedReasons()};let C=G().getLastFinalizeError(),x={status:V?"ok":"degraded",lifecycleState:X,bootState:J,daemon:{profile:_,bootState:J,ok:J==="ready"},profiles:q,components:W,plugins:H,degradedReasons:K,lastFinalizeError:C,timestamp:new Date().toISOString()};if(!V)G().logger.warn("health","Readiness probe failed",{components:W,plugins:H,bootState:J});return x})}var u2=0,W4=0;function z4(){return new D({name:"inflight-tracker"}).onRequest(()=>{u2+=1}).onAfterResponse(()=>{u2=Math.max(0,u2-1),W4+=1})}function H4(){return new D({prefix:"/api/stats"}).get("/inflight",()=>({inflight:Math.max(0,u2-1),totalServed:W4}))}var H0=Object.freeze(["code","code-insiders","codium","cursor","idea","pycharm","webstorm","goland","phpstorm","rubymine","clion","rider","zed","subl","vim","nvim","emacs","neovide","fleet","helix"]),zQ=new Set(H0),HQ=new Set(["--new-window","-n","--reuse-window","-r","--wait","-w","--add","--goto"]);function G4($){try{return Bun.which($)??null}catch{return null}}function K4(){return new D({prefix:"/api/editor"}).get("/allowlist",()=>({commands:[...H0]})).get("/detect",async()=>{let $=H0.map((Y)=>[Y,G4(Y)]),Z=[],Q={};for(let[Y,X]of $)if(X)Z.push(Y),Q[Y]=X;return{available:Z,paths:Q}}).post("/open",async({body:$,set:Z})=>{let{command:Q,path:Y,args:X=[]}=$;if(!zQ.has(Q))return Z.status=400,{ok:!1,error:`Command '${Q}' is not in the IDE allowlist`};for(let H of X)if(typeof H!=="string"||!HQ.has(H))return Z.status=400,{ok:!1,error:`Argument '${H}' is not in the flag allowlist`};let J;try{J=(await V4(Y,{mustExist:!0})).realPath}catch(H){return Z.status=400,{ok:!1,error:`Invalid path: ${H instanceof Error?H.message:String(H)}`}}let W=G4(Q);if(!W)return Z.status=404,{ok:!1,error:`'${Q}' is not installed or not on PATH on this agent`};try{let H=B4({owner:`editor:${Q}`,cmd:[W,...X,J],env:process.env,stdout:"ignore",stderr:"ignore",stdin:"ignore",meta:{command:Q,path:J}});return G().logger.info("editor",`Launched ${Q} on ${J}`,{pid:H.pid}),G().audit.emit("agent","editor.open",{command:Q,path:J,pid:H.pid}),{ok:!0,command:Q,resolvedPath:J,pid:H.pid}}catch(H){return Z.status=500,{ok:!1,error:`Failed to spawn editor: ${H instanceof Error?H.message:String(H)}`}}},{body:z.Object({command:z.String({minLength:1,maxLength:40}),path:z.String({minLength:1,maxLength:4096}),args:z.Optional(z.Array(z.String({maxLength:32})))})})}var F4=Symbol.for("@vibecontrols/plugin-sdk:contextProviders@1");function GQ(){let $=globalThis,Z=$[F4];if(Z)return Z;let Q=new Map;return $[F4]=Q,Q}function G0(){return Array.from(GQ().values())}function _4(){return(y()??G()).dataDir}function n(){let $=t({dir:_4()});return{ownerUserId:$.ownerUserId,workspaceId:$.workspaceId}}function m2(){return t({dir:_4()}).agentRecordId}function L4($){if(!$)return null;try{return new URL($).host}catch{return null}}async function N4($,Z){let Q=$.getPluginManager(),Y=Q?Q.getPluginDetails().map((H)=>({pluginName:H.pluginName,packageName:H.packageName,version:H.version,tags:H.tags??[]})):[],X=process.memoryUsage(),J=L4($.getTunnelHost?.()??null),W;try{W=F2(n()).map((H)=>({id:H.id,label:H.label,host:L4(H.tunnelUrl),agentRecordId:H.agentRecordId??null,permissions:H.permissions,canForward:H.permissions.includes("mesh:forward"),lastReachable:H.lastReachable??null}))}catch{W=[]}return{pluginName:"agent",description:"vibecontrols-agent runtime self-report",generatedAt:new Date().toISOString(),data:{profile:Z.profile,vibeId:Z.vibeId??null,runtime:{bunVersion:typeof Bun<"u"?Bun.version:null,nodeVersion:process.versions.node??null,platform:process.platform,arch:process.arch,pid:process.pid,uptimeSeconds:Math.round(process.uptime()),memory:{rssMB:Math.round(X.rss/1048576),heapUsedMB:Math.round(X.heapUsed/1048576)}},agent:{version:$.getAgentVersion?.()??null,profileRegistered:E2(),tunnelHost:J},plugins:{count:Y.length,items:Y},mesh:{peerCount:W.length,peers:W}}}}var VQ=2000,j4=1000;async function BQ($,Z){let Q,Y=new Promise((X,J)=>{Q=setTimeout(()=>J(Error(`timeout after ${Z}ms`)),Z)});try{return await Promise.race([$,Y])}finally{if(Q)clearTimeout(Q)}}async function U4($,Z){let Q=performance.now(),Y=$.timeoutMs??VQ;try{let X=await BQ($.getContext(Z),Y);if(!X.generatedAt)X.generatedAt=new Date().toISOString();return{ok:!0,data:X,durationMs:Math.round(performance.now()-Q)}}catch(X){return{ok:!1,error:X.message??String(X),durationMs:Math.round(performance.now()-Q)}}}class V0{deps;inflight=new Map;constructor($){this.deps=$}async aggregate($){let Z=`${$.profile}::${$.vibeId??""}`,Q=this.inflight.get(Z);if(Q&&Date.now()-Q.ts<j4)return Q.promise;let Y=this.doAggregate($).finally(()=>{setTimeout(()=>{let X=this.inflight.get(Z);if(X&&X.promise===Y)this.inflight.delete(Z)},j4).unref?.()});return this.inflight.set(Z,{ts:Date.now(),promise:Y}),Y}async selfContext($){return N4(this.deps,$)}async pluginContext($,Z){let Q=G0().find((Y)=>Y.name===$);if(!Q)return null;return U4(Q,Z)}async pluginsContext($){let Z=G0(),Q=await Promise.allSettled(Z.map((X)=>U4(X,$))),Y={};return Z.forEach((X,J)=>{let W=Q[J];if(W&&W.status==="fulfilled")Y[X.name]=W.value;else if(W&&W.status==="rejected")Y[X.name]={ok:!1,error:W.reason instanceof Error?W.reason.message:String(W.reason),durationMs:0}}),Y}async doAggregate($){let[Z,Q]=await Promise.all([this.selfContext($),this.pluginsContext($)]);return{agent:Z,plugins:Q}}}function g2($){let Z=$.vibeId;if(typeof Z!=="string")return;let Q=Z.trim();return Q.length>0&&Q.length<=128?Q:void 0}function x4($){let Z=new V0($);return new D({prefix:"/api/agent/context"}).get("/",async({params:Q,query:Y})=>{let X=Q?.profile??"default",J=g2(Y);return Z.aggregate({profile:X,vibeId:J})},{query:z.Object({vibeId:z.Optional(z.String())})}).get("/agent",async({params:Q,query:Y})=>{let X=Q?.profile??"default",J=g2(Y);return Z.selfContext({profile:X,vibeId:J})},{query:z.Object({vibeId:z.Optional(z.String())})}).get("/plugins",async({params:Q,query:Y})=>{let X=Q?.profile??"default",J=g2(Y);return Z.pluginsContext({profile:X,vibeId:J})},{query:z.Object({vibeId:z.Optional(z.String())})}).get("/plugins/:name",async({params:Q,query:Y,set:X})=>{let J=Q?.profile??"default",W=Q?.name;if(!W)return X.status=400,{error:"missing plugin name"};let H=g2(Y),V=await Z.pluginContext(W,{profile:J,vibeId:H});if(!V)return X.status=404,{error:`no context provider registered under name "${W}"`};return V},{params:z.Object({name:z.String()}),query:z.Object({vibeId:z.Optional(z.String())})})}var Z2="autoupdate",KQ=86400000,O4=300000,FQ=900000,S={timer:null,running:!1,profile:"default",lastCheckAt:null,lastCheck:null,lastUpdateAt:null,lastUpdate:null,startedAt:null};function B0(){let $=(process.env.VIBE_AUTOUPDATE??"").trim().toLowerCase();return $==="0"||$==="false"||$==="off"||$==="no"}function T4(){if(B0())return!1;try{return t().autoUpdate!==!1}catch{return!0}}function K0(){let $=Number(process.env.VIBE_AUTOUPDATE_INTERVAL_MS);if(Number.isFinite($)&&$>0)return Math.max(FQ,$);return KQ}async function F0($){let Z=G().logger;if(S.running)return{check:S.lastCheck??await M4(),update:null};S.running=!0;try{let Q=await C2();if(S.lastCheck=Q,S.lastCheckAt=new Date().toISOString(),Q.error)Z.debug(Z2,`Update check failed: ${Q.error}`);else if(Q.hasUpdate)Z.info(Z2,`New agent version available: ${Q.current} \u2192 ${Q.latest}`);let Y=$?.force||T4();if(!Q.hasUpdate||!Y)return{check:Q,update:null};Z.info(Z2,`Auto-updating ${Q.current} \u2192 ${Q.latest} (idle-gated restart)\u2026`);let X=await p2({restart:!0,name:S.profile,onLog:(J)=>Z.info(Z2,J)});if(S.lastUpdate=X,S.lastUpdateAt=new Date().toISOString(),X.ok&&X.updated)Z.info(Z2,`Auto-update applied: now ${X.current} (restart: ${X.restart}).`);else if(!X.ok)Z.warn(Z2,`Auto-update failed: ${X.error}`);return{check:Q,update:X}}catch(Q){return Z.warn(Z2,`Auto-update tick threw: ${Q instanceof Error?Q.message:String(Q)}`),{check:await M4(),update:null}}finally{S.running=!1}}async function M4(){if(S.lastCheck)return S.lastCheck;let $=await C2();return S.lastCheck=$,S.lastCheckAt=new Date().toISOString(),$}function E4($){if(S.timer)clearTimeout(S.timer);S.timer=setTimeout(()=>{F0().finally(()=>{if(S.startedAt)E4(K0())})},$),S.timer.unref?.()}function _Q($){let Z=G().logger;if(S.profile=$?.profile||process.env.VIBECONTROLS_PROFILE||"default",S.startedAt=new Date().toISOString(),B0()){Z.info(Z2,"Autoupdate disabled via VIBE_AUTOUPDATE \u2014 not scheduling.");return}Z.info(Z2,`Autoupdate scheduled (first check in ${Math.round(O4/60000)}m, then every ${Math.round(K0()/3600000)}h).`),E4(O4)}function V7(){if(S.timer)clearTimeout(S.timer),S.timer=null;S.startedAt=null}function C4($){if(f2({autoUpdate:$}),$&&!S.startedAt)_Q({profile:S.profile})}function _0(){let $=!0;try{$=t().autoUpdate!==!1}catch{}return{enabled:T4(),envKillSwitch:B0(),configEnabled:$,scheduled:!!S.startedAt,intervalMs:K0(),profile:S.profile,startedAt:S.startedAt,lastCheckAt:S.lastCheckAt,lastCheck:S.lastCheck,lastUpdateAt:S.lastUpdateAt,lastUpdate:S.lastUpdate}}import{existsSync as I4}from"fs";import{join as q4}from"path";var LQ=600000,L0=1e6;function NQ(){let $=_2(),Z=$.which("bun")??`bun${$.executableSuffix}`,Q=q4(import.meta.dir,"cli.js");if(I4(Q))return{runner:Z,prefix:[Q]};let Y=q4(import.meta.dir,"..","cli.ts");if(I4(Y))return{runner:Z,prefix:[Y]};let X=$.which("vibe");if(X)return{runner:X,prefix:[]};return null}function w4($){if($.length<=L0)return $;return $.slice(0,L0)+`
|
|
4
|
-
\u2026[output truncated at ${L0} bytes]`}async function l2($,Z={}){let Q=NQ();if(!Q)return{ok:!1,exitCode:null,stdout:"",stderr:"Could not locate the vibe CLI to execute (no dist/cli.js, source, or PATH entry).",timedOut:!1,argv:$,command:"(unresolved)"};let Y=[...Q.prefix,...$],X=[Q.runner,...Y].join(" ");try{let J=Bun.spawn([Q.runner,...Y],{cwd:Z.cwd,env:{...process.env,VIBE_AUTO_ACCEPT:"1",CI:"1",NO_COLOR:"1",...Z.env},stdout:"pipe",stderr:"pipe"}),W=Z.timeoutMs??LQ,H=!1,V=setTimeout(()=>{H=!0;try{J.kill()}catch{}},W),[K,_,q]=await Promise.all([new Response(J.stdout).text(),new Response(J.stderr).text(),J.exited]);return clearTimeout(V),{ok:!H&&q===0,exitCode:q,stdout:w4(K),stderr:w4(_),timedOut:H,argv:$,command:X}}catch(J){return{ok:!1,exitCode:null,stdout:"",stderr:`Failed to spawn vibe CLI: ${J instanceof Error?J.message:String(J)}`,timedOut:!1,argv:$,command:X}}}async function R4(){let{Command:$}=await import("./esm-9fpye77x.js"),{registerCoreCommands:Z}=await import("./register-core-xhrk6ay5.js"),Q=new $;Q.name("vibe").option("--json").option("--plain").option("-y, --yes").option("-p, --profile <name>");try{Z(Q)}catch{}let Y=new Set(["nuke","kill","gc","stop","rollback","deploy"]),X=[];for(let J of Q.commands){let W=J.name();if(!W||W==="help")continue;X.push({name:W,description:J.description()||"",usage:J.usage()||"",options:J.options.map((H)=>({flags:H.flags,description:H.description||""})),group:"core",destructive:Y.has(W)})}return X.sort((J,W)=>J.name.localeCompare(W.name))}import{spawn as jQ}from"child_process";import{writeFileSync as UQ,mkdirSync as xQ}from"fs";import{tmpdir as OQ}from"os";import{join as A4}from"path";var MQ="@vibecontrols/agent";function k4($){let Z=_2(),Q=Z.which("bun")??`bun${Z.executableSuffix}`,Y=Z.which("npm")??`npm${Z.executableSuffix}`,X=d2(),J=$.delayMs??3000,W=$.pids.filter((V)=>Number.isInteger(V)&&V>0),H=`// vibecontrols agent self-uninstall reaper (auto-generated)
|
|
5
|
-
const PIDS = ${JSON.stringify(W)};
|
|
6
|
-
const NPM = ${JSON.stringify(Y)};
|
|
7
|
-
const BUN = ${JSON.stringify(Q)};
|
|
8
|
-
const REGISTRY = ${JSON.stringify(X)};
|
|
9
|
-
const PKG = ${JSON.stringify(MQ)};
|
|
10
|
-
await Bun.sleep(${J});
|
|
11
|
-
for (const pid of PIDS) {
|
|
12
|
-
try { process.kill(pid, "SIGTERM"); } catch {}
|
|
13
|
-
}
|
|
14
|
-
await Bun.sleep(2500);
|
|
15
|
-
for (const pid of PIDS) {
|
|
16
|
-
try { process.kill(pid, "SIGKILL"); } catch {}
|
|
17
|
-
}
|
|
18
|
-
try { Bun.spawnSync([NPM, "uninstall", "-g", PKG, "--registry=" + REGISTRY], { stdout: "inherit", stderr: "inherit" }); } catch {}
|
|
19
|
-
try { Bun.spawnSync([BUN, "remove", "-g", PKG], { stdout: "inherit", stderr: "inherit" }); } catch {}
|
|
20
|
-
`;try{let V=A4(OQ(),"vibecontrols-uninstall");xQ(V,{recursive:!0});let K=A4(V,`reaper-${process.pid}.ts`);return UQ(K,H,{encoding:"utf8"}),jQ(Q,[K],{detached:!0,stdio:"ignore",windowsHide:!0}).unref(),G().logger.info("self-uninstall",`Scheduled detached uninstall reaper (pids=${W.join(",")}) at ${K}`),{ok:!0,scriptPath:K}}catch(V){return{ok:!1,scriptPath:null,error:V instanceof Error?V.message:String(V)}}}var TQ=new Set(["db","plugins-registry","logs","binaries","subprocs"]);async function S4($){let Z=await R4();try{let Q=$.getPluginManager?.();if(Q){let Y=new Set(Z.map((X)=>X.name));for(let X of Q.getPluginDetails()){let J=X.cliCommand;if(J&&!Y.has(J))Y.add(J),Z.push({name:J,description:X.description||`${X.pluginName} plugin command`,usage:"",options:[],group:"plugin",destructive:!1})}}}catch{}return Z.sort((Q,Y)=>Q.name.localeCompare(Y.name))}function D4($={}){return new D({name:"agent-maintenance"}).get("/api/agent/update/check",async()=>{return await C2()}).get("/api/agent/update/status",()=>{return _0()}).post("/api/agent/update",async({body:Z})=>{return await p2({targetVersion:typeof Z?.version==="string"?Z.version:void 0,allowIncompatible:Z?.allowIncompatible===!0,restart:Z?.restart!==!1})},{body:z.Optional(z.Object({version:z.Optional(z.String()),allowIncompatible:z.Optional(z.Boolean()),restart:z.Optional(z.Boolean())}))}).post("/api/agent/update/config",({body:Z})=>{return C4(Z.enabled),{ok:!0,status:_0()}},{body:z.Object({enabled:z.Boolean()})}).post("/api/agent/update/check-now",async({body:Z})=>{return{ok:!0,...await F0({force:Z?.force===!0})}},{body:z.Optional(z.Object({force:z.Optional(z.Boolean())}))}).get("/api/agent/commands",async()=>{let Z=await S4($);return{commands:Z,count:Z.length}}).post("/api/agent/commands/run",async({body:Z,set:Q})=>{let Y=Array.isArray(Z?.argv)?Z.argv.filter((V)=>typeof V==="string"):[];if(Y.length===0)return Q.status=400,{ok:!1,error:"argv must be a non-empty string array"};let X=Y[0],J=await S4($),W=new Set(J.map((V)=>V.name));if(!W.has(X))return Q.status=400,{ok:!1,error:`Unknown or disallowed command: "${X}"`,allowed:[...W].sort()};return await l2(Y,{timeoutMs:typeof Z?.timeoutMs==="number"?Z.timeoutMs:void 0})},{body:z.Object({argv:z.Array(z.String()),timeoutMs:z.Optional(z.Number())})}).post("/api/agent/nuke",async({body:Z,set:Q})=>{let Y=["nuke"];if(Z?.all)Y.push("--all");if(Z?.removeConfig)Y.push("--remove-config");if(Z?.dryRun)Y.push("--dry-run");if(typeof Z?.removePlugins==="string"&&Z.removePlugins)Y.push("--remove-plugins",Z.removePlugins);if(typeof Z?.keep==="string"&&Z.keep){let W=Z.keep.split(",").map((H)=>H.trim()).filter((H)=>H&&!TQ.has(H));if(W.length>0)return Q.status=400,{ok:!1,error:`Invalid --keep value(s): ${W.join(", ")}`};Y.push("--keep",Z.keep)}Y.push("-y","--json");let X=await l2(Y),J=null;try{let W=X.stdout.trim().split(`
|
|
21
|
-
`).reverse().find((H)=>H.trim().startsWith("{"));if(W)J=JSON.parse(W)}catch{}return{...X,parsed:J}},{body:z.Optional(z.Object({all:z.Optional(z.Boolean()),removeConfig:z.Optional(z.Boolean()),removePlugins:z.Optional(z.String()),keep:z.Optional(z.String()),dryRun:z.Optional(z.Boolean())}))}).post("/api/agent/uninstall",async({body:Z})=>{let Q=Z?.dryRun===!0,Y=["nuke","--all","--remove-config","-y","--json"];if(Q)Y.push("--dry-run");let X=await l2(Y);if(Q)return{ok:X.ok,dryRun:!0,nuke:X,note:"Dry run \u2014 would nuke all state and uninstall @vibecontrols/agent."};let J=new Set([process.pid]);try{let H=new b2;for(let V of await H.listInstances())if(typeof V.pid==="number"&&V.pid>0)J.add(V.pid)}catch{}let W=k4({pids:[...J]});return{ok:X.ok&&W.ok,nuke:X,uninstallScheduled:W.ok,scriptPath:W.scriptPath,...W.error?{error:W.error}:{},note:"Agent state nuked; package self-uninstall scheduled \u2014 the daemon will stop and `@vibecontrols/agent` will be removed shortly."}},{body:z.Optional(z.Object({dryRun:z.Optional(z.Boolean())}))})}import{existsSync as wQ,readFileSync as RQ}from"fs";import{join as AQ}from"path";var EQ=`mutation AddAgentFromTunnel($input: AddAgentFromTunnelInput!) {
|
|
22
|
-
addVibecontrolsAgentFromTunnel(input: $input) { agent { id name } clientId success error }
|
|
23
|
-
}`,CQ=`mutation ReportAgentMeshLink($input: ReportAgentMeshLinkInput!) {
|
|
24
|
-
reportAgentMeshLink(input: $input) { id }
|
|
25
|
-
}`,h4="VIBE_BOOTSTRAP_JSON=";function IQ($){for(let Y of $.split(/\r?\n/)){let X=Y.indexOf(h4);if(X>=0)try{return JSON.parse(Y.slice(X+h4.length))}catch{}}let Z=$.indexOf("{"),Q=$.lastIndexOf("}");if(Z>=0&&Q>Z)try{return JSON.parse($.slice(Z,Q+1))}catch{return null}return null}async function f4($,Z){let Q=(_,q,C)=>Z?.({step:_,status:q,message:C}),Y=P4($.permissions??["tunnel:read","session:list","plugin:list","diagnostics:read","mesh:forward"]);if(!Y.includes("mesh:forward"))Y.push("mesh:forward");let X=(_)=>({ok:!1,peerId:"",agentRecordId:null,tunnelUrl:null,permissions:Y,error:_}),J;try{J=i2($.target,{identityFile:$.identityFile})}catch(_){return X(_ instanceof Error?_.message:String(_))}let W=$.label??J.id,H=Y.join(","),V,K='export PATH="$HOME/.bun/bin:$PATH"; ';try{if(!$.connectExisting){Q("probe","running");let O=await J.probe();if(Q("probe","completed",`os=${O.os??"?"} arch=${O.arch??"?"}`),!O.bun){if($.installBun===!1)return X("Bun is required to run the agent but is not installed, and Bun auto-install was disabled.");Q("install-bun","running");let i=await J.run(["sh","-c",`curl -fsSL https://bun.sh/install | bash && echo 'export PATH="$HOME/.bun/bin:$PATH"' >> ~/.bashrc`],{timeoutMs:300000});if(i.code!==0)return Q("install-bun","failed",i.stderr.slice(0,400)),X("Bun auto-install failed.");let L2=await J.run(["sh","-c","$HOME/.bun/bin/bun --version 2>/dev/null"],{timeoutMs:1e4});if(L2.code===0&&L2.stdout.trim())O.bun="$HOME/.bun/bin/bun",Q("install-bun","completed",L2.stdout.trim());else return X("Bun installed but the binary is not reachable.")}Q("install-agent","running");let I=$.version??"latest",h=$.registry??"https://registry.npmjs.org/";if(!/^[A-Za-z0-9._@/^~>=<-]+$/.test(I))return Q("install-agent","failed","invalid version"),X(`Invalid agent version: ${I}`);if(!/^https?:\/\/[A-Za-z0-9._~:/?#@!$&'()*+,;=%-]+$/.test(h))return Q("install-agent","failed","invalid registry"),X(`Invalid registry URL: ${h}`);let c=await J.run(["sh","-c",`${K}npm_config_registry="${h}" bun install -g @vibecontrols/agent@${I} --no-cache`],{timeoutMs:600000});if(c.code!==0)return Q("install-agent","failed",c.stderr.slice(0,400)),X(`Agent install failed (exit ${c.code}).`);if(V=(await J.run(["sh","-c",`${K}vibe --version`],{timeoutMs:15000})).stdout.trim()||void 0,Q("install-agent","completed",V),$.autostart)Q("autostart","running"),await J.run(["sh","-c",`${K}vibe autostart install`],{timeoutMs:60000}),Q("autostart","completed");if($.installPlugins?.length){Q("plugins","running");for(let i of $.installPlugins)await J.run(["sh","-c",`${K}vibe plugin install ${i}`],{timeoutMs:300000});Q("plugins","completed")}Q("start","running"),await J.run(["sh","-c",`${K}vibe start`],{timeoutMs:60000}),Q("start","completed")}Q("bootstrap","running");let _=$.expiresIn?` --expires-in ${$.expiresIn}`:"",q=W.replace(/'/g,""),C=null;for(let O=0;O<15;O++){let I=`${K}vibe peer-bootstrap --json --emit-default-key --label '${q}' --scope ${H}${_} 2>/dev/null`,h=await J.run(["sh","-c",I],{timeoutMs:15000});if(h.code===0){let c=IQ(h.stdout);if(c&&typeof c.apiKey==="string"){C=c;break}}await new Promise((c)=>setTimeout(c,2000))}if(!C)return Q("bootstrap","failed","could not obtain peer-bootstrap bundle"),X("Remote peer-bootstrap did not return a credential bundle.");Q("bootstrap","completed");let x=n(),B=String(C.id),E=String(C.apiKey),w=n2(typeof C.tunnelUrl==="string"?C.tunnelUrl:null),v=typeof C.agentRecordId==="string"?C.agentRecordId:null;if($.onboardBackend!==!1&&g.isConfigured()&&w&&typeof C.fullDefaultApiKey==="string"){Q("onboard","running");let O=5,I="no agent returned";for(let h=0;h<O;h++){try{let i=(await g.workspaceQuery(EQ,{input:{tunnelUrl:w,apiKey:C.fullDefaultApiKey,name:W}})).data?.addVibecontrolsAgentFromTunnel;if(i?.agent?.id){v=i.agent.id,I="",Q("onboard","completed",`agent ${v}`);break}I=i?.error??"no agent returned"}catch(r){I=r instanceof Error?r.message:String(r)}if(!/unreachable|resolve hostname|timed out|timeout|ECONN|network|to fetch|50[234]/i.test(I)||h===O-1)break;Q("onboard","running",`retry ${h+1}/${O-1}: ${I.slice(0,80)}`),await new Promise((r)=>setTimeout(r,3000*(h+1)))}if(I)Q("onboard","failed",I)}else Q("onboard","skipped");Q("store-creds","running"),v4({id:B,label:W,tunnelUrl:w??"",apiKey:E,permissions:Y,addedAt:new Date().toISOString(),agentRecordId:v??void 0,workspaceId:(typeof C.workspaceId==="string"?C.workspaceId:x.workspaceId)??void 0,fingerprint:B,ownerUserId:x.ownerUserId,sshTarget:J.mode==="ssh"?$.target:void 0,sshIdentityFile:$.identityFile}),Q("store-creds","completed");let L=m2();if($.onboardBackend!==!1&&g.isConfigured()&&L&&v){Q("report-link","running");try{await g.workspaceQuery(CQ,{input:{sourceAgentRecordId:L,destinationAgentRecordId:v,label:W}}),Q("report-link","completed")}catch(O){Q("report-link","failed",O instanceof Error?O.message:String(O))}}else Q("report-link","skipped");let T=await I2(B,"/api/profiles/default/agent/identity",{operation:"post-deploy-probe"});return Q("probe-peer",T.ok?"completed":"failed",T.error??void 0),{ok:!0,peerId:B,agentRecordId:v,tunnelUrl:w,permissions:Y,remoteVersion:V}}catch(_){return X(_ instanceof Error?_.message:String(_))}finally{await J.close().catch(()=>{})}}var N0='export PATH="$HOME/.bun/bin:$PATH"; ';function qQ($){let Z=$.indexOf("{"),Q=$.lastIndexOf("}");if(Z>=0&&Q>Z)try{let Y=JSON.parse($.slice(Z,Q+1));if(Y.tunnelUrl)return Y.tunnelUrl;if(Y.url&&Y.url.startsWith("https"))return Y.url}catch{}return null}async function c4($,Z){let Q=(J,W,H)=>Z?.({step:J,status:W,message:H}),Y=b4($);if(!Y)return{ok:!1,peerId:$,tunnelUrl:null,error:`No peer with id ${$}`};if(!Y.sshTarget)return{ok:!1,peerId:$,tunnelUrl:null,error:"No SSH target stored for this peer \u2014 it wasn't SSH-deployed, so it can't be woken via SSH."};let X;try{X=i2(Y.sshTarget,{identityFile:Y.sshIdentityFile})}catch(J){return{ok:!1,peerId:$,tunnelUrl:null,error:J instanceof Error?J.message:String(J)}}try{Q("ssh-restart","running",Y.sshTarget);let J=await X.run(["sh","-c",`${N0}vibe restart 2>/dev/null || ${N0}vibe start`],{timeoutMs:90000});if(J.code!==0)return Q("ssh-restart","failed",J.stderr.slice(0,300)),{ok:!1,peerId:$,tunnelUrl:null,error:`Remote restart failed (exit ${J.code})`};Q("ssh-restart","completed"),Q("await-tunnel","running");let W=null;for(let H=0;H<15;H++){let V=await X.run(["sh","-c",`${N0}vibe url --json 2>/dev/null`],{timeoutMs:15000});if(V.code===0){let K=qQ(V.stdout),_=n2(K);if(_){W=_;break}}await new Promise((K)=>setTimeout(K,2000))}if(!W)return Q("await-tunnel","failed","no fresh tunnel after restart"),{ok:!1,peerId:$,tunnelUrl:null,error:"Agent restarted but no fresh tunnel came up."};return Q("await-tunnel","completed",W),y4($,{tunnelUrl:W,lastReachable:new Date().toISOString()}),Q("update","completed"),{ok:!0,peerId:$,tunnelUrl:W}}catch(J){return{ok:!1,peerId:$,tunnelUrl:null,error:J instanceof Error?J.message:String(J)}}finally{await X.close().catch(()=>{})}}var kQ=Number(process.env.VIBECONTROLS_MESH_MAX_HOPS||"8");function u4(){return(y()??G()).name}function SQ(){return(y()??G()).dataDir}function m4(){try{let Z=AQ(SQ(),"runtime.json");if(wQ(Z)){let Q=JSON.parse(RQ(Z,"utf8"));if(Q.port&&Number.isInteger(Q.port))return Q.port}}catch{}let $=Number(process.env.PORT);return Number.isInteger($)&&$>0?$:3005}function DQ($){let Z={};return $.headers.forEach((Q,Y)=>{Z[Y]=Q}),Z}function X2($,Z){let Q=m(DQ($));return l4(p4(Q),Z)}function hQ($){let{apiKey:Z,...Q}=$;return{...Q,apiKey:"[REDACTED]"}}function g4($){return typeof $==="string"&&$.startsWith("/api/")&&!$.includes("..")&&!$.includes("//")}var o2=new Map;function vQ(){let $=Date.now()-3600000;for(let[Z,Q]of o2)if(Q.completedAt&&Date.parse(Q.completedAt)<$)o2.delete(Z)}function n4(){return new D({name:"agent-mesh"}).get("/api/mesh/peers",({request:$,set:Z})=>{if(!X2($,["read"]))return Z.status=403,{error:"forbidden"};return{peers:F2(n()).map(hQ)}}).delete("/api/mesh/peers/:id",({request:$,set:Z,params:Q})=>{if(!X2($,["mutate"]))return Z.status=403,{error:"forbidden"};if(!F2(n()).some((X)=>X.id===Q.id))return Z.status=404,{error:"not found"};return{ok:d4(Q.id)}}).post("/api/mesh/peers/:id/call",async({request:$,set:Z,params:Q,body:Y})=>{if(!X2($,["mesh:forward"]))return Z.status=403,{error:"forbidden"};let X=Y;if(!g4(X.path))return Z.status=400,{error:"invalid path"};if(!F2(n()).find((H)=>H.id===Q.id))return Z.status=404,{error:"not found"};let W=await I2(Q.id,X.path,{method:X.method??"GET",body:X.body,operation:"mesh-call"});return{ok:W.ok,status:W.status,data:W.data,rotated:W.rotated,error:W.error}},{body:z.Object({method:z.Optional(z.String()),path:z.String(),body:z.Optional(z.Any())})}).post("/api/mesh/forward",async({request:$,set:Z,body:Q})=>{if(!X2($,["mesh:forward"]))return Z.status=403,{error:"forbidden"};let Y=Q;if(!Y.request||!g4(Y.request.path))return Z.status=400,{error:"invalid request"};let X=(Y._hopCount??0)+1;if(X>kQ)return Z.status=422,{error:"hop limit exceeded"};let J=n(),W=m2(),H=Y.hops??[];if(H.length===0){G().audit.emit("mesh","forward.terminal",{path:Y.request.path,method:Y.request.method??"GET"});let x=(Y.request.method??"GET").toUpperCase();try{let B=await fetch(`http://127.0.0.1:${m4()}${Y.request.path}`,{method:x,headers:{"x-agent-api-key":await j0(),...Y.request.body!==void 0?{"content-type":"application/json"}:{}},body:Y.request.body!==void 0?JSON.stringify(Y.request.body):void 0,signal:AbortSignal.timeout(60000)}),E=await B.text().catch(()=>""),w=null;try{w=E?JSON.parse(E):null}catch{w=null}return{ok:B.ok,status:B.status,data:w,text:E||null,error:B.ok?null:E||`status ${B.status}`}}catch(B){return Z.status=502,{ok:!1,status:0,error:B instanceof Error?B.message:String(B)}}}let V=H[0],K=Y._traversed??[];if(V===W||K.includes(V))return Z.status=422,{error:"cycle detected",at:V};let _=U0(V,J);if(!_)return Z.status=403,{error:"next hop not in authorized boundary"};if(!_.permissions.includes("mesh:forward"))return Z.status=403,{error:"peer lacks mesh:forward grant"};G().audit.emit("mesh","forward.hop",{nextId:V,remaining:H.length,hopCount:X});let q=encodeURIComponent(u4()),C=await I2(_.id,`/api/profiles/${q}/mesh/forward`,{method:"POST",operation:"mesh-forward",timeoutMs:60000,body:{hops:H.slice(1),request:Y.request,_traversed:[...K,W??"self"],_hopCount:X}});if(!C.ok)return Z.status=502,{ok:!1,status:C.status,error:C.error,failedAtHop:V};return C.data},{body:z.Object({hops:z.Optional(z.Array(z.String())),request:z.Object({method:z.Optional(z.String()),path:z.String(),body:z.Optional(z.Any())}),_traversed:z.Optional(z.Array(z.String())),_hopCount:z.Optional(z.Number())})}).post("/api/mesh/deploy",({request:$,set:Z,body:Q})=>{if(!X2($,["admin"]))return Z.status=403,{error:"forbidden"};vQ();let Y=Q,X=n(),J=crypto.randomUUID(),W={id:J,status:"running",steps:[],ownerUserId:X.ownerUserId,workspaceId:X.workspaceId,startedAt:new Date().toISOString()};return o2.set(J,W),f4({target:Y.target,permissions:Y.permissions,installPlugins:Y.installPlugins,autostart:Y.autostart,identityFile:Y.identityFile,label:Y.label,version:Y.version,connectExisting:Y.connectExisting},(H)=>{W.steps.push(H),Y2("mesh:deploy:progress",{jobId:J,step:H})}).then((H)=>{if(W.result=H,W.status=H.ok?"completed":"failed",!H.ok)W.error=H.error;W.completedAt=new Date().toISOString(),Y2(H.ok?"mesh:deploy:complete":"mesh:deploy:failed",{jobId:J,result:H})}).catch((H)=>{W.status="failed",W.error=H instanceof Error?H.message:String(H),W.completedAt=new Date().toISOString(),Y2("mesh:deploy:failed",{jobId:J,error:W.error})}),Z.status=202,{jobId:J,status:"running"}},{body:z.Object({target:z.String(),permissions:z.Optional(z.Array(z.String())),installPlugins:z.Optional(z.Array(z.String())),autostart:z.Optional(z.Boolean()),identityFile:z.Optional(z.String()),label:z.Optional(z.String()),version:z.Optional(z.String()),connectExisting:z.Optional(z.Boolean())})}).get("/api/mesh/deploy/jobs/:id",({request:$,set:Z,params:Q})=>{if(!X2($,["read"]))return Z.status=403,{error:"forbidden"};let Y=o2.get(Q.id),X=n();if(!Y||X.ownerUserId&&Y.ownerUserId&&Y.ownerUserId!==X.ownerUserId)return Z.status=404,{error:"not found"};return Y}).post("/api/mesh/wake",async({request:$,set:Z,body:Q})=>{if(!X2($,["admin"]))return Z.status=403,{error:"forbidden"};let Y=Q,X=U0(Y.targetAgentRecordId,n());if(!X)return Z.status=404,{ok:!1,error:"peer not in authorized boundary"};G().audit.emit("mesh","wake.start",{peerId:X.id,agentRecordId:Y.targetAgentRecordId});let J=await c4(X.id,(W)=>Y2("mesh:wake:progress",{peerId:X.id,step:W}));if(!J.ok)Z.status=502;return J},{body:z.Object({targetAgentRecordId:z.String()})}).post("/api/mesh/session",async({request:$,set:Z,body:Q})=>{if(!X2($,["mesh:forward","mutate"]))return Z.status=403,{error:"forbidden"};let Y=Q,X=Y.sessionId&&/^[A-Za-z0-9_-]{1,128}$/.test(Y.sessionId)?Y.sessionId:crypto.randomUUID(),J=encodeURIComponent(u4()),W=await j0(),H=`http://127.0.0.1:${m4()}`,V=Y.command||"bash";try{let K=await fetch(`${H}/api/profiles/${J}/sessions/create`,{method:"POST",headers:{"x-agent-api-key":W,"content-type":"application/json"},body:JSON.stringify({sessionId:X,sessionName:`vc-mesh-${X.slice(0,8)}`,command:V,provider:"TERMINAL",...Y.vibeId?{projectId:Y.vibeId}:{}}),signal:AbortSignal.timeout(20000)});if(!K.ok)return Z.status=502,{error:`session create returned ${K.status}: ${await K.text().catch(()=>"")}`};let _=await fetch(`${H}/api/profiles/${J}/sessions/${encodeURIComponent(X)}/terminal`,{method:"POST",headers:{"x-agent-api-key":W},signal:AbortSignal.timeout(20000)});if(!_.ok)return Z.status=502,{error:`terminal start returned ${_.status}: ${await _.text().catch(()=>"")}`};let q=h2(`/terminal/${X}`,600);return G().audit.emit("mesh","session.created",{sessionId:X,kind:Y.kind??"TERMINAL"}),{connectionId:X,sessionId:X,capabilityToken:q.token,expiresAt:q.expiresAt}}catch(K){return Z.status=502,{error:K instanceof Error?K.message:String(K)}}},{body:z.Object({sessionId:z.Optional(z.String()),kind:z.Optional(z.String()),cwd:z.Optional(z.String()),vibeId:z.Optional(z.String()),command:z.Optional(z.String())})})}var PQ=["/health","/api/agent/status","/api/agent/version","/api/agent/identity","/api/agent/api-key","/api/agent/tunnel","/api/agent/system","/api/agent/gateway-auth","/api/stats","/metrics","/api/profiles","/api/profile-stats"];function fQ($){return PQ.some((Z)=>$.startsWith(Z))}var bQ=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function yQ($){return $.split("/").map((Z)=>{if(!Z)return Z;if(/^\d+$/.test(Z))return":id";if(bQ.test(Z))return":id";if(Z.length>=24&&/^[A-Za-z0-9_-]+$/.test(Z))return":id";return Z}).join("/")}async function l8($){let{port:Z,host:Q,dbPath:Y,logLevel:X,corsOrigin:J}=$,W=Y??T2();try{(await import("fs")).mkdirSync(W,{recursive:!0})}catch(F){throw G().logger.error("app","Failed to create dbPath dir at boot",{dbPath:W,error:String(F)}),Error(`Cannot create dbPath ${W}: ${F instanceof Error?F.message:String(F)}`,{cause:F})}if(X)G().logger.setLevel(X);(async()=>{let{logShipper:F}=await import("./log-shipper-k24m8yw5.js");F.init()})(),(async()=>{let F=await o4();await k2({version:F,profile:E2()})})();try{let{checkDependencies:F}=await import("./bootstrap.service-pjmnpxha.js"),M=F(),j=M.filter((R)=>R.required&&!R.installed),A=M.filter((R)=>!R.required&&!R.installed);if(j.length>0)G().logger.error("app",`Missing required system deps: ${j.map((R)=>R.name).join(", ")}. Run \`vibe setup\` to install.`);if(A.length>0)G().logger.warn("app",`Missing optional system deps: ${A.map((R)=>R.name).join(", ")}. Some plugins may fail their prereqs check.`)}catch(F){G().logger.warn("app","Boot-time dependency check failed",{error:String(F)})}try{G().audit.runRetention()}catch(F){G().logger.warn("app","Audit-log retention sweep failed",{error:String(F)})}let H=new _5;C5(H,{port:Z});let V="GET, POST, PUT, PATCH, DELETE, OPTIONS",K="Content-Type, x-agent-api-key, Authorization, x-requested-with",_=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(_.includes(F))return!0;if(_.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}},x=null,B=null,E=null,w=null,v=!1,L=()=>[],T=null,O=null,I=null,h=5000,c=async(F,M)=>{let j=Date.now();try{await Promise.race([Promise.resolve(M()),new Promise((A,R)=>setTimeout(()=>R(Error(`shutdown phase ${F} exceeded ${h}ms`)),h))]),G().logger.info("app",`shutdown.phase ${F} complete`,{ms:Date.now()-j})}catch(A){G().logger.warn("app",`shutdown.phase ${F} failed`,{error:String(A),ms:Date.now()-j})}},r=async(F)=>{if(v)return;if(v=!0,G().logger.info("app","Agent shutdown starting",{reason:F?.reason??"shutdown"}),await c("plugins",async()=>{if(B)await B.dispatchServerStop(F)}),await c("bootstrap-tunnel",()=>T0()),await c("tracked-subprocesses",async()=>{let{killAllTracked:M}=await import("./subprocess-g9sk1ep9.js");await M()}),F?.reason!=="reload")await c("db-close",async()=>{if(x)await x.close()});await c("http-listener",async()=>{try{await Promise.resolve(e.stop())}catch(M){G().logger.warn("app","Listener stop threw (already stopped or never started?)",{error:String(M)})}}),G().logger.info("app","Agent server stopped"),G().logger.close()},i=async(F,M)=>{if(G().getBootState()==="ready")return{ok:!0};if(I)return I;return I=(async()=>{G().setBootState("initializing");try{let j={...F,globalGatewayUrl:V2(F.globalGatewayUrl,"globalGatewayUrl"),workspaceGatewayUrl:V2(F.workspaceGatewayUrl,"workspaceGatewayUrl")},A=await N5(j),R=W,P=t({dir:G().dataDir}),p=P.storageAdapter??process.env.VIBE_STORAGE_ADAPTER??void 0,o=P.storageOptions,Q2=(N)=>{let U=(N instanceof Error?N.message:String(N)).toLowerCase(),k=N&&typeof N==="object"&&"code"in N?String(N.code).toUpperCase():"";if(k==="EBUSY"||k==="EPERM"||k==="EACCES"||k==="EAGAIN"||k==="EMFILE"||k==="ENFILE"||k==="ETIMEDOUT"||k==="ECONNRESET"||k==="ECONNREFUSED"||U.includes("encryption key")||U.includes("fetch")&&U.includes("key")||U.includes("temporarily unavailable")||U.includes("resource busy"))return"transient";if(U.includes("auth tag")||U.includes("authentication tag")||U.includes("unable to authenticate data")||U.includes("bad decrypt")||U.includes("unsupported state")||U.includes("incorrect header check")||U.includes("invalid distance")||U.includes("incorrect data check")||U.includes("unexpected end of")||U.includes("unexpected token")||U.includes("json")&&(U.includes("parse")||U.includes("invalid"))||U.includes("truncated")||U.includes("malformed")||U.includes("corrupt"))return"corruption";return"unknown"},N2=()=>a4({dbPath:R,encryptionKey:A,adapterName:p,adapterOptions:o});try{x=await N2()}catch(N){let U=N,k=Q2(N),w2=[500,2000,8000];if(k==="transient"||k==="unknown"){G().logger.warn("app",`Storage open failed (${k}); will retry up to ${w2.length} times before quarantine`,{error:N instanceof Error?N.message:String(N),path:R});for(let x2 of w2){await new Promise((f)=>setTimeout(f,x2));try{x=await N2(),U=null;break}catch(f){if(U=f,k=Q2(f),G().logger.warn("app",`Storage open retry failed (${k}) after ${x2}ms`,{error:f instanceof Error?f.message:String(f)}),k==="corruption")break}}}if(!x&&U){if(k!=="corruption"){let f=U instanceof Error?U.message:String(U);G().logger.error("app",`Storage open failed after retries with non-corruption error (${k}); refusing to quarantine valid data`,{error:f,path:R}),G().recordDegradedReason("storage",f);try{throw U}catch(G2){throw Error(`Storage open failed (${k}); agent is degraded: ${f}`,{cause:G2})}}let x2=U instanceof Error?U.message:String(U);G().logger.error("app","QUARANTINE: Storage file is corrupt \u2014 renaming and creating fresh DB",{errorClass:"corruption",error:x2,path:R});try{let f=await import("fs");if(f.existsSync(R)){let G2=new Date().toISOString().replace(/[:.]/g,"-"),q0=`${R}.broken-${G2}`;f.renameSync(R,q0),G().logger.warn("app",`Quarantined corrupt storage to ${q0} \u2014 fresh DB will be created`,{originalError:x2})}x=await N2()}catch(f){let G2=f instanceof Error?f.message:String(f);throw G().recordDegradedReason("storage",G2),Error(`Storage open failed twice (quarantine path); agent is degraded: ${G2}`,{cause:f})}}}if(!x)throw Error("Internal error: storage open recovery exited without an open database and without throwing");if(await D2({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:G().dataDir,scope:G().name}),await x.setConfig("gateway-auth:clientId",j.clientId),await x.setConfig("gateway-auth:clientSecret",j.clientSecret),await x.setConfig("gateway-auth:globalGatewayUrl",j.globalGatewayUrl),await x.setConfig("gateway-auth:workspaceGatewayUrl",j.workspaceGatewayUrl),await x.setConfig("gateway-auth:workspaceId",j.workspaceId),j.organizationId)await x.setConfig("gateway-auth:organizationId",j.organizationId);if(M?.agentRecordId)await x.setConfig("gateway-auth:agentRecordId",M.agentRecordId);H.db=x,await H.hydrateDefaultsFromDb(),B=new M5(x),await B.loadCorePlugins();try{await B.loadAll()}catch(N){G().logger.warn("app","Failed to load some external plugins",{error:String(N)})}let j2=T5(K2())??void 0,U2=process.env.VIBE_SKIP_AUTO_INSTALL==="1"||await x.getConfig("plugins:auto-install-disabled");if(U2!=="true"&&U2!==!0)try{let N=await B.ensureDefaultPlugins((U)=>G().logger.info("app",`[auto-install] ${U}`),[],j2);if(N.length>0)G().logger.info("app",`Auto-installed ${N.length} default plugin(s): ${N.map((U)=>U.packageName).join(", ")}`)}catch(N){G().logger.warn("app","Failed to auto-install default plugins",{error:String(N)})}G().logger.info("app",`Plugins loaded: ${B.getPluginDetails().length} total (${B.getPluginDetails().filter((N)=>N.isCore).length} core)`);try{let N=B.getPluginDetails(),U={loaded:N.filter((k)=>k.loaded).length,failed:N.filter((k)=>!k.loaded).length};P0(U)}catch{}let s2={async get(N,U){return await x.getPluginState(N,U)??null},async set(N,U,k){await x.setPluginState(N,U,k)},async delete(N,U){return x.deletePluginState(N,U)},async list(N){return await x.getAllPluginState(N)},async deleteAll(N){return x.deleteAllPluginState(N)}},q2=await o4();E={storage:s2,logger:G().logger,serviceRegistry:H,getProvider:(N)=>H.getProvider(N),getAgentBaseUrl:()=>process.env.AGENT_URL||`http://localhost:${Z}`,getAgentVersion:()=>q2,validateApiKey:(N)=>l(N),setCodeServerSessionValidator:(N)=>{I5=N},broadcast:Y2,workspaceQuery:async(N,U)=>g.workspaceQuery(N,U),isGatewayConfigured:()=>g.isConfigured(),getAgentRecordId:async()=>await x.getConfig("gateway-auth:agentRecordId")??null,getWorkspaceId:async()=>await x.getConfig("gateway-auth:workspaceId")??null,getConfig:async(N)=>await x.getConfig(N)??void 0,getPluginRegistry:()=>d2(),getDataDir:()=>S2(),cliContributors:new L5,audit:{emit:(N,U)=>G().audit.emit("agent",N,U??{})},telemetry:{emit:(N,U)=>{import("./telemetry-tnq47dcs.js").then(({telemetryService:k})=>k.emit(N,U??{})).catch(()=>{})}},os:_2(),iframeBridge:O5()},g.configure({globalGatewayUrl:j.globalGatewayUrl,workspaceGatewayUrl:j.workspaceGatewayUrl,clientId:j.clientId,clientSecret:j.clientSecret,workspaceId:j.workspaceId,organizationId:j.organizationId});let H2={db:x,serviceRegistry:H,pluginManager:B,broadcast:Y2,hostServices:E};H2.app=e;let I0=!1,r2=()=>{let{routes:N,getPublicPaths:U,mountPlugin:k}=e4(B,H2);if(H2.mountPlugin=k,L=U,J5(),T=N,O=x5(B),B&&I0&&E)B.dispatchServerStart(T,E).catch((w2)=>G().logger.warn("app","Re-dispatch of onServerStart after plugin reload failed",{error:String(w2)}));I0=!0};H2.rebuildPluginSurfaces=r2,r2(),w=new j5(H,B,x,e,E,r),H.registerService("agent","lifecycle",w),G().attachServices({db:x,serviceRegistry:H,pluginManager:B,lifecycle:w,hostServices:E}),K5(G(),{rebuildPluginSurfaces:r2,mountPlugin:H2.mountPlugin});try{await G().keyVault.bindApiKey(M2())}catch(N){G().logger.warn("app","Failed to bind api key into daemon keyVault",{error:String(N)})}let t2=[];try{let{failures:N}=await B.dispatchServerStart(T,E);for(let U of N)if(M0(U.plugin)||(U.packageName?M0(U.packageName):!1))t2.push(U),G().recordDegradedReason(U.plugin,U.error);else G().logger.warn("app",`Non-critical plugin ${U.plugin} failed onServerStart; continuing`,{error:U.error})}catch(N){G().logger.warn("app","Error during plugin onServerStart dispatch",{error:String(N)})}try{await B.dispatchServerReady(e,E)}catch(N){G().logger.warn("app","Error during plugin onServerReady dispatch",{error:String(N)})}if(G().clearFinalizeError(),t2.length>0)G().setBootState("degraded"),G().logger.error("app","Agent finalized but degraded \u2014 critical plugins failed",{failures:t2.map((N)=>`${N.plugin}: ${N.error}`)});else G().setBootState("ready"),G().logger.info("app","Agent finalized \u2014 state=ready"),G().audit.emit("agent","gateway-auth.configured",{workspaceId:j.workspaceId,organizationId:j.organizationId,agentRecordId:M?.agentRecordId});return(async()=>{try{if(await B.provisionDefaultPrereqs(e,E,H2.mountPlugin,j2),G().logger.info("app","Default provider prerequisites provisioned"),(H.listProvidersForType("tunnel")??[]).some((k)=>k.pluginName!=="bootstrap")){let{tryHandoverBootstrapTunnel:k}=await import("./tunnel-bootstrap-2kg79ng8.js");if(!k())T0();H.unregisterProvider("tunnel","bootstrap"),G().logger.info("app","Bootstrap tunnel handed over to the real tunnel provider")}}catch(N){G().logger.warn("app","Plugin prerequisite provisioning failed",{error:String(N)})}})(),{ok:!0}}catch(j){G().setBootState("awaiting-config");let A=j instanceof Error?j.message:String(j);if(G().recordFinalizeError(A),G().logger.error("app","Finalize failed",{error:A}),process.env.VIBE_STRICT_KEY_FETCH==="1")G().logger.error("app","VIBE_STRICT_KEY_FETCH=1 \u2192 aborting daemon (strict mode)",{error:A}),setTimeout(()=>process.exit(1),50);return{ok:!1,error:A}}finally{I=null}})(),I},L2=R0({origin:(F)=>{let M=F.headers.get("origin");return!!M&&C(M)},credentials:!0,allowedHeaders:K.split(",").map((F)=>F.trim()),methods:V.split(",").map((F)=>F.trim()),exposeHeaders:["content-type","content-length"],maxAge:86400,preflight:!0}),q5=10485760,E0=process.env.VIBECONTROLS_MAX_BODY_BYTES,a2=E0?Number.parseInt(E0,10):NaN,w5=Number.isFinite(a2)&&a2>0?a2:q5,C0={current:null},e=new D({serve:{maxRequestBodySize:w5}}).onRequest(({request:F,set:M})=>{let A=s4(F.headers)??x0();r4({requestId:A,startedAt:new Date().toISOString()});let R=M.headers??={};R["X-Request-Id"]=A}).onRequest(({request:F})=>{try{let M=new URL(F.url).pathname,A=/^\/api\/profiles\/([^/]+)(?:\/|$)/.exec(M)?.[1],R=A?s.get(A):null;O0(R??G())}catch{O0(G())}}).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 A=new URL(F.url);A.pathname=`/api/profiles/default${j.slice(4)}`;try{F.headers.set("x-vc-profile-rewrite","1"),F.headers.set("x-vc-profile-rewrite-target",A.pathname)}catch{}return}).derive(()=>({requestId:t4()??x0()})).use(L2).use(Y5()).use(X5(()=>L())).use(S0({getDb:()=>y()?.db??x})).onBeforeHandle(({request:F,set:M})=>{let j=G().getBootState();if(j==="ready")return;let A=new URL(F.url).pathname;if(fQ(A))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,A=j==="/health"||j.startsWith("/api/logs/stream")||j.startsWith("/ui/")||j==="/ws/events"||j==="/api/sessions/health-check"||j.startsWith("/terminal/"),R=typeof M.status==="number"?M.status:200,P=A?"debug":R>=400?"warn":"info";G().logger[P]("http",`${F.method} ${j} \u2192 ${R}`,{method:F.method,path:j,statusCode:R});try{v0(F.method,yQ(j),R)}catch{}}).use(Y4({serviceRegistry:H,getDb:()=>y()?.db??x,getDbPath:()=>W,getPluginManager:()=>y()?.pluginManager??B})).use(b0()).use(n0({serviceRegistry:H,runFinalize:(F,M)=>i(F,M),getDb:()=>y()?.db??x})).use(z4()).use(H4()).use(D4({getPluginManager:()=>y()?.pluginManager??B})).use(n4()).use(K4()).use(x4({getPluginManager:()=>y()?.pluginManager??B,getTunnelHost:()=>E5()?.url??null})).use(Q4()).use(Z4()).use(G5()).use(B5()).use(V5(H)).ws("/code-server/*",uQ(Z)).all("/api/profiles/:name/*",async({params:F,request:M,set:j})=>{let A=M.method!=="GET"&&M.method!=="HEAD",R=A?await M.arrayBuffer():void 0,P=await F5(F.name,M,R);if(P&&P.status!==404)return P;let p=E2(),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),N2=Q2.pathname.replace(/^\/api\/profiles\/[^/]+/,"/api"),j2=new Headers(M.headers);j2.set("x-vc-profile-rewrite","1");let U2={method:M.method,headers:j2};if(A&&R!==void 0)U2.body=R;let s2=new Request(`${Q2.origin}${N2}${Q2.search}`,U2),q2=C0.current;if(!q2)return new Response(JSON.stringify({error:"agent-not-ready"}),{status:503,headers:{"content-type":"application/json"}});return q2.handle(s2)}).all("/api/*",async({request:F})=>{if(G().getBootState()!=="ready"||!T)return new Response(JSON.stringify({error:"Agent not yet configured",state:G().getBootState(),message:"Plugin routes are unavailable until the agent reaches state=ready. POST credentials to /api/agent/gateway-auth to finalize."}),{status:503,headers:{"content-type":"application/json"}});try{let M=new URL(F.url),j=/^\/api\/plugins\/([a-z0-9-]{1,64})\/ui(?:\/.*)?$/.exec(M.pathname);if(j&&F.method==="GET"){let A=j[1];if(O2(A)){let R=M.pathname.slice(`/api/plugins/${A}/ui`.length),P=R===""||R==="/",o=F.headers.get("sec-fetch-mode")==="navigate";if(P||o){let Q2=Z5(F,A);if(!Q2||!$5(Q2,A))return new Response(U5(A,"/api/profiles/default/agent/ui-exchange-plugin"),{status:200,headers:{"content-type":"text/html; charset=utf-8","Content-Security-Policy":"frame-ancestors 'self' http://localhost:* http://127.0.0.1:* https://localhost:* https://127.0.0.1:* https://*.local.burdenoff.com https://vibecontrols.com https://*.vibecontrols.com https://burdenoff.com https://app.burdenoff.com https://alphaapp.burdenoff.com"}})}}}}catch{}return T.handle(F)}).all("/ui/*",async({request:F})=>{if(G().getBootState()!=="ready"||!O)return new Response("Plugin UI not yet available",{status:503});return O.handle(F)}).all("/code-server/*",async({request:F})=>{if(G().getBootState()!=="ready"||!T)return new Response("code-server not yet available",{status:503});return T.handle(F)}).all("/plan/*",async({request:F})=>{if(G().getBootState()!=="ready"||!T)return new Response("plan provider not yet available",{status:503});return T.handle(F)});return C0.current=e,{app:e,async start(){e.listen({port:Z,hostname:Q}),G().logger.info("app",`Agent server listening on ${Q}:${Z}`);try{let F=(process.env.VIBECONTROLS_PROFILES??"").split(",").map((P)=>P.trim()).filter(Boolean),M=G().name,{getOrCreateProfile:j}=await import("./daemon-profile-vas1vf2t.js"),{attachSecondaryProfile:A}=await import("./secondary-profile-attach-db5cr3e1.js"),R=process.env.VIBE_STRICT_KEY_FETCH==="1";for(let P of F){if(P===M)continue;try{let p=j(P),o=await A(p);if(o.ok)G().logger.info("app",`Secondary profile '${P}' attached (db+services online)`);else if(R)throw Error(`attachServices for secondary profile '${P}' failed: ${o.error}`);else p.recordDegradedReason("attach",o.error??"unknown"),G().logger.warn("app",`Secondary profile '${P}' is degraded (no creds / attach failed)`,{error:o.error})}catch(p){if(R)throw G().logger.error("app",`--strict-key-fetch: secondary profile '${P}' attach failed; aborting`,{error:String(p)}),setTimeout(()=>process.exit(1),50),p;G().logger.warn("app",`Failed to attach secondary profile '${P}'`,{error:String(p)})}}}catch{}return e},stop:r,finalize:i,getState:()=>G().getBootState(),getLifecycle:()=>y()?.lifecycle??w,getDb:()=>y()?.db??x,getServiceRegistry:()=>y()?.serviceRegistry??H,getPluginManager:()=>y()?.pluginManager??B,getHostServices:()=>y()?.hostServices??E}}var I5=null;function cQ($,Z){if(!$)return null;let Q=$.match(new RegExp(`(?:^|;\\s*)${Z}=([^;]*)`));return Q?Q[1]:null}var i4=W5(z5);function uQ($){let X=(J)=>typeof J==="string"?Buffer.byteLength(J):J.byteLength;return{open(J){let W=J.data,H=m(W.headers??{})??m(W.request?Object.fromEntries(W.request.headers.entries()):{}),V=W.query?.vt,K=!!V&&Q5(V,"/code-server","GET"),_,q=l(H);if(!q&&!K){let E=W.headers?.cookie??W.request?.headers.get("cookie")??null,w=cQ(E,"__vibe_cs_session");if(!w||!I5?.(w)){J.close(1008,"Unauthorized");return}_=`session:${w}`}else if(q)_="api-key";else _="vt";let C=J.remoteAddress??null,x=H5(C,W.headers);if(!i4.accept(_,x,J)){G().logger.warn("code-server-ws",`code-server WS cap exceeded (key=${_}, ip=${x??"unknown"})`),J.close(1013,"too many connections");return}W._csCapKey=_,W._csRemoteIp=x;let B=G().name;fetch(`http://127.0.0.1:${$}/api/profiles/${encodeURIComponent(B)}/code-server/status`,{headers:{"x-agent-api-key":M2()}}).then((E)=>E.json()).then((E)=>{if(W._csClosed)return;let w=E;if(!w.running||!w.port){J.close(1011,"code-server not running");return}let v=W.request?.url??"/code-server/",L;try{let I=new URL(v,`http://127.0.0.1:${w.port}`);L=(I.pathname.replace(/^\/code-server\/?/,"/")||"/")+I.search}catch{L="/"}let T=new WebSocket(`ws://127.0.0.1:${w.port}${L}`),O={upstream:T,ready:!1,buffer:[],bufferBytes:0,openTimer:setTimeout(()=>{try{T.close(1011,"upstream open timeout")}catch{}try{J.close(1011,"upstream open timeout")}catch{}},1e4)};W._csBridge=O,T.addEventListener("open",()=>{clearTimeout(O.openTimer),O.ready=!0;for(let I of O.buffer)T.send(I);O.buffer.length=0,O.bufferBytes=0}),T.addEventListener("message",(I)=>{try{let h=I.data;if(h instanceof ArrayBuffer)J.send(new Uint8Array(h));else if(h instanceof Blob)h.arrayBuffer().then((c)=>{try{J.send(new Uint8Array(c))}catch{}});else J.send(h)}catch{}}),T.addEventListener("close",(I)=>{clearTimeout(O.openTimer);try{J.close(I.code||1000,I.reason||"upstream closed")}catch{}}),T.addEventListener("error",()=>{clearTimeout(O.openTimer);try{J.close(1011,"upstream error")}catch{}})}).catch(()=>{J.close(1011,"Failed to query code-server status")})},message(J,W){let H=J.data?._csBridge;if(!H)return;let V;if(typeof W==="string")V=W;else if(W instanceof ArrayBuffer)V=W;else if(W instanceof Uint8Array||Buffer.isBuffer(W)){let K=new ArrayBuffer(W.byteLength);new Uint8Array(K).set(new Uint8Array(W.buffer,W.byteOffset,W.byteLength)),V=K}else if(typeof W==="object"&&W!==null)V=JSON.stringify(W);else V=String(W);if(H.upstream&&H.ready&&H.upstream.readyState===WebSocket.OPEN)try{H.upstream.send(V)}catch{}else{let K=X(V);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(V),H.bufferBytes+=K}},close(J){J.data._csClosed=!0;let W=J.data?._csBridge;if(W?.openTimer)clearTimeout(W.openTimer);if(W?.upstream&&W.upstream.readyState===WebSocket.OPEN)W.upstream.close(1000,"client disconnected");let H=J.data._csCapKey,V=J.data._csRemoteIp;if(H)i4.release(H,V??null,J)}}}async function o4(){try{let{readFileSync:$}=await import("fs"),{join:Z,dirname:Q}=await import("path"),{fileURLToPath:Y}=await import("url"),X=Q(Y(import.meta.url));return JSON.parse($(Z(X,"..","package.json"),"utf8")).version||"1.0.0"}catch{return"1.0.0"}}
|
|
26
|
-
export{X6 as j,u0 as k,_Q as l,V7 as m,l8 as n};
|
package/dist/key.cmd-wgcq6kt8.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{Vb as a,Wb as b}from"./index-dm6yjmgq.js";import"./index-2xs9cvjn.js";import"./index-5mw3eshk.js";import"./index-z5a4yxzz.js";import"./index-ef95xr4z.js";import"./index-xjzmb1pn.js";import"./index-g2raeeh4.js";import"./index-9bqd8veb.js";import"./index-0cn9bv8z.js";import"./index-jw1k4vbk.js";import"./index-yy1mm8zs.js";export{a as resolveDefaultApiKey,b as register};
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{nb as a,ob as b,pb as c,qb as d,rb as e,sb as f}from"./index-v9fx5wab.js";import"./index-01qzsnwd.js";import"./index-d5ysy1yn.js";import"./index-04n4qgvd.js";import"./index-g2raeeh4.js";import"./index-9bqd8veb.js";import"./index-0cn9bv8z.js";import"./index-jw1k4vbk.js";import"./index-yy1mm8zs.js";export{b as unmountProfileRoutes,a as mountProfileRoutes,c as dispatchProfileRequest,f as __setMountForTests,e as __resetProfileMountsForTests,d as __listMountedProfilesForTests};
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{J as a}from"./index-fzzwprvk.js";import"./index-2gsarrbn.js";import"./index-b5dhmybd.js";import"./index-e1bw1bwr.js";import"./index-g8zv1gta.js";import"./index-qfz9fy56.js";import"./index-ssjmzqcz.js";import"./index-4wgjx8bf.js";import"./index-g3ap3xpr.js";import"./index-0ckffygp.js";import"./index-rc79x8fw.js";import"./index-yrgm89r8.js";import"./index-52cp759f.js";import"./index-01qzsnwd.js";import"./index-d5ysy1yn.js";import"./index-04n4qgvd.js";import"./index-5mw3eshk.js";import"./index-z5a4yxzz.js";import"./index-ef95xr4z.js";import"./index-xjzmb1pn.js";import"./index-g2raeeh4.js";import"./index-9bqd8veb.js";import"./index-0cn9bv8z.js";import"./index-jw1k4vbk.js";import"./index-yy1mm8zs.js";export{a as registerCoreCommands};
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{x as a}from"./index-1hnw0rhc.js";import"./index-tp4y9jde.js";import"./index-4wgjx8bf.js";import"./index-g3ap3xpr.js";import"./index-0ckffygp.js";import"./index-v9fx5wab.js";import"./index-01qzsnwd.js";import"./index-d5ysy1yn.js";import"./index-04n4qgvd.js";import"./index-g2raeeh4.js";import"./index-9bqd8veb.js";import"./index-0cn9bv8z.js";import"./index-jw1k4vbk.js";import"./index-yy1mm8zs.js";export{a as attachSecondaryProfile};
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{o as a,p as b,q as c,r as d,s as e}from"./index-n7qyrdr1.js";import"./index-0ckffygp.js";import"./index-9bqd8veb.js";import"./index-0cn9bv8z.js";import"./index-jw1k4vbk.js";import"./index-yy1mm8zs.js";export{a as spawnTracked,c as listTrackedByOwner,b as listTracked,d as killTracked,e as killAllTracked};
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{pa as a,qa as b,ra as c,sa as d,ta as e,ua as f}from"./index-qfz9fy56.js";import"./index-0ckffygp.js";import"./index-yrgm89r8.js";import"./index-52cp759f.js";import"./index-9bqd8veb.js";import"./index-0cn9bv8z.js";import"./index-jw1k4vbk.js";import"./index-yy1mm8zs.js";export{c as tryHandoverBootstrapTunnel,d as stopBootstrapTunnel,b as startBootstrapTunnel,a as sanitizeEnvSuffix,f as reapOrphanTunnelsForProfile,e as getBootstrapTunnelUrl};
|