@vibecontrols/agent 2026.1127.2 → 2026.1130.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{app-4t875vbv.js → app-ntnpwedw.js} +1 -1
- package/dist/{bridge-commands-xhzhghxt.js → bridge-commands-hc1gvngq.js} +1 -1
- package/dist/cli.js +1 -1
- package/dist/{index-6b9vh0gq.js → index-5tghd67e.js} +2 -2
- package/dist/{index-12rehjp4.js → index-85jn7v8t.js} +3 -3
- package/dist/{index-p1b10hs1.js → index-8jk4a62x.js} +6 -6
- package/dist/{index-6wfd7cv3.js → index-br9bakfm.js} +1 -1
- package/dist/{index-nz7mhjjn.js → index-dr6rsnpk.js} +1 -1
- package/dist/{index-j8j1h00a.js → index-j9jwwzq2.js} +1 -1
- package/dist/{index-1smr1csg.js → index-q4fht6h2.js} +2 -2
- package/dist/{index-dtxd2xmg.js → index-sjs32cgn.js} +2 -2
- package/dist/{index-0vbsve3v.js → index-twtvt4yt.js} +1 -1
- package/dist/index.js +2 -2
- package/dist/{plugin-system-7qjqrq7s.js → plugin-system-e690jr6e.js} +1 -1
- package/dist/{register-core-vv5pddxj.js → register-core-n1dy472f.js} +1 -1
- package/dist/{secondary-profile-attach-222s85md.js → secondary-profile-attach-v7kxsk4z.js} +1 -1
- package/dist/{tunnel-bootstrap-20vwak7q.js → tunnel-bootstrap-m51w4d94.js} +1 -1
- package/package.json +1 -1
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{r,E}from"./index-1t74r13z.js";import{er,tr,Rt}from"./index-6b9vh0gq.js";import{Ai,Hi,Vi,Tt,z,Wt,Ir,T,he,ot,bt,Oe,Xt,R,O,I,ee,C,se,wt,B,N,e,at}from"./index-7wm4bqx5.js";import{Et,W}from"./index-p1b10hs1.js";import{hr,we,fr,Ut,je,Hr,qe,Li,me,yt,rt,it,Re,K,L,V,mr,Ui,Ki,Qi}from"./index-qzwbctkv.js";import{ye,zr,nt,ti,w,ri,M,Yt,X,Zt,ii,ni,si,oi}from"./index-j99tkngg.js";import{gr,Ni,dr,ki,Qe,pe,Qr,jr,Gr,_t,$r}from"./index-p7fbnfwd.js";import{Ze,te,or,Nr,ar,lt,Je,gt,kr,We,ke,Bt,Xe,Le,ze,et,dt,ht,ft,pt,mt,Pt,Mt,Dt,Se}from"./index-nz7mhjjn.js";import{wr,qr}from"./index-ednz6yz2.js";import{oe}from"./index-ppxayc0x.js";import{Rr}from"./index-bpzk441p.js";import{Ve,Or,_i,Pe}from"./index-zn9snqbg.js";import{D}from"./index-0vbsve3v.js";import{xe,Ie,vr,Oi,ve}from"./index-6wfd7cv3.js";import{b}from"./index-w4jqdhc2.js";import{k}from"./index-e5jdx9c1.js";import{P}from"./index-rae5bn1c.js";var Tr=typeof new Headers()?.toJSON==="function",qn=(t)=>{if(Tr)return Object.keys(t.toJSON()).join(", ");let n="",o=0;return t.forEach((s,i)=>{if(o)n=n+", "+i;else n=i;o++}),n},Ur=(t)=>{let{aot:n=!0,origin:o=!0,methods:s=!0,allowedHeaders:i=!0,exposeHeaders:a=!0,credentials:l=!0,maxAge:c=5,preflight:u=!0}=t??{};if(Array.isArray(i))i=i.join(", ");if(Array.isArray(a))a=a.join(", ");let f=typeof o==="boolean"?void 0:Array.isArray(o)?o:[o],m=new E({name:"@elysiajs/cors",seed:t,aot:n}),_=f?.some((G)=>G==="*"),q={};if(f){for(let G of f)if(typeof G==="string")q[G]=!0}let Z=(G,x,p)=>{if(Array.isArray(G))return G.some((j)=>Z(j,x,p));switch(typeof G){case"string":if(p in q)return!0;let j=p.indexOf("://");if(j!==-1)p=p.slice(j+3);return G===p;case"function":return G(x)===!0;case"object":if(G instanceof RegExp)return G.test(p)}return!1},g=(G,x)=>{if(o===!0){G.headers.vary="*",G.headers["access-control-allow-origin"]=x.headers.get("Origin")||"*";return}if(_){G.headers.vary="*",G.headers["access-control-allow-origin"]="*";return}if(!f?.length)return;if(f.length){let p=x.headers.get("Origin")??"";for(let j=0;j<f.length;j++)if(Z(f[j],x,p)===!0){G.headers.vary=o?"Origin":"*",G.headers["access-control-allow-origin"]=p||"*";return}}G.headers.vary="Origin"},S=(G,x)=>{if(!x)return;if(s===!0)return G.headers["access-control-allow-methods"]=x??"*";if(s===!1||!s?.length)return;if(s==="*")return G.headers["access-control-allow-methods"]="*";if(!Array.isArray(s))return G.headers["access-control-allow-methods"]=s;G.headers["access-control-allow-methods"]=s.join(", ")},A={};if(typeof a==="string")A["access-control-expose-headers"]=a;if(typeof i==="string")A["access-control-allow-headers"]=i;if(l===!0)A["access-control-allow-credentials"]="true";m.headers(A);function ne({set:G,request:x,headers:p}){if(g(G,x),S(G,x.headers.get("access-control-request-method")),i===!0||a===!0){if(i===!0)G.headers["access-control-allow-headers"]=p["access-control-request-headers"];if(a===!0)G.headers["access-control-expose-headers"]=Object.keys(p).join(",")}if(c)G.headers["access-control-max-age"]=c.toString();return new Response(null,{status:204})}if(u)m.options("/",ne).options("/*",ne);return m.onRequest(function({set:x,request:p}){if(g(x,p),u&&p.method==="OPTIONS")return ne({set:x,request:p,headers:Tr?p.headers.toJSON():Object.fromEntries(p.headers.entries())});if(S(x,p.method),i===!0||a===!0){let j=qn(p.headers);if(i===!0)x.headers["access-control-allow-headers"]=j;if(a===!0)x.headers["access-control-expose-headers"]=j}})};var Kn="/code-server";function Dr(t,n,o=qe){let s=t.method.toUpperCase();if(s!=="GET"&&s!=="HEAD")return null;let i=new URL(t.url),a=i.searchParams.get("vt");if(!a||!o(a,Kn,"GET"))return null;i.searchParams.delete("vt");let l=new Headers(t.headers);return l.set("x-agent-api-key",n()),new Request(`${i.origin}${i.pathname}${i.search}`,{method:t.method,headers:l})}import{createHash as _r}from"crypto";var $e="idempotency",Wn=300000,Mr=1e4,At=new Map;function Jn(t,n,o,s){return _r("sha256").update(`${t}|${n}|${o}|${s}`).digest("hex")}async function Yn(t,n){let o=await t.getPluginState($e,n);if(!o)return null;try{let s=JSON.parse(o);if(s.expiresAt<Date.now())return await t.deletePluginState($e,n),null;return s}catch{return null}}async function Xn(t,n,o){await t.setPluginState($e,n,JSON.stringify(o))}async function Qn(t){let n=await t.getAllPluginState($e),o=Date.now(),s=0,i=[];for(let a of n)try{if(JSON.parse(a.value).expiresAt<o)await t.deletePluginState($e,a.key),s+=1;else i.push({key:a.key,updatedAt:a.updatedAt})}catch{await t.deletePluginState($e,a.key),s+=1}if(i.length>Mr){i.sort((l,c)=>(l.updatedAt??"").localeCompare(c.updatedAt??""));let a=i.slice(0,i.length-Mr);for(let l of a)await t.deletePluginState($e,l.key),s+=1}if(s>0)e().logger.info("idempotency",`Swept ${s} expired/over-cap entries`)}var qt=null,Zn=600000;function eo(t){if(qt)return;qt=setInterval(()=>{let n=t.getDb();if(!n)return;Qn(n).catch((o)=>{e().logger.warn("idempotency","Sweep failed",{error:String(o)})})},Zn),qt.unref?.()}function Br(t){return eo(t),new E({name:"plugin/idempotency"}).onBeforeHandle(async({request:n,path:o,set:s,store:i})=>{if(n.method!=="POST"&&n.method!=="PUT")return;let a=n.headers.get("x-idempotency-key")??n.headers.get("X-Idempotency-Key");if(!a)return;if(a.length<8||a.length>200)return s.status=400,{error:"X-Idempotency-Key must be 8\u2013200 chars",code:"BAD_REQUEST"};let l=t.getDb();if(!l)return;let c="no-body";try{let S=await n.clone().text();c=_r("sha256").update(S).digest("hex")}catch{}let u=Jn(n.method,o,a,c),f=await Yn(l,u);if(f){s.status=f.status;let g=s.headers??={};g["Content-Type"]=f.contentType,g["X-Idempotency-Replay"]="true",i.__idemReplay=f.body;try{return JSON.parse(f.body)}catch{return f.body}}let m=At.get(u);if(m){let g=await m.catch(()=>null);if(g){s.status=g.status;let S=s.headers??={};S["Content-Type"]=g.contentType,S["X-Idempotency-Replay"]="true",i.__idemReplay=g.body;try{return JSON.parse(g.body)}catch{return g.body}}}let _,q,Z=new Promise((g,S)=>{_=g,q=S});At.set(u,Z),i.__idemKey=u,i.__idemResolve=_,i.__idemReject=q}).onAfterHandle(async({response:n,set:o,store:s})=>{let i=s.__idemKey;if(!i)return;let a=s.__idemResolve,l=t.getDb(),c=o.status??200,u=typeof n==="string"?n:JSON.stringify(n),m=o.headers?.["Content-Type"]??"application/json",_={status:c,body:u,contentType:m,expiresAt:Date.now()+Wn},q=c>=200&&c<300;try{if(l&&q)await Xn(l,i,_)}catch(Z){e().logger.warn("idempotency","Failed to persist response",{error:String(Z)})}finally{try{a?.(q?_:null)}catch{}At.delete(i)}}).onError(({store:n})=>{let o=n.__idemKey;if(!o)return;let s=n.__idemReject;try{s?.(Error("idempotency: handler errored"))}catch{}At.delete(o)}).as("global")}import ue from"os";import{readFileSync as fo}from"fs";import{join as mo}from"path";import{randomBytes as to,timingSafeEqual as ro}from"crypto";import{chmodSync as no,existsSync as Lr,mkdirSync as oo,readFileSync as ao,unlinkSync as io,writeFileSync as so}from"fs";import{dirname as lo,join as co}from"path";var Ne=null;function Fr(){return co(I(),"pairing-token")}function uo(){return to(32).toString("base64url")}function go(t,n){let o=Buffer.from(t),s=Buffer.from(n);if(o.length!==s.length)return!1;try{return ro(o,s)}catch{return!1}}function gi(){if(Ne)return Ne;let t=Fr();try{if(Lr(t)){let o=ao(t,"utf8").trim();if(o.length>=32)return Ne=o,o}}catch{}let n=uo();try{oo(lo(t),{recursive:!0}),so(t,n,{encoding:"utf8"});try{no(t,384)}catch{}}catch(o){}return Ne=n,n}function Kt(t){if(!t)return!1;if(!Ne)return!1;return go(t,Ne)}function zt(){Ne=null;try{let t=Fr();if(Lr(t))io(t)}catch{}}function Jt(t){return t["x-pairing-token"]??t["X-Pairing-Token"]??null}var ut=null,ct=null,po=30000;function Qt(t,n={}){if(n.isBootProfile===!1){Vr();return}if(t.globalGatewayUrl)process.env.VIBE_GLOBAL_GATEWAY_URL=t.globalGatewayUrl;if(t.workspaceGatewayUrl)process.env.VIBE_WORKSPACE_GATEWAY_URL=t.workspaceGatewayUrl;if(t.workspaceId)process.env.VIBE_WORKSPACE_ID=t.workspaceId;if(t.organizationId)process.env.VIBE_ORGANIZATION_ID=t.organizationId;Vr()}function Vr(){ut=null}async function Kr(){if(ut&&Date.now()-ut.at<po)return ut.result;if(ct)return ct;return ct=(async()=>{let t;try{let n=await X({strict:!0}),o=si(n,{workspaceId:process.env.VIBE_WORKSPACE_ID,globalGatewayUrl:process.env.VIBE_GLOBAL_GATEWAY_URL,workspaceGatewayUrl:process.env.VIBE_WORKSPACE_GATEWAY_URL});t=o?{ok:!1,message:o}:{ok:!0}}catch(n){t={ok:!0,message:`identity check skipped: ${n instanceof Error?n.message:String(n)}`}}return ut={at:Date.now(),result:t},t})().finally(()=>{ct=null}),ct}function rr(){let t=B();return!t||t.name===e().name}function yo(){let t=ue.hostname(),n=ue.platform(),o=ue.arch(),s=new Bun.CryptoHasher("sha256");return s.update(`${t}-${n}-${o}`),s.digest("hex").substring(0,16)}function ho(){for(let t of["..","../.."])try{let n=mo(import.meta.dir,t,"package.json"),s=JSON.parse(fo(n,"utf8")).version;if(s)return s}catch{}return"0.0.0"}async function wo(t){let n=[],o=t.getProvider("tunnel");if(o)n.push(o);for(let s of t.listProvidersForType("tunnel")){let i=t.getProviderByName("tunnel",s.pluginName);if(i&&!n.includes(i))n.push(i)}for(let s of n){if(!s.getActiveTunnelUrl)continue;let i=await s.getActiveTunnelUrl();if(i)return i}return null}function Wr({serviceRegistry:t,runFinalize:n,getDb:o}){let s=ho(),i=yo();return new E({prefix:"/api/agent"}).get("/identity",()=>({hostname:ue.hostname(),platform:ue.platform(),architecture:ue.arch(),agentVersion:s,agentInstanceId:ri()})).get("/version",()=>({version:s,runtime:"bun",runtimeVersion:typeof Bun<"u"?Bun.version:"unknown"})).get("/api-key",({request:a,set:l})=>{if(Ve(a))return l.status=403,{error:"Forbidden",message:"Browser requests are not permitted on /api/agent/api-key"};let c=L(Object.fromEntries(a.headers.entries()));if(!V(c))return l.status=401,{error:"Unauthorized",message:"Invalid or missing API key"};return{apiKey:K()}}).post("/iframe-token",({body:a,request:l,set:c})=>{let u=L(Object.fromEntries(l.headers.entries()));if(!V(u))return c.status=401,{error:"Unauthorized",message:"Invalid or missing API key"};try{if(Array.isArray(a.pathPrefixes)&&a.pathPrefixes.length>0)return Ut({pathPrefixes:a.pathPrefixes,methods:a.methods},a.ttlSeconds??void 0);if(!a.pathPrefix)return c.status=400,{error:"BadRequest",message:"Provide either pathPrefix (string) or pathPrefixes (string[])"};return fr(a.pathPrefix,a.ttlSeconds??void 0)}catch(f){return c.status=400,{error:"BadRequest",message:f instanceof Error?f.message:String(f)}}},{body:r.Object({pathPrefix:r.Optional(r.String({minLength:1})),pathPrefixes:r.Optional(r.Array(r.String({minLength:1}),{minItems:1,maxItems:16})),methods:r.Optional(r.Array(r.String({minLength:1}),{minItems:1,maxItems:8})),ttlSeconds:r.Optional(r.Number())})}).post("/terminal-exchange",({body:a,set:l})=>{let{sid:c,token:u}=a;if(!c||!u)return l.status=400,{error:"BadRequest",message:"sid and token required"};if(!we(c))return l.status=400,{error:"BadRequest",message:"invalid sid"};let f=`/terminal/${c}`,m=Hr(u,f);if(!m.ok)return e().logger.warn("terminal-exchange","iframe token rejected",{sid:c,reason:m.reason}),l.status=401,{error:"Unauthorized",message:"invalid iframe token",code:m.reason==="expired"?"expired":m.reason==="replayed"?"replayed":"invalid"};let _=Li(c,600),q=`vt_term_${c}`;return l.headers["set-cookie"]=`${q}=${_.token}; HttpOnly; Secure; SameSite=None; Path=/terminal/${c}; Max-Age=600`,l.status=204,null},{body:r.Object({sid:r.String({minLength:1}),token:r.String({minLength:1})})}).post("/ui-exchange",({body:a,set:l})=>{let{plugin:c,token:u}=a;if(!c||!u)return l.status=400,{error:"BadRequest",message:"plugin and token required"};if(!me(c))return l.status=400,{error:"BadRequest",message:"invalid plugin name"};let f=`/ui/${c}`;if(!je(u,f))return l.status=401,{error:"Unauthorized",message:"invalid iframe token"};let m=yt(c,600),_=`vt_ui_${c}`;return l.headers["set-cookie"]=`${_}=${m.token}; HttpOnly; Secure; SameSite=None; Path=/ui/${c}/; Max-Age=600`,l.status=204,null},{body:r.Object({plugin:r.String({minLength:1}),token:r.String({minLength:1})})}).post("/ui-exchange-plugin",({body:a,set:l})=>{let{plugin:c,token:u}=a;if(!c||!u)return l.status=400,{error:"BadRequest",message:"plugin and token required"};if(!me(c))return l.status=400,{error:"BadRequest",message:"invalid plugin name"};if(![`/api/plugins/${c}/ui`,`/${c}`].find((Z)=>je(u,Z)))return l.status=401,{error:"Unauthorized",message:"invalid iframe token"};let _=yt(c,600),q=`vt_ui_${c}`;return l.headers["set-cookie"]=`${q}=${_.token}; HttpOnly; Secure; SameSite=None; Path=/api/plugins/${c}/ui/; Max-Age=600`,l.status=204,null},{body:r.Object({plugin:r.String({minLength:1}),token:r.String({minLength:1})})}).get("/system",({request:a,set:l})=>{let c=L(Object.fromEntries(a.headers.entries()));if(!V(c))return l.status=401,{error:"Unauthorized",message:"Invalid or missing API key"};return{machineId:i,hostname:ue.hostname(),platform:ue.platform(),arch:ue.arch(),release:ue.release(),cpus:ue.cpus().length,totalMemory:ue.totalmem(),freeMemory:ue.freemem(),uptime:ue.uptime(),bunVersion:typeof Bun<"u"?Bun.version:void 0,agentVersion:s,homeDir:ue.homedir(),cwd:process.cwd(),environment:"production"}}).get("/tunnel",async({request:a,set:l})=>{let c=Object.fromEntries(a.headers.entries()),u=V(L(c)),f=Kt(Jt(c));if(!u&&!f)return l.status=401,{error:"Unauthorized",message:"Provide x-agent-api-key OR x-pairing-token to read tunnel URL"};let m=await wo(t);if(!m)return{tunnelUrl:null,message:"No tunnel provider registered"};return{tunnelUrl:m}}).get("/status",()=>{let a=["tunnel","session","ai"].filter((l)=>t.hasProvider(l));return{state:e().getBootState(),status:e().getBootState(),version:s,providers:a,timestamp:new Date().toISOString()}}).get("/gateway-auth",()=>({configured:T.isConfigured(),config:k(T.getConfig()),state:e().getBootState()})).post("/retry-config",async({set:a})=>{let{getFinalizeRetryHandle:l}=await import("./finalize-retry-handle-registry-z9mbbjmj.js"),c=l();if(!c)return a.status=409,{ok:!1,error:"No finalize retry worker is active. The agent either never had cached credentials to retry with, or it already reached the ready state."};let u=await c.forceRetryNow();if(!u.ok)a.status=503;return{ok:u.ok,error:u.ok?void 0:u.error,state:e().getBootState(),worker:c.getState()}}).post("/gateway-auth",async({body:a,request:l,set:c})=>{let u=e().getBootState(),f=Object.fromEntries(l.headers.entries());if(u==="ready"){let p=L(f);if(!V(p))return c.status=401,{success:!1,state:u,error:"Unauthorized: API key required to reconfigure"}}else{let p=L(f),j=Jt(f),J=V(p),re=Kt(j);if(!J&&!re)return c.status=401,{success:!1,state:u,error:"Unauthorized: provide x-agent-api-key OR x-pairing-token for bootstrap"}}let{clientId:m,clientSecret:_,workspaceId:q,globalGatewayUrl:Z,workspaceGatewayUrl:g}=a;if(!m||!_||!q||!Z||!g)return c.status=400,{success:!1,state:e().getBootState(),error:"clientId, clientSecret, workspaceId, globalGatewayUrl, and workspaceGatewayUrl are required"};let S,A;try{S=z(Z,"globalGatewayUrl"),A=z(g,"workspaceGatewayUrl")}catch(p){return c.status=400,{success:!1,state:e().getBootState(),error:p instanceof Error?p.message:String(p)}}let ne,G=await he("gateway-auth:push",async()=>{let p=B()??e();{let J;try{J=await X({dir:p.dataDir,scope:p.name,strict:!0})}catch(le){let De=le instanceof Error?le.message:String(le);return e().logger.error("preconfig","Could not read existing credentials \u2014 refusing the push rather than risk overwriting a live pairing",{error:De}),c.status=503,{success:!1,state:e().getBootState(),error:`Cannot verify this agent's current pairing (secrets backend unavailable: ${De}). Refusing the credential push so a live pairing is not overwritten. Retry once the secrets backend recovers.`,code:"IDENTITY_CHECK_UNAVAILABLE"}}let re=ii(J,{workspaceId:q,globalGatewayUrl:S,workspaceGatewayUrl:A});if(re&&a.force!==!0)return e().logger.warn("preconfig","Rejected a gateway-auth push that would hijack this agent's identity",{conflict:re}),c.status=409,{success:!1,state:e().getBootState(),error:re,code:"GATEWAY_IDENTITY_CONFLICT"};if(re)e().logger.warn("preconfig","Forced re-pair \u2014 overwriting an existing gateway identity",{conflict:re})}let j=null;{let J=rr()?ye():p.name,re;try{re=zr(J)}catch(de){let Me=de instanceof Error?de.message:String(de);return e().logger.error("preconfig",`Could not read profile "${J}" \u2014 refusing the push rather than assume it declares nothing`,{error:Me}),c.status=503,{success:!1,state:e().getBootState(),error:`Cannot read profile "${J}" to verify this push targets the right environment (${Me}). Refusing the credential push so a foreign environment is not accepted by default. Repair or remove the profile file and retry.`,code:"PROFILE_CHECK_UNAVAILABLE"}}let le=oi(),De={globalGatewayUrl:le.globalGatewayUrl??re.globalGatewayUrl,workspaceGatewayUrl:le.workspaceGatewayUrl??re.workspaceGatewayUrl},ae=ni(De,{workspaceId:q,globalGatewayUrl:S,workspaceGatewayUrl:A},J);if(ae&&a.force!==!0)return e().logger.warn("preconfig","Rejected a gateway-auth push that contradicts the active profile",{profileConflict:ae}),c.status=409,{success:!1,state:e().getBootState(),error:ae,code:"PROFILE_ENVIRONMENT_CONFLICT"};if(ae)j={name:J,cfg:{...re,globalGatewayUrl:S,workspaceGatewayUrl:A,workspaceId:void 0}},e().logger.warn("preconfig",`Forced repoint accepted \u2014 profile "${J}" will be updated to match the pushed environment`,{profileConflict:ae})}try{await Yt({clientId:m,clientSecret:_,workspaceId:q,ownerUserId:a.ownerUserId,organizationId:a.organizationId,globalGatewayUrl:S,workspaceGatewayUrl:A,agentRecordId:a.agentRecordId,scopes:a.scopes,pairedIdentity:Zt({workspaceId:q,globalGatewayUrl:S,workspaceGatewayUrl:A,agentRecordId:a.agentRecordId}),...a.storageAdapter?{storageAdapter:a.storageAdapter}:{},...a.storageOptions?{storageOptions:a.storageOptions}:{},...a.dbPath?{dbPath:a.dbPath}:{}},{dir:p.dataDir,scope:p.name})}catch(J){return c.status=500,{success:!1,state:e().getBootState(),error:`Failed to persist gateway credentials to secrets backend: ${J instanceof Error?J.message:String(J)}`}}if(j)try{nt(j.name,j.cfg),e().logger.warn("preconfig",`Profile "${j.name}" repointed to the pushed environment`)}catch(J){let re=J instanceof Error?J.message:String(J);ne=`Credentials were accepted, but profile "${j.name}" could not be updated (${re}). It still describes the previous environment \u2014 `+"run `vibe profile use` / fix the profile file so config and profile agree.",e().logger.error("preconfig",`Forced repoint accepted but profile "${j.name}" could not be updated \u2014 profile and config.json now disagree`,{error:re})}return null});if(G)return G;let x=e().getBootState();if(x==="ready"){let p=o();if(p){if(await p.setConfig("gateway-auth:clientId",m),await p.setConfig("gateway-auth:clientSecret",_),await p.setConfig("gateway-auth:workspaceId",q),a.organizationId)await p.setConfig("gateway-auth:organizationId",a.organizationId);if(await p.setConfig("gateway-auth:globalGatewayUrl",S),await p.setConfig("gateway-auth:workspaceGatewayUrl",A),a.agentRecordId)await p.setConfig("gateway-auth:agentRecordId",a.agentRecordId)}T.configure({globalGatewayUrl:S,workspaceGatewayUrl:A,clientId:m,clientSecret:_,workspaceId:q,organizationId:a.organizationId}),Qt({workspaceId:q,organizationId:a.organizationId,globalGatewayUrl:S,workspaceGatewayUrl:A},{isBootProfile:rr()}),e().logger.info("preconfig","Gateway credentials re-configured (agent was already ready)");let j=!!(a.storageAdapter||a.storageOptions||a.dbPath);return{success:!0,state:x,message:j?"Gateway auth re-configured. Restart the agent (vibe restart) to apply the new storage configuration.":"Gateway auth re-configured",...ne?{warning:ne}:{}}}return e().logger.info("preconfig","Gateway credentials received \u2014 beginning finalize (background)"),zt(),Qt({workspaceId:q,organizationId:a.organizationId,globalGatewayUrl:S,workspaceGatewayUrl:A},{isBootProfile:rr()}),n({clientId:m,clientSecret:_,workspaceId:q,organizationId:a.organizationId,globalGatewayUrl:S,workspaceGatewayUrl:A},{agentRecordId:a.agentRecordId,scopes:a.scopes}).catch((p)=>{e().logger.error("preconfig","Background finalize threw",{error:p instanceof Error?p.message:String(p)})}),c.status=202,{success:!0,state:e().getBootState(),agentRecordId:a.agentRecordId,message:"Gateway credentials accepted; finalize is running in the background. Poll /health/ready for completion.",...ne?{warning:ne}:{}}},{body:r.Object({clientId:r.Optional(r.String()),clientSecret:r.Optional(r.String()),workspaceId:r.Optional(r.String()),ownerUserId:r.Optional(r.String()),organizationId:r.Optional(r.String()),globalGatewayUrl:r.Optional(r.String()),workspaceGatewayUrl:r.Optional(r.String()),scopes:r.Optional(r.Array(r.String())),agentRecordId:r.Optional(r.String()),storageAdapter:r.Optional(r.String()),storageOptions:r.Optional(r.Record(r.String(),r.String())),dbPath:r.Optional(r.String()),force:r.Optional(r.Boolean())})})}import{existsSync as Te,mkdirSync as bo,rmSync as Jr,readdirSync as Xr}from"fs";import{join as It}from"path";function Ae(t){return It(C(),"agents",O(t))}function So(){let t=It(C(),"agents");if(!Te(t))return[];return Xr(t,{withFileTypes:!0}).filter((n)=>n.isDirectory()).map((n)=>n.name).filter((n)=>/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(n))}function Zr(t){return It(C(),"agents",O(t))}function nr(t){return w({dir:Zr(t)})}function Yr(t,n){return M(n,{dir:Zr(t),scope:O(t)})}function He(t){let n=Oe(),o=bt().find((a)=>a.name===t),s=N.get(t),i={name:t,isDefault:t===n,isRunning:o?.status==="running",attached:s!==void 0,bootState:s?s.getBootState():null,dataDir:s?s.dataDir:null};if(o)i.port=o.port,i.pid=o.pid,i.startTime=o.startTime;if(Te(Ae(t)))i.config=k(nr(t));return i}function en(t={}){let n=t.serviceManagerFactory?t.serviceManagerFactory():new D;return new E({prefix:"/api/profiles"}).get("/",()=>{let o=So(),s=Oe(),i=new Set(o);return i.add(s),[...i].sort().map((a)=>He(a))}).post("/",async({body:o,set:s})=>{try{let i=O(o.name),a=Ae(i);if(Te(a))return s.status=409,{error:"exists",message:`Profile '${i}' already exists.`};let l;if(o.copyFrom){let c=O(o.copyFrom);if(!Te(Ae(c)))return s.status=400,{error:"copy-source-missing",message:`Profile '${c}' does not exist.`};l=nr(c),delete l["static-api-key"],delete l.agentRecordId,delete l.apiKeys,delete l.pairedIdentity,delete l.workspaceId,delete l.organizationId}else l=ti();if(o.gatewayUrl)l.globalGatewayUrl=o.gatewayUrl;if(o.workspaceGatewayUrl)l.workspaceGatewayUrl=o.workspaceGatewayUrl;if(o.clientId)l.clientId=o.clientId;if(o.clientSecret)l.clientSecret=o.clientSecret;if(o.workspaceId)l.workspaceId=o.workspaceId;if(o.organizationId)l.organizationId=o.organizationId;bo(a,{recursive:!0}),Yr(i,l);try{at(i)}catch(c){e().logger.warn("profile-mgmt",`In-process attach failed for '${i}'`,{error:String(c)})}if(e().logger.info("profile-mgmt",`Created profile '${i}' at ${a}`),o.start){let c={name:i,port:o.port??0,daemon:!0,dbPath:ee(),profile:i};await n.startDaemon(c)}return s.status=201,He(i)}catch(i){return s.status=400,{error:"create-failed",message:i instanceof Error?i.message:String(i)}}},{body:r.Object({name:r.String(),gatewayUrl:r.Optional(r.String()),workspaceGatewayUrl:r.Optional(r.String()),clientId:r.Optional(r.String()),clientSecret:r.Optional(r.String()),workspaceId:r.Optional(r.String()),organizationId:r.Optional(r.String()),copyFrom:r.Optional(r.String()),start:r.Optional(r.Boolean()),port:r.Optional(r.Number())})}).get("/:name",({params:o,set:s})=>{try{let i=O(o.name);if(!Te(Ae(i)))return s.status=404,{error:"not-found",message:`No profile '${i}'.`};return He(i)}catch(i){return s.status=400,{error:"bad-request",message:i instanceof Error?i.message:String(i)}}},{params:r.Object({name:r.String()})}).put("/:name",({params:o,body:s,set:i})=>{try{let a=O(o.name);if(!Te(Ae(a)))return i.status=404,{error:"not-found",message:`No profile '${a}'.`};let l=["static-api-key","apiKeys","agentRecordId","pairedIdentity"];for(let f of l)if(f in s)return i.status=400,{error:"forbidden-field",message:`Field '${f}' is managed via dedicated commands (vibe key rotate / vibe profile create). It cannot be patched here.`};if("registry"in s)return i.status=400,{error:"forbidden-field",message:"Field 'registry' cannot be patched via this endpoint. Use POST /api/agent/registry with operator confirmation (VIBE_ALLOW_REGISTRY_CHANGE=1) so the change is auditable."};let u={...nr(a),...s};return Yr(a,u),He(a)}catch(a){return i.status=400,{error:"update-failed",message:a instanceof Error?a.message:String(a)}}},{params:r.Object({name:r.String()}),body:r.Record(r.String(),r.Any())}).delete("/:name",async({params:o,body:s,query:i,set:a})=>{try{let l=O(o.name);if(l===Oe())return a.status=409,{error:"is-default",message:`Cannot delete active default profile '${l}'. Switch to another profile first.`};let c=i?.purge==="true"||i?.purge==="1",u=Te(Ae(l)),f=N.has(l);if(!u&&!f)return a.status=404,{error:"not-found",message:`No profile '${l}'.`};if(u&&!c&&!s?.confirm)return a.status=400,{error:"confirm-required",message:"Pass { confirm: true } in the body or `?purge=true` in the query to delete the on-disk dataDir (destructive)."};try{await n.stop(l)}catch{}try{await N.destroy(l)}catch(m){e().logger.warn("profile-mgmt",`In-process detach failed for '${l}'`,{error:String(m)})}if(u)if(s?.keepConfig)for(let m of Xr(Ae(l))){if(m==="config.json")continue;Jr(It(Ae(l),m),{recursive:!0,force:!0})}else Jr(Ae(l),{recursive:!0,force:!0});return e().logger.info("profile-mgmt",`Deleted profile '${l}'`),{ok:!0,deleted:l,keptConfig:!!s?.keepConfig,detached:f,purged:u}}catch(l){return a.status=400,{error:"delete-failed",message:l instanceof Error?l.message:String(l)}}},{params:r.Object({name:r.String()}),query:r.Optional(r.Object({purge:r.Optional(r.String())})),body:r.Optional(r.Object({confirm:r.Optional(r.Boolean()),keepConfig:r.Optional(r.Boolean())}))}).post("/:name/switch",async({params:o,set:s})=>{try{let i=O(o.name);if(!Te(Ae(i)))return s.status=404,{error:"not-found",message:`No profile '${i}'.`};return await ot(()=>Xt(i)),e().logger.info("profile-mgmt",`Default profile switched to '${i}'`),{ok:!0,defaultProfile:i}}catch(i){return s.status=400,{error:"switch-failed",message:i instanceof Error?i.message:String(i)}}},{params:r.Object({name:r.String()})}).post("/:name/start",async({params:o,body:s,set:i})=>{try{let a=O(o.name);if(!Te(Ae(a)))return i.status=404,{error:"not-found",message:`No profile '${a}'.`};try{at(a)}catch(c){e().logger.warn("profile-mgmt",`In-process attach failed for '${a}'`,{error:String(c)})}if(!bt().some((c)=>c.name===a&&c.status==="running")){let c={name:a,port:s?.port??0,daemon:!0,dbPath:ee(),profile:a};await n.startDaemon(c)}return He(a)}catch(a){return i.status=500,{error:"start-failed",message:a instanceof Error?a.message:String(a)}}},{params:r.Object({name:r.String()}),body:r.Optional(r.Object({port:r.Optional(r.Number())}))}).post("/:name/stop",async({params:o,set:s})=>{try{let i=O(o.name);try{await n.stop(i)}catch{}try{await N.destroy(i)}catch(a){e().logger.warn("profile-mgmt",`In-process detach failed for '${i}'`,{error:String(a)})}return He(i)}catch(i){return s.status=500,{error:"stop-failed",message:i instanceof Error?i.message:String(i)}}},{params:r.Object({name:r.String()})})}function vo(){let t=process.memoryUsage(),n=process.resourceUsage(),o=n.userCPUTime/1000,s=n.systemCPUTime/1000,i=o+s,a=N.list().map((l)=>{let c;try{c=qr(l.spawnOwnerKey).length}catch{c=0}return{name:l.name,status:l.getBootState(),childPidCount:c,cpuMs:i,heapBytes:t.heapUsed,dataDir:l.dataDir}});return{process:{pid:process.pid,uptimeSeconds:process.uptime(),cpuUserMs:o,cpuSystemMs:s,heapUsedBytes:t.heapUsed,heapTotalBytes:t.heapTotal,rssBytes:t.rss},profiles:a,notes:{perProfileCpu:"deferred",perProfileHeap:"deferred"}}}function tn(){return new E({prefix:"/api/profile-stats"}).get("/",()=>vo())}function St(t,n){return Promise.race([t,new Promise((o,s)=>setTimeout(()=>s(Error(`timeout after ${n}ms`)),n))])}function ko(t){let n=t instanceof Error?t.message:String(t);return/ENOENT/.test(n)||/no such file or directory/i.test(n)}async function rn(t){let o=`__health__:probe:${typeof crypto<"u"&&typeof crypto.randomUUID==="function"?crypto.randomUUID():`${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`}`,s=String(Date.now());if(await St(t.setConfig(o,s),2000),await St(t.getConfig(o),2000)!==s)throw Error("round-trip mismatch");try{await St(t.deleteConfig(o),500)}catch{}}async function Po(t,n){if(!t)return{ok:!1,message:"database not opened"};let o=performance.now();try{return await rn(t),{ok:!0,durationMs:performance.now()-o}}catch(s){if(n&&ko(s))try{let i=await import("fs");return i.mkdirSync(n,{recursive:!0}),await rn(t),{ok:!0,message:`recovered: dbPath ${n} was missing \u2014 recreated`,durationMs:performance.now()-o}}catch(i){return{ok:!1,message:`ENOENT on dbPath ${n}: ${i instanceof Error?i.message:String(i)}`,durationMs:performance.now()-o}}return{ok:!1,message:s instanceof Error?s.message:String(s),durationMs:performance.now()-o}}}async function Ro(t){if(process.env.AGENT_TUNNEL==="false")return{ok:!0,message:"tunnel disabled via AGENT_TUNNEL=false"};if(!t)return{ok:!1,message:"no service registry"};let n=t.getProvider("tunnel"),o=e().getBootState()==="awaiting-config";if(!n)return{ok:!1,message:o?"agent is awaiting-config \u2014 POST OAuth credentials to /api/agent/gateway-auth to register tunnel provider":"no tunnel provider registered"};if(!n.getActiveTunnelUrl)return{ok:!0,message:`provider: ${n.name}`};try{let s=await St(Promise.resolve(n.getActiveTunnelUrl()),2000),i=Wt(s);if(i)return{ok:!0,message:`provider: ${n.name} \u2014 ${i}`};if(s)return{ok:!1,message:`provider: ${n.name} \u2014 reported an unusable tunnel URL (${s})`};return{ok:!1,message:`provider: ${n.name} \u2014 no active tunnel (the agent is not reachable from outside; the provider is rebuilding it)`}}catch(s){return{ok:!1,message:`provider: ${n.name} \u2014 tunnel status unavailable: ${s instanceof Error?s.message:String(s)}`}}}function Ao(t,n){if(!t)return{ok:!1,message:"no service registry"};let s=e().getBootState()==="awaiting-config";if(n==="session"){let i=t.getProvider("session");if(i)return{ok:!0,message:`provider: ${i.name}`};return{ok:!1,message:s?"agent is awaiting-config \u2014 POST OAuth credentials to /api/agent/gateway-auth to register session provider":"no session provider registered"}}return{ok:!0}}async function Io(t){if(!t)return{};let n={};for(let o of t.getAllPlugins()){let s=o.getHealth;if(typeof s!=="function")continue;let i=performance.now();try{let a=await St(Promise.resolve(s.call(o)),2000);n[o.name]={ok:a?.ok!==!1,message:a?.message,durationMs:performance.now()-i}}catch(a){n[o.name]={ok:!1,message:a instanceof Error?a.message:String(a),durationMs:performance.now()-i}}}return n}function nn(t){let n=t&&"serviceRegistry"in t?t:{serviceRegistry:t};return new E({prefix:"/health"}).get("/",()=>({status:"ok",lifecycleState:n.serviceRegistry?.getService("agent","lifecycle")?.getState()??"running",bootState:e().getBootState(),timestamp:new Date().toISOString(),uptime:process.uptime()})).get("/live",()=>({status:"ok"})).get("/ready",async({set:o})=>{let i=n.serviceRegistry?.getService("agent","lifecycle")?.getState()??"running",a=e().getBootState(),l={};l.boot={ok:a==="ready",message:a==="ready"?void 0:`boot state ${a}`},l.lifecycle={ok:i==="running",message:i==="running"?void 0:`lifecycle ${i}`},l.db=await Po(n.getDb?.()??null,n.getDbPath?.()??null),l.tunnel=await Ro(n.serviceRegistry),l.session=Ao(n.serviceRegistry,"session"),l.identity=await Kr();try{let{gatewayClient:g}=await import("./gateway-client-3zp6kkav.js");if(!g.isConfigured())l.registration={ok:!0,message:"not configured"};else{let S=n.getDb?.()??null;if(S?await S.getConfig("gateway-auth:agentRecordId"):null)l.registration={ok:!0};else{let ne=e().getDegradedReasons().some((G)=>G.plugin==="agent-registration");l.registration=ne?{ok:!1,message:"agent failed to register with the workspace after retries"}:{ok:!0,message:"registering"}}}}catch(g){l.registration={ok:!0,message:`registration check skipped: ${g instanceof Error?g.message:String(g)}`}}let c=await Io(n.getPluginManager?.()??null),u=Object.values(l).every((g)=>g.ok)&&Object.values(c).every((g)=>g.ok);if(!u)o.status=503;let f=a==="degraded"?e().getDegradedReasons():[],m=e().name,_={};for(let g of N.list())_[g.name]={bootState:g.getBootState(),ok:g.getBootState()==="ready",degradedReasons:g.getDegradedReasons()};let q=e().getLastFinalizeError(),Z={status:u?"ok":"degraded",lifecycleState:i,bootState:a,daemon:{profile:m,bootState:a,ok:a==="ready"},profiles:_,components:l,plugins:c,degradedReasons:f,lastFinalizeError:q,timestamp:new Date().toISOString()};if(!u)e().logger.warn("health","Readiness probe failed",{components:l,plugins:c,bootState:a});return Z})}var Ot=0,on=0;function an(){return new E({name:"inflight-tracker"}).onRequest(()=>{Ot+=1}).onAfterResponse(()=>{Ot=Math.max(0,Ot-1),on+=1})}function sn(){return new E({prefix:"/api/stats"}).get("/inflight",()=>({inflight:Math.max(0,Ot-1),totalServed:on}))}var ln={enabled:!1,async scrape(){return`# vibecontrols agent metrics disabled (OTel SDK not initialised)
|
|
2
|
+
import{r,E}from"./index-1t74r13z.js";import{er,tr,Rt}from"./index-5tghd67e.js";import{Ai,Hi,Vi,Tt,z,Wt,Ir,T,he,ot,bt,Oe,Xt,R,O,I,ee,C,se,wt,B,N,e,at}from"./index-7wm4bqx5.js";import{Et,W}from"./index-8jk4a62x.js";import{hr,we,fr,Ut,je,Hr,qe,Li,me,yt,rt,it,Re,K,L,V,mr,Ui,Ki,Qi}from"./index-qzwbctkv.js";import{ye,zr,nt,ti,w,ri,M,Yt,X,Zt,ii,ni,si,oi}from"./index-j99tkngg.js";import{gr,Ni,dr,ki,Qe,pe,Qr,jr,Gr,_t,$r}from"./index-p7fbnfwd.js";import{Ze,te,or,Nr,ar,lt,Je,gt,kr,We,ke,Bt,Xe,Le,ze,et,dt,ht,ft,pt,mt,Pt,Mt,Dt,Se}from"./index-dr6rsnpk.js";import{wr,qr}from"./index-ednz6yz2.js";import{oe}from"./index-ppxayc0x.js";import{Rr}from"./index-bpzk441p.js";import{Ve,Or,_i,Pe}from"./index-zn9snqbg.js";import{D}from"./index-twtvt4yt.js";import{xe,Ie,vr,Oi,ve}from"./index-br9bakfm.js";import{b}from"./index-w4jqdhc2.js";import{k}from"./index-e5jdx9c1.js";import{P}from"./index-rae5bn1c.js";var Tr=typeof new Headers()?.toJSON==="function",qn=(t)=>{if(Tr)return Object.keys(t.toJSON()).join(", ");let n="",o=0;return t.forEach((s,i)=>{if(o)n=n+", "+i;else n=i;o++}),n},Ur=(t)=>{let{aot:n=!0,origin:o=!0,methods:s=!0,allowedHeaders:i=!0,exposeHeaders:a=!0,credentials:l=!0,maxAge:c=5,preflight:u=!0}=t??{};if(Array.isArray(i))i=i.join(", ");if(Array.isArray(a))a=a.join(", ");let f=typeof o==="boolean"?void 0:Array.isArray(o)?o:[o],m=new E({name:"@elysiajs/cors",seed:t,aot:n}),_=f?.some((G)=>G==="*"),q={};if(f){for(let G of f)if(typeof G==="string")q[G]=!0}let Z=(G,x,p)=>{if(Array.isArray(G))return G.some((j)=>Z(j,x,p));switch(typeof G){case"string":if(p in q)return!0;let j=p.indexOf("://");if(j!==-1)p=p.slice(j+3);return G===p;case"function":return G(x)===!0;case"object":if(G instanceof RegExp)return G.test(p)}return!1},g=(G,x)=>{if(o===!0){G.headers.vary="*",G.headers["access-control-allow-origin"]=x.headers.get("Origin")||"*";return}if(_){G.headers.vary="*",G.headers["access-control-allow-origin"]="*";return}if(!f?.length)return;if(f.length){let p=x.headers.get("Origin")??"";for(let j=0;j<f.length;j++)if(Z(f[j],x,p)===!0){G.headers.vary=o?"Origin":"*",G.headers["access-control-allow-origin"]=p||"*";return}}G.headers.vary="Origin"},S=(G,x)=>{if(!x)return;if(s===!0)return G.headers["access-control-allow-methods"]=x??"*";if(s===!1||!s?.length)return;if(s==="*")return G.headers["access-control-allow-methods"]="*";if(!Array.isArray(s))return G.headers["access-control-allow-methods"]=s;G.headers["access-control-allow-methods"]=s.join(", ")},A={};if(typeof a==="string")A["access-control-expose-headers"]=a;if(typeof i==="string")A["access-control-allow-headers"]=i;if(l===!0)A["access-control-allow-credentials"]="true";m.headers(A);function ne({set:G,request:x,headers:p}){if(g(G,x),S(G,x.headers.get("access-control-request-method")),i===!0||a===!0){if(i===!0)G.headers["access-control-allow-headers"]=p["access-control-request-headers"];if(a===!0)G.headers["access-control-expose-headers"]=Object.keys(p).join(",")}if(c)G.headers["access-control-max-age"]=c.toString();return new Response(null,{status:204})}if(u)m.options("/",ne).options("/*",ne);return m.onRequest(function({set:x,request:p}){if(g(x,p),u&&p.method==="OPTIONS")return ne({set:x,request:p,headers:Tr?p.headers.toJSON():Object.fromEntries(p.headers.entries())});if(S(x,p.method),i===!0||a===!0){let j=qn(p.headers);if(i===!0)x.headers["access-control-allow-headers"]=j;if(a===!0)x.headers["access-control-expose-headers"]=j}})};var Kn="/code-server";function Dr(t,n,o=qe){let s=t.method.toUpperCase();if(s!=="GET"&&s!=="HEAD")return null;let i=new URL(t.url),a=i.searchParams.get("vt");if(!a||!o(a,Kn,"GET"))return null;i.searchParams.delete("vt");let l=new Headers(t.headers);return l.set("x-agent-api-key",n()),new Request(`${i.origin}${i.pathname}${i.search}`,{method:t.method,headers:l})}import{createHash as _r}from"crypto";var $e="idempotency",Wn=300000,Mr=1e4,At=new Map;function Jn(t,n,o,s){return _r("sha256").update(`${t}|${n}|${o}|${s}`).digest("hex")}async function Yn(t,n){let o=await t.getPluginState($e,n);if(!o)return null;try{let s=JSON.parse(o);if(s.expiresAt<Date.now())return await t.deletePluginState($e,n),null;return s}catch{return null}}async function Xn(t,n,o){await t.setPluginState($e,n,JSON.stringify(o))}async function Qn(t){let n=await t.getAllPluginState($e),o=Date.now(),s=0,i=[];for(let a of n)try{if(JSON.parse(a.value).expiresAt<o)await t.deletePluginState($e,a.key),s+=1;else i.push({key:a.key,updatedAt:a.updatedAt})}catch{await t.deletePluginState($e,a.key),s+=1}if(i.length>Mr){i.sort((l,c)=>(l.updatedAt??"").localeCompare(c.updatedAt??""));let a=i.slice(0,i.length-Mr);for(let l of a)await t.deletePluginState($e,l.key),s+=1}if(s>0)e().logger.info("idempotency",`Swept ${s} expired/over-cap entries`)}var qt=null,Zn=600000;function eo(t){if(qt)return;qt=setInterval(()=>{let n=t.getDb();if(!n)return;Qn(n).catch((o)=>{e().logger.warn("idempotency","Sweep failed",{error:String(o)})})},Zn),qt.unref?.()}function Br(t){return eo(t),new E({name:"plugin/idempotency"}).onBeforeHandle(async({request:n,path:o,set:s,store:i})=>{if(n.method!=="POST"&&n.method!=="PUT")return;let a=n.headers.get("x-idempotency-key")??n.headers.get("X-Idempotency-Key");if(!a)return;if(a.length<8||a.length>200)return s.status=400,{error:"X-Idempotency-Key must be 8\u2013200 chars",code:"BAD_REQUEST"};let l=t.getDb();if(!l)return;let c="no-body";try{let S=await n.clone().text();c=_r("sha256").update(S).digest("hex")}catch{}let u=Jn(n.method,o,a,c),f=await Yn(l,u);if(f){s.status=f.status;let g=s.headers??={};g["Content-Type"]=f.contentType,g["X-Idempotency-Replay"]="true",i.__idemReplay=f.body;try{return JSON.parse(f.body)}catch{return f.body}}let m=At.get(u);if(m){let g=await m.catch(()=>null);if(g){s.status=g.status;let S=s.headers??={};S["Content-Type"]=g.contentType,S["X-Idempotency-Replay"]="true",i.__idemReplay=g.body;try{return JSON.parse(g.body)}catch{return g.body}}}let _,q,Z=new Promise((g,S)=>{_=g,q=S});At.set(u,Z),i.__idemKey=u,i.__idemResolve=_,i.__idemReject=q}).onAfterHandle(async({response:n,set:o,store:s})=>{let i=s.__idemKey;if(!i)return;let a=s.__idemResolve,l=t.getDb(),c=o.status??200,u=typeof n==="string"?n:JSON.stringify(n),m=o.headers?.["Content-Type"]??"application/json",_={status:c,body:u,contentType:m,expiresAt:Date.now()+Wn},q=c>=200&&c<300;try{if(l&&q)await Xn(l,i,_)}catch(Z){e().logger.warn("idempotency","Failed to persist response",{error:String(Z)})}finally{try{a?.(q?_:null)}catch{}At.delete(i)}}).onError(({store:n})=>{let o=n.__idemKey;if(!o)return;let s=n.__idemReject;try{s?.(Error("idempotency: handler errored"))}catch{}At.delete(o)}).as("global")}import ue from"os";import{readFileSync as fo}from"fs";import{join as mo}from"path";import{randomBytes as to,timingSafeEqual as ro}from"crypto";import{chmodSync as no,existsSync as Lr,mkdirSync as oo,readFileSync as ao,unlinkSync as io,writeFileSync as so}from"fs";import{dirname as lo,join as co}from"path";var Ne=null;function Fr(){return co(I(),"pairing-token")}function uo(){return to(32).toString("base64url")}function go(t,n){let o=Buffer.from(t),s=Buffer.from(n);if(o.length!==s.length)return!1;try{return ro(o,s)}catch{return!1}}function gi(){if(Ne)return Ne;let t=Fr();try{if(Lr(t)){let o=ao(t,"utf8").trim();if(o.length>=32)return Ne=o,o}}catch{}let n=uo();try{oo(lo(t),{recursive:!0}),so(t,n,{encoding:"utf8"});try{no(t,384)}catch{}}catch(o){}return Ne=n,n}function Kt(t){if(!t)return!1;if(!Ne)return!1;return go(t,Ne)}function zt(){Ne=null;try{let t=Fr();if(Lr(t))io(t)}catch{}}function Jt(t){return t["x-pairing-token"]??t["X-Pairing-Token"]??null}var ut=null,ct=null,po=30000;function Qt(t,n={}){if(n.isBootProfile===!1){Vr();return}if(t.globalGatewayUrl)process.env.VIBE_GLOBAL_GATEWAY_URL=t.globalGatewayUrl;if(t.workspaceGatewayUrl)process.env.VIBE_WORKSPACE_GATEWAY_URL=t.workspaceGatewayUrl;if(t.workspaceId)process.env.VIBE_WORKSPACE_ID=t.workspaceId;if(t.organizationId)process.env.VIBE_ORGANIZATION_ID=t.organizationId;Vr()}function Vr(){ut=null}async function Kr(){if(ut&&Date.now()-ut.at<po)return ut.result;if(ct)return ct;return ct=(async()=>{let t;try{let n=await X({strict:!0}),o=si(n,{workspaceId:process.env.VIBE_WORKSPACE_ID,globalGatewayUrl:process.env.VIBE_GLOBAL_GATEWAY_URL,workspaceGatewayUrl:process.env.VIBE_WORKSPACE_GATEWAY_URL});t=o?{ok:!1,message:o}:{ok:!0}}catch(n){t={ok:!0,message:`identity check skipped: ${n instanceof Error?n.message:String(n)}`}}return ut={at:Date.now(),result:t},t})().finally(()=>{ct=null}),ct}function rr(){let t=B();return!t||t.name===e().name}function yo(){let t=ue.hostname(),n=ue.platform(),o=ue.arch(),s=new Bun.CryptoHasher("sha256");return s.update(`${t}-${n}-${o}`),s.digest("hex").substring(0,16)}function ho(){for(let t of["..","../.."])try{let n=mo(import.meta.dir,t,"package.json"),s=JSON.parse(fo(n,"utf8")).version;if(s)return s}catch{}return"0.0.0"}async function wo(t){let n=[],o=t.getProvider("tunnel");if(o)n.push(o);for(let s of t.listProvidersForType("tunnel")){let i=t.getProviderByName("tunnel",s.pluginName);if(i&&!n.includes(i))n.push(i)}for(let s of n){if(!s.getActiveTunnelUrl)continue;let i=await s.getActiveTunnelUrl();if(i)return i}return null}function Wr({serviceRegistry:t,runFinalize:n,getDb:o}){let s=ho(),i=yo();return new E({prefix:"/api/agent"}).get("/identity",()=>({hostname:ue.hostname(),platform:ue.platform(),architecture:ue.arch(),agentVersion:s,agentInstanceId:ri()})).get("/version",()=>({version:s,runtime:"bun",runtimeVersion:typeof Bun<"u"?Bun.version:"unknown"})).get("/api-key",({request:a,set:l})=>{if(Ve(a))return l.status=403,{error:"Forbidden",message:"Browser requests are not permitted on /api/agent/api-key"};let c=L(Object.fromEntries(a.headers.entries()));if(!V(c))return l.status=401,{error:"Unauthorized",message:"Invalid or missing API key"};return{apiKey:K()}}).post("/iframe-token",({body:a,request:l,set:c})=>{let u=L(Object.fromEntries(l.headers.entries()));if(!V(u))return c.status=401,{error:"Unauthorized",message:"Invalid or missing API key"};try{if(Array.isArray(a.pathPrefixes)&&a.pathPrefixes.length>0)return Ut({pathPrefixes:a.pathPrefixes,methods:a.methods},a.ttlSeconds??void 0);if(!a.pathPrefix)return c.status=400,{error:"BadRequest",message:"Provide either pathPrefix (string) or pathPrefixes (string[])"};return fr(a.pathPrefix,a.ttlSeconds??void 0)}catch(f){return c.status=400,{error:"BadRequest",message:f instanceof Error?f.message:String(f)}}},{body:r.Object({pathPrefix:r.Optional(r.String({minLength:1})),pathPrefixes:r.Optional(r.Array(r.String({minLength:1}),{minItems:1,maxItems:16})),methods:r.Optional(r.Array(r.String({minLength:1}),{minItems:1,maxItems:8})),ttlSeconds:r.Optional(r.Number())})}).post("/terminal-exchange",({body:a,set:l})=>{let{sid:c,token:u}=a;if(!c||!u)return l.status=400,{error:"BadRequest",message:"sid and token required"};if(!we(c))return l.status=400,{error:"BadRequest",message:"invalid sid"};let f=`/terminal/${c}`,m=Hr(u,f);if(!m.ok)return e().logger.warn("terminal-exchange","iframe token rejected",{sid:c,reason:m.reason}),l.status=401,{error:"Unauthorized",message:"invalid iframe token",code:m.reason==="expired"?"expired":m.reason==="replayed"?"replayed":"invalid"};let _=Li(c,600),q=`vt_term_${c}`;return l.headers["set-cookie"]=`${q}=${_.token}; HttpOnly; Secure; SameSite=None; Path=/terminal/${c}; Max-Age=600`,l.status=204,null},{body:r.Object({sid:r.String({minLength:1}),token:r.String({minLength:1})})}).post("/ui-exchange",({body:a,set:l})=>{let{plugin:c,token:u}=a;if(!c||!u)return l.status=400,{error:"BadRequest",message:"plugin and token required"};if(!me(c))return l.status=400,{error:"BadRequest",message:"invalid plugin name"};let f=`/ui/${c}`;if(!je(u,f))return l.status=401,{error:"Unauthorized",message:"invalid iframe token"};let m=yt(c,600),_=`vt_ui_${c}`;return l.headers["set-cookie"]=`${_}=${m.token}; HttpOnly; Secure; SameSite=None; Path=/ui/${c}/; Max-Age=600`,l.status=204,null},{body:r.Object({plugin:r.String({minLength:1}),token:r.String({minLength:1})})}).post("/ui-exchange-plugin",({body:a,set:l})=>{let{plugin:c,token:u}=a;if(!c||!u)return l.status=400,{error:"BadRequest",message:"plugin and token required"};if(!me(c))return l.status=400,{error:"BadRequest",message:"invalid plugin name"};if(![`/api/plugins/${c}/ui`,`/${c}`].find((Z)=>je(u,Z)))return l.status=401,{error:"Unauthorized",message:"invalid iframe token"};let _=yt(c,600),q=`vt_ui_${c}`;return l.headers["set-cookie"]=`${q}=${_.token}; HttpOnly; Secure; SameSite=None; Path=/api/plugins/${c}/ui/; Max-Age=600`,l.status=204,null},{body:r.Object({plugin:r.String({minLength:1}),token:r.String({minLength:1})})}).get("/system",({request:a,set:l})=>{let c=L(Object.fromEntries(a.headers.entries()));if(!V(c))return l.status=401,{error:"Unauthorized",message:"Invalid or missing API key"};return{machineId:i,hostname:ue.hostname(),platform:ue.platform(),arch:ue.arch(),release:ue.release(),cpus:ue.cpus().length,totalMemory:ue.totalmem(),freeMemory:ue.freemem(),uptime:ue.uptime(),bunVersion:typeof Bun<"u"?Bun.version:void 0,agentVersion:s,homeDir:ue.homedir(),cwd:process.cwd(),environment:"production"}}).get("/tunnel",async({request:a,set:l})=>{let c=Object.fromEntries(a.headers.entries()),u=V(L(c)),f=Kt(Jt(c));if(!u&&!f)return l.status=401,{error:"Unauthorized",message:"Provide x-agent-api-key OR x-pairing-token to read tunnel URL"};let m=await wo(t);if(!m)return{tunnelUrl:null,message:"No tunnel provider registered"};return{tunnelUrl:m}}).get("/status",()=>{let a=["tunnel","session","ai"].filter((l)=>t.hasProvider(l));return{state:e().getBootState(),status:e().getBootState(),version:s,providers:a,timestamp:new Date().toISOString()}}).get("/gateway-auth",()=>({configured:T.isConfigured(),config:k(T.getConfig()),state:e().getBootState()})).post("/retry-config",async({set:a})=>{let{getFinalizeRetryHandle:l}=await import("./finalize-retry-handle-registry-z9mbbjmj.js"),c=l();if(!c)return a.status=409,{ok:!1,error:"No finalize retry worker is active. The agent either never had cached credentials to retry with, or it already reached the ready state."};let u=await c.forceRetryNow();if(!u.ok)a.status=503;return{ok:u.ok,error:u.ok?void 0:u.error,state:e().getBootState(),worker:c.getState()}}).post("/gateway-auth",async({body:a,request:l,set:c})=>{let u=e().getBootState(),f=Object.fromEntries(l.headers.entries());if(u==="ready"){let p=L(f);if(!V(p))return c.status=401,{success:!1,state:u,error:"Unauthorized: API key required to reconfigure"}}else{let p=L(f),j=Jt(f),J=V(p),re=Kt(j);if(!J&&!re)return c.status=401,{success:!1,state:u,error:"Unauthorized: provide x-agent-api-key OR x-pairing-token for bootstrap"}}let{clientId:m,clientSecret:_,workspaceId:q,globalGatewayUrl:Z,workspaceGatewayUrl:g}=a;if(!m||!_||!q||!Z||!g)return c.status=400,{success:!1,state:e().getBootState(),error:"clientId, clientSecret, workspaceId, globalGatewayUrl, and workspaceGatewayUrl are required"};let S,A;try{S=z(Z,"globalGatewayUrl"),A=z(g,"workspaceGatewayUrl")}catch(p){return c.status=400,{success:!1,state:e().getBootState(),error:p instanceof Error?p.message:String(p)}}let ne,G=await he("gateway-auth:push",async()=>{let p=B()??e();{let J;try{J=await X({dir:p.dataDir,scope:p.name,strict:!0})}catch(le){let De=le instanceof Error?le.message:String(le);return e().logger.error("preconfig","Could not read existing credentials \u2014 refusing the push rather than risk overwriting a live pairing",{error:De}),c.status=503,{success:!1,state:e().getBootState(),error:`Cannot verify this agent's current pairing (secrets backend unavailable: ${De}). Refusing the credential push so a live pairing is not overwritten. Retry once the secrets backend recovers.`,code:"IDENTITY_CHECK_UNAVAILABLE"}}let re=ii(J,{workspaceId:q,globalGatewayUrl:S,workspaceGatewayUrl:A});if(re&&a.force!==!0)return e().logger.warn("preconfig","Rejected a gateway-auth push that would hijack this agent's identity",{conflict:re}),c.status=409,{success:!1,state:e().getBootState(),error:re,code:"GATEWAY_IDENTITY_CONFLICT"};if(re)e().logger.warn("preconfig","Forced re-pair \u2014 overwriting an existing gateway identity",{conflict:re})}let j=null;{let J=rr()?ye():p.name,re;try{re=zr(J)}catch(de){let Me=de instanceof Error?de.message:String(de);return e().logger.error("preconfig",`Could not read profile "${J}" \u2014 refusing the push rather than assume it declares nothing`,{error:Me}),c.status=503,{success:!1,state:e().getBootState(),error:`Cannot read profile "${J}" to verify this push targets the right environment (${Me}). Refusing the credential push so a foreign environment is not accepted by default. Repair or remove the profile file and retry.`,code:"PROFILE_CHECK_UNAVAILABLE"}}let le=oi(),De={globalGatewayUrl:le.globalGatewayUrl??re.globalGatewayUrl,workspaceGatewayUrl:le.workspaceGatewayUrl??re.workspaceGatewayUrl},ae=ni(De,{workspaceId:q,globalGatewayUrl:S,workspaceGatewayUrl:A},J);if(ae&&a.force!==!0)return e().logger.warn("preconfig","Rejected a gateway-auth push that contradicts the active profile",{profileConflict:ae}),c.status=409,{success:!1,state:e().getBootState(),error:ae,code:"PROFILE_ENVIRONMENT_CONFLICT"};if(ae)j={name:J,cfg:{...re,globalGatewayUrl:S,workspaceGatewayUrl:A,workspaceId:void 0}},e().logger.warn("preconfig",`Forced repoint accepted \u2014 profile "${J}" will be updated to match the pushed environment`,{profileConflict:ae})}try{await Yt({clientId:m,clientSecret:_,workspaceId:q,ownerUserId:a.ownerUserId,organizationId:a.organizationId,globalGatewayUrl:S,workspaceGatewayUrl:A,agentRecordId:a.agentRecordId,scopes:a.scopes,pairedIdentity:Zt({workspaceId:q,globalGatewayUrl:S,workspaceGatewayUrl:A,agentRecordId:a.agentRecordId}),...a.storageAdapter?{storageAdapter:a.storageAdapter}:{},...a.storageOptions?{storageOptions:a.storageOptions}:{},...a.dbPath?{dbPath:a.dbPath}:{}},{dir:p.dataDir,scope:p.name})}catch(J){return c.status=500,{success:!1,state:e().getBootState(),error:`Failed to persist gateway credentials to secrets backend: ${J instanceof Error?J.message:String(J)}`}}if(j)try{nt(j.name,j.cfg),e().logger.warn("preconfig",`Profile "${j.name}" repointed to the pushed environment`)}catch(J){let re=J instanceof Error?J.message:String(J);ne=`Credentials were accepted, but profile "${j.name}" could not be updated (${re}). It still describes the previous environment \u2014 `+"run `vibe profile use` / fix the profile file so config and profile agree.",e().logger.error("preconfig",`Forced repoint accepted but profile "${j.name}" could not be updated \u2014 profile and config.json now disagree`,{error:re})}return null});if(G)return G;let x=e().getBootState();if(x==="ready"){let p=o();if(p){if(await p.setConfig("gateway-auth:clientId",m),await p.setConfig("gateway-auth:clientSecret",_),await p.setConfig("gateway-auth:workspaceId",q),a.organizationId)await p.setConfig("gateway-auth:organizationId",a.organizationId);if(await p.setConfig("gateway-auth:globalGatewayUrl",S),await p.setConfig("gateway-auth:workspaceGatewayUrl",A),a.agentRecordId)await p.setConfig("gateway-auth:agentRecordId",a.agentRecordId)}T.configure({globalGatewayUrl:S,workspaceGatewayUrl:A,clientId:m,clientSecret:_,workspaceId:q,organizationId:a.organizationId}),Qt({workspaceId:q,organizationId:a.organizationId,globalGatewayUrl:S,workspaceGatewayUrl:A},{isBootProfile:rr()}),e().logger.info("preconfig","Gateway credentials re-configured (agent was already ready)");let j=!!(a.storageAdapter||a.storageOptions||a.dbPath);return{success:!0,state:x,message:j?"Gateway auth re-configured. Restart the agent (vibe restart) to apply the new storage configuration.":"Gateway auth re-configured",...ne?{warning:ne}:{}}}return e().logger.info("preconfig","Gateway credentials received \u2014 beginning finalize (background)"),zt(),Qt({workspaceId:q,organizationId:a.organizationId,globalGatewayUrl:S,workspaceGatewayUrl:A},{isBootProfile:rr()}),n({clientId:m,clientSecret:_,workspaceId:q,organizationId:a.organizationId,globalGatewayUrl:S,workspaceGatewayUrl:A},{agentRecordId:a.agentRecordId,scopes:a.scopes}).catch((p)=>{e().logger.error("preconfig","Background finalize threw",{error:p instanceof Error?p.message:String(p)})}),c.status=202,{success:!0,state:e().getBootState(),agentRecordId:a.agentRecordId,message:"Gateway credentials accepted; finalize is running in the background. Poll /health/ready for completion.",...ne?{warning:ne}:{}}},{body:r.Object({clientId:r.Optional(r.String()),clientSecret:r.Optional(r.String()),workspaceId:r.Optional(r.String()),ownerUserId:r.Optional(r.String()),organizationId:r.Optional(r.String()),globalGatewayUrl:r.Optional(r.String()),workspaceGatewayUrl:r.Optional(r.String()),scopes:r.Optional(r.Array(r.String())),agentRecordId:r.Optional(r.String()),storageAdapter:r.Optional(r.String()),storageOptions:r.Optional(r.Record(r.String(),r.String())),dbPath:r.Optional(r.String()),force:r.Optional(r.Boolean())})})}import{existsSync as Te,mkdirSync as bo,rmSync as Jr,readdirSync as Xr}from"fs";import{join as It}from"path";function Ae(t){return It(C(),"agents",O(t))}function So(){let t=It(C(),"agents");if(!Te(t))return[];return Xr(t,{withFileTypes:!0}).filter((n)=>n.isDirectory()).map((n)=>n.name).filter((n)=>/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(n))}function Zr(t){return It(C(),"agents",O(t))}function nr(t){return w({dir:Zr(t)})}function Yr(t,n){return M(n,{dir:Zr(t),scope:O(t)})}function He(t){let n=Oe(),o=bt().find((a)=>a.name===t),s=N.get(t),i={name:t,isDefault:t===n,isRunning:o?.status==="running",attached:s!==void 0,bootState:s?s.getBootState():null,dataDir:s?s.dataDir:null};if(o)i.port=o.port,i.pid=o.pid,i.startTime=o.startTime;if(Te(Ae(t)))i.config=k(nr(t));return i}function en(t={}){let n=t.serviceManagerFactory?t.serviceManagerFactory():new D;return new E({prefix:"/api/profiles"}).get("/",()=>{let o=So(),s=Oe(),i=new Set(o);return i.add(s),[...i].sort().map((a)=>He(a))}).post("/",async({body:o,set:s})=>{try{let i=O(o.name),a=Ae(i);if(Te(a))return s.status=409,{error:"exists",message:`Profile '${i}' already exists.`};let l;if(o.copyFrom){let c=O(o.copyFrom);if(!Te(Ae(c)))return s.status=400,{error:"copy-source-missing",message:`Profile '${c}' does not exist.`};l=nr(c),delete l["static-api-key"],delete l.agentRecordId,delete l.apiKeys,delete l.pairedIdentity,delete l.workspaceId,delete l.organizationId}else l=ti();if(o.gatewayUrl)l.globalGatewayUrl=o.gatewayUrl;if(o.workspaceGatewayUrl)l.workspaceGatewayUrl=o.workspaceGatewayUrl;if(o.clientId)l.clientId=o.clientId;if(o.clientSecret)l.clientSecret=o.clientSecret;if(o.workspaceId)l.workspaceId=o.workspaceId;if(o.organizationId)l.organizationId=o.organizationId;bo(a,{recursive:!0}),Yr(i,l);try{at(i)}catch(c){e().logger.warn("profile-mgmt",`In-process attach failed for '${i}'`,{error:String(c)})}if(e().logger.info("profile-mgmt",`Created profile '${i}' at ${a}`),o.start){let c={name:i,port:o.port??0,daemon:!0,dbPath:ee(),profile:i};await n.startDaemon(c)}return s.status=201,He(i)}catch(i){return s.status=400,{error:"create-failed",message:i instanceof Error?i.message:String(i)}}},{body:r.Object({name:r.String(),gatewayUrl:r.Optional(r.String()),workspaceGatewayUrl:r.Optional(r.String()),clientId:r.Optional(r.String()),clientSecret:r.Optional(r.String()),workspaceId:r.Optional(r.String()),organizationId:r.Optional(r.String()),copyFrom:r.Optional(r.String()),start:r.Optional(r.Boolean()),port:r.Optional(r.Number())})}).get("/:name",({params:o,set:s})=>{try{let i=O(o.name);if(!Te(Ae(i)))return s.status=404,{error:"not-found",message:`No profile '${i}'.`};return He(i)}catch(i){return s.status=400,{error:"bad-request",message:i instanceof Error?i.message:String(i)}}},{params:r.Object({name:r.String()})}).put("/:name",({params:o,body:s,set:i})=>{try{let a=O(o.name);if(!Te(Ae(a)))return i.status=404,{error:"not-found",message:`No profile '${a}'.`};let l=["static-api-key","apiKeys","agentRecordId","pairedIdentity"];for(let f of l)if(f in s)return i.status=400,{error:"forbidden-field",message:`Field '${f}' is managed via dedicated commands (vibe key rotate / vibe profile create). It cannot be patched here.`};if("registry"in s)return i.status=400,{error:"forbidden-field",message:"Field 'registry' cannot be patched via this endpoint. Use POST /api/agent/registry with operator confirmation (VIBE_ALLOW_REGISTRY_CHANGE=1) so the change is auditable."};let u={...nr(a),...s};return Yr(a,u),He(a)}catch(a){return i.status=400,{error:"update-failed",message:a instanceof Error?a.message:String(a)}}},{params:r.Object({name:r.String()}),body:r.Record(r.String(),r.Any())}).delete("/:name",async({params:o,body:s,query:i,set:a})=>{try{let l=O(o.name);if(l===Oe())return a.status=409,{error:"is-default",message:`Cannot delete active default profile '${l}'. Switch to another profile first.`};let c=i?.purge==="true"||i?.purge==="1",u=Te(Ae(l)),f=N.has(l);if(!u&&!f)return a.status=404,{error:"not-found",message:`No profile '${l}'.`};if(u&&!c&&!s?.confirm)return a.status=400,{error:"confirm-required",message:"Pass { confirm: true } in the body or `?purge=true` in the query to delete the on-disk dataDir (destructive)."};try{await n.stop(l)}catch{}try{await N.destroy(l)}catch(m){e().logger.warn("profile-mgmt",`In-process detach failed for '${l}'`,{error:String(m)})}if(u)if(s?.keepConfig)for(let m of Xr(Ae(l))){if(m==="config.json")continue;Jr(It(Ae(l),m),{recursive:!0,force:!0})}else Jr(Ae(l),{recursive:!0,force:!0});return e().logger.info("profile-mgmt",`Deleted profile '${l}'`),{ok:!0,deleted:l,keptConfig:!!s?.keepConfig,detached:f,purged:u}}catch(l){return a.status=400,{error:"delete-failed",message:l instanceof Error?l.message:String(l)}}},{params:r.Object({name:r.String()}),query:r.Optional(r.Object({purge:r.Optional(r.String())})),body:r.Optional(r.Object({confirm:r.Optional(r.Boolean()),keepConfig:r.Optional(r.Boolean())}))}).post("/:name/switch",async({params:o,set:s})=>{try{let i=O(o.name);if(!Te(Ae(i)))return s.status=404,{error:"not-found",message:`No profile '${i}'.`};return await ot(()=>Xt(i)),e().logger.info("profile-mgmt",`Default profile switched to '${i}'`),{ok:!0,defaultProfile:i}}catch(i){return s.status=400,{error:"switch-failed",message:i instanceof Error?i.message:String(i)}}},{params:r.Object({name:r.String()})}).post("/:name/start",async({params:o,body:s,set:i})=>{try{let a=O(o.name);if(!Te(Ae(a)))return i.status=404,{error:"not-found",message:`No profile '${a}'.`};try{at(a)}catch(c){e().logger.warn("profile-mgmt",`In-process attach failed for '${a}'`,{error:String(c)})}if(!bt().some((c)=>c.name===a&&c.status==="running")){let c={name:a,port:s?.port??0,daemon:!0,dbPath:ee(),profile:a};await n.startDaemon(c)}return He(a)}catch(a){return i.status=500,{error:"start-failed",message:a instanceof Error?a.message:String(a)}}},{params:r.Object({name:r.String()}),body:r.Optional(r.Object({port:r.Optional(r.Number())}))}).post("/:name/stop",async({params:o,set:s})=>{try{let i=O(o.name);try{await n.stop(i)}catch{}try{await N.destroy(i)}catch(a){e().logger.warn("profile-mgmt",`In-process detach failed for '${i}'`,{error:String(a)})}return He(i)}catch(i){return s.status=500,{error:"stop-failed",message:i instanceof Error?i.message:String(i)}}},{params:r.Object({name:r.String()})})}function vo(){let t=process.memoryUsage(),n=process.resourceUsage(),o=n.userCPUTime/1000,s=n.systemCPUTime/1000,i=o+s,a=N.list().map((l)=>{let c;try{c=qr(l.spawnOwnerKey).length}catch{c=0}return{name:l.name,status:l.getBootState(),childPidCount:c,cpuMs:i,heapBytes:t.heapUsed,dataDir:l.dataDir}});return{process:{pid:process.pid,uptimeSeconds:process.uptime(),cpuUserMs:o,cpuSystemMs:s,heapUsedBytes:t.heapUsed,heapTotalBytes:t.heapTotal,rssBytes:t.rss},profiles:a,notes:{perProfileCpu:"deferred",perProfileHeap:"deferred"}}}function tn(){return new E({prefix:"/api/profile-stats"}).get("/",()=>vo())}function St(t,n){return Promise.race([t,new Promise((o,s)=>setTimeout(()=>s(Error(`timeout after ${n}ms`)),n))])}function ko(t){let n=t instanceof Error?t.message:String(t);return/ENOENT/.test(n)||/no such file or directory/i.test(n)}async function rn(t){let o=`__health__:probe:${typeof crypto<"u"&&typeof crypto.randomUUID==="function"?crypto.randomUUID():`${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`}`,s=String(Date.now());if(await St(t.setConfig(o,s),2000),await St(t.getConfig(o),2000)!==s)throw Error("round-trip mismatch");try{await St(t.deleteConfig(o),500)}catch{}}async function Po(t,n){if(!t)return{ok:!1,message:"database not opened"};let o=performance.now();try{return await rn(t),{ok:!0,durationMs:performance.now()-o}}catch(s){if(n&&ko(s))try{let i=await import("fs");return i.mkdirSync(n,{recursive:!0}),await rn(t),{ok:!0,message:`recovered: dbPath ${n} was missing \u2014 recreated`,durationMs:performance.now()-o}}catch(i){return{ok:!1,message:`ENOENT on dbPath ${n}: ${i instanceof Error?i.message:String(i)}`,durationMs:performance.now()-o}}return{ok:!1,message:s instanceof Error?s.message:String(s),durationMs:performance.now()-o}}}async function Ro(t){if(process.env.AGENT_TUNNEL==="false")return{ok:!0,message:"tunnel disabled via AGENT_TUNNEL=false"};if(!t)return{ok:!1,message:"no service registry"};let n=t.getProvider("tunnel"),o=e().getBootState()==="awaiting-config";if(!n)return{ok:!1,message:o?"agent is awaiting-config \u2014 POST OAuth credentials to /api/agent/gateway-auth to register tunnel provider":"no tunnel provider registered"};if(!n.getActiveTunnelUrl)return{ok:!0,message:`provider: ${n.name}`};try{let s=await St(Promise.resolve(n.getActiveTunnelUrl()),2000),i=Wt(s);if(i)return{ok:!0,message:`provider: ${n.name} \u2014 ${i}`};if(s)return{ok:!1,message:`provider: ${n.name} \u2014 reported an unusable tunnel URL (${s})`};return{ok:!1,message:`provider: ${n.name} \u2014 no active tunnel (the agent is not reachable from outside; the provider is rebuilding it)`}}catch(s){return{ok:!1,message:`provider: ${n.name} \u2014 tunnel status unavailable: ${s instanceof Error?s.message:String(s)}`}}}function Ao(t,n){if(!t)return{ok:!1,message:"no service registry"};let s=e().getBootState()==="awaiting-config";if(n==="session"){let i=t.getProvider("session");if(i)return{ok:!0,message:`provider: ${i.name}`};return{ok:!1,message:s?"agent is awaiting-config \u2014 POST OAuth credentials to /api/agent/gateway-auth to register session provider":"no session provider registered"}}return{ok:!0}}async function Io(t){if(!t)return{};let n={};for(let o of t.getAllPlugins()){let s=o.getHealth;if(typeof s!=="function")continue;let i=performance.now();try{let a=await St(Promise.resolve(s.call(o)),2000);n[o.name]={ok:a?.ok!==!1,message:a?.message,durationMs:performance.now()-i}}catch(a){n[o.name]={ok:!1,message:a instanceof Error?a.message:String(a),durationMs:performance.now()-i}}}return n}function nn(t){let n=t&&"serviceRegistry"in t?t:{serviceRegistry:t};return new E({prefix:"/health"}).get("/",()=>({status:"ok",lifecycleState:n.serviceRegistry?.getService("agent","lifecycle")?.getState()??"running",bootState:e().getBootState(),timestamp:new Date().toISOString(),uptime:process.uptime()})).get("/live",()=>({status:"ok"})).get("/ready",async({set:o})=>{let i=n.serviceRegistry?.getService("agent","lifecycle")?.getState()??"running",a=e().getBootState(),l={};l.boot={ok:a==="ready",message:a==="ready"?void 0:`boot state ${a}`},l.lifecycle={ok:i==="running",message:i==="running"?void 0:`lifecycle ${i}`},l.db=await Po(n.getDb?.()??null,n.getDbPath?.()??null),l.tunnel=await Ro(n.serviceRegistry),l.session=Ao(n.serviceRegistry,"session"),l.identity=await Kr();try{let{gatewayClient:g}=await import("./gateway-client-3zp6kkav.js");if(!g.isConfigured())l.registration={ok:!0,message:"not configured"};else{let S=n.getDb?.()??null;if(S?await S.getConfig("gateway-auth:agentRecordId"):null)l.registration={ok:!0};else{let ne=e().getDegradedReasons().some((G)=>G.plugin==="agent-registration");l.registration=ne?{ok:!1,message:"agent failed to register with the workspace after retries"}:{ok:!0,message:"registering"}}}}catch(g){l.registration={ok:!0,message:`registration check skipped: ${g instanceof Error?g.message:String(g)}`}}let c=await Io(n.getPluginManager?.()??null),u=Object.values(l).every((g)=>g.ok)&&Object.values(c).every((g)=>g.ok);if(!u)o.status=503;let f=a==="degraded"?e().getDegradedReasons():[],m=e().name,_={};for(let g of N.list())_[g.name]={bootState:g.getBootState(),ok:g.getBootState()==="ready",degradedReasons:g.getDegradedReasons()};let q=e().getLastFinalizeError(),Z={status:u?"ok":"degraded",lifecycleState:i,bootState:a,daemon:{profile:m,bootState:a,ok:a==="ready"},profiles:_,components:l,plugins:c,degradedReasons:f,lastFinalizeError:q,timestamp:new Date().toISOString()};if(!u)e().logger.warn("health","Readiness probe failed",{components:l,plugins:c,bootState:a});return Z})}var Ot=0,on=0;function an(){return new E({name:"inflight-tracker"}).onRequest(()=>{Ot+=1}).onAfterResponse(()=>{Ot=Math.max(0,Ot-1),on+=1})}function sn(){return new E({prefix:"/api/stats"}).get("/inflight",()=>({inflight:Math.max(0,Ot-1),totalServed:on}))}var ln={enabled:!1,async scrape(){return`# vibecontrols agent metrics disabled (OTel SDK not initialised)
|
|
3
3
|
`},recordHttpRequest(){},setPluginsLoaded(){}},_e=null,Ct=null;async function xt(t){if(_e)return _e;if(Ct)return Ct;return Ct=(async()=>{try{let{MeterProvider:n}=await import("./index-31ssvzw8.js"),{PrometheusExporter:o,PrometheusSerializer:s}=await import("./index-7bm1kptr.js").then((m)=>P(m.default,1)),i=new o({preventServerStart:!0}),a=new s,c=new n({readers:[i]}).getMeter("vibecontrols-agent"),u=c.createGauge("vibecontrols_agent_info",{description:"Static info about the agent process; value is always 1."});c.createObservableGauge("vibecontrols_agent_uptime_seconds",{description:"Process uptime in seconds."}).addCallback((g)=>{g.observe(process.uptime())});let m=c.createCounter("vibecontrols_http_requests_total",{description:"Total HTTP requests handled by the agent, labelled by method, route, status."}),_={};c.createObservableGauge("vibecontrols_plugins_loaded",{description:"Plugins loaded by the agent, broken down by status (loaded, failed, etc.)."}).addCallback((g)=>{for(let[S,A]of Object.entries(_))g.observe(A,{status:S})}),u.record(1,{version:t?.version??"unknown",profile:t?.profile??"default"});let Z={enabled:!0,async scrape(){let g=await i.collect();if(!g.resourceMetrics)return"";return a.serialize(g.resourceMetrics)},recordHttpRequest(g,S,A){m.add(1,{method:g,route:S,status:String(A)})},setPluginsLoaded(g){_={...g}}};return _e=Z,e().logger.info("metrics","OTel Prometheus registry initialised"),Z}catch(n){return e().logger.warn("metrics","Failed to initialise OTel metrics; /metrics will return a stub body",{error:n instanceof Error?n.message:String(n)}),_e=ln,ln}})(),Ct}function cn(t,n,o){if(!_e)return;_e.recordHttpRequest(t,n,o)}function un(t){if(!_e)return;_e.setPluginsLoaded(t)}var dn=!1;function Eo(){if(dn)return;if(process.env.METRICS_ANONYMOUS_LOCALHOST==="true")dn=!0,e().logger.warn("metrics","METRICS_ANONYMOUS_LOCALHOST=true \u2014 /metrics is open to TCP loopback peers without an API key. Prefer issuing a scoped API key for your scraper.")}function Oo(t,n){return Pe(t,n)}function gn(){return Eo(),new E({name:"routes/metrics"}).get("/metrics",async({request:t,server:n,set:o})=>{if(!(process.env.METRICS_ANONYMOUS_LOCALHOST==="true"&&Oo(t,n))){let l=L(Object.fromEntries(t.headers.entries()));if(!V(l))return o.status=401,o.headers["content-type"]="application/json",JSON.stringify({error:"Unauthorized",message:"Invalid or missing API key"})}let a=await(await xt()).scrape();return o.headers["content-type"]="text/plain; version=0.0.4; charset=utf-8",a})}var ir=Object.freeze(["code","code-insiders","codium","cursor","idea","pycharm","webstorm","goland","phpstorm","rubymine","clion","rider","zed","subl","vim","nvim","emacs","neovide","fleet","helix"]),Co=new Set(ir),To=new Set(["--new-window","-n","--reuse-window","-r","--wait","-w","--add","--goto"]);function pn(t){try{return Bun.which(t)??null}catch{return null}}function fn(){return new E({prefix:"/api/editor"}).get("/allowlist",()=>({commands:[...ir]})).get("/detect",async()=>{let t=ir.map((s)=>[s,pn(s)]),n=[],o={};for(let[s,i]of t)if(i)n.push(s),o[s]=i;return{available:n,paths:o}}).post("/open",async({body:t,set:n})=>{let{command:o,path:s,args:i=[]}=t;if(!Co.has(o))return n.status=400,{ok:!1,error:`Command '${o}' is not in the IDE allowlist`};for(let c of i)if(typeof c!=="string"||!To.has(c))return n.status=400,{ok:!1,error:`Argument '${c}' is not in the flag allowlist`};let a;try{a=(await oe(s,{mustExist:!0})).realPath}catch(c){return n.status=400,{ok:!1,error:`Invalid path: ${c instanceof Error?c.message:String(c)}`}}let l=pn(o);if(!l)return n.status=404,{ok:!1,error:`'${o}' is not installed or not on PATH on this agent`};try{let c=wr({owner:`editor:${o}`,cmd:[l,...i,a],env:process.env,stdout:"ignore",stderr:"ignore",stdin:"ignore",meta:{command:o,path:a}});return e().logger.info("editor",`Launched ${o} on ${a}`,{pid:c.pid}),e().audit.emit("agent","editor.open",{command:o,path:a,pid:c.pid}),{ok:!0,command:o,resolvedPath:a,pid:c.pid}}catch(c){return n.status=500,{ok:!1,error:`Failed to spawn editor: ${c instanceof Error?c.message:String(c)}`}}},{body:r.Object({command:r.String({minLength:1,maxLength:40}),path:r.String({minLength:1,maxLength:4096}),args:r.Optional(r.Array(r.String({maxLength:32})))})})}function mn(){return(B()??e()).dataDir}function fe(){let t=w({dir:mn()});return{ownerUserId:t.ownerUserId,workspaceId:t.workspaceId}}function $t(){return w({dir:mn()}).agentRecordId}function yn(t){if(!t)return null;try{return new URL(t).host}catch{return null}}async function hn(t,n){let o=t.getPluginManager(),s=o?o.getPluginDetails().map((c)=>({pluginName:c.pluginName,packageName:c.packageName,version:c.version,tags:c.tags??[]})):[],i=process.memoryUsage(),a=yn(t.getTunnelHost?.()??null),l;try{l=gt(fe()).map((c)=>({id:c.id,label:c.label,host:yn(c.tunnelUrl),agentRecordId:c.agentRecordId??null,permissions:c.permissions,canForward:c.permissions.includes("mesh:forward"),lastReachable:c.lastReachable??null}))}catch{l=[]}return{pluginName:"agent",description:"vibecontrols-agent runtime self-report",generatedAt:new Date().toISOString(),data:{profile:n.profile,vibeId:n.vibeId??null,runtime:{bunVersion:typeof Bun<"u"?Bun.version:null,nodeVersion:process.versions.node??null,platform:process.platform,arch:process.arch,pid:process.pid,uptimeSeconds:Math.round(process.uptime()),memory:{rssMB:Math.round(i.rss/1048576),heapUsedMB:Math.round(i.heapUsed/1048576)}},agent:{version:t.getAgentVersion?.()??null,profileRegistered:R(),tunnelHost:a},plugins:{count:s.length,items:s},mesh:{peerCount:l.length,peers:l}}}}var Uo=2000,wn=1000;async function xo(t,n){let o,s=new Promise((i,a)=>{o=setTimeout(()=>a(Error(`timeout after ${n}ms`)),n)});try{return await Promise.race([t,s])}finally{if(o)clearTimeout(o)}}async function bn(t,n){let o=performance.now(),s=t.timeoutMs??Uo;try{let i=await xo(t.getContext(n),s);if(!i.generatedAt)i.generatedAt=new Date().toISOString();return{ok:!0,data:i,durationMs:Math.round(performance.now()-o)}}catch(i){return{ok:!1,error:i.message??String(i),durationMs:Math.round(performance.now()-o)}}}class sr{deps;inflight=new Map;constructor(t){this.deps=t}async aggregate(t){let n=`${t.profile}::${t.vibeId??""}`,o=this.inflight.get(n);if(o&&Date.now()-o.ts<wn)return o.promise;let s=this.doAggregate(t).finally(()=>{setTimeout(()=>{let i=this.inflight.get(n);if(i&&i.promise===s)this.inflight.delete(n)},wn).unref?.()});return this.inflight.set(n,{ts:Date.now(),promise:s}),s}async selfContext(t){return hn(this.deps,t)}async pluginContext(t,n){let o=Rr().find((s)=>s.name===t);if(!o)return null;return bn(o,n)}async pluginsContext(t){let n=Rr(),o=await Promise.allSettled(n.map((i)=>bn(i,t))),s={};return n.forEach((i,a)=>{let l=o[a];if(l&&l.status==="fulfilled")s[i.name]=l.value;else if(l&&l.status==="rejected")s[i.name]={ok:!1,error:l.reason instanceof Error?l.reason.message:String(l.reason),durationMs:0}}),s}async doAggregate(t){let[n,o]=await Promise.all([this.selfContext(t),this.pluginsContext(t)]);return{agent:n,plugins:o}}}function Nt(t){let n=t.vibeId;if(typeof n!=="string")return;let o=n.trim();return o.length>0&&o.length<=128?o:void 0}function Sn(t){let n=new sr(t);return new E({prefix:"/api/agent/context"}).get("/",async({params:o,query:s})=>{let i=o?.profile??"default",a=Nt(s);return n.aggregate({profile:i,vibeId:a})},{query:r.Object({vibeId:r.Optional(r.String())})}).get("/agent",async({params:o,query:s})=>{let i=o?.profile??"default",a=Nt(s);return n.selfContext({profile:i,vibeId:a})},{query:r.Object({vibeId:r.Optional(r.String())})}).get("/plugins",async({params:o,query:s})=>{let i=o?.profile??"default",a=Nt(s);return n.pluginsContext({profile:i,vibeId:a})},{query:r.Object({vibeId:r.Optional(r.String())})}).get("/plugins/:name",async({params:o,query:s,set:i})=>{let a=o?.profile??"default",l=o?.name;if(!l)return i.status=400,{error:"missing plugin name"};let c=Nt(s),u=await n.pluginContext(l,{profile:a,vibeId:c});if(!u)return i.status=404,{error:`no context provider registered under name "${l}"`};return u},{params:r.Object({name:r.String()}),query:r.Object({vibeId:r.Optional(r.String())})})}var Ue="autoupdate",Do=86400000,vn=300000,Mo=900000,Q={timer:null,running:!1,profile:"default",lastCheckAt:null,lastCheck:null,lastUpdateAt:null,lastUpdate:null,startedAt:null};function lr(){let t=(process.env.VIBE_AUTOUPDATE??"").trim().toLowerCase();return t==="0"||t==="false"||t==="off"||t==="no"}function Pn(){if(lr())return!1;try{return w().autoUpdate!==!1}catch{return!0}}function cr(){let t=Number(process.env.VIBE_AUTOUPDATE_INTERVAL_MS);if(Number.isFinite(t)&&t>0)return Math.max(Mo,t);return Do}async function ur(t){let n=e().logger;if(Q.running)return{check:Q.lastCheck??await kn(),update:null};Q.running=!0;try{let o=await Le();if(Q.lastCheck=o,Q.lastCheckAt=new Date().toISOString(),o.error)n.debug(Ue,`Update check failed: ${o.error}`);else if(o.hasUpdate)n.info(Ue,`New agent version available: ${o.current} \u2192 ${o.latest}`);let s=t?.force||Pn();if(!o.hasUpdate||!s)return{check:o,update:null};n.info(Ue,`Auto-updating ${o.current} \u2192 ${o.latest} (idle-gated restart)\u2026`);let i=await ze({restart:!0,name:Q.profile,onLog:(a)=>n.info(Ue,a)});if(Q.lastUpdate=i,Q.lastUpdateAt=new Date().toISOString(),i.ok&&i.updated)n.info(Ue,`Auto-update applied: now ${i.current} (restart: ${i.restart}).`);else if(!i.ok)n.warn(Ue,`Auto-update failed: ${i.error}`);return{check:o,update:i}}catch(o){return n.warn(Ue,`Auto-update tick threw: ${o instanceof Error?o.message:String(o)}`),{check:await kn(),update:null}}finally{Q.running=!1}}async function kn(){if(Q.lastCheck)return Q.lastCheck;let t=await Le();return Q.lastCheck=t,Q.lastCheckAt=new Date().toISOString(),t}function Rn(t){if(Q.timer)clearTimeout(Q.timer);Q.timer=setTimeout(()=>{ur().finally(()=>{if(Q.startedAt)Rn(cr())})},t),Q.timer.unref?.()}function xr(t){let n=e().logger;if(Q.profile=t?.profile||process.env.VIBECONTROLS_PROFILE||"default",Q.startedAt=new Date().toISOString(),lr()){n.info(Ue,"Autoupdate disabled via VIBE_AUTOUPDATE \u2014 not scheduling.");return}n.info(Ue,`Autoupdate scheduled (first check in ${Math.round(vn/60000)}m, then every ${Math.round(cr()/3600000)}h).`),Rn(vn)}function di(){if(Q.timer)clearTimeout(Q.timer),Q.timer=null;Q.startedAt=null}function An(t){if(M({autoUpdate:t}),t&&!Q.startedAt)xr({profile:Q.profile})}function pr(){let t=!0;try{t=w().autoUpdate!==!1}catch{}return{enabled:Pn(),envKillSwitch:lr(),configEnabled:t,scheduled:!!Q.startedAt,intervalMs:cr(),profile:Q.profile,startedAt:Q.startedAt,lastCheckAt:Q.lastCheckAt,lastCheck:Q.lastCheck,lastUpdateAt:Q.lastUpdateAt,lastUpdate:Q.lastUpdate}}import{existsSync as In}from"fs";import{join as En}from"path";var _o=600000,yr=1e6;function Bo(){let t=b(),n=t.which("bun")??`bun${t.executableSuffix}`,o=En(import.meta.dir,"cli.js");if(In(o))return{runner:n,prefix:[o]};let s=En(import.meta.dir,"..","cli.ts");if(In(s))return{runner:n,prefix:[s]};let i=t.which("vibe");if(i)return{runner:i,prefix:[]};return null}function On(t){if(t.length<=yr)return t;return t.slice(0,yr)+`
|
|
4
|
-
\u2026[output truncated at ${yr} bytes]`}async function Lt(t,n={}){let o=Bo();if(!o)return{ok:!1,exitCode:null,stdout:"",stderr:"Could not locate the vibe CLI to execute (no dist/cli.js, source, or PATH entry).",timedOut:!1,argv:t,command:"(unresolved)"};let s=[...o.prefix,...t],i=[o.runner,...s].join(" ");try{let a=Bun.spawn([o.runner,...s],{cwd:n.cwd,env:{...process.env,VIBE_AUTO_ACCEPT:"1",CI:"1",NO_COLOR:"1",...n.env},stdout:"pipe",stderr:"pipe"}),l=n.timeoutMs??_o,c=!1,u=setTimeout(()=>{c=!0;try{a.kill()}catch{}},l),[f,m,_]=await Promise.all([new Response(a.stdout).text(),new Response(a.stderr).text(),a.exited]);return clearTimeout(u),{ok:!c&&_===0,exitCode:_,stdout:On(f),stderr:On(m),timedOut:c,argv:t,command:i}}catch(a){return{ok:!1,exitCode:null,stdout:"",stderr:`Failed to spawn vibe CLI: ${a instanceof Error?a.message:String(a)}`,timedOut:!1,argv:t,command:i}}}async function Cn(){let{Command:t}=await import("./index-sd5bt3g5.js"),{registerCoreCommands:n}=await import("./register-core-
|
|
4
|
+
\u2026[output truncated at ${yr} bytes]`}async function Lt(t,n={}){let o=Bo();if(!o)return{ok:!1,exitCode:null,stdout:"",stderr:"Could not locate the vibe CLI to execute (no dist/cli.js, source, or PATH entry).",timedOut:!1,argv:t,command:"(unresolved)"};let s=[...o.prefix,...t],i=[o.runner,...s].join(" ");try{let a=Bun.spawn([o.runner,...s],{cwd:n.cwd,env:{...process.env,VIBE_AUTO_ACCEPT:"1",CI:"1",NO_COLOR:"1",...n.env},stdout:"pipe",stderr:"pipe"}),l=n.timeoutMs??_o,c=!1,u=setTimeout(()=>{c=!0;try{a.kill()}catch{}},l),[f,m,_]=await Promise.all([new Response(a.stdout).text(),new Response(a.stderr).text(),a.exited]);return clearTimeout(u),{ok:!c&&_===0,exitCode:_,stdout:On(f),stderr:On(m),timedOut:c,argv:t,command:i}}catch(a){return{ok:!1,exitCode:null,stdout:"",stderr:`Failed to spawn vibe CLI: ${a instanceof Error?a.message:String(a)}`,timedOut:!1,argv:t,command:i}}}async function Cn(){let{Command:t}=await import("./index-sd5bt3g5.js"),{registerCoreCommands:n}=await import("./register-core-n1dy472f.js"),o=new t;o.name("vibe").option("--json").option("--plain").option("-y, --yes").option("-p, --profile <name>");try{n(o)}catch{}let s=new Set(["nuke","kill","gc","stop","rollback","deploy"]),i=[];for(let a of o.commands){let l=a.name();if(!l||l==="help")continue;i.push({name:l,description:a.description()||"",usage:a.usage()||"",options:a.options.map((c)=>({flags:c.flags,description:c.description||""})),group:"core",destructive:s.has(l)})}return i.sort((a,l)=>a.name.localeCompare(l.name))}import{spawn as $o}from"child_process";import{writeFileSync as No,mkdirSync as Lo}from"fs";import{tmpdir as Go}from"os";import{join as Tn}from"path";var jo="@vibecontrols/agent";function Un(t){let n=b(),o=n.which("bun")??`bun${n.executableSuffix}`,s=n.which("npm")??`npm${n.executableSuffix}`,i=se(),a=t.delayMs??3000,l=t.pids.filter((u)=>Number.isInteger(u)&&u>0),c=`// vibecontrols agent self-uninstall reaper (auto-generated)
|
|
5
5
|
const PIDS = ${JSON.stringify(l)};
|
|
6
6
|
const NPM = ${JSON.stringify(s)};
|
|
7
7
|
const BUN = ${JSON.stringify(o)};
|
|
@@ -22,5 +22,5 @@ try { Bun.spawnSync([BUN, "remove", "-g", PKG], { stdout: "inherit", stderr: "in
|
|
|
22
22
|
addVibecontrolsAgentFromTunnel(input: $input) { agent { id name } clientId success error }
|
|
23
23
|
}`,zo=`mutation ReportAgentMeshLink($input: ReportAgentMeshLinkInput!) {
|
|
24
24
|
reportAgentMeshLink(input: $input) { id }
|
|
25
|
-
}`,Mn="VIBE_BOOTSTRAP_JSON=";function Vo(t){for(let s of t.split(/\r?\n/)){let i=s.indexOf(Mn);if(i>=0)try{return JSON.parse(s.slice(i+Mn.length))}catch{}}let n=t.indexOf("{"),o=t.lastIndexOf("}");if(n>=0&&o>n)try{return JSON.parse(t.slice(n,o+1))}catch{return null}return null}async function _n(t,n){let o=(m,_,q)=>n?.({step:m,status:_,message:q}),s=Xe(t.permissions??["tunnel:read","session:list","plugin:list","diagnostics:read","mesh:forward"]);if(!s.includes("mesh:forward"))s.push("mesh:forward");let i=(m)=>({ok:!1,peerId:"",agentRecordId:null,tunnelUrl:null,permissions:s,error:m}),a;try{a=et(t.target,{identityFile:t.identityFile})}catch(m){return i(m instanceof Error?m.message:String(m))}let l=t.label??a.id,c=s.join(","),u,f='export PATH="$HOME/.bun/bin:$PATH"; ';try{if(!t.connectExisting){o("probe","running");let x=await a.probe();if(o("probe","completed",`os=${x.os??"?"} arch=${x.arch??"?"}`),!x.bun){if(t.installBun===!1)return i("Bun is required to run the agent but is not installed, and Bun auto-install was disabled.");o("install-bun","running");let ae=await a.run(["sh","-c",`curl -fsSL https://bun.sh/install | bash && echo 'export PATH="$HOME/.bun/bin:$PATH"' >> ~/.bashrc`],{timeoutMs:300000});if(ae.code!==0)return o("install-bun","failed",ae.stderr.slice(0,400)),i("Bun auto-install failed.");let de=await a.run(["sh","-c","$HOME/.bun/bin/bun --version 2>/dev/null"],{timeoutMs:1e4});if(de.code===0&&de.stdout.trim())x.bun="$HOME/.bun/bin/bun",o("install-bun","completed",de.stdout.trim());else return i("Bun installed but the binary is not reachable.")}o("install-agent","running");let p=t.version??"latest",j=t.registry??"https://registry.npmjs.org/",J,re;try{J=dt(p)}catch(ae){return o("install-agent","failed","invalid version"),i(ae instanceof Error?ae.message:String(ae))}try{re=ht(j)}catch(ae){return o("install-agent","failed","invalid registry"),i(ae instanceof Error?ae.message:String(ae))}let le=await a.run(Pt(re,J),{timeoutMs:600000});if(le.code!==0)return o("install-agent","failed",le.stderr.slice(0,400)),i(`Agent install failed (exit ${le.code}).`);if(u=(await a.run(["sh","-c",`${f}vibe --version`],{timeoutMs:15000})).stdout.trim()||void 0,o("install-agent","completed",u),t.autostart)o("autostart","running"),await a.run(["sh","-c",`${f}vibe autostart install`],{timeoutMs:60000}),o("autostart","completed");if(t.installPlugins?.length){o("plugins","running");for(let ae of t.installPlugins){let de;try{de=ft(ae)}catch(Me){return o("plugins","failed","invalid plugin package"),i(Me instanceof Error?Me.message:String(Me))}await a.run(Mt(de),{timeoutMs:300000})}o("plugins","completed")}o("start","running"),await a.run(["sh","-c",`${f}vibe start`],{timeoutMs:60000}),o("start","completed")}o("bootstrap","running");let m;try{let x=mt(l),p=t.expiresIn?pt(t.expiresIn):void 0;m=Dt({label:x,scope:c,expiresIn:p,json:!0,emitDefaultKey:!0})}catch(x){return o("bootstrap","failed","invalid bootstrap arguments"),i(x instanceof Error?x.message:String(x))}let _=null;for(let x=0;x<15;x++){let p=await a.run(m,{timeoutMs:15000});if(p.code===0){let j=Vo(p.stdout);if(j&&typeof j.apiKey==="string"){_=j;break}}await new Promise((j)=>setTimeout(j,2000))}if(!_)return o("bootstrap","failed","could not obtain peer-bootstrap bundle"),i("Remote peer-bootstrap did not return a credential bundle.");o("bootstrap","completed");let q=fe(),Z=String(_.id),g=String(_.apiKey),S=Ir(typeof _.tunnelUrl==="string"?_.tunnelUrl:null),A=typeof _.agentRecordId==="string"?_.agentRecordId:null;if(t.onboardBackend!==!1&&T.isConfigured()&&S&&typeof _.fullDefaultApiKey==="string"){o("onboard","running");let x=5,p="no agent returned";for(let j=0;j<x;j++){try{let le=(await T.workspaceQuery(Ho,{input:{tunnelUrl:S,apiKey:_.fullDefaultApiKey,name:l}})).data?.addVibecontrolsAgentFromTunnel;if(le?.agent?.id){A=le.agent.id,p="",o("onboard","completed",`agent ${A}`);break}p=le?.error??"no agent returned"}catch(re){p=re instanceof Error?re.message:String(re)}if(!/unreachable|resolve hostname|timed out|timeout|ECONN|network|to fetch|50[234]/i.test(p)||j===x-1)break;o("onboard","running",`retry ${j+1}/${x-1}: ${p.slice(0,80)}`),await new Promise((re)=>setTimeout(re,3000*(j+1)))}if(p)o("onboard","failed",p)}else o("onboard","skipped");o("store-creds","running"),We({id:Z,label:l,tunnelUrl:S??"",apiKey:g,permissions:s,addedAt:new Date().toISOString(),agentRecordId:A??void 0,workspaceId:(typeof _.workspaceId==="string"?_.workspaceId:q.workspaceId)??void 0,fingerprint:Z,ownerUserId:q.ownerUserId,sshTarget:a.mode==="ssh"?t.target:void 0,sshIdentityFile:t.identityFile}),o("store-creds","completed");let ne=$t();if(t.onboardBackend!==!1&&T.isConfigured()&&ne&&A){o("report-link","running");try{await T.workspaceQuery(zo,{input:{sourceAgentRecordId:ne,destinationAgentRecordId:A,label:l}}),o("report-link","completed")}catch(x){o("report-link","failed",x instanceof Error?x.message:String(x))}}else o("report-link","skipped");let G=await Se(Z,"/api/profiles/default/agent/identity",{operation:"post-deploy-probe"});return o("probe-peer",G.ok?"completed":"failed",G.error??void 0),{ok:!0,peerId:Z,agentRecordId:A,tunnelUrl:S,permissions:s,remoteVersion:u}}catch(m){return i(m instanceof Error?m.message:String(m))}finally{await a.close().catch(()=>{})}}var Sr='export PATH="$HOME/.bun/bin:$PATH"; ';function qo(t){let n=t.indexOf("{"),o=t.lastIndexOf("}");if(n>=0&&o>n)try{let s=JSON.parse(t.slice(n,o+1));if(s.tunnelUrl)return s.tunnelUrl;if(s.url&&s.url.startsWith("https"))return s.url}catch{}return null}async function Bn(t,n){let o=(a,l,c)=>n?.({step:a,status:l,message:c}),s=Je(t);if(!s)return{ok:!1,peerId:t,tunnelUrl:null,error:`No peer with id ${t}`};if(!s.sshTarget)return{ok:!1,peerId:t,tunnelUrl:null,error:"No SSH target stored for this peer \u2014 it wasn't SSH-deployed, so it can't be woken via SSH."};let i;try{i=et(s.sshTarget,{identityFile:s.sshIdentityFile})}catch(a){return{ok:!1,peerId:t,tunnelUrl:null,error:a instanceof Error?a.message:String(a)}}try{o("ssh-restart","running",s.sshTarget);let a=await i.run(["sh","-c",`${Sr}vibe restart 2>/dev/null || ${Sr}vibe start`],{timeoutMs:90000});if(a.code!==0)return o("ssh-restart","failed",a.stderr.slice(0,300)),{ok:!1,peerId:t,tunnelUrl:null,error:`Remote restart failed (exit ${a.code})`};o("ssh-restart","completed"),o("await-tunnel","running");let l=null;for(let c=0;c<15;c++){let u=await i.run(["sh","-c",`${Sr}vibe url --json 2>/dev/null`],{timeoutMs:15000});if(u.code===0){let f=qo(u.stdout),m=Ir(f);if(m){l=m;break}}await new Promise((f)=>setTimeout(f,2000))}if(!l)return o("await-tunnel","failed","no fresh tunnel after restart"),{ok:!1,peerId:t,tunnelUrl:null,error:"Agent restarted but no fresh tunnel came up."};return o("await-tunnel","completed",l),ke(t,{tunnelUrl:l,lastReachable:new Date().toISOString()}),o("update","completed"),{ok:!0,peerId:t,tunnelUrl:l}}catch(a){return{ok:!1,peerId:t,tunnelUrl:null,error:a instanceof Error?a.message:String(a)}}finally{await i.close().catch(()=>{})}}var Yo=Number(process.env.VIBECONTROLS_MESH_MAX_HOPS||"8");function $n(){return(B()??e()).name}function Xo(){return(B()??e()).dataDir}function Nn(){try{let n=Jo(Xo(),"runtime.json");if(Ko(n)){let o=JSON.parse(Wo(n,"utf8"));if(o.port&&Number.isInteger(o.port))return o.port}}catch{}let t=Number(process.env.PORT);return Number.isInteger(t)&&t>0?t:3005}function Gn(t){let n={};return t.headers.forEach((o,s)=>{n[s]=o}),n}function Be(t,n){let o=L(Gn(t));return Ui(mr(o),n)}function Qo(t){let{apiKey:n,...o}=t;return{...o,apiKey:"[REDACTED]"}}function Ln(t){return typeof t==="string"&&t.startsWith("/api/")&&!t.includes("..")&&!t.includes("//")}var Gt=new Map;function Zo(){let t=Date.now()-3600000;for(let[n,o]of Gt)if(o.completedAt&&Date.parse(o.completedAt)<t)Gt.delete(n)}function jn(){return new E({name:"agent-mesh"}).get("/api/mesh/peers",({request:t,set:n})=>{if(!Be(t,["read"]))return n.status=403,{error:"forbidden"};return{peers:gt(fe()).map(Qo)}}).delete("/api/mesh/peers/:id",({request:t,set:n,params:o})=>{if(!Be(t,["mutate"]))return n.status=403,{error:"forbidden"};if(!gt(fe()).some((i)=>i.id===o.id))return n.status=404,{error:"not found"};return{ok:Bt(o.id)}}).post("/api/mesh/peers/:id/call",async({request:t,set:n,params:o,body:s})=>{if(!Be(t,["mesh:forward"]))return n.status=403,{error:"forbidden"};let i=s;if(!Ln(i.path))return n.status=400,{error:"invalid path"};if(!gt(fe()).find((c)=>c.id===o.id))return n.status=404,{error:"not found"};let l=await Se(o.id,i.path,{method:i.method??"GET",body:i.body,operation:"mesh-call"});return{ok:l.ok,status:l.status,data:l.data,rotated:l.rotated,error:l.error}},{body:r.Object({method:r.Optional(r.String()),path:r.String(),body:r.Optional(r.Any())})}).post("/api/mesh/forward",async({request:t,set:n,body:o})=>{if(!Be(t,["mesh:forward"]))return n.status=403,{error:"forbidden"};let s=o;if(!s.request||!Ln(s.request.path))return n.status=400,{error:"invalid request"};let i=(s._hopCount??0)+1;if(i>Yo)return n.status=422,{error:"hop limit exceeded"};let a=fe(),l=$t(),c=s.hops??[];if(c.length===0){let Z=mr(L(Gn(t))),g=(s.request.method??"GET").toUpperCase();if(!Z||!hr(Z.scopes,g,s.request.path))return e().audit.emit("mesh","forward.denied",{path:s.request.path,method:g}),n.status=403,{error:"forbidden"};e().audit.emit("mesh","forward.terminal",{path:s.request.path,method:s.request.method??"GET"});let S=(s.request.method??"GET").toUpperCase();try{let A=await fetch(`http://127.0.0.1:${Nn()}${s.request.path}`,{method:S,headers:{"x-agent-api-key":await Re(),...s.request.body!==void 0?{"content-type":"application/json"}:{}},body:s.request.body!==void 0?JSON.stringify(s.request.body):void 0,signal:AbortSignal.timeout(60000)}),ne=await A.text().catch(()=>""),G=null;try{G=ne?JSON.parse(ne):null}catch{G=null}return{ok:A.ok,status:A.status,data:G,text:ne||null,error:A.ok?null:ne||`status ${A.status}`}}catch(A){return n.status=502,{ok:!1,status:0,error:A instanceof Error?A.message:String(A)}}}let u=c[0],f=s._traversed??[];if(u===l||f.includes(u))return n.status=422,{error:"cycle detected",at:u};let m=kr(u,a);if(!m)return n.status=403,{error:"next hop not in authorized boundary"};if(!m.permissions.includes("mesh:forward"))return n.status=403,{error:"peer lacks mesh:forward grant"};e().audit.emit("mesh","forward.hop",{nextId:u,remaining:c.length,hopCount:i});let _=encodeURIComponent($n()),q=await Se(m.id,`/api/profiles/${_}/mesh/forward`,{method:"POST",operation:"mesh-forward",timeoutMs:60000,body:{hops:c.slice(1),request:s.request,_traversed:[...f,l??"self"],_hopCount:i}});if(!q.ok)return n.status=502,{ok:!1,status:q.status,error:q.error,failedAtHop:u};return q.data},{body:r.Object({hops:r.Optional(r.Array(r.String())),request:r.Object({method:r.Optional(r.String()),path:r.String(),body:r.Optional(r.Any())}),_traversed:r.Optional(r.Array(r.String())),_hopCount:r.Optional(r.Number())})}).post("/api/mesh/deploy",({request:t,set:n,body:o})=>{if(!Be(t,["admin"]))return n.status=403,{error:"forbidden"};Zo();let s=o,i=fe(),a=crypto.randomUUID(),l={id:a,status:"running",steps:[],ownerUserId:i.ownerUserId,workspaceId:i.workspaceId,startedAt:new Date().toISOString()};return Gt.set(a,l),_n({target:s.target,permissions:s.permissions,installPlugins:s.installPlugins,autostart:s.autostart,identityFile:s.identityFile,label:s.label,version:s.version,connectExisting:s.connectExisting},(c)=>{l.steps.push(c),pe("mesh:deploy:progress",{jobId:a,step:c})}).then((c)=>{if(l.result=c,l.status=c.ok?"completed":"failed",!c.ok)l.error=c.error;l.completedAt=new Date().toISOString(),pe(c.ok?"mesh:deploy:complete":"mesh:deploy:failed",{jobId:a,result:c})}).catch((c)=>{l.status="failed",l.error=c instanceof Error?c.message:String(c),l.completedAt=new Date().toISOString(),pe("mesh:deploy:failed",{jobId:a,error:l.error})}),n.status=202,{jobId:a,status:"running"}},{body:r.Object({target:r.String(),permissions:r.Optional(r.Array(r.String())),installPlugins:r.Optional(r.Array(r.String())),autostart:r.Optional(r.Boolean()),identityFile:r.Optional(r.String()),label:r.Optional(r.String()),version:r.Optional(r.String()),connectExisting:r.Optional(r.Boolean())})}).get("/api/mesh/deploy/jobs/:id",({request:t,set:n,params:o})=>{if(!Be(t,["read"]))return n.status=403,{error:"forbidden"};let s=Gt.get(o.id),i=fe();if(!s||i.ownerUserId&&s.ownerUserId&&s.ownerUserId!==i.ownerUserId)return n.status=404,{error:"not found"};return s}).post("/api/mesh/wake",async({request:t,set:n,body:o})=>{if(!Be(t,["admin"]))return n.status=403,{error:"forbidden"};let s=o,i=kr(s.targetAgentRecordId,fe());if(!i)return n.status=404,{ok:!1,error:"peer not in authorized boundary"};e().audit.emit("mesh","wake.start",{peerId:i.id,agentRecordId:s.targetAgentRecordId});let a=await Bn(i.id,(l)=>pe("mesh:wake:progress",{peerId:i.id,step:l}));if(!a.ok)n.status=502;return a},{body:r.Object({targetAgentRecordId:r.String()})}).post("/api/mesh/session",async({request:t,set:n,body:o})=>{if(!Be(t,["mesh:forward","mutate"]))return n.status=403,{error:"forbidden"};let s=o,i=s.sessionId&&/^[A-Za-z0-9_-]{1,128}$/.test(s.sessionId)?s.sessionId:crypto.randomUUID(),a=encodeURIComponent($n()),l=await Re(),c=`http://127.0.0.1:${Nn()}`,u=s.command||"bash";try{let f=await fetch(`${c}/api/profiles/${a}/sessions/create`,{method:"POST",headers:{"x-agent-api-key":l,"content-type":"application/json"},body:JSON.stringify({sessionId:i,sessionName:`vc-mesh-${i.slice(0,8)}`,command:u,provider:"TERMINAL",...s.vibeId?{projectId:s.vibeId}:{}}),signal:AbortSignal.timeout(20000)});if(!f.ok)return n.status=502,{error:`session create returned ${f.status}: ${await f.text().catch(()=>"")}`};let m=await fetch(`${c}/api/profiles/${a}/sessions/${encodeURIComponent(i)}/terminal`,{method:"POST",headers:{"x-agent-api-key":l},signal:AbortSignal.timeout(20000)});if(!m.ok)return n.status=502,{error:`terminal start returned ${m.status}: ${await m.text().catch(()=>"")}`};let _=fr(`/terminal/${i}`,600);return e().audit.emit("mesh","session.created",{sessionId:i,kind:s.kind??"TERMINAL"}),{connectionId:i,sessionId:i,capabilityToken:_.token,expiresAt:_.expiresAt}}catch(f){return n.status=502,{error:f instanceof Error?f.message:String(f)}}},{body:r.Object({sessionId:r.Optional(r.String()),kind:r.Optional(r.String()),cwd:r.Optional(r.String()),vibeId:r.Optional(r.String()),command:r.Optional(r.String())})})}var ea=["/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 ta(t){return ea.some((n)=>t.startsWith(n))}var ra=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function na(t){return t.split("/").map((n)=>{if(!n)return n;if(/^\d+$/.test(n))return":id";if(ra.test(n))return":id";if(n.length>=24&&/^[A-Za-z0-9_-]+$/.test(n))return":id";return n}).join("/")}async function br(t){let{port:n,host:o,dbPath:s,logLevel:i,corsOrigin:a}=t,l=s??ee();try{let d=await import("fs");d.mkdirSync(l,{recursive:!0})}catch(d){throw e().logger.error("app","Failed to create dbPath dir at boot",{dbPath:l,error:String(d)}),Error(`Cannot create dbPath ${l}: ${d instanceof Error?d.message:String(d)}`,{cause:d})}if(i)e().logger.setLevel(i);(async()=>{let{logShipper:d}=await import("./log-shipper-02rqvtq8.js");d.init()})(),(async()=>{let d=await Hn();await xt({version:d,profile:R()})})();try{let{checkDependencies:d}=await import("./bootstrap.service-gehm65tt.js"),U=d(),y=U.filter((H)=>H.required&&!H.installed),F=U.filter((H)=>!H.required&&!H.installed);if(y.length>0)e().logger.error("app",`Missing required system deps: ${y.map((H)=>H.name).join(", ")}. Run \`vibe setup\` to install.`);if(F.length>0)e().logger.warn("app",`Missing optional system deps: ${F.map((H)=>H.name).join(", ")}. Some plugins may fail their prereqs check.`)}catch(d){e().logger.warn("app","Boot-time dependency check failed",{error:String(d)})}try{e().audit.runRetention()}catch(d){e().logger.warn("app","Audit-log retention sweep failed",{error:String(d)})}let c=new xe;Nr(c,{port:n});let u="GET, POST, PUT, PATCH, DELETE, OPTIONS",f="Content-Type, x-agent-api-key, Authorization, x-requested-with",m=Array.isArray(a)?a:(a??"").split(",").map((d)=>d.trim()).filter(Boolean),_=(d)=>_i(d,{configuredOrigins:m,devPorts:t.devCorsPorts}),q=()=>{let d=R(),U=or(d);return[process.env.AGENT_TUNNEL_URL,process.env[`AGENT_TUNNEL_URL_${U}`],lt(),te()?.url]},Z=async()=>{let d=[],U=[],y=c.getProvider("tunnel");if(y)U.push(y);for(let F of c.listProvidersForType("tunnel")){let H=c.getProviderByName("tunnel",F.pluginName);if(H&&!U.includes(H))U.push(H)}for(let F of U){if(!F.getActiveTunnelUrl)continue;try{let H=await F.getActiveTunnelUrl();if(H)d.push(H)}catch{}}return d},g=null,S=null,A=null,ne=null,G=!1,x=()=>[],p=null,j=null,J=null,re=5000,le=async(d,U)=>{let y=Date.now();try{await Promise.race([Promise.resolve(U()),new Promise((F,H)=>setTimeout(()=>H(Error(`shutdown phase ${d} exceeded ${re}ms`)),re))]),e().logger.info("app",`shutdown.phase ${d} complete`,{ms:Date.now()-y})}catch(F){e().logger.warn("app",`shutdown.phase ${d} failed`,{error:String(F),ms:Date.now()-y})}},De=async(d)=>{if(G)return;if(G=!0,e().logger.info("app","Agent shutdown starting",{reason:d?.reason??"shutdown"}),await le("plugins",async()=>{if(S)await S.dispatchServerStop(d)}),await le("bootstrap-tunnel",()=>ar()),await le("tracked-subprocesses",async()=>{let{killAllTracked:U}=await import("./subprocess-p9bv9nqz.js");await U()}),d?.reason!=="reload")await le("db-close",async()=>{if(g)await g.close()});await le("http-listener",async()=>{try{await Promise.resolve(Ee.stop())}catch(U){e().logger.warn("app","Listener stop threw (already stopped or never started?)",{error:String(U)})}}),e().logger.info("app","Agent server stopped"),e().logger.close()},ae=async(d,U)=>{if(e().getBootState()==="ready")return{ok:!0};if(J)return J;return J=(async()=>{e().setBootState("initializing");try{let y={...d,globalGatewayUrl:z(d.globalGatewayUrl,"globalGatewayUrl"),workspaceGatewayUrl:z(d.workspaceGatewayUrl,"workspaceGatewayUrl")},F=await tr(y),H=l,ce=w({dir:e().dataDir}),ge=ce.storageAdapter??process.env.VIBE_STORAGE_ADAPTER??void 0,be=ce.storageOptions,Ce=(h)=>{let v=(h instanceof Error?h.message:String(h)).toLowerCase(),Y=h&&typeof h==="object"&&"code"in h?String(h.code).toUpperCase():"";if(Y==="EBUSY"||Y==="EPERM"||Y==="EACCES"||Y==="EAGAIN"||Y==="EMFILE"||Y==="ENFILE"||Y==="ETIMEDOUT"||Y==="ECONNRESET"||Y==="ECONNREFUSED"||v.includes("encryption key")||v.includes("fetch")&&v.includes("key")||v.includes("temporarily unavailable")||v.includes("resource busy"))return"transient";if(v.includes("auth tag")||v.includes("authentication tag")||v.includes("unable to authenticate data")||v.includes("bad decrypt")||v.includes("unsupported state")||v.includes("incorrect header check")||v.includes("invalid distance")||v.includes("incorrect data check")||v.includes("unexpected end of")||v.includes("unexpected token")||v.includes("json")&&(v.includes("parse")||v.includes("invalid"))||v.includes("truncated")||v.includes("malformed")||v.includes("corrupt"))return"corruption";return"unknown"},Ke=()=>er({dbPath:H,encryptionKey:F,adapterName:ge,adapterOptions:be});try{g=await Ke()}catch(h){let v=h,Y=Ce(h),kt=[500,2000,8000];if(Y==="transient"||Y==="unknown"){e().logger.warn("app",`Storage open failed (${Y}); will retry up to ${kt.length} times before quarantine`,{error:h instanceof Error?h.message:String(h),path:H});for(let st of kt){await new Promise((ie)=>setTimeout(ie,st));try{g=await Ke(),v=null;break}catch(ie){if(v=ie,Y=Ce(ie),e().logger.warn("app",`Storage open retry failed (${Y}) after ${st}ms`,{error:ie instanceof Error?ie.message:String(ie)}),Y==="corruption")break}}}if(!g&&v){if(Y!=="corruption"){let ie=v instanceof Error?v.message:String(v);e().logger.error("app",`Storage open failed after retries with non-corruption error (${Y}); refusing to quarantine valid data`,{error:ie,path:H}),e().recordDegradedReason("storage",ie);try{throw v}catch(Fe){throw Error(`Storage open failed (${Y}); agent is degraded: ${ie}`,{cause:Fe})}}let st=v instanceof Error?v.message:String(v);e().logger.error("app","QUARANTINE: Storage file is corrupt \u2014 renaming and creating fresh DB",{errorClass:"corruption",error:st,path:H});try{let ie=await import("fs");if(ie.existsSync(H)){let Fe=new Date().toISOString().replace(/[:.]/g,"-"),Cr=`${H}.broken-${Fe}`;ie.renameSync(H,Cr),e().logger.warn("app",`Quarantined corrupt storage to ${Cr} \u2014 fresh DB will be created`,{originalError:st})}g=await Ke()}catch(ie){let Fe=ie instanceof Error?ie.message:String(ie);throw e().recordDegradedReason("storage",Fe),Error(`Storage open failed twice (quarantine path); agent is degraded: ${Fe}`,{cause:ie})}}}if(!g)throw Error("Internal error: storage open recovery exited without an open database and without throwing");if(await Yt({clientId:y.clientId,clientSecret:y.clientSecret,workspaceId:y.workspaceId,organizationId:y.organizationId,globalGatewayUrl:y.globalGatewayUrl,workspaceGatewayUrl:y.workspaceGatewayUrl,agentRecordId:U?.agentRecordId,scopes:U?.scopes,pairedIdentity:Zt({workspaceId:y.workspaceId,globalGatewayUrl:y.globalGatewayUrl,workspaceGatewayUrl:y.workspaceGatewayUrl,agentRecordId:U?.agentRecordId})},{dir:e().dataDir,scope:e().name}),await g.setConfig("gateway-auth:clientId",y.clientId),await g.setConfig("gateway-auth:clientSecret",y.clientSecret),await g.setConfig("gateway-auth:globalGatewayUrl",y.globalGatewayUrl),await g.setConfig("gateway-auth:workspaceGatewayUrl",y.workspaceGatewayUrl),await g.setConfig("gateway-auth:workspaceId",y.workspaceId),y.organizationId)await g.setConfig("gateway-auth:organizationId",y.organizationId);if(U?.agentRecordId)await g.setConfig("gateway-auth:agentRecordId",U.agentRecordId);c.db=g,await c.hydrateDefaultsFromDb(),S=new W(g),await S.loadCorePlugins();try{await S.loadAll()}catch(h){e().logger.warn("app","Failed to load some external plugins",{error:String(h)})}let Ye=Ze(C())??void 0,tt=process.env.VIBE_SKIP_AUTO_INSTALL==="1"||await g.getConfig("plugins:auto-install-disabled");if(tt!=="true"&&tt!==!0)try{let h=await S.ensureDefaultPlugins((v)=>e().logger.info("app",`[auto-install] ${v}`),[],Ye);if(h.length>0)e().logger.info("app",`Auto-installed ${h.length} default plugin(s): ${h.map((v)=>v.packageName).join(", ")}`)}catch(h){e().logger.warn("app","Failed to auto-install default plugins",{error:String(h)})}e().logger.info("app",`Plugins loaded: ${S.getPluginDetails().length} total (${S.getPluginDetails().filter((h)=>h.isCore).length} core)`);try{let h=S.getPluginDetails(),v={loaded:h.filter((Y)=>Y.loaded).length,failed:h.filter((Y)=>!Y.loaded).length};un(v)}catch{}let Ft={async get(h,v){return await g.getPluginState(h,v)??null},async set(h,v,Y){await g.setPluginState(h,v,Y)},async delete(h,v){return g.deletePluginState(h,v)},async list(h){return await g.getAllPluginState(h)},async deleteAll(h){return g.deleteAllPluginState(h)}},vt=await Hn();A={storage:Ft,logger:e().logger,serviceRegistry:c,getProvider:(h)=>c.getProvider(h),getAgentBaseUrl:()=>process.env.AGENT_URL||`http://localhost:${n}`,getAgentVersion:()=>vt,validateApiKey:(h)=>V(h),setCodeServerSessionValidator:(h)=>{zn=h},broadcast:pe,workspaceQuery:async(h,v)=>T.workspaceQuery(h,v),isGatewayConfigured:()=>T.isConfigured(),getAgentRecordId:async()=>await g.getConfig("gateway-auth:agentRecordId")??null,getWorkspaceId:async()=>await g.getConfig("gateway-auth:workspaceId")??null,getConfig:async(h)=>await g.getConfig(h)??void 0,getPluginRegistry:()=>se(),getDataDir:()=>I(),cliContributors:new Ie,audit:{emit:(h,v)=>e().audit.emit("agent",h,v??{})},telemetry:{emit:(h,v)=>{import("./telemetry-1d3t1mbf.js").then(({telemetryService:Y})=>Y.emit(h,v??{})).catch(()=>{})}},os:b(),iframeBridge:ve()},T.configure({globalGatewayUrl:y.globalGatewayUrl,workspaceGatewayUrl:y.workspaceGatewayUrl,clientId:y.clientId,clientSecret:y.clientSecret,workspaceId:y.workspaceId,organizationId:y.organizationId});let Ge={db:g,serviceRegistry:c,pluginManager:S,broadcast:pe,hostServices:A};Ge.app=Ee;let Er=!1,Ht=()=>{let{routes:h,getPublicPaths:v,mountPlugin:Y}=gr(S,Ge);if(Ge.mountPlugin=Y,x=v,Ki(),p=h,j=Oi(S),S&&Er&&A)S.dispatchServerStart(p,A).catch((kt)=>e().logger.warn("app","Re-dispatch of onServerStart after plugin reload failed",{error:String(kt)}));Er=!0};Ge.rebuildPluginSurfaces=Ht,Ht(),ne=new Rt(c,S,g,Ee,A,De),c.registerService("agent","lifecycle",ne),e().attachServices({db:g,serviceRegistry:c,pluginManager:S,lifecycle:ne,hostServices:A}),_t(e(),{rebuildPluginSurfaces:Ht,mountPlugin:Ge.mountPlugin,app:p});try{await e().keyVault.bindApiKey(K())}catch(h){e().logger.warn("app","Failed to bind api key into daemon keyVault",{error:String(h)})}let Vt=[];try{let{failures:h}=await S.dispatchServerStart(p,A);for(let v of h)if(Et(v.plugin)||(v.packageName?Et(v.packageName):!1))Vt.push(v),e().recordDegradedReason(v.plugin,v.error);else e().logger.warn("app",`Non-critical plugin ${v.plugin} failed onServerStart; continuing`,{error:v.error})}catch(h){e().logger.warn("app","Error during plugin onServerStart dispatch",{error:String(h)})}try{await S.dispatchServerReady(Ee,A)}catch(h){e().logger.warn("app","Error during plugin onServerReady dispatch",{error:String(h)})}if(e().clearFinalizeError(),Vt.length>0)e().setBootState("degraded"),e().logger.error("app","Agent finalized but degraded \u2014 critical plugins failed",{failures:Vt.map((h)=>`${h.plugin}: ${h.error}`)});else e().setBootState("ready"),e().logger.info("app","Agent finalized \u2014 state=ready"),e().audit.emit("agent","gateway-auth.configured",{workspaceId:y.workspaceId,organizationId:y.organizationId,agentRecordId:U?.agentRecordId});return(async()=>{try{if(await S.provisionDefaultPrereqs(Ee,A,Ge.mountPlugin,Ye),e().logger.info("app","Default provider prerequisites provisioned"),(c.listProvidersForType("tunnel")??[]).some((Y)=>Y.pluginName!=="bootstrap")){let{tryHandoverBootstrapTunnel:Y}=await import("./tunnel-bootstrap-20vwak7q.js");if(!Y())ar();c.unregisterProvider("tunnel","bootstrap"),e().logger.info("app","Bootstrap tunnel handed over to the real tunnel provider")}}catch(h){e().logger.warn("app","Plugin prerequisite provisioning failed",{error:String(h)})}})(),{ok:!0}}catch(y){e().setBootState("awaiting-config");let F=y instanceof Error?y.message:String(y);if(e().recordFinalizeError(F),e().logger.error("app","Finalize failed",{error:F}),process.env.VIBE_STRICT_KEY_FETCH==="1")e().logger.error("app","VIBE_STRICT_KEY_FETCH=1 \u2192 aborting daemon (strict mode)",{error:F}),setTimeout(()=>process.exit(1),50);return{ok:!1,error:F}}finally{J=null}})(),J},de=Ur({origin:(d)=>{let U=d.headers.get("origin");return!!U&&_(U)},credentials:!0,allowedHeaders:f.split(",").map((d)=>d.trim()),methods:u.split(",").map((d)=>d.trim()),exposeHeaders:["content-type","content-length"],maxAge:86400,preflight:!0}),Me=10485760,Pr=process.env.VIBECONTROLS_MAX_BODY_BYTES,jt=Pr?Number.parseInt(Pr,10):NaN,Vn=Number.isFinite(jt)&&jt>0?jt:Me,Ar={current:null},Ee=new E({serve:{maxRequestBodySize:Vn}}).onRequest(async({request:d})=>{let U={port:n,allowedHosts:t.allowedHosts,tunnelUrls:q()},y=Or(d,U);if(!y&&c.hasProvider("tunnel")){let F=await Z();if(F.length>0)y=Or(d,{...U,tunnelUrls:[...U.tunnelUrls,...F]})}if(!y)return new Response(JSON.stringify({error:"Forbidden",message:"Invalid or disallowed Host header"}),{status:403,headers:{"content-type":"application/json"}});try{let F=new URL(d.url).pathname;if((F==="/api/agent/api-key"||/^\/api\/profiles\/[^/]+\/agent\/api-key(?:\/|$)/.test(F))&&Ve(d))return new Response(JSON.stringify({error:"Forbidden",message:"Browser requests are not permitted on /api/agent/api-key"}),{status:403,headers:{"content-type":"application/json"}})}catch{}}).onRequest(({request:d,set:U})=>{let F=Hi(d.headers)??Ai();Vi({requestId:F,startedAt:new Date().toISOString()});let H=U.headers??={};H["X-Request-Id"]=F}).onRequest(({request:d})=>{try{let U=new URL(d.url).pathname,F=/^\/api\/profiles\/([^/]+)(?:\/|$)/.exec(U)?.[1],H=F?N.get(F):null;wt(H??e())}catch{wt(e())}}).onRequest(({request:d,set:U})=>{let y=new URL(d.url).pathname;if(!y.startsWith("/api/"))return;if(y==="/api/profiles"||y.startsWith("/api/profiles/"))return;if(y==="/api/profile-stats"||y.startsWith("/api/profile-stats/"))return;let F=new URL(d.url);F.pathname=`/api/profiles/default${y.slice(4)}`;try{d.headers.set("x-vc-profile-rewrite","1"),d.headers.set("x-vc-profile-rewrite-target",F.pathname)}catch{}return}).derive(()=>({requestId:Tt()??Ai()})).use(de).use(Ni()).use(Qi(()=>x())).use(Br({getDb:()=>B()?.db??g})).onBeforeHandle(({request:d,set:U})=>{let y=e().getBootState();if(y==="ready")return;let F=new URL(d.url).pathname;if(ta(F))return;return U.status=503,{error:"Agent not yet configured",message:"Agent is in '"+y+"' state. POST credentials to /api/agent/gateway-auth to finalize.",state:y}}).onAfterHandle(({request:d,set:U})=>{let y=new URL(d.url).pathname,F=y==="/health"||y.startsWith("/api/logs/stream")||y.startsWith("/ui/")||y==="/ws/events"||y==="/api/sessions/health-check"||y.startsWith("/terminal/"),H=typeof U.status==="number"?U.status:200,ce=F?"debug":H>=400?"warn":"info";e().logger[ce]("http",`${d.method} ${y} \u2192 ${H}`,{method:d.method,path:y,statusCode:H});try{cn(d.method,na(y),H)}catch{}}).use(nn({serviceRegistry:c,getDb:()=>B()?.db??g,getDbPath:()=>l,getPluginManager:()=>B()?.pluginManager??S})).use(gn()).use(Wr({serviceRegistry:c,runFinalize:(d,U)=>ae(d,U),getDb:()=>B()?.db??g})).use(an()).use(sn()).use(Dn({getPluginManager:()=>B()?.pluginManager??S})).use(jn()).use(fn()).use(Sn({getPluginManager:()=>B()?.pluginManager??S,getTunnelHost:()=>te()?.url??null})).use(en()).use(tn()).use(Qr()).use(Gr()).use(jr(c)).ws("/code-server/*",aa(n)).all("/api/profiles/:name/*",async({params:d,request:U,set:y})=>{let F=U.method!=="GET"&&U.method!=="HEAD",H=F?await U.arrayBuffer():void 0,ce=await $r(d.name,U,H);if(ce&&ce.status!==404)return ce;let ge=R(),be=d.name;if(be!==ge)return y.status=404,{error:"profile-mismatch",running:ge,requested:be,hint:"This daemon serves a different profile. Call GET /api/profiles to discover the right tunnel."};let Ce=new URL(U.url),Ke=Ce.pathname.replace(/^\/api\/profiles\/[^/]+/,"/api"),Ye=new Headers(U.headers);Ye.set("x-vc-profile-rewrite","1");let tt={method:U.method,headers:Ye};if(F&&H!==void 0)tt.body=H;let Ft=new Request(`${Ce.origin}${Ke}${Ce.search}`,tt),vt=Ar.current;if(!vt)return new Response(JSON.stringify({error:"agent-not-ready"}),{status:503,headers:{"content-type":"application/json"}});return vt.handle(Ft)}).all("/api/*",async({request:d})=>{if(e().getBootState()!=="ready"||!p)return new Response(JSON.stringify({error:"Agent not yet configured",state:e().getBootState(),message:"Plugin routes are unavailable until the agent reaches state=ready. POST credentials to /api/agent/gateway-auth to finalize."}),{status:503,headers:{"content-type":"application/json"}});try{let U=new URL(d.url),y=/^\/api\/plugins\/([a-z0-9-]{1,64})\/ui(?:\/.*)?$/.exec(U.pathname);if(y&&d.method==="GET"){let F=y[1];if(me(F)){let H=U.pathname.slice(`/api/plugins/${F}/ui`.length),ce=H===""||H==="/",be=d.headers.get("sec-fetch-mode")==="navigate";if(ce||be){let Ce=it(d,F);if(!Ce||!rt(Ce,F))return new Response(vr(F,"/api/profiles/default/agent/ui-exchange-plugin"),{status:200,headers:{"content-type":"text/html; charset=utf-8","Content-Security-Policy":"frame-ancestors 'self' http://localhost:* http://127.0.0.1:* https://localhost:* https://127.0.0.1:* https://*.local.burdenoff.com https://vibecontrols.com https://*.vibecontrols.com https://burdenoff.com https://app.burdenoff.com https://alphaapp.burdenoff.com"}})}}}}catch{}return p.handle(d)}).all("/ui/*",async({request:d})=>{if(e().getBootState()!=="ready"||!j)return new Response("Plugin UI not yet available",{status:503});return j.handle(d)}).all("/code-server/*",async({request:d})=>{if(e().getBootState()!=="ready"||!p)return new Response("code-server not yet available",{status:503});let U=Dr(d,K);return p.handle(U??d)}).all("/plan/*",async({request:d})=>{if(e().getBootState()!=="ready"||!p)return new Response("plan provider not yet available",{status:503});return p.handle(d)});return Ar.current=Ee,{app:Ee,async start(){Ee.listen({port:n,hostname:o}),e().logger.info("app",`Agent server listening on ${o}:${n}`);try{let d=(process.env.VIBECONTROLS_PROFILES??"").split(",").map((ce)=>ce.trim()).filter(Boolean),U=e().name,{getOrCreateProfile:y}=await import("./daemon-profile-fnhc7pcf.js"),{attachSecondaryProfile:F}=await import("./secondary-profile-attach-222s85md.js"),H=process.env.VIBE_STRICT_KEY_FETCH==="1";for(let ce of d){if(ce===U)continue;try{let ge=y(ce),be=await F(ge);if(be.ok)e().logger.info("app",`Secondary profile '${ce}' attached (db+services online)`);else if(H)throw Error(`attachServices for secondary profile '${ce}' failed: ${be.error}`);else ge.recordDegradedReason("attach",be.error??"unknown"),e().logger.warn("app",`Secondary profile '${ce}' is degraded (no creds / attach failed)`,{error:be.error})}catch(ge){if(H)throw e().logger.error("app",`--strict-key-fetch: secondary profile '${ce}' attach failed; aborting`,{error:String(ge)}),setTimeout(()=>process.exit(1),50),ge;e().logger.warn("app",`Failed to attach secondary profile '${ce}'`,{error:String(ge)})}}}catch{}return Ee},stop:De,finalize:ae,getState:()=>e().getBootState(),getLifecycle:()=>B()?.lifecycle??ne,getDb:()=>B()?.db??g,getServiceRegistry:()=>B()?.serviceRegistry??c,getPluginManager:()=>B()?.pluginManager??S,getHostServices:()=>B()?.hostServices??A}}var zn=null;function oa(t,n){if(!t)return null;let o=t.match(new RegExp(`(?:^|;\\s*)${n}=([^;]*)`));return o?o[1]:null}var Fn=dr(ki);function aa(t){let i=(a)=>typeof a==="string"?Buffer.byteLength(a):a.byteLength;return{open(a){let l=a.data,c=L(l.headers??{})??L(l.request?Object.fromEntries(l.request.headers.entries()):{}),u=l.query?.vt,f=!!u&&qe(u,"/code-server","GET"),m,_=V(c);if(!_&&!f){let S=l.headers?.cookie??l.request?.headers.get("cookie")??null,A=oa(S,"__vibe_cs_session");if(!A||!zn?.(A)){a.close(1008,"Unauthorized");return}m=`session:${A}`}else if(_)m="api-key";else m="vt";let q=a.remoteAddress??null,Z=Qe(q,l.headers);if(!Fn.accept(m,Z,a)){e().logger.warn("code-server-ws",`code-server WS cap exceeded (key=${m}, ip=${Z??"unknown"})`),a.close(1013,"too many connections");return}l._csCapKey=m,l._csRemoteIp=Z;let g=e().name;fetch(`http://127.0.0.1:${t}/api/profiles/${encodeURIComponent(g)}/code-server/status`,{headers:{"x-agent-api-key":K()}}).then((S)=>S.json()).then((S)=>{if(l._csClosed)return;let A=S;if(!A.running||!A.port){a.close(1011,"code-server not running");return}let ne=l.request?.url??"/code-server/",G;try{let j=new URL(ne,`http://127.0.0.1:${A.port}`);G=(j.pathname.replace(/^\/code-server\/?/,"/")||"/")+j.search}catch{G="/"}let x=new WebSocket(`ws://127.0.0.1:${A.port}${G}`),p={upstream:x,ready:!1,buffer:[],bufferBytes:0,openTimer:setTimeout(()=>{try{x.close(1011,"upstream open timeout")}catch{}try{a.close(1011,"upstream open timeout")}catch{}},1e4)};l._csBridge=p,x.addEventListener("open",()=>{clearTimeout(p.openTimer),p.ready=!0;for(let j of p.buffer)x.send(j);p.buffer.length=0,p.bufferBytes=0}),x.addEventListener("message",(j)=>{try{let J=j.data;if(J instanceof ArrayBuffer)a.send(new Uint8Array(J));else if(J instanceof Blob)J.arrayBuffer().then((re)=>{try{a.send(new Uint8Array(re))}catch{}});else a.send(J)}catch{}}),x.addEventListener("close",(j)=>{clearTimeout(p.openTimer);try{a.close(j.code||1000,j.reason||"upstream closed")}catch{}}),x.addEventListener("error",()=>{clearTimeout(p.openTimer);try{a.close(1011,"upstream error")}catch{}})}).catch(()=>{a.close(1011,"Failed to query code-server status")})},message(a,l){let c=a.data?._csBridge;if(!c)return;let u;if(typeof l==="string")u=l;else if(l instanceof ArrayBuffer)u=l;else if(l instanceof Uint8Array||Buffer.isBuffer(l)){let f=new ArrayBuffer(l.byteLength);new Uint8Array(f).set(new Uint8Array(l.buffer,l.byteOffset,l.byteLength)),u=f}else if(typeof l==="object"&&l!==null)u=JSON.stringify(l);else u=String(l);if(c.upstream&&c.ready&&c.upstream.readyState===WebSocket.OPEN)try{c.upstream.send(u)}catch{}else{let f=i(u);if(c.buffer.length>=256||c.bufferBytes+f>1048576){try{c.upstream.close(1013,"buffer limit exceeded")}catch{}try{a.close(1013,"buffer limit exceeded")}catch{}return}c.buffer.push(u),c.bufferBytes+=f}},close(a){a.data._csClosed=!0;let l=a.data?._csBridge;if(l?.openTimer)clearTimeout(l.openTimer);if(l?.upstream&&l.upstream.readyState===WebSocket.OPEN)l.upstream.close(1000,"client disconnected");let c=a.data._csCapKey,u=a.data._csRemoteIp;if(c)Fn.release(c,u??null,a)}}}async function Hn(){try{let{readFileSync:t}=await import("fs"),{join:n,dirname:o}=await import("path"),{fileURLToPath:s}=await import("url"),i=o(s(import.meta.url));return JSON.parse(t(n(i,"..","package.json"),"utf8")).version||"1.0.0"}catch{return"1.0.0"}}
|
|
25
|
+
}`,Mn="VIBE_BOOTSTRAP_JSON=";function Vo(t){for(let s of t.split(/\r?\n/)){let i=s.indexOf(Mn);if(i>=0)try{return JSON.parse(s.slice(i+Mn.length))}catch{}}let n=t.indexOf("{"),o=t.lastIndexOf("}");if(n>=0&&o>n)try{return JSON.parse(t.slice(n,o+1))}catch{return null}return null}async function _n(t,n){let o=(m,_,q)=>n?.({step:m,status:_,message:q}),s=Xe(t.permissions??["tunnel:read","session:list","plugin:list","diagnostics:read","mesh:forward"]);if(!s.includes("mesh:forward"))s.push("mesh:forward");let i=(m)=>({ok:!1,peerId:"",agentRecordId:null,tunnelUrl:null,permissions:s,error:m}),a;try{a=et(t.target,{identityFile:t.identityFile})}catch(m){return i(m instanceof Error?m.message:String(m))}let l=t.label??a.id,c=s.join(","),u,f='export PATH="$HOME/.bun/bin:$PATH"; ';try{if(!t.connectExisting){o("probe","running");let x=await a.probe();if(o("probe","completed",`os=${x.os??"?"} arch=${x.arch??"?"}`),!x.bun){if(t.installBun===!1)return i("Bun is required to run the agent but is not installed, and Bun auto-install was disabled.");o("install-bun","running");let ae=await a.run(["sh","-c",`curl -fsSL https://bun.sh/install | bash && echo 'export PATH="$HOME/.bun/bin:$PATH"' >> ~/.bashrc`],{timeoutMs:300000});if(ae.code!==0)return o("install-bun","failed",ae.stderr.slice(0,400)),i("Bun auto-install failed.");let de=await a.run(["sh","-c","$HOME/.bun/bin/bun --version 2>/dev/null"],{timeoutMs:1e4});if(de.code===0&&de.stdout.trim())x.bun="$HOME/.bun/bin/bun",o("install-bun","completed",de.stdout.trim());else return i("Bun installed but the binary is not reachable.")}o("install-agent","running");let p=t.version??"latest",j=t.registry??"https://registry.npmjs.org/",J,re;try{J=dt(p)}catch(ae){return o("install-agent","failed","invalid version"),i(ae instanceof Error?ae.message:String(ae))}try{re=ht(j)}catch(ae){return o("install-agent","failed","invalid registry"),i(ae instanceof Error?ae.message:String(ae))}let le=await a.run(Pt(re,J),{timeoutMs:600000});if(le.code!==0)return o("install-agent","failed",le.stderr.slice(0,400)),i(`Agent install failed (exit ${le.code}).`);if(u=(await a.run(["sh","-c",`${f}vibe --version`],{timeoutMs:15000})).stdout.trim()||void 0,o("install-agent","completed",u),t.autostart)o("autostart","running"),await a.run(["sh","-c",`${f}vibe autostart install`],{timeoutMs:60000}),o("autostart","completed");if(t.installPlugins?.length){o("plugins","running");for(let ae of t.installPlugins){let de;try{de=ft(ae)}catch(Me){return o("plugins","failed","invalid plugin package"),i(Me instanceof Error?Me.message:String(Me))}await a.run(Mt(de),{timeoutMs:300000})}o("plugins","completed")}o("start","running"),await a.run(["sh","-c",`${f}vibe start`],{timeoutMs:60000}),o("start","completed")}o("bootstrap","running");let m;try{let x=mt(l),p=t.expiresIn?pt(t.expiresIn):void 0;m=Dt({label:x,scope:c,expiresIn:p,json:!0,emitDefaultKey:!0})}catch(x){return o("bootstrap","failed","invalid bootstrap arguments"),i(x instanceof Error?x.message:String(x))}let _=null;for(let x=0;x<15;x++){let p=await a.run(m,{timeoutMs:15000});if(p.code===0){let j=Vo(p.stdout);if(j&&typeof j.apiKey==="string"){_=j;break}}await new Promise((j)=>setTimeout(j,2000))}if(!_)return o("bootstrap","failed","could not obtain peer-bootstrap bundle"),i("Remote peer-bootstrap did not return a credential bundle.");o("bootstrap","completed");let q=fe(),Z=String(_.id),g=String(_.apiKey),S=Ir(typeof _.tunnelUrl==="string"?_.tunnelUrl:null),A=typeof _.agentRecordId==="string"?_.agentRecordId:null;if(t.onboardBackend!==!1&&T.isConfigured()&&S&&typeof _.fullDefaultApiKey==="string"){o("onboard","running");let x=5,p="no agent returned";for(let j=0;j<x;j++){try{let le=(await T.workspaceQuery(Ho,{input:{tunnelUrl:S,apiKey:_.fullDefaultApiKey,name:l}})).data?.addVibecontrolsAgentFromTunnel;if(le?.agent?.id){A=le.agent.id,p="",o("onboard","completed",`agent ${A}`);break}p=le?.error??"no agent returned"}catch(re){p=re instanceof Error?re.message:String(re)}if(!/unreachable|resolve hostname|timed out|timeout|ECONN|network|to fetch|50[234]/i.test(p)||j===x-1)break;o("onboard","running",`retry ${j+1}/${x-1}: ${p.slice(0,80)}`),await new Promise((re)=>setTimeout(re,3000*(j+1)))}if(p)o("onboard","failed",p)}else o("onboard","skipped");o("store-creds","running"),We({id:Z,label:l,tunnelUrl:S??"",apiKey:g,permissions:s,addedAt:new Date().toISOString(),agentRecordId:A??void 0,workspaceId:(typeof _.workspaceId==="string"?_.workspaceId:q.workspaceId)??void 0,fingerprint:Z,ownerUserId:q.ownerUserId,sshTarget:a.mode==="ssh"?t.target:void 0,sshIdentityFile:t.identityFile}),o("store-creds","completed");let ne=$t();if(t.onboardBackend!==!1&&T.isConfigured()&&ne&&A){o("report-link","running");try{await T.workspaceQuery(zo,{input:{sourceAgentRecordId:ne,destinationAgentRecordId:A,label:l}}),o("report-link","completed")}catch(x){o("report-link","failed",x instanceof Error?x.message:String(x))}}else o("report-link","skipped");let G=await Se(Z,"/api/profiles/default/agent/identity",{operation:"post-deploy-probe"});return o("probe-peer",G.ok?"completed":"failed",G.error??void 0),{ok:!0,peerId:Z,agentRecordId:A,tunnelUrl:S,permissions:s,remoteVersion:u}}catch(m){return i(m instanceof Error?m.message:String(m))}finally{await a.close().catch(()=>{})}}var Sr='export PATH="$HOME/.bun/bin:$PATH"; ';function qo(t){let n=t.indexOf("{"),o=t.lastIndexOf("}");if(n>=0&&o>n)try{let s=JSON.parse(t.slice(n,o+1));if(s.tunnelUrl)return s.tunnelUrl;if(s.url&&s.url.startsWith("https"))return s.url}catch{}return null}async function Bn(t,n){let o=(a,l,c)=>n?.({step:a,status:l,message:c}),s=Je(t);if(!s)return{ok:!1,peerId:t,tunnelUrl:null,error:`No peer with id ${t}`};if(!s.sshTarget)return{ok:!1,peerId:t,tunnelUrl:null,error:"No SSH target stored for this peer \u2014 it wasn't SSH-deployed, so it can't be woken via SSH."};let i;try{i=et(s.sshTarget,{identityFile:s.sshIdentityFile})}catch(a){return{ok:!1,peerId:t,tunnelUrl:null,error:a instanceof Error?a.message:String(a)}}try{o("ssh-restart","running",s.sshTarget);let a=await i.run(["sh","-c",`${Sr}vibe restart 2>/dev/null || ${Sr}vibe start`],{timeoutMs:90000});if(a.code!==0)return o("ssh-restart","failed",a.stderr.slice(0,300)),{ok:!1,peerId:t,tunnelUrl:null,error:`Remote restart failed (exit ${a.code})`};o("ssh-restart","completed"),o("await-tunnel","running");let l=null;for(let c=0;c<15;c++){let u=await i.run(["sh","-c",`${Sr}vibe url --json 2>/dev/null`],{timeoutMs:15000});if(u.code===0){let f=qo(u.stdout),m=Ir(f);if(m){l=m;break}}await new Promise((f)=>setTimeout(f,2000))}if(!l)return o("await-tunnel","failed","no fresh tunnel after restart"),{ok:!1,peerId:t,tunnelUrl:null,error:"Agent restarted but no fresh tunnel came up."};return o("await-tunnel","completed",l),ke(t,{tunnelUrl:l,lastReachable:new Date().toISOString()}),o("update","completed"),{ok:!0,peerId:t,tunnelUrl:l}}catch(a){return{ok:!1,peerId:t,tunnelUrl:null,error:a instanceof Error?a.message:String(a)}}finally{await i.close().catch(()=>{})}}var Yo=Number(process.env.VIBECONTROLS_MESH_MAX_HOPS||"8");function $n(){return(B()??e()).name}function Xo(){return(B()??e()).dataDir}function Nn(){try{let n=Jo(Xo(),"runtime.json");if(Ko(n)){let o=JSON.parse(Wo(n,"utf8"));if(o.port&&Number.isInteger(o.port))return o.port}}catch{}let t=Number(process.env.PORT);return Number.isInteger(t)&&t>0?t:3005}function Gn(t){let n={};return t.headers.forEach((o,s)=>{n[s]=o}),n}function Be(t,n){let o=L(Gn(t));return Ui(mr(o),n)}function Qo(t){let{apiKey:n,...o}=t;return{...o,apiKey:"[REDACTED]"}}function Ln(t){return typeof t==="string"&&t.startsWith("/api/")&&!t.includes("..")&&!t.includes("//")}var Gt=new Map;function Zo(){let t=Date.now()-3600000;for(let[n,o]of Gt)if(o.completedAt&&Date.parse(o.completedAt)<t)Gt.delete(n)}function jn(){return new E({name:"agent-mesh"}).get("/api/mesh/peers",({request:t,set:n})=>{if(!Be(t,["read"]))return n.status=403,{error:"forbidden"};return{peers:gt(fe()).map(Qo)}}).delete("/api/mesh/peers/:id",({request:t,set:n,params:o})=>{if(!Be(t,["mutate"]))return n.status=403,{error:"forbidden"};if(!gt(fe()).some((i)=>i.id===o.id))return n.status=404,{error:"not found"};return{ok:Bt(o.id)}}).post("/api/mesh/peers/:id/call",async({request:t,set:n,params:o,body:s})=>{if(!Be(t,["mesh:forward"]))return n.status=403,{error:"forbidden"};let i=s;if(!Ln(i.path))return n.status=400,{error:"invalid path"};if(!gt(fe()).find((c)=>c.id===o.id))return n.status=404,{error:"not found"};let l=await Se(o.id,i.path,{method:i.method??"GET",body:i.body,operation:"mesh-call"});return{ok:l.ok,status:l.status,data:l.data,rotated:l.rotated,error:l.error}},{body:r.Object({method:r.Optional(r.String()),path:r.String(),body:r.Optional(r.Any())})}).post("/api/mesh/forward",async({request:t,set:n,body:o})=>{if(!Be(t,["mesh:forward"]))return n.status=403,{error:"forbidden"};let s=o;if(!s.request||!Ln(s.request.path))return n.status=400,{error:"invalid request"};let i=(s._hopCount??0)+1;if(i>Yo)return n.status=422,{error:"hop limit exceeded"};let a=fe(),l=$t(),c=s.hops??[];if(c.length===0){let Z=mr(L(Gn(t))),g=(s.request.method??"GET").toUpperCase();if(!Z||!hr(Z.scopes,g,s.request.path))return e().audit.emit("mesh","forward.denied",{path:s.request.path,method:g}),n.status=403,{error:"forbidden"};e().audit.emit("mesh","forward.terminal",{path:s.request.path,method:s.request.method??"GET"});let S=(s.request.method??"GET").toUpperCase();try{let A=await fetch(`http://127.0.0.1:${Nn()}${s.request.path}`,{method:S,headers:{"x-agent-api-key":await Re(),...s.request.body!==void 0?{"content-type":"application/json"}:{}},body:s.request.body!==void 0?JSON.stringify(s.request.body):void 0,signal:AbortSignal.timeout(60000)}),ne=await A.text().catch(()=>""),G=null;try{G=ne?JSON.parse(ne):null}catch{G=null}return{ok:A.ok,status:A.status,data:G,text:ne||null,error:A.ok?null:ne||`status ${A.status}`}}catch(A){return n.status=502,{ok:!1,status:0,error:A instanceof Error?A.message:String(A)}}}let u=c[0],f=s._traversed??[];if(u===l||f.includes(u))return n.status=422,{error:"cycle detected",at:u};let m=kr(u,a);if(!m)return n.status=403,{error:"next hop not in authorized boundary"};if(!m.permissions.includes("mesh:forward"))return n.status=403,{error:"peer lacks mesh:forward grant"};e().audit.emit("mesh","forward.hop",{nextId:u,remaining:c.length,hopCount:i});let _=encodeURIComponent($n()),q=await Se(m.id,`/api/profiles/${_}/mesh/forward`,{method:"POST",operation:"mesh-forward",timeoutMs:60000,body:{hops:c.slice(1),request:s.request,_traversed:[...f,l??"self"],_hopCount:i}});if(!q.ok)return n.status=502,{ok:!1,status:q.status,error:q.error,failedAtHop:u};return q.data},{body:r.Object({hops:r.Optional(r.Array(r.String())),request:r.Object({method:r.Optional(r.String()),path:r.String(),body:r.Optional(r.Any())}),_traversed:r.Optional(r.Array(r.String())),_hopCount:r.Optional(r.Number())})}).post("/api/mesh/deploy",({request:t,set:n,body:o})=>{if(!Be(t,["admin"]))return n.status=403,{error:"forbidden"};Zo();let s=o,i=fe(),a=crypto.randomUUID(),l={id:a,status:"running",steps:[],ownerUserId:i.ownerUserId,workspaceId:i.workspaceId,startedAt:new Date().toISOString()};return Gt.set(a,l),_n({target:s.target,permissions:s.permissions,installPlugins:s.installPlugins,autostart:s.autostart,identityFile:s.identityFile,label:s.label,version:s.version,connectExisting:s.connectExisting},(c)=>{l.steps.push(c),pe("mesh:deploy:progress",{jobId:a,step:c})}).then((c)=>{if(l.result=c,l.status=c.ok?"completed":"failed",!c.ok)l.error=c.error;l.completedAt=new Date().toISOString(),pe(c.ok?"mesh:deploy:complete":"mesh:deploy:failed",{jobId:a,result:c})}).catch((c)=>{l.status="failed",l.error=c instanceof Error?c.message:String(c),l.completedAt=new Date().toISOString(),pe("mesh:deploy:failed",{jobId:a,error:l.error})}),n.status=202,{jobId:a,status:"running"}},{body:r.Object({target:r.String(),permissions:r.Optional(r.Array(r.String())),installPlugins:r.Optional(r.Array(r.String())),autostart:r.Optional(r.Boolean()),identityFile:r.Optional(r.String()),label:r.Optional(r.String()),version:r.Optional(r.String()),connectExisting:r.Optional(r.Boolean())})}).get("/api/mesh/deploy/jobs/:id",({request:t,set:n,params:o})=>{if(!Be(t,["read"]))return n.status=403,{error:"forbidden"};let s=Gt.get(o.id),i=fe();if(!s||i.ownerUserId&&s.ownerUserId&&s.ownerUserId!==i.ownerUserId)return n.status=404,{error:"not found"};return s}).post("/api/mesh/wake",async({request:t,set:n,body:o})=>{if(!Be(t,["admin"]))return n.status=403,{error:"forbidden"};let s=o,i=kr(s.targetAgentRecordId,fe());if(!i)return n.status=404,{ok:!1,error:"peer not in authorized boundary"};e().audit.emit("mesh","wake.start",{peerId:i.id,agentRecordId:s.targetAgentRecordId});let a=await Bn(i.id,(l)=>pe("mesh:wake:progress",{peerId:i.id,step:l}));if(!a.ok)n.status=502;return a},{body:r.Object({targetAgentRecordId:r.String()})}).post("/api/mesh/session",async({request:t,set:n,body:o})=>{if(!Be(t,["mesh:forward","mutate"]))return n.status=403,{error:"forbidden"};let s=o,i=s.sessionId&&/^[A-Za-z0-9_-]{1,128}$/.test(s.sessionId)?s.sessionId:crypto.randomUUID(),a=encodeURIComponent($n()),l=await Re(),c=`http://127.0.0.1:${Nn()}`,u=s.command||"bash";try{let f=await fetch(`${c}/api/profiles/${a}/sessions/create`,{method:"POST",headers:{"x-agent-api-key":l,"content-type":"application/json"},body:JSON.stringify({sessionId:i,sessionName:`vc-mesh-${i.slice(0,8)}`,command:u,provider:"TERMINAL",...s.vibeId?{projectId:s.vibeId}:{}}),signal:AbortSignal.timeout(20000)});if(!f.ok)return n.status=502,{error:`session create returned ${f.status}: ${await f.text().catch(()=>"")}`};let m=await fetch(`${c}/api/profiles/${a}/sessions/${encodeURIComponent(i)}/terminal`,{method:"POST",headers:{"x-agent-api-key":l},signal:AbortSignal.timeout(20000)});if(!m.ok)return n.status=502,{error:`terminal start returned ${m.status}: ${await m.text().catch(()=>"")}`};let _=fr(`/terminal/${i}`,600);return e().audit.emit("mesh","session.created",{sessionId:i,kind:s.kind??"TERMINAL"}),{connectionId:i,sessionId:i,capabilityToken:_.token,expiresAt:_.expiresAt}}catch(f){return n.status=502,{error:f instanceof Error?f.message:String(f)}}},{body:r.Object({sessionId:r.Optional(r.String()),kind:r.Optional(r.String()),cwd:r.Optional(r.String()),vibeId:r.Optional(r.String()),command:r.Optional(r.String())})})}var ea=["/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 ta(t){return ea.some((n)=>t.startsWith(n))}var ra=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function na(t){return t.split("/").map((n)=>{if(!n)return n;if(/^\d+$/.test(n))return":id";if(ra.test(n))return":id";if(n.length>=24&&/^[A-Za-z0-9_-]+$/.test(n))return":id";return n}).join("/")}async function br(t){let{port:n,host:o,dbPath:s,logLevel:i,corsOrigin:a}=t,l=s??ee();try{let d=await import("fs");d.mkdirSync(l,{recursive:!0})}catch(d){throw e().logger.error("app","Failed to create dbPath dir at boot",{dbPath:l,error:String(d)}),Error(`Cannot create dbPath ${l}: ${d instanceof Error?d.message:String(d)}`,{cause:d})}if(i)e().logger.setLevel(i);(async()=>{let{logShipper:d}=await import("./log-shipper-02rqvtq8.js");d.init()})(),(async()=>{let d=await Hn();await xt({version:d,profile:R()})})();try{let{checkDependencies:d}=await import("./bootstrap.service-gehm65tt.js"),U=d(),y=U.filter((H)=>H.required&&!H.installed),F=U.filter((H)=>!H.required&&!H.installed);if(y.length>0)e().logger.error("app",`Missing required system deps: ${y.map((H)=>H.name).join(", ")}. Run \`vibe setup\` to install.`);if(F.length>0)e().logger.warn("app",`Missing optional system deps: ${F.map((H)=>H.name).join(", ")}. Some plugins may fail their prereqs check.`)}catch(d){e().logger.warn("app","Boot-time dependency check failed",{error:String(d)})}try{e().audit.runRetention()}catch(d){e().logger.warn("app","Audit-log retention sweep failed",{error:String(d)})}let c=new xe;Nr(c,{port:n});let u="GET, POST, PUT, PATCH, DELETE, OPTIONS",f="Content-Type, x-agent-api-key, Authorization, x-requested-with",m=Array.isArray(a)?a:(a??"").split(",").map((d)=>d.trim()).filter(Boolean),_=(d)=>_i(d,{configuredOrigins:m,devPorts:t.devCorsPorts}),q=()=>{let d=R(),U=or(d);return[process.env.AGENT_TUNNEL_URL,process.env[`AGENT_TUNNEL_URL_${U}`],lt(),te()?.url]},Z=async()=>{let d=[],U=[],y=c.getProvider("tunnel");if(y)U.push(y);for(let F of c.listProvidersForType("tunnel")){let H=c.getProviderByName("tunnel",F.pluginName);if(H&&!U.includes(H))U.push(H)}for(let F of U){if(!F.getActiveTunnelUrl)continue;try{let H=await F.getActiveTunnelUrl();if(H)d.push(H)}catch{}}return d},g=null,S=null,A=null,ne=null,G=!1,x=()=>[],p=null,j=null,J=null,re=5000,le=async(d,U)=>{let y=Date.now();try{await Promise.race([Promise.resolve(U()),new Promise((F,H)=>setTimeout(()=>H(Error(`shutdown phase ${d} exceeded ${re}ms`)),re))]),e().logger.info("app",`shutdown.phase ${d} complete`,{ms:Date.now()-y})}catch(F){e().logger.warn("app",`shutdown.phase ${d} failed`,{error:String(F),ms:Date.now()-y})}},De=async(d)=>{if(G)return;if(G=!0,e().logger.info("app","Agent shutdown starting",{reason:d?.reason??"shutdown"}),await le("plugins",async()=>{if(S)await S.dispatchServerStop(d)}),await le("bootstrap-tunnel",()=>ar()),await le("tracked-subprocesses",async()=>{let{killAllTracked:U}=await import("./subprocess-p9bv9nqz.js");await U()}),d?.reason!=="reload")await le("db-close",async()=>{if(g)await g.close()});await le("http-listener",async()=>{try{await Promise.resolve(Ee.stop())}catch(U){e().logger.warn("app","Listener stop threw (already stopped or never started?)",{error:String(U)})}}),e().logger.info("app","Agent server stopped"),e().logger.close()},ae=async(d,U)=>{if(e().getBootState()==="ready")return{ok:!0};if(J)return J;return J=(async()=>{e().setBootState("initializing");try{let y={...d,globalGatewayUrl:z(d.globalGatewayUrl,"globalGatewayUrl"),workspaceGatewayUrl:z(d.workspaceGatewayUrl,"workspaceGatewayUrl")},F=await tr(y),H=l,ce=w({dir:e().dataDir}),ge=ce.storageAdapter??process.env.VIBE_STORAGE_ADAPTER??void 0,be=ce.storageOptions,Ce=(h)=>{let v=(h instanceof Error?h.message:String(h)).toLowerCase(),Y=h&&typeof h==="object"&&"code"in h?String(h.code).toUpperCase():"";if(Y==="EBUSY"||Y==="EPERM"||Y==="EACCES"||Y==="EAGAIN"||Y==="EMFILE"||Y==="ENFILE"||Y==="ETIMEDOUT"||Y==="ECONNRESET"||Y==="ECONNREFUSED"||v.includes("encryption key")||v.includes("fetch")&&v.includes("key")||v.includes("temporarily unavailable")||v.includes("resource busy"))return"transient";if(v.includes("auth tag")||v.includes("authentication tag")||v.includes("unable to authenticate data")||v.includes("bad decrypt")||v.includes("unsupported state")||v.includes("incorrect header check")||v.includes("invalid distance")||v.includes("incorrect data check")||v.includes("unexpected end of")||v.includes("unexpected token")||v.includes("json")&&(v.includes("parse")||v.includes("invalid"))||v.includes("truncated")||v.includes("malformed")||v.includes("corrupt"))return"corruption";return"unknown"},Ke=()=>er({dbPath:H,encryptionKey:F,adapterName:ge,adapterOptions:be});try{g=await Ke()}catch(h){let v=h,Y=Ce(h),kt=[500,2000,8000];if(Y==="transient"||Y==="unknown"){e().logger.warn("app",`Storage open failed (${Y}); will retry up to ${kt.length} times before quarantine`,{error:h instanceof Error?h.message:String(h),path:H});for(let st of kt){await new Promise((ie)=>setTimeout(ie,st));try{g=await Ke(),v=null;break}catch(ie){if(v=ie,Y=Ce(ie),e().logger.warn("app",`Storage open retry failed (${Y}) after ${st}ms`,{error:ie instanceof Error?ie.message:String(ie)}),Y==="corruption")break}}}if(!g&&v){if(Y!=="corruption"){let ie=v instanceof Error?v.message:String(v);e().logger.error("app",`Storage open failed after retries with non-corruption error (${Y}); refusing to quarantine valid data`,{error:ie,path:H}),e().recordDegradedReason("storage",ie);try{throw v}catch(Fe){throw Error(`Storage open failed (${Y}); agent is degraded: ${ie}`,{cause:Fe})}}let st=v instanceof Error?v.message:String(v);e().logger.error("app","QUARANTINE: Storage file is corrupt \u2014 renaming and creating fresh DB",{errorClass:"corruption",error:st,path:H});try{let ie=await import("fs");if(ie.existsSync(H)){let Fe=new Date().toISOString().replace(/[:.]/g,"-"),Cr=`${H}.broken-${Fe}`;ie.renameSync(H,Cr),e().logger.warn("app",`Quarantined corrupt storage to ${Cr} \u2014 fresh DB will be created`,{originalError:st})}g=await Ke()}catch(ie){let Fe=ie instanceof Error?ie.message:String(ie);throw e().recordDegradedReason("storage",Fe),Error(`Storage open failed twice (quarantine path); agent is degraded: ${Fe}`,{cause:ie})}}}if(!g)throw Error("Internal error: storage open recovery exited without an open database and without throwing");if(await Yt({clientId:y.clientId,clientSecret:y.clientSecret,workspaceId:y.workspaceId,organizationId:y.organizationId,globalGatewayUrl:y.globalGatewayUrl,workspaceGatewayUrl:y.workspaceGatewayUrl,agentRecordId:U?.agentRecordId,scopes:U?.scopes,pairedIdentity:Zt({workspaceId:y.workspaceId,globalGatewayUrl:y.globalGatewayUrl,workspaceGatewayUrl:y.workspaceGatewayUrl,agentRecordId:U?.agentRecordId})},{dir:e().dataDir,scope:e().name}),await g.setConfig("gateway-auth:clientId",y.clientId),await g.setConfig("gateway-auth:clientSecret",y.clientSecret),await g.setConfig("gateway-auth:globalGatewayUrl",y.globalGatewayUrl),await g.setConfig("gateway-auth:workspaceGatewayUrl",y.workspaceGatewayUrl),await g.setConfig("gateway-auth:workspaceId",y.workspaceId),y.organizationId)await g.setConfig("gateway-auth:organizationId",y.organizationId);if(U?.agentRecordId)await g.setConfig("gateway-auth:agentRecordId",U.agentRecordId);c.db=g,await c.hydrateDefaultsFromDb(),S=new W(g),await S.loadCorePlugins();try{await S.loadAll()}catch(h){e().logger.warn("app","Failed to load some external plugins",{error:String(h)})}let Ye=Ze(C())??void 0,tt=process.env.VIBE_SKIP_AUTO_INSTALL==="1"||await g.getConfig("plugins:auto-install-disabled");if(tt!=="true"&&tt!==!0)try{let h=await S.ensureDefaultPlugins((v)=>e().logger.info("app",`[auto-install] ${v}`),[],Ye);if(h.length>0)e().logger.info("app",`Auto-installed ${h.length} default plugin(s): ${h.map((v)=>v.packageName).join(", ")}`)}catch(h){e().logger.warn("app","Failed to auto-install default plugins",{error:String(h)})}e().logger.info("app",`Plugins loaded: ${S.getPluginDetails().length} total (${S.getPluginDetails().filter((h)=>h.isCore).length} core)`);try{let h=S.getPluginDetails(),v={loaded:h.filter((Y)=>Y.loaded).length,failed:h.filter((Y)=>!Y.loaded).length};un(v)}catch{}let Ft={async get(h,v){return await g.getPluginState(h,v)??null},async set(h,v,Y){await g.setPluginState(h,v,Y)},async delete(h,v){return g.deletePluginState(h,v)},async list(h){return await g.getAllPluginState(h)},async deleteAll(h){return g.deleteAllPluginState(h)}},vt=await Hn();A={storage:Ft,logger:e().logger,serviceRegistry:c,getProvider:(h)=>c.getProvider(h),getAgentBaseUrl:()=>process.env.AGENT_URL||`http://localhost:${n}`,getAgentVersion:()=>vt,validateApiKey:(h)=>V(h),setCodeServerSessionValidator:(h)=>{zn=h},broadcast:pe,workspaceQuery:async(h,v)=>T.workspaceQuery(h,v),isGatewayConfigured:()=>T.isConfigured(),getAgentRecordId:async()=>await g.getConfig("gateway-auth:agentRecordId")??null,getWorkspaceId:async()=>await g.getConfig("gateway-auth:workspaceId")??null,getConfig:async(h)=>await g.getConfig(h)??void 0,getPluginRegistry:()=>se(),getDataDir:()=>I(),cliContributors:new Ie,audit:{emit:(h,v)=>e().audit.emit("agent",h,v??{})},telemetry:{emit:(h,v)=>{import("./telemetry-1d3t1mbf.js").then(({telemetryService:Y})=>Y.emit(h,v??{})).catch(()=>{})}},os:b(),iframeBridge:ve()},T.configure({globalGatewayUrl:y.globalGatewayUrl,workspaceGatewayUrl:y.workspaceGatewayUrl,clientId:y.clientId,clientSecret:y.clientSecret,workspaceId:y.workspaceId,organizationId:y.organizationId});let Ge={db:g,serviceRegistry:c,pluginManager:S,broadcast:pe,hostServices:A};Ge.app=Ee;let Er=!1,Ht=()=>{let{routes:h,getPublicPaths:v,mountPlugin:Y}=gr(S,Ge);if(Ge.mountPlugin=Y,x=v,Ki(),p=h,j=Oi(S),S&&Er&&A)S.dispatchServerStart(p,A).catch((kt)=>e().logger.warn("app","Re-dispatch of onServerStart after plugin reload failed",{error:String(kt)}));Er=!0};Ge.rebuildPluginSurfaces=Ht,Ht(),ne=new Rt(c,S,g,Ee,A,De),c.registerService("agent","lifecycle",ne),e().attachServices({db:g,serviceRegistry:c,pluginManager:S,lifecycle:ne,hostServices:A}),_t(e(),{rebuildPluginSurfaces:Ht,mountPlugin:Ge.mountPlugin,app:p});try{await e().keyVault.bindApiKey(K())}catch(h){e().logger.warn("app","Failed to bind api key into daemon keyVault",{error:String(h)})}let Vt=[];try{let{failures:h}=await S.dispatchServerStart(p,A);for(let v of h)if(Et(v.plugin)||(v.packageName?Et(v.packageName):!1))Vt.push(v),e().recordDegradedReason(v.plugin,v.error);else e().logger.warn("app",`Non-critical plugin ${v.plugin} failed onServerStart; continuing`,{error:v.error})}catch(h){e().logger.warn("app","Error during plugin onServerStart dispatch",{error:String(h)})}try{await S.dispatchServerReady(Ee,A)}catch(h){e().logger.warn("app","Error during plugin onServerReady dispatch",{error:String(h)})}if(e().clearFinalizeError(),Vt.length>0)e().setBootState("degraded"),e().logger.error("app","Agent finalized but degraded \u2014 critical plugins failed",{failures:Vt.map((h)=>`${h.plugin}: ${h.error}`)});else e().setBootState("ready"),e().logger.info("app","Agent finalized \u2014 state=ready"),e().audit.emit("agent","gateway-auth.configured",{workspaceId:y.workspaceId,organizationId:y.organizationId,agentRecordId:U?.agentRecordId});return(async()=>{try{if(await S.provisionDefaultPrereqs(Ee,A,Ge.mountPlugin,Ye),e().logger.info("app","Default provider prerequisites provisioned"),(c.listProvidersForType("tunnel")??[]).some((Y)=>Y.pluginName!=="bootstrap")){let{tryHandoverBootstrapTunnel:Y}=await import("./tunnel-bootstrap-m51w4d94.js");if(!Y())ar();c.unregisterProvider("tunnel","bootstrap"),e().logger.info("app","Bootstrap tunnel handed over to the real tunnel provider")}}catch(h){e().logger.warn("app","Plugin prerequisite provisioning failed",{error:String(h)})}})(),{ok:!0}}catch(y){e().setBootState("awaiting-config");let F=y instanceof Error?y.message:String(y);if(e().recordFinalizeError(F),e().logger.error("app","Finalize failed",{error:F}),process.env.VIBE_STRICT_KEY_FETCH==="1")e().logger.error("app","VIBE_STRICT_KEY_FETCH=1 \u2192 aborting daemon (strict mode)",{error:F}),setTimeout(()=>process.exit(1),50);return{ok:!1,error:F}}finally{J=null}})(),J},de=Ur({origin:(d)=>{let U=d.headers.get("origin");return!!U&&_(U)},credentials:!0,allowedHeaders:f.split(",").map((d)=>d.trim()),methods:u.split(",").map((d)=>d.trim()),exposeHeaders:["content-type","content-length"],maxAge:86400,preflight:!0}),Me=10485760,Pr=process.env.VIBECONTROLS_MAX_BODY_BYTES,jt=Pr?Number.parseInt(Pr,10):NaN,Vn=Number.isFinite(jt)&&jt>0?jt:Me,Ar={current:null},Ee=new E({serve:{maxRequestBodySize:Vn}}).onRequest(async({request:d})=>{let U={port:n,allowedHosts:t.allowedHosts,tunnelUrls:q()},y=Or(d,U);if(!y&&c.hasProvider("tunnel")){let F=await Z();if(F.length>0)y=Or(d,{...U,tunnelUrls:[...U.tunnelUrls,...F]})}if(!y)return new Response(JSON.stringify({error:"Forbidden",message:"Invalid or disallowed Host header"}),{status:403,headers:{"content-type":"application/json"}});try{let F=new URL(d.url).pathname;if((F==="/api/agent/api-key"||/^\/api\/profiles\/[^/]+\/agent\/api-key(?:\/|$)/.test(F))&&Ve(d))return new Response(JSON.stringify({error:"Forbidden",message:"Browser requests are not permitted on /api/agent/api-key"}),{status:403,headers:{"content-type":"application/json"}})}catch{}}).onRequest(({request:d,set:U})=>{let F=Hi(d.headers)??Ai();Vi({requestId:F,startedAt:new Date().toISOString()});let H=U.headers??={};H["X-Request-Id"]=F}).onRequest(({request:d})=>{try{let U=new URL(d.url).pathname,F=/^\/api\/profiles\/([^/]+)(?:\/|$)/.exec(U)?.[1],H=F?N.get(F):null;wt(H??e())}catch{wt(e())}}).onRequest(({request:d,set:U})=>{let y=new URL(d.url).pathname;if(!y.startsWith("/api/"))return;if(y==="/api/profiles"||y.startsWith("/api/profiles/"))return;if(y==="/api/profile-stats"||y.startsWith("/api/profile-stats/"))return;let F=new URL(d.url);F.pathname=`/api/profiles/default${y.slice(4)}`;try{d.headers.set("x-vc-profile-rewrite","1"),d.headers.set("x-vc-profile-rewrite-target",F.pathname)}catch{}return}).derive(()=>({requestId:Tt()??Ai()})).use(de).use(Ni()).use(Qi(()=>x())).use(Br({getDb:()=>B()?.db??g})).onBeforeHandle(({request:d,set:U})=>{let y=e().getBootState();if(y==="ready")return;let F=new URL(d.url).pathname;if(ta(F))return;return U.status=503,{error:"Agent not yet configured",message:"Agent is in '"+y+"' state. POST credentials to /api/agent/gateway-auth to finalize.",state:y}}).onAfterHandle(({request:d,set:U})=>{let y=new URL(d.url).pathname,F=y==="/health"||y.startsWith("/api/logs/stream")||y.startsWith("/ui/")||y==="/ws/events"||y==="/api/sessions/health-check"||y.startsWith("/terminal/"),H=typeof U.status==="number"?U.status:200,ce=F?"debug":H>=400?"warn":"info";e().logger[ce]("http",`${d.method} ${y} \u2192 ${H}`,{method:d.method,path:y,statusCode:H});try{cn(d.method,na(y),H)}catch{}}).use(nn({serviceRegistry:c,getDb:()=>B()?.db??g,getDbPath:()=>l,getPluginManager:()=>B()?.pluginManager??S})).use(gn()).use(Wr({serviceRegistry:c,runFinalize:(d,U)=>ae(d,U),getDb:()=>B()?.db??g})).use(an()).use(sn()).use(Dn({getPluginManager:()=>B()?.pluginManager??S})).use(jn()).use(fn()).use(Sn({getPluginManager:()=>B()?.pluginManager??S,getTunnelHost:()=>te()?.url??null})).use(en()).use(tn()).use(Qr()).use(Gr()).use(jr(c)).ws("/code-server/*",aa(n)).all("/api/profiles/:name/*",async({params:d,request:U,set:y})=>{let F=U.method!=="GET"&&U.method!=="HEAD",H=F?await U.arrayBuffer():void 0,ce=await $r(d.name,U,H);if(ce&&ce.status!==404)return ce;let ge=R(),be=d.name;if(be!==ge)return y.status=404,{error:"profile-mismatch",running:ge,requested:be,hint:"This daemon serves a different profile. Call GET /api/profiles to discover the right tunnel."};let Ce=new URL(U.url),Ke=Ce.pathname.replace(/^\/api\/profiles\/[^/]+/,"/api"),Ye=new Headers(U.headers);Ye.set("x-vc-profile-rewrite","1");let tt={method:U.method,headers:Ye};if(F&&H!==void 0)tt.body=H;let Ft=new Request(`${Ce.origin}${Ke}${Ce.search}`,tt),vt=Ar.current;if(!vt)return new Response(JSON.stringify({error:"agent-not-ready"}),{status:503,headers:{"content-type":"application/json"}});return vt.handle(Ft)}).all("/api/*",async({request:d})=>{if(e().getBootState()!=="ready"||!p)return new Response(JSON.stringify({error:"Agent not yet configured",state:e().getBootState(),message:"Plugin routes are unavailable until the agent reaches state=ready. POST credentials to /api/agent/gateway-auth to finalize."}),{status:503,headers:{"content-type":"application/json"}});try{let U=new URL(d.url),y=/^\/api\/plugins\/([a-z0-9-]{1,64})\/ui(?:\/.*)?$/.exec(U.pathname);if(y&&d.method==="GET"){let F=y[1];if(me(F)){let H=U.pathname.slice(`/api/plugins/${F}/ui`.length),ce=H===""||H==="/",be=d.headers.get("sec-fetch-mode")==="navigate";if(ce||be){let Ce=it(d,F);if(!Ce||!rt(Ce,F))return new Response(vr(F,"/api/profiles/default/agent/ui-exchange-plugin"),{status:200,headers:{"content-type":"text/html; charset=utf-8","Content-Security-Policy":"frame-ancestors 'self' http://localhost:* http://127.0.0.1:* https://localhost:* https://127.0.0.1:* https://*.local.burdenoff.com https://vibecontrols.com https://*.vibecontrols.com https://burdenoff.com https://app.burdenoff.com https://alphaapp.burdenoff.com"}})}}}}catch{}return p.handle(d)}).all("/ui/*",async({request:d})=>{if(e().getBootState()!=="ready"||!j)return new Response("Plugin UI not yet available",{status:503});return j.handle(d)}).all("/code-server/*",async({request:d})=>{if(e().getBootState()!=="ready"||!p)return new Response("code-server not yet available",{status:503});let U=Dr(d,K);return p.handle(U??d)}).all("/plan/*",async({request:d})=>{if(e().getBootState()!=="ready"||!p)return new Response("plan provider not yet available",{status:503});return p.handle(d)});return Ar.current=Ee,{app:Ee,async start(){Ee.listen({port:n,hostname:o}),e().logger.info("app",`Agent server listening on ${o}:${n}`);try{let d=(process.env.VIBECONTROLS_PROFILES??"").split(",").map((ce)=>ce.trim()).filter(Boolean),U=e().name,{getOrCreateProfile:y}=await import("./daemon-profile-fnhc7pcf.js"),{attachSecondaryProfile:F}=await import("./secondary-profile-attach-v7kxsk4z.js"),H=process.env.VIBE_STRICT_KEY_FETCH==="1";for(let ce of d){if(ce===U)continue;try{let ge=y(ce),be=await F(ge);if(be.ok)e().logger.info("app",`Secondary profile '${ce}' attached (db+services online)`);else if(H)throw Error(`attachServices for secondary profile '${ce}' failed: ${be.error}`);else ge.recordDegradedReason("attach",be.error??"unknown"),e().logger.warn("app",`Secondary profile '${ce}' is degraded (no creds / attach failed)`,{error:be.error})}catch(ge){if(H)throw e().logger.error("app",`--strict-key-fetch: secondary profile '${ce}' attach failed; aborting`,{error:String(ge)}),setTimeout(()=>process.exit(1),50),ge;e().logger.warn("app",`Failed to attach secondary profile '${ce}'`,{error:String(ge)})}}}catch{}return Ee},stop:De,finalize:ae,getState:()=>e().getBootState(),getLifecycle:()=>B()?.lifecycle??ne,getDb:()=>B()?.db??g,getServiceRegistry:()=>B()?.serviceRegistry??c,getPluginManager:()=>B()?.pluginManager??S,getHostServices:()=>B()?.hostServices??A}}var zn=null;function oa(t,n){if(!t)return null;let o=t.match(new RegExp(`(?:^|;\\s*)${n}=([^;]*)`));return o?o[1]:null}var Fn=dr(ki);function aa(t){let i=(a)=>typeof a==="string"?Buffer.byteLength(a):a.byteLength;return{open(a){let l=a.data,c=L(l.headers??{})??L(l.request?Object.fromEntries(l.request.headers.entries()):{}),u=l.query?.vt,f=!!u&&qe(u,"/code-server","GET"),m,_=V(c);if(!_&&!f){let S=l.headers?.cookie??l.request?.headers.get("cookie")??null,A=oa(S,"__vibe_cs_session");if(!A||!zn?.(A)){a.close(1008,"Unauthorized");return}m=`session:${A}`}else if(_)m="api-key";else m="vt";let q=a.remoteAddress??null,Z=Qe(q,l.headers);if(!Fn.accept(m,Z,a)){e().logger.warn("code-server-ws",`code-server WS cap exceeded (key=${m}, ip=${Z??"unknown"})`),a.close(1013,"too many connections");return}l._csCapKey=m,l._csRemoteIp=Z;let g=e().name;fetch(`http://127.0.0.1:${t}/api/profiles/${encodeURIComponent(g)}/code-server/status`,{headers:{"x-agent-api-key":K()}}).then((S)=>S.json()).then((S)=>{if(l._csClosed)return;let A=S;if(!A.running||!A.port){a.close(1011,"code-server not running");return}let ne=l.request?.url??"/code-server/",G;try{let j=new URL(ne,`http://127.0.0.1:${A.port}`);G=(j.pathname.replace(/^\/code-server\/?/,"/")||"/")+j.search}catch{G="/"}let x=new WebSocket(`ws://127.0.0.1:${A.port}${G}`),p={upstream:x,ready:!1,buffer:[],bufferBytes:0,openTimer:setTimeout(()=>{try{x.close(1011,"upstream open timeout")}catch{}try{a.close(1011,"upstream open timeout")}catch{}},1e4)};l._csBridge=p,x.addEventListener("open",()=>{clearTimeout(p.openTimer),p.ready=!0;for(let j of p.buffer)x.send(j);p.buffer.length=0,p.bufferBytes=0}),x.addEventListener("message",(j)=>{try{let J=j.data;if(J instanceof ArrayBuffer)a.send(new Uint8Array(J));else if(J instanceof Blob)J.arrayBuffer().then((re)=>{try{a.send(new Uint8Array(re))}catch{}});else a.send(J)}catch{}}),x.addEventListener("close",(j)=>{clearTimeout(p.openTimer);try{a.close(j.code||1000,j.reason||"upstream closed")}catch{}}),x.addEventListener("error",()=>{clearTimeout(p.openTimer);try{a.close(1011,"upstream error")}catch{}})}).catch(()=>{a.close(1011,"Failed to query code-server status")})},message(a,l){let c=a.data?._csBridge;if(!c)return;let u;if(typeof l==="string")u=l;else if(l instanceof ArrayBuffer)u=l;else if(l instanceof Uint8Array||Buffer.isBuffer(l)){let f=new ArrayBuffer(l.byteLength);new Uint8Array(f).set(new Uint8Array(l.buffer,l.byteOffset,l.byteLength)),u=f}else if(typeof l==="object"&&l!==null)u=JSON.stringify(l);else u=String(l);if(c.upstream&&c.ready&&c.upstream.readyState===WebSocket.OPEN)try{c.upstream.send(u)}catch{}else{let f=i(u);if(c.buffer.length>=256||c.bufferBytes+f>1048576){try{c.upstream.close(1013,"buffer limit exceeded")}catch{}try{a.close(1013,"buffer limit exceeded")}catch{}return}c.buffer.push(u),c.bufferBytes+=f}},close(a){a.data._csClosed=!0;let l=a.data?._csBridge;if(l?.openTimer)clearTimeout(l.openTimer);if(l?.upstream&&l.upstream.readyState===WebSocket.OPEN)l.upstream.close(1000,"client disconnected");let c=a.data._csCapKey,u=a.data._csRemoteIp;if(c)Fn.release(c,u??null,a)}}}async function Hn(){try{let{readFileSync:t}=await import("fs"),{join:n,dirname:o}=await import("path"),{fileURLToPath:s}=await import("url"),i=o(s(import.meta.url));return JSON.parse(t(n(i,"..","package.json"),"utf8")).version||"1.0.0"}catch{return"1.0.0"}}
|
|
26
26
|
export{gi,zt,xr,di,br};
|