@vibecontrols/agent 2026.602.7 → 2026.608.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-5asxkthh.js → app-wj8qwk11.js} +1 -1
- package/dist/cli.js +1 -1
- package/dist/{index-9bdbnx8f.js → index-41vve5br.js} +1 -1
- package/dist/{index-c6xa5nd4.js → index-4hn26x1h.js} +1 -1
- package/dist/{index-x0xv3rpa.js → index-68r2ex9d.js} +1 -1
- package/dist/{index-n1222y6a.js → index-84hfet2g.js} +3 -3
- package/dist/{index-2nq63va3.js → index-bwt6c337.js} +1 -1
- package/dist/{index-cfa3pgh5.js → index-cv0xhb46.js} +2 -2
- package/dist/{index-5mnyfrck.js → index-ebx79cc1.js} +1 -1
- package/dist/{index-ekzav1nc.js → index-ghz61a5p.js} +2 -2
- package/dist/{index-z40ptwv4.js → index-z2gbk1pn.js} +2 -2
- package/dist/index.js +1 -1
- package/dist/{plugin-system-f47jdx66.js → plugin-system-jegwkd9p.js} +1 -1
- package/dist/{register-core-2t9dmbnp.js → register-core-r7fjpp4w.js} +1 -1
- package/dist/{secondary-profile-attach-s5z9dppt.js → secondary-profile-attach-kxg4xj2t.js} +1 -1
- package/package.json +2 -2
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{n as a}from"./index-
|
|
2
|
+
import{n as a}from"./index-84hfet2g.js";import"./index-czrb2yd1.js";import"./index-41vve5br.js";import"./index-6jzsthh9.js";import"./index-ebx79cc1.js";import"./index-yas07mv9.js";import"./index-68r2ex9d.js";import"./index-4hn26x1h.js";import"./index-4wgjx8bf.js";import"./index-cv0xhb46.js";import"./index-0ckffygp.js";import"./index-rc79x8fw.js";import"./index-jrtsdm8f.js";import"./index-52cp759f.js";import"./index-6p3gcnxr.js";import"./index-bfeekmyh.js";import"./index-5dysvvjv.js";import"./index-pgew6sge.js";import"./index-t8tnkqxh.js";import"./index-63ba5fb4.js";import"./index-xnr6t79p.js";import"./index-a4854mwz.js";import"./index-4qq083yd.js";import"./index-c7554sg7.js";export{a as createApp};
|
package/dist/cli.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
3
|
-
import{H as O}from"./index-mxc61yr1.js";import{I as Q,J as w}from"./index-
|
|
3
|
+
import{H as O}from"./index-mxc61yr1.js";import{I as Q,J as w}from"./index-ghz61a5p.js";import"./index-wetsgcyq.js";import"./index-b5dhmybd.js";import"./index-e1bw1bwr.js";import"./index-ebx79cc1.js";import"./index-yas07mv9.js";import"./index-68r2ex9d.js";import{wa as Z,za as I}from"./index-4hn26x1h.js";import{Aa as G,Ba as H}from"./index-4wgjx8bf.js";import{Wa as J}from"./index-cv0xhb46.js";import{Xa as U}from"./index-0ckffygp.js";import"./index-rc79x8fw.js";import{bb as K}from"./index-jrtsdm8f.js";import"./index-52cp759f.js";import"./index-bfeekmyh.js";import"./index-5dysvvjv.js";import"./index-pgew6sge.js";import{dc as $}from"./index-8sdrhr3q.js";import"./index-8nqp3a4d.js";import{nc as E}from"./index-85ke6hng.js";import"./index-thammzct.js";import"./index-t8tnkqxh.js";import"./index-63ba5fb4.js";import{Od as Y}from"./index-xnr6t79p.js";import{$d as W,de as X}from"./index-a4854mwz.js";import"./index-4qq083yd.js";import"./index-c7554sg7.js";import{join as B}from"path";if(typeof Bun>"u")console.error(`\x1B[31mError:\x1B[0m VibeControls Agent requires the Bun runtime.
|
|
4
4
|
Install Bun: https://bun.sh
|
|
5
5
|
Then run: bun run vibe ...`),process.exit(1);var T=process.argv.slice(2),_=T.includes("--plain")||T.includes("--json")||process.env.NO_COLOR==="1"||!process.stdout.isTTY;E(!_);try{O()}catch{}var N="1.0.0";try{let q=B(import.meta.dir,"..","package.json");N=(await Bun.file(q).json()).version}catch{}var x=new $;x.name("vibe").description("VibeControls Agent CLI \u2014 Remote development environment management").version(N,"-v, --version").option("--provider <name>","Override the default provider for tunnel/session operations").option("-p, --profile <name>","Target a specific profile (one-off; doesn't change the persisted default). See `vibe profile`.").option("--json","Emit machine-readable JSON instead of human output.").option("--plain","Force plain-text output (no interactive UI).").hook("preAction",(q,z)=>{let F=q.opts().profile;if(F)process.env.VIBECONTROLS_PROFILE=F;try{K.init(),K.emit("command.executed",{command_name:z.name()})}catch{}});w(x);async function M(){let q=new J;try{await q.loadCorePlugins()}catch{}try{await q.loadAll()}catch{}let z=new Z,F={storage:{async get(){return null},async set(){},async delete(){return!1},async list(){return[]},async deleteAll(){return 0}},logger:Y().logger,serviceRegistry:z,getProvider:(L)=>z.getProvider(L),getAgentBaseUrl:()=>process.env.AGENT_URL||"http://localhost:3005",getAgentVersion:()=>N,broadcast:()=>{},workspaceQuery:async()=>({data:void 0,errors:[{message:"workspaceQuery is not available in CLI mode"}]}),isGatewayConfigured:()=>!1,getAgentRecordId:async()=>null,getWorkspaceId:async()=>null,getConfig:async()=>{return},getPluginRegistry:()=>X(),getDataDir:()=>W(),cliContributors:new G,telemetry:{emit:(L,D)=>{try{K.emit(L,D??{})}catch{}}},os:U(),iframeBridge:I()};H(F.cliContributors);try{await q.dispatchCliSetup(x,F)}catch{}x.configureHelp({formatHelp:()=>Q(x,!0)}),await x.parseAsync()}M().then(()=>{process.exit(process.exitCode??0)}).catch((q)=>{console.error(`\x1B[31mFatal:\x1B[0m ${q instanceof Error?q.message:q}`),process.exit(1)});
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{wa as qa,za as Fa}from"./index-
|
|
2
|
+
import{wa as qa,za as Fa}from"./index-4hn26x1h.js";import{Aa as Ka}from"./index-4wgjx8bf.js";import{Da as ka,Wa as Ua}from"./index-cv0xhb46.js";import{Xa as Pa}from"./index-0ckffygp.js";import{nb as ja}from"./index-6p3gcnxr.js";import{Jb as Ma}from"./index-bfeekmyh.js";import{qd as ba,sd as yt}from"./index-63ba5fb4.js";import{Ad as Gt,Cd as os,Ed as Ra,Id as v,Md as Ta,Od as g,Pd as Oa}from"./index-xnr6t79p.js";import{Zd as Xt,ce as Ia}from"./index-a4854mwz.js";import{ie as Ae}from"./index-c7554sg7.js";var Qt=[0,5000,15000,30000,60000],za=2000,Ba=5000,Xa=120000,cs=10,Ha=1048576;class Zt extends Error{resetAt;resource;constructor(e,t,i){super(e);this.name="RateLimitError",this.resource=t,this.resetAt=i}}function ei(e,t){if(!e?.length)return null;let i=e.find((r)=>r.extensions?.code==="RATE_LIMITED");if(!i)return null;let s=i.extensions?.resetAt,n=null;if(s){let r=new Date(s);if(!Number.isNaN(r.getTime()))n=r}return new Zt(`${t} rate limited${n?` until ${n.toISOString()}`:""}`,t,n)}function Va(e){if(!e.resetAt)return 60000;let t=e.resetAt.getTime()-Date.now()+za;return Math.min(Math.max(t,Ba),Xa)}async function Ja(e,t){let i=e.headers.get("content-length");if(i){let o=Number.parseInt(i,10);if(Number.isInteger(o)&&o>t)throw Error(`Gateway response is too large (${o} bytes)`)}if(!e.body)return"";let s=e.body.getReader(),n=[],r=0;try{while(!0){let{done:o,value:c}=await s.read();if(o)break;if(!c)continue;if(r+=c.byteLength,r>t)throw await s.cancel().catch(()=>{return}),Error(`Gateway response exceeds ${t} bytes`);n.push(c)}}finally{s.releaseLock()}let a=new Uint8Array(r),l=0;for(let o of n)a.set(o,l),l+=o.byteLength;return new TextDecoder().decode(a)}async function ti(e,t){let i=await Ja(e,Ha),s;try{s=i?JSON.parse(i):{}}catch(n){let r=i.slice(0,240).replace(/\s+/g," ");throw Error(`${t} returned non-JSON response (${e.status} ${e.statusText})${r?`: ${r}`:""}`,{cause:n})}if(!e.ok){let n=i.slice(0,240).replace(/\s+/g," ");throw Error(`${t} failed (${e.status} ${e.statusText})${n?`: ${n}`:""}`)}return s}function ii(e){return e.endsWith("/graphql")?e:`${e}/graphql`}function Ya(e){let t;try{t=new URL(e).hostname.toLowerCase().replace(/^\[|\]$/g,"")}catch{return!1}if(t==="localhost"||t==="127.0.0.1"||t==="::1"||t==="0.0.0.0"||t==="host.docker.internal")return!0;return t.endsWith(".localhost")||t.endsWith(".local")||t.endsWith(".local.burdenoff.com")}function si(e){if(!(process.env.VIBE_DEV_INSECURE_TLS==="1"||process.env.NODE_TLS_REJECT_UNAUTHORIZED==="0")&&!Ya(e))return{};return{tls:{rejectUnauthorized:!1}}}async function Wa(e,t,i){let s=await fetch(ii(e),{method:"POST",...si(e),headers:{"Content-Type":"application/json"},body:JSON.stringify({query:`mutation AuthenticateApp($input: AuthenticateAppInput!) {
|
|
3
3
|
authenticateApp(input: $input) { accessToken expiresIn }
|
|
4
4
|
}`,variables:{input:{clientId:t,clientSecret:i,scopes:[]}}}),signal:AbortSignal.timeout(15000)}),n=await ti(s,"authenticateApp"),r=ei(n.errors,"authenticateApp");if(r)throw r;if(n.errors?.length){let l=n.errors.map((o)=>o.extensions?.code??"UNKNOWN").join(",");throw Error(`authenticateApp errors [${l}]: ${n.errors.map((o)=>o.message).join("; ")}`)}let a=n.data?.authenticateApp?.accessToken;if(!a)throw Error("authenticateApp returned no token");return a}async function Qa(e,t,i,s){let n=await fetch(ii(e),{method:"POST",...si(e),headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify({query:`mutation IssueAgentWorkspaceToken($input: IssueWorkspaceTokenInput!) {
|
|
5
5
|
issueWorkspaceToken(input: $input) {
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Sa as k}from"./index-
|
|
2
|
+
import{Sa as k}from"./index-cv0xhb46.js";import{Eb as F,Fb as h,Gb as S,Hb as q,Jb as N,wb as f,zb as c}from"./index-bfeekmyh.js";import{Vb as P}from"./index-pgew6sge.js";import{Od as V}from"./index-xnr6t79p.js";var U=["tunnel","session","ai","plan","gitops","security"];class m{providers=new Map;providerOrder=new Map;defaults=new Map;services=new Map;db;constructor(z){this.db=z}getDb(){return this.db}setProviderDefault(z,J){this.defaults.set(z,J)}clearProviderDefault(z,J){if(!J||this.defaults.get(z)===J)this.defaults.delete(z)}async hydrateDefaultsFromDb(){if(!this.db)return;for(let z of U)try{let J=await this.db.getConfig(`provider:default:${z}`);if(J)this.defaults.set(z,J)}catch{}}registerProvider(z,J,Q){if(!this.providers.has(z))this.providers.set(z,new Map),this.providerOrder.set(z,[]);let W=this.providers.get(z),Z=this.providerOrder.get(z);if(W.has(Q))V().logger.info("service-registry",`Updating ${z} provider from plugin '${Q}'`);else V().logger.info("service-registry",`Registered ${z} provider from plugin '${Q}'`);if(W.set(Q,{provider:J,pluginName:Q,registeredAt:new Date}),!Z.includes(Q))Z.push(Q)}getProvider(z){let J=this.providers.get(z);if(!J||J.size===0)return;let Q=this.defaults.get(z);if(Q&&J.has(Q))return J.get(Q).provider;let W=this.providerOrder.get(z);if(W&&W.length>0){let Z=W[0];return J.get(Z)?.provider}return}getProviderByName(z,J){let Q=this.providers.get(z);if(!Q)return;return Q.get(J)?.provider}hasProvider(z){let J=this.providers.get(z);return!!J&&J.size>0}unregisterProvider(z,J){let Q=this.providers.get(z);if(!Q)return!1;let W=Q.delete(J);if(W){let Z=this.providerOrder.get(z);if(Z){let X=Z.indexOf(J);if(X!==-1)Z.splice(X,1)}this.clearProviderDefault(z,J),V().logger.info("service-registry",`Unregistered ${z} provider from plugin '${J}'`)}return W}unregisterPlugin(z){for(let J of U)this.unregisterProvider(J,z);this.unregisterServices(z)}listProvidersForType(z){let J=this.providers.get(z);if(!J)return[];let Q=this.defaults.get(z);if(!Q||!J.has(Q)){let W=this.providerOrder.get(z);Q=W&&W.length>0?W[0]:void 0}return Array.from(J.keys()).map((W)=>({pluginName:W,isDefault:W===Q}))}registerService(z,J,Q){let W=`${z}:${J}`;this.services.set(W,{service:Q,pluginName:z}),V().logger.debug("service-registry",`Registered service '${W}'`)}getService(z,J){let Q=`${z}:${J}`;return this.services.get(Q)?.service}unregisterServices(z){let J=[];for(let[Q,W]of this.services)if(W.pluginName===z)J.push(Q);for(let Q of J)this.services.delete(Q);if(J.length>0)V().logger.info("service-registry",`Unregistered ${J.length} services from ${z}`)}listProviders(){let z=[];for(let[J,Q]of this.providers)for(let[W,Z]of Q)z.push({type:J,name:W,pluginName:Z.pluginName});return z}listServices(){return Array.from(this.services.entries()).map(([z,J])=>({pluginName:J.pluginName,serviceName:z.split(":").slice(1).join(":")}))}clear(){this.providers.clear(),this.providerOrder.clear(),this.defaults.clear(),this.services.clear()}}import{extname as g,relative as o,resolve as u}from"path";import{realpath as E}from"fs/promises";var n=["'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"],D=!1;function w(){let z=process.env.VIBE_UI_FRAME_ANCESTORS?.trim(),J=z?z.split(/[\s,]+/).filter(Boolean):n;if(z&&!D&&(J.includes("*")||!J.includes("'self'")))D=!0,console.warn(`[ui-server] VIBE_UI_FRAME_ANCESTORS override does not include "'self'" or contains "*". This significantly weakens CSP frame-ancestors and is almost never intended. Override: ${z}`);return`frame-ancestors ${J.join(" ")}`}var l={".html":"text/html",".js":"application/javascript",".mjs":"application/javascript",".css":"text/css",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".map":"application/json",".wasm":"application/wasm"};function s(z){return l[g(z).toLowerCase()]||"application/octet-stream"}var b=`<script>
|
|
3
3
|
window.__VIBE_AUTH__={apiKey:null};
|
|
4
4
|
(function(){
|
|
5
5
|
var p=new URLSearchParams(window.location.search);
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Da as D}from"./index-
|
|
2
|
+
import{Da as D}from"./index-cv0xhb46.js";import{Xa as V}from"./index-0ckffygp.js";import{$d as A,Sd as _,Td as w,Ud as x,Vd as N,Wd as j,Zd as X,ce as I}from"./index-a4854mwz.js";import{ie as S}from"./index-c7554sg7.js";import{existsSync as $,readdirSync as v,readFileSync as O,writeFileSync as M,mkdirSync as E,openSync as T,closeSync as b,unlinkSync as R}from"fs";import{join as Q}from"path";import{tmpdir as F}from"os";import{spawn as h}from"child_process";class P{registryPath;logsDir;productDir;constructor(){let q=I();this.productDir=q,this.registryPath=Q(q,"agents.json");let z=A();this.logsDir=Q(z,"logs"),E(q,{recursive:!0}),E(z,{recursive:!0}),E(this.logsDir,{recursive:!0})}async startDaemon(q){return X(q.name),this.withInstanceLock(q.name,async()=>{let z=await this.findProcessByName(q.name);if(z&&z.status==="running"){let U=z.version,W=D();if(U===W){console.log(`\u26A0\uFE0F Agent '${q.name}' is already running on port ${z.port}`);return}console.log(`\uD83D\uDD04 Agent '${q.name}' is running an older build (${U??"unknown"} \u2192 ${W}) \u2014 restarting to apply the update`);try{await this.stopInternal(q.name)}catch(Z){console.log(`\u26A0\uFE0F Could not cleanly stop the stale daemon (${Z instanceof Error?Z.message:String(Z)}); proceeding to start the new build`)}}let B=Q(this.logsDir,`${q.name}.log`),C=T(B,"a"),H=Q(import.meta.dir,"index.js"),G=Q(import.meta.dir,"..","index.ts"),L=$(H)?H:G,K=h(process.execPath,["run",L],{detached:!0,windowsHide:!0,stdio:["ignore",C,C],env:{...process.env,VIBECONTROLS_PROFILE:q.profile||"default",PORT:q.port.toString(),DB_PATH:q.dbPath,NODE_ENV:"production",AGENT_LOG_FILE:B}});K.on("error",()=>{}),b(C),await new Promise((U)=>setTimeout(U,2000));let J=K.pid;if(!(J!==void 0&&await this.isProcessRunning(J))){let U="";try{U=O(B,"utf8").split(/\r?\n/).filter((k)=>k.trim()).slice(-25).join(`
|
|
3
3
|
`)}catch{}let W=`See ${B}`;throw Error(U?`Failed to start agent '${q.name}'. ${W}
|
|
4
4
|
--- last log lines ---
|
|
5
5
|
${U}`:`Failed to start agent '${q.name}'. ${W}`)}K.unref(),await this.saveProcessInfo(q.name,J,q),console.log(`\uD83D\uDE80 Agent '${q.name}' started (PID: ${J}, Port: ${q.port})`)})}async stop(q){return X(q),this.withInstanceLock(q,()=>this.stopInternal(q))}async stopInternal(q){let z=await this.findProcessByName(q);if(!z||z.status!=="running"){console.log(`\u26A0\uFE0F Agent '${q}' is not running`);return}try{if(process.kill(z.pid,"SIGTERM"),await new Promise((C)=>setTimeout(C,3000)),await this.isProcessRunning(z.pid))process.kill(z.pid,"SIGKILL");await this.updateProcessStatus(q,"stopped"),console.log(`\u2705 Agent '${q}' stopped (tunnel + API key preserved)`)}catch(B){throw Error(`Failed to stop agent '${q}': ${B}`,{cause:B})}}async restart(q,z){X(q),X(z.name);let B=await this.findProcessByName(q);if(B&&B.status==="running")await this.stop(q);await this.startDaemon(z),console.log(`\uD83D\uDD04 Agent '${q}' restarted (tunnel + API key preserved)`)}async kill(q){return X(q),this.withInstanceLock(q,async()=>{let z=await this.findProcessByName(q);if(!z||z.status!=="running"){console.log(`\u26A0\uFE0F Agent '${q}' is not running`);return}let B=Q(F(),`.boff-vibecontrols-kill-${z.pid}`);try{await Bun.write(B,"kill")}catch{}try{process.kill(z.pid,"SIGTERM"),await new Promise((H)=>setTimeout(H,5000))}catch{}if(await this.isProcessRunning(z.pid))await this.killProcessTree(z.pid);await this.updateProcessStatus(q,"stopped"),console.log(`\uD83D\uDC80 Agent '${q}' killed (tunnel + state torn down)`)})}async getStatus(q){return X(q),this.findProcessByName(q)}discoverRuntimeInstances(){let q=Q(this.productDir,"agents");if(!$(q))return[];let z;try{z=v(q,{withFileTypes:!0}).filter((C)=>C.isDirectory()).map((C)=>C.name)}catch{return[]}let B=[];for(let C of z){let H=Q(q,C,"runtime.json");if(!$(H))continue;try{let G=JSON.parse(O(H,"utf8"));if(typeof G.pid!=="number"||typeof G.port!=="number")continue;let L=G.profile||C;try{X(L)}catch{continue}B.push({name:L,pid:G.pid,port:G.port,config:{name:L,port:G.port,daemon:!0,dbPath:Q(q,C,"agent-db"),host:G.host,profile:L},startTime:G.startedAt??new Date(0).toISOString(),status:"unknown",version:G.version})}catch{}}return B}async getStatusAll(){let q=this.loadRegistry(),z=new Set(q.map((G)=>G.name)),B=[...q];for(let G of this.discoverRuntimeInstances())if(!z.has(G.name))B.push(G);let C=[];for(let G of B){let L=await this.isManagedProcessRunning(G);if(!z.has(G.name)&&!L)continue;C.push({...G,status:L?"running":"stopped"})}let H=C.filter((G)=>G.status==="running"&&!z.has(G.name));if(H.length>0)try{await _(()=>{let G=this.loadRegistry(),L=new Set(G.map((J)=>J.name)),K=H.filter((J)=>!L.has(J.name));if(K.length>0)this.saveRegistry([...G,...K.map((J)=>({...J,status:"running"}))])})}catch{}return C}async listInstances(){return this.getStatusAll()}getDefaultProfile(){return N()}setDefaultProfile(q){j(X(q))}async showLogs(q,z){X(q);let B=Q(this.logsDir,`${q}.log`);if(!$(B)){console.log(`No logs found for agent '${q}'`);return}if(z.follow)try{let C=async(J)=>{let Y=await Bun.file(B).text(),W=Y.split(`
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{o as F4,q as J4}from"./index-czrb2yd1.js";import{u as r4,v as U5,w as j5}from"./index-
|
|
2
|
+
import{o as F4,q as J4}from"./index-czrb2yd1.js";import{u as r4,v as U5,w as j5}from"./index-41vve5br.js";import{E as K4}from"./index-6jzsthh9.js";import{$ as y4,Q as C5,aa as L2,ba as x0,ca as f4,da as u4,ea as i4,fa as b4,ha as E2,ia as l2,ja as o2,ka as I2}from"./index-ebx79cc1.js";import{la as E5,qa as I5,sa as C0}from"./index-yas07mv9.js";import{va as c2}from"./index-68r2ex9d.js";import{wa as N5,xa as x5,ya as O5,za as M5}from"./index-4hn26x1h.js";import{Aa as _5}from"./index-4wgjx8bf.js";import{Ja as T0,Wa as T5}from"./index-cv0xhb46.js";import{Xa as N2}from"./index-0ckffygp.js";import{ab as P2}from"./index-rc79x8fw.js";import{eb as $5,fb as W5,gb as z5,hb as H5,ib as G5,jb as Y2,kb as B5,lb as V5,mb as K5,nb as F5,pb as L5}from"./index-6p3gcnxr.js";import{Ab as i0,Eb as M2,Fb as Y0,Gb as Z5,Hb as J5,Ib as j0,Jb as V2,Lb as m,Mb as l,Nb as d4,Ob as n4,Pb as X5,Qb as Y5,tb as l0,ub as v2,vb as d0,wb as X0,xb as n0,yb as R2}from"./index-bfeekmyh.js";import{Ub as z,Vb as D}from"./index-pgew6sge.js";import{nd as e0,od as t,pd as p0,qd as b2,rd as h2}from"./index-63ba5fb4.js";import{Ad as B2,Dd as i2,Id as g,Kd as M0,Ld as c,Md as s,Od as G,Pd as W0,wd as O0,xd as t4,yd as e4,zd as Q5}from"./index-xnr6t79p.js";import{$d as D2,Sd as r0,Td as H0,Vd as f2,Wd as t0,Yd as C2,Zd as d,be as T2,ce as F2,de as n2}from"./index-a4854mwz.js";import{fe as v0,ie as b}from"./index-c7554sg7.js";var R0=typeof new Headers()?.toJSON==="function",A5=($)=>{if(R0)return Object.keys($.toJSON()).join(", ");let Z="",Q=0;return $.forEach((Y,X)=>{if(Q)Z=Z+", "+X;else Z=X;Q++}),Z},A0=($)=>{let{aot:Z=!0,origin:Q=!0,methods:Y=!0,allowedHeaders:X=!0,exposeHeaders:J=!0,credentials:W=!0,maxAge:H=5,preflight:B=!0}=$??{};if(Array.isArray(X))X=X.join(", ");if(Array.isArray(J))J=J.join(", ");let K=typeof Q==="boolean"?void 0:Array.isArray(Q)?Q:[Q],L=new D({name:"@elysiajs/cors",seed:$,aot:Z}),w=K?.some((N)=>N==="*"),E={};if(K){for(let N of K)if(typeof N==="string")E[N]=!0}let x=(N,T,O)=>{if(Array.isArray(N))return N.some((I)=>x(I,T,O));switch(typeof N){case"string":if(O in E)return!0;let I=O.indexOf("://");if(I!==-1)O=O.slice(I+3);return N===O;case"function":return N(T)===!0;case"object":if(N instanceof RegExp)return N.test(O)}return!1},V=(N,T)=>{if(Q===!0){N.headers.vary="*",N.headers["access-control-allow-origin"]=T.headers.get("Origin")||"*";return}if(w){N.headers.vary="*",N.headers["access-control-allow-origin"]="*";return}if(!K?.length)return;if(K.length){let O=T.headers.get("Origin")??"";for(let I=0;I<K.length;I++)if(x(K[I],T,O)===!0){N.headers.vary=Q?"Origin":"*",N.headers["access-control-allow-origin"]=O||"*";return}}N.headers.vary="Origin"},C=(N,T)=>{if(!T)return;if(Y===!0)return N.headers["access-control-allow-methods"]=T??"*";if(Y===!1||!Y?.length)return;if(Y==="*")return N.headers["access-control-allow-methods"]="*";if(!Array.isArray(Y))return N.headers["access-control-allow-methods"]=Y;N.headers["access-control-allow-methods"]=Y.join(", ")},q={};if(typeof J==="string")q["access-control-expose-headers"]=J;if(typeof X==="string")q["access-control-allow-headers"]=X;if(W===!0)q["access-control-allow-credentials"]="true";L.headers(q);function v({set:N,request:T,headers:O}){if(V(N,T),C(N,T.headers.get("access-control-request-method")),X===!0||J===!0){if(X===!0)N.headers["access-control-allow-headers"]=O["access-control-request-headers"];if(J===!0)N.headers["access-control-expose-headers"]=Object.keys(O).join(",")}if(H)N.headers["access-control-max-age"]=H.toString();return new Response(null,{status:204})}if(B)L.options("/",v).options("/*",v);return L.onRequest(function({set:T,request:O}){if(V(T,O),B&&O.method==="OPTIONS")return v({set:T,request:O,headers:R0?O.headers.toJSON():Object.fromEntries(O.headers.entries())});if(C(T,O.method),X===!0||J===!0){let I=A5(O.headers);if(X===!0)T.headers["access-control-allow-headers"]=I;if(J===!0)T.headers["access-control-expose-headers"]=I}})};var k5="/code-server";function k0($,Z,Q=R2){let Y=$.method.toUpperCase();if(Y!=="GET"&&Y!=="HEAD")return null;let X=new URL($.url),J=X.searchParams.get("vt");if(!J||!Q(J,k5,"GET"))return null;X.searchParams.delete("vt");let W=new Headers($.headers);return W.set("x-agent-api-key",Z()),new Request(`${X.origin}${X.pathname}${X.search}`,{method:$.method,headers:W})}import{createHash as D0}from"crypto";var W2="idempotency",S5=300000,S0=1e4,A2=new Map;function D5($,Z,Q,Y){return D0("sha256").update(`${$}|${Z}|${Q}|${Y}`).digest("hex")}async function h5($,Z){let Q=await $.getPluginState(W2,Z);if(!Q)return null;try{let Y=JSON.parse(Q);if(Y.expiresAt<Date.now())return await $.deletePluginState(W2,Z),null;return Y}catch{return null}}async function v5($,Z,Q){await $.setPluginState(W2,Z,JSON.stringify(Q))}async function P5($){let Z=await $.getAllPluginState(W2),Q=Date.now(),Y=0,X=[];for(let J of Z)try{if(JSON.parse(J.value).expiresAt<Q)await $.deletePluginState(W2,J.key),Y+=1;else X.push({key:J.key,updatedAt:J.updatedAt})}catch{await $.deletePluginState(W2,J.key),Y+=1}if(X.length>S0){X.sort((W,H)=>(W.updatedAt??"").localeCompare(H.updatedAt??""));let J=X.slice(0,X.length-S0);for(let W of J)await $.deletePluginState(W2,W.key),Y+=1}if(Y>0)G().logger.info("idempotency",`Swept ${Y} expired/over-cap entries`)}var Q0=null,f5=600000;function b5($){if(Q0)return;Q0=setInterval(()=>{let Z=$.getDb();if(!Z)return;P5(Z).catch((Q)=>{G().logger.warn("idempotency","Sweep failed",{error:String(Q)})})},f5),Q0.unref?.()}function h0($){return b5($),new D({name:"plugin/idempotency"}).onBeforeHandle(async({request:Z,path:Q,set:Y,store:X})=>{if(Z.method!=="POST"&&Z.method!=="PUT")return;let J=Z.headers.get("x-idempotency-key")??Z.headers.get("X-Idempotency-Key");if(!J)return;if(J.length<8||J.length>200)return Y.status=400,{error:"X-Idempotency-Key must be 8\u2013200 chars",code:"BAD_REQUEST"};let W=$.getDb();if(!W)return;let H="no-body";try{let C=await Z.clone().text();H=D0("sha256").update(C).digest("hex")}catch{}let B=D5(Z.method,Q,J,H),K=await h5(W,B);if(K){Y.status=K.status;let V=Y.headers??={};V["Content-Type"]=K.contentType,V["X-Idempotency-Replay"]="true",X.__idemReplay=K.body;try{return JSON.parse(K.body)}catch{return K.body}}let L=A2.get(B);if(L){let V=await L.catch(()=>null);if(V){Y.status=V.status;let C=Y.headers??={};C["Content-Type"]=V.contentType,C["X-Idempotency-Replay"]="true",X.__idemReplay=V.body;try{return JSON.parse(V.body)}catch{return V.body}}}let w,E,x=new Promise((V,C)=>{w=V,E=C});A2.set(B,x),X.__idemKey=B,X.__idemResolve=w,X.__idemReject=E}).onAfterHandle(async({response:Z,set:Q,store:Y})=>{let X=Y.__idemKey;if(!X)return;let J=Y.__idemResolve,W=$.getDb(),H=Q.status??200,B=typeof Z==="string"?Z:JSON.stringify(Z),L=Q.headers?.["Content-Type"]??"application/json",w={status:H,body:B,contentType:L,expiresAt:Date.now()+S5},E=H>=200&&H<300;try{if(W&&E)await v5(W,X,w)}catch(x){G().logger.warn("idempotency","Failed to persist response",{error:String(x)})}finally{try{J?.(E?w:null)}catch{}A2.delete(X)}}).onError(({store:Z})=>{let Q=Z.__idemKey;if(!Q)return;let Y=Z.__idemReject;try{Y?.(Error("idempotency: handler errored"))}catch{}A2.delete(Q)}).as("global")}import u from"os";import{readFileSync as t5}from"fs";import{join as e5}from"path";var P0={enabled:!1,async scrape(){return`# vibecontrols agent metrics disabled (OTel SDK not initialised)
|
|
3
3
|
`},recordHttpRequest(){},setPluginsLoaded(){}},J2=null,k2=null;async function S2($){if(J2)return J2;if(k2)return k2;return k2=(async()=>{try{let{MeterProvider:Z}=await import("./index-p23tet7a.js").then((m)=>v0(m.default,1)),{PrometheusExporter:Q,PrometheusSerializer:Y}=await import("./index-qwtspxw8.js").then((m)=>v0(m.default,1)),X=new Q({preventServerStart:!0}),J=new Y,H=new Z({readers:[X]}).getMeter("vibecontrols-agent"),B=H.createGauge("vibecontrols_agent_info",{description:"Static info about the agent process; value is always 1."});H.createObservableGauge("vibecontrols_agent_uptime_seconds",{description:"Process uptime in seconds."}).addCallback((V)=>{V.observe(process.uptime())});let L=H.createCounter("vibecontrols_http_requests_total",{description:"Total HTTP requests handled by the agent, labelled by method, route, status."}),w={};H.createObservableGauge("vibecontrols_plugins_loaded",{description:"Plugins loaded by the agent, broken down by status (loaded, failed, etc.)."}).addCallback((V)=>{for(let[C,q]of Object.entries(w))V.observe(q,{status:C})}),B.record(1,{version:$?.version??"unknown",profile:$?.profile??"default"});let x={enabled:!0,async scrape(){let V=await X.collect();if(!V.resourceMetrics)return"";return J.serialize(V.resourceMetrics)},recordHttpRequest(V,C,q){L.add(1,{method:V,route:C,status:String(q)})},setPluginsLoaded(V){w={...V}}};return J2=x,G().logger.info("metrics","OTel Prometheus registry initialised"),x}catch(Z){return G().logger.warn("metrics","Failed to initialise OTel metrics; /metrics will return a stub body",{error:Z instanceof Error?Z.message:String(Z)}),J2=P0,P0}})(),k2}function f0($,Z,Q){if(!J2)return;J2.recordHttpRequest($,Z,Q)}function b0($){if(!J2)return;J2.setPluginsLoaded($)}var c5=new Set(["127.0.0.1","::1"]),c0=!1;function y5(){if(c0)return;if(process.env.METRICS_ANONYMOUS_LOCALHOST==="true")c0=!0,G().logger.warn("metrics","METRICS_ANONYMOUS_LOCALHOST=true \u2014 /metrics is open to TCP loopback peers without an API key. Prefer issuing a scoped API key for your scraper.")}function u5($){let Z=$.replace(/^\[|\]$/g,"");if(Z.startsWith("::ffff:"))return Z.slice(7);return Z}function $0($,Z){let Q=Z?.requestIP($)?.address;if(!Q)return!1;return c5.has(u5(Q))}function y0(){return y5(),new D({name:"routes/metrics"}).get("/metrics",async({request:$,server:Z,set:Q})=>{if(!(process.env.METRICS_ANONYMOUS_LOCALHOST==="true"&&$0($,Z))){let W=m(Object.fromEntries($.headers.entries()));if(!l(W))return Q.status=401,Q.headers["content-type"]="application/json",JSON.stringify({error:"Unauthorized",message:"Invalid or missing API key"})}let J=await(await S2()).scrape();return Q.headers["content-type"]="text/plain; version=0.0.4; charset=utf-8",J})}import{randomBytes as m5,timingSafeEqual as g5}from"crypto";import{chmodSync as p5,existsSync as u0,mkdirSync as l5,readFileSync as d5,unlinkSync as n5,writeFileSync as i5}from"fs";import{dirname as o5,join as a5}from"path";var z2=null;function m0(){return a5(D2(),"pairing-token")}function s5(){return m5(32).toString("base64url")}function r5($,Z){let Q=Buffer.from($),Y=Buffer.from(Z);if(Q.length!==Y.length)return!1;try{return g5(Q,Y)}catch{return!1}}function H6(){if(z2)return z2;let $=m0();try{if(u0($)){let Q=d5($,"utf8").trim();if(Q.length>=32)return z2=Q,Q}}catch{}let Z=s5();try{l5(o5($),{recursive:!0}),i5($,Z,{encoding:"utf8"});try{p5($,384)}catch{}}catch(Q){}return z2=Z,Z}function Z0($){if(!$)return!1;if(!z2)return!1;return r5($,z2)}function g0(){z2=null;try{let $=m0();if(u0($))n5($)}catch{}}function J0($){return $["x-pairing-token"]??$["X-Pairing-Token"]??null}function QQ(){let $=u.hostname(),Z=u.platform(),Q=u.arch(),Y=new Bun.CryptoHasher("sha256");return Y.update(`${$}-${Z}-${Q}`),Y.digest("hex").substring(0,16)}function $Q(){for(let $ of["..","../.."])try{let Z=e5(import.meta.dir,$,"package.json"),Y=JSON.parse(t5(Z,"utf8")).version;if(Y)return Y}catch{}return"0.0.0"}async function ZQ($){let Z=[],Q=$.getProvider("tunnel");if(Q)Z.push(Q);for(let Y of $.listProvidersForType("tunnel")){let X=$.getProviderByName("tunnel",Y.pluginName);if(X&&!Z.includes(X))Z.push(X)}for(let Y of Z){if(!Y.getActiveTunnelUrl)continue;let X=await Y.getActiveTunnelUrl();if(X)return X}return null}function o0({serviceRegistry:$,runFinalize:Z,getDb:Q}){let Y=$Q(),X=QQ();return new D({prefix:"/api/agent"}).get("/identity",()=>({hostname:u.hostname(),platform:u.platform(),architecture:u.arch(),agentVersion:Y,agentInstanceId:p0()})).get("/version",()=>({version:Y,runtime:"bun",runtimeVersion:typeof Bun<"u"?Bun.version:"unknown"})).get("/api-key",({request:J,server:W,set:H})=>{if(!$0(J,W)){let K=m(Object.fromEntries(J.headers.entries()));if(!l(K))return H.status=401,{error:"Unauthorized",message:"Invalid or missing API key"}}return{apiKey:V2()}}).post("/iframe-token",({body:J,request:W,set:H})=>{let B=m(Object.fromEntries(W.headers.entries()));if(!l(B))return H.status=401,{error:"Unauthorized",message:"Invalid or missing API key"};try{if(Array.isArray(J.pathPrefixes)&&J.pathPrefixes.length>0)return d0({pathPrefixes:J.pathPrefixes,methods:J.methods},J.ttlSeconds??void 0);if(!J.pathPrefix)return H.status=400,{error:"BadRequest",message:"Provide either pathPrefix (string) or pathPrefixes (string[])"};return v2(J.pathPrefix,J.ttlSeconds??void 0)}catch(K){return H.status=400,{error:"BadRequest",message:K instanceof Error?K.message:String(K)}}},{body:z.Object({pathPrefix:z.Optional(z.String({minLength:1})),pathPrefixes:z.Optional(z.Array(z.String({minLength:1}),{minItems:1,maxItems:16})),methods:z.Optional(z.Array(z.String({minLength:1}),{minItems:1,maxItems:8})),ttlSeconds:z.Optional(z.Number())})}).post("/terminal-exchange",({body:J,set:W})=>{let{sid:H,token:B}=J;if(!H||!B)return W.status=400,{error:"BadRequest",message:"sid and token required"};if(!l0(H))return W.status=400,{error:"BadRequest",message:"invalid sid"};let K=`/terminal/${H}`,L=n0(B,K);if(!L.ok)return G().logger.warn("terminal-exchange","iframe token rejected",{sid:H,reason:L.reason}),W.status=401,{error:"Unauthorized",message:"invalid iframe token",code:L.reason==="expired"?"expired":L.reason==="replayed"?"replayed":"invalid"};let w=i0(H,600),E=`vt_term_${H}`;return W.headers["set-cookie"]=`${E}=${w.token}; HttpOnly; Secure; SameSite=None; Path=/terminal/${H}; Max-Age=600`,W.status=204,null},{body:z.Object({sid:z.String({minLength:1}),token:z.String({minLength:1})})}).post("/ui-exchange",({body:J,set:W})=>{let{plugin:H,token:B}=J;if(!H||!B)return W.status=400,{error:"BadRequest",message:"plugin and token required"};if(!M2(H))return W.status=400,{error:"BadRequest",message:"invalid plugin name"};let K=`/ui/${H}`;if(!X0(B,K))return W.status=401,{error:"Unauthorized",message:"invalid iframe token"};let L=Y0(H,600),w=`vt_ui_${H}`;return W.headers["set-cookie"]=`${w}=${L.token}; HttpOnly; Secure; SameSite=None; Path=/ui/${H}/; Max-Age=600`,W.status=204,null},{body:z.Object({plugin:z.String({minLength:1}),token:z.String({minLength:1})})}).post("/ui-exchange-plugin",({body:J,set:W})=>{let{plugin:H,token:B}=J;if(!H||!B)return W.status=400,{error:"BadRequest",message:"plugin and token required"};if(!M2(H))return W.status=400,{error:"BadRequest",message:"invalid plugin name"};if(![`/api/plugins/${H}/ui`,`/${H}`].find((x)=>X0(B,x)))return W.status=401,{error:"Unauthorized",message:"invalid iframe token"};let w=Y0(H,600),E=`vt_ui_${H}`;return W.headers["set-cookie"]=`${E}=${w.token}; HttpOnly; Secure; SameSite=None; Path=/api/plugins/${H}/ui/; Max-Age=600`,W.status=204,null},{body:z.Object({plugin:z.String({minLength:1}),token:z.String({minLength:1})})}).get("/system",({request:J,set:W})=>{let H=m(Object.fromEntries(J.headers.entries()));if(!l(H))return W.status=401,{error:"Unauthorized",message:"Invalid or missing API key"};return{machineId:X,hostname:u.hostname(),platform:u.platform(),arch:u.arch(),release:u.release(),cpus:u.cpus().length,totalMemory:u.totalmem(),freeMemory:u.freemem(),uptime:u.uptime(),bunVersion:typeof Bun<"u"?Bun.version:void 0,agentVersion:Y,homeDir:u.homedir(),cwd:process.cwd(),environment:"production"}}).get("/tunnel",async({request:J,set:W})=>{let H=Object.fromEntries(J.headers.entries()),B=l(m(H)),K=Z0(J0(H));if(!B&&!K)return W.status=401,{error:"Unauthorized",message:"Provide x-agent-api-key OR x-pairing-token to read tunnel URL"};let L=await ZQ($);if(!L)return{tunnelUrl:null,message:"No tunnel provider registered"};return{tunnelUrl:L}}).get("/status",()=>{let J=["tunnel","session","ai"].filter((W)=>$.hasProvider(W));return{state:G().getBootState(),status:G().getBootState(),version:Y,providers:J,timestamp:new Date().toISOString()}}).get("/gateway-auth",()=>({configured:g.isConfigured(),config:P2(g.getConfig()),state:G().getBootState()})).post("/retry-config",async({set:J})=>{let{getFinalizeRetryHandle:W}=await import("./finalize-retry-handle-registry-xnm9kxry.js"),H=W();if(!H)return J.status=409,{ok:!1,error:"No finalize retry worker is active. The agent either never had cached credentials to retry with, or it already reached the ready state."};let B=await H.forceRetryNow();if(!B.ok)J.status=503;return{ok:B.ok,error:B.ok?void 0:B.error,state:G().getBootState(),worker:H.getState()}}).post("/gateway-auth",async({body:J,request:W,set:H})=>{let B=G().getBootState(),K=Object.fromEntries(W.headers.entries());if(B==="ready"){let N=m(K);if(!l(N))return H.status=401,{success:!1,state:B,error:"Unauthorized: API key required to reconfigure"}}else{let N=m(K),T=J0(K),O=l(N),I=Z0(T);if(!O&&!I)return H.status=401,{success:!1,state:B,error:"Unauthorized: provide x-agent-api-key OR x-pairing-token for bootstrap"}}let{clientId:L,clientSecret:w,workspaceId:E,globalGatewayUrl:x,workspaceGatewayUrl:V}=J;if(!L||!w||!E||!x||!V)return H.status=400,{success:!1,state:G().getBootState(),error:"clientId, clientSecret, workspaceId, globalGatewayUrl, and workspaceGatewayUrl are required"};let C,q;try{C=B2(x,"globalGatewayUrl"),q=B2(V,"workspaceGatewayUrl")}catch(N){return H.status=400,{success:!1,state:G().getBootState(),error:N instanceof Error?N.message:String(N)}}{let N=c()??G();try{await h2({clientId:L,clientSecret:w,workspaceId:E,ownerUserId:J.ownerUserId,organizationId:J.organizationId,globalGatewayUrl:C,workspaceGatewayUrl:q,agentRecordId:J.agentRecordId,scopes:J.scopes,...J.storageAdapter?{storageAdapter:J.storageAdapter}:{},...J.storageOptions?{storageOptions:J.storageOptions}:{},...J.dbPath?{dbPath:J.dbPath}:{}},{dir:N.dataDir,scope:N.name})}catch(T){return H.status=500,{success:!1,state:G().getBootState(),error:`Failed to persist gateway credentials to secrets backend: ${T instanceof Error?T.message:String(T)}`}}}let v=G().getBootState();if(v==="ready"){let N=Q();if(N){if(await N.setConfig("gateway-auth:clientId",L),await N.setConfig("gateway-auth:clientSecret",w),await N.setConfig("gateway-auth:workspaceId",E),J.organizationId)await N.setConfig("gateway-auth:organizationId",J.organizationId);if(await N.setConfig("gateway-auth:globalGatewayUrl",C),await N.setConfig("gateway-auth:workspaceGatewayUrl",q),J.agentRecordId)await N.setConfig("gateway-auth:agentRecordId",J.agentRecordId)}g.configure({globalGatewayUrl:C,workspaceGatewayUrl:q,clientId:L,clientSecret:w,workspaceId:E,organizationId:J.organizationId}),G().logger.info("preconfig","Gateway credentials re-configured (agent was already ready)");let T=!!(J.storageAdapter||J.storageOptions||J.dbPath);return{success:!0,state:v,message:T?"Gateway auth re-configured. Restart the agent (vibe restart) to apply the new storage configuration.":"Gateway auth re-configured"}}return G().logger.info("preconfig","Gateway credentials received \u2014 beginning finalize (background)"),g0(),Z({clientId:L,clientSecret:w,workspaceId:E,organizationId:J.organizationId,globalGatewayUrl:C,workspaceGatewayUrl:q},{agentRecordId:J.agentRecordId,scopes:J.scopes}).catch((N)=>{G().logger.error("preconfig","Background finalize threw",{error:N instanceof Error?N.message:String(N)})}),H.status=202,{success:!0,state:G().getBootState(),agentRecordId:J.agentRecordId,message:"Gateway credentials accepted; finalize is running in the background. Poll /health/ready for completion."}},{body:z.Object({clientId:z.Optional(z.String()),clientSecret:z.Optional(z.String()),workspaceId:z.Optional(z.String()),ownerUserId:z.Optional(z.String()),organizationId:z.Optional(z.String()),globalGatewayUrl:z.Optional(z.String()),workspaceGatewayUrl:z.Optional(z.String()),scopes:z.Optional(z.Array(z.String())),agentRecordId:z.Optional(z.String()),storageAdapter:z.Optional(z.String()),storageOptions:z.Optional(z.Record(z.String(),z.String())),dbPath:z.Optional(z.String())})})}import{existsSync as $2,mkdirSync as JQ,rmSync as a0,readdirSync as Q4}from"fs";import{join as y2}from"path";function a($){return y2(F2(),"agents",d($))}function XQ(){let $=y2(F2(),"agents");if(!$2($))return[];return Q4($,{withFileTypes:!0}).filter((Z)=>Z.isDirectory()).map((Z)=>Z.name).filter((Z)=>/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(Z))}function $4($){return y2(F2(),"agents",d($))}function z0($){return t({dir:$4($)})}function s0($,Z){return b2(Z,{dir:$4($),scope:d($)})}function K2($){let Z=f2(),Q=H0().find((J)=>J.name===$),Y=s.get($),X={name:$,isDefault:$===Z,isRunning:Q?.status==="running",attached:Y!==void 0,bootState:Y?Y.getBootState():null,dataDir:Y?Y.dataDir:null};if(Q)X.port=Q.port,X.pid=Q.pid,X.startTime=Q.startTime;if($2(a($)))X.config=P2(z0($));return X}function Z4($={}){let Z=$.serviceManagerFactory?$.serviceManagerFactory():new c2;return new D({prefix:"/api/profiles"}).get("/",()=>{let Q=XQ(),Y=f2(),X=new Set(Q);return X.add(Y),[...X].sort().map((J)=>K2(J))}).post("/",async({body:Q,set:Y})=>{try{let X=d(Q.name),J=a(X);if($2(J))return Y.status=409,{error:"exists",message:`Profile '${X}' already exists.`};let W;if(Q.copyFrom){let H=d(Q.copyFrom);if(!$2(a(H)))return Y.status=400,{error:"copy-source-missing",message:`Profile '${H}' does not exist.`};W=z0(H),delete W["static-api-key"],delete W.agentRecordId,delete W.apiKeys}else W=e0();if(Q.gatewayUrl)W.globalGatewayUrl=Q.gatewayUrl;if(Q.workspaceGatewayUrl)W.workspaceGatewayUrl=Q.workspaceGatewayUrl;if(Q.clientId)W.clientId=Q.clientId;if(Q.clientSecret)W.clientSecret=Q.clientSecret;if(Q.workspaceId)W.workspaceId=Q.workspaceId;if(Q.organizationId)W.organizationId=Q.organizationId;JQ(J,{recursive:!0}),s0(X,W);try{W0(X)}catch(H){G().logger.warn("profile-mgmt",`In-process attach failed for '${X}'`,{error:String(H)})}if(G().logger.info("profile-mgmt",`Created profile '${X}' at ${J}`),Q.start){let H={name:X,port:Q.port??0,daemon:!0,dbPath:T2(),profile:X};await Z.startDaemon(H)}return Y.status=201,K2(X)}catch(X){return Y.status=400,{error:"create-failed",message:X instanceof Error?X.message:String(X)}}},{body:z.Object({name:z.String(),gatewayUrl:z.Optional(z.String()),workspaceGatewayUrl:z.Optional(z.String()),clientId:z.Optional(z.String()),clientSecret:z.Optional(z.String()),workspaceId:z.Optional(z.String()),organizationId:z.Optional(z.String()),copyFrom:z.Optional(z.String()),start:z.Optional(z.Boolean()),port:z.Optional(z.Number())})}).get("/:name",({params:Q,set:Y})=>{try{let X=d(Q.name);if(!$2(a(X)))return Y.status=404,{error:"not-found",message:`No profile '${X}'.`};return K2(X)}catch(X){return Y.status=400,{error:"bad-request",message:X instanceof Error?X.message:String(X)}}},{params:z.Object({name:z.String()})}).put("/:name",({params:Q,body:Y,set:X})=>{try{let J=d(Q.name);if(!$2(a(J)))return X.status=404,{error:"not-found",message:`No profile '${J}'.`};let W=["static-api-key","apiKeys","agentRecordId"];for(let K of W)if(K in Y)return X.status=400,{error:"forbidden-field",message:`Field '${K}' is managed via dedicated commands (vibe key rotate / vibe profile create). It cannot be patched here.`};if("registry"in Y)return X.status=400,{error:"forbidden-field",message:"Field 'registry' cannot be patched via this endpoint. Use POST /api/agent/registry with operator confirmation (VIBE_ALLOW_REGISTRY_CHANGE=1) so the change is auditable."};let B={...z0(J),...Y};return s0(J,B),K2(J)}catch(J){return X.status=400,{error:"update-failed",message:J instanceof Error?J.message:String(J)}}},{params:z.Object({name:z.String()}),body:z.Record(z.String(),z.Any())}).delete("/:name",async({params:Q,body:Y,query:X,set:J})=>{try{let W=d(Q.name);if(W===f2())return J.status=409,{error:"is-default",message:`Cannot delete active default profile '${W}'. Switch to another profile first.`};let H=X?.purge==="true"||X?.purge==="1",B=$2(a(W)),K=s.has(W);if(!B&&!K)return J.status=404,{error:"not-found",message:`No profile '${W}'.`};if(B&&!H&&!Y?.confirm)return J.status=400,{error:"confirm-required",message:"Pass { confirm: true } in the body or `?purge=true` in the query to delete the on-disk dataDir (destructive)."};try{await Z.stop(W)}catch{}try{await s.destroy(W)}catch(L){G().logger.warn("profile-mgmt",`In-process detach failed for '${W}'`,{error:String(L)})}if(B)if(Y?.keepConfig)for(let L of Q4(a(W))){if(L==="config.json")continue;a0(y2(a(W),L),{recursive:!0,force:!0})}else a0(a(W),{recursive:!0,force:!0});return G().logger.info("profile-mgmt",`Deleted profile '${W}'`),{ok:!0,deleted:W,keptConfig:!!Y?.keepConfig,detached:K,purged:B}}catch(W){return J.status=400,{error:"delete-failed",message:W instanceof Error?W.message:String(W)}}},{params:z.Object({name:z.String()}),query:z.Optional(z.Object({purge:z.Optional(z.String())})),body:z.Optional(z.Object({confirm:z.Optional(z.Boolean()),keepConfig:z.Optional(z.Boolean())}))}).post("/:name/switch",async({params:Q,set:Y})=>{try{let X=d(Q.name);if(!$2(a(X)))return Y.status=404,{error:"not-found",message:`No profile '${X}'.`};return await r0(()=>t0(X)),G().logger.info("profile-mgmt",`Default profile switched to '${X}'`),{ok:!0,defaultProfile:X}}catch(X){return Y.status=400,{error:"switch-failed",message:X instanceof Error?X.message:String(X)}}},{params:z.Object({name:z.String()})}).post("/:name/start",async({params:Q,body:Y,set:X})=>{try{let J=d(Q.name);if(!$2(a(J)))return X.status=404,{error:"not-found",message:`No profile '${J}'.`};try{W0(J)}catch(H){G().logger.warn("profile-mgmt",`In-process attach failed for '${J}'`,{error:String(H)})}if(!H0().some((H)=>H.name===J&&H.status==="running")){let H={name:J,port:Y?.port??0,daemon:!0,dbPath:T2(),profile:J};await Z.startDaemon(H)}return K2(J)}catch(J){return X.status=500,{error:"start-failed",message:J instanceof Error?J.message:String(J)}}},{params:z.Object({name:z.String()}),body:z.Optional(z.Object({port:z.Optional(z.Number())}))}).post("/:name/stop",async({params:Q,set:Y})=>{try{let X=d(Q.name);try{await Z.stop(X)}catch{}try{await s.destroy(X)}catch(J){G().logger.warn("profile-mgmt",`In-process detach failed for '${X}'`,{error:String(J)})}return K2(X)}catch(X){return Y.status=500,{error:"stop-failed",message:X instanceof Error?X.message:String(X)}}},{params:z.Object({name:z.String()})})}function YQ(){let $=process.memoryUsage(),Z=process.resourceUsage(),Q=Z.userCPUTime/1000,Y=Z.systemCPUTime/1000,X=Q+Y,J=s.list().map((W)=>{let H;try{H=J4(W.spawnOwnerKey).length}catch{H=0}return{name:W.name,status:W.getBootState(),childPidCount:H,cpuMs:X,heapBytes:$.heapUsed,dataDir:W.dataDir}});return{process:{pid:process.pid,uptimeSeconds:process.uptime(),cpuUserMs:Q,cpuSystemMs:Y,heapUsedBytes:$.heapUsed,heapTotalBytes:$.heapTotal,rssBytes:$.rss},profiles:J,notes:{perProfileCpu:"deferred",perProfileHeap:"deferred"}}}function X4(){return new D({prefix:"/api/profile-stats"}).get("/",()=>YQ())}function u2($,Z){return Promise.race([$,new Promise((Q,Y)=>setTimeout(()=>Y(Error(`timeout after ${Z}ms`)),Z))])}function WQ($){let Z=$ instanceof Error?$.message:String($);return/ENOENT/.test(Z)||/no such file or directory/i.test(Z)}async function Y4($){let Q=`__health__:probe:${typeof crypto<"u"&&typeof crypto.randomUUID==="function"?crypto.randomUUID():`${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`}`,Y=String(Date.now());if(await u2($.setConfig(Q,Y),2000),await u2($.getConfig(Q),2000)!==Y)throw Error("round-trip mismatch");try{await u2($.deleteConfig(Q),500)}catch{}}async function zQ($,Z){if(!$)return{ok:!1,message:"database not opened"};let Q=performance.now();try{return await Y4($),{ok:!0,durationMs:performance.now()-Q}}catch(Y){if(Z&&WQ(Y))try{return(await import("fs")).mkdirSync(Z,{recursive:!0}),await Y4($),{ok:!0,message:`recovered: dbPath ${Z} was missing \u2014 recreated`,durationMs:performance.now()-Q}}catch(X){return{ok:!1,message:`ENOENT on dbPath ${Z}: ${X instanceof Error?X.message:String(X)}`,durationMs:performance.now()-Q}}return{ok:!1,message:Y instanceof Error?Y.message:String(Y),durationMs:performance.now()-Q}}}function W4($,Z){if(!$)return{ok:!1,message:"no service registry"};let Y=G().getBootState()==="awaiting-config";if(Z==="tunnel"){let X=$.getProvider("tunnel");if(!X&&process.env.AGENT_TUNNEL==="false")return{ok:!0,message:"tunnel disabled via AGENT_TUNNEL=false"};if(X)return{ok:!0,message:`provider: ${X.name}`};return{ok:!1,message:Y?"agent is awaiting-config \u2014 POST OAuth credentials to /api/agent/gateway-auth to register tunnel provider":"no tunnel provider registered"}}if(Z==="session"){let X=$.getProvider("session");if(X)return{ok:!0,message:`provider: ${X.name}`};return{ok:!1,message:Y?"agent is awaiting-config \u2014 POST OAuth credentials to /api/agent/gateway-auth to register session provider":"no session provider registered"}}return{ok:!0}}async function HQ($){if(!$)return{};let Z={};for(let Q of $.getAllPlugins()){let Y=Q.getHealth;if(typeof Y!=="function")continue;let X=performance.now();try{let J=await u2(Promise.resolve(Y.call(Q)),2000);Z[Q.name]={ok:J?.ok!==!1,message:J?.message,durationMs:performance.now()-X}}catch(J){Z[Q.name]={ok:!1,message:J instanceof Error?J.message:String(J),durationMs:performance.now()-X}}}return Z}function z4($){let Z=$&&"serviceRegistry"in $?$:{serviceRegistry:$};return new D({prefix:"/health"}).get("/",()=>{return{status:"ok",lifecycleState:Z.serviceRegistry?.getService("agent","lifecycle")?.getState()??"running",bootState:G().getBootState(),timestamp:new Date().toISOString(),uptime:process.uptime()}}).get("/live",()=>({status:"ok"})).get("/ready",async({set:Q})=>{let X=Z.serviceRegistry?.getService("agent","lifecycle")?.getState()??"running",J=G().getBootState(),W={};W.boot={ok:J==="ready",message:J==="ready"?void 0:`boot state ${J}`},W.lifecycle={ok:X==="running",message:X==="running"?void 0:`lifecycle ${X}`},W.db=await zQ(Z.getDb?.()??null,Z.getDbPath?.()??null),W.tunnel=W4(Z.serviceRegistry,"tunnel"),W.session=W4(Z.serviceRegistry,"session");try{let{gatewayClient:V}=await import("./gateway-client-xdy5g715.js");if(!V.isConfigured())W.registration={ok:!0,message:"not configured"};else{let C=Z.getDb?.()??null;if(C?await C.getConfig("gateway-auth:agentRecordId"):null)W.registration={ok:!0};else{let v=G().getDegradedReasons().some((N)=>N.plugin==="agent-registration");W.registration=v?{ok:!1,message:"agent failed to register with the workspace after retries"}:{ok:!0,message:"registering"}}}}catch(V){W.registration={ok:!0,message:`registration check skipped: ${V instanceof Error?V.message:String(V)}`}}let H=await HQ(Z.getPluginManager?.()??null),B=Object.values(W).every((V)=>V.ok)&&Object.values(H).every((V)=>V.ok);if(!B)Q.status=503;let K=J==="degraded"?G().getDegradedReasons():[],L=G().name,w={};for(let V of s.list())w[V.name]={bootState:V.getBootState(),ok:V.getBootState()==="ready",degradedReasons:V.getDegradedReasons()};let E=G().getLastFinalizeError(),x={status:B?"ok":"degraded",lifecycleState:X,bootState:J,daemon:{profile:L,bootState:J,ok:J==="ready"},profiles:w,components:W,plugins:H,degradedReasons:K,lastFinalizeError:E,timestamp:new Date().toISOString()};if(!B)G().logger.warn("health","Readiness probe failed",{components:W,plugins:H,bootState:J});return x})}var m2=0,H4=0;function G4(){return new D({name:"inflight-tracker"}).onRequest(()=>{m2+=1}).onAfterResponse(()=>{m2=Math.max(0,m2-1),H4+=1})}function B4(){return new D({prefix:"/api/stats"}).get("/inflight",()=>({inflight:Math.max(0,m2-1),totalServed:H4}))}var G0=Object.freeze(["code","code-insiders","codium","cursor","idea","pycharm","webstorm","goland","phpstorm","rubymine","clion","rider","zed","subl","vim","nvim","emacs","neovide","fleet","helix"]),GQ=new Set(G0),BQ=new Set(["--new-window","-n","--reuse-window","-r","--wait","-w","--add","--goto"]);function V4($){try{return Bun.which($)??null}catch{return null}}function L4(){return new D({prefix:"/api/editor"}).get("/allowlist",()=>({commands:[...G0]})).get("/detect",async()=>{let $=G0.map((Y)=>[Y,V4(Y)]),Z=[],Q={};for(let[Y,X]of $)if(X)Z.push(Y),Q[Y]=X;return{available:Z,paths:Q}}).post("/open",async({body:$,set:Z})=>{let{command:Q,path:Y,args:X=[]}=$;if(!GQ.has(Q))return Z.status=400,{ok:!1,error:`Command '${Q}' is not in the IDE allowlist`};for(let H of X)if(typeof H!=="string"||!BQ.has(H))return Z.status=400,{ok:!1,error:`Argument '${H}' is not in the flag allowlist`};let J;try{J=(await K4(Y,{mustExist:!0})).realPath}catch(H){return Z.status=400,{ok:!1,error:`Invalid path: ${H instanceof Error?H.message:String(H)}`}}let W=V4(Q);if(!W)return Z.status=404,{ok:!1,error:`'${Q}' is not installed or not on PATH on this agent`};try{let H=F4({owner:`editor:${Q}`,cmd:[W,...X,J],env:process.env,stdout:"ignore",stderr:"ignore",stdin:"ignore",meta:{command:Q,path:J}});return G().logger.info("editor",`Launched ${Q} on ${J}`,{pid:H.pid}),G().audit.emit("agent","editor.open",{command:Q,path:J,pid:H.pid}),{ok:!0,command:Q,resolvedPath:J,pid:H.pid}}catch(H){return Z.status=500,{ok:!1,error:`Failed to spawn editor: ${H instanceof Error?H.message:String(H)}`}}},{body:z.Object({command:z.String({minLength:1,maxLength:40}),path:z.String({minLength:1,maxLength:4096}),args:z.Optional(z.Array(z.String({maxLength:32})))})})}var N4=Symbol.for("@vibecontrols/plugin-sdk:contextProviders@1");function VQ(){let $=globalThis,Z=$[N4];if(Z)return Z;let Q=new Map;return $[N4]=Q,Q}function B0(){return Array.from(VQ().values())}function _4(){return(c()??G()).dataDir}function n(){let $=t({dir:_4()});return{ownerUserId:$.ownerUserId,workspaceId:$.workspaceId}}function g2(){return t({dir:_4()}).agentRecordId}function U4($){if(!$)return null;try{return new URL($).host}catch{return null}}async function j4($,Z){let Q=$.getPluginManager(),Y=Q?Q.getPluginDetails().map((H)=>({pluginName:H.pluginName,packageName:H.packageName,version:H.version,tags:H.tags??[]})):[],X=process.memoryUsage(),J=U4($.getTunnelHost?.()??null),W;try{W=L2(n()).map((H)=>({id:H.id,label:H.label,host:U4(H.tunnelUrl),agentRecordId:H.agentRecordId??null,permissions:H.permissions,canForward:H.permissions.includes("mesh:forward"),lastReachable:H.lastReachable??null}))}catch{W=[]}return{pluginName:"agent",description:"vibecontrols-agent runtime self-report",generatedAt:new Date().toISOString(),data:{profile:Z.profile,vibeId:Z.vibeId??null,runtime:{bunVersion:typeof Bun<"u"?Bun.version:null,nodeVersion:process.versions.node??null,platform:process.platform,arch:process.arch,pid:process.pid,uptimeSeconds:Math.round(process.uptime()),memory:{rssMB:Math.round(X.rss/1048576),heapUsedMB:Math.round(X.heapUsed/1048576)}},agent:{version:$.getAgentVersion?.()??null,profileRegistered:C2(),tunnelHost:J},plugins:{count:Y.length,items:Y},mesh:{peerCount:W.length,peers:W}}}}var KQ=2000,x4=1000;async function FQ($,Z){let Q,Y=new Promise((X,J)=>{Q=setTimeout(()=>J(Error(`timeout after ${Z}ms`)),Z)});try{return await Promise.race([$,Y])}finally{if(Q)clearTimeout(Q)}}async function O4($,Z){let Q=performance.now(),Y=$.timeoutMs??KQ;try{let X=await FQ($.getContext(Z),Y);if(!X.generatedAt)X.generatedAt=new Date().toISOString();return{ok:!0,data:X,durationMs:Math.round(performance.now()-Q)}}catch(X){return{ok:!1,error:X.message??String(X),durationMs:Math.round(performance.now()-Q)}}}class V0{deps;inflight=new Map;constructor($){this.deps=$}async aggregate($){let Z=`${$.profile}::${$.vibeId??""}`,Q=this.inflight.get(Z);if(Q&&Date.now()-Q.ts<x4)return Q.promise;let Y=this.doAggregate($).finally(()=>{setTimeout(()=>{let X=this.inflight.get(Z);if(X&&X.promise===Y)this.inflight.delete(Z)},x4).unref?.()});return this.inflight.set(Z,{ts:Date.now(),promise:Y}),Y}async selfContext($){return j4(this.deps,$)}async pluginContext($,Z){let Q=B0().find((Y)=>Y.name===$);if(!Q)return null;return O4(Q,Z)}async pluginsContext($){let Z=B0(),Q=await Promise.allSettled(Z.map((X)=>O4(X,$))),Y={};return Z.forEach((X,J)=>{let W=Q[J];if(W&&W.status==="fulfilled")Y[X.name]=W.value;else if(W&&W.status==="rejected")Y[X.name]={ok:!1,error:W.reason instanceof Error?W.reason.message:String(W.reason),durationMs:0}}),Y}async doAggregate($){let[Z,Q]=await Promise.all([this.selfContext($),this.pluginsContext($)]);return{agent:Z,plugins:Q}}}function p2($){let Z=$.vibeId;if(typeof Z!=="string")return;let Q=Z.trim();return Q.length>0&&Q.length<=128?Q:void 0}function M4($){let Z=new V0($);return new D({prefix:"/api/agent/context"}).get("/",async({params:Q,query:Y})=>{let X=Q?.profile??"default",J=p2(Y);return Z.aggregate({profile:X,vibeId:J})},{query:z.Object({vibeId:z.Optional(z.String())})}).get("/agent",async({params:Q,query:Y})=>{let X=Q?.profile??"default",J=p2(Y);return Z.selfContext({profile:X,vibeId:J})},{query:z.Object({vibeId:z.Optional(z.String())})}).get("/plugins",async({params:Q,query:Y})=>{let X=Q?.profile??"default",J=p2(Y);return Z.pluginsContext({profile:X,vibeId:J})},{query:z.Object({vibeId:z.Optional(z.String())})}).get("/plugins/:name",async({params:Q,query:Y,set:X})=>{let J=Q?.profile??"default",W=Q?.name;if(!W)return X.status=400,{error:"missing plugin name"};let H=p2(Y),B=await Z.pluginContext(W,{profile:J,vibeId:H});if(!B)return X.status=404,{error:`no context provider registered under name "${W}"`};return B},{params:z.Object({name:z.String()}),query:z.Object({vibeId:z.Optional(z.String())})})}var Z2="autoupdate",LQ=86400000,T4=300000,NQ=900000,S={timer:null,running:!1,profile:"default",lastCheckAt:null,lastCheck:null,lastUpdateAt:null,lastUpdate:null,startedAt:null};function K0(){let $=(process.env.VIBE_AUTOUPDATE??"").trim().toLowerCase();return $==="0"||$==="false"||$==="off"||$==="no"}function E4(){if(K0())return!1;try{return t().autoUpdate!==!1}catch{return!0}}function F0(){let $=Number(process.env.VIBE_AUTOUPDATE_INTERVAL_MS);if(Number.isFinite($)&&$>0)return Math.max(NQ,$);return LQ}async function L0($){let Z=G().logger;if(S.running)return{check:S.lastCheck??await C4(),update:null};S.running=!0;try{let Q=await E2();if(S.lastCheck=Q,S.lastCheckAt=new Date().toISOString(),Q.error)Z.debug(Z2,`Update check failed: ${Q.error}`);else if(Q.hasUpdate)Z.info(Z2,`New agent version available: ${Q.current} \u2192 ${Q.latest}`);let Y=$?.force||E4();if(!Q.hasUpdate||!Y)return{check:Q,update:null};Z.info(Z2,`Auto-updating ${Q.current} \u2192 ${Q.latest} (idle-gated restart)\u2026`);let X=await l2({restart:!0,name:S.profile,onLog:(J)=>Z.info(Z2,J)});if(S.lastUpdate=X,S.lastUpdateAt=new Date().toISOString(),X.ok&&X.updated)Z.info(Z2,`Auto-update applied: now ${X.current} (restart: ${X.restart}).`);else if(!X.ok)Z.warn(Z2,`Auto-update failed: ${X.error}`);return{check:Q,update:X}}catch(Q){return Z.warn(Z2,`Auto-update tick threw: ${Q instanceof Error?Q.message:String(Q)}`),{check:await C4(),update:null}}finally{S.running=!1}}async function C4(){if(S.lastCheck)return S.lastCheck;let $=await E2();return S.lastCheck=$,S.lastCheckAt=new Date().toISOString(),$}function I4($){if(S.timer)clearTimeout(S.timer);S.timer=setTimeout(()=>{L0().finally(()=>{if(S.startedAt)I4(F0())})},$),S.timer.unref?.()}function _Q($){let Z=G().logger;if(S.profile=$?.profile||process.env.VIBECONTROLS_PROFILE||"default",S.startedAt=new Date().toISOString(),K0()){Z.info(Z2,"Autoupdate disabled via VIBE_AUTOUPDATE \u2014 not scheduling.");return}Z.info(Z2,`Autoupdate scheduled (first check in ${Math.round(T4/60000)}m, then every ${Math.round(F0()/3600000)}h).`),I4(T4)}function L7(){if(S.timer)clearTimeout(S.timer),S.timer=null;S.startedAt=null}function w4($){if(b2({autoUpdate:$}),$&&!S.startedAt)_Q({profile:S.profile})}function N0(){let $=!0;try{$=t().autoUpdate!==!1}catch{}return{enabled:E4(),envKillSwitch:K0(),configEnabled:$,scheduled:!!S.startedAt,intervalMs:F0(),profile:S.profile,startedAt:S.startedAt,lastCheckAt:S.lastCheckAt,lastCheck:S.lastCheck,lastUpdateAt:S.lastUpdateAt,lastUpdate:S.lastUpdate}}import{existsSync as q4}from"fs";import{join as R4}from"path";var UQ=600000,_0=1e6;function jQ(){let $=N2(),Z=$.which("bun")??`bun${$.executableSuffix}`,Q=R4(import.meta.dir,"cli.js");if(q4(Q))return{runner:Z,prefix:[Q]};let Y=R4(import.meta.dir,"..","cli.ts");if(q4(Y))return{runner:Z,prefix:[Y]};let X=$.which("vibe");if(X)return{runner:X,prefix:[]};return null}function A4($){if($.length<=_0)return $;return $.slice(0,_0)+`
|
|
4
|
-
\u2026[output truncated at ${_0} bytes]`}async function d2($,Z={}){let Q=jQ();if(!Q)return{ok:!1,exitCode:null,stdout:"",stderr:"Could not locate the vibe CLI to execute (no dist/cli.js, source, or PATH entry).",timedOut:!1,argv:$,command:"(unresolved)"};let Y=[...Q.prefix,...$],X=[Q.runner,...Y].join(" ");try{let J=Bun.spawn([Q.runner,...Y],{cwd:Z.cwd,env:{...process.env,VIBE_AUTO_ACCEPT:"1",CI:"1",NO_COLOR:"1",...Z.env},stdout:"pipe",stderr:"pipe"}),W=Z.timeoutMs??UQ,H=!1,B=setTimeout(()=>{H=!0;try{J.kill()}catch{}},W),[K,L,w]=await Promise.all([new Response(J.stdout).text(),new Response(J.stderr).text(),J.exited]);return clearTimeout(B),{ok:!H&&w===0,exitCode:w,stdout:A4(K),stderr:A4(L),timedOut:H,argv:$,command:X}}catch(J){return{ok:!1,exitCode:null,stdout:"",stderr:`Failed to spawn vibe CLI: ${J instanceof Error?J.message:String(J)}`,timedOut:!1,argv:$,command:X}}}async function k4(){let{Command:$}=await import("./esm-6f3dfn6v.js"),{registerCoreCommands:Z}=await import("./register-core-
|
|
4
|
+
\u2026[output truncated at ${_0} bytes]`}async function d2($,Z={}){let Q=jQ();if(!Q)return{ok:!1,exitCode:null,stdout:"",stderr:"Could not locate the vibe CLI to execute (no dist/cli.js, source, or PATH entry).",timedOut:!1,argv:$,command:"(unresolved)"};let Y=[...Q.prefix,...$],X=[Q.runner,...Y].join(" ");try{let J=Bun.spawn([Q.runner,...Y],{cwd:Z.cwd,env:{...process.env,VIBE_AUTO_ACCEPT:"1",CI:"1",NO_COLOR:"1",...Z.env},stdout:"pipe",stderr:"pipe"}),W=Z.timeoutMs??UQ,H=!1,B=setTimeout(()=>{H=!0;try{J.kill()}catch{}},W),[K,L,w]=await Promise.all([new Response(J.stdout).text(),new Response(J.stderr).text(),J.exited]);return clearTimeout(B),{ok:!H&&w===0,exitCode:w,stdout:A4(K),stderr:A4(L),timedOut:H,argv:$,command:X}}catch(J){return{ok:!1,exitCode:null,stdout:"",stderr:`Failed to spawn vibe CLI: ${J instanceof Error?J.message:String(J)}`,timedOut:!1,argv:$,command:X}}}async function k4(){let{Command:$}=await import("./esm-6f3dfn6v.js"),{registerCoreCommands:Z}=await import("./register-core-r7fjpp4w.js"),Q=new $;Q.name("vibe").option("--json").option("--plain").option("-y, --yes").option("-p, --profile <name>");try{Z(Q)}catch{}let Y=new Set(["nuke","kill","gc","stop","rollback","deploy"]),X=[];for(let J of Q.commands){let W=J.name();if(!W||W==="help")continue;X.push({name:W,description:J.description()||"",usage:J.usage()||"",options:J.options.map((H)=>({flags:H.flags,description:H.description||""})),group:"core",destructive:Y.has(W)})}return X.sort((J,W)=>J.name.localeCompare(W.name))}import{spawn as xQ}from"child_process";import{writeFileSync as OQ,mkdirSync as MQ}from"fs";import{tmpdir as TQ}from"os";import{join as S4}from"path";var CQ="@vibecontrols/agent";function D4($){let Z=N2(),Q=Z.which("bun")??`bun${Z.executableSuffix}`,Y=Z.which("npm")??`npm${Z.executableSuffix}`,X=n2(),J=$.delayMs??3000,W=$.pids.filter((B)=>Number.isInteger(B)&&B>0),H=`// vibecontrols agent self-uninstall reaper (auto-generated)
|
|
5
5
|
const PIDS = ${JSON.stringify(W)};
|
|
6
6
|
const NPM = ${JSON.stringify(Y)};
|
|
7
7
|
const BUN = ${JSON.stringify(Q)};
|
|
@@ -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
|
}`,wQ=`mutation ReportAgentMeshLink($input: ReportAgentMeshLinkInput!) {
|
|
24
24
|
reportAgentMeshLink(input: $input) { id }
|
|
25
|
-
}`,P4="VIBE_BOOTSTRAP_JSON=";function qQ($){for(let Y of $.split(/\r?\n/)){let X=Y.indexOf(P4);if(X>=0)try{return JSON.parse(Y.slice(X+P4.length))}catch{}}let Z=$.indexOf("{"),Q=$.lastIndexOf("}");if(Z>=0&&Q>Z)try{return JSON.parse($.slice(Z,Q+1))}catch{return null}return null}async function c4($,Z){let Q=(L,w,E)=>Z?.({step:L,status:w,message:E}),Y=b4($.permissions??["tunnel:read","session:list","plugin:list","diagnostics:read","mesh:forward"]);if(!Y.includes("mesh:forward"))Y.push("mesh:forward");let X=(L)=>({ok:!1,peerId:"",agentRecordId:null,tunnelUrl:null,permissions:Y,error:L}),J;try{J=o2($.target,{identityFile:$.identityFile})}catch(L){return X(L instanceof Error?L.message:String(L))}let W=$.label??J.id,H=Y.join(","),B,K='export PATH="$HOME/.bun/bin:$PATH"; ';try{if(!$.connectExisting){Q("probe","running");let O=await J.probe();if(Q("probe","completed",`os=${O.os??"?"} arch=${O.arch??"?"}`),!O.bun){if($.installBun===!1)return X("Bun is required to run the agent but is not installed, and Bun auto-install was disabled.");Q("install-bun","running");let i=await J.run(["sh","-c",`curl -fsSL https://bun.sh/install | bash && echo 'export PATH="$HOME/.bun/bin:$PATH"' >> ~/.bashrc`],{timeoutMs:300000});if(i.code!==0)return Q("install-bun","failed",i.stderr.slice(0,400)),X("Bun auto-install failed.");let _2=await J.run(["sh","-c","$HOME/.bun/bin/bun --version 2>/dev/null"],{timeoutMs:1e4});if(_2.code===0&&_2.stdout.trim())O.bun="$HOME/.bun/bin/bun",Q("install-bun","completed",_2.stdout.trim());else return X("Bun installed but the binary is not reachable.")}Q("install-agent","running");let I=$.version??"latest",h=$.registry??"https://registry.npmjs.org/";if(!/^[A-Za-z0-9._@/^~>=<-]+$/.test(I))return Q("install-agent","failed","invalid version"),X(`Invalid agent version: ${I}`);if(!/^https?:\/\/[A-Za-z0-9._~:/?#@!$&'()*+,;=%-]+$/.test(h))return Q("install-agent","failed","invalid registry"),X(`Invalid registry URL: ${h}`);let y=await J.run(["sh","-c",`${K}npm_config_registry="${h}" bun install -g @vibecontrols/agent@${I} --no-cache`],{timeoutMs:600000});if(y.code!==0)return Q("install-agent","failed",y.stderr.slice(0,400)),X(`Agent install failed (exit ${y.code}).`);if(B=(await J.run(["sh","-c",`${K}vibe --version`],{timeoutMs:15000})).stdout.trim()||void 0,Q("install-agent","completed",B),$.autostart)Q("autostart","running"),await J.run(["sh","-c",`${K}vibe autostart install`],{timeoutMs:60000}),Q("autostart","completed");if($.installPlugins?.length){Q("plugins","running");for(let i of $.installPlugins)await J.run(["sh","-c",`${K}vibe plugin install ${i}`],{timeoutMs:300000});Q("plugins","completed")}Q("start","running"),await J.run(["sh","-c",`${K}vibe start`],{timeoutMs:60000}),Q("start","completed")}Q("bootstrap","running");let L=$.expiresIn?` --expires-in ${$.expiresIn}`:"",w=W.replace(/'/g,""),E=null;for(let O=0;O<15;O++){let I=`${K}vibe peer-bootstrap --json --emit-default-key --label '${w}' --scope ${H}${L} 2>/dev/null`,h=await J.run(["sh","-c",I],{timeoutMs:15000});if(h.code===0){let y=qQ(h.stdout);if(y&&typeof y.apiKey==="string"){E=y;break}}await new Promise((y)=>setTimeout(y,2000))}if(!E)return Q("bootstrap","failed","could not obtain peer-bootstrap bundle"),X("Remote peer-bootstrap did not return a credential bundle.");Q("bootstrap","completed");let x=n(),V=String(E.id),C=String(E.apiKey),q=i2(typeof E.tunnelUrl==="string"?E.tunnelUrl:null),v=typeof E.agentRecordId==="string"?E.agentRecordId:null;if($.onboardBackend!==!1&&g.isConfigured()&&q&&typeof E.fullDefaultApiKey==="string"){Q("onboard","running");let O=5,I="no agent returned";for(let h=0;h<O;h++){try{let i=(await g.workspaceQuery(IQ,{input:{tunnelUrl:q,apiKey:E.fullDefaultApiKey,name:W}})).data?.addVibecontrolsAgentFromTunnel;if(i?.agent?.id){v=i.agent.id,I="",Q("onboard","completed",`agent ${v}`);break}I=i?.error??"no agent returned"}catch(r){I=r instanceof Error?r.message:String(r)}if(!/unreachable|resolve hostname|timed out|timeout|ECONN|network|to fetch|50[234]/i.test(I)||h===O-1)break;Q("onboard","running",`retry ${h+1}/${O-1}: ${I.slice(0,80)}`),await new Promise((r)=>setTimeout(r,3000*(h+1)))}if(I)Q("onboard","failed",I)}else Q("onboard","skipped");Q("store-creds","running"),f4({id:V,label:W,tunnelUrl:q??"",apiKey:C,permissions:Y,addedAt:new Date().toISOString(),agentRecordId:v??void 0,workspaceId:(typeof E.workspaceId==="string"?E.workspaceId:x.workspaceId)??void 0,fingerprint:V,ownerUserId:x.ownerUserId,sshTarget:J.mode==="ssh"?$.target:void 0,sshIdentityFile:$.identityFile}),Q("store-creds","completed");let N=g2();if($.onboardBackend!==!1&&g.isConfigured()&&N&&v){Q("report-link","running");try{await g.workspaceQuery(wQ,{input:{sourceAgentRecordId:N,destinationAgentRecordId:v,label:W}}),Q("report-link","completed")}catch(O){Q("report-link","failed",O instanceof Error?O.message:String(O))}}else Q("report-link","skipped");let T=await I2(V,"/api/profiles/default/agent/identity",{operation:"post-deploy-probe"});return Q("probe-peer",T.ok?"completed":"failed",T.error??void 0),{ok:!0,peerId:V,agentRecordId:v,tunnelUrl:q,permissions:Y,remoteVersion:B}}catch(L){return X(L instanceof Error?L.message:String(L))}finally{await J.close().catch(()=>{})}}var U0='export PATH="$HOME/.bun/bin:$PATH"; ';function RQ($){let Z=$.indexOf("{"),Q=$.lastIndexOf("}");if(Z>=0&&Q>Z)try{let Y=JSON.parse($.slice(Z,Q+1));if(Y.tunnelUrl)return Y.tunnelUrl;if(Y.url&&Y.url.startsWith("https"))return Y.url}catch{}return null}async function m4($,Z){let Q=(J,W,H)=>Z?.({step:J,status:W,message:H}),Y=y4($);if(!Y)return{ok:!1,peerId:$,tunnelUrl:null,error:`No peer with id ${$}`};if(!Y.sshTarget)return{ok:!1,peerId:$,tunnelUrl:null,error:"No SSH target stored for this peer \u2014 it wasn't SSH-deployed, so it can't be woken via SSH."};let X;try{X=o2(Y.sshTarget,{identityFile:Y.sshIdentityFile})}catch(J){return{ok:!1,peerId:$,tunnelUrl:null,error:J instanceof Error?J.message:String(J)}}try{Q("ssh-restart","running",Y.sshTarget);let J=await X.run(["sh","-c",`${U0}vibe restart 2>/dev/null || ${U0}vibe start`],{timeoutMs:90000});if(J.code!==0)return Q("ssh-restart","failed",J.stderr.slice(0,300)),{ok:!1,peerId:$,tunnelUrl:null,error:`Remote restart failed (exit ${J.code})`};Q("ssh-restart","completed"),Q("await-tunnel","running");let W=null;for(let H=0;H<15;H++){let B=await X.run(["sh","-c",`${U0}vibe url --json 2>/dev/null`],{timeoutMs:15000});if(B.code===0){let K=RQ(B.stdout),L=i2(K);if(L){W=L;break}}await new Promise((K)=>setTimeout(K,2000))}if(!W)return Q("await-tunnel","failed","no fresh tunnel after restart"),{ok:!1,peerId:$,tunnelUrl:null,error:"Agent restarted but no fresh tunnel came up."};return Q("await-tunnel","completed",W),u4($,{tunnelUrl:W,lastReachable:new Date().toISOString()}),Q("update","completed"),{ok:!0,peerId:$,tunnelUrl:W}}catch(J){return{ok:!1,peerId:$,tunnelUrl:null,error:J instanceof Error?J.message:String(J)}}finally{await X.close().catch(()=>{})}}var DQ=Number(process.env.VIBECONTROLS_MESH_MAX_HOPS||"8");function g4(){return(c()??G()).name}function hQ(){return(c()??G()).dataDir}function p4(){try{let Z=SQ(hQ(),"runtime.json");if(AQ(Z)){let Q=JSON.parse(kQ(Z,"utf8"));if(Q.port&&Number.isInteger(Q.port))return Q.port}}catch{}let $=Number(process.env.PORT);return Number.isInteger($)&&$>0?$:3005}function vQ($){let Z={};return $.headers.forEach((Q,Y)=>{Z[Y]=Q}),Z}function X2($,Z){let Q=m(vQ($));return n4(d4(Q),Z)}function PQ($){let{apiKey:Z,...Q}=$;return{...Q,apiKey:"[REDACTED]"}}function l4($){return typeof $==="string"&&$.startsWith("/api/")&&!$.includes("..")&&!$.includes("//")}var a2=new Map;function fQ(){let $=Date.now()-3600000;for(let[Z,Q]of a2)if(Q.completedAt&&Date.parse(Q.completedAt)<$)a2.delete(Z)}function o4(){return new D({name:"agent-mesh"}).get("/api/mesh/peers",({request:$,set:Z})=>{if(!X2($,["read"]))return Z.status=403,{error:"forbidden"};return{peers:L2(n()).map(PQ)}}).delete("/api/mesh/peers/:id",({request:$,set:Z,params:Q})=>{if(!X2($,["mutate"]))return Z.status=403,{error:"forbidden"};if(!L2(n()).some((X)=>X.id===Q.id))return Z.status=404,{error:"not found"};return{ok:i4(Q.id)}}).post("/api/mesh/peers/:id/call",async({request:$,set:Z,params:Q,body:Y})=>{if(!X2($,["mesh:forward"]))return Z.status=403,{error:"forbidden"};let X=Y;if(!l4(X.path))return Z.status=400,{error:"invalid path"};if(!L2(n()).find((H)=>H.id===Q.id))return Z.status=404,{error:"not found"};let W=await I2(Q.id,X.path,{method:X.method??"GET",body:X.body,operation:"mesh-call"});return{ok:W.ok,status:W.status,data:W.data,rotated:W.rotated,error:W.error}},{body:z.Object({method:z.Optional(z.String()),path:z.String(),body:z.Optional(z.Any())})}).post("/api/mesh/forward",async({request:$,set:Z,body:Q})=>{if(!X2($,["mesh:forward"]))return Z.status=403,{error:"forbidden"};let Y=Q;if(!Y.request||!l4(Y.request.path))return Z.status=400,{error:"invalid request"};let X=(Y._hopCount??0)+1;if(X>DQ)return Z.status=422,{error:"hop limit exceeded"};let J=n(),W=g2(),H=Y.hops??[];if(H.length===0){G().audit.emit("mesh","forward.terminal",{path:Y.request.path,method:Y.request.method??"GET"});let x=(Y.request.method??"GET").toUpperCase();try{let V=await fetch(`http://127.0.0.1:${p4()}${Y.request.path}`,{method:x,headers:{"x-agent-api-key":await j0(),...Y.request.body!==void 0?{"content-type":"application/json"}:{}},body:Y.request.body!==void 0?JSON.stringify(Y.request.body):void 0,signal:AbortSignal.timeout(60000)}),C=await V.text().catch(()=>""),q=null;try{q=C?JSON.parse(C):null}catch{q=null}return{ok:V.ok,status:V.status,data:q,text:C||null,error:V.ok?null:C||`status ${V.status}`}}catch(V){return Z.status=502,{ok:!1,status:0,error:V instanceof Error?V.message:String(V)}}}let B=H[0],K=Y._traversed??[];if(B===W||K.includes(B))return Z.status=422,{error:"cycle detected",at:B};let L=x0(B,J);if(!L)return Z.status=403,{error:"next hop not in authorized boundary"};if(!L.permissions.includes("mesh:forward"))return Z.status=403,{error:"peer lacks mesh:forward grant"};G().audit.emit("mesh","forward.hop",{nextId:B,remaining:H.length,hopCount:X});let w=encodeURIComponent(g4()),E=await I2(L.id,`/api/profiles/${w}/mesh/forward`,{method:"POST",operation:"mesh-forward",timeoutMs:60000,body:{hops:H.slice(1),request:Y.request,_traversed:[...K,W??"self"],_hopCount:X}});if(!E.ok)return Z.status=502,{ok:!1,status:E.status,error:E.error,failedAtHop:B};return E.data},{body:z.Object({hops:z.Optional(z.Array(z.String())),request:z.Object({method:z.Optional(z.String()),path:z.String(),body:z.Optional(z.Any())}),_traversed:z.Optional(z.Array(z.String())),_hopCount:z.Optional(z.Number())})}).post("/api/mesh/deploy",({request:$,set:Z,body:Q})=>{if(!X2($,["admin"]))return Z.status=403,{error:"forbidden"};fQ();let Y=Q,X=n(),J=crypto.randomUUID(),W={id:J,status:"running",steps:[],ownerUserId:X.ownerUserId,workspaceId:X.workspaceId,startedAt:new Date().toISOString()};return a2.set(J,W),c4({target:Y.target,permissions:Y.permissions,installPlugins:Y.installPlugins,autostart:Y.autostart,identityFile:Y.identityFile,label:Y.label,version:Y.version,connectExisting:Y.connectExisting},(H)=>{W.steps.push(H),Y2("mesh:deploy:progress",{jobId:J,step:H})}).then((H)=>{if(W.result=H,W.status=H.ok?"completed":"failed",!H.ok)W.error=H.error;W.completedAt=new Date().toISOString(),Y2(H.ok?"mesh:deploy:complete":"mesh:deploy:failed",{jobId:J,result:H})}).catch((H)=>{W.status="failed",W.error=H instanceof Error?H.message:String(H),W.completedAt=new Date().toISOString(),Y2("mesh:deploy:failed",{jobId:J,error:W.error})}),Z.status=202,{jobId:J,status:"running"}},{body:z.Object({target:z.String(),permissions:z.Optional(z.Array(z.String())),installPlugins:z.Optional(z.Array(z.String())),autostart:z.Optional(z.Boolean()),identityFile:z.Optional(z.String()),label:z.Optional(z.String()),version:z.Optional(z.String()),connectExisting:z.Optional(z.Boolean())})}).get("/api/mesh/deploy/jobs/:id",({request:$,set:Z,params:Q})=>{if(!X2($,["read"]))return Z.status=403,{error:"forbidden"};let Y=a2.get(Q.id),X=n();if(!Y||X.ownerUserId&&Y.ownerUserId&&Y.ownerUserId!==X.ownerUserId)return Z.status=404,{error:"not found"};return Y}).post("/api/mesh/wake",async({request:$,set:Z,body:Q})=>{if(!X2($,["admin"]))return Z.status=403,{error:"forbidden"};let Y=Q,X=x0(Y.targetAgentRecordId,n());if(!X)return Z.status=404,{ok:!1,error:"peer not in authorized boundary"};G().audit.emit("mesh","wake.start",{peerId:X.id,agentRecordId:Y.targetAgentRecordId});let J=await m4(X.id,(W)=>Y2("mesh:wake:progress",{peerId:X.id,step:W}));if(!J.ok)Z.status=502;return J},{body:z.Object({targetAgentRecordId:z.String()})}).post("/api/mesh/session",async({request:$,set:Z,body:Q})=>{if(!X2($,["mesh:forward","mutate"]))return Z.status=403,{error:"forbidden"};let Y=Q,X=Y.sessionId&&/^[A-Za-z0-9_-]{1,128}$/.test(Y.sessionId)?Y.sessionId:crypto.randomUUID(),J=encodeURIComponent(g4()),W=await j0(),H=`http://127.0.0.1:${p4()}`,B=Y.command||"bash";try{let K=await fetch(`${H}/api/profiles/${J}/sessions/create`,{method:"POST",headers:{"x-agent-api-key":W,"content-type":"application/json"},body:JSON.stringify({sessionId:X,sessionName:`vc-mesh-${X.slice(0,8)}`,command:B,provider:"TERMINAL",...Y.vibeId?{projectId:Y.vibeId}:{}}),signal:AbortSignal.timeout(20000)});if(!K.ok)return Z.status=502,{error:`session create returned ${K.status}: ${await K.text().catch(()=>"")}`};let L=await fetch(`${H}/api/profiles/${J}/sessions/${encodeURIComponent(X)}/terminal`,{method:"POST",headers:{"x-agent-api-key":W},signal:AbortSignal.timeout(20000)});if(!L.ok)return Z.status=502,{error:`terminal start returned ${L.status}: ${await L.text().catch(()=>"")}`};let w=v2(`/terminal/${X}`,600);return G().audit.emit("mesh","session.created",{sessionId:X,kind:Y.kind??"TERMINAL"}),{connectionId:X,sessionId:X,capabilityToken:w.token,expiresAt:w.expiresAt}}catch(K){return Z.status=502,{error:K instanceof Error?K.message:String(K)}}},{body:z.Object({sessionId:z.Optional(z.String()),kind:z.Optional(z.String()),cwd:z.Optional(z.String()),vibeId:z.Optional(z.String()),command:z.Optional(z.String())})})}var bQ=["/health","/api/agent/status","/api/agent/version","/api/agent/identity","/api/agent/api-key","/api/agent/tunnel","/api/agent/system","/api/agent/gateway-auth","/api/stats","/metrics","/api/profiles","/api/profile-stats"];function cQ($){return bQ.some((Z)=>$.startsWith(Z))}var yQ=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function uQ($){return $.split("/").map((Z)=>{if(!Z)return Z;if(/^\d+$/.test(Z))return":id";if(yQ.test(Z))return":id";if(Z.length>=24&&/^[A-Za-z0-9_-]+$/.test(Z))return":id";return Z}).join("/")}async function a8($){let{port:Z,host:Q,dbPath:Y,logLevel:X,corsOrigin:J}=$,W=Y??T2();try{(await import("fs")).mkdirSync(W,{recursive:!0})}catch(F){throw G().logger.error("app","Failed to create dbPath dir at boot",{dbPath:W,error:String(F)}),Error(`Cannot create dbPath ${W}: ${F instanceof Error?F.message:String(F)}`,{cause:F})}if(X)G().logger.setLevel(X);(async()=>{let{logShipper:F}=await import("./log-shipper-hjnn1d5p.js");F.init()})(),(async()=>{let F=await s4();await S2({version:F,profile:C2()})})();try{let{checkDependencies:F}=await import("./bootstrap.service-vg72w8pa.js"),M=F(),U=M.filter((R)=>R.required&&!R.installed),A=M.filter((R)=>!R.required&&!R.installed);if(U.length>0)G().logger.error("app",`Missing required system deps: ${U.map((R)=>R.name).join(", ")}. Run \`vibe setup\` to install.`);if(A.length>0)G().logger.warn("app",`Missing optional system deps: ${A.map((R)=>R.name).join(", ")}. Some plugins may fail their prereqs check.`)}catch(F){G().logger.warn("app","Boot-time dependency check failed",{error:String(F)})}try{G().audit.runRetention()}catch(F){G().logger.warn("app","Audit-log retention sweep failed",{error:String(F)})}let H=new N5;I5(H,{port:Z});let B="GET, POST, PUT, PATCH, DELETE, OPTIONS",K="Content-Type, x-agent-api-key, Authorization, x-requested-with",L=Array.isArray(J)?J:(J??"").split(",").map((F)=>F.trim()).filter(Boolean),w=new Set(["https://vibecontrols.com","https://app.vibecontrols.com","https://alphaapp.vibecontrols.com","https://burdenoff.com","https://app.burdenoff.com","https://alphaapp.burdenoff.com"]),E=(F)=>{try{let M=new URL(F);if(L.includes(F))return!0;if(L.includes("*"))return!1;return M.hostname==="localhost"||M.hostname==="127.0.0.1"||M.hostname==="0.0.0.0"||M.hostname.endsWith(".local.burdenoff.com")||w.has(M.origin)}catch{return!1}},x=null,V=null,C=null,q=null,v=!1,N=()=>[],T=null,O=null,I=null,h=5000,y=async(F,M)=>{let U=Date.now();try{await Promise.race([Promise.resolve(M()),new Promise((A,R)=>setTimeout(()=>R(Error(`shutdown phase ${F} exceeded ${h}ms`)),h))]),G().logger.info("app",`shutdown.phase ${F} complete`,{ms:Date.now()-U})}catch(A){G().logger.warn("app",`shutdown.phase ${F} failed`,{error:String(A),ms:Date.now()-U})}},r=async(F)=>{if(v)return;if(v=!0,G().logger.info("app","Agent shutdown starting",{reason:F?.reason??"shutdown"}),await y("plugins",async()=>{if(V)await V.dispatchServerStop(F)}),await y("bootstrap-tunnel",()=>C0()),await y("tracked-subprocesses",async()=>{let{killAllTracked:M}=await import("./subprocess-q2ky0ptw.js");await M()}),F?.reason!=="reload")await y("db-close",async()=>{if(x)await x.close()});await y("http-listener",async()=>{try{await Promise.resolve(e.stop())}catch(M){G().logger.warn("app","Listener stop threw (already stopped or never started?)",{error:String(M)})}}),G().logger.info("app","Agent server stopped"),G().logger.close()},i=async(F,M)=>{if(G().getBootState()==="ready")return{ok:!0};if(I)return I;return I=(async()=>{G().setBootState("initializing");try{let U={...F,globalGatewayUrl:B2(F.globalGatewayUrl,"globalGatewayUrl"),workspaceGatewayUrl:B2(F.workspaceGatewayUrl,"workspaceGatewayUrl")},A=await U5(U),R=W,P=t({dir:G().dataDir}),p=P.storageAdapter??process.env.VIBE_STORAGE_ADAPTER??void 0,o=P.storageOptions,Q2=(_)=>{let j=(_ instanceof Error?_.message:String(_)).toLowerCase(),k=_&&typeof _==="object"&&"code"in _?String(_.code).toUpperCase():"";if(k==="EBUSY"||k==="EPERM"||k==="EACCES"||k==="EAGAIN"||k==="EMFILE"||k==="ENFILE"||k==="ETIMEDOUT"||k==="ECONNRESET"||k==="ECONNREFUSED"||j.includes("encryption key")||j.includes("fetch")&&j.includes("key")||j.includes("temporarily unavailable")||j.includes("resource busy"))return"transient";if(j.includes("auth tag")||j.includes("authentication tag")||j.includes("unable to authenticate data")||j.includes("bad decrypt")||j.includes("unsupported state")||j.includes("incorrect header check")||j.includes("invalid distance")||j.includes("incorrect data check")||j.includes("unexpected end of")||j.includes("unexpected token")||j.includes("json")&&(j.includes("parse")||j.includes("invalid"))||j.includes("truncated")||j.includes("malformed")||j.includes("corrupt"))return"corruption";return"unknown"},U2=()=>r4({dbPath:R,encryptionKey:A,adapterName:p,adapterOptions:o});try{x=await U2()}catch(_){let j=_,k=Q2(_),q2=[500,2000,8000];if(k==="transient"||k==="unknown"){G().logger.warn("app",`Storage open failed (${k}); will retry up to ${q2.length} times before quarantine`,{error:_ instanceof Error?_.message:String(_),path:R});for(let O2 of q2){await new Promise((f)=>setTimeout(f,O2));try{x=await U2(),j=null;break}catch(f){if(j=f,k=Q2(f),G().logger.warn("app",`Storage open retry failed (${k}) after ${O2}ms`,{error:f instanceof Error?f.message:String(f)}),k==="corruption")break}}}if(!x&&j){if(k!=="corruption"){let f=j instanceof Error?j.message:String(j);G().logger.error("app",`Storage open failed after retries with non-corruption error (${k}); refusing to quarantine valid data`,{error:f,path:R}),G().recordDegradedReason("storage",f);try{throw j}catch(G2){throw Error(`Storage open failed (${k}); agent is degraded: ${f}`,{cause:G2})}}let O2=j instanceof Error?j.message:String(j);G().logger.error("app","QUARANTINE: Storage file is corrupt \u2014 renaming and creating fresh DB",{errorClass:"corruption",error:O2,path:R});try{let f=await import("fs");if(f.existsSync(R)){let G2=new Date().toISOString().replace(/[:.]/g,"-"),q0=`${R}.broken-${G2}`;f.renameSync(R,q0),G().logger.warn("app",`Quarantined corrupt storage to ${q0} \u2014 fresh DB will be created`,{originalError:O2})}x=await U2()}catch(f){let G2=f instanceof Error?f.message:String(f);throw G().recordDegradedReason("storage",G2),Error(`Storage open failed twice (quarantine path); agent is degraded: ${G2}`,{cause:f})}}}if(!x)throw Error("Internal error: storage open recovery exited without an open database and without throwing");if(await h2({clientId:U.clientId,clientSecret:U.clientSecret,workspaceId:U.workspaceId,organizationId:U.organizationId,globalGatewayUrl:U.globalGatewayUrl,workspaceGatewayUrl:U.workspaceGatewayUrl,agentRecordId:M?.agentRecordId,scopes:M?.scopes},{dir:G().dataDir,scope:G().name}),await x.setConfig("gateway-auth:clientId",U.clientId),await x.setConfig("gateway-auth:clientSecret",U.clientSecret),await x.setConfig("gateway-auth:globalGatewayUrl",U.globalGatewayUrl),await x.setConfig("gateway-auth:workspaceGatewayUrl",U.workspaceGatewayUrl),await x.setConfig("gateway-auth:workspaceId",U.workspaceId),U.organizationId)await x.setConfig("gateway-auth:organizationId",U.organizationId);if(M?.agentRecordId)await x.setConfig("gateway-auth:agentRecordId",M.agentRecordId);H.db=x,await H.hydrateDefaultsFromDb(),V=new T5(x),await V.loadCorePlugins();try{await V.loadAll()}catch(_){G().logger.warn("app","Failed to load some external plugins",{error:String(_)})}let j2=C5(F2())??void 0,x2=process.env.VIBE_SKIP_AUTO_INSTALL==="1"||await x.getConfig("plugins:auto-install-disabled");if(x2!=="true"&&x2!==!0)try{let _=await V.ensureDefaultPlugins((j)=>G().logger.info("app",`[auto-install] ${j}`),[],j2);if(_.length>0)G().logger.info("app",`Auto-installed ${_.length} default plugin(s): ${_.map((j)=>j.packageName).join(", ")}`)}catch(_){G().logger.warn("app","Failed to auto-install default plugins",{error:String(_)})}G().logger.info("app",`Plugins loaded: ${V.getPluginDetails().length} total (${V.getPluginDetails().filter((_)=>_.isCore).length} core)`);try{let _=V.getPluginDetails(),j={loaded:_.filter((k)=>k.loaded).length,failed:_.filter((k)=>!k.loaded).length};b0(j)}catch{}let r2={async get(_,j){return await x.getPluginState(_,j)??null},async set(_,j,k){await x.setPluginState(_,j,k)},async delete(_,j){return x.deletePluginState(_,j)},async list(_){return await x.getAllPluginState(_)},async deleteAll(_){return x.deleteAllPluginState(_)}},w2=await s4();C={storage:r2,logger:G().logger,serviceRegistry:H,getProvider:(_)=>H.getProvider(_),getAgentBaseUrl:()=>process.env.AGENT_URL||`http://localhost:${Z}`,getAgentVersion:()=>w2,validateApiKey:(_)=>l(_),setCodeServerSessionValidator:(_)=>{w5=_},broadcast:Y2,workspaceQuery:async(_,j)=>g.workspaceQuery(_,j),isGatewayConfigured:()=>g.isConfigured(),getAgentRecordId:async()=>await x.getConfig("gateway-auth:agentRecordId")??null,getWorkspaceId:async()=>await x.getConfig("gateway-auth:workspaceId")??null,getConfig:async(_)=>await x.getConfig(_)??void 0,getPluginRegistry:()=>n2(),getDataDir:()=>D2(),cliContributors:new _5,audit:{emit:(_,j)=>G().audit.emit("agent",_,j??{})},telemetry:{emit:(_,j)=>{import("./telemetry-jxfgrm61.js").then(({telemetryService:k})=>k.emit(_,j??{})).catch(()=>{})}},os:N2(),iframeBridge:M5()},g.configure({globalGatewayUrl:U.globalGatewayUrl,workspaceGatewayUrl:U.workspaceGatewayUrl,clientId:U.clientId,clientSecret:U.clientSecret,workspaceId:U.workspaceId,organizationId:U.organizationId});let H2={db:x,serviceRegistry:H,pluginManager:V,broadcast:Y2,hostServices:C};H2.app=e;let w0=!1,t2=()=>{let{routes:_,getPublicPaths:j,mountPlugin:k}=$5(V,H2);if(H2.mountPlugin=k,N=j,X5(),T=_,O=O5(V),V&&w0&&C)V.dispatchServerStart(T,C).catch((q2)=>G().logger.warn("app","Re-dispatch of onServerStart after plugin reload failed",{error:String(q2)}));w0=!0};H2.rebuildPluginSurfaces=t2,t2(),q=new j5(H,V,x,e,C,r),H.registerService("agent","lifecycle",q),G().attachServices({db:x,serviceRegistry:H,pluginManager:V,lifecycle:q,hostServices:C}),F5(G(),{rebuildPluginSurfaces:t2,mountPlugin:H2.mountPlugin,app:T});try{await G().keyVault.bindApiKey(V2())}catch(_){G().logger.warn("app","Failed to bind api key into daemon keyVault",{error:String(_)})}let e2=[];try{let{failures:_}=await V.dispatchServerStart(T,C);for(let j of _)if(T0(j.plugin)||(j.packageName?T0(j.packageName):!1))e2.push(j),G().recordDegradedReason(j.plugin,j.error);else G().logger.warn("app",`Non-critical plugin ${j.plugin} failed onServerStart; continuing`,{error:j.error})}catch(_){G().logger.warn("app","Error during plugin onServerStart dispatch",{error:String(_)})}try{await V.dispatchServerReady(e,C)}catch(_){G().logger.warn("app","Error during plugin onServerReady dispatch",{error:String(_)})}if(G().clearFinalizeError(),e2.length>0)G().setBootState("degraded"),G().logger.error("app","Agent finalized but degraded \u2014 critical plugins failed",{failures:e2.map((_)=>`${_.plugin}: ${_.error}`)});else G().setBootState("ready"),G().logger.info("app","Agent finalized \u2014 state=ready"),G().audit.emit("agent","gateway-auth.configured",{workspaceId:U.workspaceId,organizationId:U.organizationId,agentRecordId:M?.agentRecordId});return(async()=>{try{if(await V.provisionDefaultPrereqs(e,C,H2.mountPlugin,j2),G().logger.info("app","Default provider prerequisites provisioned"),(H.listProvidersForType("tunnel")??[]).some((k)=>k.pluginName!=="bootstrap")){let{tryHandoverBootstrapTunnel:k}=await import("./tunnel-bootstrap-zdczwezc.js");if(!k())C0();H.unregisterProvider("tunnel","bootstrap"),G().logger.info("app","Bootstrap tunnel handed over to the real tunnel provider")}}catch(_){G().logger.warn("app","Plugin prerequisite provisioning failed",{error:String(_)})}})(),{ok:!0}}catch(U){G().setBootState("awaiting-config");let A=U instanceof Error?U.message:String(U);if(G().recordFinalizeError(A),G().logger.error("app","Finalize failed",{error:A}),process.env.VIBE_STRICT_KEY_FETCH==="1")G().logger.error("app","VIBE_STRICT_KEY_FETCH=1 \u2192 aborting daemon (strict mode)",{error:A}),setTimeout(()=>process.exit(1),50);return{ok:!1,error:A}}finally{I=null}})(),I},_2=A0({origin:(F)=>{let M=F.headers.get("origin");return!!M&&E(M)},credentials:!0,allowedHeaders:K.split(",").map((F)=>F.trim()),methods:B.split(",").map((F)=>F.trim()),exposeHeaders:["content-type","content-length"],maxAge:86400,preflight:!0}),q5=10485760,E0=process.env.VIBECONTROLS_MAX_BODY_BYTES,s2=E0?Number.parseInt(E0,10):NaN,R5=Number.isFinite(s2)&&s2>0?s2:q5,I0={current:null},e=new D({serve:{maxRequestBodySize:R5}}).onRequest(({request:F,set:M})=>{let A=t4(F.headers)??O0();e4({requestId:A,startedAt:new Date().toISOString()});let R=M.headers??={};R["X-Request-Id"]=A}).onRequest(({request:F})=>{try{let M=new URL(F.url).pathname,A=/^\/api\/profiles\/([^/]+)(?:\/|$)/.exec(M)?.[1],R=A?s.get(A):null;M0(R??G())}catch{M0(G())}}).onRequest(({request:F,set:M})=>{let U=new URL(F.url).pathname;if(!U.startsWith("/api/"))return;if(U==="/api/profiles"||U.startsWith("/api/profiles/"))return;if(U==="/api/profile-stats"||U.startsWith("/api/profile-stats/"))return;let A=new URL(F.url);A.pathname=`/api/profiles/default${U.slice(4)}`;try{F.headers.set("x-vc-profile-rewrite","1"),F.headers.set("x-vc-profile-rewrite-target",A.pathname)}catch{}return}).derive(()=>({requestId:Q5()??O0()})).use(_2).use(W5()).use(Y5(()=>N())).use(h0({getDb:()=>c()?.db??x})).onBeforeHandle(({request:F,set:M})=>{let U=G().getBootState();if(U==="ready")return;let A=new URL(F.url).pathname;if(cQ(A))return;return M.status=503,{error:"Agent not yet configured",message:"Agent is in '"+U+"' state. POST credentials to /api/agent/gateway-auth to finalize.",state:U}}).onAfterHandle(({request:F,set:M})=>{let U=new URL(F.url).pathname,A=U==="/health"||U.startsWith("/api/logs/stream")||U.startsWith("/ui/")||U==="/ws/events"||U==="/api/sessions/health-check"||U.startsWith("/terminal/"),R=typeof M.status==="number"?M.status:200,P=A?"debug":R>=400?"warn":"info";G().logger[P]("http",`${F.method} ${U} \u2192 ${R}`,{method:F.method,path:U,statusCode:R});try{f0(F.method,uQ(U),R)}catch{}}).use(z4({serviceRegistry:H,getDb:()=>c()?.db??x,getDbPath:()=>W,getPluginManager:()=>c()?.pluginManager??V})).use(y0()).use(o0({serviceRegistry:H,runFinalize:(F,M)=>i(F,M),getDb:()=>c()?.db??x})).use(G4()).use(B4()).use(v4({getPluginManager:()=>c()?.pluginManager??V})).use(o4()).use(L4()).use(M4({getPluginManager:()=>c()?.pluginManager??V,getTunnelHost:()=>E5()?.url??null})).use(Z4()).use(X4()).use(B5()).use(K5()).use(V5(H)).ws("/code-server/*",gQ(Z)).all("/api/profiles/:name/*",async({params:F,request:M,set:U})=>{let A=M.method!=="GET"&&M.method!=="HEAD",R=A?await M.arrayBuffer():void 0,P=await L5(F.name,M,R);if(P&&P.status!==404)return P;let p=C2(),o=F.name;if(o!==p)return U.status=404,{error:"profile-mismatch",running:p,requested:o,hint:"This daemon serves a different profile. Call GET /api/profiles to discover the right tunnel."};let Q2=new URL(M.url),U2=Q2.pathname.replace(/^\/api\/profiles\/[^/]+/,"/api"),j2=new Headers(M.headers);j2.set("x-vc-profile-rewrite","1");let x2={method:M.method,headers:j2};if(A&&R!==void 0)x2.body=R;let r2=new Request(`${Q2.origin}${U2}${Q2.search}`,x2),w2=I0.current;if(!w2)return new Response(JSON.stringify({error:"agent-not-ready"}),{status:503,headers:{"content-type":"application/json"}});return w2.handle(r2)}).all("/api/*",async({request:F})=>{if(G().getBootState()!=="ready"||!T)return new Response(JSON.stringify({error:"Agent not yet configured",state:G().getBootState(),message:"Plugin routes are unavailable until the agent reaches state=ready. POST credentials to /api/agent/gateway-auth to finalize."}),{status:503,headers:{"content-type":"application/json"}});try{let M=new URL(F.url),U=/^\/api\/plugins\/([a-z0-9-]{1,64})\/ui(?:\/.*)?$/.exec(M.pathname);if(U&&F.method==="GET"){let A=U[1];if(M2(A)){let R=M.pathname.slice(`/api/plugins/${A}/ui`.length),P=R===""||R==="/",o=F.headers.get("sec-fetch-mode")==="navigate";if(P||o){let Q2=J5(F,A);if(!Q2||!Z5(Q2,A))return new Response(x5(A,"/api/profiles/default/agent/ui-exchange-plugin"),{status:200,headers:{"content-type":"text/html; charset=utf-8","Content-Security-Policy":"frame-ancestors 'self' http://localhost:* http://127.0.0.1:* https://localhost:* https://127.0.0.1:* https://*.local.burdenoff.com https://vibecontrols.com https://*.vibecontrols.com https://burdenoff.com https://app.burdenoff.com https://alphaapp.burdenoff.com"}})}}}}catch{}return T.handle(F)}).all("/ui/*",async({request:F})=>{if(G().getBootState()!=="ready"||!O)return new Response("Plugin UI not yet available",{status:503});return O.handle(F)}).all("/code-server/*",async({request:F})=>{if(G().getBootState()!=="ready"||!T)return new Response("code-server not yet available",{status:503});let M=k0(F,V2);return T.handle(M??F)}).all("/plan/*",async({request:F})=>{if(G().getBootState()!=="ready"||!T)return new Response("plan provider not yet available",{status:503});return T.handle(F)});return I0.current=e,{app:e,async start(){e.listen({port:Z,hostname:Q}),G().logger.info("app",`Agent server listening on ${Q}:${Z}`);try{let F=(process.env.VIBECONTROLS_PROFILES??"").split(",").map((P)=>P.trim()).filter(Boolean),M=G().name,{getOrCreateProfile:U}=await import("./daemon-profile-696722nr.js"),{attachSecondaryProfile:A}=await import("./secondary-profile-attach-s5z9dppt.js"),R=process.env.VIBE_STRICT_KEY_FETCH==="1";for(let P of F){if(P===M)continue;try{let p=U(P),o=await A(p);if(o.ok)G().logger.info("app",`Secondary profile '${P}' attached (db+services online)`);else if(R)throw Error(`attachServices for secondary profile '${P}' failed: ${o.error}`);else p.recordDegradedReason("attach",o.error??"unknown"),G().logger.warn("app",`Secondary profile '${P}' is degraded (no creds / attach failed)`,{error:o.error})}catch(p){if(R)throw G().logger.error("app",`--strict-key-fetch: secondary profile '${P}' attach failed; aborting`,{error:String(p)}),setTimeout(()=>process.exit(1),50),p;G().logger.warn("app",`Failed to attach secondary profile '${P}'`,{error:String(p)})}}}catch{}return e},stop:r,finalize:i,getState:()=>G().getBootState(),getLifecycle:()=>c()?.lifecycle??q,getDb:()=>c()?.db??x,getServiceRegistry:()=>c()?.serviceRegistry??H,getPluginManager:()=>c()?.pluginManager??V,getHostServices:()=>c()?.hostServices??C}}var w5=null;function mQ($,Z){if(!$)return null;let Q=$.match(new RegExp(`(?:^|;\\s*)${Z}=([^;]*)`));return Q?Q[1]:null}var a4=z5(H5);function gQ($){let X=(J)=>typeof J==="string"?Buffer.byteLength(J):J.byteLength;return{open(J){let W=J.data,H=m(W.headers??{})??m(W.request?Object.fromEntries(W.request.headers.entries()):{}),B=W.query?.vt,K=!!B&&R2(B,"/code-server","GET"),L,w=l(H);if(!w&&!K){let C=W.headers?.cookie??W.request?.headers.get("cookie")??null,q=mQ(C,"__vibe_cs_session");if(!q||!w5?.(q)){J.close(1008,"Unauthorized");return}L=`session:${q}`}else if(w)L="api-key";else L="vt";let E=J.remoteAddress??null,x=G5(E,W.headers);if(!a4.accept(L,x,J)){G().logger.warn("code-server-ws",`code-server WS cap exceeded (key=${L}, ip=${x??"unknown"})`),J.close(1013,"too many connections");return}W._csCapKey=L,W._csRemoteIp=x;let V=G().name;fetch(`http://127.0.0.1:${$}/api/profiles/${encodeURIComponent(V)}/code-server/status`,{headers:{"x-agent-api-key":V2()}}).then((C)=>C.json()).then((C)=>{if(W._csClosed)return;let q=C;if(!q.running||!q.port){J.close(1011,"code-server not running");return}let v=W.request?.url??"/code-server/",N;try{let I=new URL(v,`http://127.0.0.1:${q.port}`);N=(I.pathname.replace(/^\/code-server\/?/,"/")||"/")+I.search}catch{N="/"}let T=new WebSocket(`ws://127.0.0.1:${q.port}${N}`),O={upstream:T,ready:!1,buffer:[],bufferBytes:0,openTimer:setTimeout(()=>{try{T.close(1011,"upstream open timeout")}catch{}try{J.close(1011,"upstream open timeout")}catch{}},1e4)};W._csBridge=O,T.addEventListener("open",()=>{clearTimeout(O.openTimer),O.ready=!0;for(let I of O.buffer)T.send(I);O.buffer.length=0,O.bufferBytes=0}),T.addEventListener("message",(I)=>{try{let h=I.data;if(h instanceof ArrayBuffer)J.send(new Uint8Array(h));else if(h instanceof Blob)h.arrayBuffer().then((y)=>{try{J.send(new Uint8Array(y))}catch{}});else J.send(h)}catch{}}),T.addEventListener("close",(I)=>{clearTimeout(O.openTimer);try{J.close(I.code||1000,I.reason||"upstream closed")}catch{}}),T.addEventListener("error",()=>{clearTimeout(O.openTimer);try{J.close(1011,"upstream error")}catch{}})}).catch(()=>{J.close(1011,"Failed to query code-server status")})},message(J,W){let H=J.data?._csBridge;if(!H)return;let B;if(typeof W==="string")B=W;else if(W instanceof ArrayBuffer)B=W;else if(W instanceof Uint8Array||Buffer.isBuffer(W)){let K=new ArrayBuffer(W.byteLength);new Uint8Array(K).set(new Uint8Array(W.buffer,W.byteOffset,W.byteLength)),B=K}else if(typeof W==="object"&&W!==null)B=JSON.stringify(W);else B=String(W);if(H.upstream&&H.ready&&H.upstream.readyState===WebSocket.OPEN)try{H.upstream.send(B)}catch{}else{let K=X(B);if(H.buffer.length>=256||H.bufferBytes+K>1048576){try{H.upstream.close(1013,"buffer limit exceeded")}catch{}try{J.close(1013,"buffer limit exceeded")}catch{}return}H.buffer.push(B),H.bufferBytes+=K}},close(J){J.data._csClosed=!0;let W=J.data?._csBridge;if(W?.openTimer)clearTimeout(W.openTimer);if(W?.upstream&&W.upstream.readyState===WebSocket.OPEN)W.upstream.close(1000,"client disconnected");let H=J.data._csCapKey,B=J.data._csRemoteIp;if(H)a4.release(H,B??null,J)}}}async function s4(){try{let{readFileSync:$}=await import("fs"),{join:Z,dirname:Q}=await import("path"),{fileURLToPath:Y}=await import("url"),X=Q(Y(import.meta.url));return JSON.parse($(Z(X,"..","package.json"),"utf8")).version||"1.0.0"}catch{return"1.0.0"}}
|
|
25
|
+
}`,P4="VIBE_BOOTSTRAP_JSON=";function qQ($){for(let Y of $.split(/\r?\n/)){let X=Y.indexOf(P4);if(X>=0)try{return JSON.parse(Y.slice(X+P4.length))}catch{}}let Z=$.indexOf("{"),Q=$.lastIndexOf("}");if(Z>=0&&Q>Z)try{return JSON.parse($.slice(Z,Q+1))}catch{return null}return null}async function c4($,Z){let Q=(L,w,E)=>Z?.({step:L,status:w,message:E}),Y=b4($.permissions??["tunnel:read","session:list","plugin:list","diagnostics:read","mesh:forward"]);if(!Y.includes("mesh:forward"))Y.push("mesh:forward");let X=(L)=>({ok:!1,peerId:"",agentRecordId:null,tunnelUrl:null,permissions:Y,error:L}),J;try{J=o2($.target,{identityFile:$.identityFile})}catch(L){return X(L instanceof Error?L.message:String(L))}let W=$.label??J.id,H=Y.join(","),B,K='export PATH="$HOME/.bun/bin:$PATH"; ';try{if(!$.connectExisting){Q("probe","running");let O=await J.probe();if(Q("probe","completed",`os=${O.os??"?"} arch=${O.arch??"?"}`),!O.bun){if($.installBun===!1)return X("Bun is required to run the agent but is not installed, and Bun auto-install was disabled.");Q("install-bun","running");let i=await J.run(["sh","-c",`curl -fsSL https://bun.sh/install | bash && echo 'export PATH="$HOME/.bun/bin:$PATH"' >> ~/.bashrc`],{timeoutMs:300000});if(i.code!==0)return Q("install-bun","failed",i.stderr.slice(0,400)),X("Bun auto-install failed.");let _2=await J.run(["sh","-c","$HOME/.bun/bin/bun --version 2>/dev/null"],{timeoutMs:1e4});if(_2.code===0&&_2.stdout.trim())O.bun="$HOME/.bun/bin/bun",Q("install-bun","completed",_2.stdout.trim());else return X("Bun installed but the binary is not reachable.")}Q("install-agent","running");let I=$.version??"latest",h=$.registry??"https://registry.npmjs.org/";if(!/^[A-Za-z0-9._@/^~>=<-]+$/.test(I))return Q("install-agent","failed","invalid version"),X(`Invalid agent version: ${I}`);if(!/^https?:\/\/[A-Za-z0-9._~:/?#@!$&'()*+,;=%-]+$/.test(h))return Q("install-agent","failed","invalid registry"),X(`Invalid registry URL: ${h}`);let y=await J.run(["sh","-c",`${K}npm_config_registry="${h}" bun install -g @vibecontrols/agent@${I} --no-cache`],{timeoutMs:600000});if(y.code!==0)return Q("install-agent","failed",y.stderr.slice(0,400)),X(`Agent install failed (exit ${y.code}).`);if(B=(await J.run(["sh","-c",`${K}vibe --version`],{timeoutMs:15000})).stdout.trim()||void 0,Q("install-agent","completed",B),$.autostart)Q("autostart","running"),await J.run(["sh","-c",`${K}vibe autostart install`],{timeoutMs:60000}),Q("autostart","completed");if($.installPlugins?.length){Q("plugins","running");for(let i of $.installPlugins)await J.run(["sh","-c",`${K}vibe plugin install ${i}`],{timeoutMs:300000});Q("plugins","completed")}Q("start","running"),await J.run(["sh","-c",`${K}vibe start`],{timeoutMs:60000}),Q("start","completed")}Q("bootstrap","running");let L=$.expiresIn?` --expires-in ${$.expiresIn}`:"",w=W.replace(/'/g,""),E=null;for(let O=0;O<15;O++){let I=`${K}vibe peer-bootstrap --json --emit-default-key --label '${w}' --scope ${H}${L} 2>/dev/null`,h=await J.run(["sh","-c",I],{timeoutMs:15000});if(h.code===0){let y=qQ(h.stdout);if(y&&typeof y.apiKey==="string"){E=y;break}}await new Promise((y)=>setTimeout(y,2000))}if(!E)return Q("bootstrap","failed","could not obtain peer-bootstrap bundle"),X("Remote peer-bootstrap did not return a credential bundle.");Q("bootstrap","completed");let x=n(),V=String(E.id),C=String(E.apiKey),q=i2(typeof E.tunnelUrl==="string"?E.tunnelUrl:null),v=typeof E.agentRecordId==="string"?E.agentRecordId:null;if($.onboardBackend!==!1&&g.isConfigured()&&q&&typeof E.fullDefaultApiKey==="string"){Q("onboard","running");let O=5,I="no agent returned";for(let h=0;h<O;h++){try{let i=(await g.workspaceQuery(IQ,{input:{tunnelUrl:q,apiKey:E.fullDefaultApiKey,name:W}})).data?.addVibecontrolsAgentFromTunnel;if(i?.agent?.id){v=i.agent.id,I="",Q("onboard","completed",`agent ${v}`);break}I=i?.error??"no agent returned"}catch(r){I=r instanceof Error?r.message:String(r)}if(!/unreachable|resolve hostname|timed out|timeout|ECONN|network|to fetch|50[234]/i.test(I)||h===O-1)break;Q("onboard","running",`retry ${h+1}/${O-1}: ${I.slice(0,80)}`),await new Promise((r)=>setTimeout(r,3000*(h+1)))}if(I)Q("onboard","failed",I)}else Q("onboard","skipped");Q("store-creds","running"),f4({id:V,label:W,tunnelUrl:q??"",apiKey:C,permissions:Y,addedAt:new Date().toISOString(),agentRecordId:v??void 0,workspaceId:(typeof E.workspaceId==="string"?E.workspaceId:x.workspaceId)??void 0,fingerprint:V,ownerUserId:x.ownerUserId,sshTarget:J.mode==="ssh"?$.target:void 0,sshIdentityFile:$.identityFile}),Q("store-creds","completed");let N=g2();if($.onboardBackend!==!1&&g.isConfigured()&&N&&v){Q("report-link","running");try{await g.workspaceQuery(wQ,{input:{sourceAgentRecordId:N,destinationAgentRecordId:v,label:W}}),Q("report-link","completed")}catch(O){Q("report-link","failed",O instanceof Error?O.message:String(O))}}else Q("report-link","skipped");let T=await I2(V,"/api/profiles/default/agent/identity",{operation:"post-deploy-probe"});return Q("probe-peer",T.ok?"completed":"failed",T.error??void 0),{ok:!0,peerId:V,agentRecordId:v,tunnelUrl:q,permissions:Y,remoteVersion:B}}catch(L){return X(L instanceof Error?L.message:String(L))}finally{await J.close().catch(()=>{})}}var U0='export PATH="$HOME/.bun/bin:$PATH"; ';function RQ($){let Z=$.indexOf("{"),Q=$.lastIndexOf("}");if(Z>=0&&Q>Z)try{let Y=JSON.parse($.slice(Z,Q+1));if(Y.tunnelUrl)return Y.tunnelUrl;if(Y.url&&Y.url.startsWith("https"))return Y.url}catch{}return null}async function m4($,Z){let Q=(J,W,H)=>Z?.({step:J,status:W,message:H}),Y=y4($);if(!Y)return{ok:!1,peerId:$,tunnelUrl:null,error:`No peer with id ${$}`};if(!Y.sshTarget)return{ok:!1,peerId:$,tunnelUrl:null,error:"No SSH target stored for this peer \u2014 it wasn't SSH-deployed, so it can't be woken via SSH."};let X;try{X=o2(Y.sshTarget,{identityFile:Y.sshIdentityFile})}catch(J){return{ok:!1,peerId:$,tunnelUrl:null,error:J instanceof Error?J.message:String(J)}}try{Q("ssh-restart","running",Y.sshTarget);let J=await X.run(["sh","-c",`${U0}vibe restart 2>/dev/null || ${U0}vibe start`],{timeoutMs:90000});if(J.code!==0)return Q("ssh-restart","failed",J.stderr.slice(0,300)),{ok:!1,peerId:$,tunnelUrl:null,error:`Remote restart failed (exit ${J.code})`};Q("ssh-restart","completed"),Q("await-tunnel","running");let W=null;for(let H=0;H<15;H++){let B=await X.run(["sh","-c",`${U0}vibe url --json 2>/dev/null`],{timeoutMs:15000});if(B.code===0){let K=RQ(B.stdout),L=i2(K);if(L){W=L;break}}await new Promise((K)=>setTimeout(K,2000))}if(!W)return Q("await-tunnel","failed","no fresh tunnel after restart"),{ok:!1,peerId:$,tunnelUrl:null,error:"Agent restarted but no fresh tunnel came up."};return Q("await-tunnel","completed",W),u4($,{tunnelUrl:W,lastReachable:new Date().toISOString()}),Q("update","completed"),{ok:!0,peerId:$,tunnelUrl:W}}catch(J){return{ok:!1,peerId:$,tunnelUrl:null,error:J instanceof Error?J.message:String(J)}}finally{await X.close().catch(()=>{})}}var DQ=Number(process.env.VIBECONTROLS_MESH_MAX_HOPS||"8");function g4(){return(c()??G()).name}function hQ(){return(c()??G()).dataDir}function p4(){try{let Z=SQ(hQ(),"runtime.json");if(AQ(Z)){let Q=JSON.parse(kQ(Z,"utf8"));if(Q.port&&Number.isInteger(Q.port))return Q.port}}catch{}let $=Number(process.env.PORT);return Number.isInteger($)&&$>0?$:3005}function vQ($){let Z={};return $.headers.forEach((Q,Y)=>{Z[Y]=Q}),Z}function X2($,Z){let Q=m(vQ($));return n4(d4(Q),Z)}function PQ($){let{apiKey:Z,...Q}=$;return{...Q,apiKey:"[REDACTED]"}}function l4($){return typeof $==="string"&&$.startsWith("/api/")&&!$.includes("..")&&!$.includes("//")}var a2=new Map;function fQ(){let $=Date.now()-3600000;for(let[Z,Q]of a2)if(Q.completedAt&&Date.parse(Q.completedAt)<$)a2.delete(Z)}function o4(){return new D({name:"agent-mesh"}).get("/api/mesh/peers",({request:$,set:Z})=>{if(!X2($,["read"]))return Z.status=403,{error:"forbidden"};return{peers:L2(n()).map(PQ)}}).delete("/api/mesh/peers/:id",({request:$,set:Z,params:Q})=>{if(!X2($,["mutate"]))return Z.status=403,{error:"forbidden"};if(!L2(n()).some((X)=>X.id===Q.id))return Z.status=404,{error:"not found"};return{ok:i4(Q.id)}}).post("/api/mesh/peers/:id/call",async({request:$,set:Z,params:Q,body:Y})=>{if(!X2($,["mesh:forward"]))return Z.status=403,{error:"forbidden"};let X=Y;if(!l4(X.path))return Z.status=400,{error:"invalid path"};if(!L2(n()).find((H)=>H.id===Q.id))return Z.status=404,{error:"not found"};let W=await I2(Q.id,X.path,{method:X.method??"GET",body:X.body,operation:"mesh-call"});return{ok:W.ok,status:W.status,data:W.data,rotated:W.rotated,error:W.error}},{body:z.Object({method:z.Optional(z.String()),path:z.String(),body:z.Optional(z.Any())})}).post("/api/mesh/forward",async({request:$,set:Z,body:Q})=>{if(!X2($,["mesh:forward"]))return Z.status=403,{error:"forbidden"};let Y=Q;if(!Y.request||!l4(Y.request.path))return Z.status=400,{error:"invalid request"};let X=(Y._hopCount??0)+1;if(X>DQ)return Z.status=422,{error:"hop limit exceeded"};let J=n(),W=g2(),H=Y.hops??[];if(H.length===0){G().audit.emit("mesh","forward.terminal",{path:Y.request.path,method:Y.request.method??"GET"});let x=(Y.request.method??"GET").toUpperCase();try{let V=await fetch(`http://127.0.0.1:${p4()}${Y.request.path}`,{method:x,headers:{"x-agent-api-key":await j0(),...Y.request.body!==void 0?{"content-type":"application/json"}:{}},body:Y.request.body!==void 0?JSON.stringify(Y.request.body):void 0,signal:AbortSignal.timeout(60000)}),C=await V.text().catch(()=>""),q=null;try{q=C?JSON.parse(C):null}catch{q=null}return{ok:V.ok,status:V.status,data:q,text:C||null,error:V.ok?null:C||`status ${V.status}`}}catch(V){return Z.status=502,{ok:!1,status:0,error:V instanceof Error?V.message:String(V)}}}let B=H[0],K=Y._traversed??[];if(B===W||K.includes(B))return Z.status=422,{error:"cycle detected",at:B};let L=x0(B,J);if(!L)return Z.status=403,{error:"next hop not in authorized boundary"};if(!L.permissions.includes("mesh:forward"))return Z.status=403,{error:"peer lacks mesh:forward grant"};G().audit.emit("mesh","forward.hop",{nextId:B,remaining:H.length,hopCount:X});let w=encodeURIComponent(g4()),E=await I2(L.id,`/api/profiles/${w}/mesh/forward`,{method:"POST",operation:"mesh-forward",timeoutMs:60000,body:{hops:H.slice(1),request:Y.request,_traversed:[...K,W??"self"],_hopCount:X}});if(!E.ok)return Z.status=502,{ok:!1,status:E.status,error:E.error,failedAtHop:B};return E.data},{body:z.Object({hops:z.Optional(z.Array(z.String())),request:z.Object({method:z.Optional(z.String()),path:z.String(),body:z.Optional(z.Any())}),_traversed:z.Optional(z.Array(z.String())),_hopCount:z.Optional(z.Number())})}).post("/api/mesh/deploy",({request:$,set:Z,body:Q})=>{if(!X2($,["admin"]))return Z.status=403,{error:"forbidden"};fQ();let Y=Q,X=n(),J=crypto.randomUUID(),W={id:J,status:"running",steps:[],ownerUserId:X.ownerUserId,workspaceId:X.workspaceId,startedAt:new Date().toISOString()};return a2.set(J,W),c4({target:Y.target,permissions:Y.permissions,installPlugins:Y.installPlugins,autostart:Y.autostart,identityFile:Y.identityFile,label:Y.label,version:Y.version,connectExisting:Y.connectExisting},(H)=>{W.steps.push(H),Y2("mesh:deploy:progress",{jobId:J,step:H})}).then((H)=>{if(W.result=H,W.status=H.ok?"completed":"failed",!H.ok)W.error=H.error;W.completedAt=new Date().toISOString(),Y2(H.ok?"mesh:deploy:complete":"mesh:deploy:failed",{jobId:J,result:H})}).catch((H)=>{W.status="failed",W.error=H instanceof Error?H.message:String(H),W.completedAt=new Date().toISOString(),Y2("mesh:deploy:failed",{jobId:J,error:W.error})}),Z.status=202,{jobId:J,status:"running"}},{body:z.Object({target:z.String(),permissions:z.Optional(z.Array(z.String())),installPlugins:z.Optional(z.Array(z.String())),autostart:z.Optional(z.Boolean()),identityFile:z.Optional(z.String()),label:z.Optional(z.String()),version:z.Optional(z.String()),connectExisting:z.Optional(z.Boolean())})}).get("/api/mesh/deploy/jobs/:id",({request:$,set:Z,params:Q})=>{if(!X2($,["read"]))return Z.status=403,{error:"forbidden"};let Y=a2.get(Q.id),X=n();if(!Y||X.ownerUserId&&Y.ownerUserId&&Y.ownerUserId!==X.ownerUserId)return Z.status=404,{error:"not found"};return Y}).post("/api/mesh/wake",async({request:$,set:Z,body:Q})=>{if(!X2($,["admin"]))return Z.status=403,{error:"forbidden"};let Y=Q,X=x0(Y.targetAgentRecordId,n());if(!X)return Z.status=404,{ok:!1,error:"peer not in authorized boundary"};G().audit.emit("mesh","wake.start",{peerId:X.id,agentRecordId:Y.targetAgentRecordId});let J=await m4(X.id,(W)=>Y2("mesh:wake:progress",{peerId:X.id,step:W}));if(!J.ok)Z.status=502;return J},{body:z.Object({targetAgentRecordId:z.String()})}).post("/api/mesh/session",async({request:$,set:Z,body:Q})=>{if(!X2($,["mesh:forward","mutate"]))return Z.status=403,{error:"forbidden"};let Y=Q,X=Y.sessionId&&/^[A-Za-z0-9_-]{1,128}$/.test(Y.sessionId)?Y.sessionId:crypto.randomUUID(),J=encodeURIComponent(g4()),W=await j0(),H=`http://127.0.0.1:${p4()}`,B=Y.command||"bash";try{let K=await fetch(`${H}/api/profiles/${J}/sessions/create`,{method:"POST",headers:{"x-agent-api-key":W,"content-type":"application/json"},body:JSON.stringify({sessionId:X,sessionName:`vc-mesh-${X.slice(0,8)}`,command:B,provider:"TERMINAL",...Y.vibeId?{projectId:Y.vibeId}:{}}),signal:AbortSignal.timeout(20000)});if(!K.ok)return Z.status=502,{error:`session create returned ${K.status}: ${await K.text().catch(()=>"")}`};let L=await fetch(`${H}/api/profiles/${J}/sessions/${encodeURIComponent(X)}/terminal`,{method:"POST",headers:{"x-agent-api-key":W},signal:AbortSignal.timeout(20000)});if(!L.ok)return Z.status=502,{error:`terminal start returned ${L.status}: ${await L.text().catch(()=>"")}`};let w=v2(`/terminal/${X}`,600);return G().audit.emit("mesh","session.created",{sessionId:X,kind:Y.kind??"TERMINAL"}),{connectionId:X,sessionId:X,capabilityToken:w.token,expiresAt:w.expiresAt}}catch(K){return Z.status=502,{error:K instanceof Error?K.message:String(K)}}},{body:z.Object({sessionId:z.Optional(z.String()),kind:z.Optional(z.String()),cwd:z.Optional(z.String()),vibeId:z.Optional(z.String()),command:z.Optional(z.String())})})}var bQ=["/health","/api/agent/status","/api/agent/version","/api/agent/identity","/api/agent/api-key","/api/agent/tunnel","/api/agent/system","/api/agent/gateway-auth","/api/stats","/metrics","/api/profiles","/api/profile-stats"];function cQ($){return bQ.some((Z)=>$.startsWith(Z))}var yQ=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function uQ($){return $.split("/").map((Z)=>{if(!Z)return Z;if(/^\d+$/.test(Z))return":id";if(yQ.test(Z))return":id";if(Z.length>=24&&/^[A-Za-z0-9_-]+$/.test(Z))return":id";return Z}).join("/")}async function a8($){let{port:Z,host:Q,dbPath:Y,logLevel:X,corsOrigin:J}=$,W=Y??T2();try{(await import("fs")).mkdirSync(W,{recursive:!0})}catch(F){throw G().logger.error("app","Failed to create dbPath dir at boot",{dbPath:W,error:String(F)}),Error(`Cannot create dbPath ${W}: ${F instanceof Error?F.message:String(F)}`,{cause:F})}if(X)G().logger.setLevel(X);(async()=>{let{logShipper:F}=await import("./log-shipper-hjnn1d5p.js");F.init()})(),(async()=>{let F=await s4();await S2({version:F,profile:C2()})})();try{let{checkDependencies:F}=await import("./bootstrap.service-vg72w8pa.js"),M=F(),U=M.filter((R)=>R.required&&!R.installed),A=M.filter((R)=>!R.required&&!R.installed);if(U.length>0)G().logger.error("app",`Missing required system deps: ${U.map((R)=>R.name).join(", ")}. Run \`vibe setup\` to install.`);if(A.length>0)G().logger.warn("app",`Missing optional system deps: ${A.map((R)=>R.name).join(", ")}. Some plugins may fail their prereqs check.`)}catch(F){G().logger.warn("app","Boot-time dependency check failed",{error:String(F)})}try{G().audit.runRetention()}catch(F){G().logger.warn("app","Audit-log retention sweep failed",{error:String(F)})}let H=new N5;I5(H,{port:Z});let B="GET, POST, PUT, PATCH, DELETE, OPTIONS",K="Content-Type, x-agent-api-key, Authorization, x-requested-with",L=Array.isArray(J)?J:(J??"").split(",").map((F)=>F.trim()).filter(Boolean),w=new Set(["https://vibecontrols.com","https://app.vibecontrols.com","https://alphaapp.vibecontrols.com","https://burdenoff.com","https://app.burdenoff.com","https://alphaapp.burdenoff.com"]),E=(F)=>{try{let M=new URL(F);if(L.includes(F))return!0;if(L.includes("*"))return!1;return M.hostname==="localhost"||M.hostname==="127.0.0.1"||M.hostname==="0.0.0.0"||M.hostname.endsWith(".local.burdenoff.com")||w.has(M.origin)}catch{return!1}},x=null,V=null,C=null,q=null,v=!1,N=()=>[],T=null,O=null,I=null,h=5000,y=async(F,M)=>{let U=Date.now();try{await Promise.race([Promise.resolve(M()),new Promise((A,R)=>setTimeout(()=>R(Error(`shutdown phase ${F} exceeded ${h}ms`)),h))]),G().logger.info("app",`shutdown.phase ${F} complete`,{ms:Date.now()-U})}catch(A){G().logger.warn("app",`shutdown.phase ${F} failed`,{error:String(A),ms:Date.now()-U})}},r=async(F)=>{if(v)return;if(v=!0,G().logger.info("app","Agent shutdown starting",{reason:F?.reason??"shutdown"}),await y("plugins",async()=>{if(V)await V.dispatchServerStop(F)}),await y("bootstrap-tunnel",()=>C0()),await y("tracked-subprocesses",async()=>{let{killAllTracked:M}=await import("./subprocess-q2ky0ptw.js");await M()}),F?.reason!=="reload")await y("db-close",async()=>{if(x)await x.close()});await y("http-listener",async()=>{try{await Promise.resolve(e.stop())}catch(M){G().logger.warn("app","Listener stop threw (already stopped or never started?)",{error:String(M)})}}),G().logger.info("app","Agent server stopped"),G().logger.close()},i=async(F,M)=>{if(G().getBootState()==="ready")return{ok:!0};if(I)return I;return I=(async()=>{G().setBootState("initializing");try{let U={...F,globalGatewayUrl:B2(F.globalGatewayUrl,"globalGatewayUrl"),workspaceGatewayUrl:B2(F.workspaceGatewayUrl,"workspaceGatewayUrl")},A=await U5(U),R=W,P=t({dir:G().dataDir}),p=P.storageAdapter??process.env.VIBE_STORAGE_ADAPTER??void 0,o=P.storageOptions,Q2=(_)=>{let j=(_ instanceof Error?_.message:String(_)).toLowerCase(),k=_&&typeof _==="object"&&"code"in _?String(_.code).toUpperCase():"";if(k==="EBUSY"||k==="EPERM"||k==="EACCES"||k==="EAGAIN"||k==="EMFILE"||k==="ENFILE"||k==="ETIMEDOUT"||k==="ECONNRESET"||k==="ECONNREFUSED"||j.includes("encryption key")||j.includes("fetch")&&j.includes("key")||j.includes("temporarily unavailable")||j.includes("resource busy"))return"transient";if(j.includes("auth tag")||j.includes("authentication tag")||j.includes("unable to authenticate data")||j.includes("bad decrypt")||j.includes("unsupported state")||j.includes("incorrect header check")||j.includes("invalid distance")||j.includes("incorrect data check")||j.includes("unexpected end of")||j.includes("unexpected token")||j.includes("json")&&(j.includes("parse")||j.includes("invalid"))||j.includes("truncated")||j.includes("malformed")||j.includes("corrupt"))return"corruption";return"unknown"},U2=()=>r4({dbPath:R,encryptionKey:A,adapterName:p,adapterOptions:o});try{x=await U2()}catch(_){let j=_,k=Q2(_),q2=[500,2000,8000];if(k==="transient"||k==="unknown"){G().logger.warn("app",`Storage open failed (${k}); will retry up to ${q2.length} times before quarantine`,{error:_ instanceof Error?_.message:String(_),path:R});for(let O2 of q2){await new Promise((f)=>setTimeout(f,O2));try{x=await U2(),j=null;break}catch(f){if(j=f,k=Q2(f),G().logger.warn("app",`Storage open retry failed (${k}) after ${O2}ms`,{error:f instanceof Error?f.message:String(f)}),k==="corruption")break}}}if(!x&&j){if(k!=="corruption"){let f=j instanceof Error?j.message:String(j);G().logger.error("app",`Storage open failed after retries with non-corruption error (${k}); refusing to quarantine valid data`,{error:f,path:R}),G().recordDegradedReason("storage",f);try{throw j}catch(G2){throw Error(`Storage open failed (${k}); agent is degraded: ${f}`,{cause:G2})}}let O2=j instanceof Error?j.message:String(j);G().logger.error("app","QUARANTINE: Storage file is corrupt \u2014 renaming and creating fresh DB",{errorClass:"corruption",error:O2,path:R});try{let f=await import("fs");if(f.existsSync(R)){let G2=new Date().toISOString().replace(/[:.]/g,"-"),q0=`${R}.broken-${G2}`;f.renameSync(R,q0),G().logger.warn("app",`Quarantined corrupt storage to ${q0} \u2014 fresh DB will be created`,{originalError:O2})}x=await U2()}catch(f){let G2=f instanceof Error?f.message:String(f);throw G().recordDegradedReason("storage",G2),Error(`Storage open failed twice (quarantine path); agent is degraded: ${G2}`,{cause:f})}}}if(!x)throw Error("Internal error: storage open recovery exited without an open database and without throwing");if(await h2({clientId:U.clientId,clientSecret:U.clientSecret,workspaceId:U.workspaceId,organizationId:U.organizationId,globalGatewayUrl:U.globalGatewayUrl,workspaceGatewayUrl:U.workspaceGatewayUrl,agentRecordId:M?.agentRecordId,scopes:M?.scopes},{dir:G().dataDir,scope:G().name}),await x.setConfig("gateway-auth:clientId",U.clientId),await x.setConfig("gateway-auth:clientSecret",U.clientSecret),await x.setConfig("gateway-auth:globalGatewayUrl",U.globalGatewayUrl),await x.setConfig("gateway-auth:workspaceGatewayUrl",U.workspaceGatewayUrl),await x.setConfig("gateway-auth:workspaceId",U.workspaceId),U.organizationId)await x.setConfig("gateway-auth:organizationId",U.organizationId);if(M?.agentRecordId)await x.setConfig("gateway-auth:agentRecordId",M.agentRecordId);H.db=x,await H.hydrateDefaultsFromDb(),V=new T5(x),await V.loadCorePlugins();try{await V.loadAll()}catch(_){G().logger.warn("app","Failed to load some external plugins",{error:String(_)})}let j2=C5(F2())??void 0,x2=process.env.VIBE_SKIP_AUTO_INSTALL==="1"||await x.getConfig("plugins:auto-install-disabled");if(x2!=="true"&&x2!==!0)try{let _=await V.ensureDefaultPlugins((j)=>G().logger.info("app",`[auto-install] ${j}`),[],j2);if(_.length>0)G().logger.info("app",`Auto-installed ${_.length} default plugin(s): ${_.map((j)=>j.packageName).join(", ")}`)}catch(_){G().logger.warn("app","Failed to auto-install default plugins",{error:String(_)})}G().logger.info("app",`Plugins loaded: ${V.getPluginDetails().length} total (${V.getPluginDetails().filter((_)=>_.isCore).length} core)`);try{let _=V.getPluginDetails(),j={loaded:_.filter((k)=>k.loaded).length,failed:_.filter((k)=>!k.loaded).length};b0(j)}catch{}let r2={async get(_,j){return await x.getPluginState(_,j)??null},async set(_,j,k){await x.setPluginState(_,j,k)},async delete(_,j){return x.deletePluginState(_,j)},async list(_){return await x.getAllPluginState(_)},async deleteAll(_){return x.deleteAllPluginState(_)}},w2=await s4();C={storage:r2,logger:G().logger,serviceRegistry:H,getProvider:(_)=>H.getProvider(_),getAgentBaseUrl:()=>process.env.AGENT_URL||`http://localhost:${Z}`,getAgentVersion:()=>w2,validateApiKey:(_)=>l(_),setCodeServerSessionValidator:(_)=>{w5=_},broadcast:Y2,workspaceQuery:async(_,j)=>g.workspaceQuery(_,j),isGatewayConfigured:()=>g.isConfigured(),getAgentRecordId:async()=>await x.getConfig("gateway-auth:agentRecordId")??null,getWorkspaceId:async()=>await x.getConfig("gateway-auth:workspaceId")??null,getConfig:async(_)=>await x.getConfig(_)??void 0,getPluginRegistry:()=>n2(),getDataDir:()=>D2(),cliContributors:new _5,audit:{emit:(_,j)=>G().audit.emit("agent",_,j??{})},telemetry:{emit:(_,j)=>{import("./telemetry-jxfgrm61.js").then(({telemetryService:k})=>k.emit(_,j??{})).catch(()=>{})}},os:N2(),iframeBridge:M5()},g.configure({globalGatewayUrl:U.globalGatewayUrl,workspaceGatewayUrl:U.workspaceGatewayUrl,clientId:U.clientId,clientSecret:U.clientSecret,workspaceId:U.workspaceId,organizationId:U.organizationId});let H2={db:x,serviceRegistry:H,pluginManager:V,broadcast:Y2,hostServices:C};H2.app=e;let w0=!1,t2=()=>{let{routes:_,getPublicPaths:j,mountPlugin:k}=$5(V,H2);if(H2.mountPlugin=k,N=j,X5(),T=_,O=O5(V),V&&w0&&C)V.dispatchServerStart(T,C).catch((q2)=>G().logger.warn("app","Re-dispatch of onServerStart after plugin reload failed",{error:String(q2)}));w0=!0};H2.rebuildPluginSurfaces=t2,t2(),q=new j5(H,V,x,e,C,r),H.registerService("agent","lifecycle",q),G().attachServices({db:x,serviceRegistry:H,pluginManager:V,lifecycle:q,hostServices:C}),F5(G(),{rebuildPluginSurfaces:t2,mountPlugin:H2.mountPlugin,app:T});try{await G().keyVault.bindApiKey(V2())}catch(_){G().logger.warn("app","Failed to bind api key into daemon keyVault",{error:String(_)})}let e2=[];try{let{failures:_}=await V.dispatchServerStart(T,C);for(let j of _)if(T0(j.plugin)||(j.packageName?T0(j.packageName):!1))e2.push(j),G().recordDegradedReason(j.plugin,j.error);else G().logger.warn("app",`Non-critical plugin ${j.plugin} failed onServerStart; continuing`,{error:j.error})}catch(_){G().logger.warn("app","Error during plugin onServerStart dispatch",{error:String(_)})}try{await V.dispatchServerReady(e,C)}catch(_){G().logger.warn("app","Error during plugin onServerReady dispatch",{error:String(_)})}if(G().clearFinalizeError(),e2.length>0)G().setBootState("degraded"),G().logger.error("app","Agent finalized but degraded \u2014 critical plugins failed",{failures:e2.map((_)=>`${_.plugin}: ${_.error}`)});else G().setBootState("ready"),G().logger.info("app","Agent finalized \u2014 state=ready"),G().audit.emit("agent","gateway-auth.configured",{workspaceId:U.workspaceId,organizationId:U.organizationId,agentRecordId:M?.agentRecordId});return(async()=>{try{if(await V.provisionDefaultPrereqs(e,C,H2.mountPlugin,j2),G().logger.info("app","Default provider prerequisites provisioned"),(H.listProvidersForType("tunnel")??[]).some((k)=>k.pluginName!=="bootstrap")){let{tryHandoverBootstrapTunnel:k}=await import("./tunnel-bootstrap-zdczwezc.js");if(!k())C0();H.unregisterProvider("tunnel","bootstrap"),G().logger.info("app","Bootstrap tunnel handed over to the real tunnel provider")}}catch(_){G().logger.warn("app","Plugin prerequisite provisioning failed",{error:String(_)})}})(),{ok:!0}}catch(U){G().setBootState("awaiting-config");let A=U instanceof Error?U.message:String(U);if(G().recordFinalizeError(A),G().logger.error("app","Finalize failed",{error:A}),process.env.VIBE_STRICT_KEY_FETCH==="1")G().logger.error("app","VIBE_STRICT_KEY_FETCH=1 \u2192 aborting daemon (strict mode)",{error:A}),setTimeout(()=>process.exit(1),50);return{ok:!1,error:A}}finally{I=null}})(),I},_2=A0({origin:(F)=>{let M=F.headers.get("origin");return!!M&&E(M)},credentials:!0,allowedHeaders:K.split(",").map((F)=>F.trim()),methods:B.split(",").map((F)=>F.trim()),exposeHeaders:["content-type","content-length"],maxAge:86400,preflight:!0}),q5=10485760,E0=process.env.VIBECONTROLS_MAX_BODY_BYTES,s2=E0?Number.parseInt(E0,10):NaN,R5=Number.isFinite(s2)&&s2>0?s2:q5,I0={current:null},e=new D({serve:{maxRequestBodySize:R5}}).onRequest(({request:F,set:M})=>{let A=t4(F.headers)??O0();e4({requestId:A,startedAt:new Date().toISOString()});let R=M.headers??={};R["X-Request-Id"]=A}).onRequest(({request:F})=>{try{let M=new URL(F.url).pathname,A=/^\/api\/profiles\/([^/]+)(?:\/|$)/.exec(M)?.[1],R=A?s.get(A):null;M0(R??G())}catch{M0(G())}}).onRequest(({request:F,set:M})=>{let U=new URL(F.url).pathname;if(!U.startsWith("/api/"))return;if(U==="/api/profiles"||U.startsWith("/api/profiles/"))return;if(U==="/api/profile-stats"||U.startsWith("/api/profile-stats/"))return;let A=new URL(F.url);A.pathname=`/api/profiles/default${U.slice(4)}`;try{F.headers.set("x-vc-profile-rewrite","1"),F.headers.set("x-vc-profile-rewrite-target",A.pathname)}catch{}return}).derive(()=>({requestId:Q5()??O0()})).use(_2).use(W5()).use(Y5(()=>N())).use(h0({getDb:()=>c()?.db??x})).onBeforeHandle(({request:F,set:M})=>{let U=G().getBootState();if(U==="ready")return;let A=new URL(F.url).pathname;if(cQ(A))return;return M.status=503,{error:"Agent not yet configured",message:"Agent is in '"+U+"' state. POST credentials to /api/agent/gateway-auth to finalize.",state:U}}).onAfterHandle(({request:F,set:M})=>{let U=new URL(F.url).pathname,A=U==="/health"||U.startsWith("/api/logs/stream")||U.startsWith("/ui/")||U==="/ws/events"||U==="/api/sessions/health-check"||U.startsWith("/terminal/"),R=typeof M.status==="number"?M.status:200,P=A?"debug":R>=400?"warn":"info";G().logger[P]("http",`${F.method} ${U} \u2192 ${R}`,{method:F.method,path:U,statusCode:R});try{f0(F.method,uQ(U),R)}catch{}}).use(z4({serviceRegistry:H,getDb:()=>c()?.db??x,getDbPath:()=>W,getPluginManager:()=>c()?.pluginManager??V})).use(y0()).use(o0({serviceRegistry:H,runFinalize:(F,M)=>i(F,M),getDb:()=>c()?.db??x})).use(G4()).use(B4()).use(v4({getPluginManager:()=>c()?.pluginManager??V})).use(o4()).use(L4()).use(M4({getPluginManager:()=>c()?.pluginManager??V,getTunnelHost:()=>E5()?.url??null})).use(Z4()).use(X4()).use(B5()).use(K5()).use(V5(H)).ws("/code-server/*",gQ(Z)).all("/api/profiles/:name/*",async({params:F,request:M,set:U})=>{let A=M.method!=="GET"&&M.method!=="HEAD",R=A?await M.arrayBuffer():void 0,P=await L5(F.name,M,R);if(P&&P.status!==404)return P;let p=C2(),o=F.name;if(o!==p)return U.status=404,{error:"profile-mismatch",running:p,requested:o,hint:"This daemon serves a different profile. Call GET /api/profiles to discover the right tunnel."};let Q2=new URL(M.url),U2=Q2.pathname.replace(/^\/api\/profiles\/[^/]+/,"/api"),j2=new Headers(M.headers);j2.set("x-vc-profile-rewrite","1");let x2={method:M.method,headers:j2};if(A&&R!==void 0)x2.body=R;let r2=new Request(`${Q2.origin}${U2}${Q2.search}`,x2),w2=I0.current;if(!w2)return new Response(JSON.stringify({error:"agent-not-ready"}),{status:503,headers:{"content-type":"application/json"}});return w2.handle(r2)}).all("/api/*",async({request:F})=>{if(G().getBootState()!=="ready"||!T)return new Response(JSON.stringify({error:"Agent not yet configured",state:G().getBootState(),message:"Plugin routes are unavailable until the agent reaches state=ready. POST credentials to /api/agent/gateway-auth to finalize."}),{status:503,headers:{"content-type":"application/json"}});try{let M=new URL(F.url),U=/^\/api\/plugins\/([a-z0-9-]{1,64})\/ui(?:\/.*)?$/.exec(M.pathname);if(U&&F.method==="GET"){let A=U[1];if(M2(A)){let R=M.pathname.slice(`/api/plugins/${A}/ui`.length),P=R===""||R==="/",o=F.headers.get("sec-fetch-mode")==="navigate";if(P||o){let Q2=J5(F,A);if(!Q2||!Z5(Q2,A))return new Response(x5(A,"/api/profiles/default/agent/ui-exchange-plugin"),{status:200,headers:{"content-type":"text/html; charset=utf-8","Content-Security-Policy":"frame-ancestors 'self' http://localhost:* http://127.0.0.1:* https://localhost:* https://127.0.0.1:* https://*.local.burdenoff.com https://vibecontrols.com https://*.vibecontrols.com https://burdenoff.com https://app.burdenoff.com https://alphaapp.burdenoff.com"}})}}}}catch{}return T.handle(F)}).all("/ui/*",async({request:F})=>{if(G().getBootState()!=="ready"||!O)return new Response("Plugin UI not yet available",{status:503});return O.handle(F)}).all("/code-server/*",async({request:F})=>{if(G().getBootState()!=="ready"||!T)return new Response("code-server not yet available",{status:503});let M=k0(F,V2);return T.handle(M??F)}).all("/plan/*",async({request:F})=>{if(G().getBootState()!=="ready"||!T)return new Response("plan provider not yet available",{status:503});return T.handle(F)});return I0.current=e,{app:e,async start(){e.listen({port:Z,hostname:Q}),G().logger.info("app",`Agent server listening on ${Q}:${Z}`);try{let F=(process.env.VIBECONTROLS_PROFILES??"").split(",").map((P)=>P.trim()).filter(Boolean),M=G().name,{getOrCreateProfile:U}=await import("./daemon-profile-696722nr.js"),{attachSecondaryProfile:A}=await import("./secondary-profile-attach-kxg4xj2t.js"),R=process.env.VIBE_STRICT_KEY_FETCH==="1";for(let P of F){if(P===M)continue;try{let p=U(P),o=await A(p);if(o.ok)G().logger.info("app",`Secondary profile '${P}' attached (db+services online)`);else if(R)throw Error(`attachServices for secondary profile '${P}' failed: ${o.error}`);else p.recordDegradedReason("attach",o.error??"unknown"),G().logger.warn("app",`Secondary profile '${P}' is degraded (no creds / attach failed)`,{error:o.error})}catch(p){if(R)throw G().logger.error("app",`--strict-key-fetch: secondary profile '${P}' attach failed; aborting`,{error:String(p)}),setTimeout(()=>process.exit(1),50),p;G().logger.warn("app",`Failed to attach secondary profile '${P}'`,{error:String(p)})}}}catch{}return e},stop:r,finalize:i,getState:()=>G().getBootState(),getLifecycle:()=>c()?.lifecycle??q,getDb:()=>c()?.db??x,getServiceRegistry:()=>c()?.serviceRegistry??H,getPluginManager:()=>c()?.pluginManager??V,getHostServices:()=>c()?.hostServices??C}}var w5=null;function mQ($,Z){if(!$)return null;let Q=$.match(new RegExp(`(?:^|;\\s*)${Z}=([^;]*)`));return Q?Q[1]:null}var a4=z5(H5);function gQ($){let X=(J)=>typeof J==="string"?Buffer.byteLength(J):J.byteLength;return{open(J){let W=J.data,H=m(W.headers??{})??m(W.request?Object.fromEntries(W.request.headers.entries()):{}),B=W.query?.vt,K=!!B&&R2(B,"/code-server","GET"),L,w=l(H);if(!w&&!K){let C=W.headers?.cookie??W.request?.headers.get("cookie")??null,q=mQ(C,"__vibe_cs_session");if(!q||!w5?.(q)){J.close(1008,"Unauthorized");return}L=`session:${q}`}else if(w)L="api-key";else L="vt";let E=J.remoteAddress??null,x=G5(E,W.headers);if(!a4.accept(L,x,J)){G().logger.warn("code-server-ws",`code-server WS cap exceeded (key=${L}, ip=${x??"unknown"})`),J.close(1013,"too many connections");return}W._csCapKey=L,W._csRemoteIp=x;let V=G().name;fetch(`http://127.0.0.1:${$}/api/profiles/${encodeURIComponent(V)}/code-server/status`,{headers:{"x-agent-api-key":V2()}}).then((C)=>C.json()).then((C)=>{if(W._csClosed)return;let q=C;if(!q.running||!q.port){J.close(1011,"code-server not running");return}let v=W.request?.url??"/code-server/",N;try{let I=new URL(v,`http://127.0.0.1:${q.port}`);N=(I.pathname.replace(/^\/code-server\/?/,"/")||"/")+I.search}catch{N="/"}let T=new WebSocket(`ws://127.0.0.1:${q.port}${N}`),O={upstream:T,ready:!1,buffer:[],bufferBytes:0,openTimer:setTimeout(()=>{try{T.close(1011,"upstream open timeout")}catch{}try{J.close(1011,"upstream open timeout")}catch{}},1e4)};W._csBridge=O,T.addEventListener("open",()=>{clearTimeout(O.openTimer),O.ready=!0;for(let I of O.buffer)T.send(I);O.buffer.length=0,O.bufferBytes=0}),T.addEventListener("message",(I)=>{try{let h=I.data;if(h instanceof ArrayBuffer)J.send(new Uint8Array(h));else if(h instanceof Blob)h.arrayBuffer().then((y)=>{try{J.send(new Uint8Array(y))}catch{}});else J.send(h)}catch{}}),T.addEventListener("close",(I)=>{clearTimeout(O.openTimer);try{J.close(I.code||1000,I.reason||"upstream closed")}catch{}}),T.addEventListener("error",()=>{clearTimeout(O.openTimer);try{J.close(1011,"upstream error")}catch{}})}).catch(()=>{J.close(1011,"Failed to query code-server status")})},message(J,W){let H=J.data?._csBridge;if(!H)return;let B;if(typeof W==="string")B=W;else if(W instanceof ArrayBuffer)B=W;else if(W instanceof Uint8Array||Buffer.isBuffer(W)){let K=new ArrayBuffer(W.byteLength);new Uint8Array(K).set(new Uint8Array(W.buffer,W.byteOffset,W.byteLength)),B=K}else if(typeof W==="object"&&W!==null)B=JSON.stringify(W);else B=String(W);if(H.upstream&&H.ready&&H.upstream.readyState===WebSocket.OPEN)try{H.upstream.send(B)}catch{}else{let K=X(B);if(H.buffer.length>=256||H.bufferBytes+K>1048576){try{H.upstream.close(1013,"buffer limit exceeded")}catch{}try{J.close(1013,"buffer limit exceeded")}catch{}return}H.buffer.push(B),H.bufferBytes+=K}},close(J){J.data._csClosed=!0;let W=J.data?._csBridge;if(W?.openTimer)clearTimeout(W.openTimer);if(W?.upstream&&W.upstream.readyState===WebSocket.OPEN)W.upstream.close(1000,"client disconnected");let H=J.data._csCapKey,B=J.data._csRemoteIp;if(H)a4.release(H,B??null,J)}}}async function s4(){try{let{readFileSync:$}=await import("fs"),{join:Z,dirname:Q}=await import("path"),{fileURLToPath:Y}=await import("url"),X=Q(Y(import.meta.url));return JSON.parse($(Z(X,"..","package.json"),"utf8")).version||"1.0.0"}catch{return"1.0.0"}}
|
|
26
26
|
export{H6 as j,g0 as k,_Q as l,L7 as m,a8 as n};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{h as y,i as c}from"./index-cs78wq6y.js";import{A as p$,B as i$,y as l$}from"./index-
|
|
2
|
+
import{h as y,i as c}from"./index-cs78wq6y.js";import{A as p$,B as i$,y as l$}from"./index-41vve5br.js";import{N as j$}from"./index-b5dhmybd.js";import{O as H$,P as K$}from"./index-e1bw1bwr.js";import{va as g}from"./index-68r2ex9d.js";import"./index-4hn26x1h.js";import{Ca as k$}from"./index-4wgjx8bf.js";import"./index-cv0xhb46.js";import"./index-0ckffygp.js";import{ab as v}from"./index-rc79x8fw.js";import{db as Y$}from"./index-52cp759f.js";import"./index-6p3gcnxr.js";import{Jb as C$,Kb as D$,tb as X$,vb as L$}from"./index-bfeekmyh.js";import"./index-5dysvvjv.js";import{Ub as F,Vb as p}from"./index-pgew6sge.js";import{Xb as g$}from"./index-zhyxdyk6.js";import"./index-8sdrhr3q.js";import{jc as x,kc as _,lc as c$}from"./index-8nqp3a4d.js";import{Ac as s,Bc as N,Cc as u,oc as V,pc as Z,qc as Y,rc as H,sc as A,uc as z,vc as X,wc as J,xc as Q,yc as h$,zc as k}from"./index-85ke6hng.js";import{Hc as K}from"./index-thammzct.js";import{Lc as T,Nc as b,Oc as M,Pc as y$}from"./index-t8tnkqxh.js";import{qd as T$}from"./index-63ba5fb4.js";import{Id as z$,Ld as q$,Od as q}from"./index-xnr6t79p.js";import{$d as $$,Yd as J$,_d as a,ae as U$}from"./index-a4854mwz.js";import"./index-4qq083yd.js";import{ie as d}from"./index-c7554sg7.js";function t(f){let{name:W,onInit:w,onShutdown:U,onNuke:R,telemetryEventName:$,skipPlatforms:G}=f;return{onServerStart:async(I,O)=>{if(G&&G.includes(process.platform)){process.stderr.write(`[${W}] skipping init on unsupported platform '${process.platform}'
|
|
3
3
|
`);return}if(w)await w(O);if($)O.telemetry?.emit($,{plugin:W})},onServerStop:async(I)=>{if(U)await U(I)},onNuke:async(I,O)=>{if(R)return R(I,O)}}}var e=class{constructor(f,W){this.logger=f,this.source=W}logger;source;info(f,W){this.logger?.info?.(this.source,f,W)}warn(f,W){this.logger?.warn?.(this.source,f,W)}error(f,W){this.logger?.error?.(this.source,f,W)}debug(f,W){this.logger?.debug?.(this.source,f,W)}};import{existsSync as t$,rmSync as e$,statSync as a$}from"fs";import{resolve as $U}from"path";function R$(f=$$()){let W=[],w=$U(f),U=U$();if(!a(U,w))throw Error("Refusing to reset a path outside the agents directory");if(t$(w)&&a$(w).isDirectory())e$(w,{recursive:!0,force:!0}),W.push(w);return{removed:W,agentDir:w}}var S="alias",G$=/^[a-zA-Z0-9_-]{1,64}$/,w$=16384,f$=256,W$=1024,UU=new Set(["help","start","stop","restart","kill","list","status","setup","update","completion","autostart","export","import","diagnostics","nuke","doctor","log-level","gc","deploy","network","profile","peer-bootstrap","gateway-auth","info","key","system","url","health","notify","tunnel","session","git","config","log","plugin","ai","audit","alias","run"]);class D extends Error{code;constructor(f,W){super(W);this.code=f,this.name="AliasValidationError"}}class E extends Error{constructor(f){super(`alias '${f}' already exists`);this.name="AliasConflictError"}}class P extends Error{constructor(f){super(`alias '${f}' not found`);this.name="AliasNotFoundError"}}function RU(f){if(typeof f!=="string"||!G$.test(f))throw new D("invalid_name",`alias name must match ${G$} (got '${f}')`);if(UU.has(f))throw new D("reserved_name",`alias name '${f}' is reserved`)}function I$(f){if(typeof f!=="string"||f.length===0)throw new D("invalid_command","alias command must be a non-empty string");if(f.length>w$)throw new D("command_too_long",`alias command exceeds ${w$} bytes`)}function O$(f){if(f===void 0)return;if(typeof f!=="string")throw new D("invalid_description","alias description must be a string");if(f.length>f$)throw new D("description_too_long",`alias description exceeds ${f$} chars`)}function F$(f){if(f===void 0||f===null||f==="")return;if(typeof f!=="string")throw new D("invalid_cwd","alias cwd must be a string");if(f.length>W$)throw new D("cwd_too_long",`alias cwd exceeds ${W$} chars`);if(f.includes("\x00"))throw new D("invalid_cwd","alias cwd must not contain NUL bytes")}function GU(f){if(!f)return;try{return JSON.parse(f)}catch{return}}async function i(f){let W=await f.getAllPluginState(S),w=[];for(let U of W){let R=GU(U.value);if(R)w.push(R)}return w.sort((U,R)=>U.name.localeCompare(R.name)),w}async function n(f,W){return(await i(f)).find((U)=>U.name===W)}function V$(f){if(f===void 0||f===null)return null;let W=f.trim();return W===""?null:W}async function Q$(f,W){if(RU(W.name),I$(W.command),O$(W.description),F$(W.cwd),await n(f,W.name))throw new E(W.name);let U=new Date().toISOString(),R={id:crypto.randomUUID(),name:W.name,command:W.command,description:W.description,cwd:V$(W.cwd),profile:J$(),createdAt:U,updatedAt:U};return await f.setPluginState(S,R.id,JSON.stringify(R)),R}async function Z$(f,W,w){let U=await n(f,W);if(!U)throw new P(W);if(w.command!==void 0)I$(w.command);if(w.description!==void 0)O$(w.description);if(w.cwd!==void 0)F$(w.cwd);let R={...U,command:w.command??U.command,description:w.description!==void 0?w.description:U.description,cwd:w.cwd!==void 0?V$(w.cwd):U.cwd,updatedAt:new Date().toISOString()};return await f.setPluginState(S,R.id,JSON.stringify(R)),R}async function B$(f,W){let w=await n(f,W);if(!w)throw new P(W);await f.deletePluginState(S,w.id)}function m(){let f=q$()??q();return{dir:f.dataDir,scope:f.name}}function M$(f){let{serviceRegistry:W,db:w}=f;return new p().get("/api-key",()=>({apiKey:C$()})).post("/reset-key",async({body:U,set:R})=>{let $=U.apiKey;if(!$||typeof $!=="string")return R.status=400,{error:"Missing required field: apiKey"};try{return await D$($),await q().keyVault.bindApiKey($),q().logger.info("auth","Adopted backend-rotated agent API key via /reset-key"),{success:!0}}catch(G){return R.status=400,{error:"reset-key failed",message:G instanceof Error?G.message:String(G)}}},{body:F.Object({apiKey:F.String()})}).get("/audit",({query:U})=>{let R=U,$=R.limit?Math.min(5000,Math.max(1,Number.parseInt(R.limit,10)||100)):100,G=q().audit.listEvents({since:R.since,limit:$,event:R.event});return{events:G,count:G.length}},{query:F.Object({since:F.Optional(F.String()),limit:F.Optional(F.String()),event:F.Optional(F.String())})}).get("/setup/check",()=>{let U=H$();return{ready:U.filter(($)=>$.required).every(($)=>$.installed),dependencies:U}}).post("/setup/install",async({request:U,server:R,set:$})=>{let G=await c(U,"VIBECONTROLS_ALLOW_REMOTE_SETUP_INSTALL",R);if(G)return $.status=403,{error:"Forbidden",message:G};return await K$()}).get("/url",async()=>{let U=W.getProvider("tunnel"),R=U&&U.getActiveTunnelUrl?await U.getActiveTunnelUrl():null,$=`http://localhost:${process.env.PORT||3005}`;return{url:R||$,tunnelUrl:R,localUrl:$,source:R?"tunnel":"local"}}).get("/lifecycle/state",()=>{return{state:W.getService("agent","lifecycle")?.getState()??"running"}}).post("/lifecycle/stop",async({set:U})=>{let R=W.getService("agent","lifecycle");if(!R)return U.status=500,{error:"Lifecycle manager not initialized"};return await R.stop(),{state:"stopped"}}).post("/lifecycle/start",async({set:U})=>{let R=W.getService("agent","lifecycle");if(!R)return U.status=500,{error:"Lifecycle manager not initialized"};return await R.start(),{state:"running"}}).post("/lifecycle/kill",async({set:U})=>{let R=W.getService("agent","lifecycle");if(!R)return U.status=500,{error:"Lifecycle manager not initialized"};return setTimeout(()=>R.kill(),100),{state:"killing"}}).post("/log-level",async({body:U,request:R,server:$,set:G})=>{let I=await c(R,"VIBECONTROLS_ALLOW_REMOTE_LOG_LEVEL",$);if(I)return G.status=403,{error:"Forbidden",message:I};let O=String(U.level??"").toLowerCase();if(!["debug","info","warn","error"].includes(O))return G.status=400,{error:"Invalid level",message:"level must be debug | info | warn | error"};return q().logger.setLevel(O),q().logger.info("agent",`Log level set to ${O} via API`),{ok:!0,level:O}},{body:F.Object({level:F.String()})}).post("/reset",async({body:U,request:R,server:$,set:G})=>{if(!U.confirm)return G.status=400,{error:"Reset confirmation required",message:"Send { confirm: true } to reset local agent state."};let I=await c(R,"VIBECONTROLS_ALLOW_REMOTE_RESET",$);if(I)return G.status=403,{error:"Forbidden",message:I};let O=W.getService("agent","lifecycle");try{if(O)await O.prepareForReset()}catch(h){q().logger.warn("agent","prepareForReset failed during reset \u2014 proceeding to wipe anyway",{error:String(h)})}try{z$.configure({globalGatewayUrl:"",workspaceGatewayUrl:void 0,clientId:"",clientSecret:"",workspaceId:void 0})}catch{}await w.close();let{removed:B,agentDir:L}=R$();q().logger.info("agent","Reset wiped local agent state",{agentDir:L,removed:B});let C=new Uint8Array(32);crypto.getRandomValues(C);let j=`vcak_${Buffer.from(C).toString("base64url")}`;return T$({"static-api-key":j},m()),q().setBootState("awaiting-config"),G.status=200,{success:!0,state:"awaiting-config",...y(R,$)||process.env.VIBECONTROLS_RETURN_RESET_API_KEY==="1"?{newApiKey:j}:{},agentDir:L,removed:B}},{body:F.Object({confirm:F.Boolean()})}).post("/sessions/:sessionId/share",async({params:U,body:R,server:$,request:G,set:I})=>{if(!y(G,$)&&process.env.VIBECONTROLS_ALLOW_REMOTE_SESSION_SHARE!=="1")return I.status=403,{error:"Forbidden",message:"Session-share mint must come from a local request unless VIBECONTROLS_ALLOW_REMOTE_SESSION_SHARE=1."};if(!X$(U.sessionId))return I.status=400,{error:"BadRequest",message:"invalid sessionId"};let O=wU(R?.expiresIn)??1800000,B=crypto.randomUUID(),L=new Uint8Array(32);crypto.getRandomValues(L);let C=`vcak_${Buffer.from(L).toString("base64url")}`,j=new Date(Date.now()+O).toISOString(),r=[...(await import("./agent-config-pxkfd7ec.js")).readAgentConfig({dir:m().dir}).apiKeys??[],{id:B,name:`session-share:${U.sessionId}:${R?.label??"viewer"}`,key:C,scopes:["read"],expiresAt:j,createdAt:new Date().toISOString()}];(await import("./agent-config-pxkfd7ec.js")).writeAgentConfig({apiKeys:r},m());let h=W.getProvider("tunnel"),d$=(h&&h.getActiveTunnelUrl?await h.getActiveTunnelUrl():null)??`http://localhost:${process.env.PORT||3005}`,s$=L$({pathPrefixes:[`/terminal/${U.sessionId}`],methods:["GET"]},Math.min(600,Math.floor(O/1000))),r$=`${d$.replace(/\/$/,"")}/terminal/${encodeURIComponent(U.sessionId)}/#vt=${encodeURIComponent(s$.token)}`;return q().logger.info("session-share","Minted share credential",{sessionId:U.sessionId,keyId:B,expiresAt:j}),{ok:!0,keyId:B,apiKey:C,joinUrl:r$,sessionId:U.sessionId,expiresAt:j}},{params:F.Object({sessionId:F.String()}),body:F.Optional(F.Object({permissions:F.Optional(F.Array(F.String())),expiresIn:F.Optional(F.String()),label:F.Optional(F.String())}))}).get("/aliases",async()=>{return{aliases:await i(w)}}).get("/aliases/:name",async({params:U,set:R})=>{let $=await n(w,U.name);if(!$)return R.status=404,{error:"Alias not found"};return $},{params:F.Object({name:F.String()})}).post("/aliases",async({body:U,set:R})=>{try{let $=await Q$(w,U);return R.status=201,$}catch($){if($ instanceof E)return R.status=409,{error:"Alias already exists",message:$.message};if($ instanceof D)return R.status=400,{error:$.code,message:$.message};throw $}},{body:F.Object({name:F.String(),command:F.String(),description:F.Optional(F.String()),cwd:F.Optional(F.Union([F.String(),F.Null()]))})}).put("/aliases/:name",async({params:U,body:R,set:$})=>{try{return await Z$(w,U.name,R)}catch(G){if(G instanceof P)return $.status=404,{error:"Alias not found"};if(G instanceof D)return $.status=400,{error:G.code,message:G.message};throw G}},{params:F.Object({name:F.String()}),body:F.Object({command:F.Optional(F.String()),description:F.Optional(F.String()),cwd:F.Optional(F.Union([F.String(),F.Null()]))})}).delete("/aliases/:name",async({params:U,set:R})=>{try{return await B$(w,U.name),R.status=204,null}catch($){if($ instanceof P)return R.status=404,{error:"Alias not found"};throw $}},{params:F.Object({name:F.String()})}).post("/aliases/:name/execute",async({params:U,body:R,set:$})=>{let G=await n(w,U.name);if(!G)return $.status=404,{error:"Alias not found"};let I=R?.args??[],O=await j$(G,I);q().audit.emit("agent","alias.executed",{exit_code:O.exit_code});let B=Y$("alias.executed",{exit_code:O.exit_code});if(!B.ok)q().logger.debug("alias",`telemetry validate failed: ${B.reason}`);if(O.timed_out)$.status=408;return{exit_code:O.exit_code,stdout:O.stdout,stderr:O.stderr,duration_ms:O.duration_ms,truncated:O.truncated,cwd:O.cwd}},{params:F.Object({name:F.String()}),body:F.Optional(F.Object({args:F.Optional(F.Array(F.String()))}))}).post("/sessions/share/:keyId/revoke",async({params:U,server:R,request:$,set:G})=>{if(!y($,R)&&process.env.VIBECONTROLS_ALLOW_REMOTE_SESSION_SHARE!=="1")return G.status=403,{error:"Forbidden"};let I=await import("./agent-config-pxkfd7ec.js"),O=m(),B=I.readAgentConfig({dir:O.dir}),L=(B.apiKeys??[]).length,C=(B.apiKeys??[]).filter((j)=>j.id!==U.keyId);if(C.length===L)return G.status=404,{error:"No such share key"};return I.writeAgentConfig({apiKeys:C},O),{ok:!0,revoked:U.keyId}},{params:F.Object({keyId:F.String()})})}function wU(f){if(!f)return null;let W=/^(\d+)([smhdw]?)$/.exec(f.trim());if(!W)return null;let w=Number(W[1]),U=W[2]||"m";return U==="s"?w*1000:U==="m"?w*60000:U==="h"?w*3600000:U==="d"?w*86400000:w*7*86400000}var fU="http://localhost:3005";function x$(f){f.command("health").description("Check health of a VibeControls agent instance").option("-n, --name <name>","Agent instance name").option("--agent-url <url>","Agent URL",fU).option("--json","Emit JSON").option("--plain","Force plain text output").action(async function(W){try{let w={...f.opts(),...W};await _({mode:x(w),fetchData:async()=>{if(w.name){let $=await new g().checkHealth(w.name);return{mode:"named",agentUrl:T(w),name:w.name,healthy:$.healthy,details:$.details??{}}}let U=T(w);try{let R=await M(U,"/health");return{mode:"url",agentUrl:U,healthy:!0,details:R}}catch(R){return{mode:"url",agentUrl:U,healthy:!1,details:{status:"unhealthy",...R instanceof Error?{error:H(R)}:{}}}}},plain:(U)=>{if(X("Agent Health"),Q(),U.mode==="named"){if(!U.healthy){Y(`Agent instance ${V.bold(U.name??"")} is not responding.`);return}let R=U.details;if(J("Instance",U.name??""),J("Status",u(R.status??"healthy")),R.uptime!==void 0)J("Uptime",`${R.uptime}s`);if(R.checks){Q(),z(`${Z.info} Health checks:`);for(let[$,G]of Object.entries(R.checks)){let I=G.status==="healthy"?Z.success:Z.error;J(` ${I} ${$}`,u(G.status))}}}else{if(J("URL",U.agentUrl),J("Status",u(U.details.status??"unhealthy")),U.details.version)J("Version",U.details.version);if(U.details.uptime!==void 0)J("Uptime",`${U.details.uptime}s`);if(U.details.timestamp)J("Timestamp",U.details.timestamp);if(U.details.checks){Q(),z(`${Z.info} Health checks:`);for(let[R,$]of Object.entries(U.details.checks)){let G=$.status==="healthy"?Z.success:Z.error;J(` ${G} ${R}`,u($.status))}}}if(Q(),U.healthy)A(`${Z.success} Agent is healthy.`)},interactive:async(U)=>{let R=[];if(U.mode==="named")R.push(`Instance: ${U.name??""}`);else R.push(`URL: ${U.agentUrl}`);if(R.push(`Status: ${u(U.details.status??(U.healthy?"healthy":"unhealthy"))}`),U.details.version)R.push(`Version: ${U.details.version}`);if(U.details.uptime!==void 0)R.push(`Uptime: ${U.details.uptime}s`);if(U.details.timestamp)R.push(`Time: ${U.details.timestamp}`);if(U.details.checks){R.push(""),R.push("Checks:");for(let[$,G]of Object.entries(U.details.checks))R.push(` ${$}: ${G.status}`)}await K({title:"Agent Health",body:R.join(`
|
|
4
4
|
`),footer:"press q to exit"})},json:(U)=>({mode:U.mode,agentUrl:U.agentUrl,name:U.name??null,healthy:U.healthy,details:U.details})})}catch(w){Y(`Health check failed: ${H(w)}`)}})}import{platform as WU,arch as JU,release as IU,hostname as OU,cpus as FU,totalmem as VU}from"os";var QU="http://localhost:3005";function _$(f){f.command("info").description("Show local and remote VibeControls agent information").option("--agent-url <url>","Agent URL",QU).option("--json","Emit JSON").option("--plain","Force plain text output").action(async function(W){try{let w={...f.opts(),...W},U=T(w),R=encodeURIComponent(b(w));await _({mode:x(w),fetchData:async()=>{let $={hostname:OU(),platform:WU(),arch:JU(),release:IU(),cpus:FU().length,totalMemory:VU(),nodeVersion:process.version,bunVersion:process.versions.bun};try{let G=await M(U,`/api/profiles/${R}/agent/version`);return{local:$,agentUrl:U,remote:G}}catch(G){return{local:$,agentUrl:U,remote:null,remoteError:G instanceof Error?H(G):String(G)}}},plain:($)=>{if(X("VibeControls Agent Info"),Q(),z(`${Z.info} Local System`),J("Hostname",$.local.hostname),J("Platform",`${$.local.platform} ${$.local.arch}`),J("OS Release",$.local.release),J("CPUs",String($.local.cpus)),J("Total Memory",N($.local.totalMemory)),J("Node.js",$.local.nodeVersion),$.local.bunVersion)J("Bun",$.local.bunVersion);if(Q(),z(`${Z.info} Remote Agent`),J("URL",$.agentUrl),$.remote){if(J("Version",V.bold($.remote.version)),$.remote.build)J("Build",$.remote.build);if($.remote.commit)J("Commit",$.remote.commit);if($.remote.nodeVersion)J("Node.js (remote)",$.remote.nodeVersion);if($.remote.bunVersion)J("Bun (remote)",$.remote.bunVersion)}else J("Status",V.dim("not reachable"));Q()},interactive:async($)=>{let G=[];if(G.push("Local System"),G.push(` Hostname: ${$.local.hostname}`),G.push(` Platform: ${$.local.platform} ${$.local.arch}`),G.push(` OS Release: ${$.local.release}`),G.push(` CPUs: ${$.local.cpus}`),G.push(` Total Memory: ${N($.local.totalMemory)}`),G.push(` Node.js: ${$.local.nodeVersion}`),$.local.bunVersion)G.push(` Bun: ${$.local.bunVersion}`);if(G.push(""),G.push("Remote Agent"),G.push(` URL: ${$.agentUrl}`),$.remote){if(G.push(` Version: ${$.remote.version}`),$.remote.build)G.push(` Build: ${$.remote.build}`);if($.remote.commit)G.push(` Commit: ${$.remote.commit}`);if($.remote.nodeVersion)G.push(` Node.js: ${$.remote.nodeVersion} (remote)`);if($.remote.bunVersion)G.push(` Bun: ${$.remote.bunVersion} (remote)`)}else G.push(" Status: not reachable");await K({title:"VibeControls Agent Info",body:G.join(`
|
|
5
5
|
`),footer:"press q to exit"})},json:($)=>({local:$.local,agentUrl:$.agentUrl,remote:$.remote,remoteError:$.remoteError??null})})}catch(w){Y(`Failed to get info: ${H(w)}`)}})}var ZU="http://localhost:3005";function b$(f){f.command("system").description("Show system information for a running VibeControls agent").option("--agent-url <url>","Agent URL",ZU).option("--json","Emit JSON").option("--plain","Force plain text output").action(async function(W){try{let w={...f.opts(),...W},U=T(w),R=encodeURIComponent(b(w));await _({mode:x(w),fetchData:()=>M(U,`/api/profiles/${R}/agent/system`),plain:($)=>{if(X("Agent System Information"),Q(),z(`${Z.info} Agent`),J("Version",V.bold($.agentVersion)),$.bunVersion)J("Bun",$.bunVersion);if($.environment)J("Environment",$.environment);J("Uptime",s($.uptime)),Q(),z(`${Z.info} Platform`),J("OS",`${$.platform} ${$.arch}`),J("Hostname",$.hostname),J("Release",$.release),Q(),z(`${Z.info} Resources`),J("CPUs",String($.cpus)),J("Total Memory",N($.totalMemory)),J("Free Memory",N($.freeMemory)),Q(),z(`${Z.info} Paths`),J("Home",$.homeDir),J("CWD",$.cwd),Q()},interactive:async($)=>{let G=["Agent",` Version: ${$.agentVersion}`,...$.bunVersion?[` Bun: ${$.bunVersion}`]:[],...$.environment?[` Environment: ${$.environment}`]:[],` Uptime: ${s($.uptime)}`,"","Platform",` OS: ${$.platform} ${$.arch}`,` Hostname: ${$.hostname}`,` Release: ${$.release}`,"","Resources",` CPUs: ${$.cpus}`,` Total Mem: ${N($.totalMemory)}`,` Free Mem: ${N($.freeMemory)}`,"","Paths",` Home: ${$.homeDir}`,` CWD: ${$.cwd}`];await K({title:"Agent System Information",body:G.join(`
|