@vibecontrols/agent 2026.824.1 → 2026.1124.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent-config-v9d7gcz0.js +2 -0
- package/dist/agent-ready-tracker-mewxehg9.js +2 -0
- package/dist/app-k7z7tjem.js +2 -0
- package/dist/autostart.cmd-ahet7b1t.js +2 -0
- package/dist/bootstrap-workspace-3pb8qjsh.js +2 -0
- package/dist/bootstrap.service-9m7m1ksa.js +2 -0
- package/dist/bridge-client-xvqy3n15.js +2 -0
- package/dist/cli.js +2 -2
- package/dist/daemon-profile-sg8fp50z.js +2 -0
- package/dist/finalize-retry-handle-registry-z9mbbjmj.js +2 -0
- package/dist/finalize-retry-worker-az74f2qv.js +2 -0
- package/dist/gateway-client-ermpz52n.js +2 -0
- package/dist/getMachineId-bsd-4w1wmcjv.js +2 -0
- package/dist/getMachineId-darwin-kejwz8w5.js +3 -0
- package/dist/getMachineId-linux-mpm53wat.js +2 -0
- package/dist/getMachineId-unsupported-54seyw5v.js +2 -0
- package/dist/getMachineId-win-cva7ghz9.js +2 -0
- package/dist/highlights-3nz7pbkh.js +2 -0
- package/dist/highlights-6dgztt5d.js +2 -0
- package/dist/highlights-jq0g1547.js +2 -0
- package/dist/highlights-yc7cwzcr.js +2 -0
- package/dist/highlights-z2sw1kpq.js +2 -0
- package/dist/index-01fp85ft.js +171 -0
- package/dist/index-06bmw4xf.js +83 -0
- package/dist/index-0gmhd3hs.js +4 -0
- package/dist/index-0qjbnyg4.js +21 -0
- package/dist/index-2r6cmxxz.js +9 -0
- package/dist/index-2vcxt38h.js +3 -0
- package/dist/index-3b5xejjs.js +5 -0
- package/dist/index-3cbesatx.js +178 -0
- package/dist/index-4q8y6k1e.js +26 -0
- package/dist/index-4z1y39jt.js +3 -0
- package/dist/index-5021rk8n.js +3 -0
- package/dist/index-652f9scs.js +4 -0
- package/dist/index-76m37yd8.js +22 -0
- package/dist/index-7f2k4g6q.js +8 -0
- package/dist/index-7gk1x74m.js +15 -0
- package/dist/index-7wben1jx.js +3 -0
- package/dist/index-8rbhm4g8.js +7 -0
- package/dist/index-9bj65n3s.js +13 -0
- package/dist/index-9xrhb68w.js +14 -0
- package/dist/index-a0vx2zyx.js +3 -0
- package/dist/index-aav1drxa.js +158 -0
- package/dist/index-akk3rxnn.js +4 -0
- package/dist/index-b3v08awy.js +3 -0
- package/dist/index-byerrz46.js +3 -0
- package/dist/index-c4whjk5r.js +3 -0
- package/dist/index-cy97asyh.js +133 -0
- package/dist/index-d59kp6zr.js +3 -0
- package/dist/index-haww9jpq.js +27 -0
- package/dist/index-hsrt2v87.js +2 -0
- package/dist/index-jmx5awkj.js +3 -0
- package/dist/index-jnxjjx2y.js +3 -0
- package/dist/index-kwhx023z.js +11 -0
- package/dist/index-m942hydk.js +116 -0
- package/dist/index-mmx2kp76.js +16 -0
- package/dist/index-p0bbp16g.js +11 -0
- package/dist/index-qe3xpt41.js +3 -0
- package/dist/index-qfxwk38p.js +82 -0
- package/dist/index-ss5gez2p.js +2 -0
- package/dist/index-t5cfkz1e.js +4 -0
- package/dist/index-t6p4szqx.js +5 -0
- package/dist/index-tahaxp6n.js +3 -0
- package/dist/index-v16qz1fa.js +3 -0
- package/dist/index-vtsd74g0.js +9 -0
- package/dist/index-w0m3jm0s.js +408 -0
- package/dist/index-w4jqdhc2.js +5 -0
- package/dist/index-wr888ydc.js +17 -0
- package/dist/index-xtd0j8ve.js +3 -0
- package/dist/index-ywnfz6nm.js +3 -0
- package/dist/index.js +3 -3
- package/dist/injections-h25c1fmk.js +2 -0
- package/dist/interactive-vbz68zh5.js +2 -0
- package/dist/key.cmd-f6rjvjy8.js +2 -0
- package/dist/log-shipper-0erbwn0q.js +2 -0
- package/dist/path-utils-r4df8d3w.js +2 -0
- package/dist/plugin-system-kvg955t3.js +2 -0
- package/dist/prereqs-runner-gca0bytz.js +2 -0
- package/dist/profile-mount-s4mc1x18.js +2 -0
- package/dist/prune-stale-shims-4nqtv0xt.js +2 -0
- package/dist/register-core-31wm1d8m.js +2 -0
- package/dist/secondary-profile-attach-95kmnrhf.js +2 -0
- package/dist/subprocess-4gg77skg.js +2 -0
- package/dist/telemetry-nmtywcba.js +2 -0
- package/dist/tree-sitter-javascript-rfadfcwb.js +2 -0
- package/dist/tree-sitter-markdown-gkyb2qez.js +2 -0
- package/dist/tree-sitter-markdown_inline-xzttqkvb.js +2 -0
- package/dist/tree-sitter-typescript-4z897028.js +2 -0
- package/dist/tree-sitter-zig-y6n7djp6.js +2 -0
- package/dist/tunnel-bootstrap-rym0b0x5.js +2 -0
- package/package.json +10 -9
- package/dist/agent-config-5b0avmy6.js +0 -2
- package/dist/agent-ready-tracker-ez6r9djg.js +0 -2
- package/dist/app-hkt10ta3.js +0 -2
- package/dist/autostart.cmd-fdcdqrr2.js +0 -2
- package/dist/bootstrap-workspace-t5fyq07m.js +0 -2
- package/dist/bootstrap.service-nxhkrsf1.js +0 -2
- package/dist/bridge-client-bgkr7bcn.js +0 -2
- package/dist/daemon-profile-j2wt35x8.js +0 -2
- package/dist/esm-n9r8p5n2.js +0 -2
- package/dist/finalize-retry-handle-registry-fvm4gm8s.js +0 -2
- package/dist/finalize-retry-worker-wb8wj1yw.js +0 -2
- package/dist/gateway-client-6dqagbg4.js +0 -2
- package/dist/getMachineId-bsd-fgatzdd7.js +0 -2
- package/dist/getMachineId-darwin-gt8j2jw2.js +0 -3
- package/dist/getMachineId-linux-bcz4rr1x.js +0 -2
- package/dist/getMachineId-unsupported-079qwwb4.js +0 -2
- package/dist/getMachineId-win-2hk4e8bg.js +0 -2
- package/dist/highlights-0gfz787m.js +0 -2
- package/dist/highlights-86sbx76f.js +0 -2
- package/dist/highlights-n55f5jnk.js +0 -2
- package/dist/highlights-tbmszdr7.js +0 -2
- package/dist/highlights-wm2cs773.js +0 -2
- package/dist/index-06es0fmw.js +0 -10
- package/dist/index-0d4wfjbt.js +0 -171
- package/dist/index-29fmptfn.js +0 -13
- package/dist/index-2q2jadag.js +0 -11
- package/dist/index-2sn36kaj.js +0 -7
- package/dist/index-3p4n7nwg.js +0 -83
- package/dist/index-3tf12pw3.js +0 -3
- package/dist/index-4gsn3d9r.js +0 -26
- package/dist/index-54mmh1eb.js +0 -4
- package/dist/index-6jzsthh9.js +0 -3
- package/dist/index-7wejfjj9.js +0 -5
- package/dist/index-8q19ryt2.js +0 -28
- package/dist/index-8xh8m2z7.js +0 -8
- package/dist/index-a8n6s2ae.js +0 -2
- package/dist/index-b16y8wyz.js +0 -15
- package/dist/index-bv1z3fxw.js +0 -3
- package/dist/index-cs78wq6y.js +0 -3
- package/dist/index-df19rrbe.js +0 -5
- package/dist/index-dx9hjdp4.js +0 -178
- package/dist/index-ea42kfvk.js +0 -5
- package/dist/index-ekr40gvh.js +0 -3
- package/dist/index-evnbrmdf.js +0 -4
- package/dist/index-ggxs7nwz.js +0 -3
- package/dist/index-gz5t0vvc.js +0 -4
- package/dist/index-hey6w5m0.js +0 -3
- package/dist/index-hp8jrj6j.js +0 -3
- package/dist/index-hrfkzecw.js +0 -3
- package/dist/index-hwpmdq5z.js +0 -4
- package/dist/index-hz5cy6vz.js +0 -11
- package/dist/index-jbxh0ffn.js +0 -407
- package/dist/index-js2r0men.js +0 -9
- package/dist/index-k3jkzj3k.js +0 -9
- package/dist/index-kteawn2b.js +0 -3
- package/dist/index-mbhq916m.js +0 -3
- package/dist/index-mxc61yr1.js +0 -3
- package/dist/index-pnk33bjw.js +0 -116
- package/dist/index-qdbxvcwr.js +0 -17
- package/dist/index-qqq9qyy6.js +0 -21
- package/dist/index-rmh8pff5.js +0 -3
- package/dist/index-sspydg85.js +0 -15
- package/dist/index-tk81f249.js +0 -3
- package/dist/index-vjdg5qb2.js +0 -2
- package/dist/index-vkrf8kzp.js +0 -158
- package/dist/index-vnxqna70.js +0 -16
- package/dist/index-w2j4ttsx.js +0 -130
- package/dist/index-w7gctzhm.js +0 -83
- package/dist/index-wj5hx7gq.js +0 -4
- package/dist/index-x4eaagvr.js +0 -3
- package/dist/index-xjr60th0.js +0 -3
- package/dist/index-xtbppqnv.js +0 -3
- package/dist/index-zr9rmjyp.js +0 -3
- package/dist/injections-2g0zh0bq.js +0 -2
- package/dist/interactive-08vyaapn.js +0 -2
- package/dist/key.cmd-642xcxb4.js +0 -2
- package/dist/log-shipper-9xfnjwr6.js +0 -2
- package/dist/path-utils-g449hqvm.js +0 -2
- package/dist/plugin-system-gpzcch00.js +0 -2
- package/dist/prereqs-runner-re9f51fp.js +0 -2
- package/dist/profile-mount-txvgkaz8.js +0 -2
- package/dist/prune-stale-shims-vs6a07tb.js +0 -2
- package/dist/register-core-e0ha52yw.js +0 -2
- package/dist/secondary-profile-attach-m9x9e7py.js +0 -2
- package/dist/subprocess-zcgpccp1.js +0 -2
- package/dist/telemetry-k6em3vy2.js +0 -2
- package/dist/tree-sitter-javascript-qh90w7td.js +0 -2
- package/dist/tree-sitter-markdown-favzteb6.js +0 -2
- package/dist/tree-sitter-markdown_inline-x2726t9j.js +0 -2
- package/dist/tree-sitter-typescript-m7ep8z1h.js +0 -2
- package/dist/tree-sitter-zig-3vsxg5wh.js +0 -2
- package/dist/tunnel-bootstrap-y8dczezc.js +0 -2
package/dist/index-29fmptfn.js
DELETED
|
@@ -1,13 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{Ha as D}from"./index-7wejfjj9.js";import{$a as V}from"./index-ea42kfvk.js";import{ee as _,fe as w,ge as x,he as N,ie as j,le as X,ne as A,qe as I}from"./index-gz5t0vvc.js";import{we as S}from"./index-xjr60th0.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
|
-
`)}catch{}let W=`See ${B}`;throw Error(U?`Failed to start agent '${q.name}'. ${W}
|
|
4
|
-
--- last log lines ---
|
|
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(`
|
|
6
|
-
`).slice(-z.tail).join(`
|
|
7
|
-
`);if(process.stdout.write(J?W:W),J&&!W.endsWith(`
|
|
8
|
-
`))process.stdout.write(`
|
|
9
|
-
`);return Y.length},H=await C(!0),G=!1,L=setInterval(async()=>{if(G)return;try{let J=await import("fs"),Y=J.statSync(B);if(Y.size>H){let U=J.openSync(B,"r"),W=Y.size-H,Z=Buffer.alloc(W);J.readSync(U,Z,0,W,H),J.closeSync(U),process.stdout.write(Z),H=Y.size}else if(Y.size<H)H=await C(!1)}catch{}},500),K=()=>{if(G)return;G=!0,clearInterval(L)};process.on("SIGINT",()=>{K(),process.exit(0)}),process.on("SIGTERM",()=>{K(),process.exit(0)}),process.on("SIGHUP",()=>{K(),process.exit(0)}),process.on("exit",K)}catch(C){console.error("Failed to follow logs:",C)}else try{let G=(await Bun.file(B).text()).split(`
|
|
10
|
-
`).slice(-z.tail).join(`
|
|
11
|
-
`);console.log(G)}catch(C){console.error("Failed to read logs:",C)}}async checkHealth(q){let z=await this.findProcessByName(q);if(!z||z.status!=="running")return{healthy:!1,details:{error:"Process not running"}};try{let B=await fetch(`http://localhost:${z.port}/health`),C=await B.json();return{healthy:B.ok,details:C}}catch(B){return{healthy:!1,details:{error:"Health check failed",message:B.message}}}}async setConfig(q,z){let B=Q(I(),"config.json"),C={};if($(B))C=JSON.parse(O(B,"utf8"));C[q]=z,M(B,JSON.stringify(C,null,2))}async getConfig(q){let z=Q(I(),"config.json");if(!$(z))return q?void 0:{};let B=JSON.parse(O(z,"utf8"));return q?B[q]:B}loadRegistry(){return w()}saveRegistry(q){x(q)}async withInstanceLock(q,z){let B=X(q),C=Q(this.productDir,`.agent-${B}.lock`),H;try{H=T(C,"wx",384),M(H,`${process.pid}
|
|
12
|
-
`)}catch(G){if(G.code==="EEXIST"){let K=parseInt(O(C,"utf8"),10);if(!K||!await this.isProcessRunning(K)){try{R(C)}catch{}return this.withInstanceLock(q,z)}throw Error(`Agent '${q}' is already being modified`,{cause:G})}throw G}try{return await z()}finally{try{b(H)}catch{}try{R(C)}catch{}}}async saveProcessInfo(q,z,B){await _(()=>{let H=this.loadRegistry().filter((G)=>G.name!==q);H.push({name:q,pid:z,port:B.port,config:B,startTime:new Date().toISOString(),status:"running"}),this.saveRegistry(H)})}async updateProcessStatus(q,z){await _(()=>{let B=this.loadRegistry(),C=B.find((H)=>H.name===q);if(C)C.status=z,this.saveRegistry(B)})}async findProcessByName(q){X(q);let B=this.loadRegistry().find((H)=>H.name===q);if(!B)return null;let C=await this.isManagedProcessRunning(B);return B.status=C?"running":"stopped",B}async isManagedProcessRunning(q){if(!await this.isProcessRunning(q.pid))return!1;try{return(await fetch(`http://127.0.0.1:${q.port}/health/live`,{signal:AbortSignal.timeout(1000)})).ok}catch{return!1}}async isProcessRunning(q){try{return process.kill(q,0),!0}catch{return!1}}killProcessTree(q){try{V().killProcessTree(q,"SIGKILL")}catch{}}}
|
|
13
|
-
export{P as za};
|
package/dist/index-2q2jadag.js
DELETED
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{ae as r}from"./index-qqq9qyy6.js";import{de as U,ke as Lq,ne as Cq,qe as V}from"./index-gz5t0vvc.js";import{existsSync as G,mkdirSync as I,readdirSync as rq,readFileSync as D,renameSync as v,rmSync as iq,writeFileSync as F}from"fs";import{dirname as h,join as E}from"path";import{randomUUID as aq}from"crypto";import{existsSync as L,mkdirSync as p,readFileSync as Yq,renameSync as Wq,unlinkSync as Rq,writeFileSync as P}from"fs";import{dirname as d,join as K}from"path";import{spawnSync as e}from"child_process";import{hostname as Aq,networkInterfaces as Pq,platform as jq,userInfo as kq}from"os";import{createCipheriv as _q,createDecipheriv as uq,pbkdf2Sync as xq,randomBytes as Iq}from"crypto";var qq="secrets:fallback",Gq="secrets:index",Qq=10,vq=100,$q=new Map;function Vq(q,Q){let $=`${q}:${Q}`,z=($q.get($)??0)+1;if($q.set($,z),z<=Qq)return!0;return(z-Qq)%vq===0}var A="vibecontrols-agent",Kq=".libsecret-install-attempted",Uq="secrets.json";function hq(){return globalThis.Bun?.secrets??null}class o{api;kind="bun-secrets";constructor(q){this.api=q}async get(q){return this.api.get({service:A,name:q})}async set(q,Q){await this.api.set({service:A,name:q,value:Q}),await dq(q)}async delete(q){let Q=await this.api.delete({service:A,name:q});return await oq(q),Q}async list(q){return pq(q)}}var Mq=".secrets-encrypted-v1",Eq=1e5,Sq=32,yq="sha256",N=null,zq=null;function fq(){let q=Pq();for(let Q of Object.values(q)){if(!Q)continue;for(let $ of Q){let z=$?.mac;if(z&&z!=="00:00:00:00:00:00")return z}}return"no-mac"}function Zq(){if(zq!==null)return zq;let q;try{q=kq().username||"unknown"}catch{q=process.env.USER||process.env.USERNAME||"unknown"}return`${Aq()}|${q}|${fq()}`}function Bq(){if(N)return N;let q=`vibecontrols-agent::${Zq()}`;return N=xq(q,Zq(),Eq,Sq,yq),N}function Jq(q){let Q=Iq(12),$=_q("aes-256-gcm",Bq(),Q),z=Buffer.concat([$.update(q,"utf8"),$.final()]),Z=$.getAuthTag();return`${Q.toString("hex")}:${Z.toString("hex")}:${z.toString("hex")}`}function lq(q){let Q=q.split(":");if(Q.length!==3)return!1;let[$,z,Z]=Q;return/^[0-9a-f]+$/i.test($)&&$.length===24&&/^[0-9a-f]+$/i.test(z)&&z.length===32&&/^[0-9a-f]*$/i.test(Z)}function gq(q){if(!lq(q))return null;try{let[Q,$,z]=q.split(":"),Z=uq("aes-256-gcm",Bq(),Buffer.from(Q,"hex"));return Z.setAuthTag(Buffer.from($,"hex")),Buffer.concat([Z.update(Buffer.from(z,"hex")),Z.final()]).toString("utf8")}catch{return null}}class Tq{kind="json-fallback";path;constructor(){this.path=K(V(),Uq)}async get(q){let{plain:Q}=this.readWithMigration(),$=Q[q];return typeof $==="string"?$:null}async set(q,Q){await U(qq,async()=>{let{encrypted:$}=this.readWithMigration();$[q]=Jq(Q),this.writeEncrypted($)})}async delete(q){return U(qq,async()=>{let{encrypted:Q}=this.readWithMigration();if(!(q in Q))return!1;return delete Q[q],this.writeEncrypted(Q),!0})}async list(q){let{encrypted:Q}=this.readWithMigration(),$=Object.keys(Q);return(q?$.filter((Z)=>Z.startsWith(q)):$).sort().map((Z)=>({name:Z}))}readWithMigration(){if(!L(this.path))return{encrypted:{},plain:{}};let q;try{q=Yq(this.path,"utf8")}catch{return{encrypted:{},plain:{}}}let Q;try{Q=JSON.parse(q)}catch{return{encrypted:{},plain:{}}}if(!Q||typeof Q!=="object"||Array.isArray(Q))return{encrypted:{},plain:{}};let $={},z={},Z=!1;for(let[J,X]of Object.entries(Q)){if(typeof X!=="string")continue;let W=gq(X);if(W!==null){$[J]=X,z[J]=W;continue}$[J]=Jq(X),z[J]=X,Z=!0}if(Z)try{this.writeEncrypted($),this.writeMarker()}catch{}return{encrypted:$,plain:z}}writeEncrypted(q){p(d(this.path),{recursive:!0});let Q=`${this.path}.${process.pid}.tmp`;if(P(Q,`${JSON.stringify(q,null,2)}
|
|
3
|
-
`,{mode:384}),Wq(Q,this.path),!L(this.markerPath()))this.writeMarker()}markerPath(){return K(d(this.path),Mq)}writeMarker(){try{P(this.markerPath(),`${new Date().toISOString()}
|
|
4
|
-
`,{mode:384})}catch{}}}var mq=".secrets-index.json";function c(){return K(V(),mq)}function s(){let q=c();if(!L(q))return new Set;try{let Q=Yq(q,"utf8"),$=JSON.parse(Q);if(Array.isArray($))return new Set($.filter((z)=>typeof z==="string"))}catch{}return new Set}function Dq(q){let Q=c();p(d(Q),{recursive:!0});let $=`${Q}.${process.pid}.tmp`;P($,`${JSON.stringify([...q].sort(),null,2)}
|
|
5
|
-
`,{mode:384}),Wq($,Q)}async function dq(q){await U(Gq,()=>{let Q=s();if(Q.has(q))return;Q.add(q),Dq(Q)})}async function oq(q){await U(Gq,()=>{let Q=s();if(!Q.delete(q))return;Dq(Q)})}function pq(q){let $=[...s()];return(q?$.filter((Z)=>Z.startsWith(q)):$).sort().map((Z)=>({name:Z}))}function cq(){if(jq()!=="linux")return{ok:!1};if(process.env.CI==="true")return{ok:!1,warning:"CI/test environment detected; using JSON fallback"};if(process.env.VIBE_SKIP_LIBSECRET_INSTALL==="1")return{ok:!1,warning:"VIBE_SKIP_LIBSECRET_INSTALL=1 set; using JSON fallback"};let q=V(),Q=K(q,Kq);if(L(Q))return{ok:!1,warning:"previous attempt failed; not retrying"};try{p(q,{recursive:!0}),P(Q,`${new Date().toISOString()}
|
|
6
|
-
`,{mode:384})}catch{return{ok:!1,warning:"could not write install marker"}}let $=[{check:["sh","-c","command -v apt-get"],install:["sudo","-n","apt-get","install","-y","libsecret-1-0"]},{check:["sh","-c","command -v dnf"],install:["sudo","-n","dnf","install","-y","libsecret"]},{check:["sh","-c","command -v pacman"],install:["sudo","-n","pacman","-S","--noconfirm","libsecret"]}];for(let z of $){if(e(z.check[0],z.check.slice(1),{stdio:["ignore","pipe","pipe"]}).status!==0)continue;let J=e(z.install[0],z.install.slice(1),{stdio:["ignore","pipe","pipe"]});if(J.status===0)return{ok:!0};return{ok:!1,warning:`auto-install via '${z.install.join(" ")}' failed (exit ${J.status??"unknown"})`}}return{ok:!1,warning:"no supported package manager found"}}var g=null,m=null,Xq=null;async function Hq(q){try{return await q.get({service:A,name:"__probe__"}),!0}catch{return!1}}async function sq(){if(Xq)return Xq;let q=hq();if(q&&await Hq(q))return new o(q);if(jq()==="linux"&&q){let Q=cq();if(Q.ok&&await Hq(q))return new o(q);if(Q.warning)console.warn(`[secrets] libsecret unavailable (${Q.warning}); using JSON fallback`);else console.warn("[secrets] Bun.secrets unavailable; using JSON fallback. Install libsecret-1-0 (apt) / libsecret (dnf/pacman) for OS keychain support.")}else if(!q)console.warn("[secrets] Bun.secrets API not present in this runtime; using JSON fallback.");return new Tq}async function k(){if(g)return g;if(!m)m=sq().then((q)=>{return g=q,q});return m}async function _(q){let $=await(await k()).get(q);if(Vq("read",q))r().audit.emit("agent","secret.read",{name:q,hit:$!==null});return $}async function u(q,Q){if(await(await k()).set(q,Q),Vq("written",q))r().audit.emit("agent","secret.written",{name:q,valueLen:Q.length})}async function CQ(){let q=await k(),Q=(await q.list()).map(($)=>$.name);return{count:Q.length,backend:Q.length===0?"none":q.kind,names:Q}}async function wQ(){let q=await k(),$=(await q.list()).map((z)=>z.name);for(let z of $)try{await q.delete(z)}catch{}if(q.kind==="bun-secrets")R(c()),R(K(V(),Kq));else if(q.kind==="json-fallback"){let z=V();R(K(z,Uq)),R(K(z,Mq))}return{count:$.length,backend:$.length===0?"none":q.kind,names:$}}function R(q){try{if(L(q))Rq(q)}catch{}}function nq(q){return`agent-config:${q}`}var b=["clientId","clientSecret","gatewayClientId","gatewayClientSecret","static-api-key"];function wq(q){return b.includes(q)}function T(q,Q){return`${q}:${Q}`}function S(){try{return Lq()}catch{return"default"}}var B=1,tq=[],y={globalGatewayUrl:"https://graphql.burdenoff.com/global/graphql",workspaceGatewayUrl:"https://graphqlworkspaces.burdenoff.com/workspaces/graphql"},eq={globalGatewayUrl:"https://alphagraphql.burdenoff.com/global/graphql",workspaceGatewayUrl:"https://alphagraphqlworkspaces.burdenoff.com/workspaces/graphql"},qQ={globalGatewayUrl:"http://localhost:4000/global/graphql",workspaceGatewayUrl:"http://localhost:4003/workspaces/graphql"},Fq={default:{...y}},kQ={local:{...qQ},alpha:{...eq},prod:{...y}},C="default",bq=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;function f(q){if(!bq.test(q))throw Error("Profile name must use 1-64 characters: letters, numbers, dot, underscore, or dash.");return q}function Oq(){return E(V(),"profiles")}function i(){return E(V(),"active")}function O(q){return E(Oq(),`${f(q)}.json`)}function QQ(){let q=i();if(!G(q))return C;try{let Q=D(q,"utf8").trim();if(!Q)return C;return f(Q)}catch{return C}}function $Q(q){let Q=f(q),$=i();I(h($),{recursive:!0});let z=`${$}.${process.pid}.tmp`;F(z,`${Q}
|
|
7
|
-
`,{mode:384}),v(z,$)}function _Q(){let q=Oq();if(!G(q))return[];return rq(q,{withFileTypes:!0}).filter((Q)=>Q.isFile()&&Q.name.endsWith(".json")).map((Q)=>Q.name.slice(0,-5)).filter((Q)=>bq.test(Q)).sort()}function zQ(q){let Q=O(q);if(!G(Q))return{};try{return l(D(Q,"utf8"))}catch{return{}}}function Nq(q,Q){let $=JSON.parse(q);if(!$||typeof $!=="object"||Array.isArray($))throw Error(`${Q} is not a JSON object`);return $}function uQ(q){let Q=O(q);if(!G(Q))return{};return Nq(D(Q,"utf8"),`Profile ${Q}`)}function ZQ(q,Q){let $=f(q),z=O($);I(h(z),{recursive:!0});let Z={schemaVersion:B,...Q},J={...Z};for(let W of b){let H=J[W];if(typeof H==="string"&&H.length>0)u(T($,W),H).catch(()=>{});delete J[W]}let X=`${z}.${process.pid}.tmp`;return F(X,`${JSON.stringify(J,null,2)}
|
|
8
|
-
`,{mode:384}),v(X,z),Z}function xQ(q){let Q=O(q);if(!G(Q))return!1;return iq(Q,{force:!0}),!0}function JQ(q,Q={}){let $=Fq[q];return{schemaVersion:B,globalGatewayUrl:$.globalGatewayUrl,workspaceGatewayUrl:$.workspaceGatewayUrl,...Q}}function XQ(){let q={created:[],activeWritten:null};for(let Q of Object.keys(Fq))if(!G(O(Q)))ZQ(Q,JQ(Q)),q.created.push(Q);if(!G(i()))$Q(C),q.activeWritten=C;return q}function HQ(){return{...y}}function a(q){let Q=q?.dir??Cq();return E(Q,"config.json")}function YQ(){return{...y}}function IQ(q={}){let Q=HQ();return{schemaVersion:B,globalGatewayUrl:Q.globalGatewayUrl,workspaceGatewayUrl:Q.workspaceGatewayUrl,...q}}function l(q){try{let Q=JSON.parse(q);if(Q&&typeof Q==="object")return Q}catch{}return{}}function n(q){let Q=a(q);if(!G(Q))return{};let $;try{let Z=D(Q,"utf8");$=q?.strict?Nq(Z,`Agent config ${Q}`):l(Z)}catch(Z){if(q?.strict)throw Z;return{}}if(($.schemaVersion??0)>=B)return $;for(let Z of tq){if(Z.from<($.schemaVersion??0))continue;$=Z.apply($),$.schemaVersion=Z.to}if($.schemaVersion!==B)$.schemaVersion=B;if(!q?.strict)try{F(Q,JSON.stringify($,null,2),{mode:384})}catch{}return $}function vQ(q){let Q=n(q);if(Q.agentInstanceId)return Q.agentInstanceId;let $=aq();return WQ({agentInstanceId:$},q),$}function WQ(q,Q){let $=a(Q);I(h($),{recursive:!0});let z=G($)?l(D($,"utf8")):{},Z={...z},J={...z};for(let H of b)delete J[H];let X=Q?.scope??S();for(let[H,Y]of Object.entries(q)){if(Y===void 0||Y==="")continue;if(Z[H]=Y,wq(H)&&typeof Y==="string"){u(T(X,H),Y).catch(()=>{});continue}J[H]=Y}let W=`${$}.${process.pid}.tmp`;return F(W,`${JSON.stringify(J,null,2)}
|
|
9
|
-
`,{mode:384}),v(W,$),Z}async function hQ(q,Q){let $=a(Q);return U(nq($),async()=>{I(h($),{recursive:!0});let z=G($)?l(D($,"utf8")):{},Z={...z},J={...z};for(let Y of b)delete J[Y];let X=Q?.scope??S(),W=[];for(let[Y,M]of Object.entries(q)){if(M===void 0||M==="")continue;if(Z[Y]=M,wq(Y)&&typeof M==="string"){W.push(u(T(X,Y),M));continue}J[Y]=M}await Promise.all(W);let H=`${$}.${process.pid}.tmp`;return F(H,`${JSON.stringify(J,null,2)}
|
|
10
|
-
`,{mode:384}),v(H,$),Z})}async function EQ(q){let Q=n({dir:q?.dir,strict:q?.strict}),$=q?.scope??S();for(let z of b){if(Q[z])continue;try{let Z=await _(T($,z));if(Z)Q[z]=Z}catch(Z){if(q?.strict)throw Z}}return Q}function jQ(){return zQ(QQ())}function j(q){if(!q)return null;try{return new URL(q).origin}catch{return null}}function SQ(q,Q=new Date().toISOString()){let $={pairedAt:Q},z=j(q.globalGatewayUrl);if(z)$.globalGatewayOrigin=z;let Z=j(q.workspaceGatewayUrl);if(Z)$.workspaceGatewayOrigin=Z;if(q.workspaceId)$.workspaceId=q.workspaceId;if(q.agentRecordId)$.agentRecordId=q.agentRecordId;return $}function GQ(q){if(!Boolean(q.clientId||q.pairedIdentity||q.workspaceId||q.agentRecordId))return null;let $=q.pairedIdentity,z={workspaceId:$?.workspaceId??q.workspaceId,globalGatewayUrl:j($?.globalGatewayOrigin??q.globalGatewayUrl)??void 0,workspaceGatewayUrl:j($?.workspaceGatewayOrigin??q.workspaceGatewayUrl)??void 0};if(Boolean(z.workspaceId||z.globalGatewayUrl||z.workspaceGatewayUrl))return z;return null}function yQ(q,Q){let $=GQ(q);if(!$)return null;let z=t($,Q);if(!z.length)return null;let Z=w($),J=q.pairedIdentity?.pairedAt;return`${q.clientId?`This agent is already paired with ${Z}.`:`This agent holds no credential right now, but it is still bound to ${Z}${J?` (paired ${J})`:""} \u2014 a cleared `+"secrets store is not an unpaired agent."} Refusing a credential push from ${w(Q)} (${z.join("; ")}): it would overwrite the only credential slot and strand the existing pairing on 401. Re-send with "force": true to repair deliberately, or run the other environment under its own profile (VIBECONTROLS_PROFILE).`}function fQ(q,Q,$){let z=t({globalGatewayUrl:q.globalGatewayUrl,workspaceGatewayUrl:q.workspaceGatewayUrl},{...Q,workspaceId:void 0});if(!z.length)return null;let Z=j(q.globalGatewayUrl)??j(q.workspaceGatewayUrl)??"its configured gateway";return`Profile "${$}" is configured for ${Z}, but this credential push is for ${w(Q)} (${z.join("; ")}). Accepting it would repoint the profile `+"without saying so \u2014 the agent would run against one environment while "+`"${$}" still describes another. Run that environment under its own profile (VIBECONTROLS_PROFILE=<name>, or \`vibe profile create <name>\`), or re-send with "force": true to repoint "${$}" deliberately.`}function w(q){return`${j(q.globalGatewayUrl)??"unknown gateway"} (workspace ${q.workspaceId??"unknown"})`}function t(q,Q){let $=[],z=j(q.globalGatewayUrl),Z=j(Q.globalGatewayUrl);if(z&&Z&&z!==Z)$.push(`global gateway ${z} -> ${Z}`);let J=j(q.workspaceGatewayUrl),X=j(Q.workspaceGatewayUrl);if(J&&X&&J!==X)$.push(`workspace gateway ${J} -> ${X}`);if(q.workspaceId&&Q.workspaceId&&q.workspaceId!==Q.workspaceId)$.push(`workspace ${q.workspaceId} -> ${Q.workspaceId}`);return $}function lQ(q,Q){if(!q.clientId)return null;let $=t(q,Q);if(!$.length)return null;return`Credentials were issued for ${w(q)} but this agent is configured for ${w(Q)} (${$.join("; ")}). `+"They cannot authenticate there \u2014 re-pair the agent from the environment "+"it should belong to, or clear the conflicting environment override (VIBE_GLOBAL_GATEWAY_URL / VIBE_WORKSPACE_GATEWAY_URL / VIBE_WORKSPACE_ID)."}var x=null;function gQ(){return{...x??{}}}function mQ(){x=null}function dQ(){try{XQ()}catch{}let q=jQ(),Q=n(),$={...q,...Q};if(x===null)x={globalGatewayUrl:process.env.VIBE_GLOBAL_GATEWAY_URL,workspaceGatewayUrl:process.env.VIBE_WORKSPACE_GATEWAY_URL};let z=(J,X)=>{if(!process.env[J]&&X)process.env[J]=X};z("VIBE_WORKSPACE_ID",$.workspaceId),z("VIBE_ORGANIZATION_ID",$.organizationId);let Z=YQ();return z("VIBE_GLOBAL_GATEWAY_URL",$.globalGatewayUrl??Z.globalGatewayUrl),z("VIBE_WORKSPACE_GATEWAY_URL",$.workspaceGatewayUrl??Z.workspaceGatewayUrl),z("VIBE_STORAGE_ADAPTER",$.storageAdapter),z("VIBECONTROLS_PLUGIN_INSTALL_SCOPE",$.pluginInstallScope),$}async function oQ(){let q=($,z)=>{if(!process.env[$]&&z)process.env[$]=z},Q=S();try{let $=await _(T(Q,"clientId"));q("VIBE_CLIENT_ID",$??void 0)}catch{}try{let $=await _(T(Q,"clientSecret"));q("VIBE_CLIENT_SECRET",$??void 0)}catch{}}
|
|
11
|
-
export{_ as Wc,u as Xc,CQ as Yc,wQ as Zc,B as _c,Fq as $c,kQ as ad,C as bd,f as cd,Oq as dd,i as ed,O as fd,QQ as gd,$Q as hd,_Q as id,zQ as jd,uQ as kd,ZQ as ld,xQ as md,JQ as nd,XQ as od,HQ as pd,a as qd,YQ as rd,IQ as sd,n as td,vQ as ud,WQ as vd,hQ as wd,EQ as xd,jQ as yd,j as zd,SQ as Ad,GQ as Bd,yQ as Cd,fQ as Dd,lQ as Ed,gQ as Fd,mQ as Gd,dQ as Hd,oQ as Id};
|
package/dist/index-2sn36kaj.js
DELETED
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{ae as H}from"./index-qqq9qyy6.js";import{ne as Q,qe as U}from"./index-gz5t0vvc.js";import{existsSync as Z,mkdirSync as $,readFileSync as x,appendFileSync as k,writeFileSync as A}from"fs";import{join as V,relative as b,resolve as M,isAbsolute as j}from"path";var z=".boff/",F=new Set([".boff",".boff/","/.boff","/.boff/"]);function u(){$(Q(),{recursive:!0}),f()}function f(){let W=M(U()),J=M(process.cwd()),K=b(J,W);if(K.startsWith("..")||j(K))return;let q=V(J,".gitignore");if(!Z(q)){A(q,`${z}
|
|
3
|
-
`,{mode:420}),H().logger.info("bootstrap",`Created .gitignore with ${z}`);return}let B=x(q,"utf8");if(B.split(/\r?\n/).some((Y)=>{let C=Y.trim();if(!C||C.startsWith("#"))return!1;return F.has(C)}))return;let X=B.length>0&&!B.endsWith(`
|
|
4
|
-
`);k(q,`${X?`
|
|
5
|
-
`:""}${z}
|
|
6
|
-
`),H().logger.info("bootstrap",`Appended ${z} to .gitignore`)}
|
|
7
|
-
export{u as t};
|
package/dist/index-3p4n7nwg.js
DELETED
|
@@ -1,83 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{Cb as v,Fb as k,Gb as a,Hb as y,Pb as T,Qb as x,xb as r}from"./index-vnxqna70.js";import{Zb as B}from"./index-jbxh0ffn.js";import{Yd as e,ae as j}from"./index-qqq9qyy6.js";function w(Q,J){let $=new B,Z=[],G=new Set;function Y(z){return z.endsWith("/")&&z!=="/"?z.slice(0,-1):z}function U(z,H){if(!H.startsWith("/"))return null;if(H==="/"||H.includes("..")||H.includes("*"))return null;let F=Y(z),X=Y(`${F}${H}`);if(X===F||!X.startsWith(`${F}/`))return null;return X}function V(z){if(!z.createRoutes)return!1;if(G.has(z.name))return!1;let H=z.apiPrefix||`/api/${z.name}`;try{let F=z.createRoutes(J);if(j().logger.info("plugin-router",`Plugin '${z.name}' registered routes`,{prefix:H}),$.use(new B({prefix:H}).derive(()=>({pluginContext:{chain:[z.name],parentPlugin:void 0,activePlugin:z.name}})).use(F)),z.publicPaths)for(let X of z.publicPaths){let K=U(H,X);if(!K){j().logger.warn("plugin-router",`Ignoring unsafe public path from plugin '${z.name}'`,{publicPath:X,prefix:H});continue}Z.push(K)}return G.add(z.name),!0}catch(F){return j().logger.error("plugin-router",`Failed to mount routes for plugin '${z.name}'`,{error:String(F)}),!1}}for(let z of Q.getAllPlugins())V(z);return{routes:$,getPublicPaths:()=>[...Z],mountPlugin:V}}import{EventEmitter as VJ}from"events";var u=1e4;function L(Q,J){let $=process.env[Q];if(!$)return J;let Z=Number.parseInt($,10);return Number.isFinite(Z)&&Z>0?Z:J}function ZJ(){return[{name:"health",match:(Q)=>Q.startsWith("/health"),perMinute:L("VIBECONTROLS_RATELIMIT_HEALTH",1000)},{name:"gateway-auth",match:(Q)=>Q.startsWith("/api/agent/gateway-auth"),perMinute:L("VIBECONTROLS_RATELIMIT_GATEWAY_AUTH",10)},{name:"plugin-install",match:(Q)=>Q.startsWith("/api/plugins/install"),perMinute:L("VIBECONTROLS_RATELIMIT_PLUGIN_INSTALL",5)},{name:"alias-exec",match:(Q)=>/^\/api\/aliases\/[^/]+\/execute/.test(Q),perMinute:L("VIBECONTROLS_RATELIMIT_ALIAS_EXEC",30)},{name:"api",match:(Q)=>Q.startsWith("/api/"),perMinute:L("VIBECONTROLS_RATELIMIT_API",100)}]}function $J(Q,J,$){for(let Z of Q)if(Z.match(J,$))return Z;return null}function R(Q){if(!Q)return!1;return Q==="127.0.0.1"||Q==="::1"||Q==="::ffff:127.0.0.1"||Q.startsWith("127.")}function GJ(Q=Date.now){let J=new Map,$=(Z,G)=>{J.delete(Z),J.set(Z,G)};return{take(Z,G,Y){let U=Q(),V=J.get(Z);if(!V)V={tokens:G,lastRefillMs:U,capacity:G,refillPerSec:Y};else{let H=(U-V.lastRefillMs)/1000;V.tokens=Math.min(G,V.tokens+H*Y),V.lastRefillMs=U,V.capacity=G,V.refillPerSec=Y}let z=V.tokens>=1;if(z)V.tokens-=1;if($(Z,V),J.size>u){let H=J.keys();while(J.size>u){let F=H.next();if(F.done)break;J.delete(F.value)}}return z},retryAfterSec(Z){let G=J.get(Z);if(!G)return 1;if(G.refillPerSec<=0)return 60;let Y=1-G.tokens;if(Y<=0)return 0;return Math.max(1,Math.ceil(Y/G.refillPerSec))},size(){return J.size},reset(){J.clear()}}}function SJ(Q={}){let J=Q.classes??ZJ(),$=Q.store??GJ();return new B({name:"plugin/rate-limit"}).onRequest(({request:Z,set:G,server:Y})=>{let U;try{U=Y?.requestIP(Z)?.address??null}catch{U=null}if(R(U))return;let V=new URL(Z.url),z=$J(J,V.pathname,Z.method);if(!z)return;let F=`${U??"unknown"}|${z.name}`,X=z.perMinute/60;if(!$.take(F,z.perMinute,X)){let K=$.retryAfterSec(F);G.status=429;let P=G.headers??={};return P["Retry-After"]=String(K),{error:"rate_limited",message:`Too many requests for ${z.name}; retry after ${K}s.`,retryAfterSec:K}}}).as("global")}var YJ=(()=>{let Q=process.env.VIBECONTROLS_WS_MAX_PER_IP,J=Q?Number.parseInt(Q,10):NaN;return Number.isFinite(J)&&J>0?J:5})();function C(Q=YJ){let J=new Map;return{accept($,Z){if(R($))return!0;let G=$??"unknown",Y=J.get(G);if(!Y)Y=new Set,J.set(G,Y);if(Y.size>=Q)return!1;return Y.add(Z),!0},release($,Z){if(R($))return;let G=$??"unknown",Y=J.get(G);if(!Y)return;if(Y.delete(Z),Y.size===0)J.delete(G)},size($){let Z=$??"unknown";return J.get(Z)?.size??0}}}function c(Q){let J=new Set,$=new Map,Z=new Map;return{accept(G,Y,U){if(J.size>=Q.maxGlobal)return!1;let V=$.get(G)??new Set;if(V.size>=Q.maxPerKey)return!1;let z=Y??"unknown";if(!R(Y)){let H=Z.get(z)??new Set;if(H.size>=Q.maxPerIp)return!1;H.add(U),Z.set(z,H)}return J.add(U),V.add(U),$.set(G,V),!0},release(G,Y,U){J.delete(U);let V=$.get(G);if(V){if(V.delete(U),V.size===0)$.delete(G)}if(!R(Y)){let z=Y??"unknown",H=Z.get(z);if(H){if(H.delete(U),H.size===0)Z.delete(z)}}},globalCount(){return J.size},keyCount(G){return $.get(G)?.size??0}}}function _(Q,J){let $=process.env[Q];if(!$)return J;let Z=Number.parseInt($,10);return Number.isFinite(Z)&&Z>0?Z:J}var m={maxGlobal:_("VIBE_TERMINAL_WS_MAX_GLOBAL",64),maxPerKey:_("VIBE_TERMINAL_WS_MAX_PER_SESSION",4),maxPerIp:_("VIBE_TERMINAL_WS_MAX_PER_IP",16)},LJ={maxGlobal:_("VIBE_CODE_SERVER_WS_MAX_GLOBAL",64),maxPerKey:_("VIBE_CODE_SERVER_WS_MAX_PER_SESSION",8),maxPerIp:_("VIBE_CODE_SERVER_WS_MAX_PER_IP",16)};function UJ(Q){if(!Q)return new Set;let J=new Set;for(let $ of Q.split(",")){let Z=$.trim();if(Z)J.add(Z)}return J}var D=null;function zJ(){let Q=process.env.VIBE_TRUSTED_PROXIES;if(!D||D.raw!==Q)D={raw:Q,set:UJ(Q)};return D.set}function E(Q,J){let $=zJ();if(!!Q&&(R(Q)||$.has(Q))&&J){let G=J["x-forwarded-for"];if(G){let U=G.split(",")[0]?.trim();if(U)return U}let Y=J["x-real-ip"];if(Y)return Y}return Q}var d=C(),h=new VJ;h.setMaxListeners(100);function b(Q,J){let $={type:Q,payload:J,timestamp:new Date().toISOString()};h.emit("ws:event",$)}var p=(()=>{let Q=process.env.VIBECONTROLS_MAX_WS_CLIENTS,J=Q?Number.parseInt(Q,10):NaN;return Number.isFinite(J)&&J>0?J:200})(),HJ=(()=>{let Q=process.env.VIBECONTROLS_MAX_WS_BUFFER_PER_CLIENT,J=Q?Number.parseInt(Q,10):NaN;return Number.isFinite(J)&&J>0?J:100})();function XJ(){let Q=new Set;return h.on("ws:event",(J)=>{let $=JSON.stringify(J);for(let Z of Q){if(Z.pendingSends>=HJ){if(Z.drops+=1,Z.drops===1||Z.drops%100===0)j().logger.warn("ws-events",`Dropping events for slow client (${Z.drops} dropped)`);continue}try{Z.send($)}catch{}}}),new B().ws("/ws/events",{open(J){if(Q.size>=p){j().logger.warn("ws-events",`MAX_WS_CLIENTS exceeded (${Q.size}/${p}); refusing new connection`),J.close(1013,"Server overloaded");return}let $=J.data,Z=T($.headers??{});if(!x(Z)){J.close(1008,"Unauthorized: invalid or missing API key");return}let G=J.remoteAddress??null,Y=E(G,$.headers);if(!d.accept(Y??null,J)){J.close(1008,"too many connections");return}J._remoteIp=Y??null;let U={ws:J,channels:new Set,pendingSends:0,drops:0,send:(V)=>{U.pendingSends+=1;try{J.send(V)}finally{queueMicrotask(()=>{U.pendingSends=Math.max(0,U.pendingSends-1)})}}};Q.add(U),J._client=U,j().logger.debug("ws-events","Client connected",{id:String(J.id||"unknown")}),J.send(JSON.stringify({type:"connected",timestamp:new Date().toISOString()}))},message(J,$){try{let Z=typeof $==="string"?JSON.parse($):$;switch(Z.type){case"subscribe":{let G=J._client;if(G)G.channels.add(Z.channel);j().logger.debug("ws-events",`Subscribed to ${Z.channel}`);break}case"unsubscribe":{let G=J._client;if(G)G.channels.delete(Z.channel);j().logger.debug("ws-events",`Unsubscribed from ${Z.channel}`);break}case"ping":J.send(JSON.stringify({type:"pong",timestamp:new Date().toISOString()}));break;default:j().logger.debug("ws-events",`Unknown message type: ${Z.type}`)}}catch{j().logger.warn("ws-events","Failed to parse incoming message")}},close(J){let $=J._client;if($)Q.delete($);let Z=J._remoteIp;d.release(Z??null,J),j().logger.debug("ws-events","Client disconnected")}})}var g=c(m),FJ=256,jJ=1048576,KJ=1e4;async function l(Q,J,$,Z,G,Y){let U={};for(let[z,H]of Object.entries(G))if(H&&!["host","connection"].includes(z.toLowerCase()))U[z]=H;let V={method:Z,headers:U};if(Z!=="GET"&&Z!=="HEAD"&&Y)V.body=typeof Y==="string"?Y:JSON.stringify(Y);return fetch(`http://${Q}:${J}${$}`,V)}async function I(Q,J){let $=Q.listProvidersForType("session");for(let{pluginName:Z}of $){let G=Q.getProviderByName("session",Z);if(!G)continue;let Y=await G.getTerminalInfo(J);if(!Y)continue;try{process.kill(Y.pid,0)}catch{continue}let U=Y;return{host:U.host??"127.0.0.1",port:Y.port,wsPath:U.wsPath??"/ws",subprotocols:U.subprotocols??["tty"]}}return null}var M=new Map,NJ=0,q=new Map,o=30000;function A(Q){g.release(Q.sessionId,Q.remoteIp,Q.capRef)}function BJ(Q){return typeof Q==="string"?Buffer.byteLength(Q):Q.byteLength}function n(Q){let J=new Headers(Q.headers);return J.set("Permissions-Policy","clipboard-read=(self), clipboard-write=(self)"),J.delete("X-Frame-Options"),new Response(Q.body,{status:Q.status,headers:J})}function i(Q){return`<!doctype html>
|
|
3
|
-
<html>
|
|
4
|
-
<head>
|
|
5
|
-
<meta charset="utf-8">
|
|
6
|
-
<title>Loading terminal\u2026</title>
|
|
7
|
-
<style>
|
|
8
|
-
body { font: 14px/1.4 system-ui, -apple-system, sans-serif; color: #ccc; background: #111; padding: 2rem; }
|
|
9
|
-
.err { color: #f88; }
|
|
10
|
-
</style>
|
|
11
|
-
</head>
|
|
12
|
-
<body>
|
|
13
|
-
<p id="status">Loading terminal\u2026</p>
|
|
14
|
-
<script>
|
|
15
|
-
(async () => {
|
|
16
|
-
const SID = '${Q.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}';
|
|
17
|
-
const statusEl = document.getElementById('status');
|
|
18
|
-
function fail(msg) {
|
|
19
|
-
statusEl.textContent = msg;
|
|
20
|
-
statusEl.className = 'err';
|
|
21
|
-
}
|
|
22
|
-
// Ask the parent window for a fresh capability mint. The microfe
|
|
23
|
-
// hosts the iframe and owns the GraphQL connection to mint a new
|
|
24
|
-
// TERMINAL_SESSION capability. Reply shape: { type: 'vt-token',
|
|
25
|
-
// token: string } or { type: 'vt-token-failed', reason: string }.
|
|
26
|
-
function requestFreshToken() {
|
|
27
|
-
if (window.parent === window) return; // standalone open, no parent
|
|
28
|
-
window.parent.postMessage({ type: 'vt-token-request', sid: SID }, '*');
|
|
29
|
-
}
|
|
30
|
-
const m = location.hash.match(/[#&]vt=([^&]+)/);
|
|
31
|
-
if (!m) { fail('Missing terminal token'); return; }
|
|
32
|
-
const token = decodeURIComponent(m[1]);
|
|
33
|
-
// Use the canonical profile-scoped URL form so the request works on:
|
|
34
|
-
// - agents that still enforce 410-Gone on bare /api/* (older code)
|
|
35
|
-
// - agents with the bare-path fallback (newer code) \u2014 bare and
|
|
36
|
-
// profile-scoped paths both route to the same handler
|
|
37
|
-
// We don't know which profile the session was created under at
|
|
38
|
-
// render time, so we default to 'default'. The cookie-shim is
|
|
39
|
-
// process-scoped (signing secret is the same regardless of which
|
|
40
|
-
// profile path the exchange came through), so this is safe.
|
|
41
|
-
const exchangeUrl = '/api/profiles/default/agent/terminal-exchange';
|
|
42
|
-
let r;
|
|
43
|
-
try {
|
|
44
|
-
r = await fetch(exchangeUrl, {
|
|
45
|
-
method: 'POST',
|
|
46
|
-
headers: { 'content-type': 'application/json' },
|
|
47
|
-
credentials: 'include',
|
|
48
|
-
body: JSON.stringify({ sid: SID, token: token })
|
|
49
|
-
});
|
|
50
|
-
} catch (e) {
|
|
51
|
-
fail('Terminal authentication failed: network error');
|
|
52
|
-
return;
|
|
53
|
-
}
|
|
54
|
-
if (!r.ok) {
|
|
55
|
-
// Parse the agent's reason code (added in the agent route for
|
|
56
|
-
// diagnostics). On 'expired'/'replayed' the right move is to ask
|
|
57
|
-
// the host frame for a fresh token rather than dead-ending.
|
|
58
|
-
let code = 'invalid';
|
|
59
|
-
try {
|
|
60
|
-
const body = await r.json();
|
|
61
|
-
if (body && typeof body.code === 'string') code = body.code;
|
|
62
|
-
} catch { /* response had no JSON body */ }
|
|
63
|
-
if (code === 'expired' || code === 'replayed') {
|
|
64
|
-
statusEl.textContent = 'Refreshing terminal token...';
|
|
65
|
-
requestFreshToken();
|
|
66
|
-
// The host frame is expected to update the iframe src with a
|
|
67
|
-
// fresh #vt= hash, which causes a fresh navigation. No
|
|
68
|
-
// further action here.
|
|
69
|
-
return;
|
|
70
|
-
}
|
|
71
|
-
if (code === 'expired') fail('Terminal token expired \u2014 please refresh');
|
|
72
|
-
else if (code === 'replayed') fail('Terminal token already used \u2014 please refresh');
|
|
73
|
-
else fail('Terminal authentication failed');
|
|
74
|
-
return;
|
|
75
|
-
}
|
|
76
|
-
const url = new URL(location.href);
|
|
77
|
-
url.hash = '';
|
|
78
|
-
location.replace(url.toString());
|
|
79
|
-
})();
|
|
80
|
-
</script>
|
|
81
|
-
</body>
|
|
82
|
-
</html>`}function MJ(Q){return new B().all("/terminal/:sessionId",async({params:J,request:$,set:Z})=>{let G=J.sessionId,Y=y($,G);if(!Y||!k(Y,G)){if($.method==="GET")return Z.status=200,Z.headers["content-type"]="text/html; charset=utf-8",i(G);return Z.status=401,{error:"Unauthorized: terminal cookie required"}}let U=await I(Q,G);if(!U)return Z.status=502,{error:"Terminal not running for this session"};let V=await l(U.host,U.port,"/",$.method,Object.fromEntries(Object.entries($.headers).map(([z,H])=>[z,H])));return Z.status=V.status,n(V)}).all("/terminal/:sessionId/*",async({params:J,request:$,set:Z})=>{let G=J.sessionId,Y=J["*"]||"",U=y($,G);if(!U||!k(U,G)){if($.method==="GET"&&(Y===""||Y==="/"))return Z.status=200,Z.headers["content-type"]="text/html; charset=utf-8",i(G);return Z.status=401,{error:"Unauthorized: terminal cookie required"}}let V=await I(Q,G);if(!V)return Z.status=502,{error:"Terminal not running for this session"};let z=await l(V.host,V.port,`/${Y}`,$.method,Object.fromEntries(Object.entries($.headers).map(([H,F])=>[H,F])));return Z.status=z.status,n(z)}).ws("/terminal/:sessionId/ws",{open(J){let $=J.data,Z=$.params?.sessionId;if(!Z){J.close(1008,"Missing sessionId");return}if(!r(Z)){J.close(1008,"Invalid sessionId");return}let G=a($.headers??{},Z),Y=!!G&&k(G,Z),U=$.query?.vt,V=!!U&&v(U,`/terminal/${Z}`,"GET");if(!Y&&!V){J.close(1008,"Unauthorized: invalid or missing terminal credentials");return}let z=J.remoteAddress??null,H=E(z,$.headers),F=`bridge-${++NJ}`;if($._bridgeId=F,!g.accept(Z,H,F)){j().logger.warn("terminal-ws",`Terminal WS cap exceeded for session ${Z} (ip=${H??"unknown"})`),J.close(1013,"too many connections");return}$._remoteIp=H;let X={upstream:null,upstreamReady:!1,buffer:[],bufferBytes:0,openTimer:null,sessionId:Z,remoteIp:H,capRef:F};M.set(F,X),j().logger.debug("terminal-ws",`Client connected for session ${Z} (${F})`),I(Q,Z).then((K)=>{if(M.get(F)!==X)return;if(!K){let O=q.get(Z)??0,N=Date.now();if(q.size>50){let f=N-o*2;for(let[JJ,QJ]of q)if(QJ<f)q.delete(JJ)}if(N-O>o)j().logger.warn("terminal-ws",`No terminal running for session ${Z}`),q.set(Z,N);A(X),M.delete(F),J.close(1011,"No terminal running");return}let P=`ws://${K.host}:${K.port}${K.wsPath}`,W=new WebSocket(P,K.subprotocols);X.upstream=W,X.openTimer=setTimeout(()=>{A(X),M.delete(F);try{W.close(1011,"upstream open timeout")}catch{}try{J.close(1011,"Upstream open timeout")}catch{}},KJ),W.addEventListener("open",()=>{if(X.openTimer)clearTimeout(X.openTimer),X.openTimer=null;X.upstreamReady=!0,j().logger.debug("terminal-ws",`Bridge established \u2192 port ${K.port}, buffered=${X.buffer.length}`,{sessionId:Z});for(let O of X.buffer)W.send(O);X.buffer.length=0,X.bufferBytes=0}),W.addEventListener("message",(O)=>{try{let N=O.data;if(N instanceof ArrayBuffer)J.send(new Uint8Array(N));else if(N instanceof Blob)N.arrayBuffer().then((f)=>{try{J.send(new Uint8Array(f))}catch{}});else J.send(N)}catch(N){j().logger.error("terminal-ws",`Failed to forward upstream\u2192client: ${N}`,{sessionId:Z})}}),W.addEventListener("close",(O)=>{if(X.openTimer)clearTimeout(X.openTimer),X.openTimer=null;j().logger.debug("terminal-ws",`Upstream closed (code=${O.code})`,{sessionId:Z}),A(X),M.delete(F);try{J.close(1000,"Upstream closed")}catch{}}),W.addEventListener("error",(O)=>{if(X.openTimer)clearTimeout(X.openTimer),X.openTimer=null;j().logger.error("terminal-ws","Upstream error",{sessionId:Z}),A(X),M.delete(F);try{J.close(1011,"Upstream error")}catch{}})}).catch((K)=>{A(X),M.delete(F),j().logger.warn("terminal-ws","Failed to resolve terminal endpoint",{sessionId:Z,error:String(K)});try{J.close(1011,"Failed to resolve terminal")}catch{}})},message(J,$){let G=J.data._bridgeId;if(!G)return;let Y=M.get(G);if(!Y)return;let U;if(typeof $==="string")U=$;else if($ instanceof ArrayBuffer)U=$;else if($ instanceof Uint8Array||Buffer.isBuffer($)){let V=new ArrayBuffer($.byteLength);new Uint8Array(V).set(new Uint8Array($.buffer,$.byteOffset,$.byteLength)),U=V}else if(typeof $==="object"&&$!==null)U=JSON.stringify($);else U=String($);if(Y.upstream&&Y.upstreamReady&&Y.upstream.readyState===WebSocket.OPEN)try{Y.upstream.send(U)}catch(V){j().logger.error("terminal-ws",`Failed to forward client\u2192upstream: ${V}`,{sessionId:Y.sessionId})}else{let V=BJ(U);if(Y.buffer.length>=FJ||Y.bufferBytes+V>jJ){A(Y),M.delete(G);try{J.close(1013,"Terminal buffer limit exceeded")}catch{}return}Y.buffer.push(U),Y.bufferBytes+=V}},close(J){let $=J.data,Z=$._bridgeId,G=$.params?.sessionId;if(j().logger.debug("terminal-ws","Client disconnected",{sessionId:G}),Z){let Y=M.get(Z);if(Y?.upstream&&Y.upstream.readyState===WebSocket.OPEN)Y.upstream.close(1000,"Client disconnected");if(Y?.openTimer)clearTimeout(Y.openTimer);if(Y)A(Y);M.delete(Z)}if(G&&Z)g.release(G,$._remoteIp??null,Z)}})}var t=C(),s={debug:0,info:1,warn:2,error:3};function OJ(Q){return Q==="debug"||Q==="info"||Q==="warn"||Q==="error"?Q:null}function WJ(){return new B().ws("/ws/logs",{open(Q){let J=Q.data,$=T(J.headers??{}),Z=J.query?.vt,G=x($),Y=!!Z&&v(Z,"/ws/logs","GET");if(!G&&!Y){Q.close(1008,"Unauthorized: invalid or missing credentials");return}let U=Q.remoteAddress??null,V=E(U,J.headers);if(!t.accept(V??null,Q)){Q.close(1008,"too many connections");return}Q._remoteIp=V??null,j().logger.info("ws-logs","Log stream client connected");let z={minLevel:"info",source:""};Q._filters=z;let H=(F)=>{let X=Q._filters;if(s[F.level]<s[X.minLevel])return;if(X.source&&!F.source.includes(X.source))return;try{Q.send(JSON.stringify(F))}catch{}};j().logger.on("log",H),Q._logHandler=H,Q.send(JSON.stringify({type:"connected",timestamp:new Date().toISOString()}))},message(Q,J){try{let $=typeof J==="string"?JSON.parse(J):J;if($.type==="filter"){let Z=Q._filters,G=OJ($.level);if(G)Z.minLevel=G;if(typeof $.source==="string")Z.source=$.source.slice(0,128);Q.send(JSON.stringify({type:"filter-updated",filters:Z}))}}catch{}},close(Q){let J=Q._logHandler;if(J)j().logger.removeListener("log",J);let $=Q._remoteIp;t.release($??null,Q),j().logger.info("ws-logs","Log stream client disconnected")}})}var S=new Map;function tJ(Q,J){if(!Q.db||!Q.serviceRegistry||!Q.pluginManager)throw Error(`mountProfileRoutes: profile '${Q.name}' has no attached services`);let $={db:Q.db,serviceRegistry:Q.serviceRegistry,pluginManager:Q.pluginManager,broadcast:b,hostServices:Q.hostServices??void 0,rebuildPluginSurfaces:J?.rebuildPluginSurfaces,mountPlugin:J?.mountPlugin,app:J?.app},{routes:Z}=w(Q.pluginManager,$);S.set(Q.name,{ctx:Q,router:Z})}function sJ(Q){return S.delete(Q)}async function eJ(Q,J,$){let Z=S.get(Q);if(!Z)return null;e(Z.ctx);let G=new URL(J.url),U=`/api${G.pathname.replace(/^\/api\/profiles\/[^/]+/,"")}${G.search}`,V=new Headers(J.headers),z={method:J.method,headers:V};if(J.method!=="GET"&&J.method!=="HEAD")if($!==void 0)z.body=$;else z.body=J.body,z.duplex="half";let H=new Request(`${G.origin}${U}`,z);return Z.router.handle(H)}function JQ(){return[...S.keys()].sort()}function QQ(){S.clear()}function ZQ(Q,J,$){S.set(Q,{ctx:J,router:$})}
|
|
83
|
-
export{w as ib,SJ as jb,c as kb,LJ as lb,E as mb,b as nb,XJ as ob,MJ as pb,WJ as qb,tJ as rb,sJ as sb,eJ as tb,JQ as ub,QQ as vb,ZQ as wb};
|
package/dist/index-3tf12pw3.js
DELETED
package/dist/index-4gsn3d9r.js
DELETED
|
@@ -1,26 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{o as w4,q as x4}from"./index-hrfkzecw.js";import{u as L5,v as v5,w as P5}from"./index-dx9hjdp4.js";import{E as R4}from"./index-6jzsthh9.js";import{U as m5,da as Z5,ea as _2,fa as q0,ga as e4,ha as J5,ia as B5,ja as Q5,la as R2,ma as s2,na as Q0,oa as w2}from"./index-qdbxvcwr.js";import{pa as u5,ua as g5,wa as S0}from"./index-xtbppqnv.js";import{za as d2}from"./index-29fmptfn.js";import{Aa as D5,Ba as f5,Ca as b5,Da as y5}from"./index-w7gctzhm.js";import{Ea as h5}from"./index-hey6w5m0.js";import{Na as w0,_a as c5}from"./index-7wejfjj9.js";import{$a as N2}from"./index-ea42kfvk.js";import{eb as g2}from"./index-rmh8pff5.js";import{ib as O5,jb as A5,kb as E5,lb as I5,mb as C5,nb as H2,ob as q5,pb as k5,qb as R5,rb as w5,tb as S5}from"./index-3p4n7nwg.js";import{Ab as F0,Bb as W4,Cb as h2,Eb as B4,Ib as I2,Jb as G0,Kb as U5,Lb as x5,Mb as C0,Nb as F2,Pb as p,Qb as n,Rb as V5,Sb as W5,Tb as M5,Ub as T5,xb as z4,yb as u2,zb as V4}from"./index-vnxqna70.js";import{Yb as z,Zb as v}from"./index-jbxh0ffn.js";import{Ad as m2,Cd as X4,Dd as Y4,Ed as r0,Fd as H4,gd as Q4,kd as $4,ld as Z4,sd as N4,td as e,ud as J4,vd as l2,wd as c2,xd as y2}from"./index-2q2jadag.js";import{Jd as k0,Kd as _5,Ld as N5,Md as j5,Nd as K2,Qd as A4,Rd as e2,Wd as l,Yd as R0,Zd as b,_d as t,ae as W,be as L0}from"./index-qqq9qyy6.js";import{de as e0,ee as L4,fe as N0,he as p2,ie as _4,ke as k2,le as i,ne as b2,pe as C2,qe as L2,re as t2}from"./index-gz5t0vvc.js";import{te as u0,we as c}from"./index-xjr60th0.js";var P0=typeof new Headers()?.toJSON==="function",d5=(Q)=>{if(P0)return Object.keys(Q.toJSON()).join(", ");let $="",Z=0;return Q.forEach((Y,X)=>{if(Z)$=$+", "+X;else $=X;Z++}),$},f0=(Q)=>{let{aot:$=!0,origin:Z=!0,methods:Y=!0,allowedHeaders:X=!0,exposeHeaders:J=!0,credentials:H=!0,maxAge:V=5,preflight:B=!0}=Q??{};if(Array.isArray(X))X=X.join(", ");if(Array.isArray(J))J=J.join(", ");let F=typeof Z==="boolean"?void 0:Array.isArray(Z)?Z:[Z],_=new v({name:"@elysiajs/cors",seed:Q,aot:$}),q=F?.some((E)=>E==="*"),A={};if(F){for(let E of F)if(typeof E==="string")A[E]=!0}let U=(E,C,G)=>{if(Array.isArray(E))return E.some((x)=>U(x,C,G));switch(typeof E){case"string":if(G in A)return!0;let x=G.indexOf("://");if(x!==-1)G=G.slice(x+3);return E===G;case"function":return E(C)===!0;case"object":if(E instanceof RegExp)return E.test(G)}return!1},K=(E,C)=>{if(Z===!0){E.headers.vary="*",E.headers["access-control-allow-origin"]=C.headers.get("Origin")||"*";return}if(q){E.headers.vary="*",E.headers["access-control-allow-origin"]="*";return}if(!F?.length)return;if(F.length){let G=C.headers.get("Origin")??"";for(let x=0;x<F.length;x++)if(U(F[x],C,G)===!0){E.headers.vary=Z?"Origin":"*",E.headers["access-control-allow-origin"]=G||"*";return}}E.headers.vary="Origin"},T=(E,C)=>{if(!C)return;if(Y===!0)return E.headers["access-control-allow-methods"]=C??"*";if(Y===!1||!Y?.length)return;if(Y==="*")return E.headers["access-control-allow-methods"]="*";if(!Array.isArray(Y))return E.headers["access-control-allow-methods"]=Y;E.headers["access-control-allow-methods"]=Y.join(", ")},I={};if(typeof J==="string")I["access-control-expose-headers"]=J;if(typeof X==="string")I["access-control-allow-headers"]=X;if(H===!0)I["access-control-allow-credentials"]="true";_.headers(I);function P({set:E,request:C,headers:G}){if(K(E,C),T(E,C.headers.get("access-control-request-method")),X===!0||J===!0){if(X===!0)E.headers["access-control-allow-headers"]=G["access-control-request-headers"];if(J===!0)E.headers["access-control-expose-headers"]=Object.keys(G).join(",")}if(V)E.headers["access-control-max-age"]=V.toString();return new Response(null,{status:204})}if(B)_.options("/",P).options("/*",P);return _.onRequest(function({set:C,request:G}){if(K(C,G),B&&G.method==="OPTIONS")return P({set:C,request:G,headers:P0?G.headers.toJSON():Object.fromEntries(G.headers.entries())});if(T(C,G.method),X===!0||J===!0){let x=d5(G.headers);if(X===!0)C.headers["access-control-allow-headers"]=x;if(J===!0)C.headers["access-control-expose-headers"]=x}})};var n5="/code-server";function b0(Q,$,Z=h2){let Y=Q.method.toUpperCase();if(Y!=="GET"&&Y!=="HEAD")return null;let X=new URL(Q.url),J=X.searchParams.get("vt");if(!J||!Z(J,n5,"GET"))return null;X.searchParams.delete("vt");let H=new Headers(Q.headers);return H.set("x-agent-api-key",$()),new Request(`${X.origin}${X.pathname}${X.search}`,{method:Q.method,headers:H})}import{createHash as c0}from"crypto";var z2="idempotency",i5=300000,y0=1e4,v2=new Map;function o5(Q,$,Z,Y){return c0("sha256").update(`${Q}|${$}|${Z}|${Y}`).digest("hex")}async function a5(Q,$){let Z=await Q.getPluginState(z2,$);if(!Z)return null;try{let Y=JSON.parse(Z);if(Y.expiresAt<Date.now())return await Q.deletePluginState(z2,$),null;return Y}catch{return null}}async function s5(Q,$,Z){await Q.setPluginState(z2,$,JSON.stringify(Z))}async function r5(Q){let $=await Q.getAllPluginState(z2),Z=Date.now(),Y=0,X=[];for(let J of $)try{if(JSON.parse(J.value).expiresAt<Z)await Q.deletePluginState(z2,J.key),Y+=1;else X.push({key:J.key,updatedAt:J.updatedAt})}catch{await Q.deletePluginState(z2,J.key),Y+=1}if(X.length>y0){X.sort((H,V)=>(H.updatedAt??"").localeCompare(V.updatedAt??""));let J=X.slice(0,X.length-y0);for(let H of J)await Q.deletePluginState(z2,H.key),Y+=1}if(Y>0)W().logger.info("idempotency",`Swept ${Y} expired/over-cap entries`)}var H0=null,t5=600000;function e5(Q){if(H0)return;H0=setInterval(()=>{let $=Q.getDb();if(!$)return;r5($).catch((Z)=>{W().logger.warn("idempotency","Sweep failed",{error:String(Z)})})},t5),H0.unref?.()}function m0(Q){return e5(Q),new v({name:"plugin/idempotency"}).onBeforeHandle(async({request:$,path:Z,set:Y,store:X})=>{if($.method!=="POST"&&$.method!=="PUT")return;let J=$.headers.get("x-idempotency-key")??$.headers.get("X-Idempotency-Key");if(!J)return;if(J.length<8||J.length>200)return Y.status=400,{error:"X-Idempotency-Key must be 8\u2013200 chars",code:"BAD_REQUEST"};let H=Q.getDb();if(!H)return;let V="no-body";try{let T=await $.clone().text();V=c0("sha256").update(T).digest("hex")}catch{}let B=o5($.method,Z,J,V),F=await a5(H,B);if(F){Y.status=F.status;let K=Y.headers??={};K["Content-Type"]=F.contentType,K["X-Idempotency-Replay"]="true",X.__idemReplay=F.body;try{return JSON.parse(F.body)}catch{return F.body}}let _=v2.get(B);if(_){let K=await _.catch(()=>null);if(K){Y.status=K.status;let T=Y.headers??={};T["Content-Type"]=K.contentType,T["X-Idempotency-Replay"]="true",X.__idemReplay=K.body;try{return JSON.parse(K.body)}catch{return K.body}}}let q,A,U=new Promise((K,T)=>{q=K,A=T});v2.set(B,U),X.__idemKey=B,X.__idemResolve=q,X.__idemReject=A}).onAfterHandle(async({response:$,set:Z,store:Y})=>{let X=Y.__idemKey;if(!X)return;let J=Y.__idemResolve,H=Q.getDb(),V=Z.status??200,B=typeof $==="string"?$:JSON.stringify($),_=Z.headers?.["Content-Type"]??"application/json",q={status:V,body:B,contentType:_,expiresAt:Date.now()+i5},A=V>=200&&V<300;try{if(H&&A)await s5(H,X,q)}catch(U){W().logger.warn("idempotency","Failed to persist response",{error:String(U)})}finally{try{J?.(A?q:null)}catch{}v2.delete(X)}}).onError(({store:$})=>{let Z=$.__idemKey;if(!Z)return;let Y=$.__idemReject;try{Y?.(Error("idempotency: handler errored"))}catch{}v2.delete(Z)}).as("global")}import g from"os";import{readFileSync as _Q}from"fs";import{join as NQ}from"path";var g0={enabled:!1,async scrape(){return`# vibecontrols agent metrics disabled (OTel SDK not initialised)
|
|
3
|
-
`},recordHttpRequest(){},setPluginsLoaded(){}},X2=null,P2=null;async function f2(Q){if(X2)return X2;if(P2)return P2;return P2=(async()=>{try{let{MeterProvider:$}=await import("./index-a8n6s2ae.js").then((m)=>u0(m.default,1)),{PrometheusExporter:Z,PrometheusSerializer:Y}=await import("./index-06es0fmw.js").then((m)=>u0(m.default,1)),X=new Z({preventServerStart:!0}),J=new Y,V=new $({readers:[X]}).getMeter("vibecontrols-agent"),B=V.createGauge("vibecontrols_agent_info",{description:"Static info about the agent process; value is always 1."});V.createObservableGauge("vibecontrols_agent_uptime_seconds",{description:"Process uptime in seconds."}).addCallback((K)=>{K.observe(process.uptime())});let _=V.createCounter("vibecontrols_http_requests_total",{description:"Total HTTP requests handled by the agent, labelled by method, route, status."}),q={};V.createObservableGauge("vibecontrols_plugins_loaded",{description:"Plugins loaded by the agent, broken down by status (loaded, failed, etc.)."}).addCallback((K)=>{for(let[T,I]of Object.entries(q))K.observe(I,{status:T})}),B.record(1,{version:Q?.version??"unknown",profile:Q?.profile??"default"});let U={enabled:!0,async scrape(){let K=await X.collect();if(!K.resourceMetrics)return"";return J.serialize(K.resourceMetrics)},recordHttpRequest(K,T,I){_.add(1,{method:K,route:T,status:String(I)})},setPluginsLoaded(K){q={...K}}};return X2=U,W().logger.info("metrics","OTel Prometheus registry initialised"),U}catch($){return W().logger.warn("metrics","Failed to initialise OTel metrics; /metrics will return a stub body",{error:$ instanceof Error?$.message:String($)}),X2=g0,g0}})(),P2}function p0(Q,$,Z){if(!X2)return;X2.recordHttpRequest(Q,$,Z)}function l0(Q){if(!X2)return;X2.setPluginsLoaded(Q)}var QQ=new Set(["127.0.0.1","::1"]),d0=!1;function $Q(){if(d0)return;if(process.env.METRICS_ANONYMOUS_LOCALHOST==="true")d0=!0,W().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 ZQ(Q){let $=Q.replace(/^\[|\]$/g,"");if($.startsWith("::ffff:"))return $.slice(7);return $}function z0(Q,$){let Z=$?.requestIP(Q)?.address;if(!Z)return!1;return QQ.has(ZQ(Z))}function n0(){return $Q(),new v({name:"routes/metrics"}).get("/metrics",async({request:Q,server:$,set:Z})=>{if(!(process.env.METRICS_ANONYMOUS_LOCALHOST==="true"&&z0(Q,$))){let H=p(Object.fromEntries(Q.headers.entries()));if(!n(H))return Z.status=401,Z.headers["content-type"]="application/json",JSON.stringify({error:"Unauthorized",message:"Invalid or missing API key"})}let J=await(await f2()).scrape();return Z.headers["content-type"]="text/plain; version=0.0.4; charset=utf-8",J})}import{randomBytes as JQ,timingSafeEqual as XQ}from"crypto";import{chmodSync as YQ,existsSync as i0,mkdirSync as HQ,readFileSync as zQ,unlinkSync as VQ,writeFileSync as WQ}from"fs";import{dirname as BQ,join as KQ}from"path";var V2=null;function o0(){return KQ(b2(),"pairing-token")}function FQ(){return JQ(32).toString("base64url")}function GQ(Q,$){let Z=Buffer.from(Q),Y=Buffer.from($);if(Z.length!==Y.length)return!1;try{return XQ(Z,Y)}catch{return!1}}function q6(){if(V2)return V2;let Q=o0();try{if(i0(Q)){let Z=zQ(Q,"utf8").trim();if(Z.length>=32)return V2=Z,Z}}catch{}let $=FQ();try{HQ(BQ(Q),{recursive:!0}),WQ(Q,$,{encoding:"utf8"});try{YQ(Q,384)}catch{}}catch(Z){}return V2=$,$}function V0(Q){if(!Q)return!1;if(!V2)return!1;return GQ(Q,V2)}function a0(){V2=null;try{let Q=o0();if(i0(Q))VQ(Q)}catch{}}function W0(Q){return Q["x-pairing-token"]??Q["X-Pairing-Token"]??null}var E2=null,A2=null,LQ=30000;function B0(Q,$={}){if($.isBootProfile===!1){s0();return}if(Q.globalGatewayUrl)process.env.VIBE_GLOBAL_GATEWAY_URL=Q.globalGatewayUrl;if(Q.workspaceGatewayUrl)process.env.VIBE_WORKSPACE_GATEWAY_URL=Q.workspaceGatewayUrl;if(Q.workspaceId)process.env.VIBE_WORKSPACE_ID=Q.workspaceId;if(Q.organizationId)process.env.VIBE_ORGANIZATION_ID=Q.organizationId;s0()}function s0(){E2=null}async function t0(){if(E2&&Date.now()-E2.at<LQ)return E2.result;if(A2)return A2;return A2=(async()=>{let Q;try{let $=await y2({strict:!0}),Z=r0($,{workspaceId:process.env.VIBE_WORKSPACE_ID,globalGatewayUrl:process.env.VIBE_GLOBAL_GATEWAY_URL,workspaceGatewayUrl:process.env.VIBE_WORKSPACE_GATEWAY_URL});Q=Z?{ok:!1,message:Z}:{ok:!0}}catch($){Q={ok:!0,message:`identity check skipped: ${$ instanceof Error?$.message:String($)}`}}return E2={at:Date.now(),result:Q},Q})().finally(()=>{A2=null}),A2}function K0(){let Q=b();return!Q||Q.name===W().name}function jQ(){let Q=g.hostname(),$=g.platform(),Z=g.arch(),Y=new Bun.CryptoHasher("sha256");return Y.update(`${Q}-${$}-${Z}`),Y.digest("hex").substring(0,16)}function OQ(){for(let Q of["..","../.."])try{let $=NQ(import.meta.dir,Q,"package.json"),Y=JSON.parse(_Q($,"utf8")).version;if(Y)return Y}catch{}return"0.0.0"}async function UQ(Q){let $=[],Z=Q.getProvider("tunnel");if(Z)$.push(Z);for(let Y of Q.listProvidersForType("tunnel")){let X=Q.getProviderByName("tunnel",Y.pluginName);if(X&&!$.includes(X))$.push(X)}for(let Y of $){if(!Y.getActiveTunnelUrl)continue;let X=await Y.getActiveTunnelUrl();if(X)return X}return null}function K4({serviceRegistry:Q,runFinalize:$,getDb:Z}){let Y=OQ(),X=jQ();return new v({prefix:"/api/agent"}).get("/identity",()=>({hostname:g.hostname(),platform:g.platform(),architecture:g.arch(),agentVersion:Y,agentInstanceId:J4()})).get("/version",()=>({version:Y,runtime:"bun",runtimeVersion:typeof Bun<"u"?Bun.version:"unknown"})).get("/api-key",({request:J,server:H,set:V})=>{if(!z0(J,H)){let F=p(Object.fromEntries(J.headers.entries()));if(!n(F))return V.status=401,{error:"Unauthorized",message:"Invalid or missing API key"}}return{apiKey:F2()}}).post("/iframe-token",({body:J,request:H,set:V})=>{let B=p(Object.fromEntries(H.headers.entries()));if(!n(B))return V.status=401,{error:"Unauthorized",message:"Invalid or missing API key"};try{if(Array.isArray(J.pathPrefixes)&&J.pathPrefixes.length>0)return V4({pathPrefixes:J.pathPrefixes,methods:J.methods},J.ttlSeconds??void 0);if(!J.pathPrefix)return V.status=400,{error:"BadRequest",message:"Provide either pathPrefix (string) or pathPrefixes (string[])"};return u2(J.pathPrefix,J.ttlSeconds??void 0)}catch(F){return V.status=400,{error:"BadRequest",message:F instanceof Error?F.message:String(F)}}},{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:H})=>{let{sid:V,token:B}=J;if(!V||!B)return H.status=400,{error:"BadRequest",message:"sid and token required"};if(!z4(V))return H.status=400,{error:"BadRequest",message:"invalid sid"};let F=`/terminal/${V}`,_=W4(B,F);if(!_.ok)return W().logger.warn("terminal-exchange","iframe token rejected",{sid:V,reason:_.reason}),H.status=401,{error:"Unauthorized",message:"invalid iframe token",code:_.reason==="expired"?"expired":_.reason==="replayed"?"replayed":"invalid"};let q=B4(V,600),A=`vt_term_${V}`;return H.headers["set-cookie"]=`${A}=${q.token}; HttpOnly; Secure; SameSite=None; Path=/terminal/${V}; Max-Age=600`,H.status=204,null},{body:z.Object({sid:z.String({minLength:1}),token:z.String({minLength:1})})}).post("/ui-exchange",({body:J,set:H})=>{let{plugin:V,token:B}=J;if(!V||!B)return H.status=400,{error:"BadRequest",message:"plugin and token required"};if(!I2(V))return H.status=400,{error:"BadRequest",message:"invalid plugin name"};let F=`/ui/${V}`;if(!F0(B,F))return H.status=401,{error:"Unauthorized",message:"invalid iframe token"};let _=G0(V,600),q=`vt_ui_${V}`;return H.headers["set-cookie"]=`${q}=${_.token}; HttpOnly; Secure; SameSite=None; Path=/ui/${V}/; Max-Age=600`,H.status=204,null},{body:z.Object({plugin:z.String({minLength:1}),token:z.String({minLength:1})})}).post("/ui-exchange-plugin",({body:J,set:H})=>{let{plugin:V,token:B}=J;if(!V||!B)return H.status=400,{error:"BadRequest",message:"plugin and token required"};if(!I2(V))return H.status=400,{error:"BadRequest",message:"invalid plugin name"};if(![`/api/plugins/${V}/ui`,`/${V}`].find((U)=>F0(B,U)))return H.status=401,{error:"Unauthorized",message:"invalid iframe token"};let q=G0(V,600),A=`vt_ui_${V}`;return H.headers["set-cookie"]=`${A}=${q.token}; HttpOnly; Secure; SameSite=None; Path=/api/plugins/${V}/ui/; Max-Age=600`,H.status=204,null},{body:z.Object({plugin:z.String({minLength:1}),token:z.String({minLength:1})})}).get("/system",({request:J,set:H})=>{let V=p(Object.fromEntries(J.headers.entries()));if(!n(V))return H.status=401,{error:"Unauthorized",message:"Invalid or missing API key"};return{machineId:X,hostname:g.hostname(),platform:g.platform(),arch:g.arch(),release:g.release(),cpus:g.cpus().length,totalMemory:g.totalmem(),freeMemory:g.freemem(),uptime:g.uptime(),bunVersion:typeof Bun<"u"?Bun.version:void 0,agentVersion:Y,homeDir:g.homedir(),cwd:process.cwd(),environment:"production"}}).get("/tunnel",async({request:J,set:H})=>{let V=Object.fromEntries(J.headers.entries()),B=n(p(V)),F=V0(W0(V));if(!B&&!F)return H.status=401,{error:"Unauthorized",message:"Provide x-agent-api-key OR x-pairing-token to read tunnel URL"};let _=await UQ(Q);if(!_)return{tunnelUrl:null,message:"No tunnel provider registered"};return{tunnelUrl:_}}).get("/status",()=>{let J=["tunnel","session","ai"].filter((H)=>Q.hasProvider(H));return{state:W().getBootState(),status:W().getBootState(),version:Y,providers:J,timestamp:new Date().toISOString()}}).get("/gateway-auth",()=>({configured:l.isConfigured(),config:g2(l.getConfig()),state:W().getBootState()})).post("/retry-config",async({set:J})=>{let{getFinalizeRetryHandle:H}=await import("./finalize-retry-handle-registry-fvm4gm8s.js"),V=H();if(!V)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 V.forceRetryNow();if(!B.ok)J.status=503;return{ok:B.ok,error:B.ok?void 0:B.error,state:W().getBootState(),worker:V.getState()}}).post("/gateway-auth",async({body:J,request:H,set:V})=>{let B=W().getBootState(),F=Object.fromEntries(H.headers.entries());if(B==="ready"){let G=p(F);if(!n(G))return V.status=401,{success:!1,state:B,error:"Unauthorized: API key required to reconfigure"}}else{let G=p(F),x=W0(F),k=n(G),S=V0(x);if(!k&&!S)return V.status=401,{success:!1,state:B,error:"Unauthorized: provide x-agent-api-key OR x-pairing-token for bootstrap"}}let{clientId:_,clientSecret:q,workspaceId:A,globalGatewayUrl:U,workspaceGatewayUrl:K}=J;if(!_||!q||!A||!U||!K)return V.status=400,{success:!1,state:W().getBootState(),error:"clientId, clientSecret, workspaceId, globalGatewayUrl, and workspaceGatewayUrl are required"};let T,I;try{T=K2(U,"globalGatewayUrl"),I=K2(K,"workspaceGatewayUrl")}catch(G){return V.status=400,{success:!1,state:W().getBootState(),error:G instanceof Error?G.message:String(G)}}let P,E=await e0("gateway-auth:push",async()=>{let G=b()??W();{let k;try{k=await y2({dir:G.dataDir,scope:G.name,strict:!0})}catch(m){let u=m instanceof Error?m.message:String(m);return W().logger.error("preconfig","Could not read existing credentials \u2014 refusing the push rather than risk overwriting a live pairing",{error:u}),V.status=503,{success:!1,state:W().getBootState(),error:`Cannot verify this agent's current pairing (secrets backend unavailable: ${u}). Refusing the credential push so a live pairing is not overwritten. Retry once the secrets backend recovers.`,code:"IDENTITY_CHECK_UNAVAILABLE"}}let S=X4(k,{workspaceId:A,globalGatewayUrl:T,workspaceGatewayUrl:I});if(S&&J.force!==!0)return W().logger.warn("preconfig","Rejected a gateway-auth push that would hijack this agent's identity",{conflict:S}),V.status=409,{success:!1,state:W().getBootState(),error:S,code:"GATEWAY_IDENTITY_CONFLICT"};if(S)W().logger.warn("preconfig","Forced re-pair \u2014 overwriting an existing gateway identity",{conflict:S})}let x=null;{let k=K0()?Q4():G.name,S;try{S=$4(k)}catch(j2){let O2=j2 instanceof Error?j2.message:String(j2);return W().logger.error("preconfig",`Could not read profile "${k}" \u2014 refusing the push rather than assume it declares nothing`,{error:O2}),V.status=503,{success:!1,state:W().getBootState(),error:`Cannot read profile "${k}" to verify this push targets the right environment (${O2}). Refusing the credential push so a foreign environment is not accepted by default. Repair or remove the profile file and retry.`,code:"PROFILE_CHECK_UNAVAILABLE"}}let m=H4(),u={globalGatewayUrl:m.globalGatewayUrl??S.globalGatewayUrl,workspaceGatewayUrl:m.workspaceGatewayUrl??S.workspaceGatewayUrl},a=Y4(u,{workspaceId:A,globalGatewayUrl:T,workspaceGatewayUrl:I},k);if(a&&J.force!==!0)return W().logger.warn("preconfig","Rejected a gateway-auth push that contradicts the active profile",{profileConflict:a}),V.status=409,{success:!1,state:W().getBootState(),error:a,code:"PROFILE_ENVIRONMENT_CONFLICT"};if(a)x={name:k,cfg:{...S,globalGatewayUrl:T,workspaceGatewayUrl:I,workspaceId:void 0}},W().logger.warn("preconfig",`Forced repoint accepted \u2014 profile "${k}" will be updated to match the pushed environment`,{profileConflict:a})}try{await c2({clientId:_,clientSecret:q,workspaceId:A,ownerUserId:J.ownerUserId,organizationId:J.organizationId,globalGatewayUrl:T,workspaceGatewayUrl:I,agentRecordId:J.agentRecordId,scopes:J.scopes,pairedIdentity:m2({workspaceId:A,globalGatewayUrl:T,workspaceGatewayUrl:I,agentRecordId:J.agentRecordId}),...J.storageAdapter?{storageAdapter:J.storageAdapter}:{},...J.storageOptions?{storageOptions:J.storageOptions}:{},...J.dbPath?{dbPath:J.dbPath}:{}},{dir:G.dataDir,scope:G.name})}catch(k){return V.status=500,{success:!1,state:W().getBootState(),error:`Failed to persist gateway credentials to secrets backend: ${k instanceof Error?k.message:String(k)}`}}if(x)try{Z4(x.name,x.cfg),W().logger.warn("preconfig",`Profile "${x.name}" repointed to the pushed environment`)}catch(k){let S=k instanceof Error?k.message:String(k);P=`Credentials were accepted, but profile "${x.name}" could not be updated (${S}). It still describes the previous environment \u2014 `+"run `vibe profile use` / fix the profile file so config and profile agree.",W().logger.error("preconfig",`Forced repoint accepted but profile "${x.name}" could not be updated \u2014 profile and config.json now disagree`,{error:S})}return null});if(E)return E;let C=W().getBootState();if(C==="ready"){let G=Z();if(G){if(await G.setConfig("gateway-auth:clientId",_),await G.setConfig("gateway-auth:clientSecret",q),await G.setConfig("gateway-auth:workspaceId",A),J.organizationId)await G.setConfig("gateway-auth:organizationId",J.organizationId);if(await G.setConfig("gateway-auth:globalGatewayUrl",T),await G.setConfig("gateway-auth:workspaceGatewayUrl",I),J.agentRecordId)await G.setConfig("gateway-auth:agentRecordId",J.agentRecordId)}l.configure({globalGatewayUrl:T,workspaceGatewayUrl:I,clientId:_,clientSecret:q,workspaceId:A,organizationId:J.organizationId}),B0({workspaceId:A,organizationId:J.organizationId,globalGatewayUrl:T,workspaceGatewayUrl:I},{isBootProfile:K0()}),W().logger.info("preconfig","Gateway credentials re-configured (agent was already ready)");let x=!!(J.storageAdapter||J.storageOptions||J.dbPath);return{success:!0,state:C,message:x?"Gateway auth re-configured. Restart the agent (vibe restart) to apply the new storage configuration.":"Gateway auth re-configured",...P?{warning:P}:{}}}return W().logger.info("preconfig","Gateway credentials received \u2014 beginning finalize (background)"),a0(),B0({workspaceId:A,organizationId:J.organizationId,globalGatewayUrl:T,workspaceGatewayUrl:I},{isBootProfile:K0()}),$({clientId:_,clientSecret:q,workspaceId:A,organizationId:J.organizationId,globalGatewayUrl:T,workspaceGatewayUrl:I},{agentRecordId:J.agentRecordId,scopes:J.scopes}).catch((G)=>{W().logger.error("preconfig","Background finalize threw",{error:G instanceof Error?G.message:String(G)})}),V.status=202,{success:!0,state:W().getBootState(),agentRecordId:J.agentRecordId,message:"Gateway credentials accepted; finalize is running in the background. Poll /health/ready for completion.",...P?{warning:P}:{}}},{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()),force:z.Optional(z.Boolean())})})}import{existsSync as Z2,mkdirSync as xQ,rmSync as F4,readdirSync as j4}from"fs";import{join as n2}from"path";function r(Q){return n2(L2(),"agents",i(Q))}function MQ(){let Q=n2(L2(),"agents");if(!Z2(Q))return[];return j4(Q,{withFileTypes:!0}).filter(($)=>$.isDirectory()).map(($)=>$.name).filter(($)=>/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test($))}function O4(Q){return n2(L2(),"agents",i(Q))}function _0(Q){return e({dir:O4(Q)})}function G4(Q,$){return l2($,{dir:O4(Q),scope:i(Q)})}function G2(Q){let $=p2(),Z=N0().find((J)=>J.name===Q),Y=t.get(Q),X={name:Q,isDefault:Q===$,isRunning:Z?.status==="running",attached:Y!==void 0,bootState:Y?Y.getBootState():null,dataDir:Y?Y.dataDir:null};if(Z)X.port=Z.port,X.pid=Z.pid,X.startTime=Z.startTime;if(Z2(r(Q)))X.config=g2(_0(Q));return X}function U4(Q={}){let $=Q.serviceManagerFactory?Q.serviceManagerFactory():new d2;return new v({prefix:"/api/profiles"}).get("/",()=>{let Z=MQ(),Y=p2(),X=new Set(Z);return X.add(Y),[...X].sort().map((J)=>G2(J))}).post("/",async({body:Z,set:Y})=>{try{let X=i(Z.name),J=r(X);if(Z2(J))return Y.status=409,{error:"exists",message:`Profile '${X}' already exists.`};let H;if(Z.copyFrom){let V=i(Z.copyFrom);if(!Z2(r(V)))return Y.status=400,{error:"copy-source-missing",message:`Profile '${V}' does not exist.`};H=_0(V),delete H["static-api-key"],delete H.agentRecordId,delete H.apiKeys,delete H.pairedIdentity,delete H.workspaceId,delete H.organizationId}else H=N4();if(Z.gatewayUrl)H.globalGatewayUrl=Z.gatewayUrl;if(Z.workspaceGatewayUrl)H.workspaceGatewayUrl=Z.workspaceGatewayUrl;if(Z.clientId)H.clientId=Z.clientId;if(Z.clientSecret)H.clientSecret=Z.clientSecret;if(Z.workspaceId)H.workspaceId=Z.workspaceId;if(Z.organizationId)H.organizationId=Z.organizationId;xQ(J,{recursive:!0}),G4(X,H);try{L0(X)}catch(V){W().logger.warn("profile-mgmt",`In-process attach failed for '${X}'`,{error:String(V)})}if(W().logger.info("profile-mgmt",`Created profile '${X}' at ${J}`),Z.start){let V={name:X,port:Z.port??0,daemon:!0,dbPath:C2(),profile:X};await $.startDaemon(V)}return Y.status=201,G2(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:Z,set:Y})=>{try{let X=i(Z.name);if(!Z2(r(X)))return Y.status=404,{error:"not-found",message:`No profile '${X}'.`};return G2(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:Z,body:Y,set:X})=>{try{let J=i(Z.name);if(!Z2(r(J)))return X.status=404,{error:"not-found",message:`No profile '${J}'.`};let H=["static-api-key","apiKeys","agentRecordId","pairedIdentity"];for(let F of H)if(F in Y)return X.status=400,{error:"forbidden-field",message:`Field '${F}' is managed via dedicated commands (vibe key rotate / vibe profile create). It cannot be patched here.`};if("registry"in 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={..._0(J),...Y};return G4(J,B),G2(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:Z,body:Y,query:X,set:J})=>{try{let H=i(Z.name);if(H===p2())return J.status=409,{error:"is-default",message:`Cannot delete active default profile '${H}'. Switch to another profile first.`};let V=X?.purge==="true"||X?.purge==="1",B=Z2(r(H)),F=t.has(H);if(!B&&!F)return J.status=404,{error:"not-found",message:`No profile '${H}'.`};if(B&&!V&&!Y?.confirm)return J.status=400,{error:"confirm-required",message:"Pass { confirm: true } in the body or `?purge=true` in the query to delete the on-disk dataDir (destructive)."};try{await $.stop(H)}catch{}try{await t.destroy(H)}catch(_){W().logger.warn("profile-mgmt",`In-process detach failed for '${H}'`,{error:String(_)})}if(B)if(Y?.keepConfig)for(let _ of j4(r(H))){if(_==="config.json")continue;F4(n2(r(H),_),{recursive:!0,force:!0})}else F4(r(H),{recursive:!0,force:!0});return W().logger.info("profile-mgmt",`Deleted profile '${H}'`),{ok:!0,deleted:H,keptConfig:!!Y?.keepConfig,detached:F,purged:B}}catch(H){return J.status=400,{error:"delete-failed",message:H instanceof Error?H.message:String(H)}}},{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:Z,set:Y})=>{try{let X=i(Z.name);if(!Z2(r(X)))return Y.status=404,{error:"not-found",message:`No profile '${X}'.`};return await L4(()=>_4(X)),W().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:Z,body:Y,set:X})=>{try{let J=i(Z.name);if(!Z2(r(J)))return X.status=404,{error:"not-found",message:`No profile '${J}'.`};try{L0(J)}catch(V){W().logger.warn("profile-mgmt",`In-process attach failed for '${J}'`,{error:String(V)})}if(!N0().some((V)=>V.name===J&&V.status==="running")){let V={name:J,port:Y?.port??0,daemon:!0,dbPath:C2(),profile:J};await $.startDaemon(V)}return G2(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:Z,set:Y})=>{try{let X=i(Z.name);try{await $.stop(X)}catch{}try{await t.destroy(X)}catch(J){W().logger.warn("profile-mgmt",`In-process detach failed for '${X}'`,{error:String(J)})}return G2(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 TQ(){let Q=process.memoryUsage(),$=process.resourceUsage(),Z=$.userCPUTime/1000,Y=$.systemCPUTime/1000,X=Z+Y,J=t.list().map((H)=>{let V;try{V=x4(H.spawnOwnerKey).length}catch{V=0}return{name:H.name,status:H.getBootState(),childPidCount:V,cpuMs:X,heapBytes:Q.heapUsed,dataDir:H.dataDir}});return{process:{pid:process.pid,uptimeSeconds:process.uptime(),cpuUserMs:Z,cpuSystemMs:Y,heapUsedBytes:Q.heapUsed,heapTotalBytes:Q.heapTotal,rssBytes:Q.rss},profiles:J,notes:{perProfileCpu:"deferred",perProfileHeap:"deferred"}}}function M4(){return new v({prefix:"/api/profile-stats"}).get("/",()=>TQ())}function q2(Q,$){return Promise.race([Q,new Promise((Z,Y)=>setTimeout(()=>Y(Error(`timeout after ${$}ms`)),$))])}function AQ(Q){let $=Q instanceof Error?Q.message:String(Q);return/ENOENT/.test($)||/no such file or directory/i.test($)}async function T4(Q){let Z=`__health__:probe:${typeof crypto<"u"&&typeof crypto.randomUUID==="function"?crypto.randomUUID():`${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`}`,Y=String(Date.now());if(await q2(Q.setConfig(Z,Y),2000),await q2(Q.getConfig(Z),2000)!==Y)throw Error("round-trip mismatch");try{await q2(Q.deleteConfig(Z),500)}catch{}}async function EQ(Q,$){if(!Q)return{ok:!1,message:"database not opened"};let Z=performance.now();try{return await T4(Q),{ok:!0,durationMs:performance.now()-Z}}catch(Y){if($&&AQ(Y))try{return(await import("fs")).mkdirSync($,{recursive:!0}),await T4(Q),{ok:!0,message:`recovered: dbPath ${$} was missing \u2014 recreated`,durationMs:performance.now()-Z}}catch(X){return{ok:!1,message:`ENOENT on dbPath ${$}: ${X instanceof Error?X.message:String(X)}`,durationMs:performance.now()-Z}}return{ok:!1,message:Y instanceof Error?Y.message:String(Y),durationMs:performance.now()-Z}}}async function IQ(Q){if(process.env.AGENT_TUNNEL==="false")return{ok:!0,message:"tunnel disabled via AGENT_TUNNEL=false"};if(!Q)return{ok:!1,message:"no service registry"};let $=Q.getProvider("tunnel"),Z=W().getBootState()==="awaiting-config";if(!$)return{ok:!1,message:Z?"agent is awaiting-config \u2014 POST OAuth credentials to /api/agent/gateway-auth to register tunnel provider":"no tunnel provider registered"};if(!$.getActiveTunnelUrl)return{ok:!0,message:`provider: ${$.name}`};try{let Y=await q2(Promise.resolve($.getActiveTunnelUrl()),2000),X=A4(Y);if(X)return{ok:!0,message:`provider: ${$.name} \u2014 ${X}`};if(Y)return{ok:!1,message:`provider: ${$.name} \u2014 reported an unusable tunnel URL (${Y})`};return{ok:!1,message:`provider: ${$.name} \u2014 no active tunnel (the agent is not reachable from outside; the provider is rebuilding it)`}}catch(Y){return{ok:!1,message:`provider: ${$.name} \u2014 tunnel status unavailable: ${Y instanceof Error?Y.message:String(Y)}`}}}function CQ(Q,$){if(!Q)return{ok:!1,message:"no service registry"};let Y=W().getBootState()==="awaiting-config";if($==="session"){let X=Q.getProvider("session");if(X)return{ok:!0,message:`provider: ${X.name}`};return{ok:!1,message:Y?"agent is awaiting-config \u2014 POST OAuth credentials to /api/agent/gateway-auth to register session provider":"no session provider registered"}}return{ok:!0}}async function qQ(Q){if(!Q)return{};let $={};for(let Z of Q.getAllPlugins()){let Y=Z.getHealth;if(typeof Y!=="function")continue;let X=performance.now();try{let J=await q2(Promise.resolve(Y.call(Z)),2000);$[Z.name]={ok:J?.ok!==!1,message:J?.message,durationMs:performance.now()-X}}catch(J){$[Z.name]={ok:!1,message:J instanceof Error?J.message:String(J),durationMs:performance.now()-X}}}return $}function E4(Q){let $=Q&&"serviceRegistry"in Q?Q:{serviceRegistry:Q};return new v({prefix:"/health"}).get("/",()=>{return{status:"ok",lifecycleState:$.serviceRegistry?.getService("agent","lifecycle")?.getState()??"running",bootState:W().getBootState(),timestamp:new Date().toISOString(),uptime:process.uptime()}}).get("/live",()=>({status:"ok"})).get("/ready",async({set:Z})=>{let X=$.serviceRegistry?.getService("agent","lifecycle")?.getState()??"running",J=W().getBootState(),H={};H.boot={ok:J==="ready",message:J==="ready"?void 0:`boot state ${J}`},H.lifecycle={ok:X==="running",message:X==="running"?void 0:`lifecycle ${X}`},H.db=await EQ($.getDb?.()??null,$.getDbPath?.()??null),H.tunnel=await IQ($.serviceRegistry),H.session=CQ($.serviceRegistry,"session"),H.identity=await t0();try{let{gatewayClient:K}=await import("./gateway-client-6dqagbg4.js");if(!K.isConfigured())H.registration={ok:!0,message:"not configured"};else{let T=$.getDb?.()??null;if(T?await T.getConfig("gateway-auth:agentRecordId"):null)H.registration={ok:!0};else{let P=W().getDegradedReasons().some((E)=>E.plugin==="agent-registration");H.registration=P?{ok:!1,message:"agent failed to register with the workspace after retries"}:{ok:!0,message:"registering"}}}}catch(K){H.registration={ok:!0,message:`registration check skipped: ${K instanceof Error?K.message:String(K)}`}}let V=await qQ($.getPluginManager?.()??null),B=Object.values(H).every((K)=>K.ok)&&Object.values(V).every((K)=>K.ok);if(!B)Z.status=503;let F=J==="degraded"?W().getDegradedReasons():[],_=W().name,q={};for(let K of t.list())q[K.name]={bootState:K.getBootState(),ok:K.getBootState()==="ready",degradedReasons:K.getDegradedReasons()};let A=W().getLastFinalizeError(),U={status:B?"ok":"degraded",lifecycleState:X,bootState:J,daemon:{profile:_,bootState:J,ok:J==="ready"},profiles:q,components:H,plugins:V,degradedReasons:F,lastFinalizeError:A,timestamp:new Date().toISOString()};if(!B)W().logger.warn("health","Readiness probe failed",{components:H,plugins:V,bootState:J});return U})}var i2=0,I4=0;function C4(){return new v({name:"inflight-tracker"}).onRequest(()=>{i2+=1}).onAfterResponse(()=>{i2=Math.max(0,i2-1),I4+=1})}function q4(){return new v({prefix:"/api/stats"}).get("/inflight",()=>({inflight:Math.max(0,i2-1),totalServed:I4}))}var j0=Object.freeze(["code","code-insiders","codium","cursor","idea","pycharm","webstorm","goland","phpstorm","rubymine","clion","rider","zed","subl","vim","nvim","emacs","neovide","fleet","helix"]),kQ=new Set(j0),RQ=new Set(["--new-window","-n","--reuse-window","-r","--wait","-w","--add","--goto"]);function k4(Q){try{return Bun.which(Q)??null}catch{return null}}function S4(){return new v({prefix:"/api/editor"}).get("/allowlist",()=>({commands:[...j0]})).get("/detect",async()=>{let Q=j0.map((Y)=>[Y,k4(Y)]),$=[],Z={};for(let[Y,X]of Q)if(X)$.push(Y),Z[Y]=X;return{available:$,paths:Z}}).post("/open",async({body:Q,set:$})=>{let{command:Z,path:Y,args:X=[]}=Q;if(!kQ.has(Z))return $.status=400,{ok:!1,error:`Command '${Z}' is not in the IDE allowlist`};for(let V of X)if(typeof V!=="string"||!RQ.has(V))return $.status=400,{ok:!1,error:`Argument '${V}' is not in the flag allowlist`};let J;try{J=(await R4(Y,{mustExist:!0})).realPath}catch(V){return $.status=400,{ok:!1,error:`Invalid path: ${V instanceof Error?V.message:String(V)}`}}let H=k4(Z);if(!H)return $.status=404,{ok:!1,error:`'${Z}' is not installed or not on PATH on this agent`};try{let V=w4({owner:`editor:${Z}`,cmd:[H,...X,J],env:process.env,stdout:"ignore",stderr:"ignore",stdin:"ignore",meta:{command:Z,path:J}});return W().logger.info("editor",`Launched ${Z} on ${J}`,{pid:V.pid}),W().audit.emit("agent","editor.open",{command:Z,path:J,pid:V.pid}),{ok:!0,command:Z,resolvedPath:J,pid:V.pid}}catch(V){return $.status=500,{ok:!1,error:`Failed to spawn editor: ${V instanceof Error?V.message:String(V)}`}}},{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 D4=Symbol.for("@vibecontrols/plugin-sdk:contextProviders@1");function wQ(){let Q=globalThis,$=Q[D4];if($)return $;let Z=new Map;return Q[D4]=Z,Z}function O0(){return Array.from(wQ().values())}function h4(){return(b()??W()).dataDir}function o(){let Q=e({dir:h4()});return{ownerUserId:Q.ownerUserId,workspaceId:Q.workspaceId}}function o2(){return e({dir:h4()}).agentRecordId}function v4(Q){if(!Q)return null;try{return new URL(Q).host}catch{return null}}async function P4(Q,$){let Z=Q.getPluginManager(),Y=Z?Z.getPluginDetails().map((V)=>({pluginName:V.pluginName,packageName:V.packageName,version:V.version,tags:V.tags??[]})):[],X=process.memoryUsage(),J=v4(Q.getTunnelHost?.()??null),H;try{H=_2(o()).map((V)=>({id:V.id,label:V.label,host:v4(V.tunnelUrl),agentRecordId:V.agentRecordId??null,permissions:V.permissions,canForward:V.permissions.includes("mesh:forward"),lastReachable:V.lastReachable??null}))}catch{H=[]}return{pluginName:"agent",description:"vibecontrols-agent runtime self-report",generatedAt:new Date().toISOString(),data:{profile:$.profile,vibeId:$.vibeId??null,runtime:{bunVersion:typeof Bun<"u"?Bun.version:null,nodeVersion:process.versions.node??null,platform:process.platform,arch:process.arch,pid:process.pid,uptimeSeconds:Math.round(process.uptime()),memory:{rssMB:Math.round(X.rss/1048576),heapUsedMB:Math.round(X.heapUsed/1048576)}},agent:{version:Q.getAgentVersion?.()??null,profileRegistered:k2(),tunnelHost:J},plugins:{count:Y.length,items:Y},mesh:{peerCount:H.length,peers:H}}}}var SQ=2000,f4=1000;async function DQ(Q,$){let Z,Y=new Promise((X,J)=>{Z=setTimeout(()=>J(Error(`timeout after ${$}ms`)),$)});try{return await Promise.race([Q,Y])}finally{if(Z)clearTimeout(Z)}}async function b4(Q,$){let Z=performance.now(),Y=Q.timeoutMs??SQ;try{let X=await DQ(Q.getContext($),Y);if(!X.generatedAt)X.generatedAt=new Date().toISOString();return{ok:!0,data:X,durationMs:Math.round(performance.now()-Z)}}catch(X){return{ok:!1,error:X.message??String(X),durationMs:Math.round(performance.now()-Z)}}}class U0{deps;inflight=new Map;constructor(Q){this.deps=Q}async aggregate(Q){let $=`${Q.profile}::${Q.vibeId??""}`,Z=this.inflight.get($);if(Z&&Date.now()-Z.ts<f4)return Z.promise;let Y=this.doAggregate(Q).finally(()=>{setTimeout(()=>{let X=this.inflight.get($);if(X&&X.promise===Y)this.inflight.delete($)},f4).unref?.()});return this.inflight.set($,{ts:Date.now(),promise:Y}),Y}async selfContext(Q){return P4(this.deps,Q)}async pluginContext(Q,$){let Z=O0().find((Y)=>Y.name===Q);if(!Z)return null;return b4(Z,$)}async pluginsContext(Q){let $=O0(),Z=await Promise.allSettled($.map((X)=>b4(X,Q))),Y={};return $.forEach((X,J)=>{let H=Z[J];if(H&&H.status==="fulfilled")Y[X.name]=H.value;else if(H&&H.status==="rejected")Y[X.name]={ok:!1,error:H.reason instanceof Error?H.reason.message:String(H.reason),durationMs:0}}),Y}async doAggregate(Q){let[$,Z]=await Promise.all([this.selfContext(Q),this.pluginsContext(Q)]);return{agent:$,plugins:Z}}}function a2(Q){let $=Q.vibeId;if(typeof $!=="string")return;let Z=$.trim();return Z.length>0&&Z.length<=128?Z:void 0}function y4(Q){let $=new U0(Q);return new v({prefix:"/api/agent/context"}).get("/",async({params:Z,query:Y})=>{let X=Z?.profile??"default",J=a2(Y);return $.aggregate({profile:X,vibeId:J})},{query:z.Object({vibeId:z.Optional(z.String())})}).get("/agent",async({params:Z,query:Y})=>{let X=Z?.profile??"default",J=a2(Y);return $.selfContext({profile:X,vibeId:J})},{query:z.Object({vibeId:z.Optional(z.String())})}).get("/plugins",async({params:Z,query:Y})=>{let X=Z?.profile??"default",J=a2(Y);return $.pluginsContext({profile:X,vibeId:J})},{query:z.Object({vibeId:z.Optional(z.String())})}).get("/plugins/:name",async({params:Z,query:Y,set:X})=>{let J=Z?.profile??"default",H=Z?.name;if(!H)return X.status=400,{error:"missing plugin name"};let V=a2(Y),B=await $.pluginContext(H,{profile:J,vibeId:V});if(!B)return X.status=404,{error:`no context provider registered under name "${H}"`};return B},{params:z.Object({name:z.String()}),query:z.Object({vibeId:z.Optional(z.String())})})}var J2="autoupdate",hQ=86400000,c4=300000,vQ=900000,h={timer:null,running:!1,profile:"default",lastCheckAt:null,lastCheck:null,lastUpdateAt:null,lastUpdate:null,startedAt:null};function x0(){let Q=(process.env.VIBE_AUTOUPDATE??"").trim().toLowerCase();return Q==="0"||Q==="false"||Q==="off"||Q==="no"}function u4(){if(x0())return!1;try{return e().autoUpdate!==!1}catch{return!0}}function M0(){let Q=Number(process.env.VIBE_AUTOUPDATE_INTERVAL_MS);if(Number.isFinite(Q)&&Q>0)return Math.max(vQ,Q);return hQ}async function T0(Q){let $=W().logger;if(h.running)return{check:h.lastCheck??await m4(),update:null};h.running=!0;try{let Z=await R2();if(h.lastCheck=Z,h.lastCheckAt=new Date().toISOString(),Z.error)$.debug(J2,`Update check failed: ${Z.error}`);else if(Z.hasUpdate)$.info(J2,`New agent version available: ${Z.current} \u2192 ${Z.latest}`);let Y=Q?.force||u4();if(!Z.hasUpdate||!Y)return{check:Z,update:null};$.info(J2,`Auto-updating ${Z.current} \u2192 ${Z.latest} (idle-gated restart)\u2026`);let X=await s2({restart:!0,name:h.profile,onLog:(J)=>$.info(J2,J)});if(h.lastUpdate=X,h.lastUpdateAt=new Date().toISOString(),X.ok&&X.updated)$.info(J2,`Auto-update applied: now ${X.current} (restart: ${X.restart}).`);else if(!X.ok)$.warn(J2,`Auto-update failed: ${X.error}`);return{check:Z,update:X}}catch(Z){return $.warn(J2,`Auto-update tick threw: ${Z instanceof Error?Z.message:String(Z)}`),{check:await m4(),update:null}}finally{h.running=!1}}async function m4(){if(h.lastCheck)return h.lastCheck;let Q=await R2();return h.lastCheck=Q,h.lastCheckAt=new Date().toISOString(),Q}function g4(Q){if(h.timer)clearTimeout(h.timer);h.timer=setTimeout(()=>{T0().finally(()=>{if(h.startedAt)g4(M0())})},Q),h.timer.unref?.()}function PQ(Q){let $=W().logger;if(h.profile=Q?.profile||process.env.VIBECONTROLS_PROFILE||"default",h.startedAt=new Date().toISOString(),x0()){$.info(J2,"Autoupdate disabled via VIBE_AUTOUPDATE \u2014 not scheduling.");return}$.info(J2,`Autoupdate scheduled (first check in ${Math.round(c4/60000)}m, then every ${Math.round(M0()/3600000)}h).`),g4(c4)}function c7(){if(h.timer)clearTimeout(h.timer),h.timer=null;h.startedAt=null}function p4(Q){if(l2({autoUpdate:Q}),Q&&!h.startedAt)PQ({profile:h.profile})}function A0(){let Q=!0;try{Q=e().autoUpdate!==!1}catch{}return{enabled:u4(),envKillSwitch:x0(),configEnabled:Q,scheduled:!!h.startedAt,intervalMs:M0(),profile:h.profile,startedAt:h.startedAt,lastCheckAt:h.lastCheckAt,lastCheck:h.lastCheck,lastUpdateAt:h.lastUpdateAt,lastUpdate:h.lastUpdate}}import{existsSync as l4}from"fs";import{join as d4}from"path";var fQ=600000,E0=1e6;function bQ(){let Q=N2(),$=Q.which("bun")??`bun${Q.executableSuffix}`,Z=d4(import.meta.dir,"cli.js");if(l4(Z))return{runner:$,prefix:[Z]};let Y=d4(import.meta.dir,"..","cli.ts");if(l4(Y))return{runner:$,prefix:[Y]};let X=Q.which("vibe");if(X)return{runner:X,prefix:[]};return null}function n4(Q){if(Q.length<=E0)return Q;return Q.slice(0,E0)+`
|
|
4
|
-
\u2026[output truncated at ${E0} bytes]`}async function r2(Q,$={}){let Z=bQ();if(!Z)return{ok:!1,exitCode:null,stdout:"",stderr:"Could not locate the vibe CLI to execute (no dist/cli.js, source, or PATH entry).",timedOut:!1,argv:Q,command:"(unresolved)"};let Y=[...Z.prefix,...Q],X=[Z.runner,...Y].join(" ");try{let J=Bun.spawn([Z.runner,...Y],{cwd:$.cwd,env:{...process.env,VIBE_AUTO_ACCEPT:"1",CI:"1",NO_COLOR:"1",...$.env},stdout:"pipe",stderr:"pipe"}),H=$.timeoutMs??fQ,V=!1,B=setTimeout(()=>{V=!0;try{J.kill()}catch{}},H),[F,_,q]=await Promise.all([new Response(J.stdout).text(),new Response(J.stderr).text(),J.exited]);return clearTimeout(B),{ok:!V&&q===0,exitCode:q,stdout:n4(F),stderr:n4(_),timedOut:V,argv:Q,command:X}}catch(J){return{ok:!1,exitCode:null,stdout:"",stderr:`Failed to spawn vibe CLI: ${J instanceof Error?J.message:String(J)}`,timedOut:!1,argv:Q,command:X}}}async function i4(){let{Command:Q}=await import("./esm-n9r8p5n2.js"),{registerCoreCommands:$}=await import("./register-core-e0ha52yw.js"),Z=new Q;Z.name("vibe").option("--json").option("--plain").option("-y, --yes").option("-p, --profile <name>");try{$(Z)}catch{}let Y=new Set(["nuke","kill","gc","stop","rollback","deploy"]),X=[];for(let J of Z.commands){let H=J.name();if(!H||H==="help")continue;X.push({name:H,description:J.description()||"",usage:J.usage()||"",options:J.options.map((V)=>({flags:V.flags,description:V.description||""})),group:"core",destructive:Y.has(H)})}return X.sort((J,H)=>J.name.localeCompare(H.name))}import{spawn as yQ}from"child_process";import{writeFileSync as cQ,mkdirSync as mQ}from"fs";import{tmpdir as uQ}from"os";import{join as o4}from"path";var gQ="@vibecontrols/agent";function a4(Q){let $=N2(),Z=$.which("bun")??`bun${$.executableSuffix}`,Y=$.which("npm")??`npm${$.executableSuffix}`,X=t2(),J=Q.delayMs??3000,H=Q.pids.filter((B)=>Number.isInteger(B)&&B>0),V=`// vibecontrols agent self-uninstall reaper (auto-generated)
|
|
5
|
-
const PIDS = ${JSON.stringify(H)};
|
|
6
|
-
const NPM = ${JSON.stringify(Y)};
|
|
7
|
-
const BUN = ${JSON.stringify(Z)};
|
|
8
|
-
const REGISTRY = ${JSON.stringify(X)};
|
|
9
|
-
const PKG = ${JSON.stringify(gQ)};
|
|
10
|
-
await Bun.sleep(${J});
|
|
11
|
-
for (const pid of PIDS) {
|
|
12
|
-
try { process.kill(pid, "SIGTERM"); } catch {}
|
|
13
|
-
}
|
|
14
|
-
await Bun.sleep(2500);
|
|
15
|
-
for (const pid of PIDS) {
|
|
16
|
-
try { process.kill(pid, "SIGKILL"); } catch {}
|
|
17
|
-
}
|
|
18
|
-
try { Bun.spawnSync([NPM, "uninstall", "-g", PKG, "--registry=" + REGISTRY], { stdout: "inherit", stderr: "inherit" }); } catch {}
|
|
19
|
-
try { Bun.spawnSync([BUN, "remove", "-g", PKG], { stdout: "inherit", stderr: "inherit" }); } catch {}
|
|
20
|
-
`;try{let B=o4(uQ(),"vibecontrols-uninstall");mQ(B,{recursive:!0});let F=o4(B,`reaper-${process.pid}.ts`);return cQ(F,V,{encoding:"utf8"}),yQ(Z,[F],{detached:!0,stdio:"ignore",windowsHide:!0}).unref(),W().logger.info("self-uninstall",`Scheduled detached uninstall reaper (pids=${H.join(",")}) at ${F}`),{ok:!0,scriptPath:F}}catch(B){return{ok:!1,scriptPath:null,error:B instanceof Error?B.message:String(B)}}}var pQ=new Set(["db","plugins-registry","logs","binaries","subprocs"]);async function s4(Q){let $=await i4();try{let Z=Q.getPluginManager?.();if(Z){let Y=new Set($.map((X)=>X.name));for(let X of Z.getPluginDetails()){let J=X.cliCommand;if(J&&!Y.has(J))Y.add(J),$.push({name:J,description:X.description||`${X.pluginName} plugin command`,usage:"",options:[],group:"plugin",destructive:!1})}}}catch{}return $.sort((Z,Y)=>Z.name.localeCompare(Y.name))}function r4(Q={}){return new v({name:"agent-maintenance"}).get("/api/agent/update/check",async()=>{return await R2()}).get("/api/agent/update/status",()=>{return A0()}).post("/api/agent/update",async({body:$})=>{return await s2({targetVersion:typeof $?.version==="string"?$.version:void 0,allowIncompatible:$?.allowIncompatible===!0,restart:$?.restart!==!1})},{body:z.Optional(z.Object({version:z.Optional(z.String()),allowIncompatible:z.Optional(z.Boolean()),restart:z.Optional(z.Boolean())}))}).post("/api/agent/update/config",({body:$})=>{return p4($.enabled),{ok:!0,status:A0()}},{body:z.Object({enabled:z.Boolean()})}).post("/api/agent/update/check-now",async({body:$})=>{return{ok:!0,...await T0({force:$?.force===!0})}},{body:z.Optional(z.Object({force:z.Optional(z.Boolean())}))}).get("/api/agent/commands",async()=>{let $=await s4(Q);return{commands:$,count:$.length}}).post("/api/agent/commands/run",async({body:$,set:Z})=>{let Y=Array.isArray($?.argv)?$.argv.filter((B)=>typeof B==="string"):[];if(Y.length===0)return Z.status=400,{ok:!1,error:"argv must be a non-empty string array"};let X=Y[0],J=await s4(Q),H=new Set(J.map((B)=>B.name));if(!H.has(X))return Z.status=400,{ok:!1,error:`Unknown or disallowed command: "${X}"`,allowed:[...H].sort()};return await r2(Y,{timeoutMs:typeof $?.timeoutMs==="number"?$.timeoutMs:void 0})},{body:z.Object({argv:z.Array(z.String()),timeoutMs:z.Optional(z.Number())})}).post("/api/agent/nuke",async({body:$,set:Z})=>{let Y=["nuke"];if($?.all)Y.push("--all");if($?.removeConfig)Y.push("--remove-config");if($?.dryRun)Y.push("--dry-run");if(typeof $?.removePlugins==="string"&&$.removePlugins)Y.push("--remove-plugins",$.removePlugins);if(typeof $?.keep==="string"&&$.keep){let H=$.keep.split(",").map((V)=>V.trim()).filter((V)=>V&&!pQ.has(V));if(H.length>0)return Z.status=400,{ok:!1,error:`Invalid --keep value(s): ${H.join(", ")}`};Y.push("--keep",$.keep)}Y.push("-y","--json");let X=await r2(Y),J=null;try{let H=X.stdout.trim().split(`
|
|
21
|
-
`).reverse().find((V)=>V.trim().startsWith("{"));if(H)J=JSON.parse(H)}catch{}return{...X,parsed:J}},{body:z.Optional(z.Object({all:z.Optional(z.Boolean()),removeConfig:z.Optional(z.Boolean()),removePlugins:z.Optional(z.String()),keep:z.Optional(z.String()),dryRun:z.Optional(z.Boolean())}))}).post("/api/agent/uninstall",async({body:$})=>{let Z=$?.dryRun===!0,Y=["nuke","--all","--remove-config","-y","--json"];if(Z)Y.push("--dry-run");let X=await r2(Y);if(Z)return{ok:X.ok,dryRun:!0,nuke:X,note:"Dry run \u2014 would nuke all state and uninstall @vibecontrols/agent."};let J=new Set([process.pid]);try{let V=new d2;for(let B of await V.listInstances())if(typeof B.pid==="number"&&B.pid>0)J.add(B.pid)}catch{}let H=a4({pids:[...J]});return{ok:X.ok&&H.ok,nuke:X,uninstallScheduled:H.ok,scriptPath:H.scriptPath,...H.error?{error:H.error}:{},note:"Agent state nuked; package self-uninstall scheduled \u2014 the daemon will stop and `@vibecontrols/agent` will be removed shortly."}},{body:z.Optional(z.Object({dryRun:z.Optional(z.Boolean())}))})}import{existsSync as oQ,readFileSync as aQ}from"fs";import{join as sQ}from"path";var lQ=`mutation AddAgentFromTunnel($input: AddAgentFromTunnelInput!) {
|
|
22
|
-
addVibecontrolsAgentFromTunnel(input: $input) { agent { id name } clientId success error }
|
|
23
|
-
}`,dQ=`mutation ReportAgentMeshLink($input: ReportAgentMeshLinkInput!) {
|
|
24
|
-
reportAgentMeshLink(input: $input) { id }
|
|
25
|
-
}`,t4="VIBE_BOOTSTRAP_JSON=";function nQ(Q){for(let Y of Q.split(/\r?\n/)){let X=Y.indexOf(t4);if(X>=0)try{return JSON.parse(Y.slice(X+t4.length))}catch{}}let $=Q.indexOf("{"),Z=Q.lastIndexOf("}");if($>=0&&Z>$)try{return JSON.parse(Q.slice($,Z+1))}catch{return null}return null}async function $5(Q,$){let Z=(_,q,A)=>$?.({step:_,status:q,message:A}),Y=Q5(Q.permissions??["tunnel:read","session:list","plugin:list","diagnostics:read","mesh:forward"]);if(!Y.includes("mesh:forward"))Y.push("mesh:forward");let X=(_)=>({ok:!1,peerId:"",agentRecordId:null,tunnelUrl:null,permissions:Y,error:_}),J;try{J=Q0(Q.target,{identityFile:Q.identityFile})}catch(_){return X(_ instanceof Error?_.message:String(_))}let H=Q.label??J.id,V=Y.join(","),B,F='export PATH="$HOME/.bun/bin:$PATH"; ';try{if(!Q.connectExisting){Z("probe","running");let G=await J.probe();if(Z("probe","completed",`os=${G.os??"?"} arch=${G.arch??"?"}`),!G.bun){if(Q.installBun===!1)return X("Bun is required to run the agent but is not installed, and Bun auto-install was disabled.");Z("install-bun","running");let u=await J.run(["sh","-c",`curl -fsSL https://bun.sh/install | bash && echo 'export PATH="$HOME/.bun/bin:$PATH"' >> ~/.bashrc`],{timeoutMs:300000});if(u.code!==0)return Z("install-bun","failed",u.stderr.slice(0,400)),X("Bun auto-install failed.");let a=await J.run(["sh","-c","$HOME/.bun/bin/bun --version 2>/dev/null"],{timeoutMs:1e4});if(a.code===0&&a.stdout.trim())G.bun="$HOME/.bun/bin/bun",Z("install-bun","completed",a.stdout.trim());else return X("Bun installed but the binary is not reachable.")}Z("install-agent","running");let x=Q.version??"latest",k=Q.registry??"https://registry.npmjs.org/";if(!/^[A-Za-z0-9._@/^~>=<-]+$/.test(x))return Z("install-agent","failed","invalid version"),X(`Invalid agent version: ${x}`);if(!/^https?:\/\/[A-Za-z0-9._~:/?#@!$&'()*+,;=%-]+$/.test(k))return Z("install-agent","failed","invalid registry"),X(`Invalid registry URL: ${k}`);let S=await J.run(["sh","-c",`${F}npm_config_registry="${k}" bun install -g @vibecontrols/agent@${x} --no-cache`],{timeoutMs:600000});if(S.code!==0)return Z("install-agent","failed",S.stderr.slice(0,400)),X(`Agent install failed (exit ${S.code}).`);if(B=(await J.run(["sh","-c",`${F}vibe --version`],{timeoutMs:15000})).stdout.trim()||void 0,Z("install-agent","completed",B),Q.autostart)Z("autostart","running"),await J.run(["sh","-c",`${F}vibe autostart install`],{timeoutMs:60000}),Z("autostart","completed");if(Q.installPlugins?.length){Z("plugins","running");for(let u of Q.installPlugins)await J.run(["sh","-c",`${F}vibe plugin install ${u}`],{timeoutMs:300000});Z("plugins","completed")}Z("start","running"),await J.run(["sh","-c",`${F}vibe start`],{timeoutMs:60000}),Z("start","completed")}Z("bootstrap","running");let _=Q.expiresIn?` --expires-in ${Q.expiresIn}`:"",q=H.replace(/'/g,""),A=null;for(let G=0;G<15;G++){let x=`${F}vibe peer-bootstrap --json --emit-default-key --label '${q}' --scope ${V}${_} 2>/dev/null`,k=await J.run(["sh","-c",x],{timeoutMs:15000});if(k.code===0){let S=nQ(k.stdout);if(S&&typeof S.apiKey==="string"){A=S;break}}await new Promise((S)=>setTimeout(S,2000))}if(!A)return Z("bootstrap","failed","could not obtain peer-bootstrap bundle"),X("Remote peer-bootstrap did not return a credential bundle.");Z("bootstrap","completed");let U=o(),K=String(A.id),T=String(A.apiKey),I=e2(typeof A.tunnelUrl==="string"?A.tunnelUrl:null),P=typeof A.agentRecordId==="string"?A.agentRecordId:null;if(Q.onboardBackend!==!1&&l.isConfigured()&&I&&typeof A.fullDefaultApiKey==="string"){Z("onboard","running");let G=5,x="no agent returned";for(let k=0;k<G;k++){try{let u=(await l.workspaceQuery(lQ,{input:{tunnelUrl:I,apiKey:A.fullDefaultApiKey,name:H}})).data?.addVibecontrolsAgentFromTunnel;if(u?.agent?.id){P=u.agent.id,x="",Z("onboard","completed",`agent ${P}`);break}x=u?.error??"no agent returned"}catch(m){x=m instanceof Error?m.message:String(m)}if(!/unreachable|resolve hostname|timed out|timeout|ECONN|network|to fetch|50[234]/i.test(x)||k===G-1)break;Z("onboard","running",`retry ${k+1}/${G-1}: ${x.slice(0,80)}`),await new Promise((m)=>setTimeout(m,3000*(k+1)))}if(x)Z("onboard","failed",x)}else Z("onboard","skipped");Z("store-creds","running"),e4({id:K,label:H,tunnelUrl:I??"",apiKey:T,permissions:Y,addedAt:new Date().toISOString(),agentRecordId:P??void 0,workspaceId:(typeof A.workspaceId==="string"?A.workspaceId:U.workspaceId)??void 0,fingerprint:K,ownerUserId:U.ownerUserId,sshTarget:J.mode==="ssh"?Q.target:void 0,sshIdentityFile:Q.identityFile}),Z("store-creds","completed");let E=o2();if(Q.onboardBackend!==!1&&l.isConfigured()&&E&&P){Z("report-link","running");try{await l.workspaceQuery(dQ,{input:{sourceAgentRecordId:E,destinationAgentRecordId:P,label:H}}),Z("report-link","completed")}catch(G){Z("report-link","failed",G instanceof Error?G.message:String(G))}}else Z("report-link","skipped");let C=await w2(K,"/api/profiles/default/agent/identity",{operation:"post-deploy-probe"});return Z("probe-peer",C.ok?"completed":"failed",C.error??void 0),{ok:!0,peerId:K,agentRecordId:P,tunnelUrl:I,permissions:Y,remoteVersion:B}}catch(_){return X(_ instanceof Error?_.message:String(_))}finally{await J.close().catch(()=>{})}}var I0='export PATH="$HOME/.bun/bin:$PATH"; ';function iQ(Q){let $=Q.indexOf("{"),Z=Q.lastIndexOf("}");if($>=0&&Z>$)try{let Y=JSON.parse(Q.slice($,Z+1));if(Y.tunnelUrl)return Y.tunnelUrl;if(Y.url&&Y.url.startsWith("https"))return Y.url}catch{}return null}async function X5(Q,$){let Z=(J,H,V)=>$?.({step:J,status:H,message:V}),Y=Z5(Q);if(!Y)return{ok:!1,peerId:Q,tunnelUrl:null,error:`No peer with id ${Q}`};if(!Y.sshTarget)return{ok:!1,peerId:Q,tunnelUrl:null,error:"No SSH target stored for this peer \u2014 it wasn't SSH-deployed, so it can't be woken via SSH."};let X;try{X=Q0(Y.sshTarget,{identityFile:Y.sshIdentityFile})}catch(J){return{ok:!1,peerId:Q,tunnelUrl:null,error:J instanceof Error?J.message:String(J)}}try{Z("ssh-restart","running",Y.sshTarget);let J=await X.run(["sh","-c",`${I0}vibe restart 2>/dev/null || ${I0}vibe start`],{timeoutMs:90000});if(J.code!==0)return Z("ssh-restart","failed",J.stderr.slice(0,300)),{ok:!1,peerId:Q,tunnelUrl:null,error:`Remote restart failed (exit ${J.code})`};Z("ssh-restart","completed"),Z("await-tunnel","running");let H=null;for(let V=0;V<15;V++){let B=await X.run(["sh","-c",`${I0}vibe url --json 2>/dev/null`],{timeoutMs:15000});if(B.code===0){let F=iQ(B.stdout),_=e2(F);if(_){H=_;break}}await new Promise((F)=>setTimeout(F,2000))}if(!H)return Z("await-tunnel","failed","no fresh tunnel after restart"),{ok:!1,peerId:Q,tunnelUrl:null,error:"Agent restarted but no fresh tunnel came up."};return Z("await-tunnel","completed",H),J5(Q,{tunnelUrl:H,lastReachable:new Date().toISOString()}),Z("update","completed"),{ok:!0,peerId:Q,tunnelUrl:H}}catch(J){return{ok:!1,peerId:Q,tunnelUrl:null,error:J instanceof Error?J.message:String(J)}}finally{await X.close().catch(()=>{})}}var rQ=Number(process.env.VIBECONTROLS_MESH_MAX_HOPS||"8");function Y5(){return(b()??W()).name}function tQ(){return(b()??W()).dataDir}function H5(){try{let $=sQ(tQ(),"runtime.json");if(oQ($)){let Z=JSON.parse(aQ($,"utf8"));if(Z.port&&Number.isInteger(Z.port))return Z.port}}catch{}let Q=Number(process.env.PORT);return Number.isInteger(Q)&&Q>0?Q:3005}function eQ(Q){let $={};return Q.headers.forEach((Z,Y)=>{$[Y]=Z}),$}function Y2(Q,$){let Z=p(eQ(Q));return W5(V5(Z),$)}function Q6(Q){let{apiKey:$,...Z}=Q;return{...Z,apiKey:"[REDACTED]"}}function z5(Q){return typeof Q==="string"&&Q.startsWith("/api/")&&!Q.includes("..")&&!Q.includes("//")}var $0=new Map;function $6(){let Q=Date.now()-3600000;for(let[$,Z]of $0)if(Z.completedAt&&Date.parse(Z.completedAt)<Q)$0.delete($)}function K5(){return new v({name:"agent-mesh"}).get("/api/mesh/peers",({request:Q,set:$})=>{if(!Y2(Q,["read"]))return $.status=403,{error:"forbidden"};return{peers:_2(o()).map(Q6)}}).delete("/api/mesh/peers/:id",({request:Q,set:$,params:Z})=>{if(!Y2(Q,["mutate"]))return $.status=403,{error:"forbidden"};if(!_2(o()).some((X)=>X.id===Z.id))return $.status=404,{error:"not found"};return{ok:B5(Z.id)}}).post("/api/mesh/peers/:id/call",async({request:Q,set:$,params:Z,body:Y})=>{if(!Y2(Q,["mesh:forward"]))return $.status=403,{error:"forbidden"};let X=Y;if(!z5(X.path))return $.status=400,{error:"invalid path"};if(!_2(o()).find((V)=>V.id===Z.id))return $.status=404,{error:"not found"};let H=await w2(Z.id,X.path,{method:X.method??"GET",body:X.body,operation:"mesh-call"});return{ok:H.ok,status:H.status,data:H.data,rotated:H.rotated,error:H.error}},{body:z.Object({method:z.Optional(z.String()),path:z.String(),body:z.Optional(z.Any())})}).post("/api/mesh/forward",async({request:Q,set:$,body:Z})=>{if(!Y2(Q,["mesh:forward"]))return $.status=403,{error:"forbidden"};let Y=Z;if(!Y.request||!z5(Y.request.path))return $.status=400,{error:"invalid request"};let X=(Y._hopCount??0)+1;if(X>rQ)return $.status=422,{error:"hop limit exceeded"};let J=o(),H=o2(),V=Y.hops??[];if(V.length===0){W().audit.emit("mesh","forward.terminal",{path:Y.request.path,method:Y.request.method??"GET"});let U=(Y.request.method??"GET").toUpperCase();try{let K=await fetch(`http://127.0.0.1:${H5()}${Y.request.path}`,{method:U,headers:{"x-agent-api-key":await C0(),...Y.request.body!==void 0?{"content-type":"application/json"}:{}},body:Y.request.body!==void 0?JSON.stringify(Y.request.body):void 0,signal:AbortSignal.timeout(60000)}),T=await K.text().catch(()=>""),I=null;try{I=T?JSON.parse(T):null}catch{I=null}return{ok:K.ok,status:K.status,data:I,text:T||null,error:K.ok?null:T||`status ${K.status}`}}catch(K){return $.status=502,{ok:!1,status:0,error:K instanceof Error?K.message:String(K)}}}let B=V[0],F=Y._traversed??[];if(B===H||F.includes(B))return $.status=422,{error:"cycle detected",at:B};let _=q0(B,J);if(!_)return $.status=403,{error:"next hop not in authorized boundary"};if(!_.permissions.includes("mesh:forward"))return $.status=403,{error:"peer lacks mesh:forward grant"};W().audit.emit("mesh","forward.hop",{nextId:B,remaining:V.length,hopCount:X});let q=encodeURIComponent(Y5()),A=await w2(_.id,`/api/profiles/${q}/mesh/forward`,{method:"POST",operation:"mesh-forward",timeoutMs:60000,body:{hops:V.slice(1),request:Y.request,_traversed:[...F,H??"self"],_hopCount:X}});if(!A.ok)return $.status=502,{ok:!1,status:A.status,error:A.error,failedAtHop:B};return A.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:Q,set:$,body:Z})=>{if(!Y2(Q,["admin"]))return $.status=403,{error:"forbidden"};$6();let Y=Z,X=o(),J=crypto.randomUUID(),H={id:J,status:"running",steps:[],ownerUserId:X.ownerUserId,workspaceId:X.workspaceId,startedAt:new Date().toISOString()};return $0.set(J,H),$5({target:Y.target,permissions:Y.permissions,installPlugins:Y.installPlugins,autostart:Y.autostart,identityFile:Y.identityFile,label:Y.label,version:Y.version,connectExisting:Y.connectExisting},(V)=>{H.steps.push(V),H2("mesh:deploy:progress",{jobId:J,step:V})}).then((V)=>{if(H.result=V,H.status=V.ok?"completed":"failed",!V.ok)H.error=V.error;H.completedAt=new Date().toISOString(),H2(V.ok?"mesh:deploy:complete":"mesh:deploy:failed",{jobId:J,result:V})}).catch((V)=>{H.status="failed",H.error=V instanceof Error?V.message:String(V),H.completedAt=new Date().toISOString(),H2("mesh:deploy:failed",{jobId:J,error:H.error})}),$.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:Q,set:$,params:Z})=>{if(!Y2(Q,["read"]))return $.status=403,{error:"forbidden"};let Y=$0.get(Z.id),X=o();if(!Y||X.ownerUserId&&Y.ownerUserId&&Y.ownerUserId!==X.ownerUserId)return $.status=404,{error:"not found"};return Y}).post("/api/mesh/wake",async({request:Q,set:$,body:Z})=>{if(!Y2(Q,["admin"]))return $.status=403,{error:"forbidden"};let Y=Z,X=q0(Y.targetAgentRecordId,o());if(!X)return $.status=404,{ok:!1,error:"peer not in authorized boundary"};W().audit.emit("mesh","wake.start",{peerId:X.id,agentRecordId:Y.targetAgentRecordId});let J=await X5(X.id,(H)=>H2("mesh:wake:progress",{peerId:X.id,step:H}));if(!J.ok)$.status=502;return J},{body:z.Object({targetAgentRecordId:z.String()})}).post("/api/mesh/session",async({request:Q,set:$,body:Z})=>{if(!Y2(Q,["mesh:forward","mutate"]))return $.status=403,{error:"forbidden"};let Y=Z,X=Y.sessionId&&/^[A-Za-z0-9_-]{1,128}$/.test(Y.sessionId)?Y.sessionId:crypto.randomUUID(),J=encodeURIComponent(Y5()),H=await C0(),V=`http://127.0.0.1:${H5()}`,B=Y.command||"bash";try{let F=await fetch(`${V}/api/profiles/${J}/sessions/create`,{method:"POST",headers:{"x-agent-api-key":H,"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(!F.ok)return $.status=502,{error:`session create returned ${F.status}: ${await F.text().catch(()=>"")}`};let _=await fetch(`${V}/api/profiles/${J}/sessions/${encodeURIComponent(X)}/terminal`,{method:"POST",headers:{"x-agent-api-key":H},signal:AbortSignal.timeout(20000)});if(!_.ok)return $.status=502,{error:`terminal start returned ${_.status}: ${await _.text().catch(()=>"")}`};let q=u2(`/terminal/${X}`,600);return W().audit.emit("mesh","session.created",{sessionId:X,kind:Y.kind??"TERMINAL"}),{connectionId:X,sessionId:X,capabilityToken:q.token,expiresAt:q.expiresAt}}catch(F){return $.status=502,{error:F instanceof Error?F.message:String(F)}}},{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 Z6=["/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 J6(Q){return Z6.some(($)=>Q.startsWith($))}var X6=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Y6(Q){return Q.split("/").map(($)=>{if(!$)return $;if(/^\d+$/.test($))return":id";if(X6.test($))return":id";if($.length>=24&&/^[A-Za-z0-9_-]+$/.test($))return":id";return $}).join("/")}async function x9(Q){let{port:$,host:Z,dbPath:Y,logLevel:X,corsOrigin:J}=Q,H=Y??C2();try{(await import("fs")).mkdirSync(H,{recursive:!0})}catch(L){throw W().logger.error("app","Failed to create dbPath dir at boot",{dbPath:H,error:String(L)}),Error(`Cannot create dbPath ${H}: ${L instanceof Error?L.message:String(L)}`,{cause:L})}if(X)W().logger.setLevel(X);(async()=>{let{logShipper:L}=await import("./log-shipper-9xfnjwr6.js");L.init()})(),(async()=>{let L=await G5();await f2({version:L,profile:k2()})})();try{let{checkDependencies:L}=await import("./bootstrap.service-nxhkrsf1.js"),M=L(),N=M.filter((R)=>R.required&&!R.installed),w=M.filter((R)=>!R.required&&!R.installed);if(N.length>0)W().logger.error("app",`Missing required system deps: ${N.map((R)=>R.name).join(", ")}. Run \`vibe setup\` to install.`);if(w.length>0)W().logger.warn("app",`Missing optional system deps: ${w.map((R)=>R.name).join(", ")}. Some plugins may fail their prereqs check.`)}catch(L){W().logger.warn("app","Boot-time dependency check failed",{error:String(L)})}try{W().audit.runRetention()}catch(L){W().logger.warn("app","Audit-log retention sweep failed",{error:String(L)})}let V=new D5;g5(V,{port:$});let B="GET, POST, PUT, PATCH, DELETE, OPTIONS",F="Content-Type, x-agent-api-key, Authorization, x-requested-with",_=Array.isArray(J)?J:(J??"").split(",").map((L)=>L.trim()).filter(Boolean),q=new Set(["https://vibecontrols.com","https://app.vibecontrols.com","https://alphaapp.vibecontrols.com","https://burdenoff.com","https://app.burdenoff.com","https://alphaapp.burdenoff.com"]),A=(L)=>{try{let M=new URL(L);if(_.includes(L))return!0;if(_.includes("*"))return!1;return M.hostname==="localhost"||M.hostname==="127.0.0.1"||M.hostname==="0.0.0.0"||M.hostname.endsWith(".local.burdenoff.com")||q.has(M.origin)}catch{return!1}},U=null,K=null,T=null,I=null,P=!1,E=()=>[],C=null,G=null,x=null,k=5000,S=async(L,M)=>{let N=Date.now();try{await Promise.race([Promise.resolve(M()),new Promise((w,R)=>setTimeout(()=>R(Error(`shutdown phase ${L} exceeded ${k}ms`)),k))]),W().logger.info("app",`shutdown.phase ${L} complete`,{ms:Date.now()-N})}catch(w){W().logger.warn("app",`shutdown.phase ${L} failed`,{error:String(w),ms:Date.now()-N})}},m=async(L)=>{if(P)return;if(P=!0,W().logger.info("app","Agent shutdown starting",{reason:L?.reason??"shutdown"}),await S("plugins",async()=>{if(K)await K.dispatchServerStop(L)}),await S("bootstrap-tunnel",()=>S0()),await S("tracked-subprocesses",async()=>{let{killAllTracked:M}=await import("./subprocess-zcgpccp1.js");await M()}),L?.reason!=="reload")await S("db-close",async()=>{if(U)await U.close()});await S("http-listener",async()=>{try{await Promise.resolve(Q2.stop())}catch(M){W().logger.warn("app","Listener stop threw (already stopped or never started?)",{error:String(M)})}}),W().logger.info("app","Agent server stopped"),W().logger.close()},u=async(L,M)=>{if(W().getBootState()==="ready")return{ok:!0};if(x)return x;return x=(async()=>{W().setBootState("initializing");try{let N={...L,globalGatewayUrl:K2(L.globalGatewayUrl,"globalGatewayUrl"),workspaceGatewayUrl:K2(L.workspaceGatewayUrl,"workspaceGatewayUrl")},w=await v5(N),R=H,f=e({dir:W().dataDir}),d=f.storageAdapter??process.env.VIBE_STORAGE_ADAPTER??void 0,s=f.storageOptions,$2=(j)=>{let O=(j instanceof Error?j.message:String(j)).toLowerCase(),D=j&&typeof j==="object"&&"code"in j?String(j.code).toUpperCase():"";if(D==="EBUSY"||D==="EPERM"||D==="EACCES"||D==="EAGAIN"||D==="EMFILE"||D==="ENFILE"||D==="ETIMEDOUT"||D==="ECONNRESET"||D==="ECONNREFUSED"||O.includes("encryption key")||O.includes("fetch")&&O.includes("key")||O.includes("temporarily unavailable")||O.includes("resource busy"))return"transient";if(O.includes("auth tag")||O.includes("authentication tag")||O.includes("unable to authenticate data")||O.includes("bad decrypt")||O.includes("unsupported state")||O.includes("incorrect header check")||O.includes("invalid distance")||O.includes("incorrect data check")||O.includes("unexpected end of")||O.includes("unexpected token")||O.includes("json")&&(O.includes("parse")||O.includes("invalid"))||O.includes("truncated")||O.includes("malformed")||O.includes("corrupt"))return"corruption";return"unknown"},U2=()=>L5({dbPath:R,encryptionKey:w,adapterName:d,adapterOptions:s});try{U=await U2()}catch(j){let O=j,D=$2(j),D2=[500,2000,8000];if(D==="transient"||D==="unknown"){W().logger.warn("app",`Storage open failed (${D}); will retry up to ${D2.length} times before quarantine`,{error:j instanceof Error?j.message:String(j),path:R});for(let T2 of D2){await new Promise((y)=>setTimeout(y,T2));try{U=await U2(),O=null;break}catch(y){if(O=y,D=$2(y),W().logger.warn("app",`Storage open retry failed (${D}) after ${T2}ms`,{error:y instanceof Error?y.message:String(y)}),D==="corruption")break}}}if(!U&&O){if(D!=="corruption"){let y=O instanceof Error?O.message:String(O);W().logger.error("app",`Storage open failed after retries with non-corruption error (${D}); refusing to quarantine valid data`,{error:y,path:R}),W().recordDegradedReason("storage",y);try{throw O}catch(B2){throw Error(`Storage open failed (${D}); agent is degraded: ${y}`,{cause:B2})}}let T2=O instanceof Error?O.message:String(O);W().logger.error("app","QUARANTINE: Storage file is corrupt \u2014 renaming and creating fresh DB",{errorClass:"corruption",error:T2,path:R});try{let y=await import("fs");if(y.existsSync(R)){let B2=new Date().toISOString().replace(/[:.]/g,"-"),v0=`${R}.broken-${B2}`;y.renameSync(R,v0),W().logger.warn("app",`Quarantined corrupt storage to ${v0} \u2014 fresh DB will be created`,{originalError:T2})}U=await U2()}catch(y){let B2=y instanceof Error?y.message:String(y);throw W().recordDegradedReason("storage",B2),Error(`Storage open failed twice (quarantine path); agent is degraded: ${B2}`,{cause:y})}}}if(!U)throw Error("Internal error: storage open recovery exited without an open database and without throwing");if(await c2({clientId:N.clientId,clientSecret:N.clientSecret,workspaceId:N.workspaceId,organizationId:N.organizationId,globalGatewayUrl:N.globalGatewayUrl,workspaceGatewayUrl:N.workspaceGatewayUrl,agentRecordId:M?.agentRecordId,scopes:M?.scopes,pairedIdentity:m2({workspaceId:N.workspaceId,globalGatewayUrl:N.globalGatewayUrl,workspaceGatewayUrl:N.workspaceGatewayUrl,agentRecordId:M?.agentRecordId})},{dir:W().dataDir,scope:W().name}),await U.setConfig("gateway-auth:clientId",N.clientId),await U.setConfig("gateway-auth:clientSecret",N.clientSecret),await U.setConfig("gateway-auth:globalGatewayUrl",N.globalGatewayUrl),await U.setConfig("gateway-auth:workspaceGatewayUrl",N.workspaceGatewayUrl),await U.setConfig("gateway-auth:workspaceId",N.workspaceId),N.organizationId)await U.setConfig("gateway-auth:organizationId",N.organizationId);if(M?.agentRecordId)await U.setConfig("gateway-auth:agentRecordId",M.agentRecordId);V.db=U,await V.hydrateDefaultsFromDb(),K=new c5(U),await K.loadCorePlugins();try{await K.loadAll()}catch(j){W().logger.warn("app","Failed to load some external plugins",{error:String(j)})}let x2=m5(L2())??void 0,M2=process.env.VIBE_SKIP_AUTO_INSTALL==="1"||await U.getConfig("plugins:auto-install-disabled");if(M2!=="true"&&M2!==!0)try{let j=await K.ensureDefaultPlugins((O)=>W().logger.info("app",`[auto-install] ${O}`),[],x2);if(j.length>0)W().logger.info("app",`Auto-installed ${j.length} default plugin(s): ${j.map((O)=>O.packageName).join(", ")}`)}catch(j){W().logger.warn("app","Failed to auto-install default plugins",{error:String(j)})}W().logger.info("app",`Plugins loaded: ${K.getPluginDetails().length} total (${K.getPluginDetails().filter((j)=>j.isCore).length} core)`);try{let j=K.getPluginDetails(),O={loaded:j.filter((D)=>D.loaded).length,failed:j.filter((D)=>!D.loaded).length};l0(O)}catch{}let J0={async get(j,O){return await U.getPluginState(j,O)??null},async set(j,O,D){await U.setPluginState(j,O,D)},async delete(j,O){return U.deletePluginState(j,O)},async list(j){return await U.getAllPluginState(j)},async deleteAll(j){return U.deleteAllPluginState(j)}},S2=await G5();T={storage:J0,logger:W().logger,serviceRegistry:V,getProvider:(j)=>V.getProvider(j),getAgentBaseUrl:()=>process.env.AGENT_URL||`http://localhost:${$}`,getAgentVersion:()=>S2,validateApiKey:(j)=>n(j),setCodeServerSessionValidator:(j)=>{p5=j},broadcast:H2,workspaceQuery:async(j,O)=>l.workspaceQuery(j,O),isGatewayConfigured:()=>l.isConfigured(),getAgentRecordId:async()=>await U.getConfig("gateway-auth:agentRecordId")??null,getWorkspaceId:async()=>await U.getConfig("gateway-auth:workspaceId")??null,getConfig:async(j)=>await U.getConfig(j)??void 0,getPluginRegistry:()=>t2(),getDataDir:()=>b2(),cliContributors:new h5,audit:{emit:(j,O)=>W().audit.emit("agent",j,O??{})},telemetry:{emit:(j,O)=>{import("./telemetry-k6em3vy2.js").then(({telemetryService:D})=>D.emit(j,O??{})).catch(()=>{})}},os:N2(),iframeBridge:y5()},l.configure({globalGatewayUrl:N.globalGatewayUrl,workspaceGatewayUrl:N.workspaceGatewayUrl,clientId:N.clientId,clientSecret:N.clientSecret,workspaceId:N.workspaceId,organizationId:N.organizationId});let W2={db:U,serviceRegistry:V,pluginManager:K,broadcast:H2,hostServices:T};W2.app=Q2;let h0=!1,X0=()=>{let{routes:j,getPublicPaths:O,mountPlugin:D}=O5(K,W2);if(W2.mountPlugin=D,E=O,M5(),C=j,G=b5(K),K&&h0&&T)K.dispatchServerStart(C,T).catch((D2)=>W().logger.warn("app","Re-dispatch of onServerStart after plugin reload failed",{error:String(D2)}));h0=!0};W2.rebuildPluginSurfaces=X0,X0(),I=new P5(V,K,U,Q2,T,m),V.registerService("agent","lifecycle",I),W().attachServices({db:U,serviceRegistry:V,pluginManager:K,lifecycle:I,hostServices:T}),w5(W(),{rebuildPluginSurfaces:X0,mountPlugin:W2.mountPlugin,app:C});try{await W().keyVault.bindApiKey(F2())}catch(j){W().logger.warn("app","Failed to bind api key into daemon keyVault",{error:String(j)})}let Y0=[];try{let{failures:j}=await K.dispatchServerStart(C,T);for(let O of j)if(w0(O.plugin)||(O.packageName?w0(O.packageName):!1))Y0.push(O),W().recordDegradedReason(O.plugin,O.error);else W().logger.warn("app",`Non-critical plugin ${O.plugin} failed onServerStart; continuing`,{error:O.error})}catch(j){W().logger.warn("app","Error during plugin onServerStart dispatch",{error:String(j)})}try{await K.dispatchServerReady(Q2,T)}catch(j){W().logger.warn("app","Error during plugin onServerReady dispatch",{error:String(j)})}if(W().clearFinalizeError(),Y0.length>0)W().setBootState("degraded"),W().logger.error("app","Agent finalized but degraded \u2014 critical plugins failed",{failures:Y0.map((j)=>`${j.plugin}: ${j.error}`)});else W().setBootState("ready"),W().logger.info("app","Agent finalized \u2014 state=ready"),W().audit.emit("agent","gateway-auth.configured",{workspaceId:N.workspaceId,organizationId:N.organizationId,agentRecordId:M?.agentRecordId});return(async()=>{try{if(await K.provisionDefaultPrereqs(Q2,T,W2.mountPlugin,x2),W().logger.info("app","Default provider prerequisites provisioned"),(V.listProvidersForType("tunnel")??[]).some((D)=>D.pluginName!=="bootstrap")){let{tryHandoverBootstrapTunnel:D}=await import("./tunnel-bootstrap-y8dczezc.js");if(!D())S0();V.unregisterProvider("tunnel","bootstrap"),W().logger.info("app","Bootstrap tunnel handed over to the real tunnel provider")}}catch(j){W().logger.warn("app","Plugin prerequisite provisioning failed",{error:String(j)})}})(),{ok:!0}}catch(N){W().setBootState("awaiting-config");let w=N instanceof Error?N.message:String(N);if(W().recordFinalizeError(w),W().logger.error("app","Finalize failed",{error:w}),process.env.VIBE_STRICT_KEY_FETCH==="1")W().logger.error("app","VIBE_STRICT_KEY_FETCH=1 \u2192 aborting daemon (strict mode)",{error:w}),setTimeout(()=>process.exit(1),50);return{ok:!1,error:w}}finally{x=null}})(),x},a=f0({origin:(L)=>{let M=L.headers.get("origin");return!!M&&A(M)},credentials:!0,allowedHeaders:F.split(",").map((L)=>L.trim()),methods:B.split(",").map((L)=>L.trim()),exposeHeaders:["content-type","content-length"],maxAge:86400,preflight:!0}),j2=10485760,O2=process.env.VIBECONTROLS_MAX_BODY_BYTES,Z0=O2?Number.parseInt(O2,10):NaN,l5=Number.isFinite(Z0)&&Z0>0?Z0:j2,D0={current:null},Q2=new v({serve:{maxRequestBodySize:l5}}).onRequest(({request:L,set:M})=>{let w=_5(L.headers)??k0();N5({requestId:w,startedAt:new Date().toISOString()});let R=M.headers??={};R["X-Request-Id"]=w}).onRequest(({request:L})=>{try{let M=new URL(L.url).pathname,w=/^\/api\/profiles\/([^/]+)(?:\/|$)/.exec(M)?.[1],R=w?t.get(w):null;R0(R??W())}catch{R0(W())}}).onRequest(({request:L,set:M})=>{let N=new URL(L.url).pathname;if(!N.startsWith("/api/"))return;if(N==="/api/profiles"||N.startsWith("/api/profiles/"))return;if(N==="/api/profile-stats"||N.startsWith("/api/profile-stats/"))return;let w=new URL(L.url);w.pathname=`/api/profiles/default${N.slice(4)}`;try{L.headers.set("x-vc-profile-rewrite","1"),L.headers.set("x-vc-profile-rewrite-target",w.pathname)}catch{}return}).derive(()=>({requestId:j5()??k0()})).use(a).use(A5()).use(T5(()=>E())).use(m0({getDb:()=>b()?.db??U})).onBeforeHandle(({request:L,set:M})=>{let N=W().getBootState();if(N==="ready")return;let w=new URL(L.url).pathname;if(J6(w))return;return M.status=503,{error:"Agent not yet configured",message:"Agent is in '"+N+"' state. POST credentials to /api/agent/gateway-auth to finalize.",state:N}}).onAfterHandle(({request:L,set:M})=>{let N=new URL(L.url).pathname,w=N==="/health"||N.startsWith("/api/logs/stream")||N.startsWith("/ui/")||N==="/ws/events"||N==="/api/sessions/health-check"||N.startsWith("/terminal/"),R=typeof M.status==="number"?M.status:200,f=w?"debug":R>=400?"warn":"info";W().logger[f]("http",`${L.method} ${N} \u2192 ${R}`,{method:L.method,path:N,statusCode:R});try{p0(L.method,Y6(N),R)}catch{}}).use(E4({serviceRegistry:V,getDb:()=>b()?.db??U,getDbPath:()=>H,getPluginManager:()=>b()?.pluginManager??K})).use(n0()).use(K4({serviceRegistry:V,runFinalize:(L,M)=>u(L,M),getDb:()=>b()?.db??U})).use(C4()).use(q4()).use(r4({getPluginManager:()=>b()?.pluginManager??K})).use(K5()).use(S4()).use(y4({getPluginManager:()=>b()?.pluginManager??K,getTunnelHost:()=>u5()?.url??null})).use(U4()).use(M4()).use(q5()).use(R5()).use(k5(V)).ws("/code-server/*",z6($)).all("/api/profiles/:name/*",async({params:L,request:M,set:N})=>{let w=M.method!=="GET"&&M.method!=="HEAD",R=w?await M.arrayBuffer():void 0,f=await S5(L.name,M,R);if(f&&f.status!==404)return f;let d=k2(),s=L.name;if(s!==d)return N.status=404,{error:"profile-mismatch",running:d,requested:s,hint:"This daemon serves a different profile. Call GET /api/profiles to discover the right tunnel."};let $2=new URL(M.url),U2=$2.pathname.replace(/^\/api\/profiles\/[^/]+/,"/api"),x2=new Headers(M.headers);x2.set("x-vc-profile-rewrite","1");let M2={method:M.method,headers:x2};if(w&&R!==void 0)M2.body=R;let J0=new Request(`${$2.origin}${U2}${$2.search}`,M2),S2=D0.current;if(!S2)return new Response(JSON.stringify({error:"agent-not-ready"}),{status:503,headers:{"content-type":"application/json"}});return S2.handle(J0)}).all("/api/*",async({request:L})=>{if(W().getBootState()!=="ready"||!C)return new Response(JSON.stringify({error:"Agent not yet configured",state:W().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(L.url),N=/^\/api\/plugins\/([a-z0-9-]{1,64})\/ui(?:\/.*)?$/.exec(M.pathname);if(N&&L.method==="GET"){let w=N[1];if(I2(w)){let R=M.pathname.slice(`/api/plugins/${w}/ui`.length),f=R===""||R==="/",s=L.headers.get("sec-fetch-mode")==="navigate";if(f||s){let $2=x5(L,w);if(!$2||!U5($2,w))return new Response(f5(w,"/api/profiles/default/agent/ui-exchange-plugin"),{status:200,headers:{"content-type":"text/html; charset=utf-8","Content-Security-Policy":"frame-ancestors 'self' http://localhost:* http://127.0.0.1:* https://localhost:* https://127.0.0.1:* https://*.local.burdenoff.com https://vibecontrols.com https://*.vibecontrols.com https://burdenoff.com https://app.burdenoff.com https://alphaapp.burdenoff.com"}})}}}}catch{}return C.handle(L)}).all("/ui/*",async({request:L})=>{if(W().getBootState()!=="ready"||!G)return new Response("Plugin UI not yet available",{status:503});return G.handle(L)}).all("/code-server/*",async({request:L})=>{if(W().getBootState()!=="ready"||!C)return new Response("code-server not yet available",{status:503});let M=b0(L,F2);return C.handle(M??L)}).all("/plan/*",async({request:L})=>{if(W().getBootState()!=="ready"||!C)return new Response("plan provider not yet available",{status:503});return C.handle(L)});return D0.current=Q2,{app:Q2,async start(){Q2.listen({port:$,hostname:Z}),W().logger.info("app",`Agent server listening on ${Z}:${$}`);try{let L=(process.env.VIBECONTROLS_PROFILES??"").split(",").map((f)=>f.trim()).filter(Boolean),M=W().name,{getOrCreateProfile:N}=await import("./daemon-profile-j2wt35x8.js"),{attachSecondaryProfile:w}=await import("./secondary-profile-attach-m9x9e7py.js"),R=process.env.VIBE_STRICT_KEY_FETCH==="1";for(let f of L){if(f===M)continue;try{let d=N(f),s=await w(d);if(s.ok)W().logger.info("app",`Secondary profile '${f}' attached (db+services online)`);else if(R)throw Error(`attachServices for secondary profile '${f}' failed: ${s.error}`);else d.recordDegradedReason("attach",s.error??"unknown"),W().logger.warn("app",`Secondary profile '${f}' is degraded (no creds / attach failed)`,{error:s.error})}catch(d){if(R)throw W().logger.error("app",`--strict-key-fetch: secondary profile '${f}' attach failed; aborting`,{error:String(d)}),setTimeout(()=>process.exit(1),50),d;W().logger.warn("app",`Failed to attach secondary profile '${f}'`,{error:String(d)})}}}catch{}return Q2},stop:m,finalize:u,getState:()=>W().getBootState(),getLifecycle:()=>b()?.lifecycle??I,getDb:()=>b()?.db??U,getServiceRegistry:()=>b()?.serviceRegistry??V,getPluginManager:()=>b()?.pluginManager??K,getHostServices:()=>b()?.hostServices??T}}var p5=null;function H6(Q,$){if(!Q)return null;let Z=Q.match(new RegExp(`(?:^|;\\s*)${$}=([^;]*)`));return Z?Z[1]:null}var F5=E5(I5);function z6(Q){let X=(J)=>typeof J==="string"?Buffer.byteLength(J):J.byteLength;return{open(J){let H=J.data,V=p(H.headers??{})??p(H.request?Object.fromEntries(H.request.headers.entries()):{}),B=H.query?.vt,F=!!B&&h2(B,"/code-server","GET"),_,q=n(V);if(!q&&!F){let T=H.headers?.cookie??H.request?.headers.get("cookie")??null,I=H6(T,"__vibe_cs_session");if(!I||!p5?.(I)){J.close(1008,"Unauthorized");return}_=`session:${I}`}else if(q)_="api-key";else _="vt";let A=J.remoteAddress??null,U=C5(A,H.headers);if(!F5.accept(_,U,J)){W().logger.warn("code-server-ws",`code-server WS cap exceeded (key=${_}, ip=${U??"unknown"})`),J.close(1013,"too many connections");return}H._csCapKey=_,H._csRemoteIp=U;let K=W().name;fetch(`http://127.0.0.1:${Q}/api/profiles/${encodeURIComponent(K)}/code-server/status`,{headers:{"x-agent-api-key":F2()}}).then((T)=>T.json()).then((T)=>{if(H._csClosed)return;let I=T;if(!I.running||!I.port){J.close(1011,"code-server not running");return}let P=H.request?.url??"/code-server/",E;try{let x=new URL(P,`http://127.0.0.1:${I.port}`);E=(x.pathname.replace(/^\/code-server\/?/,"/")||"/")+x.search}catch{E="/"}let C=new WebSocket(`ws://127.0.0.1:${I.port}${E}`),G={upstream:C,ready:!1,buffer:[],bufferBytes:0,openTimer:setTimeout(()=>{try{C.close(1011,"upstream open timeout")}catch{}try{J.close(1011,"upstream open timeout")}catch{}},1e4)};H._csBridge=G,C.addEventListener("open",()=>{clearTimeout(G.openTimer),G.ready=!0;for(let x of G.buffer)C.send(x);G.buffer.length=0,G.bufferBytes=0}),C.addEventListener("message",(x)=>{try{let k=x.data;if(k instanceof ArrayBuffer)J.send(new Uint8Array(k));else if(k instanceof Blob)k.arrayBuffer().then((S)=>{try{J.send(new Uint8Array(S))}catch{}});else J.send(k)}catch{}}),C.addEventListener("close",(x)=>{clearTimeout(G.openTimer);try{J.close(x.code||1000,x.reason||"upstream closed")}catch{}}),C.addEventListener("error",()=>{clearTimeout(G.openTimer);try{J.close(1011,"upstream error")}catch{}})}).catch(()=>{J.close(1011,"Failed to query code-server status")})},message(J,H){let V=J.data?._csBridge;if(!V)return;let B;if(typeof H==="string")B=H;else if(H instanceof ArrayBuffer)B=H;else if(H instanceof Uint8Array||Buffer.isBuffer(H)){let F=new ArrayBuffer(H.byteLength);new Uint8Array(F).set(new Uint8Array(H.buffer,H.byteOffset,H.byteLength)),B=F}else if(typeof H==="object"&&H!==null)B=JSON.stringify(H);else B=String(H);if(V.upstream&&V.ready&&V.upstream.readyState===WebSocket.OPEN)try{V.upstream.send(B)}catch{}else{let F=X(B);if(V.buffer.length>=256||V.bufferBytes+F>1048576){try{V.upstream.close(1013,"buffer limit exceeded")}catch{}try{J.close(1013,"buffer limit exceeded")}catch{}return}V.buffer.push(B),V.bufferBytes+=F}},close(J){J.data._csClosed=!0;let H=J.data?._csBridge;if(H?.openTimer)clearTimeout(H.openTimer);if(H?.upstream&&H.upstream.readyState===WebSocket.OPEN)H.upstream.close(1000,"client disconnected");let V=J.data._csCapKey,B=J.data._csRemoteIp;if(V)F5.release(V,B??null,J)}}}async function G5(){try{let{readFileSync:Q}=await import("fs"),{join:$,dirname:Z}=await import("path"),{fileURLToPath:Y}=await import("url"),X=Z(Y(import.meta.url));return JSON.parse(Q($(X,"..","package.json"),"utf8")).version||"1.0.0"}catch{return"1.0.0"}}
|
|
26
|
-
export{q6 as j,a0 as k,PQ as l,c7 as m,x9 as n};
|
package/dist/index-54mmh1eb.js
DELETED
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
function V(j){let H=[["--version"],["-V"],["version"]];for(let F of H)try{let z=Bun.spawnSync([j,...F],{timeout:5000,stdout:"pipe",stderr:"pipe"});if(z.exitCode===0){let J=z.stdout.toString().trim(),K=z.stderr.toString().trim();return{installed:!0,version:(J||K).split(`
|
|
3
|
-
`)[0]||void 0}}}catch{}try{if(Bun.which(j,{PATH:process.env.PATH}))return{installed:!0}}catch{}return{installed:!1}}var X=[{name:"bun",cmd:"bun",required:!0,category:"runtime"}];function Z(j){let H=X.map((F)=>{let{installed:z,version:J}=V(F.cmd);return{name:F.name,installed:z,version:J,required:F.required,category:F.category}});if(j!==void 0){let F=j instanceof Set?j:new Set(j);for(let z of F){if(H.some((Q)=>Q.name===z))continue;let{installed:J,version:K}=V(z);H.push({name:z,installed:J,version:K,required:!1,category:"tool"})}}return H}async function $(j){return{success:!0,installed:[],failed:[],skipped:j??[]}}
|
|
4
|
-
export{Z as S,$ as T};
|
package/dist/index-6jzsthh9.js
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{promises as g,closeSync as R,constants as S,fstatSync as m,lstatSync as E,openSync as P,readSync as f,realpathSync as N,statSync as c}from"fs";import W from"os";import K from"path";function Y(j,G){let q=parseInt(process.env[j]??"",10);return Number.isInteger(q)&&q>0?q:G}var b=Y("VIBECONTROLS_MAX_FILE_READ_BYTES",10485760),M=Y("VIBECONTROLS_MAX_DIRECTORY_ENTRIES",2000),F=[/(?:^|\/)\.env(?:\..*)?$/,/\.pem$/,/\.key$/,/(?:^|\/)id_rsa(?:$|\.)/,/(?:^|\/)\.ssh(?:\/|$)/,/(?:^|\/)\.git\/config$/,/(?:^|\/)\.npmrc$/],X=["/","/etc","/usr","/bin","/sbin","/var","/opt"],z=["C:\\Windows","C:\\Program Files","C:\\Program Files (x86)","C:\\ProgramData"];function C(){return process.platform==="win32"?z:X}function V(j){return process.platform==="win32"?j.toLowerCase():j}function y(){let j=process.env.VIBECONTROLS_ALLOWED_ROOTS;if(j)return j.split(K.delimiter).map((G)=>G.trim()).filter(Boolean);return[process.cwd(),W.homedir(),W.tmpdir()].filter(Boolean)}async function U(j){try{return await g.realpath(j)}catch{return null}}async function w(){let j=[];for(let G of y()){let q=K.resolve(G),J=await U(q)??q;if(!j.includes(J))j.push(J)}return j}function A(j,G){let q=K.relative(G,j);return q===""||!!q&&!q.startsWith("..")&&!K.isAbsolute(q)}async function L(j){if(!(await w()).some((q)=>A(j,q)))throw Error("Access denied: path is outside allowed directories")}async function T(j){let G=K.dirname(j);while(G&&G!==K.dirname(G)){let J=await U(G);if(J)return J;G=K.dirname(G)}let q=await U(G||K.parse(j).root);if(!q)throw Error("Path parent does not exist");return q}async function u(j){if((await g.lstat(K.resolve(j)).catch(()=>null))?.isSymbolicLink())throw Error("Access denied: symbolic links are not allowed")}function d(j){return F.some((G)=>G.test(j))}function I(j){if(!j.startsWith("/"))return!1;let G=j.replace(/\\/g,"/").replace(/\/+/g,"/");return X.some((q)=>G===q||G.startsWith(q==="/"?"/":`${q}/`))}function i(j){let G=K.resolve(j),q=(()=>{try{return N(G)}catch{return null}})(),J=q?[G,q]:[G],Q=W.tmpdir(),H=W.homedir(),v=(()=>{try{return N(Q)}catch{return Q}})(),x=(()=>{try{return N(H)}catch{return H}})(),O=K.sep,D=[Q,v,H,x];for(let k of J){let Z=V(k);if(D.some((B)=>{let $=V(B);return Z===$||Z.startsWith($+O)}))return!1}if(J.some((k)=>{let Z=V(k);return C().some((B)=>{let $=V(B);return Z===$||Z.startsWith($+O)})}))return!0;return I(j)}async function s(j,G={}){if(!j||j.includes("\x00"))throw Error("Invalid path");let q=K.resolve(j);await u(q);let J=await U(q);if(J)return await L(J),{path:q,realPath:J};if(G.mustExist)throw Error("Path not found");if(!G.forWrite)return await L(q),{path:q,realPath:q};let Q=await T(q);return await L(Q),{path:q,realPath:q}}async function l(j){let G=await g.stat(j);if(G.isFile()&&G.size>b)throw Error(`File is too large to read safely (${G.size} bytes, max ${b})`)}async function n(j){let G=await g.opendir(j),q=[];try{for await(let J of G)if(q.push(J),q.length>M)throw Error(`Directory has too many entries (>${M})`)}finally{let J=G.close?.();if(J&&typeof J.catch==="function")await J.catch(()=>{return})}return q}
|
|
3
|
-
export{d as C,i as D,s as E,l as F,n as G};
|