@vibecontrols/agent 2026.601.30
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/LICENSE +22 -0
- package/README.md +558 -0
- package/dist/agent-config-85pskv43.js +2 -0
- package/dist/agent-ready-tracker-zp6p8e6f.js +2 -0
- package/dist/app-yvjadjmh.js +2 -0
- package/dist/bootstrap-workspace-zpm20zez.js +2 -0
- package/dist/bootstrap.service-pjmnpxha.js +2 -0
- package/dist/bridge-client-341r9rry.js +2 -0
- package/dist/cli.js +5 -0
- package/dist/daemon-profile-vas1vf2t.js +2 -0
- package/dist/esm-9fpye77x.js +2 -0
- package/dist/finalize-retry-handle-registry-vv241fsq.js +2 -0
- package/dist/finalize-retry-worker-xp1nhv3c.js +2 -0
- package/dist/gateway-client-43gzvj5s.js +2 -0
- package/dist/getMachineId-bsd-a56s0v8c.js +2 -0
- package/dist/getMachineId-darwin-w9k0yw9r.js +3 -0
- package/dist/getMachineId-linux-anh31jbf.js +2 -0
- package/dist/getMachineId-unsupported-5hv3pwca.js +2 -0
- package/dist/getMachineId-win-njb8tery.js +2 -0
- package/dist/highlights-8d9mgr01.js +2 -0
- package/dist/highlights-eq9cgrbb.scm +604 -0
- package/dist/highlights-ghv9g403.scm +205 -0
- package/dist/highlights-hk7bwhj4.scm +284 -0
- package/dist/highlights-jwvdxm9x.js +2 -0
- package/dist/highlights-qbx2vnme.js +2 -0
- package/dist/highlights-r3m83kn9.js +2 -0
- package/dist/highlights-r812a2qc.scm +150 -0
- package/dist/highlights-s7mqapt6.js +2 -0
- package/dist/highlights-x6tmsnaa.scm +115 -0
- package/dist/index-01qzsnwd.js +16 -0
- package/dist/index-0248afsn.js +3 -0
- package/dist/index-04n4qgvd.js +407 -0
- package/dist/index-0ckffygp.js +5 -0
- package/dist/index-0cn9bv8z.js +4 -0
- package/dist/index-1hnw0rhc.js +178 -0
- package/dist/index-1zw3kea7.js +10 -0
- package/dist/index-2gsarrbn.js +4 -0
- package/dist/index-2xs9cvjn.js +28 -0
- package/dist/index-3ys16efc.js +231 -0
- package/dist/index-4wgjx8bf.js +3 -0
- package/dist/index-52cp759f.js +3 -0
- package/dist/index-5mw3eshk.js +4 -0
- package/dist/index-678rwfc0.js +5 -0
- package/dist/index-6jq17k9s.js +7 -0
- package/dist/index-6jzsthh9.js +3 -0
- package/dist/index-6mprnf7p.js +9 -0
- package/dist/index-8kvc8ttn.js +15 -0
- package/dist/index-8sm0nkh8.js +3 -0
- package/dist/index-9bqd8veb.js +21 -0
- package/dist/index-b5dhmybd.js +4 -0
- package/dist/index-c58g96mb.js +26 -0
- package/dist/index-cs78wq6y.js +3 -0
- package/dist/index-d5ysy1yn.js +3 -0
- package/dist/index-dm6yjmgq.js +3 -0
- package/dist/index-e1bw1bwr.js +4 -0
- package/dist/index-ef95xr4z.js +9 -0
- package/dist/index-g2raeeh4.js +11 -0
- package/dist/index-g3ap3xpr.js +5 -0
- package/dist/index-g8zv1gta.js +17 -0
- package/dist/index-h8a8s8sn.js +3 -0
- package/dist/index-hrdamx5j.js +2 -0
- package/dist/index-jw1k4vbk.js +3 -0
- package/dist/index-mtm8cfyt.js +158 -0
- package/dist/index-mxc61yr1.js +3 -0
- package/dist/index-n7qyrdr1.js +3 -0
- package/dist/index-qfz9fy56.js +3 -0
- package/dist/index-rc79x8fw.js +3 -0
- package/dist/index-rdp5xq4r.js +15 -0
- package/dist/index-scsjyj4m.js +171 -0
- package/dist/index-ssjmzqcz.js +13 -0
- package/dist/index-tmrbs96r.js +11 -0
- package/dist/index-tp4y9jde.js +83 -0
- package/dist/index-v9fx5wab.js +83 -0
- package/dist/index-vdahdt49.js +2 -0
- package/dist/index-x1h8r7pr.js +3 -0
- package/dist/index-xjzmb1pn.js +3 -0
- package/dist/index-yrgm89r8.js +3 -0
- package/dist/index-yy1mm8zs.js +3 -0
- package/dist/index-z5a4yxzz.js +8 -0
- package/dist/index.js +5 -0
- package/dist/injections-73j83es3.scm +27 -0
- package/dist/injections-srewsjcz.js +2 -0
- package/dist/interactive-22ta89hc.js +2 -0
- package/dist/key.cmd-wgcq6kt8.js +2 -0
- package/dist/log-shipper-k24m8yw5.js +2 -0
- package/dist/path-utils-35re7qf9.js +2 -0
- package/dist/plugin-system-c916v9an.js +2 -0
- package/dist/postinstall-shim-fix.cjs +382 -0
- package/dist/prereqs-runner-ca4kt803.js +2 -0
- package/dist/preuninstall.cjs +254 -0
- package/dist/profile-mount-npcknw6v.js +2 -0
- package/dist/prune-stale-shims-nkx9vq5m.js +2 -0
- package/dist/register-core-qrawzyym.js +2 -0
- package/dist/secondary-profile-attach-db5cr3e1.js +2 -0
- package/dist/subprocess-g9sk1ep9.js +2 -0
- package/dist/telemetry-tnq47dcs.js +2 -0
- package/dist/tree-sitter-javascript-3h25c6bs.js +2 -0
- package/dist/tree-sitter-javascript-nd0q4pe9.wasm +0 -0
- package/dist/tree-sitter-markdown-3nemcjhe.js +2 -0
- package/dist/tree-sitter-markdown-411r6y9b.wasm +0 -0
- package/dist/tree-sitter-markdown_inline-16ftwa53.js +2 -0
- package/dist/tree-sitter-markdown_inline-j5349f42.wasm +0 -0
- package/dist/tree-sitter-typescript-f6mq6ze6.js +2 -0
- package/dist/tree-sitter-typescript-zxjzwt75.wasm +0 -0
- package/dist/tree-sitter-zig-e78zbjpm.wasm +0 -0
- package/dist/tree-sitter-zig-s2trkm2d.js +2 -0
- package/dist/tunnel-bootstrap-2kg79ng8.js +2 -0
- package/package.json +122 -0
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{Da as D}from"./index-g3ap3xpr.js";import{Xa as V}from"./index-0ckffygp.js";import{Rd as _,Sd as w,Td as x,Ud as N,Vd as j,Yd as X,_d as A,be as I}from"./index-0cn9bv8z.js";import{he as S}from"./index-yy1mm8zs.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 va};
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{h as y,i as A}from"./index-cs78wq6y.js";import{A as l$,B as p$,y as v$}from"./index-1hnw0rhc.js";import{N as H$}from"./index-b5dhmybd.js";import{O as K$,P as q$}from"./index-e1bw1bwr.js";import{va as g}from"./index-ssjmzqcz.js";import"./index-tp4y9jde.js";import{Ca as h$}from"./index-4wgjx8bf.js";import"./index-g3ap3xpr.js";import"./index-0ckffygp.js";import{ab as v}from"./index-rc79x8fw.js";import{db as Y$}from"./index-52cp759f.js";import"./index-v9fx5wab.js";import{Jb as C$,tb as X$,vb as L$}from"./index-01qzsnwd.js";import"./index-d5ysy1yn.js";import{Tb as F,Ub as p}from"./index-04n4qgvd.js";import{Wb as c$}from"./index-dm6yjmgq.js";import"./index-2xs9cvjn.js";import{ic as M,jc as x,kc as y$}from"./index-5mw3eshk.js";import{Ac as N,Bc as u,nc as V,oc as Z,pc as Y,qc as K,rc as c,tc as z,uc as X,vc as J,wc as Q,xc as P$,yc as k,zc as s}from"./index-z5a4yxzz.js";import{Gc as q}from"./index-ef95xr4z.js";import{Kc as T,Mc as _,Nc as j,Oc as m$}from"./index-xjzmb1pn.js";import{pd as T$}from"./index-g2raeeh4.js";import{Hd as z$,Kd as D$,Nd as b}from"./index-9bqd8veb.js";import{$d as U$,Xd as J$,Zd as a,_d as $$}from"./index-0cn9bv8z.js";import"./index-jw1k4vbk.js";import{he as d}from"./index-yy1mm8zs.js";function t(f){let{name:W,onInit:G,onShutdown:U,onNuke:R,telemetryEventName:$,skipPlatforms:w}=f;return{onServerStart:async(I,O)=>{if(w&&w.includes(process.platform)){process.stderr.write(`[${W}] skipping init on unsupported platform '${process.platform}'
|
|
3
|
+
`);return}if(G)await G(O);if($)O.telemetry?.emit($,{plugin:W})},onServerStop:async(I)=>{if(U)await U(I)},onNuke:async(I,O)=>{if(R)return R(I,O)}}}var e=class{constructor(f,W){this.logger=f,this.source=W}logger;source;info(f,W){this.logger?.info?.(this.source,f,W)}warn(f,W){this.logger?.warn?.(this.source,f,W)}error(f,W){this.logger?.error?.(this.source,f,W)}debug(f,W){this.logger?.debug?.(this.source,f,W)}};import{existsSync as r$,rmSync as t$,statSync as e$}from"fs";import{resolve as a$}from"path";function R$(f=$$()){let W=[],G=a$(f),U=U$();if(!a(U,G))throw Error("Refusing to reset a path outside the agents directory");if(r$(G)&&e$(G).isDirectory())t$(G,{recursive:!0,force:!0}),W.push(G);return{removed:W,agentDir:G}}var S="alias",w$=/^[a-zA-Z0-9_-]{1,64}$/,G$=16384,f$=256,W$=1024,$U=new Set(["help","start","stop","restart","kill","list","status","setup","update","completion","autostart","export","import","diagnostics","nuke","doctor","log-level","gc","deploy","network","profile","peer-bootstrap","gateway-auth","info","key","system","url","health","notify","tunnel","session","git","config","log","plugin","ai","audit","alias","run"]);class D extends Error{code;constructor(f,W){super(W);this.code=f,this.name="AliasValidationError"}}class E extends Error{constructor(f){super(`alias '${f}' already exists`);this.name="AliasConflictError"}}class n extends Error{constructor(f){super(`alias '${f}' not found`);this.name="AliasNotFoundError"}}function UU(f){if(typeof f!=="string"||!w$.test(f))throw new D("invalid_name",`alias name must match ${w$} (got '${f}')`);if($U.has(f))throw new D("reserved_name",`alias name '${f}' is reserved`)}function I$(f){if(typeof f!=="string"||f.length===0)throw new D("invalid_command","alias command must be a non-empty string");if(f.length>G$)throw new D("command_too_long",`alias command exceeds ${G$} bytes`)}function O$(f){if(f===void 0)return;if(typeof f!=="string")throw new D("invalid_description","alias description must be a string");if(f.length>f$)throw new D("description_too_long",`alias description exceeds ${f$} chars`)}function F$(f){if(f===void 0||f===null||f==="")return;if(typeof f!=="string")throw new D("invalid_cwd","alias cwd must be a string");if(f.length>W$)throw new D("cwd_too_long",`alias cwd exceeds ${W$} chars`);if(f.includes("\x00"))throw new D("invalid_cwd","alias cwd must not contain NUL bytes")}function RU(f){if(!f)return;try{return JSON.parse(f)}catch{return}}async function i(f){let W=await f.getAllPluginState(S),G=[];for(let U of W){let R=RU(U.value);if(R)G.push(R)}return G.sort((U,R)=>U.name.localeCompare(R.name)),G}async function P(f,W){return(await i(f)).find((U)=>U.name===W)}function V$(f){if(f===void 0||f===null)return null;let W=f.trim();return W===""?null:W}async function Q$(f,W){if(UU(W.name),I$(W.command),O$(W.description),F$(W.cwd),await P(f,W.name))throw new E(W.name);let U=new Date().toISOString(),R={id:crypto.randomUUID(),name:W.name,command:W.command,description:W.description,cwd:V$(W.cwd),profile:J$(),createdAt:U,updatedAt:U};return await f.setPluginState(S,R.id,JSON.stringify(R)),R}async function Z$(f,W,G){let U=await P(f,W);if(!U)throw new n(W);if(G.command!==void 0)I$(G.command);if(G.description!==void 0)O$(G.description);if(G.cwd!==void 0)F$(G.cwd);let R={...U,command:G.command??U.command,description:G.description!==void 0?G.description:U.description,cwd:G.cwd!==void 0?V$(G.cwd):U.cwd,updatedAt:new Date().toISOString()};return await f.setPluginState(S,R.id,JSON.stringify(R)),R}async function B$(f,W){let G=await P(f,W);if(!G)throw new n(W);await f.deletePluginState(S,G.id)}function m(){let f=D$()??b();return{dir:f.dataDir,scope:f.name}}function j$(f){let{serviceRegistry:W,db:G}=f;return new p().get("/api-key",()=>({apiKey:C$()})).get("/audit",({query:U})=>{let R=U,$=R.limit?Math.min(5000,Math.max(1,Number.parseInt(R.limit,10)||100)):100,w=b().audit.listEvents({since:R.since,limit:$,event:R.event});return{events:w,count:w.length}},{query:F.Object({since:F.Optional(F.String()),limit:F.Optional(F.String()),event:F.Optional(F.String())})}).get("/setup/check",()=>{let U=K$();return{ready:U.filter(($)=>$.required).every(($)=>$.installed),dependencies:U}}).post("/setup/install",async({request:U,server:R,set:$})=>{let w=await A(U,"VIBECONTROLS_ALLOW_REMOTE_SETUP_INSTALL",R);if(w)return $.status=403,{error:"Forbidden",message:w};return await q$()}).get("/url",async()=>{let U=W.getProvider("tunnel"),R=U&&U.getActiveTunnelUrl?await U.getActiveTunnelUrl():null,$=`http://localhost:${process.env.PORT||3005}`;return{url:R||$,tunnelUrl:R,localUrl:$,source:R?"tunnel":"local"}}).get("/lifecycle/state",()=>{return{state:W.getService("agent","lifecycle")?.getState()??"running"}}).post("/lifecycle/stop",async({set:U})=>{let R=W.getService("agent","lifecycle");if(!R)return U.status=500,{error:"Lifecycle manager not initialized"};return await R.stop(),{state:"stopped"}}).post("/lifecycle/start",async({set:U})=>{let R=W.getService("agent","lifecycle");if(!R)return U.status=500,{error:"Lifecycle manager not initialized"};return await R.start(),{state:"running"}}).post("/lifecycle/kill",async({set:U})=>{let R=W.getService("agent","lifecycle");if(!R)return U.status=500,{error:"Lifecycle manager not initialized"};return setTimeout(()=>R.kill(),100),{state:"killing"}}).post("/log-level",async({body:U,request:R,server:$,set:w})=>{let I=await A(R,"VIBECONTROLS_ALLOW_REMOTE_LOG_LEVEL",$);if(I)return w.status=403,{error:"Forbidden",message:I};let O=String(U.level??"").toLowerCase();if(!["debug","info","warn","error"].includes(O))return w.status=400,{error:"Invalid level",message:"level must be debug | info | warn | error"};return b().logger.setLevel(O),b().logger.info("agent",`Log level set to ${O} via API`),{ok:!0,level:O}},{body:F.Object({level:F.String()})}).post("/reset",async({body:U,request:R,server:$,set:w})=>{if(!U.confirm)return w.status=400,{error:"Reset confirmation required",message:"Send { confirm: true } to reset local agent state."};let I=await A(R,"VIBECONTROLS_ALLOW_REMOTE_RESET",$);if(I)return w.status=403,{error:"Forbidden",message:I};let O=W.getService("agent","lifecycle");try{if(O)await O.prepareForReset()}catch(h){b().logger.warn("agent","prepareForReset failed during reset \u2014 proceeding to wipe anyway",{error:String(h)})}try{z$.configure({globalGatewayUrl:"",workspaceGatewayUrl:void 0,clientId:"",clientSecret:"",workspaceId:void 0})}catch{}await G.close();let{removed:B,agentDir:L}=R$();b().logger.info("agent","Reset wiped local agent state",{agentDir:L,removed:B});let C=new Uint8Array(32);crypto.getRandomValues(C);let H=`vcak_${Buffer.from(C).toString("base64url")}`;return T$({"static-api-key":H},m()),b().setBootState("awaiting-config"),w.status=200,{success:!0,state:"awaiting-config",...y(R,$)||process.env.VIBECONTROLS_RETURN_RESET_API_KEY==="1"?{newApiKey:H}:{},agentDir:L,removed:B}},{body:F.Object({confirm:F.Boolean()})}).post("/sessions/:sessionId/share",async({params:U,body:R,server:$,request:w,set:I})=>{if(!y(w,$)&&process.env.VIBECONTROLS_ALLOW_REMOTE_SESSION_SHARE!=="1")return I.status=403,{error:"Forbidden",message:"Session-share mint must come from a local request unless VIBECONTROLS_ALLOW_REMOTE_SESSION_SHARE=1."};if(!X$(U.sessionId))return I.status=400,{error:"BadRequest",message:"invalid sessionId"};let O=wU(R?.expiresIn)??1800000,B=crypto.randomUUID(),L=new Uint8Array(32);crypto.getRandomValues(L);let C=`vcak_${Buffer.from(L).toString("base64url")}`,H=new Date(Date.now()+O).toISOString(),r=[...(await import("./agent-config-85pskv43.js")).readAgentConfig({dir:m().dir}).apiKeys??[],{id:B,name:`session-share:${U.sessionId}:${R?.label??"viewer"}`,key:C,scopes:["read"],expiresAt:H,createdAt:new Date().toISOString()}];(await import("./agent-config-85pskv43.js")).writeAgentConfig({apiKeys:r},m());let h=W.getProvider("tunnel"),i$=(h&&h.getActiveTunnelUrl?await h.getActiveTunnelUrl():null)??`http://localhost:${process.env.PORT||3005}`,d$=L$({pathPrefixes:[`/terminal/${U.sessionId}`],methods:["GET"]},Math.min(600,Math.floor(O/1000))),s$=`${i$.replace(/\/$/,"")}/terminal/${encodeURIComponent(U.sessionId)}/#vt=${encodeURIComponent(d$.token)}`;return b().logger.info("session-share","Minted share credential",{sessionId:U.sessionId,keyId:B,expiresAt:H}),{ok:!0,keyId:B,apiKey:C,joinUrl:s$,sessionId:U.sessionId,expiresAt:H}},{params:F.Object({sessionId:F.String()}),body:F.Optional(F.Object({permissions:F.Optional(F.Array(F.String())),expiresIn:F.Optional(F.String()),label:F.Optional(F.String())}))}).get("/aliases",async()=>{return{aliases:await i(G)}}).get("/aliases/:name",async({params:U,set:R})=>{let $=await P(G,U.name);if(!$)return R.status=404,{error:"Alias not found"};return $},{params:F.Object({name:F.String()})}).post("/aliases",async({body:U,set:R})=>{try{let $=await Q$(G,U);return R.status=201,$}catch($){if($ instanceof E)return R.status=409,{error:"Alias already exists",message:$.message};if($ instanceof D)return R.status=400,{error:$.code,message:$.message};throw $}},{body:F.Object({name:F.String(),command:F.String(),description:F.Optional(F.String()),cwd:F.Optional(F.Union([F.String(),F.Null()]))})}).put("/aliases/:name",async({params:U,body:R,set:$})=>{try{return await Z$(G,U.name,R)}catch(w){if(w instanceof n)return $.status=404,{error:"Alias not found"};if(w instanceof D)return $.status=400,{error:w.code,message:w.message};throw w}},{params:F.Object({name:F.String()}),body:F.Object({command:F.Optional(F.String()),description:F.Optional(F.String()),cwd:F.Optional(F.Union([F.String(),F.Null()]))})}).delete("/aliases/:name",async({params:U,set:R})=>{try{return await B$(G,U.name),R.status=204,null}catch($){if($ instanceof n)return R.status=404,{error:"Alias not found"};throw $}},{params:F.Object({name:F.String()})}).post("/aliases/:name/execute",async({params:U,body:R,set:$})=>{let w=await P(G,U.name);if(!w)return $.status=404,{error:"Alias not found"};let I=R?.args??[],O=await H$(w,I);b().audit.emit("agent","alias.executed",{exit_code:O.exit_code});let B=Y$("alias.executed",{exit_code:O.exit_code});if(!B.ok)b().logger.debug("alias",`telemetry validate failed: ${B.reason}`);if(O.timed_out)$.status=408;return{exit_code:O.exit_code,stdout:O.stdout,stderr:O.stderr,duration_ms:O.duration_ms,truncated:O.truncated,cwd:O.cwd}},{params:F.Object({name:F.String()}),body:F.Optional(F.Object({args:F.Optional(F.Array(F.String()))}))}).post("/sessions/share/:keyId/revoke",async({params:U,server:R,request:$,set:w})=>{if(!y($,R)&&process.env.VIBECONTROLS_ALLOW_REMOTE_SESSION_SHARE!=="1")return w.status=403,{error:"Forbidden"};let I=await import("./agent-config-85pskv43.js"),O=m(),B=I.readAgentConfig({dir:O.dir}),L=(B.apiKeys??[]).length,C=(B.apiKeys??[]).filter((H)=>H.id!==U.keyId);if(C.length===L)return w.status=404,{error:"No such share key"};return I.writeAgentConfig({apiKeys:C},O),{ok:!0,revoked:U.keyId}},{params:F.Object({keyId:F.String()})})}function wU(f){if(!f)return null;let W=/^(\d+)([smhdw]?)$/.exec(f.trim());if(!W)return null;let G=Number(W[1]),U=W[2]||"m";return U==="s"?G*1000:U==="m"?G*60000:U==="h"?G*3600000:U==="d"?G*86400000:G*7*86400000}var GU="http://localhost:3005";function M$(f){f.command("health").description("Check health of a VibeControls agent instance").option("-n, --name <name>","Agent instance name").option("--agent-url <url>","Agent URL",GU).option("--json","Emit JSON").option("--plain","Force plain text output").action(async function(W){try{let G={...f.opts(),...W};await x({mode:M(G),fetchData:async()=>{if(G.name){let $=await new g().checkHealth(G.name);return{mode:"named",agentUrl:T(G),name:G.name,healthy:$.healthy,details:$.details??{}}}let U=T(G);try{let R=await j(U,"/health");return{mode:"url",agentUrl:U,healthy:!0,details:R}}catch(R){return{mode:"url",agentUrl:U,healthy:!1,details:{status:"unhealthy",...R instanceof Error?{error:K(R)}:{}}}}},plain:(U)=>{if(X("Agent Health"),Q(),U.mode==="named"){if(!U.healthy){Y(`Agent instance ${V.bold(U.name??"")} is not responding.`);return}let R=U.details;if(J("Instance",U.name??""),J("Status",u(R.status??"healthy")),R.uptime!==void 0)J("Uptime",`${R.uptime}s`);if(R.checks){Q(),z(`${Z.info} Health checks:`);for(let[$,w]of Object.entries(R.checks)){let I=w.status==="healthy"?Z.success:Z.error;J(` ${I} ${$}`,u(w.status))}}}else{if(J("URL",U.agentUrl),J("Status",u(U.details.status??"unhealthy")),U.details.version)J("Version",U.details.version);if(U.details.uptime!==void 0)J("Uptime",`${U.details.uptime}s`);if(U.details.timestamp)J("Timestamp",U.details.timestamp);if(U.details.checks){Q(),z(`${Z.info} Health checks:`);for(let[R,$]of Object.entries(U.details.checks)){let w=$.status==="healthy"?Z.success:Z.error;J(` ${w} ${R}`,u($.status))}}}if(Q(),U.healthy)c(`${Z.success} Agent is healthy.`)},interactive:async(U)=>{let R=[];if(U.mode==="named")R.push(`Instance: ${U.name??""}`);else R.push(`URL: ${U.agentUrl}`);if(R.push(`Status: ${u(U.details.status??(U.healthy?"healthy":"unhealthy"))}`),U.details.version)R.push(`Version: ${U.details.version}`);if(U.details.uptime!==void 0)R.push(`Uptime: ${U.details.uptime}s`);if(U.details.timestamp)R.push(`Time: ${U.details.timestamp}`);if(U.details.checks){R.push(""),R.push("Checks:");for(let[$,w]of Object.entries(U.details.checks))R.push(` ${$}: ${w.status}`)}await q({title:"Agent Health",body:R.join(`
|
|
4
|
+
`),footer:"press q to exit"})},json:(U)=>({mode:U.mode,agentUrl:U.agentUrl,name:U.name??null,healthy:U.healthy,details:U.details})})}catch(G){Y(`Health check failed: ${K(G)}`)}})}import{platform as fU,arch as WU,release as JU,hostname as IU,cpus as OU,totalmem as FU}from"os";var VU="http://localhost:3005";function x$(f){f.command("info").description("Show local and remote VibeControls agent information").option("--agent-url <url>","Agent URL",VU).option("--json","Emit JSON").option("--plain","Force plain text output").action(async function(W){try{let G={...f.opts(),...W},U=T(G),R=encodeURIComponent(_(G));await x({mode:M(G),fetchData:async()=>{let $={hostname:IU(),platform:fU(),arch:WU(),release:JU(),cpus:OU().length,totalMemory:FU(),nodeVersion:process.version,bunVersion:process.versions.bun};try{let w=await j(U,`/api/profiles/${R}/agent/version`);return{local:$,agentUrl:U,remote:w}}catch(w){return{local:$,agentUrl:U,remote:null,remoteError:w instanceof Error?K(w):String(w)}}},plain:($)=>{if(X("VibeControls Agent Info"),Q(),z(`${Z.info} Local System`),J("Hostname",$.local.hostname),J("Platform",`${$.local.platform} ${$.local.arch}`),J("OS Release",$.local.release),J("CPUs",String($.local.cpus)),J("Total Memory",N($.local.totalMemory)),J("Node.js",$.local.nodeVersion),$.local.bunVersion)J("Bun",$.local.bunVersion);if(Q(),z(`${Z.info} Remote Agent`),J("URL",$.agentUrl),$.remote){if(J("Version",V.bold($.remote.version)),$.remote.build)J("Build",$.remote.build);if($.remote.commit)J("Commit",$.remote.commit);if($.remote.nodeVersion)J("Node.js (remote)",$.remote.nodeVersion);if($.remote.bunVersion)J("Bun (remote)",$.remote.bunVersion)}else J("Status",V.dim("not reachable"));Q()},interactive:async($)=>{let w=[];if(w.push("Local System"),w.push(` Hostname: ${$.local.hostname}`),w.push(` Platform: ${$.local.platform} ${$.local.arch}`),w.push(` OS Release: ${$.local.release}`),w.push(` CPUs: ${$.local.cpus}`),w.push(` Total Memory: ${N($.local.totalMemory)}`),w.push(` Node.js: ${$.local.nodeVersion}`),$.local.bunVersion)w.push(` Bun: ${$.local.bunVersion}`);if(w.push(""),w.push("Remote Agent"),w.push(` URL: ${$.agentUrl}`),$.remote){if(w.push(` Version: ${$.remote.version}`),$.remote.build)w.push(` Build: ${$.remote.build}`);if($.remote.commit)w.push(` Commit: ${$.remote.commit}`);if($.remote.nodeVersion)w.push(` Node.js: ${$.remote.nodeVersion} (remote)`);if($.remote.bunVersion)w.push(` Bun: ${$.remote.bunVersion} (remote)`)}else w.push(" Status: not reachable");await q({title:"VibeControls Agent Info",body:w.join(`
|
|
5
|
+
`),footer:"press q to exit"})},json:($)=>({local:$.local,agentUrl:$.agentUrl,remote:$.remote,remoteError:$.remoteError??null})})}catch(G){Y(`Failed to get info: ${K(G)}`)}})}var QU="http://localhost:3005";function _$(f){f.command("system").description("Show system information for a running VibeControls agent").option("--agent-url <url>","Agent URL",QU).option("--json","Emit JSON").option("--plain","Force plain text output").action(async function(W){try{let G={...f.opts(),...W},U=T(G),R=encodeURIComponent(_(G));await x({mode:M(G),fetchData:()=>j(U,`/api/profiles/${R}/agent/system`),plain:($)=>{if(X("Agent System Information"),Q(),z(`${Z.info} Agent`),J("Version",V.bold($.agentVersion)),$.bunVersion)J("Bun",$.bunVersion);if($.environment)J("Environment",$.environment);J("Uptime",s($.uptime)),Q(),z(`${Z.info} Platform`),J("OS",`${$.platform} ${$.arch}`),J("Hostname",$.hostname),J("Release",$.release),Q(),z(`${Z.info} Resources`),J("CPUs",String($.cpus)),J("Total Memory",N($.totalMemory)),J("Free Memory",N($.freeMemory)),Q(),z(`${Z.info} Paths`),J("Home",$.homeDir),J("CWD",$.cwd),Q()},interactive:async($)=>{let w=["Agent",` Version: ${$.agentVersion}`,...$.bunVersion?[` Bun: ${$.bunVersion}`]:[],...$.environment?[` Environment: ${$.environment}`]:[],` Uptime: ${s($.uptime)}`,"","Platform",` OS: ${$.platform} ${$.arch}`,` Hostname: ${$.hostname}`,` Release: ${$.release}`,"","Resources",` CPUs: ${$.cpus}`,` Total Mem: ${N($.totalMemory)}`,` Free Mem: ${N($.freeMemory)}`,"","Paths",` Home: ${$.homeDir}`,` CWD: ${$.cwd}`];await q({title:"Agent System Information",body:w.join(`
|
|
6
|
+
`),footer:"press q to exit"})}})}catch(G){Y(`Failed to get system info: ${K(G)}`)}})}var ZU="http://localhost:3005";async function b$(f){try{let W=await fetch(`${f}/health/ready`);if(W.status===200||W.status===503)return await W.json();return{healthy:!1,status:W.status}}catch{return{healthy:!1,error:"unreachable"}}}async function u$(f,W){try{let G=await fetch(`${f}/api/profiles/${W}/agent/api-key`);if(!G.ok)return null;return(await G.json()).apiKey??null}catch{return null}}async function BU(f,W){try{return await j(f,`/api/profiles/${W}/plugins`)}catch{return null}}function o(f){let W=f??{};if(W.error==="unreachable")return V.red("unreachable");if(typeof W.status==="number"&&W.status>=400)return V.red(`http ${W.status}`);let G=typeof W.status==="string"?W.status:"",U=typeof W.bootState==="string"?W.bootState:"";if(G==="ok"&&U==="ready")return V.green("ready");if(U==="awaiting-config")return V.yellow("awaiting-config");if(U==="initializing")return V.yellow("initializing");if(U==="degraded"||G==="degraded")return V.red(`degraded${U?` (${U})`:""}`);if(W.healthy===!1)return V.red("unhealthy");return V.green("healthy")}function zU(f){let G=(f??{}).lastFinalizeError;if(!G||typeof G!=="object")return null;let U=G;if(typeof U.message!=="string"||typeof U.at!=="string")return null;return{message:U.message,at:U.at,attempt:typeof U.attempt==="number"?U.attempt:void 0}}function N$(f){let W=f??{},G=typeof W.bootState==="string"?W.bootState:"";if(G!=="awaiting-config"&&G!=="degraded")return null;let U=[],R=zU(f);if(R)if(U.push(`${V.gray("\xB7")} Last error: ${V.red(R.message)}`),R.attempt!==void 0)U.push(`${V.gray("\xB7")} Background retry: attempt ${R.attempt}`);else U.push(`${V.gray("\xB7")} Last seen: ${R.at}`);if(G==="awaiting-config")U.push(`${V.gray("\xB7")} Force retry now: ${V.bold("vibe retry-config")}`);return U.push(`${V.gray("\xB7")} Full trace: ${V.bold("vibe logs --since 10m")}`),U.join(`
|
|
7
|
+
`)}async function YU(f,W){let G={agentUrl:W},U=f.jsonKey??f.title.toLowerCase(),R;try{R=await f.render(G)}catch(w){R=V.red(`error (${w.message})`)}let $=null;if(f.json)try{$=await f.json(G)}catch{$=null}return{title:f.title,jsonKey:U,text:R,json:$}}async function n$(f){let G=h$().getStatusSections();return Promise.all(G.map((U)=>YU(U,f)))}function k$(f){f.command("status").description("Show comprehensive status of VibeControls agent instance(s)").option("-n, --name <name>","Agent instance name").option("--agent-url <url>","Agent URL",ZU).option("--profile <name>","Target a specific profile by name").option("--json","Emit JSON").option("--plain","Force plain text output").action(async function(W){try{let G={...f.opts(),...W},U=new g;await x({mode:M(G),fetchData:async()=>{if(G.name){let I=await U.getStatus(G.name);if(!I)return{kind:"instance",agentUrl:T(G),instance:null,contributed:[]};let O=I.status==="running"&&I.port?`http://localhost:${I.port}`:T(G);if(I.status!=="running")return{kind:"instance",agentUrl:O,instance:I,contributed:[]};let B=encodeURIComponent(_({profile:I.name})),[L,C,H,l]=await Promise.all([b$(O),u$(O,B),BU(O,B),n$(O)]);return{kind:"instance",agentUrl:O,instance:I,health:L,apiKey:C,plugins:H,contributed:l}}let R=await U.listInstances(),$=R.filter((I)=>I.status==="running"),w=await Promise.all($.map(async(I)=>{let O=`http://localhost:${I.port}`,B=encodeURIComponent(_({profile:I.name})),[L,C,H]=await Promise.all([b$(O),u$(O,B),n$(O)]);return{name:I.name,agentUrl:O,health:L,apiKey:C,contributed:H}}));return{kind:"overview",instances:R,perRunning:w}},plain:(R)=>{if(R.kind==="instance"){if(!R.instance){Y(`Agent instance ${V.bold(G.name??"")} not found.`);return}let w=R.instance;if(X(`Agent Status: ${w.name}`),J("Name",w.name),J("Status",u(w.status)),J("PID",w.pid?String(w.pid):V.dim("n/a")),J("Port",w.port?String(w.port):V.dim("n/a")),J("Host",w.config?.host||V.dim("n/a")),J("Database",w.config?.dbPath||V.dim("n/a")),w.startTime)J("Started",k(w.startTime));if(w.status==="running"){Q(),J("Health",o(R.health));let I=N$(R.health);if(I)Q(),console.log(I),Q();let O=R.health?.uptime;if(O)J("Uptime",String(O));if(J("API Key",R.apiKey??V.dim("(unavailable)")),R.plugins){let B=R.plugins.plugins??[],L=B.filter((C)=>C.isCore).length;J("Plugins",`${B.length} total (${L} core, ${B.length-L} external)`)}else J("Plugins",V.dim("(unable to fetch)"));for(let B of R.contributed){if(B.text===null)continue;J(B.title,B.text)}}Q();return}if(X("Agent Instances"),Q(),!R.instances||R.instances.length===0){z(`${Z.info} No agent instances found.`),z(`Run ${V.bold("vibe start")} to start an agent.`);return}let $=R.instances.map((w)=>({Name:w.name,Status:u(w.status),PID:w.pid||"-",Port:w.port||"-",Started:w.startTime?k(w.startTime):"-"}));P$($),Q();for(let w of R.perRunning){Q(),X(`Quick Status: ${w.name}`),J("Health",o(w.health));let I=N$(w.health);if(I)Q(),console.log(I),Q();J("API Key",w.apiKey??V.dim("(unavailable)"));for(let O of w.contributed){if(O.text===null)continue;J(O.title,O.text)}}Q(),z(`${Z.info} ${R.instances.length} instance(s) found. Use ${V.bold("vibe status -n <name>")} for full details.`)},interactive:async(R)=>{let $=[];if(R.kind==="instance"){if(!R.instance)$.push(`Agent instance "${G.name??""}" not found.`);else{let w=R.instance;if($.push(`Name: ${w.name}`),$.push(`Status: ${u(w.status)}`),$.push(`PID: ${w.pid??"n/a"}`),$.push(`Port: ${w.port??"n/a"}`),$.push(`Host: ${w.config?.host??"n/a"}`),$.push(`Database: ${w.config?.dbPath??"n/a"}`),w.startTime)$.push(`Started: ${k(w.startTime)}`);if(w.status==="running"){if($.push(""),$.push(`Health: ${o(R.health)}`),$.push(`API Key: ${R.apiKey??"(unavailable)"}`),R.plugins){let I=R.plugins.plugins??[],O=I.filter((B)=>B.isCore).length;$.push(`Plugins: ${I.length} (${O} core, ${I.length-O} external)`)}for(let I of R.contributed){if(I.text===null)continue;$.push(`${I.title.padEnd(9)} ${I.text}`)}}}await q({title:`vibe status${G.name?` \u2014 ${G.name}`:""}`,body:$.join(`
|
|
8
|
+
`),footer:"press q to exit"});return}if(!R.instances||R.instances.length===0)$.push("No agent instances found."),$.push("Run `vibe start` to start an agent.");else for(let w of R.instances){$.push(`${V.bold(w.name)} ${u(w.status)}`),$.push(` PID: ${w.pid??"-"}`),$.push(` Port: ${w.port??"-"}`),$.push(` Started: ${w.startTime?k(w.startTime):"-"}`);let I=R.perRunning.find((O)=>O.name===w.name);if(I){$.push(` Health: ${o(I.health)}`);for(let O of I.contributed){if(O.text===null)continue;$.push(` ${O.title.padEnd(9)} ${O.text}`)}}$.push("")}await q({title:`vibe status \u2014 ${R.instances.length} instance(s)`,body:$.join(`
|
|
9
|
+
`),footer:"press q to exit"})},json:(R)=>{let $=(w)=>Object.fromEntries(w.map((I)=>[I.jsonKey,I.json]));if(R.kind==="instance"){if(!R.instance)return{instance:null};let w={instance:{name:R.instance.name,status:R.instance.status,pid:R.instance.pid,port:R.instance.port,host:R.instance.config?.host,dbPath:R.instance.config?.dbPath,startTime:R.instance.startTime}};if(R.instance.status==="running")w.health=R.health??null,w.plugins=R.plugins??null,Object.assign(w,$(R.contributed));return w}return{instances:R.instances.map((w)=>({name:w.name,status:w.status,pid:w.pid,port:w.port,startTime:w.startTime})),perRunning:R.perRunning.map((w)=>({name:w.name,health:w.health??null,...$(w.contributed)}))}}})}catch(G){let U=G instanceof Error?K(G):String(G);Y(`Failed to get status: ${U}`)}})}var TU="http://localhost:3005";function S$(f){f.command("url").description("Show the active URL for a running VibeControls agent").option("--agent-url <url>","Agent URL",TU).option("--json","Emit JSON").option("--plain","Force plain text output").action(async(W)=>{try{let G={...f.opts(),...W},U=T(W),R=encodeURIComponent(_(G));await x({mode:M(G),fetchData:()=>j(U,`/api/profiles/${R}/agent/url`),plain:($)=>{if(X("Agent URL"),Q(),J("Active URL",V.bold($.url)),J("Local URL",$.localUrl),$.tunnelUrl)J("Tunnel URL",V.cyan($.tunnelUrl));if(J("Mode",$.isTunnel?`${Z.running} Tunnel active`:`${Z.info} Local only`),Q(),$.isTunnel)z(`${Z.info} Agent is accessible via tunnel at ${V.bold($.tunnelUrl)}`);else z(`${Z.info} Agent is running locally at ${V.bold($.localUrl)}`)},interactive:async($)=>{let w=[` Active URL: ${$.url}`,` Local URL: ${$.localUrl}`,` Tunnel URL: ${$.tunnelUrl??"-"}`,` Mode: ${$.isTunnel?"Tunnel active":"Local only"}`];await q({title:"Agent URL",body:w.join(`
|
|
10
|
+
`)})},json:($)=>v($)})}catch(G){Y(`Failed to get URL: ${G.message}`)}})}var E$="http://localhost:3005";function A$(f){let W=f.command("gateway-auth").description("Manage gateway authentication for VibeControls agent");W.command("configure").description("Configure gateway authentication credentials").requiredOption("--global-url <url>","Global gateway URL").requiredOption("--workspace-url <url>","Workspace gateway URL").requiredOption("--client-id <id>","OAuth client ID").requiredOption("--client-secret <secret>","OAuth client secret").option("--workspace-id <id>","Workspace ID for auto-report").option("--agent-record-id <id>","Existing backend agent record ID").option("--agent-url <url>","Agent URL",E$).option("--json","Emit JSON result").action(async(G)=>{try{let U={...f.opts(),...G},R=T(G),$=encodeURIComponent(_(U)),w=await m$(R,`/api/profiles/${$}/agent/gateway-auth`,{globalGatewayUrl:G.globalUrl,workspaceGatewayUrl:G.workspaceUrl,clientId:G.clientId,clientSecret:G.clientSecret,workspaceId:G.workspaceId,agentRecordId:G.agentRecordId});if(y$(U,{ok:!!w.success,message:w.message??null,globalGatewayUrl:G.globalUrl,workspaceGatewayUrl:G.workspaceUrl,clientId:G.clientId,workspaceId:G.workspaceId??null,agentRecordId:G.agentRecordId??null}))return;if(X("Configure Gateway Authentication"),Q(),z(`${Z.info} Sending gateway auth configuration...`),Q(),w.success){if(c(`${Z.success} Gateway authentication configured successfully.`),Q(),J("Global URL",G.globalUrl),J("Workspace URL",G.workspaceUrl),J("Client ID",G.clientId),J("Client Secret",V.dim("********")),G.workspaceId)J("Workspace ID",G.workspaceId);if(G.agentRecordId)J("Agent Record ID",G.agentRecordId)}else Y(w.message||"Failed to configure gateway authentication.");Q()}catch(U){Y(`Failed to configure gateway auth: ${U instanceof Error?K(U):String(U)}`)}}),W.command("status").description("Check gateway authentication status").option("--agent-url <url>","Agent URL",E$).option("--json","Emit JSON").option("--plain","Force plain text output").action(async(G)=>{try{let U={...f.opts(),...G},R=T(G),$=encodeURIComponent(_(U));await x({mode:M(U),fetchData:()=>j(R,`/api/profiles/${$}/agent/gateway-auth`),plain:(w)=>{if(X("Gateway Authentication Status"),Q(),J("Configured",w.configured?`${Z.success} ${V.green("Yes")}`:`${Z.error} ${V.red("No")}`),w.configured){if(J("Global URL",w.config?.globalGatewayUrl||V.dim("n/a")),J("Workspace URL",w.config?.workspaceGatewayUrl||V.dim("n/a")),J("Client ID",w.config?.clientId||V.dim("n/a")),w.config?.workspaceId)J("Workspace ID",w.config.workspaceId)}else Q(),z(`${Z.info} Run ${V.bold("vibe gateway-auth configure")} to set up gateway authentication.`);Q()},interactive:async(w)=>{let I=w.configured?[" Configured: yes",` Global URL: ${w.config?.globalGatewayUrl??"n/a"}`,` Workspace URL: ${w.config?.workspaceGatewayUrl??"n/a"}`,` Client ID: ${w.config?.clientId??"n/a"}`,` Workspace ID: ${w.config?.workspaceId??"-"}`]:[" Configured: no",""," Run `vibe gateway-auth configure` to set up."];await q({title:"Gateway Authentication Status",body:I.join(`
|
|
11
|
+
`)})},json:(w)=>v(w)})}catch(U){Y(`Failed to get gateway auth status: ${U instanceof Error?K(U):String(U)}`)}})}function g$(f,W){M$(f),x$(f),c$(f),_$(f),k$(f),S$(f),A$(f)}var o$="agent";function LR(f){let W=null,G=t({name:o$,onShutdown:()=>{l$(),v$()}});return{name:o$,version:"2.3.0",description:"Core agent identity, system info, setup, gateway authentication, and auto-report",capabilities:{storage:"rw",secrets:"rw",gateway:!0,broadcast:!0,audit:!0,telemetry:!0},tags:["backend","cli"],cliCommand:"agent",apiPrefix:"/api/agent",publicPaths:["/identity","/tunnel"],createRoutes:(U)=>{return W=U.db,j$(U)},onCliSetup:async(U,R)=>{g$(U,R)},onServerReady:async(U,R)=>{if(W){let $=U,w=(typeof $.decorator?.apiKey==="string"?$.decorator.apiKey:void 0)??(typeof $.store?.apiKey==="string"?$.store.apiKey:void 0)??"unknown",I=new e(R.logger,"agent-plugin");p$(W,R.serviceRegistry,w).catch((O)=>{I.warn(`Auto-report background task failed: ${O}`)})}},onServerStop:()=>G.onServerStop({})}}export{LR as createPlugin};
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{Sa as k}from"./index-g3ap3xpr.js";import{Eb as F,Fb as h,Gb as S,Hb as q,Jb as N,wb as f,zb as c}from"./index-01qzsnwd.js";import{Ub as P}from"./index-04n4qgvd.js";import{Nd as V}from"./index-9bqd8veb.js";var U=["tunnel","session","ai","plan","gitops","security"];class m{providers=new Map;providerOrder=new Map;defaults=new Map;services=new Map;db;constructor(z){this.db=z}getDb(){return this.db}setProviderDefault(z,J){this.defaults.set(z,J)}clearProviderDefault(z,J){if(!J||this.defaults.get(z)===J)this.defaults.delete(z)}async hydrateDefaultsFromDb(){if(!this.db)return;for(let z of U)try{let J=await this.db.getConfig(`provider:default:${z}`);if(J)this.defaults.set(z,J)}catch{}}registerProvider(z,J,Q){if(!this.providers.has(z))this.providers.set(z,new Map),this.providerOrder.set(z,[]);let W=this.providers.get(z),Z=this.providerOrder.get(z);if(W.has(Q))V().logger.info("service-registry",`Updating ${z} provider from plugin '${Q}'`);else V().logger.info("service-registry",`Registered ${z} provider from plugin '${Q}'`);if(W.set(Q,{provider:J,pluginName:Q,registeredAt:new Date}),!Z.includes(Q))Z.push(Q)}getProvider(z){let J=this.providers.get(z);if(!J||J.size===0)return;let Q=this.defaults.get(z);if(Q&&J.has(Q))return J.get(Q).provider;let W=this.providerOrder.get(z);if(W&&W.length>0){let Z=W[0];return J.get(Z)?.provider}return}getProviderByName(z,J){let Q=this.providers.get(z);if(!Q)return;return Q.get(J)?.provider}hasProvider(z){let J=this.providers.get(z);return!!J&&J.size>0}unregisterProvider(z,J){let Q=this.providers.get(z);if(!Q)return!1;let W=Q.delete(J);if(W){let Z=this.providerOrder.get(z);if(Z){let X=Z.indexOf(J);if(X!==-1)Z.splice(X,1)}this.clearProviderDefault(z,J),V().logger.info("service-registry",`Unregistered ${z} provider from plugin '${J}'`)}return W}unregisterPlugin(z){for(let J of U)this.unregisterProvider(J,z);this.unregisterServices(z)}listProvidersForType(z){let J=this.providers.get(z);if(!J)return[];let Q=this.defaults.get(z);if(!Q||!J.has(Q)){let W=this.providerOrder.get(z);Q=W&&W.length>0?W[0]:void 0}return Array.from(J.keys()).map((W)=>({pluginName:W,isDefault:W===Q}))}registerService(z,J,Q){let W=`${z}:${J}`;this.services.set(W,{service:Q,pluginName:z}),V().logger.debug("service-registry",`Registered service '${W}'`)}getService(z,J){let Q=`${z}:${J}`;return this.services.get(Q)?.service}unregisterServices(z){let J=[];for(let[Q,W]of this.services)if(W.pluginName===z)J.push(Q);for(let Q of J)this.services.delete(Q);if(J.length>0)V().logger.info("service-registry",`Unregistered ${J.length} services from ${z}`)}listProviders(){let z=[];for(let[J,Q]of this.providers)for(let[W,Z]of Q)z.push({type:J,name:W,pluginName:Z.pluginName});return z}listServices(){return Array.from(this.services.entries()).map(([z,J])=>({pluginName:J.pluginName,serviceName:z.split(":").slice(1).join(":")}))}clear(){this.providers.clear(),this.providerOrder.clear(),this.defaults.clear(),this.services.clear()}}import{extname as g,relative as o,resolve as u}from"path";import{realpath as E}from"fs/promises";var n=["'self'","http://localhost:*","http://127.0.0.1:*","https://localhost:*","https://127.0.0.1:*","https://*.local.burdenoff.com","https://vibecontrols.com","https://*.vibecontrols.com","https://burdenoff.com","https://app.burdenoff.com","https://alphaapp.burdenoff.com"],D=!1;function w(){let z=process.env.VIBE_UI_FRAME_ANCESTORS?.trim(),J=z?z.split(/[\s,]+/).filter(Boolean):n;if(z&&!D&&(J.includes("*")||!J.includes("'self'")))D=!0,console.warn(`[ui-server] VIBE_UI_FRAME_ANCESTORS override does not include "'self'" or contains "*". This significantly weakens CSP frame-ancestors and is almost never intended. Override: ${z}`);return`frame-ancestors ${J.join(" ")}`}var l={".html":"text/html",".js":"application/javascript",".mjs":"application/javascript",".css":"text/css",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".map":"application/json",".wasm":"application/wasm"};function s(z){return l[g(z).toLowerCase()]||"application/octet-stream"}var b=`<script>
|
|
3
|
+
window.__VIBE_AUTH__={apiKey:null};
|
|
4
|
+
(function(){
|
|
5
|
+
var p=new URLSearchParams(window.location.search);
|
|
6
|
+
if(p.get('apiKey'))window.__VIBE_AUTH__.apiKey=p.get('apiKey');
|
|
7
|
+
function allowedOrigin(origin){
|
|
8
|
+
try{
|
|
9
|
+
var u=new URL(origin);
|
|
10
|
+
return u.hostname==='localhost'||u.hostname==='127.0.0.1'||u.hostname.endsWith('.local.burdenoff.com')||u.hostname==='vibecontrols.com'||u.hostname.endsWith('.vibecontrols.com')||u.hostname==='burdenoff.com'||u.hostname==='app.burdenoff.com'||u.hostname==='alphaapp.burdenoff.com';
|
|
11
|
+
}catch(e){return false;}
|
|
12
|
+
}
|
|
13
|
+
window.addEventListener('message',function(e){
|
|
14
|
+
if(!allowedOrigin(e.origin))return;
|
|
15
|
+
if(e.data&&e.data.type==='vibe-auth'&&e.data.apiKey){
|
|
16
|
+
window.__VIBE_AUTH__.apiKey=e.data.apiKey;
|
|
17
|
+
window.dispatchEvent(new CustomEvent('vibe-auth-ready'));
|
|
18
|
+
}
|
|
19
|
+
});
|
|
20
|
+
})();
|
|
21
|
+
</script>`;function j(z){if(!z.headers.has("Content-Security-Policy"))z.headers.set("Content-Security-Policy",w());return z}function R(z){if(z.includes("</head>"))return z.replace("</head>",b+"</head>");if(z.includes("</body>"))return z.replace("</body>",b+"</body>");return z+b}function T(z){return z.replace(/[&<>"']/g,(J)=>{switch(J){case"&":return"&";case"<":return"<";case">":return">";case'"':return""";case"'":return"'";default:return J}})}function M(z,J){let Q=o(z,J);return Q===""||!!Q&&!Q.startsWith("..")&&!Q.startsWith("/")}async function v(z,J,Q){let W=k(z);if(!W)return null;let Z=await E(W),X=await E(J);if(!M(Z,X))return null;let $=u(X,Q),x=await E($).catch(()=>$);if(!M(X,x))return null;return $}function r(z){return!1}function i(z,J="/api/profiles/default/agent/ui-exchange"){let Q=z.replace(/\\/g,"\\\\").replace(/'/g,"\\'"),W=J.replace(/\\/g,"\\\\").replace(/'/g,"\\'");return`<!doctype html>
|
|
22
|
+
<html>
|
|
23
|
+
<head>
|
|
24
|
+
<meta charset="utf-8">
|
|
25
|
+
<title>Loading plugin\u2026</title>
|
|
26
|
+
<style>
|
|
27
|
+
body { font: 14px/1.4 system-ui, -apple-system, sans-serif; color: #ccc; background: #111; padding: 2rem; }
|
|
28
|
+
.err { color: #f88; }
|
|
29
|
+
</style>
|
|
30
|
+
</head>
|
|
31
|
+
<body>
|
|
32
|
+
<p id="status">Loading plugin\u2026</p>
|
|
33
|
+
<script>
|
|
34
|
+
(async () => {
|
|
35
|
+
const PLUGIN = '${Q}';
|
|
36
|
+
const EXCHANGE = '${W}';
|
|
37
|
+
const statusEl = document.getElementById('status');
|
|
38
|
+
function fail(msg) {
|
|
39
|
+
statusEl.textContent = msg;
|
|
40
|
+
statusEl.className = 'err';
|
|
41
|
+
}
|
|
42
|
+
const m = location.hash.match(/[#&]vt=([^&]+)/);
|
|
43
|
+
if (!m) { fail('Missing plugin token'); return; }
|
|
44
|
+
const token = decodeURIComponent(m[1]);
|
|
45
|
+
let r;
|
|
46
|
+
try {
|
|
47
|
+
r = await fetch(EXCHANGE, {
|
|
48
|
+
method: 'POST',
|
|
49
|
+
headers: { 'content-type': 'application/json' },
|
|
50
|
+
credentials: 'include',
|
|
51
|
+
body: JSON.stringify({ plugin: PLUGIN, token: token })
|
|
52
|
+
});
|
|
53
|
+
} catch (e) {
|
|
54
|
+
fail('Plugin authentication failed: network error');
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
if (!r.ok) { fail('Plugin authentication failed'); return; }
|
|
58
|
+
const url = new URL(location.href);
|
|
59
|
+
url.hash = '';
|
|
60
|
+
location.replace(url.toString());
|
|
61
|
+
})();
|
|
62
|
+
</script>
|
|
63
|
+
</body>
|
|
64
|
+
</html>`}function a(z){let J=z.map((Q)=>{let W=(Q.tags||[]).map(($)=>`<span class="tag">${T($)}</span>`).join(" "),Z=encodeURIComponent(Q.name),X=T(Q.title||Q.name);return`<li><a href="/ui/${Z}">${X}</a> ${W}</li>`}).join(`
|
|
65
|
+
`);return`<!DOCTYPE html>
|
|
66
|
+
<html lang="en">
|
|
67
|
+
<head>
|
|
68
|
+
<meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
|
69
|
+
<title>VibeControls - Plugin UIs</title>
|
|
70
|
+
<style>
|
|
71
|
+
body{font-family:system-ui,-apple-system,sans-serif;max-width:800px;margin:2rem auto;padding:0 1rem;background:#0a0a0a;color:#e0e0e0}
|
|
72
|
+
h1{color:#fff}a{color:#60a5fa;text-decoration:none}a:hover{text-decoration:underline}
|
|
73
|
+
ul{list-style:none;padding:0}li{padding:0.75rem 1rem;border:1px solid #333;border-radius:8px;margin-bottom:0.5rem;display:flex;align-items:center;gap:0.5rem}
|
|
74
|
+
.tag{font-size:0.75rem;padding:2px 8px;border-radius:4px;background:#1e3a5f;color:#93c5fd}
|
|
75
|
+
.empty{color:#888;font-style:italic}
|
|
76
|
+
</style>
|
|
77
|
+
</head>
|
|
78
|
+
<body>
|
|
79
|
+
<h1>VibeControls Plugin UIs</h1>
|
|
80
|
+
${z.length>0?`<ul>${J}</ul>`:'<p class="empty">No plugins with UIs installed.</p>'}
|
|
81
|
+
</body>
|
|
82
|
+
</html>`}function Zz(z){return new P({prefix:"/ui"}).onAfterHandle(({set:J})=>{J.headers["Content-Security-Policy"]=w()}).get("/",()=>{let J=z.getAllPlugins().filter((Q)=>Q.ui).map((Q)=>({name:Q.name,title:Q.ui?.title??Q.name,tags:Q.tags}));return j(new Response(a(J),{headers:{"Content-Type":"text/html; charset=utf-8"}}))}).get("/*",async({params:J,request:Q,set:W})=>{let X=(J["*"]||"").split("/").filter(Boolean);if(X.length===0)return W.status=404,{error:"Plugin not specified"};let $=X[0];if(!F($))return W.status=404,{error:`Invalid plugin name '${$}'`};let x=X.length===1||X.length===2&&!X[1],A=Q.headers.get("sec-fetch-mode"),d=x&&(A==="navigate"||A===null),C=q(Q,$);if(!(!!C&&S(C,$))){if(d)return W.status=200,W.headers["content-type"]="text/html; charset=utf-8",W.headers["Content-Security-Policy"]=w(),i($);return W.status=401,{error:"Unauthorized: UI plugin cookie required"}}let L=z.getPluginByKey($),I=X.slice(1).join("/");if(L&&X.length>=2){let G=z.getPluginByKey(X[1]);if(G?.ui)L=G,I=X.slice(2).join("/")}if(!L?.ui)return W.status=404,{error:`No UI available for plugin '${$}'`};if(L.ui.devUrl){if(!r(L.ui.devUrl))return W.status=403,{error:"Plugin UI dev proxy is disabled for this URL"};try{let G=new URL(L.ui.devUrl);G.pathname=`/${I}`.replace(/\/+/g,"/");let B=await fetch(G,{redirect:"manual"}),O=await B.arrayBuffer(),Y=new Headers;return B.headers.forEach((K,H)=>Y.set(H,K)),j(new Response(O,{status:B.status,headers:Y}))}catch{return W.status=502,{error:`Failed to proxy to dev server at ${L.ui.devUrl}`}}}if(L.ui.staticDir){let G=L.ui.staticDir,O=await v(L,G,I||"index.html");if(!O)return W.status=403,{error:"Access denied"};let Y=Bun.file(O);if(await Y.exists()){let _=s(O);if(_==="text/html"){let y=await Y.text();return j(new Response(R(y),{headers:{"Content-Type":"text/html; charset=utf-8"}}))}return j(new Response(Y,{headers:{"Content-Type":_}}))}let K=await v(L,G,"index.html"),H=K?Bun.file(K):null;if(H&&await H.exists()){let _=await H.text();return j(new Response(R(_),{headers:{"Content-Type":"text/html; charset=utf-8"}}))}return W.status=404,{error:"File not found"}}return W.status=404,{error:"No UI configuration (neither staticDir nor devUrl)"}})}function Vz(){return{getAgentApiKey:()=>N(),verifyIframeToken:(z,J)=>f(z,J),verifyUiCookieToken:(z,J)=>S(z,J),issueUiCookieToken:(z,J)=>{let Q=h(z,J);return{token:Q.token,expiresAt:Date.parse(Q.expiresAt)}},getIframeTokenFromRequest:(z,J)=>c(z,J),getUiCookieFromRequest:(z,J)=>q(z,J),isValidUiPluginName:(z)=>F(z),frameAncestorsCsp:()=>w()}}
|
|
83
|
+
export{m as wa,i as xa,Zz as ya,Vz as za};
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{Bb as k,Cb as a,Db as y,Kb as T,Lb as x,tb as r,yb as v}from"./index-01qzsnwd.js";import{Ub as B}from"./index-04n4qgvd.js";import{Jd as e,Nd as j}from"./index-9bqd8veb.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},{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 eb,SJ as fb,c as gb,LJ as hb,E as ib,b as jb,XJ as kb,MJ as lb,WJ as mb,tJ as nb,sJ as ob,eJ as pb,JQ as qb,QQ as rb,ZQ as sb};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{$a as S,Za as h,_a as Z}from"./index-rc79x8fw.js";import{bb as K}from"./index-yrgm89r8.js";import"./index-52cp759f.js";import{Tb as X,Ub as R}from"./index-04n4qgvd.js";import{ic as N,jc as O,kc as D}from"./index-5mw3eshk.js";import{nc as W,oc as _,pc as F,qc as A,rc as G,tc as $,uc as I,vc as U,wc as j,xc as C}from"./index-z5a4yxzz.js";import"./index-ef95xr4z.js";import{Kc as V,Mc as M,Nc as q,Pc as E,Qc as J}from"./index-xjzmb1pn.js";import"./index-g2raeeh4.js";import"./index-9bqd8veb.js";import"./index-0cn9bv8z.js";import"./index-jw1k4vbk.js";import"./index-yy1mm8zs.js";function L(Q,w){if(Q==="telemetry.enabled")K.setEnabled(w==="true")}function v(Q){return Object.entries(Q).map(([w,x])=>({key:w,value:x}))}function T(Q){let{db:w}=Q;return new R().get("/",async()=>{let x=await w.getAllConfig(),B=S(x);return{config:B,configs:v(B)}}).get("/status",async()=>{return await w.getConfigStatus()}).get("/:key",async({params:x,set:B})=>{let H=await w.getConfig(x.key);if(H===void 0)return B.status=404,{error:"Configuration key not found"};return{key:x.key,value:Z(x.key,H)}}).put("/:key",async({params:x,body:B,set:H})=>{if(h(x.key))return H.status=403,{error:"Configuration key is managed by a dedicated endpoint"};try{return await w.setConfig(x.key,B.value),L(x.key,B.value),{success:!0}}catch(z){return H.status=500,{error:"Failed to set configuration",details:String(z)}}},{body:X.Object({value:X.String()})}).delete("/:key",async({params:x,set:B})=>{if(h(x.key))return B.status=403,{error:"Configuration key is managed by a dedicated endpoint"};if(await w.getConfig(x.key)===void 0)return B.status=404,{error:"Configuration key not found"};try{return await w.deleteConfig(x.key),{success:!0}}catch(z){return B.status=500,{error:"Failed to delete configuration",details:String(z)}}}).post("/",async({body:x,set:B})=>{if(h(x.key))return B.status=403,{error:"Configuration key is managed by a dedicated endpoint"};try{return await w.setConfig(x.key,x.value),L(x.key,x.value),{success:!0,key:x.key}}catch(H){return B.status=500,{error:"Failed to set configuration",details:String(H)}}},{body:X.Object({key:X.String(),value:X.String()})}).post("/bulk",async({body:x,set:B})=>{let H=Object.keys(x.configs).filter(h);if(H.length>0)return B.status=403,{error:"One or more configuration keys are managed by dedicated endpoints",keys:H};try{await w.bulkSetConfig(x.configs);for(let[z,P]of Object.entries(x.configs))L(z,P);return{success:!0}}catch(z){return B.status=500,{error:"Failed to set configuration",details:String(z)}}},{body:X.Object({configs:X.Record(X.String(),X.String())})})}var f="http://localhost:3005";function u(Q){Q.command("config").description("Manage VibeControls agent configuration").option("--set <key=value>","Set a configuration value").option("--get <key>","Get a configuration value").option("--delete <key>","Delete a configuration value").option("--list","List all configuration values",!1).option("--value <value>","Value used with `--set <key>` (alternative to `--set key=value`)").option("--agent-url <url>","Agent URL",f).option("--json","Emit JSON").option("--plain","Force plain text output").action(async function(w){let x={...Q.opts(),...w};try{let B=V(w),H=encodeURIComponent(M(x));if(w.set){let z=w.set.indexOf("="),P,Y;if(z===-1){if(w.value===void 0){if(x.json){D(x,{ok:!1,error:"Invalid format: use key=value or --set key --value v"});return}F(`Invalid format. Use ${W.bold("--set key=value")} or ${W.bold("--set key --value value")}`);return}P=w.set.trim(),Y=String(w.value).trim()}else P=w.set.slice(0,z).trim(),Y=w.set.slice(z+1).trim();if(!P){if(x.json){D(x,{ok:!1,error:"Configuration key cannot be empty"});return}F("Configuration key cannot be empty.");return}if(await E(B,`/api/profiles/${H}/config/${encodeURIComponent(P)}`,{value:Y}),D(x,{ok:!0,key:P}))return;G(`${_.success} Set ${W.bold(P)} = ${W.cyan(String(Z(P,Y)))}`)}else if(w.get)await O({mode:N(x),fetchData:()=>q(B,`/api/profiles/${H}/config/${encodeURIComponent(w.get)}`),plain:(z)=>{I("Configuration"),j(),U(z.key,W.bold(String(Z(z.key,z.value)))),j()},json:(z)=>({key:z.key,value:Z(z.key,z.value)})});else if(w.delete){if(await J(B,`/api/profiles/${H}/config/${encodeURIComponent(w.delete)}`),D(x,{ok:!0,key:w.delete}))return;G(`${_.success} Deleted configuration key: ${W.bold(w.delete)}`)}else if(w.list)await O({mode:N(x),fetchData:()=>q(B,`/api/profiles/${H}/config/`),plain:(z)=>{if(I("Agent Configuration"),j(),!z.configs||z.configs.length===0){$(`${_.info} No configuration entries found.`);return}let P=z.configs.map((Y)=>({Key:Y.key,Value:String(Z(Y.key,Y.value))}));C(P),j(),$(`${_.info} ${z.configs.length} configuration(s) found.`)},json:(z)=>(z.configs??[]).map((P)=>({key:P.key,value:Z(P.key,P.value)}))});else{if(x.json){D(x,{ok:!1,error:"No operation specified"});return}$(`${_.info} Usage:`),$(` ${W.bold("vibe config --list")} List all config values`),$(` ${W.bold("vibe config --get <key>")} Get a config value`),$(` ${W.bold("vibe config --set <key=value>")} Set a config value`),$(` ${W.bold("vibe config --delete <key>")} Delete a config value`)}}catch(B){if(x.json){D(x,{ok:!1,error:A(B)});return}F(`Config operation failed: ${A(B)}`)}})}function k(Q,w){u(Q)}function d(Q){return{name:"config",version:"2.2.0",description:"Agent configuration key-value store",capabilities:{storage:"rw",audit:!0},tags:["backend","cli"],cliCommand:"config",apiPrefix:"/api/config",createRoutes:(w)=>T(w),onCliSetup:async(w,x)=>{k(w,x)}}}export{d as createPlugin};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{fe as $}from"./index-yy1mm8zs.js";var v=$((Eq)=>{Object.defineProperty(Eq,"__esModule",{value:!0});Eq.VERSION=void 0;Eq.VERSION="1.9.1"});var Sq=$((Pq)=>{Object.defineProperty(Pq,"__esModule",{value:!0});Pq.isCompatible=Pq._makeCompatibilityCheck=void 0;var jZ=v(),Tq=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function yq(q){let z=new Set([q]),J=new Set,Z=q.match(Tq);if(!Z)return()=>!1;let Q={major:+Z[1],minor:+Z[2],patch:+Z[3],prerelease:Z[4]};if(Q.prerelease!=null)return function(Y){return Y===q};function X(G){return J.add(G),!1}function H(G){return z.add(G),!0}return function(Y){if(z.has(Y))return!0;if(J.has(Y))return!1;let w=Y.match(Tq);if(!w)return X(Y);let F={major:+w[1],minor:+w[2],patch:+w[3],prerelease:w[4]};if(F.prerelease!=null)return X(Y);if(Q.major!==F.major)return X(Y);if(Q.major===0){if(Q.minor===F.minor&&Q.patch<=F.patch)return H(Y);return X(Y)}if(Q.minor<=F.minor)return H(Y);return X(Y)}}Pq._makeCompatibilityCheck=yq;Pq.isCompatible=yq(jZ.VERSION)});var O=$((vq)=>{Object.defineProperty(vq,"__esModule",{value:!0});vq.unregisterGlobal=vq.getGlobal=vq.registerGlobal=void 0;var K=v(),DZ=Sq(),IZ=K.VERSION.split(".")[0],k=Symbol.for(`opentelemetry.js.api.${IZ}`),D=typeof globalThis==="object"?globalThis:typeof self==="object"?self:typeof window==="object"?window:typeof global==="object"?global:{};function VZ(q,z,J,Z=!1){var Q;let X=D[k]=(Q=D[k])!==null&&Q!==void 0?Q:{version:K.VERSION};if(!Z&&X[q]){let H=Error(`@opentelemetry/api: Attempted duplicate registration of API: ${q}`);return J.error(H.stack||H.message),!1}if(X.version!==K.VERSION){let H=Error(`@opentelemetry/api: Registration of version v${X.version} for ${q} does not match previously registered API v${K.VERSION}`);return J.error(H.stack||H.message),!1}return X[q]=z,J.debug(`@opentelemetry/api: Registered a global for ${q} v${K.VERSION}.`),!0}vq.registerGlobal=VZ;function NZ(q){var z,J;let Z=(z=D[k])===null||z===void 0?void 0:z.version;if(!Z||!(0,DZ.isCompatible)(Z))return;return(J=D[k])===null||J===void 0?void 0:J[q]}vq.getGlobal=NZ;function bZ(q,z){z.debug(`@opentelemetry/api: Unregistering a global for ${q} v${K.VERSION}.`);let J=D[k];if(J)delete J[q]}vq.unregisterGlobal=bZ});var _q=$((dq)=>{Object.defineProperty(dq,"__esModule",{value:!0});dq.DiagComponentLogger=void 0;var EZ=O();class uq{constructor(q){this._namespace=q.namespace||"DiagComponentLogger"}debug(...q){return I("debug",this._namespace,q)}error(...q){return I("error",this._namespace,q)}info(...q){return I("info",this._namespace,q)}warn(...q){return I("warn",this._namespace,q)}verbose(...q){return I("verbose",this._namespace,q)}}dq.DiagComponentLogger=uq;function I(q,z,J){let Z=(0,EZ.getGlobal)("diag");if(!Z)return;return Z[q](z,...J)}});var C=$((xq)=>{Object.defineProperty(xq,"__esModule",{value:!0});xq.DiagLogLevel=void 0;var AZ;(function(q){q[q.NONE=0]="NONE",q[q.ERROR=30]="ERROR",q[q.WARN=50]="WARN",q[q.INFO=60]="INFO",q[q.DEBUG=70]="DEBUG",q[q.VERBOSE=80]="VERBOSE",q[q.ALL=9999]="ALL"})(AZ=xq.DiagLogLevel||(xq.DiagLogLevel={}))});var gq=$((cq)=>{Object.defineProperty(cq,"__esModule",{value:!0});cq.createLogLevelDiagLogger=void 0;var h=C();function TZ(q,z){if(q<h.DiagLogLevel.NONE)q=h.DiagLogLevel.NONE;else if(q>h.DiagLogLevel.ALL)q=h.DiagLogLevel.ALL;z=z||{};function J(Z,Q){let X=z[Z];if(typeof X==="function"&&q>=Q)return X.bind(z);return function(){}}return{error:J("error",h.DiagLogLevel.ERROR),warn:J("warn",h.DiagLogLevel.WARN),info:J("info",h.DiagLogLevel.INFO),debug:J("debug",h.DiagLogLevel.DEBUG),verbose:J("verbose",h.DiagLogLevel.VERBOSE)}}cq.createLogLevelDiagLogger=TZ});var B=$((pq)=>{Object.defineProperty(pq,"__esModule",{value:!0});pq.DiagAPI=void 0;var yZ=_q(),PZ=gq(),iq=C(),R=O(),MZ="diag";class u{static instance(){if(!this._instance)this._instance=new u;return this._instance}constructor(){function q(Z){return function(...Q){let X=(0,R.getGlobal)("diag");if(!X)return;return X[Z](...Q)}}let z=this,J=(Z,Q={logLevel:iq.DiagLogLevel.INFO})=>{var X,H,G;if(Z===z){let F=Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return z.error((X=F.stack)!==null&&X!==void 0?X:F.message),!1}if(typeof Q==="number")Q={logLevel:Q};let Y=(0,R.getGlobal)("diag"),w=(0,PZ.createLogLevelDiagLogger)((H=Q.logLevel)!==null&&H!==void 0?H:iq.DiagLogLevel.INFO,Z);if(Y&&!Q.suppressOverrideMessage){let F=(G=Error().stack)!==null&&G!==void 0?G:"<failed to generate stacktrace>";Y.warn(`Current logger will be overwritten from ${F}`),w.warn(`Current logger will overwrite one already registered from ${F}`)}return(0,R.registerGlobal)("diag",w,z,!0)};z.setLogger=J,z.disable=()=>{(0,R.unregisterGlobal)(MZ,z)},z.createComponentLogger=(Z)=>{return new yZ.DiagComponentLogger(Z)},z.verbose=q("verbose"),z.debug=q("debug"),z.info=q("info"),z.warn=q("warn"),z.error=q("error")}}pq.DiagAPI=u});var oq=$((sq)=>{Object.defineProperty(sq,"__esModule",{value:!0});sq.BaggageImpl=void 0;class f{constructor(q){this._entries=q?new Map(q):new Map}getEntry(q){let z=this._entries.get(q);if(!z)return;return Object.assign({},z)}getAllEntries(){return Array.from(this._entries.entries())}setEntry(q,z){let J=new f(this._entries);return J._entries.set(q,z),J}removeEntry(q){let z=new f(this._entries);return z._entries.delete(q),z}removeEntries(...q){let z=new f(this._entries);for(let J of q)z._entries.delete(J);return z}clear(){return new f}}sq.BaggageImpl=f});var eq=$((tq)=>{Object.defineProperty(tq,"__esModule",{value:!0});tq.baggageEntryMetadataSymbol=void 0;tq.baggageEntryMetadataSymbol=Symbol("BaggageEntryMetadata")});var d=$((qz)=>{Object.defineProperty(qz,"__esModule",{value:!0});qz.baggageEntryMetadataFromString=qz.createBaggage=void 0;var SZ=B(),vZ=oq(),mZ=eq(),uZ=SZ.DiagAPI.instance();function dZ(q={}){return new vZ.BaggageImpl(new Map(Object.entries(q)))}qz.createBaggage=dZ;function LZ(q){if(typeof q!=="string")uZ.error(`Cannot create baggage metadata from unknown type: ${typeof q}`),q="";return{__TYPE__:mZ.baggageEntryMetadataSymbol,toString(){return q}}}qz.baggageEntryMetadataFromString=LZ});var V=$((Jz)=>{Object.defineProperty(Jz,"__esModule",{value:!0});Jz.ROOT_CONTEXT=Jz.createContextKey=void 0;function xZ(q){return Symbol.for(q)}Jz.createContextKey=xZ;class E{constructor(q){let z=this;z._currentContext=q?new Map(q):new Map,z.getValue=(J)=>z._currentContext.get(J),z.setValue=(J,Z)=>{let Q=new E(z._currentContext);return Q._currentContext.set(J,Z),Q},z.deleteValue=(J)=>{let Z=new E(z._currentContext);return Z._currentContext.delete(J),Z}}}Jz.ROOT_CONTEXT=new E});var Xz=$((Qz)=>{Object.defineProperty(Qz,"__esModule",{value:!0});Qz.DiagConsoleLogger=Qz._originalConsoleMethods=void 0;var L=[{n:"error",c:"error"},{n:"warn",c:"warn"},{n:"info",c:"info"},{n:"debug",c:"debug"},{n:"verbose",c:"trace"}];Qz._originalConsoleMethods={};if(typeof console<"u"){let q=["error","warn","info","debug","trace","log"];for(let z of q)if(typeof console[z]==="function")Qz._originalConsoleMethods[z]=console[z]}class $z{constructor(){function q(z){return function(...J){let Z=Qz._originalConsoleMethods[z];if(typeof Z!=="function")Z=Qz._originalConsoleMethods.log;if(typeof Z!=="function"&&console){if(Z=console[z],typeof Z!=="function")Z=console.log}if(typeof Z==="function")return Z.apply(console,J)}}for(let z=0;z<L.length;z++)this[L[z].n]=q(L[z].c)}}Qz.DiagConsoleLogger=$z});var s=$((Hz)=>{Object.defineProperty(Hz,"__esModule",{value:!0});Hz.createNoopMeter=Hz.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC=Hz.NOOP_OBSERVABLE_GAUGE_METRIC=Hz.NOOP_OBSERVABLE_COUNTER_METRIC=Hz.NOOP_UP_DOWN_COUNTER_METRIC=Hz.NOOP_HISTOGRAM_METRIC=Hz.NOOP_GAUGE_METRIC=Hz.NOOP_COUNTER_METRIC=Hz.NOOP_METER=Hz.NoopObservableUpDownCounterMetric=Hz.NoopObservableGaugeMetric=Hz.NoopObservableCounterMetric=Hz.NoopObservableMetric=Hz.NoopHistogramMetric=Hz.NoopGaugeMetric=Hz.NoopUpDownCounterMetric=Hz.NoopCounterMetric=Hz.NoopMetric=Hz.NoopMeter=void 0;class _{constructor(){}createGauge(q,z){return Hz.NOOP_GAUGE_METRIC}createHistogram(q,z){return Hz.NOOP_HISTOGRAM_METRIC}createCounter(q,z){return Hz.NOOP_COUNTER_METRIC}createUpDownCounter(q,z){return Hz.NOOP_UP_DOWN_COUNTER_METRIC}createObservableGauge(q,z){return Hz.NOOP_OBSERVABLE_GAUGE_METRIC}createObservableCounter(q,z){return Hz.NOOP_OBSERVABLE_COUNTER_METRIC}createObservableUpDownCounter(q,z){return Hz.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC}addBatchObservableCallback(q,z){}removeBatchObservableCallback(q){}}Hz.NoopMeter=_;class U{}Hz.NoopMetric=U;class x extends U{add(q,z){}}Hz.NoopCounterMetric=x;class c extends U{add(q,z){}}Hz.NoopUpDownCounterMetric=c;class l extends U{record(q,z){}}Hz.NoopGaugeMetric=l;class g extends U{record(q,z){}}Hz.NoopHistogramMetric=g;class N{addCallback(q){}removeCallback(q){}}Hz.NoopObservableMetric=N;class i extends N{}Hz.NoopObservableCounterMetric=i;class p extends N{}Hz.NoopObservableGaugeMetric=p;class n extends N{}Hz.NoopObservableUpDownCounterMetric=n;Hz.NOOP_METER=new _;Hz.NOOP_COUNTER_METRIC=new x;Hz.NOOP_GAUGE_METRIC=new l;Hz.NOOP_HISTOGRAM_METRIC=new g;Hz.NOOP_UP_DOWN_COUNTER_METRIC=new c;Hz.NOOP_OBSERVABLE_COUNTER_METRIC=new i;Hz.NOOP_OBSERVABLE_GAUGE_METRIC=new p;Hz.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC=new n;function lZ(){return Hz.NOOP_METER}Hz.createNoopMeter=lZ});var jz=$((Uz)=>{Object.defineProperty(Uz,"__esModule",{value:!0});Uz.ValueType=void 0;var q0;(function(q){q[q.INT=0]="INT",q[q.DOUBLE=1]="DOUBLE"})(q0=Uz.ValueType||(Uz.ValueType={}))});var o=$((kz)=>{Object.defineProperty(kz,"__esModule",{value:!0});kz.defaultTextMapSetter=kz.defaultTextMapGetter=void 0;kz.defaultTextMapGetter={get(q,z){if(q==null)return;return q[z]},keys(q){if(q==null)return[];return Object.keys(q)}};kz.defaultTextMapSetter={set(q,z,J){if(q==null)return;q[z]=J}}});var bz=$((Vz)=>{Object.defineProperty(Vz,"__esModule",{value:!0});Vz.NoopContextManager=void 0;var J0=V();class Iz{active(){return J0.ROOT_CONTEXT}with(q,z,J,...Z){return z.call(J,...Z)}bind(q,z){return z}enable(){return this}disable(){return this}}Vz.NoopContextManager=Iz});var b=$((Rz)=>{Object.defineProperty(Rz,"__esModule",{value:!0});Rz.ContextAPI=void 0;var Z0=bz(),t=O(),Cz=B(),a="context",$0=new Z0.NoopContextManager;class e{constructor(){}static getInstance(){if(!this._instance)this._instance=new e;return this._instance}setGlobalContextManager(q){return(0,t.registerGlobal)(a,q,Cz.DiagAPI.instance())}active(){return this._getContextManager().active()}with(q,z,J,...Z){return this._getContextManager().with(q,z,J,...Z)}bind(q,z){return this._getContextManager().bind(q,z)}_getContextManager(){return(0,t.getGlobal)(a)||$0}disable(){this._getContextManager().disable(),(0,t.unregisterGlobal)(a,Cz.DiagAPI.instance())}}Rz.ContextAPI=e});var zq=$((Az)=>{Object.defineProperty(Az,"__esModule",{value:!0});Az.TraceFlags=void 0;var Q0;(function(q){q[q.NONE=0]="NONE",q[q.SAMPLED=1]="SAMPLED"})(Q0=Az.TraceFlags||(Az.TraceFlags={}))});var T=$((Tz)=>{Object.defineProperty(Tz,"__esModule",{value:!0});Tz.INVALID_SPAN_CONTEXT=Tz.INVALID_TRACEID=Tz.INVALID_SPANID=void 0;var W0=zq();Tz.INVALID_SPANID="0000000000000000";Tz.INVALID_TRACEID="00000000000000000000000000000000";Tz.INVALID_SPAN_CONTEXT={traceId:Tz.INVALID_TRACEID,spanId:Tz.INVALID_SPANID,traceFlags:W0.TraceFlags.NONE}});var y=$((vz)=>{Object.defineProperty(vz,"__esModule",{value:!0});vz.NonRecordingSpan=void 0;var X0=T();class Sz{constructor(q=X0.INVALID_SPAN_CONTEXT){this._spanContext=q}spanContext(){return this._spanContext}setAttribute(q,z){return this}setAttributes(q){return this}addEvent(q,z){return this}addLink(q){return this}addLinks(q){return this}setStatus(q){return this}updateName(q){return this}end(q){}isRecording(){return!1}recordException(q,z){}}vz.NonRecordingSpan=Sz});var $q=$((dz)=>{Object.defineProperty(dz,"__esModule",{value:!0});dz.getSpanContext=dz.setSpanContext=dz.deleteSpan=dz.setSpan=dz.getActiveSpan=dz.getSpan=void 0;var H0=V(),Y0=y(),G0=b(),Jq=(0,H0.createContextKey)("OpenTelemetry Context Key SPAN");function Zq(q){return q.getValue(Jq)||void 0}dz.getSpan=Zq;function F0(){return Zq(G0.ContextAPI.getInstance().active())}dz.getActiveSpan=F0;function uz(q,z){return q.setValue(Jq,z)}dz.setSpan=uz;function w0(q){return q.deleteValue(Jq)}dz.deleteSpan=w0;function h0(q,z){return uz(q,new Y0.NonRecordingSpan(z))}dz.setSpanContext=h0;function O0(q){var z;return(z=Zq(q))===null||z===void 0?void 0:z.spanContext()}dz.getSpanContext=O0});var M=$((gz)=>{Object.defineProperty(gz,"__esModule",{value:!0});gz.wrapSpanContext=gz.isSpanContextValid=gz.isValidSpanId=gz.isValidTraceId=void 0;var _z=T(),k0=y(),P=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1]);function xz(q,z){if(typeof q!=="string"||q.length!==z)return!1;let J=0;for(let Z=0;Z<q.length;Z+=4)J+=(P[q.charCodeAt(Z)]|0)+(P[q.charCodeAt(Z+1)]|0)+(P[q.charCodeAt(Z+2)]|0)+(P[q.charCodeAt(Z+3)]|0);return J===z}function cz(q){return xz(q,32)&&q!==_z.INVALID_TRACEID}gz.isValidTraceId=cz;function lz(q){return xz(q,16)&&q!==_z.INVALID_SPANID}gz.isValidSpanId=lz;function D0(q){return cz(q.traceId)&&lz(q.spanId)}gz.isSpanContextValid=D0;function I0(q){return new k0.NonRecordingSpan(q)}gz.wrapSpanContext=I0});var Xq=$((sz)=>{Object.defineProperty(sz,"__esModule",{value:!0});sz.NoopTracer=void 0;var C0=b(),pz=$q(),Qq=y(),R0=M(),Wq=C0.ContextAPI.getInstance();class nz{startSpan(q,z,J=Wq.active()){if(Boolean(z===null||z===void 0?void 0:z.root))return new Qq.NonRecordingSpan;let Q=J&&(0,pz.getSpanContext)(J);if(E0(Q)&&(0,R0.isSpanContextValid)(Q))return new Qq.NonRecordingSpan(Q);else return new Qq.NonRecordingSpan}startActiveSpan(q,z,J,Z){let Q,X,H;if(arguments.length<2)return;else if(arguments.length===2)H=z;else if(arguments.length===3)Q=z,H=J;else Q=z,X=J,H=Z;let G=X!==null&&X!==void 0?X:Wq.active(),Y=this.startSpan(q,Q,G),w=(0,pz.setSpan)(G,Y);return Wq.with(w,H,void 0,Y)}}sz.NoopTracer=nz;function E0(q){return q!==null&&typeof q==="object"&&"spanId"in q&&typeof q.spanId==="string"&&"traceId"in q&&typeof q.traceId==="string"&&"traceFlags"in q&&typeof q.traceFlags==="number"}});var Hq=$((tz)=>{Object.defineProperty(tz,"__esModule",{value:!0});tz.ProxyTracer=void 0;var A0=Xq(),T0=new A0.NoopTracer;class oz{constructor(q,z,J,Z){this._provider=q,this.name=z,this.version=J,this.options=Z}startSpan(q,z,J){return this._getTracer().startSpan(q,z,J)}startActiveSpan(q,z,J,Z){let Q=this._getTracer();return Reflect.apply(Q.startActiveSpan,Q,arguments)}_getTracer(){if(this._delegate)return this._delegate;let q=this._provider.getDelegateTracer(this.name,this.version,this.options);if(!q)return T0;return this._delegate=q,this._delegate}}tz.ProxyTracer=oz});var JJ=$((qJ)=>{Object.defineProperty(qJ,"__esModule",{value:!0});qJ.NoopTracerProvider=void 0;var y0=Xq();class ez{getTracer(q,z,J){return new y0.NoopTracer}}qJ.NoopTracerProvider=ez});var Yq=$(($J)=>{Object.defineProperty($J,"__esModule",{value:!0});$J.ProxyTracerProvider=void 0;var P0=Hq(),M0=JJ(),S0=new M0.NoopTracerProvider;class ZJ{getTracer(q,z,J){var Z;return(Z=this.getDelegateTracer(q,z,J))!==null&&Z!==void 0?Z:new P0.ProxyTracer(this,q,z,J)}getDelegate(){var q;return(q=this._delegate)!==null&&q!==void 0?q:S0}setDelegate(q){this._delegate=q}getDelegateTracer(q,z,J){var Z;return(Z=this._delegate)===null||Z===void 0?void 0:Z.getTracer(q,z,J)}}$J.ProxyTracerProvider=ZJ});var XJ=$((WJ)=>{Object.defineProperty(WJ,"__esModule",{value:!0});WJ.SamplingDecision=void 0;var v0;(function(q){q[q.NOT_RECORD=0]="NOT_RECORD",q[q.RECORD=1]="RECORD",q[q.RECORD_AND_SAMPLED=2]="RECORD_AND_SAMPLED"})(v0=WJ.SamplingDecision||(WJ.SamplingDecision={}))});var YJ=$((HJ)=>{Object.defineProperty(HJ,"__esModule",{value:!0});HJ.SpanKind=void 0;var m0;(function(q){q[q.INTERNAL=0]="INTERNAL",q[q.SERVER=1]="SERVER",q[q.CLIENT=2]="CLIENT",q[q.PRODUCER=3]="PRODUCER",q[q.CONSUMER=4]="CONSUMER"})(m0=HJ.SpanKind||(HJ.SpanKind={}))});var FJ=$((GJ)=>{Object.defineProperty(GJ,"__esModule",{value:!0});GJ.SpanStatusCode=void 0;var u0;(function(q){q[q.UNSET=0]="UNSET",q[q.OK=1]="OK",q[q.ERROR=2]="ERROR"})(u0=GJ.SpanStatusCode||(GJ.SpanStatusCode={}))});var OJ=$((wJ)=>{Object.defineProperty(wJ,"__esModule",{value:!0});wJ.validateValue=wJ.validateKey=void 0;var hq="[_0-9a-z-*/]",d0=`[a-z]${hq}{0,255}`,L0=`[a-z0-9]${hq}{0,240}@[a-z]${hq}{0,13}`,_0=new RegExp(`^(?:${d0}|${L0})$`),x0=/^[ -~]{0,255}[!-~]$/,c0=/,|=/;function l0(q){return _0.test(q)}wJ.validateKey=l0;function g0(q){return x0.test(q)&&!c0.test(q)}wJ.validateValue=g0});var DJ=$((jJ)=>{Object.defineProperty(jJ,"__esModule",{value:!0});jJ.TraceStateImpl=void 0;var BJ=OJ(),KJ=32,p0=512,fJ=",",UJ="=";class Oq{constructor(q){if(this._internalState=new Map,q)this._parse(q)}set(q,z){let J=this._clone();if(J._internalState.has(q))J._internalState.delete(q);return J._internalState.set(q,z),J}unset(q){let z=this._clone();return z._internalState.delete(q),z}get(q){return this._internalState.get(q)}serialize(){return Array.from(this._internalState.keys()).reduceRight((q,z)=>{return q.push(z+UJ+this.get(z)),q},[]).join(fJ)}_parse(q){if(q.length>p0)return;if(this._internalState=q.split(fJ).reduceRight((z,J)=>{let Z=J.trim(),Q=Z.indexOf(UJ);if(Q!==-1){let X=Z.slice(0,Q),H=Z.slice(Q+1,J.length);if((0,BJ.validateKey)(X)&&(0,BJ.validateValue)(H))z.set(X,H)}return z},new Map),this._internalState.size>KJ)this._internalState=new Map(Array.from(this._internalState.entries()).reverse().slice(0,KJ))}_keys(){return Array.from(this._internalState.keys()).reverse()}_clone(){let q=new Oq;return q._internalState=new Map(this._internalState),q}}jJ.TraceStateImpl=Oq});var NJ=$((IJ)=>{Object.defineProperty(IJ,"__esModule",{value:!0});IJ.createTraceState=void 0;var n0=DJ();function s0(q){return new n0.TraceStateImpl(q)}IJ.createTraceState=s0});var RJ=$((bJ)=>{Object.defineProperty(bJ,"__esModule",{value:!0});bJ.context=void 0;var r0=b();bJ.context=r0.ContextAPI.getInstance()});var TJ=$((EJ)=>{Object.defineProperty(EJ,"__esModule",{value:!0});EJ.diag=void 0;var o0=B();EJ.diag=o0.DiagAPI.instance()});var MJ=$((yJ)=>{Object.defineProperty(yJ,"__esModule",{value:!0});yJ.NOOP_METER_PROVIDER=yJ.NoopMeterProvider=void 0;var t0=s();class Bq{getMeter(q,z,J){return t0.NOOP_METER}}yJ.NoopMeterProvider=Bq;yJ.NOOP_METER_PROVIDER=new Bq});var uJ=$((vJ)=>{Object.defineProperty(vJ,"__esModule",{value:!0});vJ.MetricsAPI=void 0;var e0=MJ(),Kq=O(),SJ=B(),fq="metrics";class Uq{constructor(){}static getInstance(){if(!this._instance)this._instance=new Uq;return this._instance}setGlobalMeterProvider(q){return(0,Kq.registerGlobal)(fq,q,SJ.DiagAPI.instance())}getMeterProvider(){return(0,Kq.getGlobal)(fq)||e0.NOOP_METER_PROVIDER}getMeter(q,z,J){return this.getMeterProvider().getMeter(q,z,J)}disable(){(0,Kq.unregisterGlobal)(fq,SJ.DiagAPI.instance())}}vJ.MetricsAPI=Uq});var _J=$((dJ)=>{Object.defineProperty(dJ,"__esModule",{value:!0});dJ.metrics=void 0;var q1=uJ();dJ.metrics=q1.MetricsAPI.getInstance()});var gJ=$((cJ)=>{Object.defineProperty(cJ,"__esModule",{value:!0});cJ.NoopTextMapPropagator=void 0;class xJ{inject(q,z){}extract(q,z){return q}fields(){return[]}}cJ.NoopTextMapPropagator=xJ});var sJ=$((pJ)=>{Object.defineProperty(pJ,"__esModule",{value:!0});pJ.deleteBaggage=pJ.setBaggage=pJ.getActiveBaggage=pJ.getBaggage=void 0;var z1=b(),J1=V(),jq=(0,J1.createContextKey)("OpenTelemetry Baggage Key");function iJ(q){return q.getValue(jq)||void 0}pJ.getBaggage=iJ;function Z1(){return iJ(z1.ContextAPI.getInstance().active())}pJ.getActiveBaggage=Z1;function $1(q,z){return q.setValue(jq,z)}pJ.setBaggage=$1;function Q1(q){return q.deleteValue(jq)}pJ.deleteBaggage=Q1});var eJ=$((tJ)=>{Object.defineProperty(tJ,"__esModule",{value:!0});tJ.PropagationAPI=void 0;var kq=O(),Y1=gJ(),rJ=o(),S=sJ(),G1=d(),oJ=B(),Dq="propagation",F1=new Y1.NoopTextMapPropagator;class Iq{constructor(){this.createBaggage=G1.createBaggage,this.getBaggage=S.getBaggage,this.getActiveBaggage=S.getActiveBaggage,this.setBaggage=S.setBaggage,this.deleteBaggage=S.deleteBaggage}static getInstance(){if(!this._instance)this._instance=new Iq;return this._instance}setGlobalPropagator(q){return(0,kq.registerGlobal)(Dq,q,oJ.DiagAPI.instance())}inject(q,z,J=rJ.defaultTextMapSetter){return this._getGlobalPropagator().inject(q,z,J)}extract(q,z,J=rJ.defaultTextMapGetter){return this._getGlobalPropagator().extract(q,z,J)}fields(){return this._getGlobalPropagator().fields()}disable(){(0,kq.unregisterGlobal)(Dq,oJ.DiagAPI.instance())}_getGlobalPropagator(){return(0,kq.getGlobal)(Dq)||F1}}tJ.PropagationAPI=Iq});var JZ=$((qZ)=>{Object.defineProperty(qZ,"__esModule",{value:!0});qZ.propagation=void 0;var w1=eJ();qZ.propagation=w1.PropagationAPI.getInstance()});var HZ=$((WZ)=>{Object.defineProperty(WZ,"__esModule",{value:!0});WZ.TraceAPI=void 0;var Vq=O(),ZZ=Yq(),$Z=M(),j=$q(),QZ=B(),Nq="trace";class bq{constructor(){this._proxyTracerProvider=new ZZ.ProxyTracerProvider,this.wrapSpanContext=$Z.wrapSpanContext,this.isSpanContextValid=$Z.isSpanContextValid,this.deleteSpan=j.deleteSpan,this.getSpan=j.getSpan,this.getActiveSpan=j.getActiveSpan,this.getSpanContext=j.getSpanContext,this.setSpan=j.setSpan,this.setSpanContext=j.setSpanContext}static getInstance(){if(!this._instance)this._instance=new bq;return this._instance}setGlobalTracerProvider(q){let z=(0,Vq.registerGlobal)(Nq,this._proxyTracerProvider,QZ.DiagAPI.instance());if(z)this._proxyTracerProvider.setDelegate(q);return z}getTracerProvider(){return(0,Vq.getGlobal)(Nq)||this._proxyTracerProvider}getTracer(q,z){return this.getTracerProvider().getTracer(q,z)}disable(){(0,Vq.unregisterGlobal)(Nq,QZ.DiagAPI.instance()),this._proxyTracerProvider=new ZZ.ProxyTracerProvider}}WZ.TraceAPI=bq});var FZ=$((YZ)=>{Object.defineProperty(YZ,"__esModule",{value:!0});YZ.trace=void 0;var h1=HZ();YZ.trace=h1.TraceAPI.getInstance()});var E1=$((W)=>{Object.defineProperty(W,"__esModule",{value:!0});W.trace=W.propagation=W.metrics=W.diag=W.context=W.INVALID_SPAN_CONTEXT=W.INVALID_TRACEID=W.INVALID_SPANID=W.isValidSpanId=W.isValidTraceId=W.isSpanContextValid=W.createTraceState=W.TraceFlags=W.SpanStatusCode=W.SpanKind=W.SamplingDecision=W.ProxyTracerProvider=W.ProxyTracer=W.defaultTextMapSetter=W.defaultTextMapGetter=W.ValueType=W.createNoopMeter=W.DiagLogLevel=W.DiagConsoleLogger=W.ROOT_CONTEXT=W.createContextKey=W.baggageEntryMetadataFromString=void 0;var O1=d();Object.defineProperty(W,"baggageEntryMetadataFromString",{enumerable:!0,get:function(){return O1.baggageEntryMetadataFromString}});var wZ=V();Object.defineProperty(W,"createContextKey",{enumerable:!0,get:function(){return wZ.createContextKey}});Object.defineProperty(W,"ROOT_CONTEXT",{enumerable:!0,get:function(){return wZ.ROOT_CONTEXT}});var B1=Xz();Object.defineProperty(W,"DiagConsoleLogger",{enumerable:!0,get:function(){return B1.DiagConsoleLogger}});var K1=C();Object.defineProperty(W,"DiagLogLevel",{enumerable:!0,get:function(){return K1.DiagLogLevel}});var f1=s();Object.defineProperty(W,"createNoopMeter",{enumerable:!0,get:function(){return f1.createNoopMeter}});var U1=jz();Object.defineProperty(W,"ValueType",{enumerable:!0,get:function(){return U1.ValueType}});var hZ=o();Object.defineProperty(W,"defaultTextMapGetter",{enumerable:!0,get:function(){return hZ.defaultTextMapGetter}});Object.defineProperty(W,"defaultTextMapSetter",{enumerable:!0,get:function(){return hZ.defaultTextMapSetter}});var j1=Hq();Object.defineProperty(W,"ProxyTracer",{enumerable:!0,get:function(){return j1.ProxyTracer}});var k1=Yq();Object.defineProperty(W,"ProxyTracerProvider",{enumerable:!0,get:function(){return k1.ProxyTracerProvider}});var D1=XJ();Object.defineProperty(W,"SamplingDecision",{enumerable:!0,get:function(){return D1.SamplingDecision}});var I1=YJ();Object.defineProperty(W,"SpanKind",{enumerable:!0,get:function(){return I1.SpanKind}});var V1=FJ();Object.defineProperty(W,"SpanStatusCode",{enumerable:!0,get:function(){return V1.SpanStatusCode}});var N1=zq();Object.defineProperty(W,"TraceFlags",{enumerable:!0,get:function(){return N1.TraceFlags}});var b1=NJ();Object.defineProperty(W,"createTraceState",{enumerable:!0,get:function(){return b1.createTraceState}});var Cq=M();Object.defineProperty(W,"isSpanContextValid",{enumerable:!0,get:function(){return Cq.isSpanContextValid}});Object.defineProperty(W,"isValidTraceId",{enumerable:!0,get:function(){return Cq.isValidTraceId}});Object.defineProperty(W,"isValidSpanId",{enumerable:!0,get:function(){return Cq.isValidSpanId}});var Rq=T();Object.defineProperty(W,"INVALID_SPANID",{enumerable:!0,get:function(){return Rq.INVALID_SPANID}});Object.defineProperty(W,"INVALID_TRACEID",{enumerable:!0,get:function(){return Rq.INVALID_TRACEID}});Object.defineProperty(W,"INVALID_SPAN_CONTEXT",{enumerable:!0,get:function(){return Rq.INVALID_SPAN_CONTEXT}});var OZ=RJ();Object.defineProperty(W,"context",{enumerable:!0,get:function(){return OZ.context}});var BZ=TJ();Object.defineProperty(W,"diag",{enumerable:!0,get:function(){return BZ.diag}});var KZ=_J();Object.defineProperty(W,"metrics",{enumerable:!0,get:function(){return KZ.metrics}});var fZ=JZ();Object.defineProperty(W,"propagation",{enumerable:!0,get:function(){return fZ.propagation}});var UZ=FZ();Object.defineProperty(W,"trace",{enumerable:!0,get:function(){return UZ.trace}});W.default={context:OZ.context,diag:BZ.diag,metrics:KZ.metrics,propagation:fZ.propagation,trace:UZ.trace}});
|
|
3
|
+
export{E1 as g};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{Rc as M,nd as V}from"./index-g2raeeh4.js";import{Xd as H,be as G}from"./index-0cn9bv8z.js";import{existsSync as j,readFileSync as K}from"fs";import{join as z}from"path";var x="http://localhost:3005",_=new Set(["localhost","127.0.0.1","0.0.0.0","::1","[::1]"]);function N(I){return I.toLowerCase().replace(/^\[|\]$/g,"")}function O(I){try{let Q=new URL(I);return _.has(N(Q.hostname))}catch{return!1}}function B(I){let Q=new URL(I.trim());if(Q.protocol!=="http:"&&Q.protocol!=="https:")throw Error("Agent URL must use http or https");if(Q.username||Q.password)throw Error("Agent URL must not include credentials");let J=Q.toString().replace(/\/+$/,"");if(!O(J)&&process.env.VIBECONTROLS_ALLOW_REMOTE_AGENT_URL!=="1")throw Error("Refusing non-local agent URL. Set VIBECONTROLS_ALLOW_REMOTE_AGENT_URL=1 to target a remote/tunnel URL explicitly.");return J}function T(I){if(!Number.isInteger(I)||I<=0)return!1;try{return process.kill(I,0),!0}catch{return!1}}function D(){let I=z(G(),"agents.json");if(!j(I))return[];try{let Q=JSON.parse(K(I,"utf-8"));return(Array.isArray(Q)?Q:Q&&typeof Q==="object"&&Array.isArray(Q.instances)?Q.instances:[]).filter((W)=>!!W&&typeof W==="object"&&typeof W.name==="string"&&typeof W.port==="number")}catch{return[]}}function C(I){let J=D().find((W)=>W.name===I);if(!J||!J.port)return null;if(typeof J.pid==="number"&&!T(J.pid))return null;return{url:`http://localhost:${J.port}`,port:J.port}}function u(I){let Q=I?.agentUrl&&I.agentUrl!==x?I.agentUrl:void 0;if(Q)return B(Q);if(I?.profile){let J=C(I.profile);if(J)return J.url}if(process.env.AGENT_URL)return B(process.env.AGENT_URL);try{let J=S({}),W=C(J);if(W)return W.url}catch{}return B(x)}async function v(I){let Q=O(I);if(process.env.AGENT_API_KEY){if(Q||process.env.VIBECONTROLS_SEND_API_KEY_TO_REMOTE==="1")return process.env.AGENT_API_KEY;throw Error("Refusing to send AGENT_API_KEY to a non-local agent URL. Set VIBECONTROLS_SEND_API_KEY_TO_REMOTE=1 only if you trust the target.")}if(!Q)return;let J=await F(I);if(J)return J;let W=H(),X=await M(`${W}:static-api-key`);if(X)return X;return V()["static-api-key"]}async function F(I){try{let Q=encodeURIComponent(H()),J=new AbortController,W=setTimeout(()=>J.abort(),2000);try{let X=await fetch(`${I}/api/profiles/${Q}/agent/api-key`,{signal:J.signal});if(!X.ok)return;return(await X.json().catch(()=>null))?.apiKey||void 0}finally{clearTimeout(W)}}catch{return}}function S(I){if(I?.profile)return I.profile;if(process.env.VIBECONTROLS_PROFILE)return process.env.VIBECONTROLS_PROFILE;try{let Q=z(G(),"agents.json");if(j(Q)){let J=JSON.parse(K(Q,"utf-8")),W=J&&typeof J==="object"&&!Array.isArray(J)?J.defaultProfile:void 0;if(typeof W==="string"&&W.length>0)return W}}catch{}return"default"}async function q(I,Q,J={}){let W=await v(I),X={...J.body?{"Content-Type":"application/json"}:{},...W?{"x-agent-api-key":W}:{},...J.headers??{}},Y;try{Y=await fetch(`${I}${Q}`,{...J,headers:X})}catch(Z){let R=Z instanceof Error?Z.message:String(Z),k=/unable to connect|ECONNREFUSED|ENOTFOUND|EHOSTUNREACH|fetch failed/i.test(R);if(k&&O(I))throw Error(`Agent not reachable at ${I}. Is it running? Try 'vibe status' or 'vibe start'.`,{cause:Z});if(k)throw Error(`Agent not reachable at ${I}. ${R}`,{cause:Z});throw Z}let $=await Y.json().catch(()=>({}));return{ok:Y.ok,status:Y.status,data:$}}async function f(I,Q){let{ok:J,status:W,data:X}=await q(I,Q);if(!J){let Y=X?.error||X?.message||`Agent returned ${W}`;throw Error(String(Y))}return X}async function A(I,Q,J){let{ok:W,status:X,data:Y}=await q(I,Q,{method:"POST",body:J!=null?JSON.stringify(J):void 0});if(!W){let $=Y?.error||Y?.message||`Agent returned ${X}`;throw Error(String($))}return Y}async function m(I,Q,J){let{ok:W,status:X,data:Y}=await q(I,Q,{method:"PUT",body:J!=null?JSON.stringify(J):void 0});if(!W){let $=Y?.error||Y?.message||`Agent returned ${X}`;throw Error(String($))}return Y}async function h(I,Q){let{ok:J,status:W,data:X}=await q(I,Q,{method:"DELETE"});if(!J){let Y=X?.error||X?.message||`Agent returned ${W}`;throw Error(String(Y))}return X}
|
|
3
|
+
export{O as Jc,u as Kc,v as Lc,S as Mc,f as Nc,A as Oc,m as Pc,h as Qc};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{cb as Y,db as k}from"./index-52cp759f.js";import{Nd as W}from"./index-9bqd8veb.js";import{be as V}from"./index-0cn9bv8z.js";import{createHash as g,randomUUID as x}from"crypto";import{existsSync as $,mkdirSync as L,readFileSync as O,writeFileSync as j}from"fs";import{join as K}from"path";import*as X from"os";var A="https://analytics.burdenoff.com/api/track",H="cd7d5ccc3667",w=200,f=10,B=30000,R=5000;function C(q){if(process.env.DO_NOT_TRACK==="1")return!1;let z=process.env.VIBECONTROLS_TELEMETRY?.toLowerCase();if(z==="on"||z==="true"||z==="1")return!0;if(z==="off"||z==="false"||z==="0")return!1;return q}class M{enabled=!1;persisted=!1;buffer=[];flushTimer=null;cachedAnonymousId=null;overflowWarned=!1;postFailureWarned=!1;initialized=!1;init(q){if(q?.persisted!==void 0)this.persisted=q.persisted;if(this.enabled=C(this.persisted),!this.initialized)this.initialized=!0,this.startFlushTimer()}setEnabled(q){let z=this.enabled;if(this.persisted=q,this.enabled=C(this.persisted),z&&!this.enabled)this.buffer=[],this.enqueueRaw("telemetry.disabled",{reason:"user_opt_out"}),this.flush()}emit(q,z={}){if(!this.enabled)return;let G={},J=!1;for(let[Z,N]of Object.entries(z)){if(Y(Z)){J=!0;continue}G[Z]=N}let Q=k(q,G);if(!Q.ok||!Q.sanitized){W().logger.warn("telemetry",`dropping event '${q}': ${Q.reason??"invalid"}`);return}this.enqueue(q,Q.sanitized)}enqueueRaw(q,z){this.enqueue(q,z)}enqueue(q,z){let G={site_id:H,event_name:q,properties:z,anonymous_id:this.getAnonymousId(),timestamp:new Date().toISOString()};if(this.buffer.length>=w){if(this.buffer.shift(),!this.overflowWarned)this.overflowWarned=!0,W().logger.warn("telemetry",`buffer overflow (cap=${w}) \u2014 dropping oldest events`)}if(this.buffer.push(G),this.buffer.length>=f)this.flush()}async flush(){if(this.buffer.length===0)return;let q=this.buffer.splice(0,this.buffer.length),z=new AbortController,G=setTimeout(()=>z.abort(),R);try{await fetch(A,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({events:q}),signal:z.signal})}catch(J){if(!this.postFailureWarned)this.postFailureWarned=!0,W().logger.warn("telemetry","shipper POST failed; dropping batch",{error:String(J)})}finally{clearTimeout(G)}}stop(){if(this.flushTimer)clearInterval(this.flushTimer),this.flushTimer=null;this.initialized=!1}_resetForTest(){this.stop(),this.enabled=!1,this.persisted=!1,this.buffer=[],this.cachedAnonymousId=null,this.overflowWarned=!1,this.postFailureWarned=!1}_bufferLength(){return this.buffer.length}_isEnabled(){return this.enabled}startFlushTimer(){if(this.flushTimer)return;if(this.flushTimer=setInterval(()=>{this.flush()},B),typeof this.flushTimer.unref==="function")this.flushTimer.unref()}getAnonymousId(){if(this.cachedAnonymousId)return this.cachedAnonymousId;let q=`${X.hostname()}${X.platform()}`,z=this.readOrCreateInstallId(),G=g("sha256").update(q+z).digest("hex");return this.cachedAnonymousId=G.slice(0,16),this.cachedAnonymousId}readOrCreateInstallId(){let q;try{q=V()}catch{q=K(process.cwd(),".boff","vibecontrols")}if(!$(q))try{L(q,{recursive:!0,mode:448})}catch{}let z=K(q,".install-id");if($(z))try{let J=O(z,"utf-8").trim();if(J)return J}catch{}let G=x();try{j(z,G,{mode:384})}catch{}return G}}var b=new M;
|
|
3
|
+
export{b as bb};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
var j=Object.create;var{getPrototypeOf:k,defineProperty:f,getOwnPropertyNames:l}=Object;var m=Object.prototype.hasOwnProperty;function n(a){return this[a]}var o,p,s=(a,b,c)=>{var g=a!=null&&typeof a==="object";if(g){var h=b?o??=new WeakMap:p??=new WeakMap,i=h.get(a);if(i)return i}c=a!=null?j(k(a)):{};let d=b||!a||!a.__esModule?f(c,"default",{value:a,enumerable:!0}):c;for(let e of l(a))if(!m.call(d,e))f(d,e,{get:n.bind(a,e),enumerable:!0});if(g)h.set(a,d);return d};var t=(a,b)=>()=>(b||a((b={exports:{}}).exports,b),b.exports);var q=(a)=>a;function r(a,b){this[a]=q.bind(null,b)}var u=(a,b)=>{for(var c in b)f(a,c,{get:b[c],enumerable:!0,configurable:!0,set:r.bind(b,c)})};var v=import.meta.require;
|
|
3
|
+
export{s as ee,t as fe,u as ge,v as he};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{he as A}from"./index-yy1mm8zs.js";var j=!process.env.NO_COLOR&&!!process.stdout.isTTY;function L(q){j=q}var C=(q,B)=>(F)=>j?`${q}${F}${B}`:F,z={bold:C("\x1B[1m","\x1B[22m"),dim:C("\x1B[2m","\x1B[22m"),italic:C("\x1B[3m","\x1B[23m"),underline:C("\x1B[4m","\x1B[24m"),red:C("\x1B[31m","\x1B[39m"),green:C("\x1B[32m","\x1B[39m"),yellow:C("\x1B[33m","\x1B[39m"),blue:C("\x1B[34m","\x1B[39m"),magenta:C("\x1B[35m","\x1B[39m"),cyan:C("\x1B[36m","\x1B[39m"),white:C("\x1B[37m","\x1B[39m"),gray:C("\x1B[90m","\x1B[39m"),brightRed:C("\x1B[91m","\x1B[39m"),brightGreen:C("\x1B[92m","\x1B[39m"),brightYellow:C("\x1B[93m","\x1B[39m"),brightBlue:C("\x1B[94m","\x1B[39m"),reset:"\x1B[0m"},Q={get success(){return z.green("\u2713")},get error(){return z.red("\u2717")},get warning(){return z.yellow("\u26A0")},get info(){return z.blue("\u25CF")},get running(){return z.green("\u25CF")},get stopped(){return z.red("\u25CB")},get pending(){return z.yellow("\u25CC")},get arrow(){return z.gray("\u2192")},get bullet(){return z.gray("\u2022")},get check(){return z.green("\u2714")}};function T(q){console.error(`${z.red("Error:")} ${q}`),process.exit(1)}function H(q){if(q instanceof Error)return q.message;if(typeof q==="string")return q;try{return JSON.stringify(q)}catch{return String(q)}}function M(q){console.log(` ${Q.success} ${q}`)}function f(q){console.log(` ${Q.warning} ${q}`)}function E(q){console.log(` ${Q.info} ${q}`)}function D(q){console.log(`
|
|
3
|
+
${z.bold(`\u2500\u2500 ${q} \u2500\u2500`)}
|
|
4
|
+
`)}function X(q,B){let F=B===null||B===void 0?z.gray("(none)"):String(B);console.log(` ${z.bold(q.padEnd(14))} ${F}`)}function $(){console.log()}function S(q){if(q.length===0){console.log(" (none)");return}console.table(q)}function W(q){let B=Date.now()-new Date(q).getTime(),F=Math.floor(B/1000);if(F<0)return"just now";if(F<60)return`${F}s ago`;let J=Math.floor(F/60);if(J<60)return`${J}m ago`;let N=Math.floor(J/60);if(N<24)return`${N}h ago`;let P=Math.floor(N/24);if(P<30)return`${P}d ago`;return`${Math.floor(P/30)}mo ago`}function x(q){if(q<60)return`${Math.floor(q)}s`;let B=Math.floor(q/60),F=Math.floor(q%60);if(B<60)return`${B}m ${F}s`;let J=Math.floor(B/60),N=B%60;return`${J}h ${N}m`}function K(q){if(q<1024)return`${q} B`;if(q<1048576)return`${(q/1024).toFixed(1)} KB`;if(q<1073741824)return`${(q/1048576).toFixed(1)} MB`;return`${(q/1073741824).toFixed(1)} GB`}function h(q){switch(q){case"running":case"active":case"healthy":case"success":case"completed":return z.green(q);case"stopped":case"inactive":case"terminated":case"failed":return z.red(q);case"starting":case"stopping":case"pending":case"warning":return z.yellow(q);case"error":return z.red(q);default:return q}}function k(q,B=10){if(q.length<=B)return q;return q.substring(0,B)+"..."}async function v(q,B=15000){let F=Date.now(),J=!1;while(Date.now()-F<B){try{if((await fetch(`${q}/health`)).ok){J=!0;break}}catch{}await new Promise((G)=>setTimeout(G,500))}if(!J){console.log(`
|
|
5
|
+
${Q.warning} Agent not yet responding at ${q}. Check ${z.bold("vibe logs")} for details.
|
|
6
|
+
`);return}let N=process.env.VIBECONTROLS_PROFILE||"default",P=`${q}/api/profiles/${encodeURIComponent(N)}/agent/tunnel`,R="(unavailable)";try{let{resolveDefaultApiKey:G}=await import("./key.cmd-wgcq6kt8.js"),I=await G();if(I)R=I}catch{}let Y=R&&R!=="(unavailable)"?{"x-agent-api-key":R}:{},O="(not running)",Z=!1;try{let G=await fetch(P,{headers:Y});if(G.ok){let I=await G.json();if(I.tunnelUrl)O=I.tunnelUrl;else if(I.status!=="inactive")Z=!0}}catch{}if(Z||O==="(not running)"){process.stdout.write(` ${Q.info} Provisioning tunnel (first run downloads the tunnel binary)\u2026`);let G=150000,I=Date.now();while(Date.now()-I<G){try{let V=await fetch(P,{headers:Y});if(V.ok){let _=await V.json();if(_.tunnelUrl){O=_.tunnelUrl;break}}}catch{}await new Promise((V)=>setTimeout(V,1500)),process.stdout.write(`\r ${Q.info} Provisioning tunnel (first run downloads the tunnel binary)\u2026 ${Math.round((Date.now()-I)/1000)}s`)}process.stdout.write(`
|
|
7
|
+
`)}if(D("Agent Connection Details"),X("Agent URL:",q),X("API Key:",R),X("Tunnel URL:",O==="(not running)"?z.yellow(O):z.green(O)),$(),console.log(" Copy the API Key and Tunnel URL into the VibeControls UI agent configuration."),O==="(not running)")console.log(` ${z.yellow("Tunnel still provisioning")} \u2014 the cloudflared download may still be running in the daemon.`),console.log(` Re-check shortly: ${z.bold("vibe url")}`),console.log(` Start it manually: ${z.bold(`vibe tunnel agent --start --agent-url ${q}`)}`),console.log(` If it never appears: ${z.bold("vibe logs --tail 80")} (look for 'tunnel-bootstrap' / 'install')`);$()}
|
|
8
|
+
export{L as mc,z as nc,Q as oc,T as pc,H as qc,M as rc,f as sc,E as tc,D as uc,X as vc,$ as wc,S as xc,W as yc,x as zc,K as Ac,h as Bc,k as Cc,v as Dc};
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
// @bun
|
|
3
|
+
import{j as o,k as r,l as t,m as e,n as XQ}from"./index-c58g96mb.js";import"./index-n7qyrdr1.js";import{t as QQ}from"./index-6jq17k9s.js";import"./index-1hnw0rhc.js";import"./index-6jzsthh9.js";import"./index-g8zv1gta.js";import"./index-qfz9fy56.js";import"./index-ssjmzqcz.js";import"./index-tp4y9jde.js";import"./index-4wgjx8bf.js";import{Da as a}from"./index-g3ap3xpr.js";import"./index-0ckffygp.js";import"./index-rc79x8fw.js";import{bb as W}from"./index-yrgm89r8.js";import"./index-52cp759f.js";import"./index-v9fx5wab.js";import{Ib as s,Jb as i}from"./index-01qzsnwd.js";import"./index-d5ysy1yn.js";import"./index-04n4qgvd.js";import"./index-xjzmb1pn.js";import{Rc as p,Sc as v,nd as C,td as l,ud as n}from"./index-g2raeeh4.js";import{Nd as q}from"./index-9bqd8veb.js";import{Xd as D,_d as S,ae as g,be as M}from"./index-0cn9bv8z.js";import"./index-jw1k4vbk.js";import{he as B}from"./index-yy1mm8zs.js";import{isAbsolute as MQ}from"path";import{existsSync as V,mkdirSync as y,readFileSync as _Q,readdirSync as P,renameSync as BQ,unlinkSync as DQ,writeFileSync as f}from"fs";import{dirname as d,join as F}from"path";var GQ=".secrets-migrated-v1",IQ=["static-api-key","clientId","clientSecret"];function WQ(Q,H){return`${Q}:${H}`}function c(){return F(M(),GQ)}function TQ(){let Q=c();y(d(Q),{recursive:!0}),f(Q,`${new Date().toISOString()}
|
|
4
|
+
`,{mode:384})}function JQ(Q){if(!V(Q))return null;try{let H=_Q(Q,"utf8"),X=JSON.parse(H);if(X&&typeof X==="object"&&!Array.isArray(X))return X}catch{}return null}function VQ(Q,H){y(d(Q),{recursive:!0});let X=`${Q}.${process.pid}.tmp`;f(X,`${JSON.stringify(H,null,2)}
|
|
5
|
+
`,{mode:384}),BQ(X,Q)}function FQ(){let Q=M(),H=F(Q,"agents");if(!V(H))return[];let X=[],L;try{L=P(H)}catch{return[]}for(let Y of L){let z=F(H,Y,"config.json");if(!V(z))continue;X.push({path:z,scope:Y})}return X}function jQ(){let Q=M(),H=F(Q,"profiles");if(!V(H))return[];let X=[],L;try{L=P(H)}catch{return[]}for(let Y of L){if(!Y.endsWith(".json"))continue;X.push({path:F(H,Y),scope:Y.slice(0,-5)})}return X}async function KQ(Q,H){let X=JQ(Q);if(!X)return 0;let L=0;for(let Y of IQ){let z=X[Y];if(typeof z!=="string"||z.length===0)continue;let _=WQ(H,Y);try{await v(_,z),delete X[Y],L++,q().logger.info("secrets-migrator","migrated field",{path:Q,scope:H,key:Y})}catch(G){q().logger.warn("secrets-migrator","failed to migrate field",{path:Q,scope:H,key:Y,error:String(G)})}}if(L>0)VQ(Q,X);return L}async function m(){let Q={alreadyMigrated:!1,fieldsMoved:0,filesUpdated:0};if(V(c()))return Q.alreadyMigrated=!0,Q;let H=[...FQ(),...jQ()];for(let X of H){let L;try{L=await KQ(X.path,X.scope)}catch(Y){q().logger.warn("secrets-migrator","skipping target after error",{path:X.path,error:String(Y)});continue}if(L>0)Q.fieldsMoved+=L,Q.filesUpdated++}try{TQ()}catch(X){q().logger.warn("secrets-migrator","failed to drop migration marker",{error:String(X)})}if(Q.fieldsMoved>0)q().logger.info("secrets-migrator","migration complete",{fieldsMoved:Q.fieldsMoved,filesUpdated:Q.filesUpdated});return Q}{let Q=JSON.parse.bind(JSON);JSON.parse=(L,Y)=>{try{return Q(L,Y)}catch(z){if(typeof L==="string"&&L.endsWith("}}"))try{return Q(L.slice(0,-1),Y)}catch{}throw z}};let X=globalThis.Request?.prototype;if(X&&typeof X.json==="function"){let L=X.json;X.json=async function(){let z=await this.text();if(!z)return;try{return Q(z)}catch{if(z.endsWith("}}"))try{return Q(z.slice(0,-1))}catch{}let _=new Request("http://shim/",{method:"POST",body:z});return L.call(_)}}}}QQ();l();if(!process.env.VIBECONTROLS_DATA_DIR)process.env.VIBECONTROLS_DATA_DIR=S();if(typeof Bun>"u")console.error("ERROR: VibeControls Agent requires Bun runtime."),console.error("Install Bun: https://bun.sh"),process.exit(1);function UQ(Q){if(Q==="default")return 3005;let H=2166136261;for(let X=0;X<Q.length;X++)H=Math.imul(H^Q.charCodeAt(X),16777619);return 3100+Math.abs(H)%300}var E=(()=>{try{return D()}catch{return"default"}})(),A=Number.parseInt(process.env.PORT||String(UQ(E)),10),U=Number.isInteger(A)&&A>0?A:3005,R=process.env.HOST||"0.0.0.0",RQ=(()=>{let Q=process.env.DB_PATH;if(!Q)return;if(MQ(Q))return Q;console.warn(`[boot] Ignoring relative DB_PATH=${Q} (cwd=${process.cwd()}). Use an absolute path or unset to fall back to ${g()}.`);return})(),x=process.env.AGENT_API_KEY||void 0,CQ=process.env.LOG_LEVEL||"info",EQ=process.env.CORS_ORIGIN||void 0;async function wQ(){try{await m()}catch($){q().logger.warn("server","secrets migration encountered an error",{error:String($)})}let Q=C()["static-api-key"],H=(()=>{try{return D()}catch{return"default"}})(),X=Q??await p(`${H}:static-api-key`),L=!x&&!X;await s(),await n();let Y=process.env.VIBE_CLIENT_ID,z=process.env.VIBE_CLIENT_SECRET,_=process.env.VIBE_GLOBAL_GATEWAY_URL,G=process.env.VIBE_WORKSPACE_GATEWAY_URL,b=process.env.VIBE_WORKSPACE_ID,ZQ=!!Y&&!!z&&!!_&&!!G&&!!b;q().logger.info("server","Starting VibeControls Agent...",{runtime:"bun",bunVersion:Bun.version,port:U,host:R,env:"production"});try{let $=C(),Z=$["telemetry.enabled"]===!0||$["telemetry.enabled"]==="true";W.init({persisted:Z});let N=Date.now();W.emit("agent.started",{version:process.env.npm_package_version??"unknown",profile:E,platform:process.platform}),process.__vibe_started_at=N}catch{}let j=Math.max(1,Number.parseInt(process.env.VIBECONTROLS_AGENT_BOOT_RETRIES??"10",10)||10),$Q=($)=>{let Z=String($?.message??$).toLowerCase();return Z.includes("syntax")||Z.includes("cannot find module")||Z.includes("module not found")||Z.includes("typeerror")||Z.includes("config schema")||Z.includes("invalid config")||Z.includes("corrupt")||Z.includes("eaccess")||Z.includes("eperm")},O=null,I=0;while(!O){I++;try{O=await XQ({port:U,host:R,dbPath:RQ,apiKey:x,logLevel:CQ,corsOrigin:EQ}),await O.start();try{let $=await import("fs"),Z=`${S()}/runtime.json`;$.writeFileSync(Z,JSON.stringify({pid:process.pid,port:U,host:R,profile:E,startedAt:new Date().toISOString(),version:a()},null,2));let N=()=>{try{if($.existsSync(Z))$.unlinkSync(Z)}catch{}};process.once("SIGTERM",N),process.once("SIGINT",N),process.once("exit",N)}catch($){q().logger.warn("server","Could not write runtime.json",{error:String($)})}}catch($){let Z=$Q($);if(q().logger.error("server","Failed to start agent server",{attempt:I,maxBootAttempts:j,fatal:Z,error:String($)}),Z||I>=j)console.error(`\u274C Failed to start VibeControls Agent (attempt ${I}/${j}, fatal=${Z}):`,$),process.exit(1);let N=Math.min(30000,1000*2**Math.min(5,I-1)),J=Math.floor(Math.random()*500),K=N+J;console.warn(`\u26A0\uFE0F Agent boot attempt ${I}/${j} failed (transient), retrying in ${Math.round(K/1000)}s...`),await new Promise((k)=>setTimeout(k,K)),O=null}}let h=O.getServiceRegistry().getProvider("tunnel"),T=null;if(h?.getActiveTunnelUrl)for(let $=0;$<30;$++){if(T=await h.getActiveTunnelUrl(),T)break;await new Promise((Z)=>setTimeout(Z,1000))}if(!T){let{sanitizeEnvSuffix:$}=await import("./tunnel-bootstrap-2kg79ng8.js"),{getVibecontrolsProfile:Z}=await import("./path-utils-35re7qf9.js"),N=$(Z());T=process.env[`AGENT_TUNNEL_URL_${N}`]??process.env.AGENT_TUNNEL_URL??null}let HQ=C(),LQ=x||i()||HQ["static-api-key"]||"",w=q().getBootState(),YQ=w==="ready"?null:o();if(w==="ready")r();kQ({port:U,host:R,tunnelUrl:T,apiKey:LQ,revealApiKey:L||process.env.AGENT_PRINT_API_KEY==="1",state:w,pairingToken:YQ});try{t({profile:E})}catch($){q().logger.warn("server","Could not start autoupdate",{error:String($)})}let{existsSync:NQ,unlinkSync:qQ}=await import("fs"),{tmpdir:zQ}=await import("os"),{join:OQ}=await import("path"),u=async($)=>{q().logger.info("server",`Received ${$}, shutting down...`),e();try{let N=process.__vibe_started_at??Date.now();W.emit("agent.stopped",{uptime_s:Math.round((Date.now()-N)/1000),reason:$}),await W.flush(),W.stop()}catch{}let Z=O.getLifecycle();if($==="SIGTERM"){let N=OQ(zQ(),`.boff-vibecontrols-kill-${process.pid}`);if(NQ(N)){try{qQ(N)}catch{}if(q().logger.info("server","Kill-intent flag detected \u2014 full shutdown"),Z)await Z.kill();else await O.stop({reason:"shutdown"}),process.exit(0)}else if(q().logger.info("server","No kill flag \u2014 treating as hot-reload (soft stop)"),Z)await Z.softStop();else await O.stop({reason:"reload"})}else if(Z)await Z.kill();else await O.stop({reason:"shutdown"}),process.exit(0)};if(process.on("SIGINT",()=>u("SIGINT")),process.on("SIGTERM",()=>u("SIGTERM")),ZQ){let $=(()=>{let Z=process.env.VIBECONTROLS_FINALIZE_TIMEOUT_MS,N=Z?Number.parseInt(Z,10):NaN;return Number.isFinite(N)&&N>0?N:300000})();q().logger.info("server",`VIBE_* env vars detected \u2014 running inline finalize (timeout ${Math.round($/1000)}s)`),(async()=>{let Z={clientId:Y,clientSecret:z,workspaceId:b,globalGatewayUrl:_,workspaceGatewayUrl:G};try{let N=await Promise.race([O.finalize(Z),new Promise((J)=>setTimeout(()=>J({ok:!1,error:`inline finalize timed out after ${Math.round($/1000)}s`}),$))]);if(!N.ok){q().logger.warn("server","Inline finalize failed \u2014 agent stays awaiting-config. Background retry worker will keep trying.",{error:N.error});let{startFinalizeRetryWorker:J}=await import("./finalize-retry-worker-xp1nhv3c.js"),{setFinalizeRetryHandle:K}=await import("./finalize-retry-handle-registry-vv241fsq.js"),k=J({trigger:()=>O.finalize(Z)});K(k)}}catch(N){q().logger.error("server","Inline finalize threw",{error:String(N)})}})()}else q().logger.info("server","Agent is awaiting gateway credentials. Add it on the VibeControls platform using the tunnel URL and API key shown above.")}function kQ(Q){let X=(G)=>("\u2551 "+G).padEnd(65)+"\u2551",L="\u2560"+"\u2550".repeat(64)+"\u2563",Y="\u2554"+"\u2550".repeat(64)+"\u2557",z="\u255A"+"\u2550".repeat(64)+"\u255D",_=Q.revealApiKey?Q.apiKey:Q.apiKey?`${Q.apiKey.substring(0,8)}****${Q.apiKey.substring(Q.apiKey.length-4)}`:"(none)";if(console.log(""),console.log(Y),console.log(X("VibeControls Agent")),console.log(L),console.log(X(`State: ${Q.state}`)),console.log(X(`Agent URL: http://${Q.host}:${Q.port}`)),console.log(X(`API Key: ${_}`)),console.log(X(`Tunnel URL: ${Q.tunnelUrl??"(none)"}`)),Q.pairingToken)console.log(X(`Pairing: ${Q.pairingToken}`)),console.log(X(" (send as x-pairing-token on bootstrap)"));if(console.log(L),console.log(X(`Health: http://localhost:${Q.port}/health`)),console.log(X(`Status: http://localhost:${Q.port}/api/agent/status`)),console.log(z),!Q.revealApiKey)console.log(" (Set AGENT_PRINT_API_KEY=1 to print the API key in full.)");console.log("")}wQ();
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
; Query from: https://raw.githubusercontent.com/nvim-treesitter/nvim-treesitter/refs/heads/master/queries/markdown/injections.scm
|
|
2
|
+
(fenced_code_block
|
|
3
|
+
(info_string
|
|
4
|
+
(language) @_lang)
|
|
5
|
+
(code_fence_content) @injection.content
|
|
6
|
+
(#set-lang-from-info-string! @_lang))
|
|
7
|
+
|
|
8
|
+
((html_block) @injection.content
|
|
9
|
+
(#set! injection.language "html")
|
|
10
|
+
(#set! injection.combined)
|
|
11
|
+
(#set! injection.include-children))
|
|
12
|
+
|
|
13
|
+
((minus_metadata) @injection.content
|
|
14
|
+
(#set! injection.language "yaml")
|
|
15
|
+
(#offset! @injection.content 1 0 -1 0)
|
|
16
|
+
(#set! injection.include-children))
|
|
17
|
+
|
|
18
|
+
((plus_metadata) @injection.content
|
|
19
|
+
(#set! injection.language "toml")
|
|
20
|
+
(#offset! @injection.content 1 0 -1 0)
|
|
21
|
+
(#set! injection.include-children))
|
|
22
|
+
|
|
23
|
+
([
|
|
24
|
+
(inline)
|
|
25
|
+
(pipe_table_cell)
|
|
26
|
+
] @injection.content
|
|
27
|
+
(#set! injection.language "markdown_inline"))
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{Vb as a,Wb as b}from"./index-dm6yjmgq.js";import"./index-2xs9cvjn.js";import"./index-5mw3eshk.js";import"./index-z5a4yxzz.js";import"./index-ef95xr4z.js";import"./index-xjzmb1pn.js";import"./index-g2raeeh4.js";import"./index-9bqd8veb.js";import"./index-0cn9bv8z.js";import"./index-jw1k4vbk.js";import"./index-yy1mm8zs.js";export{a as resolveDefaultApiKey,b as register};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{$d as f,Wd as a,Xd as b,Yd as c,Zd as d,_d as e,ae as g,be as h,ce as i}from"./index-0cn9bv8z.js";import"./index-yy1mm8zs.js";export{c as validateAgentName,d as isPathInside,f as getVibecontrolsProfilesDir,b as getVibecontrolsProfile,h as getVibecontrolsProductDir,e as getVibecontrolsDir,g as getProfileDataDir,i as getPluginRegistry,a as assertValidProfile};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{Ga as a,Ia as b,Qa as c,Ra as d,Sa as e,Ta as f,Ua as g,Va as h,Wa as i}from"./index-g3ap3xpr.js";import"./index-0ckffygp.js";import"./index-9bqd8veb.js";import"./index-0cn9bv8z.js";import"./index-jw1k4vbk.js";import"./index-yy1mm8zs.js";export{f as validatePluginPackageName,c as getRegistryAllowlist,e as getPluginPackageRoot,g as getInstallScope,d as assertRegistryAllowed,b as TRUSTED_PACKAGES,i as PluginManager,h as DEFAULT_PLUGINS,a as CORE_PLUGIN_NAMES};
|