@vibecontrols/agent 2026.602.7 → 2026.814.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-pxkfd7ec.js → agent-config-hzzh97dn.js} +1 -1
- package/dist/{agent-ready-tracker-pyw7zrp0.js → agent-ready-tracker-gx1yqwjk.js} +1 -1
- package/dist/app-k3dex7x4.js +2 -0
- package/dist/bootstrap-workspace-dg1e3fp6.js +2 -0
- package/dist/bootstrap.service-nbhhd4pa.js +2 -0
- package/dist/bridge-client-zye1vz1y.js +2 -0
- package/dist/cli.js +1 -1
- package/dist/daemon-profile-ryakpcbx.js +2 -0
- package/dist/{esm-6f3dfn6v.js → esm-cg5tnbkd.js} +1 -1
- package/dist/{finalize-retry-handle-registry-xnm9kxry.js → finalize-retry-handle-registry-kzfqhvwv.js} +1 -1
- package/dist/{finalize-retry-worker-vfdskqb5.js → finalize-retry-worker-74wxbdsh.js} +1 -1
- package/dist/gateway-client-8y9yd0ch.js +2 -0
- package/dist/{getMachineId-bsd-753751sw.js → getMachineId-bsd-65jabrgp.js} +1 -1
- package/dist/{getMachineId-darwin-na1pranq.js → getMachineId-darwin-yykv9khr.js} +1 -1
- package/dist/{getMachineId-linux-dmn0ncdm.js → getMachineId-linux-w09acg2n.js} +1 -1
- package/dist/{getMachineId-unsupported-yv77j894.js → getMachineId-unsupported-dwr7bb60.js} +1 -1
- package/dist/{getMachineId-win-9hmyqmm0.js → getMachineId-win-0wkw4jek.js} +1 -1
- package/dist/highlights-5wfvq2xq.js +2 -0
- package/dist/highlights-fdyzf5xj.js +2 -0
- package/dist/highlights-g5bek66n.js +2 -0
- package/dist/highlights-scv26t06.js +2 -0
- package/dist/highlights-tx5ed845.js +2 -0
- package/dist/{index-thammzct.js → index-0s81cfpe.js} +1 -1
- package/dist/{index-wetsgcyq.js → index-13xxbf03.js} +1 -1
- package/dist/{index-rjhcmnx0.js → index-16czz4df.js} +1 -1
- package/dist/{index-kt5zxp42.js → index-1ptfacy9.js} +1 -1
- package/dist/{index-xrs52f2c.js → index-2bjqvapr.js} +1 -1
- package/dist/{index-x0xv3rpa.js → index-2gwc485c.js} +1 -1
- package/dist/{index-n1222y6a.js → index-2jxqpj7r.js} +9 -9
- package/dist/{index-5mnyfrck.js → index-4gt22c81.js} +1 -1
- package/dist/{index-jrtsdm8f.js → index-53qthjhb.js} +1 -1
- package/dist/{index-m9dpfyxb.js → index-5s2zc91f.js} +1 -1
- package/dist/{index-cfa3pgh5.js → index-5wsfsj88.js} +3 -3
- package/dist/{index-z73x3sdf.js → index-7vwefvxd.js} +1 -1
- package/dist/{index-p9cgvp3x.js → index-8k78bp4w.js} +1 -1
- package/dist/{index-bfeekmyh.js → index-9g3vxhby.js} +1 -1
- package/dist/{index-z40ptwv4.js → index-c0fgge10.js} +2 -2
- package/dist/{index-xnr6t79p.js → index-c4p1qcnn.js} +6 -6
- package/dist/{index-85ke6hng.js → index-c975k3pk.js} +2 -2
- package/dist/{index-t8tnkqxh.js → index-e2dqz3tw.js} +1 -1
- package/dist/{index-8sdrhr3q.js → index-g9fthh7a.js} +1 -1
- package/dist/{index-c7554sg7.js → index-gb5bnx7a.js} +1 -1
- package/dist/{index-qwtspxw8.js → index-gx53t38f.js} +1 -1
- package/dist/{index-97mq40rr.js → index-jb3v3b39.js} +1 -1
- package/dist/{index-zhyxdyk6.js → index-jqfsvf8f.js} +1 -1
- package/dist/{index-9bdbnx8f.js → index-jrxbbb7p.js} +49 -49
- package/dist/{index-6p3gcnxr.js → index-m2kkd6t6.js} +1 -1
- package/dist/{index-08y76yzh.js → index-nj7bvgws.js} +1 -1
- package/dist/{index-4qq083yd.js → index-ntj6ymk8.js} +1 -1
- package/dist/index-nwh7j7ap.js +2 -0
- package/dist/{index-c6xa5nd4.js → index-pc05r6fd.js} +1 -1
- package/dist/{index-a4854mwz.js → index-q9dp55wv.js} +1 -1
- package/dist/{index-ep3zb271.js → index-qzhvhyvq.js} +1 -1
- package/dist/{index-2nq63va3.js → index-r49hb09r.js} +2 -2
- package/dist/{index-63ba5fb4.js → index-sv4rzv3f.js} +1 -1
- package/dist/{index-ekzav1nc.js → index-tcwmw7ed.js} +5 -5
- package/dist/{index-eawbdgkb.js → index-wd2ak0q4.js} +1 -1
- package/dist/{index-x649afed.js → index-wndzw5pk.js} +2 -2
- package/dist/{index-czrb2yd1.js → index-zabjc8f2.js} +1 -1
- package/dist/{index-pgew6sge.js → index-zaw78sxw.js} +2 -2
- package/dist/{index-yas07mv9.js → index-zb7nfmts.js} +1 -1
- package/dist/index.js +2 -2
- package/dist/injections-agpjxatz.js +2 -0
- package/dist/interactive-ewe5szk5.js +2 -0
- package/dist/key.cmd-xefsd8p4.js +2 -0
- package/dist/log-shipper-4h1k4kp6.js +2 -0
- package/dist/{path-utils-hxdyv2zn.js → path-utils-cg1gsy4m.js} +1 -1
- package/dist/{plugin-system-f47jdx66.js → plugin-system-ksatnqp4.js} +1 -1
- package/dist/prereqs-runner-6yf1e5e3.js +2 -0
- package/dist/profile-mount-13qvjqbg.js +2 -0
- package/dist/prune-stale-shims-t6kdd2an.js +2 -0
- package/dist/register-core-9k4zxnsg.js +2 -0
- package/dist/secondary-profile-attach-42x68g0c.js +2 -0
- package/dist/subprocess-6m8bja6s.js +2 -0
- package/dist/telemetry-mq37zapd.js +2 -0
- package/dist/tree-sitter-javascript-emqv64wx.js +2 -0
- package/dist/tree-sitter-markdown-v98rp3y1.js +2 -0
- package/dist/tree-sitter-markdown_inline-5gq03gn2.js +2 -0
- package/dist/tree-sitter-typescript-gr7ymg9w.js +2 -0
- package/dist/tree-sitter-zig-59q80fch.js +2 -0
- package/dist/tunnel-bootstrap-50fm2wt8.js +2 -0
- package/package.json +4 -5
- package/dist/app-5asxkthh.js +0 -2
- package/dist/bootstrap-workspace-1ff98st2.js +0 -2
- package/dist/bootstrap.service-vg72w8pa.js +0 -2
- package/dist/bridge-client-73z9c5nm.js +0 -2
- package/dist/daemon-profile-696722nr.js +0 -2
- package/dist/gateway-client-xdy5g715.js +0 -2
- package/dist/highlights-00fcgwwq.js +0 -2
- package/dist/highlights-23bc8zge.js +0 -2
- package/dist/highlights-4mhb2pb0.js +0 -2
- package/dist/highlights-q7w64nwb.js +0 -2
- package/dist/highlights-xwdw5xay.js +0 -2
- package/dist/index-p23tet7a.js +0 -2
- package/dist/injections-x3xya90r.js +0 -2
- package/dist/interactive-qc1j66mq.js +0 -2
- package/dist/key.cmd-q8c7ywwd.js +0 -2
- package/dist/log-shipper-hjnn1d5p.js +0 -2
- package/dist/prereqs-runner-t5jhqr7x.js +0 -2
- package/dist/profile-mount-m714p85h.js +0 -2
- package/dist/prune-stale-shims-23y0stm8.js +0 -2
- package/dist/register-core-2t9dmbnp.js +0 -2
- package/dist/secondary-profile-attach-s5z9dppt.js +0 -2
- package/dist/subprocess-q2ky0ptw.js +0 -2
- package/dist/telemetry-jxfgrm61.js +0 -2
- package/dist/tree-sitter-javascript-q22gvtms.js +0 -2
- package/dist/tree-sitter-markdown-pntsjzm3.js +0 -2
- package/dist/tree-sitter-markdown_inline-g1wzqf7k.js +0 -2
- package/dist/tree-sitter-typescript-m9yfes10.js +0 -2
- package/dist/tree-sitter-zig-jmh62j90.js +0 -2
- package/dist/tunnel-bootstrap-zdczwezc.js +0 -2
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Bb as k,Cb as a,Db as y,Lb as T,Mb as x,tb as r,yb as v}from"./index-
|
|
2
|
+
import{Bb as k,Cb as a,Db as y,Lb as T,Mb as x,tb as r,yb as v}from"./index-9g3vxhby.js";import{Vb as B}from"./index-zaw78sxw.js";import{Ld as e,Pd as j}from"./index-c4p1qcnn.js";function w(Q,J){let $=new B,Z=[],G=new Set;function Y(z){return z.endsWith("/")&&z!=="/"?z.slice(0,-1):z}function U(z,H){if(!H.startsWith("/"))return null;if(H==="/"||H.includes("..")||H.includes("*"))return null;let F=Y(z),X=Y(`${F}${H}`);if(X===F||!X.startsWith(`${F}/`))return null;return X}function V(z){if(!z.createRoutes)return!1;if(G.has(z.name))return!1;let H=z.apiPrefix||`/api/${z.name}`;try{let F=z.createRoutes(J);if(j().logger.info("plugin-router",`Plugin '${z.name}' registered routes`,{prefix:H}),$.use(new B({prefix:H}).derive(()=>({pluginContext:{chain:[z.name],parentPlugin:void 0,activePlugin:z.name}})).use(F)),z.publicPaths)for(let X of z.publicPaths){let K=U(H,X);if(!K){j().logger.warn("plugin-router",`Ignoring unsafe public path from plugin '${z.name}'`,{publicPath:X,prefix:H});continue}Z.push(K)}return G.add(z.name),!0}catch(F){return j().logger.error("plugin-router",`Failed to mount routes for plugin '${z.name}'`,{error:String(F)}),!1}}for(let z of Q.getAllPlugins())V(z);return{routes:$,getPublicPaths:()=>[...Z],mountPlugin:V}}import{EventEmitter as VJ}from"events";var u=1e4;function L(Q,J){let $=process.env[Q];if(!$)return J;let Z=Number.parseInt($,10);return Number.isFinite(Z)&&Z>0?Z:J}function ZJ(){return[{name:"health",match:(Q)=>Q.startsWith("/health"),perMinute:L("VIBECONTROLS_RATELIMIT_HEALTH",1000)},{name:"gateway-auth",match:(Q)=>Q.startsWith("/api/agent/gateway-auth"),perMinute:L("VIBECONTROLS_RATELIMIT_GATEWAY_AUTH",10)},{name:"plugin-install",match:(Q)=>Q.startsWith("/api/plugins/install"),perMinute:L("VIBECONTROLS_RATELIMIT_PLUGIN_INSTALL",5)},{name:"alias-exec",match:(Q)=>/^\/api\/aliases\/[^/]+\/execute/.test(Q),perMinute:L("VIBECONTROLS_RATELIMIT_ALIAS_EXEC",30)},{name:"api",match:(Q)=>Q.startsWith("/api/"),perMinute:L("VIBECONTROLS_RATELIMIT_API",100)}]}function $J(Q,J,$){for(let Z of Q)if(Z.match(J,$))return Z;return null}function R(Q){if(!Q)return!1;return Q==="127.0.0.1"||Q==="::1"||Q==="::ffff:127.0.0.1"||Q.startsWith("127.")}function GJ(Q=Date.now){let J=new Map,$=(Z,G)=>{J.delete(Z),J.set(Z,G)};return{take(Z,G,Y){let U=Q(),V=J.get(Z);if(!V)V={tokens:G,lastRefillMs:U,capacity:G,refillPerSec:Y};else{let H=(U-V.lastRefillMs)/1000;V.tokens=Math.min(G,V.tokens+H*Y),V.lastRefillMs=U,V.capacity=G,V.refillPerSec=Y}let z=V.tokens>=1;if(z)V.tokens-=1;if($(Z,V),J.size>u){let H=J.keys();while(J.size>u){let F=H.next();if(F.done)break;J.delete(F.value)}}return z},retryAfterSec(Z){let G=J.get(Z);if(!G)return 1;if(G.refillPerSec<=0)return 60;let Y=1-G.tokens;if(Y<=0)return 0;return Math.max(1,Math.ceil(Y/G.refillPerSec))},size(){return J.size},reset(){J.clear()}}}function SJ(Q={}){let J=Q.classes??ZJ(),$=Q.store??GJ();return new B({name:"plugin/rate-limit"}).onRequest(({request:Z,set:G,server:Y})=>{let U;try{U=Y?.requestIP(Z)?.address??null}catch{U=null}if(R(U))return;let V=new URL(Z.url),z=$J(J,V.pathname,Z.method);if(!z)return;let F=`${U??"unknown"}|${z.name}`,X=z.perMinute/60;if(!$.take(F,z.perMinute,X)){let K=$.retryAfterSec(F);G.status=429;let P=G.headers??={};return P["Retry-After"]=String(K),{error:"rate_limited",message:`Too many requests for ${z.name}; retry after ${K}s.`,retryAfterSec:K}}}).as("global")}var YJ=(()=>{let Q=process.env.VIBECONTROLS_WS_MAX_PER_IP,J=Q?Number.parseInt(Q,10):NaN;return Number.isFinite(J)&&J>0?J:5})();function C(Q=YJ){let J=new Map;return{accept($,Z){if(R($))return!0;let G=$??"unknown",Y=J.get(G);if(!Y)Y=new Set,J.set(G,Y);if(Y.size>=Q)return!1;return Y.add(Z),!0},release($,Z){if(R($))return;let G=$??"unknown",Y=J.get(G);if(!Y)return;if(Y.delete(Z),Y.size===0)J.delete(G)},size($){let Z=$??"unknown";return J.get(Z)?.size??0}}}function c(Q){let J=new Set,$=new Map,Z=new Map;return{accept(G,Y,U){if(J.size>=Q.maxGlobal)return!1;let V=$.get(G)??new Set;if(V.size>=Q.maxPerKey)return!1;let z=Y??"unknown";if(!R(Y)){let H=Z.get(z)??new Set;if(H.size>=Q.maxPerIp)return!1;H.add(U),Z.set(z,H)}return J.add(U),V.add(U),$.set(G,V),!0},release(G,Y,U){J.delete(U);let V=$.get(G);if(V){if(V.delete(U),V.size===0)$.delete(G)}if(!R(Y)){let z=Y??"unknown",H=Z.get(z);if(H){if(H.delete(U),H.size===0)Z.delete(z)}}},globalCount(){return J.size},keyCount(G){return $.get(G)?.size??0}}}function _(Q,J){let $=process.env[Q];if(!$)return J;let Z=Number.parseInt($,10);return Number.isFinite(Z)&&Z>0?Z:J}var m={maxGlobal:_("VIBE_TERMINAL_WS_MAX_GLOBAL",64),maxPerKey:_("VIBE_TERMINAL_WS_MAX_PER_SESSION",4),maxPerIp:_("VIBE_TERMINAL_WS_MAX_PER_IP",16)},LJ={maxGlobal:_("VIBE_CODE_SERVER_WS_MAX_GLOBAL",64),maxPerKey:_("VIBE_CODE_SERVER_WS_MAX_PER_SESSION",8),maxPerIp:_("VIBE_CODE_SERVER_WS_MAX_PER_IP",16)};function UJ(Q){if(!Q)return new Set;let J=new Set;for(let $ of Q.split(",")){let Z=$.trim();if(Z)J.add(Z)}return J}var D=null;function zJ(){let Q=process.env.VIBE_TRUSTED_PROXIES;if(!D||D.raw!==Q)D={raw:Q,set:UJ(Q)};return D.set}function E(Q,J){let $=zJ();if(!!Q&&(R(Q)||$.has(Q))&&J){let G=J["x-forwarded-for"];if(G){let U=G.split(",")[0]?.trim();if(U)return U}let Y=J["x-real-ip"];if(Y)return Y}return Q}var d=C(),h=new VJ;h.setMaxListeners(100);function b(Q,J){let $={type:Q,payload:J,timestamp:new Date().toISOString()};h.emit("ws:event",$)}var p=(()=>{let Q=process.env.VIBECONTROLS_MAX_WS_CLIENTS,J=Q?Number.parseInt(Q,10):NaN;return Number.isFinite(J)&&J>0?J:200})(),HJ=(()=>{let Q=process.env.VIBECONTROLS_MAX_WS_BUFFER_PER_CLIENT,J=Q?Number.parseInt(Q,10):NaN;return Number.isFinite(J)&&J>0?J:100})();function XJ(){let Q=new Set;return h.on("ws:event",(J)=>{let $=JSON.stringify(J);for(let Z of Q){if(Z.pendingSends>=HJ){if(Z.drops+=1,Z.drops===1||Z.drops%100===0)j().logger.warn("ws-events",`Dropping events for slow client (${Z.drops} dropped)`);continue}try{Z.send($)}catch{}}}),new B().ws("/ws/events",{open(J){if(Q.size>=p){j().logger.warn("ws-events",`MAX_WS_CLIENTS exceeded (${Q.size}/${p}); refusing new connection`),J.close(1013,"Server overloaded");return}let $=J.data,Z=T($.headers??{});if(!x(Z)){J.close(1008,"Unauthorized: invalid or missing API key");return}let G=J.remoteAddress??null,Y=E(G,$.headers);if(!d.accept(Y??null,J)){J.close(1008,"too many connections");return}J._remoteIp=Y??null;let U={ws:J,channels:new Set,pendingSends:0,drops:0,send:(V)=>{U.pendingSends+=1;try{J.send(V)}finally{queueMicrotask(()=>{U.pendingSends=Math.max(0,U.pendingSends-1)})}}};Q.add(U),J._client=U,j().logger.debug("ws-events","Client connected",{id:String(J.id||"unknown")}),J.send(JSON.stringify({type:"connected",timestamp:new Date().toISOString()}))},message(J,$){try{let Z=typeof $==="string"?JSON.parse($):$;switch(Z.type){case"subscribe":{let G=J._client;if(G)G.channels.add(Z.channel);j().logger.debug("ws-events",`Subscribed to ${Z.channel}`);break}case"unsubscribe":{let G=J._client;if(G)G.channels.delete(Z.channel);j().logger.debug("ws-events",`Unsubscribed from ${Z.channel}`);break}case"ping":J.send(JSON.stringify({type:"pong",timestamp:new Date().toISOString()}));break;default:j().logger.debug("ws-events",`Unknown message type: ${Z.type}`)}}catch{j().logger.warn("ws-events","Failed to parse incoming message")}},close(J){let $=J._client;if($)Q.delete($);let Z=J._remoteIp;d.release(Z??null,J),j().logger.debug("ws-events","Client disconnected")}})}var g=c(m),FJ=256,jJ=1048576,KJ=1e4;async function l(Q,J,$,Z,G,Y){let U={};for(let[z,H]of Object.entries(G))if(H&&!["host","connection"].includes(z.toLowerCase()))U[z]=H;let V={method:Z,headers:U};if(Z!=="GET"&&Z!=="HEAD"&&Y)V.body=typeof Y==="string"?Y:JSON.stringify(Y);return fetch(`http://${Q}:${J}${$}`,V)}async function I(Q,J){let $=Q.listProvidersForType("session");for(let{pluginName:Z}of $){let G=Q.getProviderByName("session",Z);if(!G)continue;let Y=await G.getTerminalInfo(J);if(!Y)continue;try{process.kill(Y.pid,0)}catch{continue}let U=Y;return{host:U.host??"127.0.0.1",port:Y.port,wsPath:U.wsPath??"/ws",subprotocols:U.subprotocols??["tty"]}}return null}var M=new Map,NJ=0,q=new Map,o=30000;function A(Q){g.release(Q.sessionId,Q.remoteIp,Q.capRef)}function BJ(Q){return typeof Q==="string"?Buffer.byteLength(Q):Q.byteLength}function n(Q){let J=new Headers(Q.headers);return J.set("Permissions-Policy","clipboard-read=(self), clipboard-write=(self)"),J.delete("X-Frame-Options"),new Response(Q.body,{status:Q.status,headers:J})}function i(Q){return`<!doctype html>
|
|
3
3
|
<html>
|
|
4
4
|
<head>
|
|
5
5
|
<meta charset="utf-8">
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{i as L}from"./index-cs78wq6y.js";import{C as N,D as M,E as D,F as m,G as k}from"./index-6jzsthh9.js";import{Xa as v}from"./index-0ckffygp.js";import{Ub as I,Vb as h}from"./index-
|
|
2
|
+
import{i as L}from"./index-cs78wq6y.js";import{C as N,D as M,E as D,F as m,G as k}from"./index-6jzsthh9.js";import{Xa as v}from"./index-0ckffygp.js";import{Ub as I,Vb as h}from"./index-zaw78sxw.js";import{jc as p,kc as d,lc as w}from"./index-8nqp3a4d.js";import{Cc as f,Dc as x,qc as O,rc as q,sc as B,uc as A,vc as S,yc as i,zc as E}from"./index-c975k3pk.js";import{Gc as r}from"./index-0s81cfpe.js";import{Kc as n,Lc as C,Nc as y,Oc as l,Pc as T}from"./index-e2dqz3tw.js";import"./index-sv4rzv3f.js";import{Gd as b,Jd as g}from"./index-c4p1qcnn.js";import"./index-q9dp55wv.js";import"./index-ntj6ymk8.js";import"./index-gb5bnx7a.js";import{promises as J}from"fs";import H2 from"path";import V2 from"os";function u(j,H){let Q=Number.parseInt(process.env[j]??"",10);return Number.isInteger(Q)&&Q>0?Q:H}var j2=u("VIBECONTROLS_MAX_CONCURRENT_TASKS",4),Q2=u("VIBECONTROLS_MAX_TASK_OUTPUT_BYTES",1048576),Z2=new Set(["bash","sh","zsh","python","python3","node","bun","powershell","pwsh","cmd"]);async function $2(j,H){if(!j.command)throw Error("Command is required");let Q=j.cwd?(await D(j.cwd,{mustExist:!0})).path:process.cwd(),V=Bun.spawn(v().shellArgv(j.command),{cwd:Q,env:{...process.env,...j.env},stdout:"pipe",stderr:"pipe"}),Z=!1,z;if(H&&H>0)z=setTimeout(()=>{Z=!0,V.kill()},H);let[K,$]=await Promise.all([R(V.stdout,()=>V.kill()),R(V.stderr,()=>V.kill())]),Y=await V.exited;if(z)clearTimeout(z);if(Z)throw Error(`Command timed out after ${H}ms`);return{stdout:K,stderr:$,exitCode:Y}}async function z2(j,H){if(!j.script)throw Error("Script is required");let Q=v().platform==="win32",V=j.interpreter||(Q?"powershell":"bash");if(!Z2.has(V)||V.includes("/"))throw Error(`Interpreter '${V}' is not allowed`);let Z=j.cwd?(await D(j.cwd,{mustExist:!0})).path:process.cwd(),z=V2.tmpdir(),K=V==="powershell"||V==="pwsh"?"ps1":V==="cmd"?"cmd":"sh",$=H2.join(z,`vibecontrols-script-${globalThis.crypto.randomUUID()}.${K}`);await J.writeFile($,j.script,{mode:448});try{let Y=j.env?{...process.env,...j.env}:process.env,W=V==="powershell"||V==="pwsh"?[V,"-NoProfile","-ExecutionPolicy","Bypass","-File",$]:V==="cmd"?["cmd","/c",$]:[V,$],X=Bun.spawn(W,{cwd:Z,env:Y,stdout:"pipe",stderr:"pipe"}),G=!1,_;if(H&&H>0)_=setTimeout(()=>{G=!0,X.kill()},H);let[a,e]=await Promise.all([R(X.stdout,()=>X.kill()),R(X.stderr,()=>X.kill())]),t=await X.exited;if(_)clearTimeout(_);if(G)throw Error(`Script timed out after ${H}ms`);return{stdout:a,stderr:e,exitCode:t}}finally{await J.unlink($).catch(()=>{})}}async function R(j,H){let Q=new TextDecoder,V="",Z=0,z=!1;for await(let K of j){if(Z+=K.byteLength,Z>Q2){if(!z)z=!0,H(),V+=`
|
|
3
3
|
[output truncated: task output limit exceeded]
|
|
4
4
|
`;continue}V+=Q.decode(K,{stream:!0})}return V+=Q.decode(),V}async function Y2(j){if(!j.path)throw Error("Path is required");switch(j.operation){case"read":{let H=(await D(j.path,{mustExist:!0})).path;if(N(H))throw Error("Access to sensitive files not allowed");return await m(H),{content:await J.readFile(H,"utf-8"),path:H}}case"write":{if(!j.content)throw Error("Content is required for write operation");let H=(await D(j.path,{forWrite:!0})).path;if(M(H)||N(H))throw Error("Write access to sensitive files not allowed");return await J.writeFile(H,j.content),{success:!0,path:H}}case"delete":{let H=(await D(j.path,{mustExist:!0})).path;if(M(H)||N(H))throw Error("Delete access to this path is not allowed");return await J.unlink(H),{success:!0,path:H}}case"exists":try{let H=(await D(j.path)).path;return await J.access(H),{exists:!0,path:H}}catch{return{exists:!1}}case"list":{let H=(await D(j.path,{mustExist:!0})).path;return{files:(await k(H)).map((V)=>V.name),path:H}}default:throw Error(`Unknown file operation: ${j.operation}`)}}async function K2(j,H,Q,V){try{let Z=await j.getTask(H.id);if(Z&&Z.status!=="pending")return;await j.updateTask(H.id,{status:"running"});let z=JSON.parse(H.payload),K,$;switch(H.type){case"command":{let X=await $2(z,V?.timeout);K=X,$=X.exitCode;break}case"script":{let X=await z2(z,V?.timeout);K=X,$=X.exitCode;break}case"file_operation":K=await Y2(z);break;default:throw Error(`Unknown task type: ${H.type}`)}let Y=$!==void 0&&$!==0,W=Y?"failed":"completed";if(await j.updateTask(H.id,{status:W,result:JSON.stringify(K),...$!==void 0&&{exitCode:$},...Y&&{error:`Process exited with code ${$}`}}),V?.callbackUrl)P(V.callbackUrl,{agentTaskId:H.id,status:W,result:K,exitCode:$,...Y&&{error:`Process exited with code ${$}`}})}catch(Z){let z=Z instanceof Error?Z.message:String(Z);try{await j.updateTask(H.id,{status:"failed",error:z})}catch(K){console.warn(`[task] failed to mark task ${H.id} as failed: ${K instanceof Error?K.message:String(K)}`)}if(V?.callbackUrl)P(V.callbackUrl,{agentTaskId:H.id,status:"failed",error:z})}finally{Q.active=Math.max(0,Q.active-1)}}function P(j,H){fetch(j,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(H),signal:AbortSignal.timeout(1e4)}).catch(()=>{})}function c(j){let{db:H}=j,Q={active:0};return new h().get("/",async({query:V})=>{if(V.status==="pending")return{tasks:await H.getPendingTasks()};return{tasks:await H.getAllTasks()}}).get("/:id",async({params:V,set:Z})=>{let z=await H.getTask(V.id);if(!z)return Z.status=404,{error:"Task not found"};return{task:z}}).post("/legacy",async({body:V,set:Z})=>{try{return{task:await H.createTask({id:globalThis.crypto.randomUUID(),type:"file_operation",status:"completed",payload:JSON.stringify({operation:"exists",path:process.cwd(),meta:V}),result:JSON.stringify({legacy:!0,note:"Legacy doctor-script task accepted (no-op)."})})}}catch(z){return Z.status=500,{error:"Failed to create task",details:String(z)}}},{body:I.Any()}).post("/",async({body:V,request:Z,server:z,set:K})=>{let $=V;if($&&typeof $==="object"&&!$.type&&!$.payload&&($.title||$.description||$.command))try{return{task:await H.createTask({id:globalThis.crypto.randomUUID(),type:"file_operation",status:"completed",payload:JSON.stringify({operation:"exists",path:process.cwd(),meta:$}),result:JSON.stringify({legacy:!0,note:"Legacy doctor-script task accepted (no-op)."})})}}catch(W){return K.status=500,{error:"Failed to create task",details:String(W)}}let Y=V;try{if(Y.type==="command"||Y.type==="script"){let X=await L(Z,"VIBECONTROLS_ALLOW_REMOTE_SHELL_TASK",z,{getConfig:(G)=>H.getConfig(G)});if(X)return K.status=403,{error:"Forbidden",message:X}}else if(Y.type==="file_operation"&&["write","delete"].includes(String(Y.payload?.operation??""))){let X=await L(Z,"VIBECONTROLS_ALLOW_REMOTE_FILE_TASK",z,{getConfig:(G)=>H.getConfig(G)});if(X)return K.status=403,{error:"Forbidden",message:X}}if(Q.active>=j2)return K.status=429,{error:"Too many tasks are already running"};if(Q.active+=1,Y.callbackUrl&&!b(Y.callbackUrl,(()=>{let X=g.getConfig();return[X?.globalGatewayUrl,X?.workspaceGatewayUrl]})()))return Q.active=Math.max(0,Q.active-1),K.status=400,{error:"callbackUrl is not allowed"};let W=await H.createTask({id:globalThis.crypto.randomUUID(),type:Y.type,status:"pending",payload:JSON.stringify(Y.payload),...Y.calendarTaskId&&{calendarTaskId:Y.calendarTaskId},...Y.timeout&&{timeout:Y.timeout}});return K2(H,W,Q,{timeout:Y.timeout,callbackUrl:Y.callbackUrl}),{task:W}}catch(W){return Q.active=Math.max(0,Q.active-1),K.status=500,{error:"Failed to create task",details:String(W)}}},{body:I.Any()}).post("/:id/cancel",async({params:V,set:Z})=>{let z=await H.getTask(V.id);if(!z)return Z.status=404,{error:"Task not found"};if(z.status!=="pending")return Z.status=400,{error:"Only pending tasks can be cancelled"};return await H.updateTask(V.id,{status:"failed",error:"Task cancelled by user"}),{success:!0}}).delete("/:id",async({params:V,set:Z})=>{let z=await H.getTask(V.id);if(!z)return Z.status=404,{error:"Task not found"};if(z.status==="pending")await H.updateTask(V.id,{status:"failed",error:"Task cancelled via DELETE"});return{success:!0,status:z.status}})}var U="http://localhost:3005";function F(j){return`/api/profiles/${encodeURIComponent(y(j))}/tasks`}function o(j){let H=j.command("task").description("Manage background tasks");H.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",U).option("--json","Emit JSON").option("--plain","Force plain text output").action(async function(Q){let V={...j.opts(),...Q};try{let Z=C(Q),z=F(V),K=Q.status?`${z}/?status=${encodeURIComponent(Q.status)}`:`${z}/`;await d({mode:p(V),fetchData:async()=>{return(await l(Z,K)).tasks||[]},plain:($)=>{if(!$||$.length===0){A("No tasks found.");return}S("Tasks"),i($.map((Y)=>({ID:x(Y.id),Type:Y.type||"-",Status:f(Y.status),Created:Y.createdAt?E(Y.createdAt):"-"})))},interactive:async($)=>{if(!$||$.length===0){S("Tasks"),A("No tasks found.");return}let Y=$.map((W)=>({id:String(W.id),label:W.type||x(W.id),hint:W.status||"",detail:[`ID: ${W.id}`,`Type: ${W.type??"-"}`,`Status: ${f(W.status)}`,`Created: ${W.createdAt?E(W.createdAt):"-"}`].join(`
|
|
5
5
|
`)}));await r({title:`vibe task list \u2014 ${$.length} task(s)`,rows:Y})},json:($)=>$.map((Y)=>({id:Y.id,type:Y.type??null,status:Y.status??null,createdAt:Y.createdAt??null}))})}catch(Z){O(q(Z))}}),H.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",U).option("--json","Emit JSON").action(async function(Q){let V={...j.opts(),...Q};try{let Z=C(Q);if(!n(Z)&&process.env.VIBECONTROLS_ALLOW_REMOTE_SHELL_TASK!=="1"){if(V.json){w(V,{ok:!1,error:"Remote shell task refused without env override"});return}O("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 z={command:Q.command};if(Q.cwd)z.cwd=Q.cwd;let K=F(V),$=await T(Z,`${K}/`,{type:"command",payload:z}),Y=$?.task?.id||$?.id||$?.taskId;if(w(V,{ok:!0,id:Y}))return;if(!Y){O("Task created but no ID returned by the agent");return}B(`Task created: ${x(Y)}`)}catch(Z){if(V.json){w(V,{ok:!1,error:q(Z)});return}O(q(Z))}}),H.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",U).option("--json","Emit JSON").action(async function(Q){let V={...j.opts(),...Q};try{let Z=C(Q),z=F(V);if(await T(Z,`${z}/${Q.id}/cancel`,{}),w(V,{ok:!0,id:Q.id}))return;B(`Task ${x(Q.id)} cancelled.`)}catch(Z){if(V.json){w(V,{ok:!1,error:q(Z)});return}O(q(Z))}})}function s(j,H){o(j)}function U2(j){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:(H)=>c(H),onCliSetup:async(H,Q)=>{s(H,Q)}}}export{U2 as createPlugin};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
2
|
function z(){let j=process.env.VIBECONTROLS_LOG_SHIP_URL;if(!j)return null;return{url:j,apiKey:process.env.VIBECONTROLS_LOG_SHIP_API_KEY,batchSize:Number.parseInt(process.env.VIBECONTROLS_LOG_SHIP_BATCH??"",10)||100,intervalMs:Number.parseInt(process.env.VIBECONTROLS_LOG_SHIP_INTERVAL_MS??"",10)||1e4,sampleRate:Number.parseFloat(process.env.VIBECONTROLS_LOG_SHIP_SAMPLE??"1")}}var k=1000;class s{config=null;queue=[];timer=null;inFlight=!1;dropped=0;init(){if(this.config)return;if(this.config=z(),!this.config)return;if(this.timer=setInterval(()=>{this.flush()},this.config.intervalMs),this.timer&&typeof this.timer.unref==="function")this.timer.unref()}enqueue(j){if(!this.config)return;if(j.level==="debug"&&this.config.sampleRate<1&&Math.random()>this.config.sampleRate)return;if(this.queue.length>=k)this.dropped+=1,this.queue.shift();this.queue.push(j)}async flush(){if(!this.config||this.inFlight||this.queue.length===0)return;this.inFlight=!0;let j=this.queue.splice(0,this.config.batchSize);try{await fetch(this.config.url,{method:"POST",headers:{"Content-Type":"application/json",...this.config.apiKey?{Authorization:`Bearer ${this.config.apiKey}`}:{}},body:JSON.stringify({entries:j,dropped:this.dropped}),signal:AbortSignal.timeout(5000)}),this.dropped=0}catch{this.queue=[...j,...this.queue].slice(0,k)}finally{this.inFlight=!1}}stop(){if(this.timer)clearInterval(this.timer),this.timer=null;this.flush()}}var B=new s;
|
|
3
|
-
export{B as
|
|
3
|
+
export{B as fe};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Sa as k}from"./index-
|
|
2
|
+
import{Sa as k}from"./index-5wsfsj88.js";import{Eb as F,Fb as h,Gb as S,Hb as q,Jb as N,wb as f,zb as c}from"./index-9g3vxhby.js";import{Vb as P}from"./index-zaw78sxw.js";import{Pd as V}from"./index-c4p1qcnn.js";var U=["tunnel","session","ai","plan","gitops","security"];class m{providers=new Map;providerOrder=new Map;defaults=new Map;services=new Map;db;constructor(z){this.db=z}getDb(){return this.db}setProviderDefault(z,J){this.defaults.set(z,J)}clearProviderDefault(z,J){if(!J||this.defaults.get(z)===J)this.defaults.delete(z)}async hydrateDefaultsFromDb(){if(!this.db)return;for(let z of U)try{let J=await this.db.getConfig(`provider:default:${z}`);if(J)this.defaults.set(z,J)}catch{}}registerProvider(z,J,Q){if(!this.providers.has(z))this.providers.set(z,new Map),this.providerOrder.set(z,[]);let W=this.providers.get(z),Z=this.providerOrder.get(z);if(W.has(Q))V().logger.info("service-registry",`Updating ${z} provider from plugin '${Q}'`);else V().logger.info("service-registry",`Registered ${z} provider from plugin '${Q}'`);if(W.set(Q,{provider:J,pluginName:Q,registeredAt:new Date}),!Z.includes(Q))Z.push(Q)}getProvider(z){let J=this.providers.get(z);if(!J||J.size===0)return;let Q=this.defaults.get(z);if(Q&&J.has(Q))return J.get(Q).provider;let W=this.providerOrder.get(z);if(W&&W.length>0){let Z=W[0];return J.get(Z)?.provider}return}getProviderByName(z,J){let Q=this.providers.get(z);if(!Q)return;return Q.get(J)?.provider}hasProvider(z){let J=this.providers.get(z);return!!J&&J.size>0}unregisterProvider(z,J){let Q=this.providers.get(z);if(!Q)return!1;let W=Q.delete(J);if(W){let Z=this.providerOrder.get(z);if(Z){let X=Z.indexOf(J);if(X!==-1)Z.splice(X,1)}this.clearProviderDefault(z,J),V().logger.info("service-registry",`Unregistered ${z} provider from plugin '${J}'`)}return W}unregisterPlugin(z){for(let J of U)this.unregisterProvider(J,z);this.unregisterServices(z)}listProvidersForType(z){let J=this.providers.get(z);if(!J)return[];let Q=this.defaults.get(z);if(!Q||!J.has(Q)){let W=this.providerOrder.get(z);Q=W&&W.length>0?W[0]:void 0}return Array.from(J.keys()).map((W)=>({pluginName:W,isDefault:W===Q}))}registerService(z,J,Q){let W=`${z}:${J}`;this.services.set(W,{service:Q,pluginName:z}),V().logger.debug("service-registry",`Registered service '${W}'`)}getService(z,J){let Q=`${z}:${J}`;return this.services.get(Q)?.service}unregisterServices(z){let J=[];for(let[Q,W]of this.services)if(W.pluginName===z)J.push(Q);for(let Q of J)this.services.delete(Q);if(J.length>0)V().logger.info("service-registry",`Unregistered ${J.length} services from ${z}`)}listProviders(){let z=[];for(let[J,Q]of this.providers)for(let[W,Z]of Q)z.push({type:J,name:W,pluginName:Z.pluginName});return z}listServices(){return Array.from(this.services.entries()).map(([z,J])=>({pluginName:J.pluginName,serviceName:z.split(":").slice(1).join(":")}))}clear(){this.providers.clear(),this.providerOrder.clear(),this.defaults.clear(),this.services.clear()}}import{extname as g,relative as o,resolve as u}from"path";import{realpath as E}from"fs/promises";var n=["'self'","http://localhost:*","http://127.0.0.1:*","https://localhost:*","https://127.0.0.1:*","https://*.local.burdenoff.com","https://vibecontrols.com","https://*.vibecontrols.com","https://burdenoff.com","https://app.burdenoff.com","https://alphaapp.burdenoff.com"],D=!1;function w(){let z=process.env.VIBE_UI_FRAME_ANCESTORS?.trim(),J=z?z.split(/[\s,]+/).filter(Boolean):n;if(z&&!D&&(J.includes("*")||!J.includes("'self'")))D=!0,console.warn(`[ui-server] VIBE_UI_FRAME_ANCESTORS override does not include "'self'" or contains "*". This significantly weakens CSP frame-ancestors and is almost never intended. Override: ${z}`);return`frame-ancestors ${J.join(" ")}`}var l={".html":"text/html",".js":"application/javascript",".mjs":"application/javascript",".css":"text/css",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".map":"application/json",".wasm":"application/wasm"};function s(z){return l[g(z).toLowerCase()]||"application/octet-stream"}var b=`<script>
|
|
3
3
|
window.__VIBE_AUTH__={apiKey:null};
|
|
4
4
|
(function(){
|
|
5
5
|
var p=new URLSearchParams(window.location.search);
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
2
|
import{isAbsolute as S,join as Z,relative as v,resolve as H}from"path";import{existsSync as E,readFileSync as m}from"fs";import{homedir as u}from"os";import{existsSync as F,mkdirSync as P,readFileSync as V,renameSync as j,writeFileSync as w}from"fs";import{homedir as I}from"os";import{dirname as N,join as U,resolve as b}from"path";var Q=new Map;async function B(q,z){let J=Q.get(q)??Promise.resolve(),$,K=new Promise((W)=>{$=W});Q.set(q,J.then(()=>K));try{return await J,await z()}finally{if($(),Q.get(q)===J.then(()=>K));queueMicrotask(()=>{let W=Q.get(q);if(!W)return;Promise.race([W,new Promise((D)=>{D(void 0)})]).then(()=>{if(Q.get(q)===W)Q.delete(q)})})}}var A="agents-registry";async function s(q){return B(A,q)}function T(){return b(process.env.VIBECONTROLS_HOME??U(I(),".boff","vibecontrols"))}var C=2,k="default";function M(){return U(T(),"agents.json")}function _(){let q=M();if(!F(q))return null;try{let z=JSON.parse(V(q,"utf8"));if(z&&typeof z==="object"&&!Array.isArray(z)&&"instances"in z)return z;return null}catch{return null}}function X(){let q=_();if(!q)return{schemaVersion:C,instances:[]};return q}function Y(q){let z=M();P(N(z),{recursive:!0});let J=`${z}.${process.pid}.tmp`,$={...q,schemaVersion:C};w(J,`${JSON.stringify($,null,2)}
|
|
3
3
|
`,{encoding:"utf8",mode:384}),j(J,z)}function o(){return X().instances}function a(q){let z=X();Y({...z,instances:q})}function O(){try{let z=X().defaultProfile;if(z&&typeof z==="string"&&z.length>0)return z}catch{}return k}function n(q){if(!q||typeof q!=="string")throw Error("setDefaultProfile: name is required");let z=X();Y({...z,defaultProfile:q})}var R=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/,p=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;function G(q){if(!R.test(q))throw Error("Invalid VIBECONTROLS_PROFILE. Use 1-128 characters: letters, numbers, dot, underscore, or dash.");return q}function h(){let q=process.env.VIBECONTROLS_PROFILE;if(q)return G(q);let z=O();return G(z)}function zq(q){if(!p.test(q))throw Error("Agent name must use 1-64 characters: letters, numbers, dot, underscore, or dash.");return q}function Jq(q,z){let J=v(H(q),H(z));return J===""||!!J&&!J.startsWith("..")&&!S(J)}function L(){let q=x(),z=h();return Z(q,"agents",z)}function Qq(){return Z(x(),"agents")}function Wq(){return Z(L(),"agent-db")}function x(){return H(process.env.VIBECONTROLS_HOME??Z(u(),".boff","vibecontrols"))}var y="https://registry.npmjs.org/";function Zq(){if(process.env.VIBECONTROLS_REGISTRY)return process.env.VIBECONTROLS_REGISTRY;try{let q=Z(L(),"config.json");if(E(q)){let z=JSON.parse(m(q,"utf8"));if(z.registry)return z.registry}}catch{}return y}
|
|
4
|
-
export{B as
|
|
4
|
+
export{B as Sd,s as Td,o as Ud,a as Vd,O as Wd,n as Xd,G as Yd,h as Zd,zq as _d,Jq as $d,L as ae,Qq as be,Wq as ce,x as de,Zq as ee};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
2
|
+
import{he as q,je as b}from"./index-gb5bnx7a.js";var z=q((f)=>{Object.defineProperty(f,"__esModule",{value:!0});f.execAsync=void 0;var v=b("child_process"),w=b("util");f.execAsync=w.promisify(v.exec)});
|
|
3
3
|
export{z as f};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{h as y,i as c}from"./index-cs78wq6y.js";import{A as p$,B as i$,y as l$}from"./index-
|
|
3
|
-
`);return}if(w)await w(O);if($)O.telemetry?.emit($,{plugin:W})},onServerStop:async(I)=>{if(U)await U(I)},onNuke:async(I,O)=>{if(R)return R(I,O)}}}var e=class{constructor(f,W){this.logger=f,this.source=W}logger;source;info(f,W){this.logger?.info?.(this.source,f,W)}warn(f,W){this.logger?.warn?.(this.source,f,W)}error(f,W){this.logger?.error?.(this.source,f,W)}debug(f,W){this.logger?.debug?.(this.source,f,W)}};import{existsSync as t$,rmSync as e$,statSync as a$}from"fs";import{resolve as $U}from"path";function R$(f=$$()){let W=[],w=$U(f),U=U$();if(!a(U,w))throw Error("Refusing to reset a path outside the agents directory");if(t$(w)&&a$(w).isDirectory())e$(w,{recursive:!0,force:!0}),W.push(w);return{removed:W,agentDir:w}}var S="alias",G$=/^[a-zA-Z0-9_-]{1,64}$/,w$=16384,f$=256,W$=1024,UU=new Set(["help","start","stop","restart","kill","list","status","setup","update","completion","autostart","export","import","diagnostics","nuke","doctor","log-level","gc","deploy","network","profile","peer-bootstrap","gateway-auth","info","key","system","url","health","notify","tunnel","session","git","config","log","plugin","ai","audit","alias","run"]);class D extends Error{code;constructor(f,W){super(W);this.code=f,this.name="AliasValidationError"}}class E extends Error{constructor(f){super(`alias '${f}' already exists`);this.name="AliasConflictError"}}class P extends Error{constructor(f){super(`alias '${f}' not found`);this.name="AliasNotFoundError"}}function RU(f){if(typeof f!=="string"||!G$.test(f))throw new D("invalid_name",`alias name must match ${G$} (got '${f}')`);if(UU.has(f))throw new D("reserved_name",`alias name '${f}' is reserved`)}function I$(f){if(typeof f!=="string"||f.length===0)throw new D("invalid_command","alias command must be a non-empty string");if(f.length>w$)throw new D("command_too_long",`alias command exceeds ${w$} bytes`)}function O$(f){if(f===void 0)return;if(typeof f!=="string")throw new D("invalid_description","alias description must be a string");if(f.length>f$)throw new D("description_too_long",`alias description exceeds ${f$} chars`)}function F$(f){if(f===void 0||f===null||f==="")return;if(typeof f!=="string")throw new D("invalid_cwd","alias cwd must be a string");if(f.length>W$)throw new D("cwd_too_long",`alias cwd exceeds ${W$} chars`);if(f.includes("\x00"))throw new D("invalid_cwd","alias cwd must not contain NUL bytes")}function GU(f){if(!f)return;try{return JSON.parse(f)}catch{return}}async function i(f){let W=await f.getAllPluginState(S),w=[];for(let U of W){let R=GU(U.value);if(R)w.push(R)}return w.sort((U,R)=>U.name.localeCompare(R.name)),w}async function n(f,W){return(await i(f)).find((U)=>U.name===W)}function V$(f){if(f===void 0||f===null)return null;let W=f.trim();return W===""?null:W}async function Q$(f,W){if(RU(W.name),I$(W.command),O$(W.description),F$(W.cwd),await n(f,W.name))throw new E(W.name);let U=new Date().toISOString(),R={id:crypto.randomUUID(),name:W.name,command:W.command,description:W.description,cwd:V$(W.cwd),profile:J$(),createdAt:U,updatedAt:U};return await f.setPluginState(S,R.id,JSON.stringify(R)),R}async function Z$(f,W,w){let U=await n(f,W);if(!U)throw new P(W);if(w.command!==void 0)I$(w.command);if(w.description!==void 0)O$(w.description);if(w.cwd!==void 0)F$(w.cwd);let R={...U,command:w.command??U.command,description:w.description!==void 0?w.description:U.description,cwd:w.cwd!==void 0?V$(w.cwd):U.cwd,updatedAt:new Date().toISOString()};return await f.setPluginState(S,R.id,JSON.stringify(R)),R}async function B$(f,W){let w=await n(f,W);if(!w)throw new P(W);await f.deletePluginState(S,w.id)}function m(){let f=q$()??q();return{dir:f.dataDir,scope:f.name}}function M$(f){let{serviceRegistry:W,db:w}=f;return new p().get("/api-key",()=>({apiKey:C$()})).post("/reset-key",async({body:U,set:R})=>{let $=U.apiKey;if(!$||typeof $!=="string")return R.status=400,{error:"Missing required field: apiKey"};try{return await D$($),await q().keyVault.bindApiKey($),q().logger.info("auth","Adopted backend-rotated agent API key via /reset-key"),{success:!0}}catch(G){return R.status=400,{error:"reset-key failed",message:G instanceof Error?G.message:String(G)}}},{body:F.Object({apiKey:F.String()})}).get("/audit",({query:U})=>{let R=U,$=R.limit?Math.min(5000,Math.max(1,Number.parseInt(R.limit,10)||100)):100,G=q().audit.listEvents({since:R.since,limit:$,event:R.event});return{events:G,count:G.length}},{query:F.Object({since:F.Optional(F.String()),limit:F.Optional(F.String()),event:F.Optional(F.String())})}).get("/setup/check",()=>{let U=H$();return{ready:U.filter(($)=>$.required).every(($)=>$.installed),dependencies:U}}).post("/setup/install",async({request:U,server:R,set:$})=>{let G=await c(U,"VIBECONTROLS_ALLOW_REMOTE_SETUP_INSTALL",R);if(G)return $.status=403,{error:"Forbidden",message:G};return await K$()}).get("/url",async()=>{let U=W.getProvider("tunnel"),R=U&&U.getActiveTunnelUrl?await U.getActiveTunnelUrl():null,$=`http://localhost:${process.env.PORT||3005}`;return{url:R||$,tunnelUrl:R,localUrl:$,source:R?"tunnel":"local"}}).get("/lifecycle/state",()=>{return{state:W.getService("agent","lifecycle")?.getState()??"running"}}).post("/lifecycle/stop",async({set:U})=>{let R=W.getService("agent","lifecycle");if(!R)return U.status=500,{error:"Lifecycle manager not initialized"};return await R.stop(),{state:"stopped"}}).post("/lifecycle/start",async({set:U})=>{let R=W.getService("agent","lifecycle");if(!R)return U.status=500,{error:"Lifecycle manager not initialized"};return await R.start(),{state:"running"}}).post("/lifecycle/kill",async({set:U})=>{let R=W.getService("agent","lifecycle");if(!R)return U.status=500,{error:"Lifecycle manager not initialized"};return setTimeout(()=>R.kill(),100),{state:"killing"}}).post("/log-level",async({body:U,request:R,server:$,set:G})=>{let I=await c(R,"VIBECONTROLS_ALLOW_REMOTE_LOG_LEVEL",$);if(I)return G.status=403,{error:"Forbidden",message:I};let O=String(U.level??"").toLowerCase();if(!["debug","info","warn","error"].includes(O))return G.status=400,{error:"Invalid level",message:"level must be debug | info | warn | error"};return q().logger.setLevel(O),q().logger.info("agent",`Log level set to ${O} via API`),{ok:!0,level:O}},{body:F.Object({level:F.String()})}).post("/reset",async({body:U,request:R,server:$,set:G})=>{if(!U.confirm)return G.status=400,{error:"Reset confirmation required",message:"Send { confirm: true } to reset local agent state."};let I=await c(R,"VIBECONTROLS_ALLOW_REMOTE_RESET",$);if(I)return G.status=403,{error:"Forbidden",message:I};let O=W.getService("agent","lifecycle");try{if(O)await O.prepareForReset()}catch(h){q().logger.warn("agent","prepareForReset failed during reset \u2014 proceeding to wipe anyway",{error:String(h)})}try{z$.configure({globalGatewayUrl:"",workspaceGatewayUrl:void 0,clientId:"",clientSecret:"",workspaceId:void 0})}catch{}await w.close();let{removed:B,agentDir:L}=R$();q().logger.info("agent","Reset wiped local agent state",{agentDir:L,removed:B});let C=new Uint8Array(32);crypto.getRandomValues(C);let j=`vcak_${Buffer.from(C).toString("base64url")}`;return T$({"static-api-key":j},m()),q().setBootState("awaiting-config"),G.status=200,{success:!0,state:"awaiting-config",...y(R,$)||process.env.VIBECONTROLS_RETURN_RESET_API_KEY==="1"?{newApiKey:j}:{},agentDir:L,removed:B}},{body:F.Object({confirm:F.Boolean()})}).post("/sessions/:sessionId/share",async({params:U,body:R,server:$,request:G,set:I})=>{if(!y(G,$)&&process.env.VIBECONTROLS_ALLOW_REMOTE_SESSION_SHARE!=="1")return I.status=403,{error:"Forbidden",message:"Session-share mint must come from a local request unless VIBECONTROLS_ALLOW_REMOTE_SESSION_SHARE=1."};if(!X$(U.sessionId))return I.status=400,{error:"BadRequest",message:"invalid sessionId"};let O=wU(R?.expiresIn)??1800000,B=crypto.randomUUID(),L=new Uint8Array(32);crypto.getRandomValues(L);let C=`vcak_${Buffer.from(L).toString("base64url")}`,j=new Date(Date.now()+O).toISOString(),r=[...(await import("./agent-config-pxkfd7ec.js")).readAgentConfig({dir:m().dir}).apiKeys??[],{id:B,name:`session-share:${U.sessionId}:${R?.label??"viewer"}`,key:C,scopes:["read"],expiresAt:j,createdAt:new Date().toISOString()}];(await import("./agent-config-pxkfd7ec.js")).writeAgentConfig({apiKeys:r},m());let h=W.getProvider("tunnel"),d$=(h&&h.getActiveTunnelUrl?await h.getActiveTunnelUrl():null)??`http://localhost:${process.env.PORT||3005}`,s$=L$({pathPrefixes:[`/terminal/${U.sessionId}`],methods:["GET"]},Math.min(600,Math.floor(O/1000))),r$=`${d$.replace(/\/$/,"")}/terminal/${encodeURIComponent(U.sessionId)}/#vt=${encodeURIComponent(s$.token)}`;return q().logger.info("session-share","Minted share credential",{sessionId:U.sessionId,keyId:B,expiresAt:j}),{ok:!0,keyId:B,apiKey:C,joinUrl:r$,sessionId:U.sessionId,expiresAt:j}},{params:F.Object({sessionId:F.String()}),body:F.Optional(F.Object({permissions:F.Optional(F.Array(F.String())),expiresIn:F.Optional(F.String()),label:F.Optional(F.String())}))}).get("/aliases",async()=>{return{aliases:await i(w)}}).get("/aliases/:name",async({params:U,set:R})=>{let $=await n(w,U.name);if(!$)return R.status=404,{error:"Alias not found"};return $},{params:F.Object({name:F.String()})}).post("/aliases",async({body:U,set:R})=>{try{let $=await Q$(w,U);return R.status=201,$}catch($){if($ instanceof E)return R.status=409,{error:"Alias already exists",message:$.message};if($ instanceof D)return R.status=400,{error:$.code,message:$.message};throw $}},{body:F.Object({name:F.String(),command:F.String(),description:F.Optional(F.String()),cwd:F.Optional(F.Union([F.String(),F.Null()]))})}).put("/aliases/:name",async({params:U,body:R,set:$})=>{try{return await Z$(w,U.name,R)}catch(G){if(G instanceof P)return $.status=404,{error:"Alias not found"};if(G instanceof D)return $.status=400,{error:G.code,message:G.message};throw G}},{params:F.Object({name:F.String()}),body:F.Object({command:F.Optional(F.String()),description:F.Optional(F.String()),cwd:F.Optional(F.Union([F.String(),F.Null()]))})}).delete("/aliases/:name",async({params:U,set:R})=>{try{return await B$(w,U.name),R.status=204,null}catch($){if($ instanceof P)return R.status=404,{error:"Alias not found"};throw $}},{params:F.Object({name:F.String()})}).post("/aliases/:name/execute",async({params:U,body:R,set:$})=>{let G=await n(w,U.name);if(!G)return $.status=404,{error:"Alias not found"};let I=R?.args??[],O=await j$(G,I);q().audit.emit("agent","alias.executed",{exit_code:O.exit_code});let B=Y$("alias.executed",{exit_code:O.exit_code});if(!B.ok)q().logger.debug("alias",`telemetry validate failed: ${B.reason}`);if(O.timed_out)$.status=408;return{exit_code:O.exit_code,stdout:O.stdout,stderr:O.stderr,duration_ms:O.duration_ms,truncated:O.truncated,cwd:O.cwd}},{params:F.Object({name:F.String()}),body:F.Optional(F.Object({args:F.Optional(F.Array(F.String()))}))}).post("/sessions/share/:keyId/revoke",async({params:U,server:R,request:$,set:G})=>{if(!y($,R)&&process.env.VIBECONTROLS_ALLOW_REMOTE_SESSION_SHARE!=="1")return G.status=403,{error:"Forbidden"};let I=await import("./agent-config-pxkfd7ec.js"),O=m(),B=I.readAgentConfig({dir:O.dir}),L=(B.apiKeys??[]).length,C=(B.apiKeys??[]).filter((j)=>j.id!==U.keyId);if(C.length===L)return G.status=404,{error:"No such share key"};return I.writeAgentConfig({apiKeys:C},O),{ok:!0,revoked:U.keyId}},{params:F.Object({keyId:F.String()})})}function wU(f){if(!f)return null;let W=/^(\d+)([smhdw]?)$/.exec(f.trim());if(!W)return null;let w=Number(W[1]),U=W[2]||"m";return U==="s"?w*1000:U==="m"?w*60000:U==="h"?w*3600000:U==="d"?w*86400000:w*7*86400000}var fU="http://localhost:3005";function x$(f){f.command("health").description("Check health of a VibeControls agent instance").option("-n, --name <name>","Agent instance name").option("--agent-url <url>","Agent URL",fU).option("--json","Emit JSON").option("--plain","Force plain text output").action(async function(W){try{let w={...f.opts(),...W};await _({mode:x(w),fetchData:async()=>{if(w.name){let $=await new g().checkHealth(w.name);return{mode:"named",agentUrl:T(w),name:w.name,healthy:$.healthy,details:$.details??{}}}let U=T(w);try{let R=await M(U,"/health");return{mode:"url",agentUrl:U,healthy:!0,details:R}}catch(R){return{mode:"url",agentUrl:U,healthy:!1,details:{status:"unhealthy",...R instanceof Error?{error:H(R)}:{}}}}},plain:(U)=>{if(X("Agent Health"),Q(),U.mode==="named"){if(!U.healthy){Y(`Agent instance ${V.bold(U.name??"")} is not responding.`);return}let R=U.details;if(J("Instance",U.name??""),J("Status",u(R.status??"healthy")),R.uptime!==void 0)J("Uptime",`${R.uptime}s`);if(R.checks){Q(),z(`${Z.info} Health checks:`);for(let[$,G]of Object.entries(R.checks)){let I=G.status==="healthy"?Z.success:Z.error;J(` ${I} ${$}`,u(G.status))}}}else{if(J("URL",U.agentUrl),J("Status",u(U.details.status??"unhealthy")),U.details.version)J("Version",U.details.version);if(U.details.uptime!==void 0)J("Uptime",`${U.details.uptime}s`);if(U.details.timestamp)J("Timestamp",U.details.timestamp);if(U.details.checks){Q(),z(`${Z.info} Health checks:`);for(let[R,$]of Object.entries(U.details.checks)){let G=$.status==="healthy"?Z.success:Z.error;J(` ${G} ${R}`,u($.status))}}}if(Q(),U.healthy)A(`${Z.success} Agent is healthy.`)},interactive:async(U)=>{let R=[];if(U.mode==="named")R.push(`Instance: ${U.name??""}`);else R.push(`URL: ${U.agentUrl}`);if(R.push(`Status: ${u(U.details.status??(U.healthy?"healthy":"unhealthy"))}`),U.details.version)R.push(`Version: ${U.details.version}`);if(U.details.uptime!==void 0)R.push(`Uptime: ${U.details.uptime}s`);if(U.details.timestamp)R.push(`Time: ${U.details.timestamp}`);if(U.details.checks){R.push(""),R.push("Checks:");for(let[$,G]of Object.entries(U.details.checks))R.push(` ${$}: ${G.status}`)}await K({title:"Agent Health",body:R.join(`
|
|
2
|
+
import{h as y,i as c}from"./index-cs78wq6y.js";import{A as p$,B as i$,y as l$}from"./index-jrxbbb7p.js";import{N as j$}from"./index-b5dhmybd.js";import{O as H$,P as K$}from"./index-e1bw1bwr.js";import{va as g}from"./index-2gwc485c.js";import"./index-pc05r6fd.js";import{Ca as k$}from"./index-4wgjx8bf.js";import"./index-5wsfsj88.js";import"./index-0ckffygp.js";import{ab as v}from"./index-rc79x8fw.js";import{db as Y$}from"./index-52cp759f.js";import"./index-m2kkd6t6.js";import{Jb as C$,Kb as D$,tb as X$,vb as L$}from"./index-9g3vxhby.js";import"./index-5dysvvjv.js";import{Ub as F,Vb as p}from"./index-zaw78sxw.js";import{Xb as g$}from"./index-jqfsvf8f.js";import"./index-g9fthh7a.js";import{jc as x,kc as _,lc as c$}from"./index-8nqp3a4d.js";import{Ac as s,Bc as N,Cc as u,oc as V,pc as Z,qc as Y,rc as H,sc as A,uc as z,vc as X,wc as J,xc as Q,yc as h$,zc as k}from"./index-c975k3pk.js";import{Hc as K}from"./index-0s81cfpe.js";import{Lc as T,Nc as b,Oc as M,Pc as y$}from"./index-e2dqz3tw.js";import{qd as T$}from"./index-sv4rzv3f.js";import{Jd as z$,Md as q$,Pd as q}from"./index-c4p1qcnn.js";import{$d as a,Zd as J$,ae as $$,be as U$}from"./index-q9dp55wv.js";import"./index-ntj6ymk8.js";import{je as d}from"./index-gb5bnx7a.js";function t(f){let{name:W,onInit:w,onShutdown:U,onNuke:R,telemetryEventName:$,skipPlatforms:G}=f;return{onServerStart:async(I,O)=>{if(G&&G.includes(process.platform)){process.stderr.write(`[${W}] skipping init on unsupported platform '${process.platform}'
|
|
3
|
+
`);return}if(w)await w(O);if($)O.telemetry?.emit($,{plugin:W})},onServerStop:async(I)=>{if(U)await U(I)},onNuke:async(I,O)=>{if(R)return R(I,O)}}}var e=class{constructor(f,W){this.logger=f,this.source=W}logger;source;info(f,W){this.logger?.info?.(this.source,f,W)}warn(f,W){this.logger?.warn?.(this.source,f,W)}error(f,W){this.logger?.error?.(this.source,f,W)}debug(f,W){this.logger?.debug?.(this.source,f,W)}};import{existsSync as t$,rmSync as e$,statSync as a$}from"fs";import{resolve as $U}from"path";function R$(f=$$()){let W=[],w=$U(f),U=U$();if(!a(U,w))throw Error("Refusing to reset a path outside the agents directory");if(t$(w)&&a$(w).isDirectory())e$(w,{recursive:!0,force:!0}),W.push(w);return{removed:W,agentDir:w}}var S="alias",G$=/^[a-zA-Z0-9_-]{1,64}$/,w$=16384,f$=256,W$=1024,UU=new Set(["help","start","stop","restart","kill","list","status","setup","update","completion","autostart","export","import","diagnostics","nuke","doctor","log-level","gc","deploy","network","profile","peer-bootstrap","gateway-auth","info","key","system","url","health","notify","tunnel","session","git","config","log","plugin","ai","audit","alias","run"]);class D extends Error{code;constructor(f,W){super(W);this.code=f,this.name="AliasValidationError"}}class E extends Error{constructor(f){super(`alias '${f}' already exists`);this.name="AliasConflictError"}}class P extends Error{constructor(f){super(`alias '${f}' not found`);this.name="AliasNotFoundError"}}function RU(f){if(typeof f!=="string"||!G$.test(f))throw new D("invalid_name",`alias name must match ${G$} (got '${f}')`);if(UU.has(f))throw new D("reserved_name",`alias name '${f}' is reserved`)}function I$(f){if(typeof f!=="string"||f.length===0)throw new D("invalid_command","alias command must be a non-empty string");if(f.length>w$)throw new D("command_too_long",`alias command exceeds ${w$} bytes`)}function O$(f){if(f===void 0)return;if(typeof f!=="string")throw new D("invalid_description","alias description must be a string");if(f.length>f$)throw new D("description_too_long",`alias description exceeds ${f$} chars`)}function F$(f){if(f===void 0||f===null||f==="")return;if(typeof f!=="string")throw new D("invalid_cwd","alias cwd must be a string");if(f.length>W$)throw new D("cwd_too_long",`alias cwd exceeds ${W$} chars`);if(f.includes("\x00"))throw new D("invalid_cwd","alias cwd must not contain NUL bytes")}function GU(f){if(!f)return;try{return JSON.parse(f)}catch{return}}async function i(f){let W=await f.getAllPluginState(S),w=[];for(let U of W){let R=GU(U.value);if(R)w.push(R)}return w.sort((U,R)=>U.name.localeCompare(R.name)),w}async function n(f,W){return(await i(f)).find((U)=>U.name===W)}function V$(f){if(f===void 0||f===null)return null;let W=f.trim();return W===""?null:W}async function Q$(f,W){if(RU(W.name),I$(W.command),O$(W.description),F$(W.cwd),await n(f,W.name))throw new E(W.name);let U=new Date().toISOString(),R={id:crypto.randomUUID(),name:W.name,command:W.command,description:W.description,cwd:V$(W.cwd),profile:J$(),createdAt:U,updatedAt:U};return await f.setPluginState(S,R.id,JSON.stringify(R)),R}async function Z$(f,W,w){let U=await n(f,W);if(!U)throw new P(W);if(w.command!==void 0)I$(w.command);if(w.description!==void 0)O$(w.description);if(w.cwd!==void 0)F$(w.cwd);let R={...U,command:w.command??U.command,description:w.description!==void 0?w.description:U.description,cwd:w.cwd!==void 0?V$(w.cwd):U.cwd,updatedAt:new Date().toISOString()};return await f.setPluginState(S,R.id,JSON.stringify(R)),R}async function B$(f,W){let w=await n(f,W);if(!w)throw new P(W);await f.deletePluginState(S,w.id)}function m(){let f=q$()??q();return{dir:f.dataDir,scope:f.name}}function M$(f){let{serviceRegistry:W,db:w}=f;return new p().get("/api-key",()=>({apiKey:C$()})).post("/reset-key",async({body:U,set:R})=>{let $=U.apiKey;if(!$||typeof $!=="string")return R.status=400,{error:"Missing required field: apiKey"};try{return await D$($),await q().keyVault.bindApiKey($),q().logger.info("auth","Adopted backend-rotated agent API key via /reset-key"),{success:!0}}catch(G){return R.status=400,{error:"reset-key failed",message:G instanceof Error?G.message:String(G)}}},{body:F.Object({apiKey:F.String()})}).get("/audit",({query:U})=>{let R=U,$=R.limit?Math.min(5000,Math.max(1,Number.parseInt(R.limit,10)||100)):100,G=q().audit.listEvents({since:R.since,limit:$,event:R.event});return{events:G,count:G.length}},{query:F.Object({since:F.Optional(F.String()),limit:F.Optional(F.String()),event:F.Optional(F.String())})}).get("/setup/check",()=>{let U=H$();return{ready:U.filter(($)=>$.required).every(($)=>$.installed),dependencies:U}}).post("/setup/install",async({request:U,server:R,set:$})=>{let G=await c(U,"VIBECONTROLS_ALLOW_REMOTE_SETUP_INSTALL",R);if(G)return $.status=403,{error:"Forbidden",message:G};return await K$()}).get("/url",async()=>{let U=W.getProvider("tunnel"),R=U&&U.getActiveTunnelUrl?await U.getActiveTunnelUrl():null,$=`http://localhost:${process.env.PORT||3005}`;return{url:R||$,tunnelUrl:R,localUrl:$,source:R?"tunnel":"local"}}).get("/lifecycle/state",()=>{return{state:W.getService("agent","lifecycle")?.getState()??"running"}}).post("/lifecycle/stop",async({set:U})=>{let R=W.getService("agent","lifecycle");if(!R)return U.status=500,{error:"Lifecycle manager not initialized"};return await R.stop(),{state:"stopped"}}).post("/lifecycle/start",async({set:U})=>{let R=W.getService("agent","lifecycle");if(!R)return U.status=500,{error:"Lifecycle manager not initialized"};return await R.start(),{state:"running"}}).post("/lifecycle/kill",async({set:U})=>{let R=W.getService("agent","lifecycle");if(!R)return U.status=500,{error:"Lifecycle manager not initialized"};return setTimeout(()=>R.kill(),100),{state:"killing"}}).post("/log-level",async({body:U,request:R,server:$,set:G})=>{let I=await c(R,"VIBECONTROLS_ALLOW_REMOTE_LOG_LEVEL",$);if(I)return G.status=403,{error:"Forbidden",message:I};let O=String(U.level??"").toLowerCase();if(!["debug","info","warn","error"].includes(O))return G.status=400,{error:"Invalid level",message:"level must be debug | info | warn | error"};return q().logger.setLevel(O),q().logger.info("agent",`Log level set to ${O} via API`),{ok:!0,level:O}},{body:F.Object({level:F.String()})}).post("/reset",async({body:U,request:R,server:$,set:G})=>{if(!U.confirm)return G.status=400,{error:"Reset confirmation required",message:"Send { confirm: true } to reset local agent state."};let I=await c(R,"VIBECONTROLS_ALLOW_REMOTE_RESET",$);if(I)return G.status=403,{error:"Forbidden",message:I};let O=W.getService("agent","lifecycle");try{if(O)await O.prepareForReset()}catch(h){q().logger.warn("agent","prepareForReset failed during reset \u2014 proceeding to wipe anyway",{error:String(h)})}try{z$.configure({globalGatewayUrl:"",workspaceGatewayUrl:void 0,clientId:"",clientSecret:"",workspaceId:void 0})}catch{}await w.close();let{removed:B,agentDir:L}=R$();q().logger.info("agent","Reset wiped local agent state",{agentDir:L,removed:B});let C=new Uint8Array(32);crypto.getRandomValues(C);let j=`vcak_${Buffer.from(C).toString("base64url")}`;return T$({"static-api-key":j},m()),q().setBootState("awaiting-config"),G.status=200,{success:!0,state:"awaiting-config",...y(R,$)||process.env.VIBECONTROLS_RETURN_RESET_API_KEY==="1"?{newApiKey:j}:{},agentDir:L,removed:B}},{body:F.Object({confirm:F.Boolean()})}).post("/sessions/:sessionId/share",async({params:U,body:R,server:$,request:G,set:I})=>{if(!y(G,$)&&process.env.VIBECONTROLS_ALLOW_REMOTE_SESSION_SHARE!=="1")return I.status=403,{error:"Forbidden",message:"Session-share mint must come from a local request unless VIBECONTROLS_ALLOW_REMOTE_SESSION_SHARE=1."};if(!X$(U.sessionId))return I.status=400,{error:"BadRequest",message:"invalid sessionId"};let O=wU(R?.expiresIn)??1800000,B=crypto.randomUUID(),L=new Uint8Array(32);crypto.getRandomValues(L);let C=`vcak_${Buffer.from(L).toString("base64url")}`,j=new Date(Date.now()+O).toISOString(),r=[...(await import("./agent-config-hzzh97dn.js")).readAgentConfig({dir:m().dir}).apiKeys??[],{id:B,name:`session-share:${U.sessionId}:${R?.label??"viewer"}`,key:C,scopes:["read"],expiresAt:j,createdAt:new Date().toISOString()}];(await import("./agent-config-hzzh97dn.js")).writeAgentConfig({apiKeys:r},m());let h=W.getProvider("tunnel"),d$=(h&&h.getActiveTunnelUrl?await h.getActiveTunnelUrl():null)??`http://localhost:${process.env.PORT||3005}`,s$=L$({pathPrefixes:[`/terminal/${U.sessionId}`],methods:["GET"]},Math.min(600,Math.floor(O/1000))),r$=`${d$.replace(/\/$/,"")}/terminal/${encodeURIComponent(U.sessionId)}/#vt=${encodeURIComponent(s$.token)}`;return q().logger.info("session-share","Minted share credential",{sessionId:U.sessionId,keyId:B,expiresAt:j}),{ok:!0,keyId:B,apiKey:C,joinUrl:r$,sessionId:U.sessionId,expiresAt:j}},{params:F.Object({sessionId:F.String()}),body:F.Optional(F.Object({permissions:F.Optional(F.Array(F.String())),expiresIn:F.Optional(F.String()),label:F.Optional(F.String())}))}).get("/aliases",async()=>{return{aliases:await i(w)}}).get("/aliases/:name",async({params:U,set:R})=>{let $=await n(w,U.name);if(!$)return R.status=404,{error:"Alias not found"};return $},{params:F.Object({name:F.String()})}).post("/aliases",async({body:U,set:R})=>{try{let $=await Q$(w,U);return R.status=201,$}catch($){if($ instanceof E)return R.status=409,{error:"Alias already exists",message:$.message};if($ instanceof D)return R.status=400,{error:$.code,message:$.message};throw $}},{body:F.Object({name:F.String(),command:F.String(),description:F.Optional(F.String()),cwd:F.Optional(F.Union([F.String(),F.Null()]))})}).put("/aliases/:name",async({params:U,body:R,set:$})=>{try{return await Z$(w,U.name,R)}catch(G){if(G instanceof P)return $.status=404,{error:"Alias not found"};if(G instanceof D)return $.status=400,{error:G.code,message:G.message};throw G}},{params:F.Object({name:F.String()}),body:F.Object({command:F.Optional(F.String()),description:F.Optional(F.String()),cwd:F.Optional(F.Union([F.String(),F.Null()]))})}).delete("/aliases/:name",async({params:U,set:R})=>{try{return await B$(w,U.name),R.status=204,null}catch($){if($ instanceof P)return R.status=404,{error:"Alias not found"};throw $}},{params:F.Object({name:F.String()})}).post("/aliases/:name/execute",async({params:U,body:R,set:$})=>{let G=await n(w,U.name);if(!G)return $.status=404,{error:"Alias not found"};let I=R?.args??[],O=await j$(G,I);q().audit.emit("agent","alias.executed",{exit_code:O.exit_code});let B=Y$("alias.executed",{exit_code:O.exit_code});if(!B.ok)q().logger.debug("alias",`telemetry validate failed: ${B.reason}`);if(O.timed_out)$.status=408;return{exit_code:O.exit_code,stdout:O.stdout,stderr:O.stderr,duration_ms:O.duration_ms,truncated:O.truncated,cwd:O.cwd}},{params:F.Object({name:F.String()}),body:F.Optional(F.Object({args:F.Optional(F.Array(F.String()))}))}).post("/sessions/share/:keyId/revoke",async({params:U,server:R,request:$,set:G})=>{if(!y($,R)&&process.env.VIBECONTROLS_ALLOW_REMOTE_SESSION_SHARE!=="1")return G.status=403,{error:"Forbidden"};let I=await import("./agent-config-hzzh97dn.js"),O=m(),B=I.readAgentConfig({dir:O.dir}),L=(B.apiKeys??[]).length,C=(B.apiKeys??[]).filter((j)=>j.id!==U.keyId);if(C.length===L)return G.status=404,{error:"No such share key"};return I.writeAgentConfig({apiKeys:C},O),{ok:!0,revoked:U.keyId}},{params:F.Object({keyId:F.String()})})}function wU(f){if(!f)return null;let W=/^(\d+)([smhdw]?)$/.exec(f.trim());if(!W)return null;let w=Number(W[1]),U=W[2]||"m";return U==="s"?w*1000:U==="m"?w*60000:U==="h"?w*3600000:U==="d"?w*86400000:w*7*86400000}var fU="http://localhost:3005";function x$(f){f.command("health").description("Check health of a VibeControls agent instance").option("-n, --name <name>","Agent instance name").option("--agent-url <url>","Agent URL",fU).option("--json","Emit JSON").option("--plain","Force plain text output").action(async function(W){try{let w={...f.opts(),...W};await _({mode:x(w),fetchData:async()=>{if(w.name){let $=await new g().checkHealth(w.name);return{mode:"named",agentUrl:T(w),name:w.name,healthy:$.healthy,details:$.details??{}}}let U=T(w);try{let R=await M(U,"/health");return{mode:"url",agentUrl:U,healthy:!0,details:R}}catch(R){return{mode:"url",agentUrl:U,healthy:!1,details:{status:"unhealthy",...R instanceof Error?{error:H(R)}:{}}}}},plain:(U)=>{if(X("Agent Health"),Q(),U.mode==="named"){if(!U.healthy){Y(`Agent instance ${V.bold(U.name??"")} is not responding.`);return}let R=U.details;if(J("Instance",U.name??""),J("Status",u(R.status??"healthy")),R.uptime!==void 0)J("Uptime",`${R.uptime}s`);if(R.checks){Q(),z(`${Z.info} Health checks:`);for(let[$,G]of Object.entries(R.checks)){let I=G.status==="healthy"?Z.success:Z.error;J(` ${I} ${$}`,u(G.status))}}}else{if(J("URL",U.agentUrl),J("Status",u(U.details.status??"unhealthy")),U.details.version)J("Version",U.details.version);if(U.details.uptime!==void 0)J("Uptime",`${U.details.uptime}s`);if(U.details.timestamp)J("Timestamp",U.details.timestamp);if(U.details.checks){Q(),z(`${Z.info} Health checks:`);for(let[R,$]of Object.entries(U.details.checks)){let G=$.status==="healthy"?Z.success:Z.error;J(` ${G} ${R}`,u($.status))}}}if(Q(),U.healthy)A(`${Z.success} Agent is healthy.`)},interactive:async(U)=>{let R=[];if(U.mode==="named")R.push(`Instance: ${U.name??""}`);else R.push(`URL: ${U.agentUrl}`);if(R.push(`Status: ${u(U.details.status??(U.healthy?"healthy":"unhealthy"))}`),U.details.version)R.push(`Version: ${U.details.version}`);if(U.details.uptime!==void 0)R.push(`Uptime: ${U.details.uptime}s`);if(U.details.timestamp)R.push(`Time: ${U.details.timestamp}`);if(U.details.checks){R.push(""),R.push("Checks:");for(let[$,G]of Object.entries(U.details.checks))R.push(` ${$}: ${G.status}`)}await K({title:"Agent Health",body:R.join(`
|
|
4
4
|
`),footer:"press q to exit"})},json:(U)=>({mode:U.mode,agentUrl:U.agentUrl,name:U.name??null,healthy:U.healthy,details:U.details})})}catch(w){Y(`Health check failed: ${H(w)}`)}})}import{platform as WU,arch as JU,release as IU,hostname as OU,cpus as FU,totalmem as VU}from"os";var QU="http://localhost:3005";function _$(f){f.command("info").description("Show local and remote VibeControls agent information").option("--agent-url <url>","Agent URL",QU).option("--json","Emit JSON").option("--plain","Force plain text output").action(async function(W){try{let w={...f.opts(),...W},U=T(w),R=encodeURIComponent(b(w));await _({mode:x(w),fetchData:async()=>{let $={hostname:OU(),platform:WU(),arch:JU(),release:IU(),cpus:FU().length,totalMemory:VU(),nodeVersion:process.version,bunVersion:process.versions.bun};try{let G=await M(U,`/api/profiles/${R}/agent/version`);return{local:$,agentUrl:U,remote:G}}catch(G){return{local:$,agentUrl:U,remote:null,remoteError:G instanceof Error?H(G):String(G)}}},plain:($)=>{if(X("VibeControls Agent Info"),Q(),z(`${Z.info} Local System`),J("Hostname",$.local.hostname),J("Platform",`${$.local.platform} ${$.local.arch}`),J("OS Release",$.local.release),J("CPUs",String($.local.cpus)),J("Total Memory",N($.local.totalMemory)),J("Node.js",$.local.nodeVersion),$.local.bunVersion)J("Bun",$.local.bunVersion);if(Q(),z(`${Z.info} Remote Agent`),J("URL",$.agentUrl),$.remote){if(J("Version",V.bold($.remote.version)),$.remote.build)J("Build",$.remote.build);if($.remote.commit)J("Commit",$.remote.commit);if($.remote.nodeVersion)J("Node.js (remote)",$.remote.nodeVersion);if($.remote.bunVersion)J("Bun (remote)",$.remote.bunVersion)}else J("Status",V.dim("not reachable"));Q()},interactive:async($)=>{let G=[];if(G.push("Local System"),G.push(` Hostname: ${$.local.hostname}`),G.push(` Platform: ${$.local.platform} ${$.local.arch}`),G.push(` OS Release: ${$.local.release}`),G.push(` CPUs: ${$.local.cpus}`),G.push(` Total Memory: ${N($.local.totalMemory)}`),G.push(` Node.js: ${$.local.nodeVersion}`),$.local.bunVersion)G.push(` Bun: ${$.local.bunVersion}`);if(G.push(""),G.push("Remote Agent"),G.push(` URL: ${$.agentUrl}`),$.remote){if(G.push(` Version: ${$.remote.version}`),$.remote.build)G.push(` Build: ${$.remote.build}`);if($.remote.commit)G.push(` Commit: ${$.remote.commit}`);if($.remote.nodeVersion)G.push(` Node.js: ${$.remote.nodeVersion} (remote)`);if($.remote.bunVersion)G.push(` Bun: ${$.remote.bunVersion} (remote)`)}else G.push(" Status: not reachable");await K({title:"VibeControls Agent Info",body:G.join(`
|
|
5
5
|
`),footer:"press q to exit"})},json:($)=>({local:$.local,agentUrl:$.agentUrl,remote:$.remote,remoteError:$.remoteError??null})})}catch(w){Y(`Failed to get info: ${H(w)}`)}})}var ZU="http://localhost:3005";function b$(f){f.command("system").description("Show system information for a running VibeControls agent").option("--agent-url <url>","Agent URL",ZU).option("--json","Emit JSON").option("--plain","Force plain text output").action(async function(W){try{let w={...f.opts(),...W},U=T(w),R=encodeURIComponent(b(w));await _({mode:x(w),fetchData:()=>M(U,`/api/profiles/${R}/agent/system`),plain:($)=>{if(X("Agent System Information"),Q(),z(`${Z.info} Agent`),J("Version",V.bold($.agentVersion)),$.bunVersion)J("Bun",$.bunVersion);if($.environment)J("Environment",$.environment);J("Uptime",s($.uptime)),Q(),z(`${Z.info} Platform`),J("OS",`${$.platform} ${$.arch}`),J("Hostname",$.hostname),J("Release",$.release),Q(),z(`${Z.info} Resources`),J("CPUs",String($.cpus)),J("Total Memory",N($.totalMemory)),J("Free Memory",N($.freeMemory)),Q(),z(`${Z.info} Paths`),J("Home",$.homeDir),J("CWD",$.cwd),Q()},interactive:async($)=>{let G=["Agent",` Version: ${$.agentVersion}`,...$.bunVersion?[` Bun: ${$.bunVersion}`]:[],...$.environment?[` Environment: ${$.environment}`]:[],` Uptime: ${s($.uptime)}`,"","Platform",` OS: ${$.platform} ${$.arch}`,` Hostname: ${$.hostname}`,` Release: ${$.release}`,"","Resources",` CPUs: ${$.cpus}`,` Total Mem: ${N($.totalMemory)}`,` Free Mem: ${N($.freeMemory)}`,"","Paths",` Home: ${$.homeDir}`,` CWD: ${$.cwd}`];await K({title:"Agent System Information",body:G.join(`
|
|
6
6
|
`),footer:"press q to exit"})}})}catch(w){Y(`Failed to get system info: ${H(w)}`)}})}var BU="http://localhost:3005";async function u$(f){try{let W=await fetch(`${f}/health/ready`);if(W.status===200||W.status===503)return await W.json();return{healthy:!1,status:W.status}}catch{return{healthy:!1,error:"unreachable"}}}async function N$(f,W){try{let w=await fetch(`${f}/api/profiles/${W}/agent/api-key`);if(!w.ok)return null;return(await w.json()).apiKey??null}catch{return null}}async function zU(f,W){try{return await M(f,`/api/profiles/${W}/plugins`)}catch{return null}}function o(f){let W=f??{};if(W.error==="unreachable")return V.red("unreachable");if(typeof W.status==="number"&&W.status>=400)return V.red(`http ${W.status}`);let w=typeof W.status==="string"?W.status:"",U=typeof W.bootState==="string"?W.bootState:"";if(w==="ok"&&U==="ready")return V.green("ready");if(U==="awaiting-config")return V.yellow("awaiting-config");if(U==="initializing")return V.yellow("initializing");if(U==="degraded"||w==="degraded")return V.red(`degraded${U?` (${U})`:""}`);if(W.healthy===!1)return V.red("unhealthy");return V.green("healthy")}function YU(f){let w=(f??{}).lastFinalizeError;if(!w||typeof w!=="object")return null;let U=w;if(typeof U.message!=="string"||typeof U.at!=="string")return null;return{message:U.message,at:U.at,attempt:typeof U.attempt==="number"?U.attempt:void 0}}function P$(f){let W=f??{},w=typeof W.bootState==="string"?W.bootState:"";if(w!=="awaiting-config"&&w!=="degraded")return null;let U=[],R=YU(f);if(R)if(U.push(`${V.gray("\xB7")} Last error: ${V.red(R.message)}`),R.attempt!==void 0)U.push(`${V.gray("\xB7")} Background retry: attempt ${R.attempt}`);else U.push(`${V.gray("\xB7")} Last seen: ${R.at}`);if(w==="awaiting-config")U.push(`${V.gray("\xB7")} Force retry now: ${V.bold("vibe retry-config")}`);return U.push(`${V.gray("\xB7")} Full trace: ${V.bold("vibe logs --since 10m")}`),U.join(`
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
2
|
+
import{Pd as p}from"./index-c4p1qcnn.js";import{Sd as K,Zd as Mq,ae as wq,de as j}from"./index-q9dp55wv.js";import{existsSync as G,mkdirSync as u,readdirSync as mq,readFileSync as B,renameSync as P,rmSync as oq,writeFileSync as D}from"fs";import{dirname as k,join as v}from"path";import{randomUUID as pq}from"crypto";import{existsSync as b,mkdirSync as d,readFileSync as Zq,renameSync as Jq,unlinkSync as Tq,writeFileSync as F}from"fs";import{dirname as E,join as V}from"path";import{spawnSync as r}from"child_process";import{hostname as Lq,networkInterfaces as xq,platform as Xq,userInfo as Cq}from"os";import{createCipheriv as Fq,createDecipheriv as Nq,pbkdf2Sync as Aq,randomBytes as Rq}from"crypto";var n="secrets:fallback",Wq="secrets:index",t=10,uq=100,a=new Map;function Hq(q,Q){let $=`${q}:${Q}`,z=(a.get($)??0)+1;if(a.set($,z),z<=t)return!0;return(z-t)%uq===0}var C="vibecontrols-agent",Yq=".libsecret-install-attempted",jq="secrets.json";function Pq(){return globalThis.Bun?.secrets??null}class S{api;kind="bun-secrets";constructor(q){this.api=q}async get(q){return this.api.get({service:C,name:q})}async set(q,Q){await this.api.set({service:C,name:q,value:Q}),await yq(q)}async delete(q){let Q=await this.api.delete({service:C,name:q});return await lq(q),Q}async list(q){return Eq(q)}}var Gq=".secrets-encrypted-v1",kq=1e5,vq=32,Iq="sha256",L=null,e=null;function _q(){let q=xq();for(let Q of Object.values(q)){if(!Q)continue;for(let $ of Q){let z=$?.mac;if(z&&z!=="00:00:00:00:00:00")return z}}return"no-mac"}function qq(){if(e!==null)return e;let q;try{q=Cq().username||"unknown"}catch{q=process.env.USER||process.env.USERNAME||"unknown"}return`${Lq()}|${q}|${_q()}`}function Vq(){if(L)return L;let q=`vibecontrols-agent::${qq()}`;return L=Aq(q,qq(),kq,vq,Iq),L}function Qq(q){let Q=Rq(12),$=Fq("aes-256-gcm",Vq(),Q),z=Buffer.concat([$.update(q,"utf8"),$.final()]),Z=$.getAuthTag();return`${Q.toString("hex")}:${Z.toString("hex")}:${z.toString("hex")}`}function hq(q){let Q=q.split(":");if(Q.length!==3)return!1;let[$,z,Z]=Q;return/^[0-9a-f]+$/i.test($)&&$.length===24&&/^[0-9a-f]+$/i.test(z)&&z.length===32&&/^[0-9a-f]*$/i.test(Z)}function gq(q){if(!hq(q))return null;try{let[Q,$,z]=q.split(":"),Z=Nq("aes-256-gcm",Vq(),Buffer.from(Q,"hex"));return Z.setAuthTag(Buffer.from($,"hex")),Buffer.concat([Z.update(Buffer.from(z,"hex")),Z.final()]).toString("utf8")}catch{return null}}class Kq{kind="json-fallback";path;constructor(){this.path=V(j(),jq)}async get(q){let{plain:Q}=this.readWithMigration(),$=Q[q];return typeof $==="string"?$:null}async set(q,Q){await K(n,async()=>{let{encrypted:$}=this.readWithMigration();$[q]=Qq(Q),this.writeEncrypted($)})}async delete(q){return K(n,async()=>{let{encrypted:Q}=this.readWithMigration();if(!(q in Q))return!1;return delete Q[q],this.writeEncrypted(Q),!0})}async list(q){let{encrypted:Q}=this.readWithMigration(),$=Object.keys(Q);return(q?$.filter((Z)=>Z.startsWith(q)):$).sort().map((Z)=>({name:Z}))}readWithMigration(){if(!b(this.path))return{encrypted:{},plain:{}};let q;try{q=Zq(this.path,"utf8")}catch{return{encrypted:{},plain:{}}}let Q;try{Q=JSON.parse(q)}catch{return{encrypted:{},plain:{}}}if(!Q||typeof Q!=="object"||Array.isArray(Q))return{encrypted:{},plain:{}};let $={},z={},Z=!1;for(let[J,X]of Object.entries(Q)){if(typeof X!=="string")continue;let Y=gq(X);if(Y!==null){$[J]=X,z[J]=Y;continue}$[J]=Qq(X),z[J]=X,Z=!0}if(Z)try{this.writeEncrypted($),this.writeMarker()}catch{}return{encrypted:$,plain:z}}writeEncrypted(q){d(E(this.path),{recursive:!0});let Q=`${this.path}.${process.pid}.tmp`;if(F(Q,`${JSON.stringify(q,null,2)}
|
|
3
3
|
`,{mode:384}),Jq(Q,this.path),!b(this.markerPath()))this.writeMarker()}markerPath(){return V(E(this.path),Gq)}writeMarker(){try{F(this.markerPath(),`${new Date().toISOString()}
|
|
4
4
|
`,{mode:384})}catch{}}}var fq=".secrets-index.json";function m(){return V(j(),fq)}function o(){let q=m();if(!b(q))return new Set;try{let Q=Zq(q,"utf8"),$=JSON.parse(Q);if(Array.isArray($))return new Set($.filter((z)=>typeof z==="string"))}catch{}return new Set}function Uq(q){let Q=m();d(E(Q),{recursive:!0});let $=`${Q}.${process.pid}.tmp`;F($,`${JSON.stringify([...q].sort(),null,2)}
|
|
5
5
|
`,{mode:384}),Jq($,Q)}async function yq(q){await K(Wq,()=>{let Q=o();if(Q.has(q))return;Q.add(q),Uq(Q)})}async function lq(q){await K(Wq,()=>{let Q=o();if(!Q.delete(q))return;Uq(Q)})}function Eq(q){let $=[...o()];return(q?$.filter((Z)=>Z.startsWith(q)):$).sort().map((Z)=>({name:Z}))}function Sq(){if(Xq()!=="linux")return{ok:!1};if(process.env.CI==="true")return{ok:!1,warning:"CI/test environment detected; using JSON fallback"};if(process.env.VIBE_SKIP_LIBSECRET_INSTALL==="1")return{ok:!1,warning:"VIBE_SKIP_LIBSECRET_INSTALL=1 set; using JSON fallback"};let q=j(),Q=V(q,Yq);if(b(Q))return{ok:!1,warning:"previous attempt failed; not retrying"};try{d(q,{recursive:!0}),F(Q,`${new Date().toISOString()}
|