@vibecontrols/agent 2026.1130.1 → 2026.1202.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{agent-config-xwvsmn6b.js → agent-config-mg5dvtm3.js} +1 -1
- package/dist/{agent-ready-tracker-7ebr09d9.js → agent-ready-tracker-b1dxkhrt.js} +1 -1
- package/dist/app-hvt8zawq.js +2 -0
- package/dist/autostart.cmd-4c0rekqt.js +2 -0
- package/dist/bootstrap-workspace-wsjzmm9n.js +2 -0
- package/dist/bootstrap.service-0m0rcq8d.js +2 -0
- package/dist/{bridge-client-9ax1cvj6.js → bridge-client-fcwk5tyk.js} +1 -1
- package/dist/{bridge-commands-hc1gvngq.js → bridge-commands-xagq5kq7.js} +1 -1
- package/dist/cli.js +1 -1
- package/dist/daemon-profile-0bvscqm2.js +2 -0
- package/dist/{finalize-retry-worker-c38km3mt.js → finalize-retry-worker-qe7zagk7.js} +1 -1
- package/dist/gateway-client-8gfze3jv.js +2 -0
- package/dist/{index-dr6rsnpk.js → index-2a1yq04v.js} +3 -3
- package/dist/{index-dgbe8jm8.js → index-2nq1tefj.js} +1 -1
- package/dist/{index-j99tkngg.js → index-30qr1qm3.js} +1 -1
- package/dist/{index-ednz6yz2.js → index-4qqsx04e.js} +1 -1
- package/dist/{index-twtvt4yt.js → index-5ygnxt32.js} +3 -3
- package/dist/{index-rhn7wy1p.js → index-6g3qhprq.js} +1 -1
- package/dist/{index-5tghd67e.js → index-6xd9k363.js} +6 -6
- package/dist/{index-j9jwwzq2.js → index-8y4fys3s.js} +7 -7
- package/dist/{index-yfk0pb00.js → index-ag2b7yeg.js} +1 -1
- package/dist/{index-bk17490n.js → index-c9q14161.js} +1 -1
- package/dist/{index-damc6cvc.js → index-djwa3tm3.js} +1 -1
- package/dist/{index-0rmmrrfh.js → index-ep20qw1j.js} +1 -1
- package/dist/{index-6nv5rdqh.js → index-fm1wjs3r.js} +1 -1
- package/dist/{index-12gb48hg.js → index-j9cg16we.js} +1 -1
- package/dist/{index-f5nmxa9e.js → index-jhgd7sva.js} +1 -1
- package/dist/{index-76vza24h.js → index-mrcjqvnf.js} +1 -1
- package/dist/{index-p7fbnfwd.js → index-n3kwtv6f.js} +2 -2
- package/dist/{index-e5jdx9c1.js → index-nqa1m94e.js} +2 -2
- package/dist/index-nxpw3anc.js +30 -0
- package/dist/{index-zcnfj1q4.js → index-prp5nvsa.js} +3 -3
- package/dist/{index-qzwbctkv.js → index-pw6aqemr.js} +4 -4
- package/dist/{index-4kf3nr14.js → index-r1v0yazw.js} +2 -2
- package/dist/{index-q4fht6h2.js → index-r2j1t657.js} +19 -19
- package/dist/{index-vhz1c474.js → index-tn2vyz8q.js} +1 -1
- package/dist/{index-br9bakfm.js → index-txchzvfc.js} +2 -2
- package/dist/{index-85jn7v8t.js → index-xertgyzn.js} +5 -5
- package/dist/{index-wxb9dgwq.js → index-zekdqp0t.js} +1 -1
- package/dist/{index-8jk4a62x.js → index-zfhmg1gz.js} +6 -6
- package/dist/{index-sjs32cgn.js → index-zngtj9re.js} +2 -2
- package/dist/index.js +2 -2
- package/dist/key.cmd-eevbsknq.js +2 -0
- package/dist/log-shipper-h7azf3f8.js +2 -0
- package/dist/{path-utils-qgkdkp5j.js → path-utils-3sgj48ta.js} +1 -1
- package/dist/plugin-system-e1a3ttpy.js +2 -0
- package/dist/prereqs-runner-etehmhk8.js +2 -0
- package/dist/profile-mount-rr5kr708.js +2 -0
- package/dist/register-core-7kb2k9g3.js +2 -0
- package/dist/secondary-profile-attach-2x3dsnn8.js +2 -0
- package/dist/subprocess-j0r8hvmc.js +2 -0
- package/dist/telemetry-fyced899.js +2 -0
- package/dist/tunnel-bootstrap-rm5k7qw4.js +2 -0
- package/package.json +1 -1
- package/dist/app-ntnpwedw.js +0 -2
- package/dist/autostart.cmd-mdyv35dn.js +0 -2
- package/dist/bootstrap-workspace-1pt0bwy6.js +0 -2
- package/dist/bootstrap.service-gehm65tt.js +0 -2
- package/dist/daemon-profile-fnhc7pcf.js +0 -2
- package/dist/gateway-client-3zp6kkav.js +0 -2
- package/dist/index-7wm4bqx5.js +0 -21
- package/dist/key.cmd-y415ngam.js +0 -2
- package/dist/log-shipper-02rqvtq8.js +0 -2
- package/dist/plugin-system-e690jr6e.js +0 -2
- package/dist/prereqs-runner-w7z2dwa6.js +0 -2
- package/dist/profile-mount-ga5z1vx9.js +0 -2
- package/dist/register-core-n1dy472f.js +0 -2
- package/dist/secondary-profile-attach-v7kxsk4z.js +0 -2
- package/dist/subprocess-p9bv9nqz.js +0 -2
- package/dist/telemetry-1d3t1mbf.js +0 -2
- package/dist/tunnel-bootstrap-m51w4d94.js +0 -2
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{r,E}from"./index-1t74r13z.js";import{
|
|
3
|
-
`);return}if(w)await w(C);if(t)C.telemetry?.emit(t,{plugin:O})},onServerStop:async(P)=>{if(a)await a(P)},onNuke:async(P,C)=>{if(p)return p(P,C)}}}var ie=class{logger;source;constructor(b,O){this.logger=b,this.source=O}info(b,O){this.logger?.info?.(this.source,b,O)}warn(b,O){this.logger?.warn?.(this.source,b,O)}error(b,O){this.logger?.error?.(this.source,b,O)}debug(b,O){this.logger?.debug?.(this.source,b,O)}};import{existsSync as Je,rmSync as We,statSync as ze}from"fs";import{resolve as Ye}from"path";function ae(b=I()){let O=[],w=Ye(b),a=ne();if(!li(a,w))throw Error("Refusing to reset a path outside the agents directory");if(Je(w)&&ze(w).isDirectory())We(w,{recursive:!0,force:!0}),O.push(w);return{removed:O,agentDir:w}}var X="alias",ce=/^[a-zA-Z0-9_-]{1,64}$/,le=16384,ue=256,me=1024,Xe=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 H extends Error{code;constructor(b,O){super(O);this.code=b,this.name="AliasValidationError"}}class Q extends Error{constructor(b){super(`alias '${b}' already exists`);this.name="AliasConflictError"}}class W extends Error{constructor(b){super(`alias '${b}' not found`);this.name="AliasNotFoundError"}}function Qe(b){if(typeof b!=="string"||!ce.test(b))throw new H("invalid_name",`alias name must match ${ce} (got '${b}')`);if(Xe.has(b))throw new H("reserved_name",`alias name '${b}' is reserved`)}function ge(b){if(typeof b!=="string"||b.length===0)throw new H("invalid_command","alias command must be a non-empty string");if(b.length>le)throw new H("command_too_long",`alias command exceeds ${le} bytes`)}function pe(b){if(b===void 0)return;if(typeof b!=="string")throw new H("invalid_description","alias description must be a string");if(b.length>ue)throw new H("description_too_long",`alias description exceeds ${ue} chars`)}function fe(b){if(b===void 0||b===null||b==="")return;if(typeof b!=="string")throw new H("invalid_cwd","alias cwd must be a string");if(b.length>me)throw new H("cwd_too_long",`alias cwd exceeds ${me} chars`);if(b.includes("\x00"))throw new H("invalid_cwd","alias cwd must not contain NUL bytes")}function Ze(b){if(!b)return;try{return JSON.parse(b)}catch{return}}async function se(b){let O=await b.getAllPluginState(X),w=[];for(let a of O){let p=Ze(a.value);if(p)w.push(p)}return w.sort((a,p)=>a.name.localeCompare(p.name)),w}async function z(b,O){return(await se(b)).find((a)=>a.name===O)}function de(b){if(b===void 0||b===null)return null;let O=b.trim();return O===""?null:O}async function he(b,O){if(Qe(O.name),ge(O.command),pe(O.description),fe(O.cwd),await z(b,O.name))throw new Q(O.name);let a=new Date().toISOString(),p={id:crypto.randomUUID(),name:O.name,command:O.command,description:O.description,cwd:de(O.cwd),profile:R(),createdAt:a,updatedAt:a};return await b.setPluginState(X,p.id,JSON.stringify(p)),p}async function ye(b,O,w){let a=await z(b,O);if(!a)throw new W(O);if(w.command!==void 0)ge(w.command);if(w.description!==void 0)pe(w.description);if(w.cwd!==void 0)fe(w.cwd);let p={...a,command:w.command??a.command,description:w.description!==void 0?w.description:a.description,cwd:w.cwd!==void 0?de(w.cwd):a.cwd,updatedAt:new Date().toISOString()};return await b.setPluginState(X,p.id,JSON.stringify(p)),p}async function ve(b,O){let w=await z(b,O);if(!w)throw new W(O);await b.deletePluginState(X,w.id)}function Z(){let b=B()??e();return{dir:b.dataDir,scope:b.name}}function be(b){let{serviceRegistry:O,db:w}=b;return new E().get("/api-key",({request:a,set:p})=>{if(Ve(a))return p.status=403,{error:"Forbidden",message:"Browser requests are not permitted on /api/agent/api-key"};let t=L(Object.fromEntries(a.headers.entries()));if(!V(t))return p.status=401,{error:"Unauthorized",message:"Invalid or missing API key"};return{apiKey:K()}}).post("/reset-key",async({body:a,set:p})=>{let t=a.apiKey;if(!t||typeof t!=="string")return p.status=400,{error:"Missing required field: apiKey"};try{return await vi(t),await e().keyVault.bindApiKey(t),e().logger.info("auth","Adopted backend-rotated agent API key via /reset-key"),{success:!0}}catch(h){return p.status=400,{error:"reset-key failed",message:h instanceof Error?h.message:String(h)}}},{body:r.Object({apiKey:r.String()})}).get("/audit",({query:a})=>{let p=a,t=p.limit?Math.min(5000,Math.max(1,Number.parseInt(p.limit,10)||100)):100,h=e().audit.listEvents({since:p.since,limit:t,event:p.event});return{events:h,count:h.length}},{query:r.Object({since:r.Optional(r.String()),limit:r.Optional(r.String()),event:r.Optional(r.String())})}).get("/setup/check",()=>{let a=De();return{ready:a.filter((t)=>t.required).every((t)=>t.installed),dependencies:a}}).post("/setup/install",async({request:a,server:p,set:t})=>{let h=await Me(a,"VIBECONTROLS_ALLOW_REMOTE_SETUP_INSTALL",p);if(h)return t.status=403,{error:"Forbidden",message:h};return await ct()}).get("/url",async()=>{let a=O.getProvider("tunnel"),p=a&&a.getActiveTunnelUrl?await a.getActiveTunnelUrl():null,t=`http://localhost:${process.env.PORT||3005}`;return{url:p||t,tunnelUrl:p,localUrl:t,source:p?"tunnel":"local"}}).get("/lifecycle/state",()=>({state:O.getService("agent","lifecycle")?.getState()??"running"})).post("/lifecycle/stop",async({set:a})=>{let p=O.getService("agent","lifecycle");if(!p)return a.status=500,{error:"Lifecycle manager not initialized"};return await p.stop(),{state:"stopped"}}).post("/lifecycle/start",async({set:a})=>{let p=O.getService("agent","lifecycle");if(!p)return a.status=500,{error:"Lifecycle manager not initialized"};return await p.start(),{state:"running"}}).post("/lifecycle/kill",async({set:a})=>{let p=O.getService("agent","lifecycle");if(!p)return a.status=500,{error:"Lifecycle manager not initialized"};return setTimeout(()=>p.kill(),100),{state:"killing"}}).post("/log-level",async({body:a,request:p,server:t,set:h})=>{let P=await Me(p,"VIBECONTROLS_ALLOW_REMOTE_LOG_LEVEL",t);if(P)return h.status=403,{error:"Forbidden",message:P};let C=String(a.level??"").toLowerCase();if(!["debug","info","warn","error"].includes(C))return h.status=400,{error:"Invalid level",message:"level must be debug | info | warn | error"};return e().logger.setLevel(C),e().logger.info("agent",`Log level set to ${C} via API`),{ok:!0,level:C}},{body:r.Object({level:r.String()})}).post("/reset",async({body:a,request:p,server:t,set:h})=>{if(!a.confirm)return h.status=400,{error:"Reset confirmation required",message:"Send { confirm: true } to reset local agent state."};let P=await Me(p,"VIBECONTROLS_ALLOW_REMOTE_RESET",t);if(P)return h.status=403,{error:"Forbidden",message:P};let C=O.getService("agent","lifecycle");try{if(C)await C.prepareForReset()}catch(Y){e().logger.warn("agent","prepareForReset failed during reset \u2014 proceeding to wipe anyway",{error:String(Y)})}try{T.configure({globalGatewayUrl:"",workspaceGatewayUrl:void 0,clientId:"",clientSecret:"",workspaceId:void 0})}catch{}await w.close();let{removed:x,agentDir:N}=ae();e().logger.info("agent","Reset wiped local agent state",{agentDir:N,removed:x});let j=new Uint8Array(32);crypto.getRandomValues(j);let J=`vcak_${Buffer.from(j).toString("base64url")}`;return M({"static-api-key":J},Z()),e().setBootState("awaiting-config"),h.status=200,{success:!0,state:"awaiting-config",...Pe(p,t)||process.env.VIBECONTROLS_RETURN_RESET_API_KEY==="1"?{newApiKey:J}:{},agentDir:N,removed:x}},{body:r.Object({confirm:r.Boolean()})}).post("/sessions/:sessionId/share",async({params:a,body:p,server:t,request:h,set:P})=>{if(!Pe(h,t)&&process.env.VIBECONTROLS_ALLOW_REMOTE_SESSION_SHARE!=="1")return P.status=403,{error:"Forbidden",message:"Session-share mint must come from a local request unless VIBECONTROLS_ALLOW_REMOTE_SESSION_SHARE=1."};if(!we(a.sessionId))return P.status=400,{error:"BadRequest",message:"invalid sessionId"};let C=et(p?.expiresIn)??1800000,x=crypto.randomUUID(),N=new Uint8Array(32);crypto.getRandomValues(N);let j=`vcak_${Buffer.from(N).toString("base64url")}`,J=new Date(Date.now()+C).toISOString(),oe=[...(await import("./agent-config-xwvsmn6b.js")).readAgentConfig({dir:Z().dir}).apiKeys??[],{id:x,name:`session-share:${a.sessionId}:${p?.label??"viewer"}`,key:j,scopes:["read"],expiresAt:J,createdAt:new Date().toISOString()}];(await import("./agent-config-xwvsmn6b.js")).writeAgentConfig({apiKeys:oe},Z());let Y=O.getProvider("tunnel"),Te=(Y&&Y.getActiveTunnelUrl?await Y.getActiveTunnelUrl():null)??`http://localhost:${process.env.PORT||3005}`,_e=Ut({pathPrefixes:[`/terminal/${a.sessionId}`],methods:["GET"]},Math.min(600,Math.floor(C/1000))),je=`${Te.replace(/\/$/,"")}/terminal/${encodeURIComponent(a.sessionId)}/#vt=${encodeURIComponent(_e.token)}`;return e().logger.info("session-share","Minted share credential",{sessionId:a.sessionId,keyId:x,expiresAt:J}),{ok:!0,keyId:x,apiKey:j,joinUrl:je,sessionId:a.sessionId,expiresAt:J}},{params:r.Object({sessionId:r.String()}),body:r.Optional(r.Object({permissions:r.Optional(r.Array(r.String())),expiresIn:r.Optional(r.String()),label:r.Optional(r.String())}))}).get("/aliases",async()=>({aliases:await se(w)})).get("/aliases/:name",async({params:a,set:p})=>{let t=await z(w,a.name);if(!t)return p.status=404,{error:"Alias not found"};return t},{params:r.Object({name:r.String()})}).post("/aliases",async({body:a,set:p})=>{try{let t=await he(w,a);return p.status=201,t}catch(t){if(t instanceof Q)return p.status=409,{error:"Alias already exists",message:t.message};if(t instanceof H)return p.status=400,{error:t.code,message:t.message};throw t}},{body:r.Object({name:r.String(),command:r.String(),description:r.Optional(r.String()),cwd:r.Optional(r.Union([r.String(),r.Null()]))})}).put("/aliases/:name",async({params:a,body:p,set:t})=>{try{return await ye(w,a.name,p)}catch(h){if(h instanceof W)return t.status=404,{error:"Alias not found"};if(h instanceof H)return t.status=400,{error:h.code,message:h.message};throw h}},{params:r.Object({name:r.String()}),body:r.Object({command:r.Optional(r.String()),description:r.Optional(r.String()),cwd:r.Optional(r.Union([r.String(),r.Null()]))})}).delete("/aliases/:name",async({params:a,set:p})=>{try{return await ve(w,a.name),p.status=204,null}catch(t){if(t instanceof W)return p.status=404,{error:"Alias not found"};throw t}},{params:r.Object({name:r.String()})}).post("/aliases/:name/execute",async({params:a,body:p,set:t})=>{let h=await z(w,a.name);if(!h)return t.status=404,{error:"Alias not found"};let P=p?.args??[],C=await Ci(h,P);e().audit.emit("agent","alias.executed",{exit_code:C.exit_code});let x=Ke("alias.executed",{exit_code:C.exit_code});if(!x.ok)e().logger.debug("alias",`telemetry validate failed: ${x.reason}`);if(C.timed_out)t.status=408;return{exit_code:C.exit_code,stdout:C.stdout,stderr:C.stderr,duration_ms:C.duration_ms,truncated:C.truncated,cwd:C.cwd}},{params:r.Object({name:r.String()}),body:r.Optional(r.Object({args:r.Optional(r.Array(r.String()))}))}).post("/sessions/share/:keyId/revoke",async({params:a,server:p,request:t,set:h})=>{if(!Pe(t,p)&&process.env.VIBECONTROLS_ALLOW_REMOTE_SESSION_SHARE!=="1")return h.status=403,{error:"Forbidden"};let P=await import("./agent-config-xwvsmn6b.js"),C=Z(),x=P.readAgentConfig({dir:C.dir}),N=(x.apiKeys??[]).length,j=(x.apiKeys??[]).filter((J)=>J.id!==a.keyId);if(j.length===N)return h.status=404,{error:"No such share key"};return P.writeAgentConfig({apiKeys:j},C),{ok:!0,revoked:a.keyId}},{params:r.Object({keyId:r.String()})})}function et(b){if(!b)return null;let O=/^(\d+)([smhdw]?)$/.exec(b.trim());if(!O)return null;let w=Number(O[1]),a=O[2]||"m";return a==="s"?w*1000:a==="m"?w*60000:a==="h"?w*3600000:a==="d"?w*86400000:w*7*86400000}var tt="http://localhost:3005";function Se(b){b.command("health").description("Check health of a VibeControls agent instance").option("-n, --name <name>","Agent instance name").option("--agent-url <url>","Agent URL",tt).option("--json","Emit JSON").option("--plain","Force plain text output").action(async function(O){try{let w={...b.opts(),...O};await y({mode:_(w),fetchData:async()=>{if(w.name){let t=await new D().checkHealth(w.name);return{mode:"named",agentUrl:f(w),name:w.name,healthy:t.healthy,details:t.details??{}}}let a=f(w);try{let p=await S(a,"/health");return{mode:"url",agentUrl:a,healthy:!0,details:p}}catch(p){return{mode:"url",agentUrl:a,healthy:!1,details:{status:"unhealthy",...p instanceof Error?{error:A(p)}:{}}}}},plain:(a)=>{if(g("Agent Health"),c(),a.mode==="named"){if(!a.healthy){s(`Agent instance ${i.bold(a.name??"")} is not responding.`);return}let p=a.details;if(n("Instance",a.name??""),n("Status",G(p.status??"healthy")),p.uptime!==void 0)n("Uptime",`${p.uptime}s`);if(p.checks){c(),o(`${d.info} Health checks:`);for(let[t,h]of Object.entries(p.checks)){let P=h.status==="healthy"?d.success:d.error;n(` ${P} ${t}`,G(h.status))}}}else{if(n("URL",a.agentUrl),n("Status",G(a.details.status??"unhealthy")),a.details.version)n("Version",a.details.version);if(a.details.uptime!==void 0)n("Uptime",`${a.details.uptime}s`);if(a.details.timestamp)n("Timestamp",a.details.timestamp);if(a.details.checks){c(),o(`${d.info} Health checks:`);for(let[p,t]of Object.entries(a.details.checks)){let h=t.status==="healthy"?d.success:d.error;n(` ${h} ${p}`,G(t.status))}}}if(c(),a.healthy)l(`${d.success} Agent is healthy.`)},interactive:async(a)=>{let p=[];if(a.mode==="named")p.push(`Instance: ${a.name??""}`);else p.push(`URL: ${a.agentUrl}`);if(p.push(`Status: ${G(a.details.status??(a.healthy?"healthy":"unhealthy"))}`),a.details.version)p.push(`Version: ${a.details.version}`);if(a.details.uptime!==void 0)p.push(`Uptime: ${a.details.uptime}s`);if(a.details.timestamp)p.push(`Time: ${a.details.timestamp}`);if(a.details.checks){p.push(""),p.push("Checks:");for(let[t,h]of Object.entries(a.details.checks))p.push(` ${t}: ${h.status}`)}await U({title:"Agent Health",body:p.join(`
|
|
2
|
+
import{r,E}from"./index-1t74r13z.js";import{ke,ct}from"./index-r1v0yazw.js";import{T,R,li,I,ne,B,e}from"./index-nxpw3anc.js";import{M}from"./index-30qr1qm3.js";import"./index-x4z055t8.js";import{we,Ut,K,vi,L,V}from"./index-pw6aqemr.js";import{i,d,s,A,l,o,g,n,c,F,v,Jr,Ge,G}from"./index-j9cg16we.js";import{U}from"./index-sq5j8bjn.js";import{Zr}from"./index-ag2b7yeg.js";import{fi,pi,mi}from"./index-6xd9k363.js";import"./index-zfhmg1gz.js";import"./index-n3kwtv6f.js";import{Ve,Pe,Me}from"./index-zn9snqbg.js";import{Ci}from"./index-90gn0b6x.js";import{k}from"./index-5ygnxt32.js";import{Dt}from"./index-txchzvfc.js";import{N}from"./index-nqa1m94e.js";import{Ke}from"./index-cn4p1ks0.js";import{_,y,u}from"./index-v77bb0rm.js";import{f,Fe,m,S,q}from"./index-djwa3tm3.js";function re(b){let{name:O,onInit:w,onShutdown:a,onNuke:p,telemetryEventName:t,skipPlatforms:h}=b;return{onServerStart:async(P,C)=>{if(h&&h.includes(process.platform)){process.stderr.write(`[${O}] skipping init on unsupported platform '${process.platform}'
|
|
3
|
+
`);return}if(w)await w(C);if(t)C.telemetry?.emit(t,{plugin:O})},onServerStop:async(P)=>{if(a)await a(P)},onNuke:async(P,C)=>{if(p)return p(P,C)}}}var ie=class{logger;source;constructor(b,O){this.logger=b,this.source=O}info(b,O){this.logger?.info?.(this.source,b,O)}warn(b,O){this.logger?.warn?.(this.source,b,O)}error(b,O){this.logger?.error?.(this.source,b,O)}debug(b,O){this.logger?.debug?.(this.source,b,O)}};import{existsSync as Je,rmSync as We,statSync as ze}from"fs";import{resolve as Ye}from"path";function ae(b=I()){let O=[],w=Ye(b),a=ne();if(!li(a,w))throw Error("Refusing to reset a path outside the agents directory");if(Je(w)&&ze(w).isDirectory())We(w,{recursive:!0,force:!0}),O.push(w);return{removed:O,agentDir:w}}var X="alias",ce=/^[a-zA-Z0-9_-]{1,64}$/,le=16384,ue=256,me=1024,Xe=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 H extends Error{code;constructor(b,O){super(O);this.code=b,this.name="AliasValidationError"}}class Q extends Error{constructor(b){super(`alias '${b}' already exists`);this.name="AliasConflictError"}}class W extends Error{constructor(b){super(`alias '${b}' not found`);this.name="AliasNotFoundError"}}function Qe(b){if(typeof b!=="string"||!ce.test(b))throw new H("invalid_name",`alias name must match ${ce} (got '${b}')`);if(Xe.has(b))throw new H("reserved_name",`alias name '${b}' is reserved`)}function ge(b){if(typeof b!=="string"||b.length===0)throw new H("invalid_command","alias command must be a non-empty string");if(b.length>le)throw new H("command_too_long",`alias command exceeds ${le} bytes`)}function pe(b){if(b===void 0)return;if(typeof b!=="string")throw new H("invalid_description","alias description must be a string");if(b.length>ue)throw new H("description_too_long",`alias description exceeds ${ue} chars`)}function fe(b){if(b===void 0||b===null||b==="")return;if(typeof b!=="string")throw new H("invalid_cwd","alias cwd must be a string");if(b.length>me)throw new H("cwd_too_long",`alias cwd exceeds ${me} chars`);if(b.includes("\x00"))throw new H("invalid_cwd","alias cwd must not contain NUL bytes")}function Ze(b){if(!b)return;try{return JSON.parse(b)}catch{return}}async function se(b){let O=await b.getAllPluginState(X),w=[];for(let a of O){let p=Ze(a.value);if(p)w.push(p)}return w.sort((a,p)=>a.name.localeCompare(p.name)),w}async function z(b,O){return(await se(b)).find((a)=>a.name===O)}function de(b){if(b===void 0||b===null)return null;let O=b.trim();return O===""?null:O}async function he(b,O){if(Qe(O.name),ge(O.command),pe(O.description),fe(O.cwd),await z(b,O.name))throw new Q(O.name);let a=new Date().toISOString(),p={id:crypto.randomUUID(),name:O.name,command:O.command,description:O.description,cwd:de(O.cwd),profile:R(),createdAt:a,updatedAt:a};return await b.setPluginState(X,p.id,JSON.stringify(p)),p}async function ye(b,O,w){let a=await z(b,O);if(!a)throw new W(O);if(w.command!==void 0)ge(w.command);if(w.description!==void 0)pe(w.description);if(w.cwd!==void 0)fe(w.cwd);let p={...a,command:w.command??a.command,description:w.description!==void 0?w.description:a.description,cwd:w.cwd!==void 0?de(w.cwd):a.cwd,updatedAt:new Date().toISOString()};return await b.setPluginState(X,p.id,JSON.stringify(p)),p}async function ve(b,O){let w=await z(b,O);if(!w)throw new W(O);await b.deletePluginState(X,w.id)}function Z(){let b=B()??e();return{dir:b.dataDir,scope:b.name}}function be(b){let{serviceRegistry:O,db:w}=b;return new E().get("/api-key",({request:a,set:p})=>{if(Ve(a))return p.status=403,{error:"Forbidden",message:"Browser requests are not permitted on /api/agent/api-key"};let t=L(Object.fromEntries(a.headers.entries()));if(!V(t))return p.status=401,{error:"Unauthorized",message:"Invalid or missing API key"};return{apiKey:K()}}).post("/reset-key",async({body:a,set:p})=>{let t=a.apiKey;if(!t||typeof t!=="string")return p.status=400,{error:"Missing required field: apiKey"};try{return await vi(t),await e().keyVault.bindApiKey(t),e().logger.info("auth","Adopted backend-rotated agent API key via /reset-key"),{success:!0}}catch(h){return p.status=400,{error:"reset-key failed",message:h instanceof Error?h.message:String(h)}}},{body:r.Object({apiKey:r.String()})}).get("/audit",({query:a})=>{let p=a,t=p.limit?Math.min(5000,Math.max(1,Number.parseInt(p.limit,10)||100)):100,h=e().audit.listEvents({since:p.since,limit:t,event:p.event});return{events:h,count:h.length}},{query:r.Object({since:r.Optional(r.String()),limit:r.Optional(r.String()),event:r.Optional(r.String())})}).get("/setup/check",()=>{let a=ke();return{ready:a.filter((t)=>t.required).every((t)=>t.installed),dependencies:a}}).post("/setup/install",async({request:a,server:p,set:t})=>{let h=await Me(a,"VIBECONTROLS_ALLOW_REMOTE_SETUP_INSTALL",p);if(h)return t.status=403,{error:"Forbidden",message:h};return await ct()}).get("/url",async()=>{let a=O.getProvider("tunnel"),p=a&&a.getActiveTunnelUrl?await a.getActiveTunnelUrl():null,t=`http://localhost:${process.env.PORT||3005}`;return{url:p||t,tunnelUrl:p,localUrl:t,source:p?"tunnel":"local"}}).get("/lifecycle/state",()=>({state:O.getService("agent","lifecycle")?.getState()??"running"})).post("/lifecycle/stop",async({set:a})=>{let p=O.getService("agent","lifecycle");if(!p)return a.status=500,{error:"Lifecycle manager not initialized"};return await p.stop(),{state:"stopped"}}).post("/lifecycle/start",async({set:a})=>{let p=O.getService("agent","lifecycle");if(!p)return a.status=500,{error:"Lifecycle manager not initialized"};return await p.start(),{state:"running"}}).post("/lifecycle/kill",async({set:a})=>{let p=O.getService("agent","lifecycle");if(!p)return a.status=500,{error:"Lifecycle manager not initialized"};return setTimeout(()=>p.kill(),100),{state:"killing"}}).post("/log-level",async({body:a,request:p,server:t,set:h})=>{let P=await Me(p,"VIBECONTROLS_ALLOW_REMOTE_LOG_LEVEL",t);if(P)return h.status=403,{error:"Forbidden",message:P};let C=String(a.level??"").toLowerCase();if(!["debug","info","warn","error"].includes(C))return h.status=400,{error:"Invalid level",message:"level must be debug | info | warn | error"};return e().logger.setLevel(C),e().logger.info("agent",`Log level set to ${C} via API`),{ok:!0,level:C}},{body:r.Object({level:r.String()})}).post("/reset",async({body:a,request:p,server:t,set:h})=>{if(!a.confirm)return h.status=400,{error:"Reset confirmation required",message:"Send { confirm: true } to reset local agent state."};let P=await Me(p,"VIBECONTROLS_ALLOW_REMOTE_RESET",t);if(P)return h.status=403,{error:"Forbidden",message:P};let C=O.getService("agent","lifecycle");try{if(C)await C.prepareForReset()}catch(Y){e().logger.warn("agent","prepareForReset failed during reset \u2014 proceeding to wipe anyway",{error:String(Y)})}try{T.configure({globalGatewayUrl:"",workspaceGatewayUrl:void 0,clientId:"",clientSecret:"",workspaceId:void 0})}catch{}await w.close();let{removed:x,agentDir:D}=ae();e().logger.info("agent","Reset wiped local agent state",{agentDir:D,removed:x});let j=new Uint8Array(32);crypto.getRandomValues(j);let J=`vcak_${Buffer.from(j).toString("base64url")}`;return M({"static-api-key":J},Z()),e().setBootState("awaiting-config"),h.status=200,{success:!0,state:"awaiting-config",...Pe(p,t)||process.env.VIBECONTROLS_RETURN_RESET_API_KEY==="1"?{newApiKey:J}:{},agentDir:D,removed:x}},{body:r.Object({confirm:r.Boolean()})}).post("/sessions/:sessionId/share",async({params:a,body:p,server:t,request:h,set:P})=>{if(!Pe(h,t)&&process.env.VIBECONTROLS_ALLOW_REMOTE_SESSION_SHARE!=="1")return P.status=403,{error:"Forbidden",message:"Session-share mint must come from a local request unless VIBECONTROLS_ALLOW_REMOTE_SESSION_SHARE=1."};if(!we(a.sessionId))return P.status=400,{error:"BadRequest",message:"invalid sessionId"};let C=et(p?.expiresIn)??1800000,x=crypto.randomUUID(),D=new Uint8Array(32);crypto.getRandomValues(D);let j=`vcak_${Buffer.from(D).toString("base64url")}`,J=new Date(Date.now()+C).toISOString(),oe=[...(await import("./agent-config-mg5dvtm3.js")).readAgentConfig({dir:Z().dir}).apiKeys??[],{id:x,name:`session-share:${a.sessionId}:${p?.label??"viewer"}`,key:j,scopes:["read"],expiresAt:J,createdAt:new Date().toISOString()}];(await import("./agent-config-mg5dvtm3.js")).writeAgentConfig({apiKeys:oe},Z());let Y=O.getProvider("tunnel"),De=(Y&&Y.getActiveTunnelUrl?await Y.getActiveTunnelUrl():null)??`http://localhost:${process.env.PORT||3005}`,_e=Ut({pathPrefixes:[`/terminal/${a.sessionId}`],methods:["GET"]},Math.min(600,Math.floor(C/1000))),je=`${De.replace(/\/$/,"")}/terminal/${encodeURIComponent(a.sessionId)}/#vt=${encodeURIComponent(_e.token)}`;return e().logger.info("session-share","Minted share credential",{sessionId:a.sessionId,keyId:x,expiresAt:J}),{ok:!0,keyId:x,apiKey:j,joinUrl:je,sessionId:a.sessionId,expiresAt:J}},{params:r.Object({sessionId:r.String()}),body:r.Optional(r.Object({permissions:r.Optional(r.Array(r.String())),expiresIn:r.Optional(r.String()),label:r.Optional(r.String())}))}).get("/aliases",async()=>({aliases:await se(w)})).get("/aliases/:name",async({params:a,set:p})=>{let t=await z(w,a.name);if(!t)return p.status=404,{error:"Alias not found"};return t},{params:r.Object({name:r.String()})}).post("/aliases",async({body:a,set:p})=>{try{let t=await he(w,a);return p.status=201,t}catch(t){if(t instanceof Q)return p.status=409,{error:"Alias already exists",message:t.message};if(t instanceof H)return p.status=400,{error:t.code,message:t.message};throw t}},{body:r.Object({name:r.String(),command:r.String(),description:r.Optional(r.String()),cwd:r.Optional(r.Union([r.String(),r.Null()]))})}).put("/aliases/:name",async({params:a,body:p,set:t})=>{try{return await ye(w,a.name,p)}catch(h){if(h instanceof W)return t.status=404,{error:"Alias not found"};if(h instanceof H)return t.status=400,{error:h.code,message:h.message};throw h}},{params:r.Object({name:r.String()}),body:r.Object({command:r.Optional(r.String()),description:r.Optional(r.String()),cwd:r.Optional(r.Union([r.String(),r.Null()]))})}).delete("/aliases/:name",async({params:a,set:p})=>{try{return await ve(w,a.name),p.status=204,null}catch(t){if(t instanceof W)return p.status=404,{error:"Alias not found"};throw t}},{params:r.Object({name:r.String()})}).post("/aliases/:name/execute",async({params:a,body:p,set:t})=>{let h=await z(w,a.name);if(!h)return t.status=404,{error:"Alias not found"};let P=p?.args??[],C=await Ci(h,P);e().audit.emit("agent","alias.executed",{exit_code:C.exit_code});let x=Ke("alias.executed",{exit_code:C.exit_code});if(!x.ok)e().logger.debug("alias",`telemetry validate failed: ${x.reason}`);if(C.timed_out)t.status=408;return{exit_code:C.exit_code,stdout:C.stdout,stderr:C.stderr,duration_ms:C.duration_ms,truncated:C.truncated,cwd:C.cwd}},{params:r.Object({name:r.String()}),body:r.Optional(r.Object({args:r.Optional(r.Array(r.String()))}))}).post("/sessions/share/:keyId/revoke",async({params:a,server:p,request:t,set:h})=>{if(!Pe(t,p)&&process.env.VIBECONTROLS_ALLOW_REMOTE_SESSION_SHARE!=="1")return h.status=403,{error:"Forbidden"};let P=await import("./agent-config-mg5dvtm3.js"),C=Z(),x=P.readAgentConfig({dir:C.dir}),D=(x.apiKeys??[]).length,j=(x.apiKeys??[]).filter((J)=>J.id!==a.keyId);if(j.length===D)return h.status=404,{error:"No such share key"};return P.writeAgentConfig({apiKeys:j},C),{ok:!0,revoked:a.keyId}},{params:r.Object({keyId:r.String()})})}function et(b){if(!b)return null;let O=/^(\d+)([smhdw]?)$/.exec(b.trim());if(!O)return null;let w=Number(O[1]),a=O[2]||"m";return a==="s"?w*1000:a==="m"?w*60000:a==="h"?w*3600000:a==="d"?w*86400000:w*7*86400000}var tt="http://localhost:3005";function Se(b){b.command("health").description("Check health of a VibeControls agent instance").option("-n, --name <name>","Agent instance name").option("--agent-url <url>","Agent URL",tt).option("--json","Emit JSON").option("--plain","Force plain text output").action(async function(O){try{let w={...b.opts(),...O};await y({mode:_(w),fetchData:async()=>{if(w.name){let t=await new k().checkHealth(w.name);return{mode:"named",agentUrl:f(w),name:w.name,healthy:t.healthy,details:t.details??{}}}let a=f(w);try{let p=await S(a,"/health");return{mode:"url",agentUrl:a,healthy:!0,details:p}}catch(p){return{mode:"url",agentUrl:a,healthy:!1,details:{status:"unhealthy",...p instanceof Error?{error:A(p)}:{}}}}},plain:(a)=>{if(g("Agent Health"),c(),a.mode==="named"){if(!a.healthy){s(`Agent instance ${i.bold(a.name??"")} is not responding.`);return}let p=a.details;if(n("Instance",a.name??""),n("Status",G(p.status??"healthy")),p.uptime!==void 0)n("Uptime",`${p.uptime}s`);if(p.checks){c(),o(`${d.info} Health checks:`);for(let[t,h]of Object.entries(p.checks)){let P=h.status==="healthy"?d.success:d.error;n(` ${P} ${t}`,G(h.status))}}}else{if(n("URL",a.agentUrl),n("Status",G(a.details.status??"unhealthy")),a.details.version)n("Version",a.details.version);if(a.details.uptime!==void 0)n("Uptime",`${a.details.uptime}s`);if(a.details.timestamp)n("Timestamp",a.details.timestamp);if(a.details.checks){c(),o(`${d.info} Health checks:`);for(let[p,t]of Object.entries(a.details.checks)){let h=t.status==="healthy"?d.success:d.error;n(` ${h} ${p}`,G(t.status))}}}if(c(),a.healthy)l(`${d.success} Agent is healthy.`)},interactive:async(a)=>{let p=[];if(a.mode==="named")p.push(`Instance: ${a.name??""}`);else p.push(`URL: ${a.agentUrl}`);if(p.push(`Status: ${G(a.details.status??(a.healthy?"healthy":"unhealthy"))}`),a.details.version)p.push(`Version: ${a.details.version}`);if(a.details.uptime!==void 0)p.push(`Uptime: ${a.details.uptime}s`);if(a.details.timestamp)p.push(`Time: ${a.details.timestamp}`);if(a.details.checks){p.push(""),p.push("Checks:");for(let[t,h]of Object.entries(a.details.checks))p.push(` ${t}: ${h.status}`)}await U({title:"Agent Health",body:p.join(`
|
|
4
4
|
`),footer:"press q to exit"})},json:(a)=>({mode:a.mode,agentUrl:a.agentUrl,name:a.name??null,healthy:a.healthy,details:a.details})})}catch(w){s(`Health check failed: ${A(w)}`)}})}import{platform as nt,arch as rt,release as it,hostname as st,cpus as ot,totalmem as at}from"os";var lt="http://localhost:3005";function Ae(b){b.command("info").description("Show local and remote VibeControls agent information").option("--agent-url <url>","Agent URL",lt).option("--json","Emit JSON").option("--plain","Force plain text output").action(async function(O){try{let w={...b.opts(),...O},a=f(w),p=encodeURIComponent(m(w));await y({mode:_(w),fetchData:async()=>{let t={hostname:st(),platform:nt(),arch:rt(),release:it(),cpus:ot().length,totalMemory:at(),nodeVersion:process.version,bunVersion:process.versions.bun};try{let h=await S(a,`/api/profiles/${p}/agent/version`);return{local:t,agentUrl:a,remote:h}}catch(h){return{local:t,agentUrl:a,remote:null,remoteError:h instanceof Error?A(h):String(h)}}},plain:(t)=>{if(g("VibeControls Agent Info"),c(),o(`${d.info} Local System`),n("Hostname",t.local.hostname),n("Platform",`${t.local.platform} ${t.local.arch}`),n("OS Release",t.local.release),n("CPUs",String(t.local.cpus)),n("Total Memory",Ge(t.local.totalMemory)),n("Node.js",t.local.nodeVersion),t.local.bunVersion)n("Bun",t.local.bunVersion);if(c(),o(`${d.info} Remote Agent`),n("URL",t.agentUrl),t.remote){if(n("Version",i.bold(t.remote.version)),t.remote.build)n("Build",t.remote.build);if(t.remote.commit)n("Commit",t.remote.commit);if(t.remote.nodeVersion)n("Node.js (remote)",t.remote.nodeVersion);if(t.remote.bunVersion)n("Bun (remote)",t.remote.bunVersion)}else n("Status",i.dim("not reachable"));c()},interactive:async(t)=>{let h=[];if(h.push("Local System"),h.push(` Hostname: ${t.local.hostname}`),h.push(` Platform: ${t.local.platform} ${t.local.arch}`),h.push(` OS Release: ${t.local.release}`),h.push(` CPUs: ${t.local.cpus}`),h.push(` Total Memory: ${Ge(t.local.totalMemory)}`),h.push(` Node.js: ${t.local.nodeVersion}`),t.local.bunVersion)h.push(` Bun: ${t.local.bunVersion}`);if(h.push(""),h.push("Remote Agent"),h.push(` URL: ${t.agentUrl}`),t.remote){if(h.push(` Version: ${t.remote.version}`),t.remote.build)h.push(` Build: ${t.remote.build}`);if(t.remote.commit)h.push(` Commit: ${t.remote.commit}`);if(t.remote.nodeVersion)h.push(` Node.js: ${t.remote.nodeVersion} (remote)`);if(t.remote.bunVersion)h.push(` Bun: ${t.remote.bunVersion} (remote)`)}else h.push(" Status: not reachable");await U({title:"VibeControls Agent Info",body:h.join(`
|
|
5
5
|
`),footer:"press q to exit"})},json:(t)=>({local:t.local,agentUrl:t.agentUrl,remote:t.remote,remoteError:t.remoteError??null})})}catch(w){s(`Failed to get info: ${A(w)}`)}})}var ut="http://localhost:3005";function $e(b){b.command("system").description("Show system information for a running VibeControls agent").option("--agent-url <url>","Agent URL",ut).option("--json","Emit JSON").option("--plain","Force plain text output").action(async function(O){try{let w={...b.opts(),...O},a=f(w),p=encodeURIComponent(m(w));await y({mode:_(w),fetchData:()=>S(a,`/api/profiles/${p}/agent/system`),plain:(t)=>{if(g("Agent System Information"),c(),o(`${d.info} Agent`),n("Version",i.bold(t.agentVersion)),t.bunVersion)n("Bun",t.bunVersion);if(t.environment)n("Environment",t.environment);n("Uptime",Jr(t.uptime)),c(),o(`${d.info} Platform`),n("OS",`${t.platform} ${t.arch}`),n("Hostname",t.hostname),n("Release",t.release),c(),o(`${d.info} Resources`),n("CPUs",String(t.cpus)),n("Total Memory",Ge(t.totalMemory)),n("Free Memory",Ge(t.freeMemory)),c(),o(`${d.info} Paths`),n("Home",t.homeDir),n("CWD",t.cwd),c()},interactive:async(t)=>{let h=["Agent",` Version: ${t.agentVersion}`,...t.bunVersion?[` Bun: ${t.bunVersion}`]:[],...t.environment?[` Environment: ${t.environment}`]:[],` Uptime: ${Jr(t.uptime)}`,"","Platform",` OS: ${t.platform} ${t.arch}`,` Hostname: ${t.hostname}`,` Release: ${t.release}`,"","Resources",` CPUs: ${t.cpus}`,` Total Mem: ${Ge(t.totalMemory)}`,` Free Mem: ${Ge(t.freeMemory)}`,"","Paths",` Home: ${t.homeDir}`,` CWD: ${t.cwd}`];await U({title:"Agent System Information",body:h.join(`
|
|
6
|
-
`),footer:"press q to exit"})}})}catch(w){s(`Failed to get system info: ${A(w)}`)}})}var mt="http://localhost:3005";async function Re(b){try{let O=await fetch(`${b}/health/ready`);if(O.status===200||O.status===503)return await O.json();return{healthy:!1,status:O.status}}catch{return{healthy:!1,error:"unreachable"}}}async function
|
|
7
|
-
`)}async function ft(b,O){let w={agentUrl:O},a=b.jsonKey??b.title.toLowerCase(),p;try{p=await b.render(w)}catch(h){p=i.red(`error (${h.message})`)}let t=null;if(b.json)try{t=await b.json(w)}catch{t=null}return{title:b.title,jsonKey:a,text:p,json:t}}async function
|
|
6
|
+
`),footer:"press q to exit"})}})}catch(w){s(`Failed to get system info: ${A(w)}`)}})}var mt="http://localhost:3005";async function Re(b){try{let O=await fetch(`${b}/health/ready`);if(O.status===200||O.status===503)return await O.json();return{healthy:!1,status:O.status}}catch{return{healthy:!1,error:"unreachable"}}}async function Ie(b,O){try{let w=await Fe(b);if(!w)return null;let a=await fetch(`${b}/api/profiles/${O}/agent/api-key`,{headers:{"x-agent-api-key":w}});if(!a.ok)return w;return(await a.json()).apiKey??w}catch{return null}}async function gt(b,O){try{return await S(b,`/api/profiles/${O}/plugins`)}catch{return null}}function ee(b){let O=b??{};if(O.error==="unreachable")return i.red("unreachable");if(typeof O.status==="number"&&O.status>=400)return i.red(`http ${O.status}`);let w=typeof O.status==="string"?O.status:"",a=typeof O.bootState==="string"?O.bootState:"";if(w==="ok"&&a==="ready")return i.green("ready");if(a==="awaiting-config")return i.yellow("awaiting-config");if(a==="initializing")return i.yellow("initializing");if(a==="degraded"||w==="degraded")return i.red(`degraded${a?` (${a})`:""}`);if(O.healthy===!1)return i.red("unhealthy");return i.green("healthy")}function pt(b){let w=(b??{}).lastFinalizeError;if(!w||typeof w!=="object")return null;let a=w;if(typeof a.message!=="string"||typeof a.at!=="string")return null;return{message:a.message,at:a.at,attempt:typeof a.attempt==="number"?a.attempt:void 0}}function Oe(b){let O=b??{},w=typeof O.bootState==="string"?O.bootState:"";if(w!=="awaiting-config"&&w!=="degraded")return null;let a=[],p=pt(b);if(p)if(a.push(`${i.gray("\xB7")} Last error: ${i.red(p.message)}`),p.attempt!==void 0)a.push(`${i.gray("\xB7")} Background retry: attempt ${p.attempt}`);else a.push(`${i.gray("\xB7")} Last seen: ${p.at}`);if(w==="awaiting-config")a.push(`${i.gray("\xB7")} Force retry now: ${i.bold("vibe retry-config")}`);return a.push(`${i.gray("\xB7")} Full trace: ${i.bold("vibe logs --since 10m")}`),a.join(`
|
|
7
|
+
`)}async function ft(b,O){let w={agentUrl:O},a=b.jsonKey??b.title.toLowerCase(),p;try{p=await b.render(w)}catch(h){p=i.red(`error (${h.message})`)}let t=null;if(b.json)try{t=await b.json(w)}catch{t=null}return{title:b.title,jsonKey:a,text:p,json:t}}async function Ue(b){let w=Dt().getStatusSections();return Promise.all(w.map((a)=>ft(a,b)))}function Ee(b){b.command("status").description("Show comprehensive status of VibeControls agent instance(s)").option("-n, --name <name>","Agent instance name").option("--agent-url <url>","Agent URL",mt).option("--profile <name>","Target a specific profile by name").option("--json","Emit JSON").option("--plain","Force plain text output").action(async function(O){try{let w={...b.opts(),...O},a=new k;await y({mode:_(w),fetchData:async()=>{if(w.name){let P=await a.getStatus(w.name);if(!P)return{kind:"instance",agentUrl:f(w),instance:null,contributed:[]};let C=P.status==="running"&&P.port?`http://localhost:${P.port}`:f(w);if(P.status!=="running")return{kind:"instance",agentUrl:C,instance:P,contributed:[]};let x=encodeURIComponent(m({profile:P.name})),[D,j,J,te]=await Promise.all([Re(C),Ie(C,x),gt(C,x),Ue(C)]);return{kind:"instance",agentUrl:C,instance:P,health:D,apiKey:j,plugins:J,contributed:te}}let p=await a.listInstances(),t=p.filter((P)=>P.status==="running"),h=await Promise.all(t.map(async(P)=>{let C=`http://localhost:${P.port}`,x=encodeURIComponent(m({profile:P.name})),[D,j,J]=await Promise.all([Re(C),Ie(C,x),Ue(C)]);return{name:P.name,agentUrl:C,health:D,apiKey:j,contributed:J}}));return{kind:"overview",instances:p,perRunning:h}},plain:(p)=>{if(p.kind==="instance"){if(!p.instance){s(`Agent instance ${i.bold(w.name??"")} not found.`);return}let h=p.instance;if(g(`Agent Status: ${h.name}`),n("Name",h.name),n("Status",G(h.status)),n("PID",h.pid?String(h.pid):i.dim("n/a")),n("Port",h.port?String(h.port):i.dim("n/a")),n("Host",h.config?.host||i.dim("n/a")),n("Database",h.config?.dbPath||i.dim("n/a")),h.startTime)n("Started",v(h.startTime));if(h.status==="running"){c(),n("Health",ee(p.health));let P=Oe(p.health);if(P)c(),console.log(P),c();let C=p.health?.uptime;if(C)n("Uptime",String(C));if(n("API Key",p.apiKey??i.dim("(unavailable)")),p.plugins){let x=p.plugins.plugins??[],D=x.filter((j)=>j.isCore).length;n("Plugins",`${x.length} total (${D} core, ${x.length-D} external)`)}else n("Plugins",i.dim("(unable to fetch)"));for(let x of p.contributed){if(x.text===null)continue;n(x.title,x.text)}}c();return}if(g("Agent Instances"),c(),!p.instances||p.instances.length===0){o(`${d.info} No agent instances found.`),o(`Run ${i.bold("vibe start")} to start an agent.`);return}let t=p.instances.map((h)=>({Name:h.name,Status:G(h.status),PID:h.pid||"-",Port:h.port||"-",Started:h.startTime?v(h.startTime):"-"}));F(t),c();for(let h of p.perRunning){c(),g(`Quick Status: ${h.name}`),n("Health",ee(h.health));let P=Oe(h.health);if(P)c(),console.log(P),c();n("API Key",h.apiKey??i.dim("(unavailable)"));for(let C of h.contributed){if(C.text===null)continue;n(C.title,C.text)}}c(),o(`${d.info} ${p.instances.length} instance(s) found. Use ${i.bold("vibe status -n <name>")} for full details.`)},interactive:async(p)=>{let t=[];if(p.kind==="instance"){if(!p.instance)t.push(`Agent instance "${w.name??""}" not found.`);else{let h=p.instance;if(t.push(`Name: ${h.name}`),t.push(`Status: ${G(h.status)}`),t.push(`PID: ${h.pid??"n/a"}`),t.push(`Port: ${h.port??"n/a"}`),t.push(`Host: ${h.config?.host??"n/a"}`),t.push(`Database: ${h.config?.dbPath??"n/a"}`),h.startTime)t.push(`Started: ${v(h.startTime)}`);if(h.status==="running"){if(t.push(""),t.push(`Health: ${ee(p.health)}`),t.push(`API Key: ${p.apiKey??"(unavailable)"}`),p.plugins){let P=p.plugins.plugins??[],C=P.filter((x)=>x.isCore).length;t.push(`Plugins: ${P.length} (${C} core, ${P.length-C} external)`)}for(let P of p.contributed){if(P.text===null)continue;t.push(`${P.title.padEnd(9)} ${P.text}`)}}}await U({title:`vibe status${w.name?` \u2014 ${w.name}`:""}`,body:t.join(`
|
|
8
8
|
`),footer:"press q to exit"});return}if(!p.instances||p.instances.length===0)t.push("No agent instances found."),t.push("Run `vibe start` to start an agent.");else for(let h of p.instances){t.push(`${i.bold(h.name)} ${G(h.status)}`),t.push(` PID: ${h.pid??"-"}`),t.push(` Port: ${h.port??"-"}`),t.push(` Started: ${h.startTime?v(h.startTime):"-"}`);let P=p.perRunning.find((C)=>C.name===h.name);if(P){t.push(` Health: ${ee(P.health)}`);for(let C of P.contributed){if(C.text===null)continue;t.push(` ${C.title.padEnd(9)} ${C.text}`)}}t.push("")}await U({title:`vibe status \u2014 ${p.instances.length} instance(s)`,body:t.join(`
|
|
9
|
-
`),footer:"press q to exit"})},json:(p)=>{let t=(h)=>Object.fromEntries(h.map((P)=>[P.jsonKey,P.json]));if(p.kind==="instance"){if(!p.instance)return{instance:null};let h={instance:{name:p.instance.name,status:p.instance.status,pid:p.instance.pid,port:p.instance.port,host:p.instance.config?.host,dbPath:p.instance.config?.dbPath,startTime:p.instance.startTime}};if(p.instance.status==="running")h.health=p.health??null,h.plugins=p.plugins??null,Object.assign(h,t(p.contributed));return h}return{instances:p.instances.map((h)=>({name:h.name,status:h.status,pid:h.pid,port:h.port,startTime:h.startTime})),perRunning:p.perRunning.map((h)=>({name:h.name,health:h.health??null,...t(h.contributed)}))}}})}catch(w){let a=w instanceof Error?A(w):String(w);s(`Failed to get status: ${a}`)}})}var dt="http://localhost:3005";function
|
|
10
|
-
`)})},json:(t)=>
|
|
11
|
-
`)})},json:(h)=>
|
|
9
|
+
`),footer:"press q to exit"})},json:(p)=>{let t=(h)=>Object.fromEntries(h.map((P)=>[P.jsonKey,P.json]));if(p.kind==="instance"){if(!p.instance)return{instance:null};let h={instance:{name:p.instance.name,status:p.instance.status,pid:p.instance.pid,port:p.instance.port,host:p.instance.config?.host,dbPath:p.instance.config?.dbPath,startTime:p.instance.startTime}};if(p.instance.status==="running")h.health=p.health??null,h.plugins=p.plugins??null,Object.assign(h,t(p.contributed));return h}return{instances:p.instances.map((h)=>({name:h.name,status:h.status,pid:h.pid,port:h.port,startTime:h.startTime})),perRunning:p.perRunning.map((h)=>({name:h.name,health:h.health??null,...t(h.contributed)}))}}})}catch(w){let a=w instanceof Error?A(w):String(w);s(`Failed to get status: ${a}`)}})}var dt="http://localhost:3005";function Ce(b){b.command("url").description("Show the active URL for a running VibeControls agent").option("--agent-url <url>","Agent URL",dt).option("--json","Emit JSON").option("--plain","Force plain text output").action(async(O)=>{try{let w={...b.opts(),...O},a=f(O),p=encodeURIComponent(m(w));await y({mode:_(w),fetchData:()=>S(a,`/api/profiles/${p}/agent/url`),plain:(t)=>{if(g("Agent URL"),c(),n("Active URL",i.bold(t.url)),n("Local URL",t.localUrl),t.tunnelUrl)n("Tunnel URL",i.cyan(t.tunnelUrl));if(n("Mode",t.isTunnel?`${d.running} Tunnel active`:`${d.info} Local only`),c(),t.isTunnel)o(`${d.info} Agent is accessible via tunnel at ${i.bold(t.tunnelUrl)}`);else o(`${d.info} Agent is running locally at ${i.bold(t.localUrl)}`)},interactive:async(t)=>{let h=[` Active URL: ${t.url}`,` Local URL: ${t.localUrl}`,` Tunnel URL: ${t.tunnelUrl??"-"}`,` Mode: ${t.isTunnel?"Tunnel active":"Local only"}`];await U({title:"Agent URL",body:h.join(`
|
|
10
|
+
`)})},json:(t)=>N(t)})}catch(w){s(`Failed to get URL: ${w.message}`)}})}var xe="http://localhost:3005";function Le(b){let O=b.command("gateway-auth").description("Manage gateway authentication for VibeControls agent");O.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",xe).option("--json","Emit JSON result").action(async(w)=>{try{let a={...b.opts(),...w},p=f(w),t=encodeURIComponent(m(a)),h=await q(p,`/api/profiles/${t}/agent/gateway-auth`,{globalGatewayUrl:w.globalUrl,workspaceGatewayUrl:w.workspaceUrl,clientId:w.clientId,clientSecret:w.clientSecret,workspaceId:w.workspaceId,agentRecordId:w.agentRecordId});if(u(a,{ok:!!h.success,message:h.message??null,globalGatewayUrl:w.globalUrl,workspaceGatewayUrl:w.workspaceUrl,clientId:w.clientId,workspaceId:w.workspaceId??null,agentRecordId:w.agentRecordId??null}))return;if(g("Configure Gateway Authentication"),c(),o(`${d.info} Sending gateway auth configuration...`),c(),h.success){if(l(`${d.success} Gateway authentication configured successfully.`),c(),n("Global URL",w.globalUrl),n("Workspace URL",w.workspaceUrl),n("Client ID",w.clientId),n("Client Secret",i.dim("********")),w.workspaceId)n("Workspace ID",w.workspaceId);if(w.agentRecordId)n("Agent Record ID",w.agentRecordId)}else s(h.message||"Failed to configure gateway authentication.");c()}catch(a){s(`Failed to configure gateway auth: ${a instanceof Error?A(a):String(a)}`)}}),O.command("status").description("Check gateway authentication status").option("--agent-url <url>","Agent URL",xe).option("--json","Emit JSON").option("--plain","Force plain text output").action(async(w)=>{try{let a={...b.opts(),...w},p=f(w),t=encodeURIComponent(m(a));await y({mode:_(a),fetchData:()=>S(p,`/api/profiles/${t}/agent/gateway-auth`),plain:(h)=>{if(g("Gateway Authentication Status"),c(),n("Configured",h.configured?`${d.success} ${i.green("Yes")}`:`${d.error} ${i.red("No")}`),h.configured){if(n("Global URL",h.config?.globalGatewayUrl||i.dim("n/a")),n("Workspace URL",h.config?.workspaceGatewayUrl||i.dim("n/a")),n("Client ID",h.config?.clientId||i.dim("n/a")),h.config?.workspaceId)n("Workspace ID",h.config.workspaceId)}else c(),o(`${d.info} Run ${i.bold("vibe gateway-auth configure")} to set up gateway authentication.`);c()},interactive:async(h)=>{let P=h.configured?[" Configured: yes",` Global URL: ${h.config?.globalGatewayUrl??"n/a"}`,` Workspace URL: ${h.config?.workspaceGatewayUrl??"n/a"}`,` Client ID: ${h.config?.clientId??"n/a"}`,` Workspace ID: ${h.config?.workspaceId??"-"}`]:[" Configured: no",""," Run `vibe gateway-auth configure` to set up."];await U({title:"Gateway Authentication Status",body:P.join(`
|
|
11
|
+
`)})},json:(h)=>N(h)})}catch(a){s(`Failed to get gateway auth status: ${a instanceof Error?A(a):String(a)}`)}})}function Ne(b,O){Se(b),Ae(b),Zr(b),$e(b),Ee(b),Ce(b),Le(b)}var Te="agent";function Or(b){let O=null,w=re({name:Te,onShutdown:()=>{pi(),fi()}});return{name:Te,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:(a)=>(O=a.db,be(a)),onCliSetup:async(a,p)=>{Ne(a,p)},onServerReady:async(a,p)=>{if(O){let t=a,h=(typeof t.decorator?.apiKey==="string"?t.decorator.apiKey:void 0)??(typeof t.store?.apiKey==="string"?t.store.apiKey:void 0)??"unknown",P=new ie(p.logger,"agent-plugin");mi(O,p.serviceRegistry,h).catch((C)=>{P.warn(`Auto-report background task failed: ${C}`)})}},onServerStop:w.onServerStop}}export{Or as createPlugin};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{R}from"./index-
|
|
2
|
+
import{R}from"./index-nxpw3anc.js";import{J,w,M,X}from"./index-30qr1qm3.js";import{i,s,A,l,o,g,n,c,F}from"./index-j9cg16we.js";import{_,y,u}from"./index-v77bb0rm.js";async function Xi(){if(process.env.AGENT_API_KEY)return process.env.AGENT_API_KEY;let a="default";try{a=R()}catch{}let d=await J(`${a}:static-api-key`);if(d)return d;return w()["static-api-key"]??null}var S=["read","mutate","plugin:install","plugin:remove","update","admin"];function K(a){if(a.length<=12)return"[redacted]";return`${a.slice(0,8)}...${a.slice(-4)}`}function I(){let a=new Uint8Array(32);return crypto.getRandomValues(a),`vcak_${Buffer.from(a).toString("base64url")}`}function N(){return crypto.randomUUID()}function b(a){if(!a)return;let d=/^(\d+)([smhdw]?)$/.exec(a.trim());if(!d)throw Error(`Invalid --expires-in: ${a} (use 30s, 12h, 7d, 4w; bare digits = days)`);let e=Number(d[1]),f=d[2]||"d",t=f==="s"?e*1000:f==="m"?e*60000:f==="h"?e*3600000:f==="w"?e*7*86400000:e*86400000;return new Date(Date.now()+t).toISOString()}function E(a){if(!a)return["read"];let d=a.split(",").map((e)=>e.trim()).filter(Boolean);for(let e of d)if(!S.includes(e))throw Error(`Unknown scope: ${e}. Allowed: ${S.join(", ")}`);return d}function Zr(a){let d=a.command("key").description("Show or manage VibeControls agent API keys");d.command("show",{isDefault:!0}).description("Show the default agent API key").option("--show-secret","Print the full API key",!1).option("--json","Emit JSON").option("--plain","Force plain text output").action(async function(e){let f={...a.opts(),...e};try{await y({mode:_(f),fetchData:async()=>({apiKey:await Xi()??null}),plain:(t)=>{if(g("Agent API Key"),c(),!t.apiKey){s("No API key found in AGENT_API_KEY or local agent config.");return}if(n("API Key",i.bold(e.showSecret?t.apiKey:K(t.apiKey))),!e.showSecret)n("Full key",i.dim("hidden; rerun with --show-secret"));c()},json:(t)=>({apiKey:t.apiKey?e.showSecret?t.apiKey:"[redacted]":null})})}catch(t){s(`Failed to get API key: ${A(t)}`)}}),d.command("list").description("List all scoped API keys (default + minted)").option("--json","Emit JSON").option("--plain","Force plain text output").option("--show-secret","Include full key values in JSON output",!1).action(async function(e){let f={...a.opts(),...e};try{await y({mode:_(f),fetchData:()=>X(),plain:(t)=>{let r=[],m=t["static-api-key"];if(m)r.push({ID:"default",Name:"default",Scopes:"admin",Expires:"never",Key:K(m)});for(let p of t.apiKeys??[])r.push({ID:p.id??"(legacy)",Name:p.name,Scopes:p.scopes.join(","),Expires:p.expiresAt??"never",Key:K(p.key)});if(r.length===0){o("No keys configured.");return}g("Agent API Keys"),F(r)},json:(t)=>{let r=[],m=t["static-api-key"];if(m)r.push({id:"default",name:"default",scopes:["admin"],expiresAt:null,key:e.showSecret?m:"[redacted]"});for(let p of t.apiKeys??[])r.push({id:p.id??"(legacy)",name:p.name,scopes:p.scopes,expiresAt:p.expiresAt??null,key:e.showSecret?p.key:"[redacted]"});return r}})}catch(t){s(A(t))}}),d.command("add").description("Mint a new scoped API key").requiredOption("--name <name>","Display name (logs only)").option("--scope <scope>",`Comma-separated scope list (default: read). Allowed: ${S.join(",")}`,"read").option("--expires-in <duration>","TTL (e.g. 7d, 12h, 30m). Omit for no expiry.").option("--not-before <iso>","ISO timestamp before which the key is rejected.").option("--json","Emit JSON").action(function(e){let f={...a.opts(),...e};try{let t=E(e.scope),r=b(e.expiresIn),m=w(),p=N(),h=I(),k={id:p,name:e.name,key:h,scopes:t,expiresAt:r,notBefore:e.notBefore,createdAt:new Date().toISOString()},x=[...m.apiKeys??[],k];if(M({apiKeys:x}),u(f,{ok:!0,id:p,name:e.name,scopes:t,expiresAt:r??null,key:h}))return;if(l(`Minted key ${p}`),n("Name",e.name),n("Scopes",t.join(",")),r)n("Expires",r);if(e.notBefore)n("Not before",e.notBefore);c(),n("Key (save now)",i.bold(h))}catch(t){if(f.json){u(f,{ok:!1,error:A(t)});return}s(A(t))}}),d.command("revoke <id>").description("Revoke a scoped key by ID").option("--json","Emit JSON").action(function(e,f){let t={...a.opts(),...f};try{let r=w(),m=(r.apiKeys??[]).length,p=(r.apiKeys??[]).filter((h)=>h.id!==e);if(p.length===m){if(t.json){u(t,{ok:!1,error:`No key with id ${e}`});return}s(`No key with id ${e}`);return}if(M({apiKeys:p}),u(t,{ok:!0,id:e}))return;l(`Revoked key ${e}`)}catch(r){if(t.json){u(t,{ok:!1,error:A(r)});return}s(A(r))}}),d.command("rotate <id>").description("Rotate the secret of an existing scoped key (preserves scopes/expiry)").option("--json","Emit JSON").action(function(e,f){let t={...a.opts(),...f};try{let r=w();if(!(r.apiKeys??[]).find((k)=>k.id===e)){if(t.json){u(t,{ok:!1,error:`No key with id ${e}`});return}s(`No key with id ${e}`);return}let p=I(),h=(r.apiKeys??[]).map((k)=>k.id===e?{...k,key:p}:k);if(M({apiKeys:h}),u(t,{ok:!0,id:e,key:p}))return;l(`Rotated key ${e}`),n("New key (save now)",i.bold(p))}catch(r){if(t.json){u(t,{ok:!1,error:A(r)});return}s(A(r))}})}
|
|
3
3
|
export{Xi,Zr};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{T,e}from"./index-
|
|
2
|
+
import{T,e}from"./index-nxpw3anc.js";var A="bridge-client",I=2000,O=30000,C=30000,M=6,u={commandPattern:/^[a-z][a-z0-9]*(\.[a-z][a-z0-9_-]*){0,4}$/,idPattern:/^[A-Za-z0-9-]{1,64}$/,maxTimeoutMs:120000,defaultTimeoutMs:30000,maxConcurrent:16,abandonGraceMs:30000,maxResponseBytes:8388608,errorCodePattern:/^[A-Z][A-Z0-9_]{0,63}$/};class He extends Error{code;constructor(t,r){super(r);this.code=t;this.name="BridgeCommandError"}}var n={ws:null,pingTimer:null,reconnectTimer:null,reconnectAttempt:0,connected:!1,stopped:!1,agentId:null,profile:"default",pendingEvents:[],handlers:new Map,running:new Map,clockOffsetMs:null};function s(t,r,o){e().logger[t](A,r,o)}function N(t){try{let r=new URL(t);r.protocol=r.protocol==="https:"?"wss:":"ws:",r.pathname="/agent-bridge",r.search="",r.hash="";let o=process.env.VIBE_BRIDGE_URL;if(o)return o;return r.toString()}catch{return process.env.VIBE_BRIDGE_URL??""}}async function _(){if(n.stopped||n.ws)return;if(!T.isConfigured()){s("debug","Gateway client not configured yet; deferring bridge connect");return}if(!n.agentId){s("debug","No agentId set yet; deferring bridge connect");return}let t,r,o;try{let i=await T.getAccessToken();t=i.token,r=i.workspaceGatewayUrl,o=i.workspaceId}catch(i){s("warn","Failed to fetch access token for bridge",{error:i instanceof Error?i.message:String(i)}),p();return}if(!t||!r){p();return}let d=N(r);if(!d){s("warn","Cannot resolve bridge URL from workspaceGatewayUrl",{workspaceGatewayUrl:r}),p();return}s("info","Connecting to agent-bridge",{url:d,agentId:n.agentId});let c;try{c=new WebSocket(d,{headers:{Authorization:`Bearer ${t}`,...o?{"x-workspace-id":o}:{}}})}catch(i){s("warn","Bridge connect threw",{error:i instanceof Error?i.message:String(i)}),p();return}n.ws=c,c.addEventListener("open",()=>{n.reconnectAttempt=0,s("info","Bridge socket open \u2014 sending hello"),h({type:"hello",agentId:n.agentId,profile:n.profile,version:process.env.npm_package_version??"unknown"})}),c.addEventListener("message",(i)=>{let m=typeof i.data==="string"?i.data:i.data instanceof Blob?"":new TextDecoder().decode(i.data);if(!m)return;let a;try{a=JSON.parse(m)}catch{return}if(a.type==="welcome")n.connected=!0,n.clockOffsetMs=typeof a.serverTime==="number"&&Number.isFinite(a.serverTime)?a.serverTime-Date.now():null,s("info","Bridge welcome received \u2014 connection ready",{workspaceId:typeof a.workspaceId==="string"?a.workspaceId:void 0}),G(),U();else if(a.type==="request")P(c,a);else if(a.type==="error")s("warn","Bridge error frame",{error:a})}),c.addEventListener("close",(i)=>{if(s("info","Bridge socket closed",{code:i.code,reason:i.reason}),S(),!n.stopped)p()}),c.addEventListener("error",(i)=>{s("warn","Bridge socket error",{message:i.message})})}function k(t,r){if(t.readyState!==1)return;let o;try{o=JSON.stringify(r)}catch{o=JSON.stringify({type:"response",id:r.id,ok:!1,error:{code:"AGENT_ERROR",message:"result is not serializable"}})}if(Buffer.byteLength(o,"utf8")>u.maxResponseBytes)o=JSON.stringify({type:"response",id:r.id,ok:!1,error:{code:"RESPONSE_TOO_LARGE",message:"result is too large"}});try{t.send(o)}catch(d){s("debug","Bridge response send failed",{error:d instanceof Error?d.message:String(d)})}}function x(t){let r=t instanceof He&&u.errorCodePattern.test(t.code)?t.code:"AGENT_ERROR",o=t instanceof Error?t.message:String(t);return{code:r,message:o.slice(0,500)}}async function P(t,r){let o=r.id;if(typeof o!=="string"||!u.idPattern.test(o)){s("warn","Bridge request without a valid id; ignored");return}let d=(l,f)=>k(t,{type:"response",id:o,ok:!1,error:{code:l,message:f}}),c=r.command;if(typeof c!=="string"||!u.commandPattern.test(c)){d("BAD_REQUEST","invalid command name");return}let i=n.handlers.get(c);if(!i){d("UNKNOWN_COMMAND",`this agent does not run '${c}'`);return}if(n.running.has(o)){d("BAD_REQUEST","duplicate request id");return}if(n.running.size>=u.maxConcurrent){d("TOO_MANY_REQUESTS","too many commands running on this agent");return}let m=typeof r.timeoutMs==="number"&&Number.isFinite(r.timeoutMs)?r.timeoutMs:u.defaultTimeoutMs,a=Math.min(Math.max(m,1),u.maxTimeoutMs);if(n.clockOffsetMs!==null&&typeof r.deadline==="number"&&Number.isFinite(r.deadline)){let l=r.deadline-(Date.now()+n.clockOffsetMs);if(l<=0){d("TIMEOUT","the request expired before it arrived");return}a=Math.min(a,l)}let g=new AbortController;n.running.set(o,g);let E=setTimeout(()=>g.abort(),a);E.unref?.();let y=null;g.signal.addEventListener("abort",()=>{y=setTimeout(()=>{if(n.running.get(o)!==g)return;n.running.delete(o),s("warn","Bridge command ignored its abort; slot reclaimed",{command:c})},Math.min(a,u.abandonGraceMs)),y.unref?.()});let v=new Promise((l,f)=>{g.signal.addEventListener("abort",()=>f(new He("TIMEOUT","aborted")))});v.catch(()=>{});let w;try{w=Promise.resolve(i(r.payload??null,{signal:g.signal,deadline:Date.now()+a}))}catch(l){w=Promise.reject(l)}w.catch(()=>{}).finally(()=>{if(clearTimeout(E),y)clearTimeout(y);if(n.running.get(o)===g)n.running.delete(o)});try{let l=await Promise.race([w,v]);k(t,{type:"response",id:o,ok:!0,result:l??null})}catch(l){let{code:f,message:b}=g.signal.aborted?{code:"TIMEOUT",message:`command '${c}' did not finish in time`}:x(l);if(f==="AGENT_ERROR")s("warn","Bridge command failed",{command:c,error:b});d(f,b)}}function L(){for(let t of n.running.values())t.abort()}function h(t){if(!n.ws||n.ws.readyState!==1)return!1;try{return n.ws.send(JSON.stringify(t)),!0}catch(r){return s("debug","safeSend failed",{error:r instanceof Error?r.message:String(r)}),!1}}function G(){B(),n.pingTimer=setInterval(()=>{h({type:"ping"})},C),n.pingTimer.unref?.()}function B(){if(n.pingTimer)clearInterval(n.pingTimer),n.pingTimer=null}function S(){n.connected=!1,n.clockOffsetMs=null,B(),L(),n.ws=null}function p(){if(n.stopped||n.reconnectTimer)return;let t=n.reconnectAttempt+1,r=Math.min(I*2**Math.min(t-1,5),O);if(n.reconnectAttempt=t,t===M)s("warn",`Bridge unavailable after ${t} attempts \u2014 falling back to existing HTTP polling for heartbeat/tunnel sync. Will keep retrying in the background.`);n.reconnectTimer=setTimeout(()=>{n.reconnectTimer=null,_().catch((o)=>{s("debug",`Bridge reconnect attempt failed: ${o instanceof Error?o.message:String(o)}`)})},r),n.reconnectTimer.unref?.()}function U(){if(!n.connected)return;while(n.pendingEvents.length>0){let t=n.pendingEvents.shift();if(!h({type:t.type,...t.payload})){n.pendingEvents.unshift(t);return}}}var D=500;function R(t){if(n.connected&&h({type:t.type,...t.payload}))return;if(n.pendingEvents.length>=D)n.pendingEvents.shift();n.pendingEvents.push(t)}var zi={start(t,r){if(n.stopped=!1,n.agentId===t&&n.connected)return;n.agentId=t,n.profile=r||"default",_().catch((o)=>{s("debug",`Bridge connect failed: ${o instanceof Error?o.message:String(o)}`)})},stop(){if(n.stopped=!0,n.reconnectTimer)clearTimeout(n.reconnectTimer),n.reconnectTimer=null;let t=n.ws;try{t?.close(1000,"agent shutdown")}catch{}S()},publishEvent(t){R({type:"event",payload:{topic:t.topic,payload:t.payload}})},publishLog(t){R({type:"log",payload:{payload:t}})},isConnected(){return n.connected},handle(t,r){if(!u.commandPattern.test(t))throw Error(`invalid bridge command name '${t}'`);return n.handlers.set(t,r),()=>{if(n.handlers.get(t)===r)n.handlers.delete(t)}},commands(){return[...n.handlers.keys()].sort()},isFallbackEngaged(){return n.reconnectAttempt>=M&&!n.connected}};
|
|
3
3
|
export{He,zi};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{R,C}from"./index-
|
|
2
|
+
import{R,C}from"./index-nxpw3anc.js";import{J,w}from"./index-30qr1qm3.js";import{existsSync as d,readFileSync as y}from"fs";import{join as T}from"path";var p="http://localhost:3005",h=new Set(["localhost","127.0.0.1","0.0.0.0","::1","[::1]"]);function A(r){return r.toLowerCase().replace(/^\[|\]$/g,"")}function $t(r){try{let n=new URL(r);return h.has(A(n.hostname))}catch{return!1}}function u(r){let n=new URL(r.trim());if(n.protocol!=="http:"&&n.protocol!=="https:")throw Error("Agent URL must use http or https");if(n.username||n.password)throw Error("Agent URL must not include credentials");let t=n.toString().replace(/\/+$/,"");if(!$t(t)&&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 t}function O(r){if(!Number.isInteger(r)||r<=0)return!1;try{return process.kill(r,0),!0}catch{return!1}}function _(){let r=T(C(),"agents.json");if(!d(r))return[];try{let n=JSON.parse(y(r,"utf-8"));return(Array.isArray(n)?n:n&&typeof n==="object"&&Array.isArray(n.instances)?n.instances:[]).filter((e)=>!!e&&typeof e==="object"&&typeof e.name==="string"&&typeof e.port==="number")}catch{return[]}}function E(r){let t=_().find((e)=>e.name===r);if(!t||!t.port)return null;if(typeof t.pid==="number"&&!O(t.pid))return null;return{url:`http://localhost:${t.port}`,port:t.port}}function f(r){let n=r?.agentUrl&&r.agentUrl!==p?r.agentUrl:void 0;if(n)return u(n);if(r?.profile){let t=E(r.profile);if(t)return t.url}if(process.env.AGENT_URL)return u(process.env.AGENT_URL);try{let t=m({}),e=E(t);if(e)return e.url}catch{}return u(p)}async function Fe(r){let n=$t(r);if(process.env.AGENT_API_KEY){if(n||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(!n)return;let t=R(),e=await J(`${t}:static-api-key`);if(e)return e;return w()["static-api-key"]}function m(r){if(r?.profile)return r.profile;if(process.env.VIBECONTROLS_PROFILE)return process.env.VIBECONTROLS_PROFILE;try{let n=T(C(),"agents.json");if(d(n)){let t=JSON.parse(y(n,"utf-8")),e=t&&typeof t==="object"&&!Array.isArray(t)?t.defaultProfile:void 0;if(typeof e==="string"&&e.length>0)return e}}catch{}return"default"}async function c(r,n,t={}){let e=await Fe(r),s={...t.body?{"Content-Type":"application/json"}:{},...e?{"x-agent-api-key":e}:{},...t.headers??{}},o;try{o=await fetch(`${r}${n}`,{...t,headers:s})}catch(i){let g=i instanceof Error?i.message:String(i),l=/unable to connect|ECONNREFUSED|ENOTFOUND|EHOSTUNREACH|fetch failed/i.test(g);if(l&&$t(r))throw Error(`Agent not reachable at ${r}. Is it running? Try 'vibe status' or 'vibe start'.`,{cause:i});if(l)throw Error(`Agent not reachable at ${r}. ${g}`,{cause:i});throw i}let a=await o.json().catch(()=>({}));return{ok:o.ok,status:o.status,data:a}}async function S(r,n){let{ok:t,status:e,data:s}=await c(r,n);if(!t){let o=s?.error||s?.message||`Agent returned ${e}`;throw Error(String(o))}return s}async function q(r,n,t){let{ok:e,status:s,data:o}=await c(r,n,{method:"POST",body:t!=null?JSON.stringify(t):void 0});if(!e){let a=o?.error||o?.message||`Agent returned ${s}`;throw Error(String(a))}return o}async function Te(r,n,t){let{ok:e,status:s,data:o}=await c(r,n,{method:"PUT",body:t!=null?JSON.stringify(t):void 0});if(!e){let a=o?.error||o?.message||`Agent returned ${s}`;throw Error(String(a))}return o}async function ge(r,n){let{ok:t,status:e,data:s}=await c(r,n,{method:"DELETE"});if(!t){let o=s?.error||s?.message||`Agent returned ${e}`;throw Error(String(o))}return s}
|
|
3
3
|
export{$t,f,Fe,m,S,q,Te,ge};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{I,e}from"./index-
|
|
2
|
+
import{I,e}from"./index-nxpw3anc.js";import{existsSync as s,mkdirSync as p,readFileSync as f,renameSync as m,writeFileSync as u}from"fs";import{dirname as P,join as k}from"path";var q="prereqs-installed.json",y="prereqs-installed";function c(r){return k(r??I(),q)}function l(r){let n=c(r);if(!s(n))return[];try{let t=JSON.parse(f(n,"utf8"));if(!Array.isArray(t))return[];return t.filter((i)=>!!i&&typeof i==="object"&&typeof i.name==="string"&&typeof i.pluginPackageName==="string")}catch(t){return e().logger.warn(y,`Failed to read tracker at ${n}: ${t}`),[]}}function x(r,n){let t=c(n),i=P(t);if(!s(i))p(i,{recursive:!0});let o=`${t}.${process.pid}.tmp`;u(o,`${JSON.stringify(r,null,2)}
|
|
3
3
|
`,{encoding:"utf8",mode:384}),m(o,t)}function yi(r,n){if(n.length===0)return;let i=l().filter((a)=>!(a.pluginPackageName===r&&n.some((g)=>g.name===a.name))),o=new Date().toISOString(),d=n.map((a)=>({name:a.name,kind:a.kind,installedAt:o,pluginPackageName:r}));x([...i,...d])}function Si(r){return l(r)}
|
|
4
4
|
export{yi,Si};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{E}from"./index-1t74r13z.js";import{e}from"./index-
|
|
2
|
+
import{E}from"./index-1t74r13z.js";import{e}from"./index-nxpw3anc.js";import"./index-30qr1qm3.js";import{i,s,A,o,g,c,v}from"./index-j9cg16we.js";import"./index-sq5j8bjn.js";import"./index-v77bb0rm.js";import{f,Fe,m,S}from"./index-djwa3tm3.js";var P={debug:0,info:1,warn:2,error:3};function j(r){if(!r)return;return r==="debug"||r==="info"||r==="warn"||r==="error"?r:void 0}function T(r,l,n,t){if(!r)return l;let u=parseInt(r,10);if(!Number.isInteger(u))return l;return Math.min(t,Math.max(n,u))}function U(r){return new E().get("/",async({query:l,set:n})=>{let t=l,u=j(t.level);if(t.level&&!u)return n.status=400,{error:"Invalid log level"};let y=await e().logger.readHistory({level:u,source:t.source,from:t.from,to:t.to,limit:T(t.limit,200,1,1000),offset:T(t.offset,0,0,1e5)});return{entries:y,count:y.length}}).get("/stream",({query:l,set:n})=>{let t=l,u=j(t.level);if(t.level&&!u)return n.status=400,{error:"Invalid log level"};let y=u??"info",d=t.source??"";return n.headers["Content-Type"]="text/event-stream",n.headers["Cache-Control"]="no-cache",n.headers.Connection="keep-alive",n.headers["X-Accel-Buffering"]="no",new ReadableStream({start(h){let p=new TextEncoder;h.enqueue(p.encode(`: connected
|
|
3
3
|
|
|
4
4
|
`));let a=(b)=>{if(P[b.level]<P[y])return;if(d&&!b.source.includes(d))return;try{h.enqueue(p.encode(`event: log
|
|
5
5
|
data: ${JSON.stringify(b)}
|
|
@@ -3,6 +3,6 @@ var T=!process.env.NO_COLOR&&!!process.stdout.isTTY;function Gi(e){T=e}var r=(e,
|
|
|
3
3
|
${i.bold(`\u2500\u2500 ${e} \u2500\u2500`)}
|
|
4
4
|
`)}function n(e,t){let a=t===null||t===void 0?i.gray("(none)"):String(t);console.log(` ${i.bold(e.padEnd(14))} ${a}`)}function c(){console.log()}function F(e){if(e.length===0){console.log(" (none)");return}console.table(e)}function v(e){let t=Date.now()-new Date(e).getTime(),a=Math.floor(t/1000);if(a<0)return"just now";if(a<60)return`${a}s ago`;let b=Math.floor(a/60);if(b<60)return`${b}m ago`;let m=Math.floor(b/60);if(m<24)return`${m}h ago`;let h=Math.floor(m/24);if(h<30)return`${h}d ago`;return`${Math.floor(h/30)}mo ago`}function Jr(e){if(e<60)return`${Math.floor(e)}s`;let t=Math.floor(e/60),a=Math.floor(e%60);if(t<60)return`${t}m ${a}s`;let b=Math.floor(t/60),m=t%60;return`${b}h ${m}m`}function Ge(e){if(e<1024)return`${e} B`;if(e<1048576)return`${(e/1024).toFixed(1)} KB`;if(e<1073741824)return`${(e/1048576).toFixed(1)} MB`;return`${(e/1073741824).toFixed(1)} GB`}function G(e){switch(e){case"running":case"active":case"healthy":case"success":case"completed":return i.green(e);case"stopped":case"inactive":case"terminated":case"failed":return i.red(e);case"starting":case"stopping":case"pending":case"warning":return i.yellow(e);case"error":return i.red(e);default:return e}}function H(e,t=10){if(e.length<=t)return e;return e.substring(0,t)+"..."}async function Gt(e,t=15000){let a=Date.now(),b=!1;while(Date.now()-a<t){try{if((await fetch(`${e}/health`)).ok){b=!0;break}}catch{}await new Promise((u)=>setTimeout(u,500))}if(!b){console.log(`
|
|
5
5
|
${d.warning} Agent not yet responding at ${e}. Check ${i.bold("vibe logs")} for details.
|
|
6
|
-
`);return}let m=process.env.VIBECONTROLS_PROFILE||"default",h=`${e}/api/profiles/${encodeURIComponent(m)}/agent/tunnel`,w="(unavailable)";try{let{resolveDefaultApiKey:u}=await import("./key.cmd-
|
|
6
|
+
`);return}let m=process.env.VIBECONTROLS_PROFILE||"default",h=`${e}/api/profiles/${encodeURIComponent(m)}/agent/tunnel`,w="(unavailable)";try{let{resolveDefaultApiKey:u}=await import("./key.cmd-eevbsknq.js"),f=await u();if(f)w=f}catch{}let k=w&&w!=="(unavailable)"?{"x-agent-api-key":w}:{},x="(not running)",M=!1;try{let u=await fetch(h,{headers:k});if(u.ok){let f=await u.json();if(f.tunnelUrl)x=f.tunnelUrl;else if(f.status!=="inactive")M=!0}}catch{}if(M||x==="(not running)"){process.stdout.write(` ${d.info} Provisioning tunnel (first run downloads the tunnel binary)\u2026`);let u=150000,f=Date.now();while(Date.now()-f<u){try{let y=await fetch(h,{headers:k});if(y.ok){let R=await y.json();if(R.tunnelUrl){x=R.tunnelUrl;break}}}catch{}await new Promise((y)=>setTimeout(y,1500)),process.stdout.write(`\r ${d.info} Provisioning tunnel (first run downloads the tunnel binary)\u2026 ${Math.round((Date.now()-f)/1000)}s`)}process.stdout.write(`
|
|
7
7
|
`)}if(g("Agent Connection Details"),n("Agent URL:",e),n("API Key:",w),n("Tunnel URL:",x==="(not running)"?i.yellow(x):i.green(x)),c(),console.log(" Copy the API Key and Tunnel URL into the VibeControls UI agent configuration."),x==="(not running)")console.log(` ${i.yellow("Tunnel still provisioning")} \u2014 the cloudflared download may still be running in the daemon.`),console.log(` Re-check shortly: ${i.bold("vibe url")}`),console.log(` Start it manually: ${i.bold(`vibe tunnel agent --start --agent-url ${e}`)}`),console.log(` If it never appears: ${i.bold("vibe logs --tail 80")} (look for 'tunnel-bootstrap' / 'install')`);c()}
|
|
8
8
|
export{Gi,i,d,s,A,l,p,o,g,n,c,F,v,Jr,Ge,G,H,Gt};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{r,E}from"./index-1t74r13z.js";import"./index-
|
|
2
|
+
import{r,E}from"./index-1t74r13z.js";import"./index-nxpw3anc.js";import{Z}from"./index-zekdqp0t.js";import"./index-30qr1qm3.js";import{i,d,s,A,l,o,g,n,c,F}from"./index-j9cg16we.js";import"./index-sq5j8bjn.js";import{vt,be,ki}from"./index-nqa1m94e.js";import"./index-cn4p1ks0.js";import{_,y,u}from"./index-v77bb0rm.js";import{f,m,S,Te,ge}from"./index-djwa3tm3.js";function R(C,t){if(C==="telemetry.enabled")Z.setEnabled(t==="true")}function P(C){return Object.entries(C).map(([t,e])=>({key:t,value:e}))}function j(C){let{db:t}=C;return new E().get("/",async()=>{let e=await t.getAllConfig(),p=ki(e);return{config:p,configs:P(p)}}).get("/status",async()=>await t.getConfigStatus()).get("/:key",async({params:e,set:p})=>{let k=await t.getConfig(e.key);if(k===void 0)return p.status=404,{error:"Configuration key not found"};return{key:e.key,value:be(e.key,k)}}).put("/:key",async({params:e,body:p,set:k})=>{if(vt(e.key))return k.status=403,{error:"Configuration key is managed by a dedicated endpoint"};try{return await t.setConfig(e.key,p.value),R(e.key,p.value),{success:!0}}catch(a){return k.status=500,{error:"Failed to set configuration",details:String(a)}}},{body:r.Object({value:r.String()})}).delete("/:key",async({params:e,set:p})=>{if(vt(e.key))return p.status=403,{error:"Configuration key is managed by a dedicated endpoint"};if(await t.getConfig(e.key)===void 0)return p.status=404,{error:"Configuration key not found"};try{return await t.deleteConfig(e.key),{success:!0}}catch(a){return p.status=500,{error:"Failed to delete configuration",details:String(a)}}}).post("/",async({body:e,set:p})=>{if(vt(e.key))return p.status=403,{error:"Configuration key is managed by a dedicated endpoint"};try{return await t.setConfig(e.key,e.value),R(e.key,e.value),{success:!0,key:e.key}}catch(k){return p.status=500,{error:"Failed to set configuration",details:String(k)}}},{body:r.Object({key:r.String(),value:r.String()})}).post("/bulk",async({body:e,set:p})=>{let k=Object.keys(e.configs).filter(vt);if(k.length>0)return p.status=403,{error:"One or more configuration keys are managed by dedicated endpoints",keys:k};try{await t.bulkSetConfig(e.configs);for(let[a,v]of Object.entries(e.configs))R(a,v);return{success:!0}}catch(a){return p.status=500,{error:"Failed to set configuration",details:String(a)}}},{body:r.Object({configs:r.Record(r.String(),r.String())})})}var x="http://localhost:3005";function h(C){C.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",x).option("--json","Emit JSON").option("--plain","Force plain text output").action(async function(t){let e={...C.opts(),...t};try{let p=f(t),k=encodeURIComponent(m(e));if(t.set){let a=t.set.indexOf("="),v,b;if(a===-1){if(t.value===void 0){if(e.json){u(e,{ok:!1,error:"Invalid format: use key=value or --set key --value v"});return}s(`Invalid format. Use ${i.bold("--set key=value")} or ${i.bold("--set key --value value")}`);return}v=t.set.trim(),b=String(t.value).trim()}else v=t.set.slice(0,a).trim(),b=t.set.slice(a+1).trim();if(!v){if(e.json){u(e,{ok:!1,error:"Configuration key cannot be empty"});return}s("Configuration key cannot be empty.");return}if(await Te(p,`/api/profiles/${k}/config/${encodeURIComponent(v)}`,{value:b}),u(e,{ok:!0,key:v}))return;l(`${d.success} Set ${i.bold(v)} = ${i.cyan(String(be(v,b)))}`)}else if(t.get)await y({mode:_(e),fetchData:()=>S(p,`/api/profiles/${k}/config/${encodeURIComponent(t.get)}`),plain:(a)=>{g("Configuration"),c(),n(a.key,i.bold(String(be(a.key,a.value)))),c()},json:(a)=>({key:a.key,value:be(a.key,a.value)})});else if(t.delete){if(await ge(p,`/api/profiles/${k}/config/${encodeURIComponent(t.delete)}`),u(e,{ok:!0,key:t.delete}))return;l(`${d.success} Deleted configuration key: ${i.bold(t.delete)}`)}else if(t.list)await y({mode:_(e),fetchData:()=>S(p,`/api/profiles/${k}/config/`),plain:(a)=>{if(g("Agent Configuration"),c(),!a.configs||a.configs.length===0){o(`${d.info} No configuration entries found.`);return}let v=a.configs.map((b)=>({Key:b.key,Value:String(be(b.key,b.value))}));F(v),c(),o(`${d.info} ${a.configs.length} configuration(s) found.`)},json:(a)=>(a.configs??[]).map((v)=>({key:v.key,value:be(v.key,v.value)}))});else{if(e.json){u(e,{ok:!1,error:"No operation specified"});return}o(`${d.info} Usage:`),o(` ${i.bold("vibe config --list")} List all config values`),o(` ${i.bold("vibe config --get <key>")} Get a config value`),o(` ${i.bold("vibe config --set <key=value>")} Set a config value`),o(` ${i.bold("vibe config --delete <key>")} Delete a config value`)}}catch(p){if(e.json){u(e,{ok:!1,error:A(p)});return}s(`Config operation failed: ${A(p)}`)}})}function w(C,t){h(C)}function J(C){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:(t)=>j(t),onCliSetup:async(t,e)=>{w(t,e)}}}export{J as createPlugin};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{r,E}from"./index-1t74r13z.js";import{ir,Fr,oe,Ei,Ft}from"./index-ppxayc0x.js";import{Zi,T}from"./index-
|
|
2
|
+
import{r,E}from"./index-1t74r13z.js";import{ir,Fr,oe,Ei,Ft}from"./index-ppxayc0x.js";import{Zi,T}from"./index-nxpw3anc.js";import"./index-30qr1qm3.js";import{s,A,l,o,g,F,v,G,H}from"./index-j9cg16we.js";import{Q}from"./index-sq5j8bjn.js";import{Me}from"./index-zn9snqbg.js";import{b}from"./index-w4jqdhc2.js";import{_,y,u}from"./index-v77bb0rm.js";import{$t,f,m,S,q}from"./index-djwa3tm3.js";import{promises as C}from"fs";import W from"path";import K from"os";function I(a,t){let n=Number.parseInt(process.env[a]??"",10);return Number.isInteger(n)&&n>0?n:t}var V=I("VIBECONTROLS_MAX_CONCURRENT_TASKS",4),X=I("VIBECONTROLS_MAX_TASK_OUTPUT_BYTES",1048576),z=new Set(["bash","sh","zsh","python","python3","node","bun","powershell","pwsh","cmd"]);async function Y(a,t){if(!a.command)throw Error("Command is required");let n=a.cwd?(await oe(a.cwd,{mustExist:!0})).path:process.cwd(),e=Bun.spawn(b().shellArgv(a.command),{cwd:n,env:{...process.env,...a.env},stdout:"pipe",stderr:"pipe"}),i=!1,d;if(t&&t>0)d=setTimeout(()=>{i=!0,e.kill()},t);let[w,c]=await Promise.all([x(e.stdout,()=>e.kill()),x(e.stderr,()=>e.kill())]),p=await e.exited;if(d)clearTimeout(d);if(i)throw Error(`Command timed out after ${t}ms`);return{stdout:w,stderr:c,exitCode:p}}async function Z(a,t){if(!a.script)throw Error("Script is required");let n=b().platform==="win32",e=a.interpreter||(n?"powershell":"bash");if(!z.has(e)||e.includes("/"))throw Error(`Interpreter '${e}' is not allowed`);let i=a.cwd?(await oe(a.cwd,{mustExist:!0})).path:process.cwd(),d=K.tmpdir(),w=e==="powershell"||e==="pwsh"?"ps1":e==="cmd"?"cmd":"sh",c=W.join(d,`vibecontrols-script-${globalThis.crypto.randomUUID()}.${w}`);await C.writeFile(c,a.script,{mode:448});try{let p=a.env?{...process.env,...a.env}:process.env,k=e==="powershell"||e==="pwsh"?[e,"-NoProfile","-ExecutionPolicy","Bypass","-File",c]:e==="cmd"?["cmd","/c",c]:[e,c],h=Bun.spawn(k,{cwd:i,env:p,stdout:"pipe",stderr:"pipe"}),R=!1,O;if(t&&t>0)O=setTimeout(()=>{R=!0,h.kill()},t);let[M,j]=await Promise.all([x(h.stdout,()=>h.kill()),x(h.stderr,()=>h.kill())]),B=await h.exited;if(O)clearTimeout(O);if(R)throw Error(`Script timed out after ${t}ms`);return{stdout:M,stderr:j,exitCode:B}}finally{await C.unlink(c).catch(()=>{})}}async function x(a,t){let n=new TextDecoder,e="",i=0,d=!1;for await(let w of a){if(i+=w.byteLength,i>X){if(!d)d=!0,t(),e+=`
|
|
3
3
|
[output truncated: task output limit exceeded]
|
|
4
4
|
`;continue}e+=n.decode(w,{stream:!0})}return e+=n.decode(),e}async function tt(a){if(!a.path)throw Error("Path is required");switch(a.operation){case"read":{let t=(await oe(a.path,{mustExist:!0})).path;if(ir(t))throw Error("Access to sensitive files not allowed");return await Ei(t),{content:await C.readFile(t,"utf-8"),path:t}}case"write":{if(!a.content)throw Error("Content is required for write operation");let t=(await oe(a.path,{forWrite:!0})).path;if(Fr(t)||ir(t))throw Error("Write access to sensitive files not allowed");return await C.writeFile(t,a.content),{success:!0,path:t}}case"delete":{let t=(await oe(a.path,{mustExist:!0})).path;if(Fr(t)||ir(t))throw Error("Delete access to this path is not allowed");return await C.unlink(t),{success:!0,path:t}}case"exists":try{let t=(await oe(a.path)).path;return await C.access(t),{exists:!0,path:t}}catch{return{exists:!1}}case"list":{let t=(await oe(a.path,{mustExist:!0})).path;return{files:(await Ft(t)).map((e)=>e.name),path:t}}default:throw Error(`Unknown file operation: ${a.operation}`)}}async function et(a,t,n,e){try{let i=await a.getTask(t.id);if(i&&i.status!=="pending")return;await a.updateTask(t.id,{status:"running"});let d=JSON.parse(t.payload),w,c;switch(t.type){case"command":{let h=await Y(d,e?.timeout);w=h,c=h.exitCode;break}case"script":{let h=await Z(d,e?.timeout);w=h,c=h.exitCode;break}case"file_operation":w=await tt(d);break;default:throw Error(`Unknown task type: ${t.type}`)}let p=c!==void 0&&c!==0,k=p?"failed":"completed";if(await a.updateTask(t.id,{status:k,result:JSON.stringify(w),...c!==void 0&&{exitCode:c},...p&&{error:`Process exited with code ${c}`}}),e?.callbackUrl)L(e.callbackUrl,{agentTaskId:t.id,status:k,result:w,exitCode:c,...p&&{error:`Process exited with code ${c}`}})}catch(i){let d=i instanceof Error?i.message:String(i);try{await a.updateTask(t.id,{status:"failed",error:d})}catch(w){console.warn(`[task] failed to mark task ${t.id} as failed: ${w instanceof Error?w.message:String(w)}`)}if(e?.callbackUrl)L(e.callbackUrl,{agentTaskId:t.id,status:"failed",error:d})}finally{n.active=Math.max(0,n.active-1)}}function L(a,t){fetch(a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),signal:AbortSignal.timeout(1e4)}).catch(()=>{})}function N(a){let{db:t}=a,n={active:0};return new E().get("/",async({query:e})=>{if(e.status==="pending")return{tasks:await t.getPendingTasks()};return{tasks:await t.getAllTasks()}}).get("/:id",async({params:e,set:i})=>{let d=await t.getTask(e.id);if(!d)return i.status=404,{error:"Task not found"};return{task:d}}).post("/legacy",async({body:e,set:i})=>{try{return{task:await t.createTask({id:globalThis.crypto.randomUUID(),type:"file_operation",status:"completed",payload:JSON.stringify({operation:"exists",path:process.cwd(),meta:e}),result:JSON.stringify({legacy:!0,note:"Legacy doctor-script task accepted (no-op)."})})}}catch(d){return i.status=500,{error:"Failed to create task",details:String(d)}}},{body:r.Any()}).post("/",async({body:e,request:i,server:d,set:w})=>{let c=e;if(c&&typeof c==="object"&&!c.type&&!c.payload&&(c.title||c.description||c.command))try{return{task:await t.createTask({id:globalThis.crypto.randomUUID(),type:"file_operation",status:"completed",payload:JSON.stringify({operation:"exists",path:process.cwd(),meta:c}),result:JSON.stringify({legacy:!0,note:"Legacy doctor-script task accepted (no-op)."})})}}catch(k){return w.status=500,{error:"Failed to create task",details:String(k)}}let p=e;try{if(p.type==="command"||p.type==="script"){let h=await Me(i,"VIBECONTROLS_ALLOW_REMOTE_SHELL_TASK",d,{getConfig:(R)=>t.getConfig(R)});if(h)return w.status=403,{error:"Forbidden",message:h}}else if(p.type==="file_operation"&&["write","delete"].includes(String(p.payload?.operation??""))){let h=await Me(i,"VIBECONTROLS_ALLOW_REMOTE_FILE_TASK",d,{getConfig:(R)=>t.getConfig(R)});if(h)return w.status=403,{error:"Forbidden",message:h}}if(n.active>=V)return w.status=429,{error:"Too many tasks are already running"};if(n.active+=1,p.callbackUrl&&!Zi(p.callbackUrl,(()=>{let h=T.getConfig();return[h?.globalGatewayUrl,h?.workspaceGatewayUrl]})()))return n.active=Math.max(0,n.active-1),w.status=400,{error:"callbackUrl is not allowed"};let k=await t.createTask({id:globalThis.crypto.randomUUID(),type:p.type,status:"pending",payload:JSON.stringify(p.payload),...p.calendarTaskId&&{calendarTaskId:p.calendarTaskId},...p.timeout&&{timeout:p.timeout}});return et(t,k,n,{timeout:p.timeout,callbackUrl:p.callbackUrl}),{task:k}}catch(k){return n.active=Math.max(0,n.active-1),w.status=500,{error:"Failed to create task",details:String(k)}}},{body:r.Any()}).post("/:id/cancel",async({params:e,set:i})=>{let d=await t.getTask(e.id);if(!d)return i.status=404,{error:"Task not found"};if(d.status!=="pending")return i.status=400,{error:"Only pending tasks can be cancelled"};return await t.updateTask(e.id,{status:"failed",error:"Task cancelled by user"}),{success:!0}}).delete("/:id",async({params:e,set:i})=>{let d=await t.getTask(e.id);if(!d)return i.status=404,{error:"Task not found"};if(d.status==="pending")await t.updateTask(e.id,{status:"failed",error:"Task cancelled via DELETE"});return{success:!0,status:d.status}})}var P="http://localhost:3005";function U(a){return`/api/profiles/${encodeURIComponent(m(a))}/tasks`}function D(a){let t=a.command("task").description("Manage background tasks");t.command("list").description("List tasks").option("--status <status>","Filter by status").option("--profile <name>","Profile name (overrides default resolution)").option("--agent-url <url>","Agent URL",P).option("--json","Emit JSON").option("--plain","Force plain text output").action(async function(n){let e={...a.opts(),...n};try{let i=f(n),d=U(e),w=n.status?`${d}/?status=${encodeURIComponent(n.status)}`:`${d}/`;await y({mode:_(e),fetchData:async()=>(await S(i,w)).tasks||[],plain:(c)=>{if(!c||c.length===0){o("No tasks found.");return}g("Tasks"),F(c.map((p)=>({ID:H(p.id),Type:p.type||"-",Status:G(p.status),Created:p.createdAt?v(p.createdAt):"-"})))},interactive:async(c)=>{if(!c||c.length===0){g("Tasks"),o("No tasks found.");return}let p=c.map((k)=>({id:String(k.id),label:k.type||H(k.id),hint:k.status||"",detail:[`ID: ${k.id}`,`Type: ${k.type??"-"}`,`Status: ${G(k.status)}`,`Created: ${k.createdAt?v(k.createdAt):"-"}`].join(`
|
|
5
5
|
`)}));await Q({title:`vibe task list \u2014 ${c.length} task(s)`,rows:p})},json:(c)=>c.map((p)=>({id:p.id,type:p.type??null,status:p.status??null,createdAt:p.createdAt??null}))})}catch(i){s(A(i))}}),t.command("run").description("Run a new task").requiredOption("-c, --command <cmd>","Command to run").option("--cwd <dir>","Working directory").option("--profile <name>","Profile name (overrides default resolution)").option("--agent-url <url>","Agent URL",P).option("--json","Emit JSON").action(async function(n){let e={...a.opts(),...n};try{let i=f(n);if(!$t(i)&&process.env.VIBECONTROLS_ALLOW_REMOTE_SHELL_TASK!=="1"){if(e.json){u(e,{ok:!1,error:"Remote shell task refused without env override"});return}s("Refusing to create a shell task on a remote agent URL. Set VIBECONTROLS_ALLOW_REMOTE_SHELL_TASK=1 only if you trust the target.");return}let d={command:n.command};if(n.cwd)d.cwd=n.cwd;let w=U(e),c=await q(i,`${w}/`,{type:"command",payload:d}),p=c?.task?.id||c?.id||c?.taskId;if(u(e,{ok:!0,id:p}))return;if(!p){s("Task created but no ID returned by the agent");return}l(`Task created: ${H(p)}`)}catch(i){if(e.json){u(e,{ok:!1,error:A(i)});return}s(A(i))}}),t.command("cancel").description("Cancel a running task").requiredOption("-i, --id <id>","Task ID").option("--profile <name>","Profile name (overrides default resolution)").option("--agent-url <url>","Agent URL",P).option("--json","Emit JSON").action(async function(n){let e={...a.opts(),...n};try{let i=f(n),d=U(e);if(await q(i,`${d}/${n.id}/cancel`,{}),u(e,{ok:!0,id:n.id}))return;l(`Task ${H(n.id)} cancelled.`)}catch(i){if(e.json){u(e,{ok:!1,error:A(i)});return}s(A(i))}})}function J(a,t){D(a)}function ht(a){return{name:"task",version:"2.2.0",description:"Background task execution \u2014 commands, scripts, file operations",capabilities:{storage:"rw",subprocess:!0,audit:!0,telemetry:!0},tags:["backend","cli"],cliCommand:"task",apiPrefix:"/api/tasks",createRoutes:(t)=>N(t),onCliSetup:async(t,n)=>{J(t,n)}}}export{ht as createPlugin};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{E}from"./index-1t74r13z.js";import{wt,e}from"./index-
|
|
2
|
+
import{E}from"./index-1t74r13z.js";import{wt,e}from"./index-nxpw3anc.js";import{we,qe,pr,Vr,Yr,L,V}from"./index-pw6aqemr.js";function gr(n,t){let s=new E,r=[],o=new Set;function i(l){return l.endsWith("/")&&l!=="/"?l.slice(0,-1):l}function a(l,u){if(!u.startsWith("/"))return null;if(u==="/"||u.includes("..")||u.includes("*"))return null;let f=i(l),d=i(`${f}${u}`);if(d===f||!d.startsWith(`${f}/`))return null;return d}function c(l){if(!l.createRoutes)return!1;if(o.has(l.name))return!1;let u=l.apiPrefix||`/api/${l.name}`;try{let f=l.createRoutes(n.routeDepsFor(l,t));if(e().logger.info("plugin-router",`Plugin '${l.name}' registered routes`,{prefix:u}),s.use(new E({prefix:u}).derive(()=>({pluginContext:{chain:[l.name],parentPlugin:void 0,activePlugin:l.name}})).use(f)),l.publicPaths)for(let d of l.publicPaths){let g=a(u,d);if(!g){e().logger.warn("plugin-router",`Ignoring unsafe public path from plugin '${l.name}'`,{publicPath:d,prefix:u});continue}r.push(g)}return o.add(l.name),!0}catch(f){return e().logger.error("plugin-router",`Failed to mount routes for plugin '${l.name}'`,{error:String(f)}),!1}}for(let l of n.getAllPlugins())c(l);return{routes:s,getPublicPaths:()=>[...r],mountPlugin:c}}var M=1e4;function R(n,t){let s=process.env[n];if(!s)return t;let r=Number.parseInt(s,10);return Number.isFinite(r)&&r>0?r:t}function G(){return[{name:"health",match:(n)=>n.startsWith("/health"),perMinute:R("VIBECONTROLS_RATELIMIT_HEALTH",1000)},{name:"gateway-auth",match:(n)=>n.startsWith("/api/agent/gateway-auth"),perMinute:R("VIBECONTROLS_RATELIMIT_GATEWAY_AUTH",10)},{name:"plugin-install",match:(n)=>n.startsWith("/api/plugins/install"),perMinute:R("VIBECONTROLS_RATELIMIT_PLUGIN_INSTALL",5)},{name:"alias-exec",match:(n)=>/^\/api\/aliases\/[^/]+\/execute/.test(n),perMinute:R("VIBECONTROLS_RATELIMIT_ALIAS_EXEC",30)},{name:"api",match:(n)=>n.startsWith("/api/"),perMinute:R("VIBECONTROLS_RATELIMIT_API",100)}]}function H(n,t,s){for(let r of n)if(r.match(t,s))return r;return null}function S(n){if(!n)return!1;return n==="127.0.0.1"||n==="::1"||n==="::ffff:127.0.0.1"||n.startsWith("127.")}function K(n=Date.now){let t=new Map,s=(r,o)=>{t.delete(r),t.set(r,o)};return{take(r,o,i){let a=n(),c=t.get(r);if(!c)c={tokens:o,lastRefillMs:a,capacity:o,refillPerSec:i};else{let u=(a-c.lastRefillMs)/1000;c.tokens=Math.min(o,c.tokens+u*i),c.lastRefillMs=a,c.capacity=o,c.refillPerSec=i}let l=c.tokens>=1;if(l)c.tokens-=1;if(s(r,c),t.size>M){let u=t.keys();while(t.size>M){let f=u.next();if(f.done)break;t.delete(f.value)}}return l},retryAfterSec(r){let o=t.get(r);if(!o)return 1;if(o.refillPerSec<=0)return 60;let i=1-o.tokens;if(i<=0)return 0;return Math.max(1,Math.ceil(i/o.refillPerSec))},size(){return t.size},reset(){t.clear()}}}function Di(n={}){let t=n.classes??G(),s=n.store??K();return new E({name:"plugin/rate-limit"}).onRequest(({request:r,set:o,server:i})=>{let a;try{a=i?.requestIP(r)?.address??null}catch{a=null}if(S(a))return;let c=new URL(r.url),l=H(t,c.pathname,r.method);if(!l)return;let f=`${a??"unknown"}|${l.name}`,d=l.perMinute/60;if(!s.take(f,l.perMinute,d)){let g=s.retryAfterSec(f);o.status=429;let _=o.headers??={};return _["Retry-After"]=String(g),{error:"rate_limited",message:`Too many requests for ${l.name}; retry after ${g}s.`,retryAfterSec:g}}}).as("global")}var J=(()=>{let n=process.env.VIBECONTROLS_WS_MAX_PER_IP,t=n?Number.parseInt(n,10):NaN;return Number.isFinite(t)&&t>0?t:5})();function v(n=J){let t=new Map;return{accept(s,r){if(S(s))return!0;let o=s??"unknown",i=t.get(o);if(!i)i=new Set,t.set(o,i);if(i.size>=n)return!1;return i.add(r),!0},release(s,r){if(S(s))return;let o=s??"unknown",i=t.get(o);if(!i)return;if(i.delete(r),i.size===0)t.delete(o)},size(s){let r=s??"unknown";return t.get(r)?.size??0}}}function dr(n){let t=new Set,s=new Map,r=new Map;return{accept(o,i,a){if(t.size>=n.maxGlobal)return!1;let c=s.get(o)??new Set;if(c.size>=n.maxPerKey)return!1;let l=i??"unknown";if(!S(i)){let u=r.get(l)??new Set;if(u.size>=n.maxPerIp)return!1;u.add(a),r.set(l,u)}return t.add(a),c.add(a),s.set(o,c),!0},release(o,i,a){t.delete(a);let c=s.get(o);if(c){if(c.delete(a),c.size===0)s.delete(o)}if(!S(i)){let l=i??"unknown",u=r.get(l);if(u){if(u.delete(a),u.size===0)r.delete(l)}}},globalCount(){return t.size},keyCount(o){return s.get(o)?.size??0}}}function w(n,t){let s=process.env[n];if(!s)return t;let r=Number.parseInt(s,10);return Number.isFinite(r)&&r>0?r:t}var N={maxGlobal:w("VIBE_TERMINAL_WS_MAX_GLOBAL",64),maxPerKey:w("VIBE_TERMINAL_WS_MAX_PER_SESSION",4),maxPerIp:w("VIBE_TERMINAL_WS_MAX_PER_IP",16)},Ni={maxGlobal:w("VIBE_CODE_SERVER_WS_MAX_GLOBAL",64),maxPerKey:w("VIBE_CODE_SERVER_WS_MAX_PER_SESSION",8),maxPerIp:w("VIBE_CODE_SERVER_WS_MAX_PER_IP",16)};function Y(n){if(!n)return new Set;let t=new Set;for(let s of n.split(",")){let r=s.trim();if(r)t.add(r)}return t}var k=null;function Q(){let n=process.env.VIBE_TRUSTED_PROXIES;if(!k||k.raw!==n)k={raw:n,set:Y(n)};return k.set}function Qe(n,t){let s=Q();if(!!n&&(S(n)||s.has(n))&&t){let o=t["x-forwarded-for"];if(o){let a=o.split(",")[0]?.trim();if(a)return a}let i=t["x-real-ip"];if(i)return i}return n}import{EventEmitter as Z}from"events";var O=v(),P=new Z;P.setMaxListeners(100);function pe(n,t){let s={type:n,payload:t,timestamp:new Date().toISOString()};P.emit("ws:event",s)}var B=(()=>{let n=process.env.VIBECONTROLS_MAX_WS_CLIENTS,t=n?Number.parseInt(n,10):NaN;return Number.isFinite(t)&&t>0?t:200})(),ee=(()=>{let n=process.env.VIBECONTROLS_MAX_WS_BUFFER_PER_CLIENT,t=n?Number.parseInt(n,10):NaN;return Number.isFinite(t)&&t>0?t:100})();function Qr(){let n=new Set;return P.on("ws:event",(t)=>{let s=JSON.stringify(t);for(let r of n){if(r.pendingSends>=ee){if(r.drops+=1,r.drops===1||r.drops%100===0)e().logger.warn("ws-events",`Dropping events for slow client (${r.drops} dropped)`);continue}try{r.send(s)}catch{}}}),new E().ws("/ws/events",{open(t){if(n.size>=B){e().logger.warn("ws-events",`MAX_WS_CLIENTS exceeded (${n.size}/${B}); refusing new connection`),t.close(1013,"Server overloaded");return}let s=t.data,r=L(s.headers??{});if(!V(r)){t.close(1008,"Unauthorized: invalid or missing API key");return}let o=t.remoteAddress??null,i=Qe(o,s.headers);if(!O.accept(i??null,t)){t.close(1008,"too many connections");return}t._remoteIp=i??null;let a={ws:t,channels:new Set,pendingSends:0,drops:0,send:(c)=>{a.pendingSends+=1;try{t.send(c)}finally{queueMicrotask(()=>{a.pendingSends=Math.max(0,a.pendingSends-1)})}}};n.add(a),t._client=a,e().logger.debug("ws-events","Client connected",{id:String(t.id||"unknown")}),t.send(JSON.stringify({type:"connected",timestamp:new Date().toISOString()}))},message(t,s){try{let r=typeof s==="string"?JSON.parse(s):s;switch(r.type){case"subscribe":{let o=t._client;if(o)o.channels.add(r.channel);e().logger.debug("ws-events",`Subscribed to ${r.channel}`);break}case"unsubscribe":{let o=t._client;if(o)o.channels.delete(r.channel);e().logger.debug("ws-events",`Unsubscribed from ${r.channel}`);break}case"ping":t.send(JSON.stringify({type:"pong",timestamp:new Date().toISOString()}));break;default:e().logger.debug("ws-events",`Unknown message type: ${r.type}`)}}catch{e().logger.warn("ws-events","Failed to parse incoming message")}},close(t){let s=t._client;if(s)n.delete(s);let r=t._remoteIp;O.release(r??null,t),e().logger.debug("ws-events","Client disconnected")}})}var x=dr(N),te=256,ne=1048576,re=1e4;async function W(n,t,s,r,o,i){let a={};for(let[l,u]of Object.entries(o))if(u&&!["host","connection"].includes(l.toLowerCase()))a[l]=u;let c={method:r,headers:a};if(r!=="GET"&&r!=="HEAD"&&i)c.body=typeof i==="string"?i:JSON.stringify(i);return fetch(`http://${n}:${t}${s}`,c)}async function C(n,t){let s=n.listProvidersForType("session");for(let{pluginName:r}of s){let o=n.getProviderByName("session",r);if(!o)continue;let i=await o.getTerminalInfo(t);if(!i)continue;try{process.kill(i.pid,0)}catch{continue}let a=i;return{host:a.host??"127.0.0.1",port:i.port,wsPath:a.wsPath??"/ws",subprotocols:a.subprotocols??["tty"]}}return null}var m=new Map,se=0,I=new Map,D=30000;function b(n){x.release(n.sessionId,n.remoteIp,n.capRef)}function oe(n){return typeof n==="string"?Buffer.byteLength(n):n.byteLength}function U(n){let t=new Headers(n.headers);return t.set("Permissions-Policy","clipboard-read=(self), clipboard-write=(self)"),t.delete("X-Frame-Options"),new Response(n.body,{status:n.status,headers:t})}function F(n){return`<!doctype html>
|
|
3
3
|
<html>
|
|
4
4
|
<head>
|
|
5
5
|
<meta charset="utf-8">
|
|
@@ -79,4 +79,4 @@ import{E}from"./index-1t74r13z.js";import{wt,e}from"./index-7wm4bqx5.js";import{
|
|
|
79
79
|
})();
|
|
80
80
|
</script>
|
|
81
81
|
</body>
|
|
82
|
-
</html>`}function jr(n){return new E().all("/terminal/:sessionId",async({params:t,request:s,set:r})=>{let o=t.sessionId,i=Yr(s,o);if(!i||!pr(i,o)){if(s.method==="GET")return r.status=200,r.headers["content-type"]="text/html; charset=utf-8",F(o);return r.status=401,{error:"Unauthorized: terminal cookie required"}}let a=await C(n,o);if(!a)return r.status=502,{error:"Terminal not running for this session"};let c=await W(a.host,a.port,"/",s.method,Object.fromEntries(Object.entries(s.headers).map(([l,u])=>[l,u])));return r.status=c.status,U(c)}).all("/terminal/:sessionId/*",async({params:t,request:s,set:r})=>{let o=t.sessionId,i=t["*"]||"",a=Yr(s,o);if(!a||!pr(a,o)){if(s.method==="GET"&&(i===""||i==="/"))return r.status=200,r.headers["content-type"]="text/html; charset=utf-8",F(o);return r.status=401,{error:"Unauthorized: terminal cookie required"}}let c=await C(n,o);if(!c)return r.status=502,{error:"Terminal not running for this session"};let l=await W(c.host,c.port,`/${i}`,s.method,Object.fromEntries(Object.entries(s.headers).map(([u,f])=>[u,f])));return r.status=l.status,U(l)}).ws("/terminal/:sessionId/ws",{open(t){let s=t.data,r=s.params?.sessionId;if(!r){t.close(1008,"Missing sessionId");return}if(!we(r)){t.close(1008,"Invalid sessionId");return}let o=Vr(s.headers??{},r),i=!!o&&pr(o,r),a=s.query?.vt,c=!!a&&qe(a,`/terminal/${r}`,"GET");if(!i&&!c){t.close(1008,"Unauthorized: invalid or missing terminal credentials");return}let l=t.remoteAddress??null,u=Qe(l,s.headers),f=`bridge-${++se}`;if(s._bridgeId=f,!x.accept(r,u,f)){e().logger.warn("terminal-ws",`Terminal WS cap exceeded for session ${r} (ip=${u??"unknown"})`),t.close(1013,"too many connections");return}s._remoteIp=u;let d={upstream:null,upstreamReady:!1,buffer:[],bufferBytes:0,openTimer:null,sessionId:r,remoteIp:u,capRef:f};m.set(f,d),e().logger.debug("terminal-ws",`Client connected for session ${r} (${f})`),C(n,r).then((g)=>{if(m.get(f)!==d)return;if(!g){let h=I.get(r)??0,p=Date.now();if(I.size>50){let T=p-D*2;for(let[j,q]of I)if(q<T)I.delete(j)}if(p-h>D)e().logger.warn("terminal-ws",`No terminal running for session ${r}`),I.set(r,p);b(d),m.delete(f),t.close(1011,"No terminal running");return}let _=`ws://${g.host}:${g.port}${g.wsPath}`,y=new WebSocket(_,g.subprotocols);d.upstream=y,d.openTimer=setTimeout(()=>{b(d),m.delete(f);try{y.close(1011,"upstream open timeout")}catch{}try{t.close(1011,"Upstream open timeout")}catch{}},re),y.addEventListener("open",()=>{if(d.openTimer)clearTimeout(d.openTimer),d.openTimer=null;d.upstreamReady=!0,e().logger.debug("terminal-ws",`Bridge established \u2192 port ${g.port}, buffered=${d.buffer.length}`,{sessionId:r});for(let h of d.buffer)y.send(h);d.buffer.length=0,d.bufferBytes=0}),y.addEventListener("message",(h)=>{try{let p=h.data;if(p instanceof ArrayBuffer)t.send(new Uint8Array(p));else if(p instanceof Blob)p.arrayBuffer().then((T)=>{try{t.send(new Uint8Array(T))}catch{}});else t.send(p)}catch(p){e().logger.error("terminal-ws",`Failed to forward upstream\u2192client: ${p}`,{sessionId:r})}}),y.addEventListener("close",(h)=>{if(d.openTimer)clearTimeout(d.openTimer),d.openTimer=null;e().logger.debug("terminal-ws",`Upstream closed (code=${h.code})`,{sessionId:r}),b(d),m.delete(f);try{t.close(1000,"Upstream closed")}catch{}}),y.addEventListener("error",(h)=>{if(d.openTimer)clearTimeout(d.openTimer),d.openTimer=null;e().logger.error("terminal-ws","Upstream error",{sessionId:r}),b(d),m.delete(f);try{t.close(1011,"Upstream error")}catch{}})}).catch((g)=>{b(d),m.delete(f),e().logger.warn("terminal-ws","Failed to resolve terminal endpoint",{sessionId:r,error:String(g)});try{t.close(1011,"Failed to resolve terminal")}catch{}})},message(t,s){let o=t.data._bridgeId;if(!o)return;let i=m.get(o);if(!i)return;let a;if(typeof s==="string")a=s;else if(s instanceof ArrayBuffer)a=s;else if(s instanceof Uint8Array||Buffer.isBuffer(s)){let c=new ArrayBuffer(s.byteLength);new Uint8Array(c).set(new Uint8Array(s.buffer,s.byteOffset,s.byteLength)),a=c}else if(typeof s==="object"&&s!==null)a=JSON.stringify(s);else a=String(s);if(i.upstream&&i.upstreamReady&&i.upstream.readyState===WebSocket.OPEN)try{i.upstream.send(a)}catch(c){e().logger.error("terminal-ws",`Failed to forward client\u2192upstream: ${c}`,{sessionId:i.sessionId})}else{let c=oe(a);if(i.buffer.length>=te||i.bufferBytes+c>ne){b(i),m.delete(o);try{t.close(1013,"Terminal buffer limit exceeded")}catch{}return}i.buffer.push(a),i.bufferBytes+=c}},close(t){let s=t.data,r=s._bridgeId,o=s.params?.sessionId;if(e().logger.debug("terminal-ws","Client disconnected",{sessionId:o}),r){let i=m.get(r);if(i?.upstream&&i.upstream.readyState===WebSocket.OPEN)i.upstream.close(1000,"Client disconnected");if(i?.openTimer)clearTimeout(i.openTimer);if(i)b(i);m.delete(r)}if(o&&r)x.release(o,s._remoteIp??null,r)}})}var z=v(),X={debug:0,info:1,warn:2,error:3};function ie(n){return n==="debug"||n==="info"||n==="warn"||n==="error"?n:null}function Gr(){return new E().ws("/ws/logs",{open(n){let t=n.data,s=L(t.headers??{}),r=t.query?.vt,o=V(s),i=!!r&&qe(r,"/ws/logs","GET");if(!o&&!i){n.close(1008,"Unauthorized: invalid or missing credentials");return}let a=n.remoteAddress??null,c=Qe(a,t.headers);if(!z.accept(c??null,n)){n.close(1008,"too many connections");return}n._remoteIp=c??null,e().logger.info("ws-logs","Log stream client connected");let l={minLevel:"info",source:""};n._filters=l;let u=(f)=>{let d=n._filters;if(X[f.level]<X[d.minLevel])return;if(d.source&&!f.source.includes(d.source))return;try{n.send(JSON.stringify(f))}catch{}};e().logger.on("log",u),n._logHandler=u,n.send(JSON.stringify({type:"connected",timestamp:new Date().toISOString()}))},message(n,t){try{let s=typeof t==="string"?JSON.parse(t):t;if(s.type==="filter"){let r=n._filters,o=ie(s.level);if(o)r.minLevel=o;if(typeof s.source==="string")r.source=s.source.slice(0,128);n.send(JSON.stringify({type:"filter-updated",filters:r}))}}catch{}},close(n){let t=n._logHandler;if(t)e().logger.removeListener("log",t);let s=n._remoteIp;z.release(s??null,n),e().logger.info("ws-logs","Log stream client disconnected")}})}var A=new Map;function _t(n,t){if(!n.db||!n.serviceRegistry||!n.pluginManager)throw Error(`mountProfileRoutes: profile '${n.name}' has no attached services`);let s={db:n.db,serviceRegistry:n.serviceRegistry,pluginManager:n.pluginManager,broadcast:pe,hostServices:n.hostServices??void 0,rebuildPluginSurfaces:t?.rebuildPluginSurfaces,mountPlugin:t?.mountPlugin,app:t?.app},{routes:r}=gr(n.pluginManager,s);A.set(n.name,{ctx:n,router:r})}function nn(n){return A.delete(n)}async function $r(n,t,s){let r=A.get(n);if(!r)return null;wt(r.ctx);let o=new URL(t.url),a=`/api${o.pathname.replace(/^\/api\/profiles\/[^/]+/,"")}${o.search}`,c=new Headers(t.headers),l={method:t.method,headers:c};if(t.method!=="GET"&&t.method!=="HEAD")if(s!==void 0)l.body=s;else l.body=t.body,l.duplex="half";let u=new Request(`${o.origin}${a}`,l);return r.router.handle(u)}export{gr,
|
|
82
|
+
</html>`}function jr(n){return new E().all("/terminal/:sessionId",async({params:t,request:s,set:r})=>{let o=t.sessionId,i=Yr(s,o);if(!i||!pr(i,o)){if(s.method==="GET")return r.status=200,r.headers["content-type"]="text/html; charset=utf-8",F(o);return r.status=401,{error:"Unauthorized: terminal cookie required"}}let a=await C(n,o);if(!a)return r.status=502,{error:"Terminal not running for this session"};let c=await W(a.host,a.port,"/",s.method,Object.fromEntries(Object.entries(s.headers).map(([l,u])=>[l,u])));return r.status=c.status,U(c)}).all("/terminal/:sessionId/*",async({params:t,request:s,set:r})=>{let o=t.sessionId,i=t["*"]||"",a=Yr(s,o);if(!a||!pr(a,o)){if(s.method==="GET"&&(i===""||i==="/"))return r.status=200,r.headers["content-type"]="text/html; charset=utf-8",F(o);return r.status=401,{error:"Unauthorized: terminal cookie required"}}let c=await C(n,o);if(!c)return r.status=502,{error:"Terminal not running for this session"};let l=await W(c.host,c.port,`/${i}`,s.method,Object.fromEntries(Object.entries(s.headers).map(([u,f])=>[u,f])));return r.status=l.status,U(l)}).ws("/terminal/:sessionId/ws",{open(t){let s=t.data,r=s.params?.sessionId;if(!r){t.close(1008,"Missing sessionId");return}if(!we(r)){t.close(1008,"Invalid sessionId");return}let o=Vr(s.headers??{},r),i=!!o&&pr(o,r),a=s.query?.vt,c=!!a&&qe(a,`/terminal/${r}`,"GET");if(!i&&!c){t.close(1008,"Unauthorized: invalid or missing terminal credentials");return}let l=t.remoteAddress??null,u=Qe(l,s.headers),f=`bridge-${++se}`;if(s._bridgeId=f,!x.accept(r,u,f)){e().logger.warn("terminal-ws",`Terminal WS cap exceeded for session ${r} (ip=${u??"unknown"})`),t.close(1013,"too many connections");return}s._remoteIp=u;let d={upstream:null,upstreamReady:!1,buffer:[],bufferBytes:0,openTimer:null,sessionId:r,remoteIp:u,capRef:f};m.set(f,d),e().logger.debug("terminal-ws",`Client connected for session ${r} (${f})`),C(n,r).then((g)=>{if(m.get(f)!==d)return;if(!g){let h=I.get(r)??0,p=Date.now();if(I.size>50){let T=p-D*2;for(let[j,q]of I)if(q<T)I.delete(j)}if(p-h>D)e().logger.warn("terminal-ws",`No terminal running for session ${r}`),I.set(r,p);b(d),m.delete(f),t.close(1011,"No terminal running");return}let _=`ws://${g.host}:${g.port}${g.wsPath}`,y=new WebSocket(_,g.subprotocols);d.upstream=y,d.openTimer=setTimeout(()=>{b(d),m.delete(f);try{y.close(1011,"upstream open timeout")}catch{}try{t.close(1011,"Upstream open timeout")}catch{}},re),y.addEventListener("open",()=>{if(d.openTimer)clearTimeout(d.openTimer),d.openTimer=null;d.upstreamReady=!0,e().logger.debug("terminal-ws",`Bridge established \u2192 port ${g.port}, buffered=${d.buffer.length}`,{sessionId:r});for(let h of d.buffer)y.send(h);d.buffer.length=0,d.bufferBytes=0}),y.addEventListener("message",(h)=>{try{let p=h.data;if(p instanceof ArrayBuffer)t.send(new Uint8Array(p));else if(p instanceof Blob)p.arrayBuffer().then((T)=>{try{t.send(new Uint8Array(T))}catch{}});else t.send(p)}catch(p){e().logger.error("terminal-ws",`Failed to forward upstream\u2192client: ${p}`,{sessionId:r})}}),y.addEventListener("close",(h)=>{if(d.openTimer)clearTimeout(d.openTimer),d.openTimer=null;e().logger.debug("terminal-ws",`Upstream closed (code=${h.code})`,{sessionId:r}),b(d),m.delete(f);try{t.close(1000,"Upstream closed")}catch{}}),y.addEventListener("error",(h)=>{if(d.openTimer)clearTimeout(d.openTimer),d.openTimer=null;e().logger.error("terminal-ws","Upstream error",{sessionId:r}),b(d),m.delete(f);try{t.close(1011,"Upstream error")}catch{}})}).catch((g)=>{b(d),m.delete(f),e().logger.warn("terminal-ws","Failed to resolve terminal endpoint",{sessionId:r,error:String(g)});try{t.close(1011,"Failed to resolve terminal")}catch{}})},message(t,s){let o=t.data._bridgeId;if(!o)return;let i=m.get(o);if(!i)return;let a;if(typeof s==="string")a=s;else if(s instanceof ArrayBuffer)a=s;else if(s instanceof Uint8Array||Buffer.isBuffer(s)){let c=new ArrayBuffer(s.byteLength);new Uint8Array(c).set(new Uint8Array(s.buffer,s.byteOffset,s.byteLength)),a=c}else if(typeof s==="object"&&s!==null)a=JSON.stringify(s);else a=String(s);if(i.upstream&&i.upstreamReady&&i.upstream.readyState===WebSocket.OPEN)try{i.upstream.send(a)}catch(c){e().logger.error("terminal-ws",`Failed to forward client\u2192upstream: ${c}`,{sessionId:i.sessionId})}else{let c=oe(a);if(i.buffer.length>=te||i.bufferBytes+c>ne){b(i),m.delete(o);try{t.close(1013,"Terminal buffer limit exceeded")}catch{}return}i.buffer.push(a),i.bufferBytes+=c}},close(t){let s=t.data,r=s._bridgeId,o=s.params?.sessionId;if(e().logger.debug("terminal-ws","Client disconnected",{sessionId:o}),r){let i=m.get(r);if(i?.upstream&&i.upstream.readyState===WebSocket.OPEN)i.upstream.close(1000,"Client disconnected");if(i?.openTimer)clearTimeout(i.openTimer);if(i)b(i);m.delete(r)}if(o&&r)x.release(o,s._remoteIp??null,r)}})}var z=v(),X={debug:0,info:1,warn:2,error:3};function ie(n){return n==="debug"||n==="info"||n==="warn"||n==="error"?n:null}function Gr(){return new E().ws("/ws/logs",{open(n){let t=n.data,s=L(t.headers??{}),r=t.query?.vt,o=V(s),i=!!r&&qe(r,"/ws/logs","GET");if(!o&&!i){n.close(1008,"Unauthorized: invalid or missing credentials");return}let a=n.remoteAddress??null,c=Qe(a,t.headers);if(!z.accept(c??null,n)){n.close(1008,"too many connections");return}n._remoteIp=c??null,e().logger.info("ws-logs","Log stream client connected");let l={minLevel:"info",source:""};n._filters=l;let u=(f)=>{let d=n._filters;if(X[f.level]<X[d.minLevel])return;if(d.source&&!f.source.includes(d.source))return;try{n.send(JSON.stringify(f))}catch{}};e().logger.on("log",u),n._logHandler=u,n.send(JSON.stringify({type:"connected",timestamp:new Date().toISOString()}))},message(n,t){try{let s=typeof t==="string"?JSON.parse(t):t;if(s.type==="filter"){let r=n._filters,o=ie(s.level);if(o)r.minLevel=o;if(typeof s.source==="string")r.source=s.source.slice(0,128);n.send(JSON.stringify({type:"filter-updated",filters:r}))}}catch{}},close(n){let t=n._logHandler;if(t)e().logger.removeListener("log",t);let s=n._remoteIp;z.release(s??null,n),e().logger.info("ws-logs","Log stream client disconnected")}})}var A=new Map;function _t(n,t){if(!n.db||!n.serviceRegistry||!n.pluginManager)throw Error(`mountProfileRoutes: profile '${n.name}' has no attached services`);let s={db:n.db,serviceRegistry:n.serviceRegistry,pluginManager:n.pluginManager,broadcast:pe,hostServices:n.hostServices??void 0,rebuildPluginSurfaces:t?.rebuildPluginSurfaces,mountPlugin:t?.mountPlugin,app:t?.app},{routes:r}=gr(n.pluginManager,s);A.set(n.name,{ctx:n,router:r})}function nn(n){return A.delete(n)}async function $r(n,t,s){let r=A.get(n);if(!r)return null;wt(r.ctx);let o=new URL(t.url),a=`/api${o.pathname.replace(/^\/api\/profiles\/[^/]+/,"")}${o.search}`,c=new Headers(t.headers),l={method:t.method,headers:c};if(t.method!=="GET"&&t.method!=="HEAD")if(s!==void 0)l.body=s;else l.body=t.body,l.duplex="half";let u=new Request(`${o.origin}${a}`,l);return r.router.handle(u)}export{gr,Di,dr,Ni,Qe,pe,Qr,jr,Gr,_t,nn,$r};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var i=new Set(["static-api-key","plugin-state:external-config"]),o=["gateway-auth:"],s=[/(^|[-_:])secret($|[-_:])/i,/(^|[-_:])token($|[-_:])/i,/(^|[-_:])password($|[-_:])/i,/(^|[-_:])api[-_]?key($|[-_:])/i,/^static-api-key$/i,/^gateway-auth:/i,/^clientSecret$/i,/^plugin-state:external-config$/i],Mi="[redacted]";function vt(t){return i.has(t)||o.some((n)=>t.startsWith(n))}function r(t){return s.some((n)=>n.test(t))}function be(t,n){return r(t)&&n!==void 0?"[redacted]":n}function
|
|
3
|
-
export{Mi,vt,be,
|
|
2
|
+
var i=new Set(["static-api-key","plugin-state:external-config"]),o=["gateway-auth:"],s=[/(^|[-_:])secret($|[-_:])/i,/(^|[-_:])token($|[-_:])/i,/(^|[-_:])password($|[-_:])/i,/(^|[-_:])api[-_]?key($|[-_:])/i,/^static-api-key$/i,/^gateway-auth:/i,/^clientSecret$/i,/^plugin-state:external-config$/i],Mi="[redacted]";function vt(t){return i.has(t)||o.some((n)=>t.startsWith(n))}function r(t){return s.some((n)=>n.test(t))}function be(t,n){return r(t)&&n!==void 0?"[redacted]":n}function ki(t){return Object.fromEntries(Object.entries(t).map(([n,e])=>[n,be(n,e)]))}function N(t){if(Array.isArray(t))return t.map((n)=>N(n));if(!t||typeof t!=="object")return t;return Object.fromEntries(Object.entries(t).map(([n,e])=>[n,r(n)?"[redacted]":N(e)]))}
|
|
3
|
+
export{Mi,vt,be,ki,N};
|