@vibecontrols/agent 2026.1127.2 → 2026.1201.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{app-4t875vbv.js → app-ntnpwedw.js} +1 -1
- package/dist/{bridge-commands-xhzhghxt.js → bridge-commands-hc1gvngq.js} +1 -1
- package/dist/cli.js +1 -1
- package/dist/{index-6b9vh0gq.js → index-5tghd67e.js} +2 -2
- package/dist/{index-12rehjp4.js → index-85jn7v8t.js} +3 -3
- package/dist/{index-p1b10hs1.js → index-8jk4a62x.js} +6 -6
- package/dist/{index-6wfd7cv3.js → index-br9bakfm.js} +1 -1
- package/dist/{index-nz7mhjjn.js → index-dr6rsnpk.js} +1 -1
- package/dist/{index-j8j1h00a.js → index-j9jwwzq2.js} +1 -1
- package/dist/{index-1smr1csg.js → index-q4fht6h2.js} +2 -2
- package/dist/{index-dtxd2xmg.js → index-sjs32cgn.js} +2 -2
- package/dist/{index-0vbsve3v.js → index-twtvt4yt.js} +1 -1
- package/dist/index.js +2 -2
- package/dist/{plugin-system-7qjqrq7s.js → plugin-system-e690jr6e.js} +1 -1
- package/dist/{register-core-vv5pddxj.js → register-core-n1dy472f.js} +1 -1
- package/dist/{secondary-profile-attach-222s85md.js → secondary-profile-attach-v7kxsk4z.js} +1 -1
- package/dist/{tunnel-bootstrap-20vwak7q.js → tunnel-bootstrap-m51w4d94.js} +1 -1
- package/package.json +1 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{z,R,I,ne,ee,C,e}from"./index-7wm4bqx5.js";import{J,Wr,$i,Ht,Er,_e,$e,ye,Vt,Xr,It,nt,ei,_r,yr,st,Sr,w,M,Ct}from"./index-j99tkngg.js";import{i,d,s,A,l,p,o,g,n,c,F,v,G,H,Gt}from"./index-12gb48hg.js";import{Ee,Q,U}from"./index-sq5j8bjn.js";import{De,ct}from"./index-4kf3nr14.js";import{ie,Y,Ce,Pi,Ur,Ue,W}from"./index-p1b10hs1.js";import{Dr}from"./index-zcnfj1q4.js";import{Re}from"./index-qzwbctkv.js";import{Ze,Ot,Ti,xi,nr,bi,sr,wi,ut,te,re,ae,qi,lt,Ne,Ri,Je,We,ke,Bt,Xe,Ar,Le,ze,et,dt,ht,ft,pt,Lr,mt,Pt,Mt,Dt,Se}from"./index-nz7mhjjn.js";import{Si}from"./index-0rmmrrfh.js";import{Ii}from"./index-90gn0b6x.js";import{D}from"./index-0vbsve3v.js";import{Nt}from"./index-6wfd7cv3.js";import{b}from"./index-w4jqdhc2.js";import{Mi,k}from"./index-e5jdx9c1.js";import{Ke}from"./index-cn4p1ks0.js";import{ue,le,_,y,u,jt}from"./index-v77bb0rm.js";import{f,m,S,q,Te,ge}from"./index-damc6cvc.js";import{existsSync as Qt}from"fs";import{join as ho}from"path";import{createServer as fo}from"net";function go(P,a="0.0.0.0"){return new Promise((t)=>{let r=fo();r.once("error",()=>t(!1)),r.once("listening",()=>{r.close(()=>t(!0))}),r.listen({host:a,port:P,exclusive:!0})})}async function Xt(P,a="0.0.0.0"){let t=P;while(!await go(t,a))if(t++,t>65535)throw Error(`No free port found starting from ${P}`);return t}function en(P){P.command("start").description("Start a VibeControls agent instance").option("-p, --port <port>","Port to listen on. Default: 3005 for the 'default' profile, deterministic 3100-3399 for any other profile (FNV-1a hash) so multiple profiles run side-by-side without EADDRINUSE.").option("-n, --name <name>","Agent instance name","default").option("-f, --foreground","Run in foreground mode (default: daemon)",!1).option("--no-autostart","Don't configure OS-level autostart for this agent. Without it the daemon dies with the session that started it and will not come back.").option("--db-path <path>","Path to the agent storage directory").option("--profile <profile>","Profile name for isolated config (env: VIBECONTROLS_PROFILE)").option("--host <host>","Host to bind to","0.0.0.0").option("--skip-plugin-install","Skip automatic installation of default plugins",!1).option("--skip-plugin <name>","Skip a specific default plugin (repeatable). Accepts the short pluginName or the full package name.",(a,t=[])=>[...t,a],[]).option("--no-install-deps","Skip auto-installing missing tools (installed by their plugins on start by default)").option("-y, --yes","Skip the first-run install consent prompt. Equivalent to VIBE_AUTO_ACCEPT=1; useful for CI / Docker / nohup contexts.",!1).option("--client-id <id>","Gateway OAuth client ID (env: VIBE_CLIENT_ID)").option("--client-secret <secret>","Gateway OAuth client secret (env: VIBE_CLIENT_SECRET)").option("--global-gateway-url <url>","Global gateway URL (env: VIBE_GLOBAL_GATEWAY_URL)").option("--workspace-gateway-url <url>","Workspace gateway URL (env: VIBE_WORKSPACE_GATEWAY_URL)").option("--workspace-id <id>","Workspace ID for auto-report (env: VIBE_WORKSPACE_ID)").option("--isolate <plugins>","Comma-separated list of plugin names to force into worker_threads isolation (Phase 4 hostile-plugin mode). Sets VIBE_ISOLATE_PLUGINS in the daemon env.").option("--profiles <names>","Comma-separated list of profiles to host in this daemon (multi-profile boot). When unset, the daemon hosts a single profile resolved via --profile / VIBECONTROLS_PROFILE / 'default'. Sets VIBECONTROLS_PROFILES in the daemon env so app boot can spin up additional ProfileContexts via the in-process registry.").option("--strict-key-fetch","Refuse to boot if any profile's encryption-key fetch fails. Default lenient: a failed profile is marked degraded and the daemon stays up. Sets VIBE_STRICT_KEY_FETCH=1 in the daemon env.",!1).option("--json","Emit JSON").option("--plain","Plain text output (no interactive TUI). Implied for non-TTY / CI.").option("--abilities <list>","Comma-separated ability keys to install non-interactively (e.g. session,ai,gitops). Storage/tunnel/backup are always included.").option("--providers <list>","Comma-separated extra provider plugins to install beyond each meta's default (e.g. session-wezterm,ai-claude). Accepts short names or @vibecontrols/... packages. Persisted; manage later with `vibe capability`.").option("--wait-ready [seconds]","Block until the agent is fully ready (or fails). Polls /health/ready and renders phase transitions live. Without a value, defaults to 60s. Exits non-zero if the agent ends up degraded or times out. Useful for scripts/CI.").option("--no-wait","Skip the phase tracker entirely after spawning the daemon. Restores the old fire-and-print behavior \u2014 for users who want the previous quick-return UX.").action(async function(a){let t={...P.opts(),...a};try{let oe=function(ce){if(ce==="default")return 3005;let he=2166136261;for(let fe=0;fe<ce.length;fe++)he=Math.imul(he^ce.charCodeAt(fe),16777619);return 3100+Math.abs(he)%300},r=new D,h=a.profile||process.env.VIBECONTROLS_PROFILE||"default";if(process.env.VIBECONTROLS_PROFILE=h,typeof a.isolate==="string"&&a.isolate.length>0)process.env.VIBE_ISOLATE_PLUGINS=a.isolate;if(typeof a.profiles==="string"&&a.profiles.length>0){let ce=a.profiles.split(",").map((he)=>he.trim()).filter(Boolean);if(ce.length>0){if(process.env.VIBECONTROLS_PROFILES=ce.join(","),process.env.VIBECONTROLS_PROFILE=ce[0],ce.length>1)p(`--profiles received ${ce.length} entries; daemon boots with '${ce[0]}'. Remaining (${ce.slice(1).join(", ")}) will be attached via /api/profiles after listen.`)}}if(a.strictKeyFetch===!0)process.env.VIBE_STRICT_KEY_FETCH="1";Ct();let O=a.dbPath||ee(),E=C(),N=!Qt(O)&&!Qt(ho(E,"agents.json")),j=_(t),T=j!=="json"&&j!=="plain"&&ue()&&a.yes!==!0,x=Ze(E),L;if(typeof t.abilities==="string"&&t.abilities.trim()!=="")L=bi(t.abilities);else if(x!==null)L=x;else if(T)L=await nr();else L=sr();let Z=typeof t.providers==="string"&&t.providers.trim()!=="",B=Z?Ti(t.providers):Ot(E);if(x===null){let ce=xi({installDeps:a.installDeps===!0,skipPluginInstall:a.skipPluginInstall===!0,skipPlugins:Array.isArray(a.skipPlugin)?a.skipPlugin:[]},L);if(N&&ce.plugins.length>0)c(),o(`Installing ${ce.plugins.length} plugin(s) for the selected abilities.`),c();wi(E,ce,L,process.env.VIBE_AGENT_VERSION,B)}else if(Z)ut(E,{providers:B,agentVersion:process.env.VIBE_AGENT_VERSION});if((N||Z)&&B.length>0&&a.skipPluginInstall!==!0){o(`Installing ${B.length} selected provider plugin(s)...`);try{let{PluginManager:ce}=await import("./plugin-system-7qjqrq7s.js"),he=new ce;for(let fe of B)try{await he.install(fe),l(`Installed provider ${fe}`)}catch(be){p(`Could not install provider ${fe}: ${be instanceof Error?be.message:String(be)}`)}}catch(ce){p(`Provider install skipped: ${ce instanceof Error?ce.message:String(ce)}`)}c()}if(N){o("First run detected \u2014 running setup..."),c();let ce=Array.isArray(a.skipPlugin)?a.skipPlugin:[],he=a.skipPluginInstall?[]:Ce(process.platform,L).filter((Ae)=>!ce.includes(Ae.packageName)&&!ce.includes(Ae.pluginName)).map((Ae)=>Ae.packageName),fe=Pi(he),He=De(fe).filter((Ae)=>!Ae.installed);if(He.length>0)if(p(`Missing tools: ${He.map((Ae)=>Ae.name).join(", ")}`),a.installDeps)o("Their plugins will install them automatically on startup.");else o("Auto-install skipped (`--no-install-deps`) \u2014 install them yourself or drop the flag.");else l("All plugin tools present.");c()}if(!a.skipPluginInstall){let ce=Array.isArray(a.skipPlugin)?a.skipPlugin:[],he=new W;await he.loadCorePlugins(),await he.loadAll();let fe=await he.ensureDefaultPlugins((be)=>{if(be.startsWith("No "))p(be);else if(be.startsWith("Installed "))l(be);else if(be.startsWith("Failed "))p(be);else o(be)},ce,L);if(fe.length>0)l(`Auto-installed ${fe.length} default plugin${fe.length>1?"s":""}.`),c()}let V=a.profile||process.env.VIBECONTROLS_PROFILE||a.name||"default",K=a.port?parseInt(a.port,10):oe(V);if(isNaN(K)||K<1||K>65535)s("Invalid port number. Must be between 1 and 65535.");let X=await Xt(K);if(X!==K)p(`Port ${K} is in use. Auto-selecting port ${i.bold(String(X))} instead.`),K=X;let se=a.host,Ie=`http://${se==="0.0.0.0"?"localhost":se}:${K}`,ve=a.clientId||process.env.VIBE_CLIENT_ID,de=a.clientSecret||process.env.VIBE_CLIENT_SECRET,pe=a.globalGatewayUrl||process.env.VIBE_GLOBAL_GATEWAY_URL,me=a.workspaceGatewayUrl||process.env.VIBE_WORKSPACE_GATEWAY_URL,Me=a.workspaceId||process.env.VIBE_WORKSPACE_ID;if(ve&&!de)s("--client-secret is required when --client-id is provided.");if(de&&!ve)s("--client-id is required when --client-secret is provided.");if(ve&&de){if(!pe&&!process.env.VIBE_GLOBAL_GATEWAY_URL)s("--global-gateway-url is required when providing client credentials (none set in env).");if(process.env.VIBE_CLIENT_ID=ve,process.env.VIBE_CLIENT_SECRET=de,pe)process.env.VIBE_GLOBAL_GATEWAY_URL=pe;let{writeAgentConfig:ce}=await import("./agent-config-xwvsmn6b.js");if(ce({clientId:ve,clientSecret:de,workspaceId:Me,globalGatewayUrl:pe,workspaceGatewayUrl:me}),me)process.env.VIBE_WORKSPACE_GATEWAY_URL=me;if(Me)process.env.VIBE_WORKSPACE_ID=Me;l("Gateway credentials staged in env. Agent will authenticate and persist them on startup."),c()}else if(me||Me||pe){if(p("Workspace options provided without --client-id / --client-secret \u2014 they will be staged in env but unused until credentials are configured."),me)process.env.VIBE_WORKSPACE_GATEWAY_URL=me;if(Me)process.env.VIBE_WORKSPACE_ID=Me;if(pe)process.env.VIBE_GLOBAL_GATEWAY_URL=pe;c()}if(a.foreground){if(!t.json)g("Starting agent in foreground"),n("Name",a.name),n("Port",String(K)),n("Host",se),n("Database",O),c();let{bootstrapWorkspace:ce}=await import("./bootstrap-workspace-1pt0bwy6.js");ce();let{createApp:he}=await import("./app-4t875vbv.js"),fe=await he({port:K,host:se,dbPath:O});if(await fe.start(),ve&&de&&Me&&pe&&me){let He=await fe.finalize({clientId:ve,clientSecret:de,workspaceId:Me,globalGatewayUrl:pe,workspaceGatewayUrl:me});if(!He.ok)p(`Finalize failed \u2014 agent remains in awaiting-config state: ${He.error}`)}if(u(t,{ok:!0,name:a.name,port:K,host:se,pid:process.pid,url:Ie}));else await Gt(Ie);let be=async()=>{await fe.stop(),process.exit(0)};process.on("SIGTERM",be),process.on("SIGINT",be)}else{if(!t.json)g("Starting agent in daemon mode"),n("Name",a.name),n("Port",String(K)),n("Host",se),n("Database",O),c();if(a.installDeps===!1)process.env.VIBE_SKIP_PREREQ_INSTALL="1";await r.startDaemon({port:K,name:a.name,daemon:!0,dbPath:O,host:se,profile:h});let he=(await r.getStatus(a.name))?.port??K,fe;if(a.autostart!==!1){let{ensureAutostartConfigured:xe}=await import("./autostart.cmd-mdyv35dn.js"),we=await xe({name:a.name,port:he,dbPath:O,host:se,profile:h});if(fe=we,we.installed&&!t.json)o(`Configured ${we.serviceLabel} autostart \u2014 supervised from the next login/boot. `+"The daemon running now is not yet under it; hand it over with `vibe stop && vibe autostart install`.");else if(we.failed&&!t.json)p(`Could not configure autostart (${we.reason}). This agent will NOT come back after logout or reboot \u2014 fix the cause or run \`vibe autostart install\`.`)}let be=fe?{installed:fe.installed,failed:fe.failed??!1,reason:fe.reason}:{installed:!1,failed:!1,reason:"opted out"},Ae=`http://${se==="0.0.0.0"?"localhost":se}:${he}`,kt=a.waitReady,vt=a.wait===!1,zt=kt!==void 0;if(vt&&zt)p("--wait-ready is ignored because --no-wait was also passed.");let gt=!vt&&zt,Yt=!vt&&(gt||!t.json),Zt=(()=>{let xe=typeof kt==="string"?Number.parseInt(kt,10):NaN;if(Number.isInteger(xe)&&xe>0)return xe*1000;return gt?60000:25000})();if(t.json){if(Yt){let{trackAgentReady:xe}=await import("./agent-ready-tracker-7ebr09d9.js"),we=await xe(Ae,{timeoutMs:Zt,verbose:!1});if(gt&&(we.outcome==="degraded"||we.outcome==="timeout"))process.exitCode=1;u(t,{ok:we.outcome==="ready"||we.outcome==="awaiting-config",name:a.name,port:he,host:se,url:Ae,abilities:[...L],outcome:we.outcome,bootState:we.bootState,degradedReasons:we.degradedReasons,summary:we.summary,autostart:be})}else u(t,{ok:!0,name:a.name,port:he,host:se,url:Ae,autostart:be});return}if(await Gt(Ae),Yt){let{trackAgentReady:xe}=await import("./agent-ready-tracker-7ebr09d9.js");c();let we=await xe(Ae,{timeoutMs:Zt,verbose:!0});if(gt&&(we.outcome==="degraded"||we.outcome==="timeout"))process.exitCode=1}}}catch(r){let h=r instanceof Error?A(r):String(r);if(t.json){u(t,{ok:!1,error:h});return}s(`Failed to start agent: ${h}`)}})}function tn(P){P.command("stop").description("Stop a running VibeControls agent instance").option("-n, --name <name>","Agent instance name","default").option("--all","Stop all running agent instances",!1).option("--json","Emit JSON").action(async function(a){let t={...P.opts(),...a};try{let r=new D;if(a.all){let h=await r.listInstances();if(!h||h.length===0){if(u(t,{ok:!0,stopped:[]}))return;g("Stopping all agent instances"),c(),o(`${d.info} No running agent instances found.`);return}let O=[];if(!t.json)g("Stopping all agent instances"),c();for(let E of h)try{if(await r.stop(E.name),O.push(E.name),!t.json)l(`${d.success} Stopped ${i.bold(E.name)}`)}catch{if(!t.json)s(`Failed to stop ${i.bold(E.name)}`)}if(u(t,{ok:!0,stopped:O,total:h.length}))return;c(),l(`${d.success} Stopped ${O.length}/${h.length} instance(s).`)}else{if(await r.stop(a.name),u(t,{ok:!0,name:a.name}))return;g(`Stopping agent: ${a.name}`),c(),l(`${d.success} Agent ${i.bold(a.name)} stopped.`)}}catch(r){if(t.json){u(t,{ok:!1,error:A(r)});return}s(`Failed to stop agent: ${A(r)}`)}})}function nn(P){P.command("restart").description("Restart a running VibeControls agent instance").option("-n, --name <name>","Agent instance name","default").option("-p, --port <port>","Port to listen on").option("--db-path <path>","Path to the agent storage directory").option("--json","Emit JSON").option("--no-autostart","Don't configure OS-level autostart for this agent. Without it the daemon dies with the session that started it and will not come back.").action(async function(a){let t={...P.opts(),...a};try{let r=new D;if(!t.json)g(`Restarting agent: ${a.name}`),c(),o(`${d.info} Stopping agent ${i.bold(a.name)}...`);let h=await r.getStatus(a.name);try{if(await r.stop(a.name),!t.json)l(`${d.success} Agent stopped.`)}catch{if(!t.json)o(`${d.info} Agent was not running.`)}let O=a.port??h?.port??3005,E=typeof O==="number"?O:parseInt(O,10);if(isNaN(E)||E<1||E>65535){if(t.json){u(t,{ok:!1,error:"Invalid port number"});return}s("Invalid port number. Must be between 1 and 65535.");return}let N=t.profile??h?.config?.profile??process.env.VIBECONTROLS_PROFILE??"default";process.env.VIBECONTROLS_PROFILE=N;let j={port:E,name:a.name,daemon:!0,dbPath:a.dbPath??h?.config?.dbPath??ee(),host:h?.config?.host,profile:N};if(!t.json)c(),o(`${d.info} Starting agent ${i.bold(a.name)}...`);await r.startDaemon(j);let T;if(a.autostart!==!1){let{ensureAutostartConfigured:L}=await import("./autostart.cmd-mdyv35dn.js");T=await L({name:a.name,port:E,dbPath:j.dbPath,host:j.host,profile:j.profile});let Z=T;if(Z.installed&&!t.json)o(`Configured ${Z.serviceLabel} autostart \u2014 supervised from the next login/boot. `+"The daemon running now is not yet under it; hand it over with `vibe stop && vibe autostart install`.");else if(Z.failed&&!t.json)p(`Could not configure autostart (${Z.reason}). This agent will NOT come back after logout or reboot \u2014 fix the cause or run \`vibe autostart install\`.`)}let x=`http://localhost:${E}`;if(u(t,{ok:!0,name:a.name,port:E,url:x,autostart:T?{installed:T.installed,failed:T.failed??!1,reason:T.reason}:{installed:!1,failed:!1,reason:"opted out"}}))return;c(),l(`${d.success} Agent ${i.bold(a.name)} restarted.`),c(),n("Port",String(E)),n("Database",j.dbPath),c(),Gt(x)}catch(r){if(t.json){u(t,{ok:!1,error:A(r)});return}s(`Failed to restart agent: ${A(r)}`)}})}import{existsSync as bo,readFileSync as yo,unlinkSync as on}from"fs";import{join as sn}from"path";function wo(P){let a=sn(ne(),P,"runtime.json");if(!bo(a))return null;try{let t=JSON.parse(yo(a,"utf8"));if(typeof t.pid!=="number")return null;return{...t,pid:t.pid,path:a}}catch{return null}}async function rn(P){let a=wo(P);if(!a)return null;if(!ae(a.pid)){try{on(a.path)}catch{}return`agent pid=${a.pid} (${P}) already gone (cleaned runtime.json).`}let t=b();if(!t.killProcessTree(a.pid,"SIGTERM"))return`failed to SIGTERM agent pid=${a.pid}.`;if(await new Promise((r)=>setTimeout(r,3000)),ae(a.pid))t.killProcessTree(a.pid,"SIGKILL");try{on(a.path)}catch{}return`agent ${P} pid=${a.pid}${a.port?` (port ${a.port})`:""} killed.`}async function ko(P){let a=sn(ne(),P),t=te(a);if(!t)return null;if(!ae(t.pid))return re(a),`tunnel pid=${t.pid} already gone (cleaned state).`;let r=b();if(!r.killProcessTree(t.pid,"SIGTERM"))return`failed to SIGTERM tunnel pid=${t.pid}.`;if(await new Promise((h)=>setTimeout(h,3000)),ae(t.pid))r.killProcessTree(t.pid,"SIGKILL");return re(a),`tunnel ${t.provider} pid=${t.pid} (${t.url??"no url"}) killed.`}function an(P){P.command("kill").description("Force-kill an agent instance and its tunnel. Defaults to active profile.").option("-n, --name <name>","Agent instance name (alias of --profile, kept for back-compat)").option("--profile <name>","Kill a specific profile (overrides --name and VIBECONTROLS_PROFILE)").option("--all","Kill every agent instance and every profile's tunnel",!1).option("-y, --yes","Skip the confirmation prompt (for scripts/CI)",!1).option("--json","Emit JSON").action(async function(a){let t={...P.opts(),...a},r=a.all?"ALL agent instances + every profile's tunnel":`agent '${t.profile??t.name??"active profile"}'`;if(!await jt(t,`Force-kill ${r}? This sends SIGKILL (no graceful shutdown).`)){o("Aborted.");return}let h=[];try{let O=new D;if(a.all){if(!t.json)g("Force killing all agent instances + tunnels"),c();let T=await O.listInstances()??[],x=0,L=new Set;for(let V of T)try{if(await O.kill(V.name),!t.json)l(`${d.success} agent ${i.bold(V.name)} (pid=${V.pid||"?"}) killed.`);h.push(V.name),x++,L.add(V.name)}catch{if(!t.json)p(`${d.warning} could not kill agent ${V.name}.`)}try{let V=await import("fs"),oe=ne(),K=V.existsSync(oe)?V.readdirSync(oe):[];for(let X of K){if(L.has(X))continue;let se=await rn(X);if(se)l(`${d.success} ${se}`),x++}}catch(V){p(`${d.warning} runtime.json sweep failed: ${V instanceof Error?A(V):String(V)}`)}let Z=qi({allProfiles:!0}),B=0;for(let V of Z){if(!V.alive){re(V.profileDir);continue}let oe=b();if(oe.killProcessTree(V.pid,"SIGTERM"),await new Promise((K)=>setTimeout(K,3000)),ae(V.pid))oe.killProcessTree(V.pid,"SIGKILL");re(V.profileDir),l(`${d.success} tunnel ${V.provider} pid=${V.pid} (${V.url??"no url"}, ${V.profileDir.split("/").pop()}) killed.`),B++}if(u(t,{ok:!0,killed:h,tunnels:B}))return;c(),l(`${d.success} killed ${x} agent(s) and ${B} tunnel(s).`);return}let E=a.profile||a.name||R();if(!t.json)g(`Force killing profile: ${E}`),c();let N=await O.getStatus(E);if(N){if(await O.kill(E),h.push(E),!t.json)l(`${d.success} agent ${i.bold(E)} pid=${N.pid||"?"} killed.`)}else{let T=await rn(E);if(T){if(h.push(E),!t.json)l(`${d.success} ${T}`)}else if(!t.json)o(`${d.info} no running agent service for profile ${E}.`)}let j=await ko(E);if(j){if(!t.json)l(`${d.success} ${j}`)}else if(!t.json)o(`${d.info} no tunnel recorded for profile ${E}.`);u(t,{ok:!0,killed:h})}catch(O){if(t.json){u(t,{ok:!1,error:A(O)});return}s(`Failed to kill: ${A(O)}`)}})}function ln(P){P.command("list").alias("ls").description("List all VibeControls agent instances").option("--json","Emit JSON").option("--plain","Force plain text output").action(async function(a){try{let t={...P.opts(),...a},r=new D;await y({mode:_(t),fetchData:()=>r.listInstances(),plain:(h)=>{if(g("Agent Instances"),c(),!h||h.length===0){o(`${d.info} No agent instances found.`),o(`Run ${i.bold("vibe start")} to start an agent.`);return}let O=h.map((j)=>({Name:j.name,Status:G(j.status),PID:j.pid||"-",Port:j.port||"-",Host:j.config?.host||"-",Database:j.config?.dbPath||"-",Started:j.startTime?v(j.startTime):"-"}));F(O),c();let E=h.filter((j)=>j.status==="running").length,N=h.length-E;o(`${d.info} ${h.length} instance(s): ${i.green(String(E))} running, ${i.dim(String(N))} stopped`)},interactive:async(h)=>{if(!h||h.length===0){g("Agent Instances"),c(),o(`${d.info} No agent instances found.`),o(`Run ${i.bold("vibe start")} to start an agent.`);return}let O=h.map((E)=>{let N=[`${i.bold(E.name)} ${G(E.status)}`,"",` PID: ${E.pid??"-"}`,` Port: ${E.port??"-"}`,` Host: ${E.config?.host??"-"}`,` Database: ${E.config?.dbPath??"-"}`,` Started: ${E.startTime?v(E.startTime):"-"}`];return{id:E.name,label:E.name,hint:E.status==="running"?"running":"stopped",detail:N.join(`
|
|
2
|
+
import{z,R,I,ne,ee,C,e}from"./index-7wm4bqx5.js";import{J,Wr,$i,Ht,Er,_e,$e,ye,Vt,Xr,It,nt,ei,_r,yr,st,Sr,w,M,Ct}from"./index-j99tkngg.js";import{i,d,s,A,l,p,o,g,n,c,F,v,G,H,Gt}from"./index-12gb48hg.js";import{Ee,Q,U}from"./index-sq5j8bjn.js";import{De,ct}from"./index-4kf3nr14.js";import{ie,Y,Ce,Pi,Ur,Ue,W}from"./index-8jk4a62x.js";import{Dr}from"./index-zcnfj1q4.js";import{Re}from"./index-qzwbctkv.js";import{Ze,Ot,Ti,xi,nr,bi,sr,wi,ut,te,re,ae,qi,lt,Ne,Ri,Je,We,ke,Bt,Xe,Ar,Le,ze,et,dt,ht,ft,pt,Lr,mt,Pt,Mt,Dt,Se}from"./index-dr6rsnpk.js";import{Si}from"./index-0rmmrrfh.js";import{Ii}from"./index-90gn0b6x.js";import{D}from"./index-twtvt4yt.js";import{Nt}from"./index-br9bakfm.js";import{b}from"./index-w4jqdhc2.js";import{Mi,k}from"./index-e5jdx9c1.js";import{Ke}from"./index-cn4p1ks0.js";import{ue,le,_,y,u,jt}from"./index-v77bb0rm.js";import{f,m,S,q,Te,ge}from"./index-damc6cvc.js";import{existsSync as Qt}from"fs";import{join as ho}from"path";import{createServer as fo}from"net";function go(P,a="0.0.0.0"){return new Promise((t)=>{let r=fo();r.once("error",()=>t(!1)),r.once("listening",()=>{r.close(()=>t(!0))}),r.listen({host:a,port:P,exclusive:!0})})}async function Xt(P,a="0.0.0.0"){let t=P;while(!await go(t,a))if(t++,t>65535)throw Error(`No free port found starting from ${P}`);return t}function en(P){P.command("start").description("Start a VibeControls agent instance").option("-p, --port <port>","Port to listen on. Default: 3005 for the 'default' profile, deterministic 3100-3399 for any other profile (FNV-1a hash) so multiple profiles run side-by-side without EADDRINUSE.").option("-n, --name <name>","Agent instance name","default").option("-f, --foreground","Run in foreground mode (default: daemon)",!1).option("--no-autostart","Don't configure OS-level autostart for this agent. Without it the daemon dies with the session that started it and will not come back.").option("--db-path <path>","Path to the agent storage directory").option("--profile <profile>","Profile name for isolated config (env: VIBECONTROLS_PROFILE)").option("--host <host>","Host to bind to","0.0.0.0").option("--skip-plugin-install","Skip automatic installation of default plugins",!1).option("--skip-plugin <name>","Skip a specific default plugin (repeatable). Accepts the short pluginName or the full package name.",(a,t=[])=>[...t,a],[]).option("--no-install-deps","Skip auto-installing missing tools (installed by their plugins on start by default)").option("-y, --yes","Skip the first-run install consent prompt. Equivalent to VIBE_AUTO_ACCEPT=1; useful for CI / Docker / nohup contexts.",!1).option("--client-id <id>","Gateway OAuth client ID (env: VIBE_CLIENT_ID)").option("--client-secret <secret>","Gateway OAuth client secret (env: VIBE_CLIENT_SECRET)").option("--global-gateway-url <url>","Global gateway URL (env: VIBE_GLOBAL_GATEWAY_URL)").option("--workspace-gateway-url <url>","Workspace gateway URL (env: VIBE_WORKSPACE_GATEWAY_URL)").option("--workspace-id <id>","Workspace ID for auto-report (env: VIBE_WORKSPACE_ID)").option("--isolate <plugins>","Comma-separated list of plugin names to force into worker_threads isolation (Phase 4 hostile-plugin mode). Sets VIBE_ISOLATE_PLUGINS in the daemon env.").option("--profiles <names>","Comma-separated list of profiles to host in this daemon (multi-profile boot). When unset, the daemon hosts a single profile resolved via --profile / VIBECONTROLS_PROFILE / 'default'. Sets VIBECONTROLS_PROFILES in the daemon env so app boot can spin up additional ProfileContexts via the in-process registry.").option("--strict-key-fetch","Refuse to boot if any profile's encryption-key fetch fails. Default lenient: a failed profile is marked degraded and the daemon stays up. Sets VIBE_STRICT_KEY_FETCH=1 in the daemon env.",!1).option("--json","Emit JSON").option("--plain","Plain text output (no interactive TUI). Implied for non-TTY / CI.").option("--abilities <list>","Comma-separated ability keys to install non-interactively (e.g. session,ai,gitops). Storage/tunnel/backup are always included.").option("--providers <list>","Comma-separated extra provider plugins to install beyond each meta's default (e.g. session-wezterm,ai-claude). Accepts short names or @vibecontrols/... packages. Persisted; manage later with `vibe capability`.").option("--wait-ready [seconds]","Block until the agent is fully ready (or fails). Polls /health/ready and renders phase transitions live. Without a value, defaults to 60s. Exits non-zero if the agent ends up degraded or times out. Useful for scripts/CI.").option("--no-wait","Skip the phase tracker entirely after spawning the daemon. Restores the old fire-and-print behavior \u2014 for users who want the previous quick-return UX.").action(async function(a){let t={...P.opts(),...a};try{let oe=function(ce){if(ce==="default")return 3005;let he=2166136261;for(let fe=0;fe<ce.length;fe++)he=Math.imul(he^ce.charCodeAt(fe),16777619);return 3100+Math.abs(he)%300},r=new D,h=a.profile||process.env.VIBECONTROLS_PROFILE||"default";if(process.env.VIBECONTROLS_PROFILE=h,typeof a.isolate==="string"&&a.isolate.length>0)process.env.VIBE_ISOLATE_PLUGINS=a.isolate;if(typeof a.profiles==="string"&&a.profiles.length>0){let ce=a.profiles.split(",").map((he)=>he.trim()).filter(Boolean);if(ce.length>0){if(process.env.VIBECONTROLS_PROFILES=ce.join(","),process.env.VIBECONTROLS_PROFILE=ce[0],ce.length>1)p(`--profiles received ${ce.length} entries; daemon boots with '${ce[0]}'. Remaining (${ce.slice(1).join(", ")}) will be attached via /api/profiles after listen.`)}}if(a.strictKeyFetch===!0)process.env.VIBE_STRICT_KEY_FETCH="1";Ct();let O=a.dbPath||ee(),E=C(),N=!Qt(O)&&!Qt(ho(E,"agents.json")),j=_(t),T=j!=="json"&&j!=="plain"&&ue()&&a.yes!==!0,x=Ze(E),L;if(typeof t.abilities==="string"&&t.abilities.trim()!=="")L=bi(t.abilities);else if(x!==null)L=x;else if(T)L=await nr();else L=sr();let Z=typeof t.providers==="string"&&t.providers.trim()!=="",B=Z?Ti(t.providers):Ot(E);if(x===null){let ce=xi({installDeps:a.installDeps===!0,skipPluginInstall:a.skipPluginInstall===!0,skipPlugins:Array.isArray(a.skipPlugin)?a.skipPlugin:[]},L);if(N&&ce.plugins.length>0)c(),o(`Installing ${ce.plugins.length} plugin(s) for the selected abilities.`),c();wi(E,ce,L,process.env.VIBE_AGENT_VERSION,B)}else if(Z)ut(E,{providers:B,agentVersion:process.env.VIBE_AGENT_VERSION});if((N||Z)&&B.length>0&&a.skipPluginInstall!==!0){o(`Installing ${B.length} selected provider plugin(s)...`);try{let{PluginManager:ce}=await import("./plugin-system-e690jr6e.js"),he=new ce;for(let fe of B)try{await he.install(fe),l(`Installed provider ${fe}`)}catch(be){p(`Could not install provider ${fe}: ${be instanceof Error?be.message:String(be)}`)}}catch(ce){p(`Provider install skipped: ${ce instanceof Error?ce.message:String(ce)}`)}c()}if(N){o("First run detected \u2014 running setup..."),c();let ce=Array.isArray(a.skipPlugin)?a.skipPlugin:[],he=a.skipPluginInstall?[]:Ce(process.platform,L).filter((Ae)=>!ce.includes(Ae.packageName)&&!ce.includes(Ae.pluginName)).map((Ae)=>Ae.packageName),fe=Pi(he),He=De(fe).filter((Ae)=>!Ae.installed);if(He.length>0)if(p(`Missing tools: ${He.map((Ae)=>Ae.name).join(", ")}`),a.installDeps)o("Their plugins will install them automatically on startup.");else o("Auto-install skipped (`--no-install-deps`) \u2014 install them yourself or drop the flag.");else l("All plugin tools present.");c()}if(!a.skipPluginInstall){let ce=Array.isArray(a.skipPlugin)?a.skipPlugin:[],he=new W;await he.loadCorePlugins(),await he.loadAll();let fe=await he.ensureDefaultPlugins((be)=>{if(be.startsWith("No "))p(be);else if(be.startsWith("Installed "))l(be);else if(be.startsWith("Failed "))p(be);else o(be)},ce,L);if(fe.length>0)l(`Auto-installed ${fe.length} default plugin${fe.length>1?"s":""}.`),c()}let V=a.profile||process.env.VIBECONTROLS_PROFILE||a.name||"default",K=a.port?parseInt(a.port,10):oe(V);if(isNaN(K)||K<1||K>65535)s("Invalid port number. Must be between 1 and 65535.");let X=await Xt(K);if(X!==K)p(`Port ${K} is in use. Auto-selecting port ${i.bold(String(X))} instead.`),K=X;let se=a.host,Ie=`http://${se==="0.0.0.0"?"localhost":se}:${K}`,ve=a.clientId||process.env.VIBE_CLIENT_ID,de=a.clientSecret||process.env.VIBE_CLIENT_SECRET,pe=a.globalGatewayUrl||process.env.VIBE_GLOBAL_GATEWAY_URL,me=a.workspaceGatewayUrl||process.env.VIBE_WORKSPACE_GATEWAY_URL,Me=a.workspaceId||process.env.VIBE_WORKSPACE_ID;if(ve&&!de)s("--client-secret is required when --client-id is provided.");if(de&&!ve)s("--client-id is required when --client-secret is provided.");if(ve&&de){if(!pe&&!process.env.VIBE_GLOBAL_GATEWAY_URL)s("--global-gateway-url is required when providing client credentials (none set in env).");if(process.env.VIBE_CLIENT_ID=ve,process.env.VIBE_CLIENT_SECRET=de,pe)process.env.VIBE_GLOBAL_GATEWAY_URL=pe;let{writeAgentConfig:ce}=await import("./agent-config-xwvsmn6b.js");if(ce({clientId:ve,clientSecret:de,workspaceId:Me,globalGatewayUrl:pe,workspaceGatewayUrl:me}),me)process.env.VIBE_WORKSPACE_GATEWAY_URL=me;if(Me)process.env.VIBE_WORKSPACE_ID=Me;l("Gateway credentials staged in env. Agent will authenticate and persist them on startup."),c()}else if(me||Me||pe){if(p("Workspace options provided without --client-id / --client-secret \u2014 they will be staged in env but unused until credentials are configured."),me)process.env.VIBE_WORKSPACE_GATEWAY_URL=me;if(Me)process.env.VIBE_WORKSPACE_ID=Me;if(pe)process.env.VIBE_GLOBAL_GATEWAY_URL=pe;c()}if(a.foreground){if(!t.json)g("Starting agent in foreground"),n("Name",a.name),n("Port",String(K)),n("Host",se),n("Database",O),c();let{bootstrapWorkspace:ce}=await import("./bootstrap-workspace-1pt0bwy6.js");ce();let{createApp:he}=await import("./app-ntnpwedw.js"),fe=await he({port:K,host:se,dbPath:O});if(await fe.start(),ve&&de&&Me&&pe&&me){let He=await fe.finalize({clientId:ve,clientSecret:de,workspaceId:Me,globalGatewayUrl:pe,workspaceGatewayUrl:me});if(!He.ok)p(`Finalize failed \u2014 agent remains in awaiting-config state: ${He.error}`)}if(u(t,{ok:!0,name:a.name,port:K,host:se,pid:process.pid,url:Ie}));else await Gt(Ie);let be=async()=>{await fe.stop(),process.exit(0)};process.on("SIGTERM",be),process.on("SIGINT",be)}else{if(!t.json)g("Starting agent in daemon mode"),n("Name",a.name),n("Port",String(K)),n("Host",se),n("Database",O),c();if(a.installDeps===!1)process.env.VIBE_SKIP_PREREQ_INSTALL="1";await r.startDaemon({port:K,name:a.name,daemon:!0,dbPath:O,host:se,profile:h});let he=(await r.getStatus(a.name))?.port??K,fe;if(a.autostart!==!1){let{ensureAutostartConfigured:xe}=await import("./autostart.cmd-mdyv35dn.js"),we=await xe({name:a.name,port:he,dbPath:O,host:se,profile:h});if(fe=we,we.installed&&!t.json)o(`Configured ${we.serviceLabel} autostart \u2014 supervised from the next login/boot. `+"The daemon running now is not yet under it; hand it over with `vibe stop && vibe autostart install`.");else if(we.failed&&!t.json)p(`Could not configure autostart (${we.reason}). This agent will NOT come back after logout or reboot \u2014 fix the cause or run \`vibe autostart install\`.`)}let be=fe?{installed:fe.installed,failed:fe.failed??!1,reason:fe.reason}:{installed:!1,failed:!1,reason:"opted out"},Ae=`http://${se==="0.0.0.0"?"localhost":se}:${he}`,kt=a.waitReady,vt=a.wait===!1,zt=kt!==void 0;if(vt&&zt)p("--wait-ready is ignored because --no-wait was also passed.");let gt=!vt&&zt,Yt=!vt&&(gt||!t.json),Zt=(()=>{let xe=typeof kt==="string"?Number.parseInt(kt,10):NaN;if(Number.isInteger(xe)&&xe>0)return xe*1000;return gt?60000:25000})();if(t.json){if(Yt){let{trackAgentReady:xe}=await import("./agent-ready-tracker-7ebr09d9.js"),we=await xe(Ae,{timeoutMs:Zt,verbose:!1});if(gt&&(we.outcome==="degraded"||we.outcome==="timeout"))process.exitCode=1;u(t,{ok:we.outcome==="ready"||we.outcome==="awaiting-config",name:a.name,port:he,host:se,url:Ae,abilities:[...L],outcome:we.outcome,bootState:we.bootState,degradedReasons:we.degradedReasons,summary:we.summary,autostart:be})}else u(t,{ok:!0,name:a.name,port:he,host:se,url:Ae,autostart:be});return}if(await Gt(Ae),Yt){let{trackAgentReady:xe}=await import("./agent-ready-tracker-7ebr09d9.js");c();let we=await xe(Ae,{timeoutMs:Zt,verbose:!0});if(gt&&(we.outcome==="degraded"||we.outcome==="timeout"))process.exitCode=1}}}catch(r){let h=r instanceof Error?A(r):String(r);if(t.json){u(t,{ok:!1,error:h});return}s(`Failed to start agent: ${h}`)}})}function tn(P){P.command("stop").description("Stop a running VibeControls agent instance").option("-n, --name <name>","Agent instance name","default").option("--all","Stop all running agent instances",!1).option("--json","Emit JSON").action(async function(a){let t={...P.opts(),...a};try{let r=new D;if(a.all){let h=await r.listInstances();if(!h||h.length===0){if(u(t,{ok:!0,stopped:[]}))return;g("Stopping all agent instances"),c(),o(`${d.info} No running agent instances found.`);return}let O=[];if(!t.json)g("Stopping all agent instances"),c();for(let E of h)try{if(await r.stop(E.name),O.push(E.name),!t.json)l(`${d.success} Stopped ${i.bold(E.name)}`)}catch{if(!t.json)s(`Failed to stop ${i.bold(E.name)}`)}if(u(t,{ok:!0,stopped:O,total:h.length}))return;c(),l(`${d.success} Stopped ${O.length}/${h.length} instance(s).`)}else{if(await r.stop(a.name),u(t,{ok:!0,name:a.name}))return;g(`Stopping agent: ${a.name}`),c(),l(`${d.success} Agent ${i.bold(a.name)} stopped.`)}}catch(r){if(t.json){u(t,{ok:!1,error:A(r)});return}s(`Failed to stop agent: ${A(r)}`)}})}function nn(P){P.command("restart").description("Restart a running VibeControls agent instance").option("-n, --name <name>","Agent instance name","default").option("-p, --port <port>","Port to listen on").option("--db-path <path>","Path to the agent storage directory").option("--json","Emit JSON").option("--no-autostart","Don't configure OS-level autostart for this agent. Without it the daemon dies with the session that started it and will not come back.").action(async function(a){let t={...P.opts(),...a};try{let r=new D;if(!t.json)g(`Restarting agent: ${a.name}`),c(),o(`${d.info} Stopping agent ${i.bold(a.name)}...`);let h=await r.getStatus(a.name);try{if(await r.stop(a.name),!t.json)l(`${d.success} Agent stopped.`)}catch{if(!t.json)o(`${d.info} Agent was not running.`)}let O=a.port??h?.port??3005,E=typeof O==="number"?O:parseInt(O,10);if(isNaN(E)||E<1||E>65535){if(t.json){u(t,{ok:!1,error:"Invalid port number"});return}s("Invalid port number. Must be between 1 and 65535.");return}let N=t.profile??h?.config?.profile??process.env.VIBECONTROLS_PROFILE??"default";process.env.VIBECONTROLS_PROFILE=N;let j={port:E,name:a.name,daemon:!0,dbPath:a.dbPath??h?.config?.dbPath??ee(),host:h?.config?.host,profile:N};if(!t.json)c(),o(`${d.info} Starting agent ${i.bold(a.name)}...`);await r.startDaemon(j);let T;if(a.autostart!==!1){let{ensureAutostartConfigured:L}=await import("./autostart.cmd-mdyv35dn.js");T=await L({name:a.name,port:E,dbPath:j.dbPath,host:j.host,profile:j.profile});let Z=T;if(Z.installed&&!t.json)o(`Configured ${Z.serviceLabel} autostart \u2014 supervised from the next login/boot. `+"The daemon running now is not yet under it; hand it over with `vibe stop && vibe autostart install`.");else if(Z.failed&&!t.json)p(`Could not configure autostart (${Z.reason}). This agent will NOT come back after logout or reboot \u2014 fix the cause or run \`vibe autostart install\`.`)}let x=`http://localhost:${E}`;if(u(t,{ok:!0,name:a.name,port:E,url:x,autostart:T?{installed:T.installed,failed:T.failed??!1,reason:T.reason}:{installed:!1,failed:!1,reason:"opted out"}}))return;c(),l(`${d.success} Agent ${i.bold(a.name)} restarted.`),c(),n("Port",String(E)),n("Database",j.dbPath),c(),Gt(x)}catch(r){if(t.json){u(t,{ok:!1,error:A(r)});return}s(`Failed to restart agent: ${A(r)}`)}})}import{existsSync as bo,readFileSync as yo,unlinkSync as on}from"fs";import{join as sn}from"path";function wo(P){let a=sn(ne(),P,"runtime.json");if(!bo(a))return null;try{let t=JSON.parse(yo(a,"utf8"));if(typeof t.pid!=="number")return null;return{...t,pid:t.pid,path:a}}catch{return null}}async function rn(P){let a=wo(P);if(!a)return null;if(!ae(a.pid)){try{on(a.path)}catch{}return`agent pid=${a.pid} (${P}) already gone (cleaned runtime.json).`}let t=b();if(!t.killProcessTree(a.pid,"SIGTERM"))return`failed to SIGTERM agent pid=${a.pid}.`;if(await new Promise((r)=>setTimeout(r,3000)),ae(a.pid))t.killProcessTree(a.pid,"SIGKILL");try{on(a.path)}catch{}return`agent ${P} pid=${a.pid}${a.port?` (port ${a.port})`:""} killed.`}async function ko(P){let a=sn(ne(),P),t=te(a);if(!t)return null;if(!ae(t.pid))return re(a),`tunnel pid=${t.pid} already gone (cleaned state).`;let r=b();if(!r.killProcessTree(t.pid,"SIGTERM"))return`failed to SIGTERM tunnel pid=${t.pid}.`;if(await new Promise((h)=>setTimeout(h,3000)),ae(t.pid))r.killProcessTree(t.pid,"SIGKILL");return re(a),`tunnel ${t.provider} pid=${t.pid} (${t.url??"no url"}) killed.`}function an(P){P.command("kill").description("Force-kill an agent instance and its tunnel. Defaults to active profile.").option("-n, --name <name>","Agent instance name (alias of --profile, kept for back-compat)").option("--profile <name>","Kill a specific profile (overrides --name and VIBECONTROLS_PROFILE)").option("--all","Kill every agent instance and every profile's tunnel",!1).option("-y, --yes","Skip the confirmation prompt (for scripts/CI)",!1).option("--json","Emit JSON").action(async function(a){let t={...P.opts(),...a},r=a.all?"ALL agent instances + every profile's tunnel":`agent '${t.profile??t.name??"active profile"}'`;if(!await jt(t,`Force-kill ${r}? This sends SIGKILL (no graceful shutdown).`)){o("Aborted.");return}let h=[];try{let O=new D;if(a.all){if(!t.json)g("Force killing all agent instances + tunnels"),c();let T=await O.listInstances()??[],x=0,L=new Set;for(let V of T)try{if(await O.kill(V.name),!t.json)l(`${d.success} agent ${i.bold(V.name)} (pid=${V.pid||"?"}) killed.`);h.push(V.name),x++,L.add(V.name)}catch{if(!t.json)p(`${d.warning} could not kill agent ${V.name}.`)}try{let V=await import("fs"),oe=ne(),K=V.existsSync(oe)?V.readdirSync(oe):[];for(let X of K){if(L.has(X))continue;let se=await rn(X);if(se)l(`${d.success} ${se}`),x++}}catch(V){p(`${d.warning} runtime.json sweep failed: ${V instanceof Error?A(V):String(V)}`)}let Z=qi({allProfiles:!0}),B=0;for(let V of Z){if(!V.alive){re(V.profileDir);continue}let oe=b();if(oe.killProcessTree(V.pid,"SIGTERM"),await new Promise((K)=>setTimeout(K,3000)),ae(V.pid))oe.killProcessTree(V.pid,"SIGKILL");re(V.profileDir),l(`${d.success} tunnel ${V.provider} pid=${V.pid} (${V.url??"no url"}, ${V.profileDir.split("/").pop()}) killed.`),B++}if(u(t,{ok:!0,killed:h,tunnels:B}))return;c(),l(`${d.success} killed ${x} agent(s) and ${B} tunnel(s).`);return}let E=a.profile||a.name||R();if(!t.json)g(`Force killing profile: ${E}`),c();let N=await O.getStatus(E);if(N){if(await O.kill(E),h.push(E),!t.json)l(`${d.success} agent ${i.bold(E)} pid=${N.pid||"?"} killed.`)}else{let T=await rn(E);if(T){if(h.push(E),!t.json)l(`${d.success} ${T}`)}else if(!t.json)o(`${d.info} no running agent service for profile ${E}.`)}let j=await ko(E);if(j){if(!t.json)l(`${d.success} ${j}`)}else if(!t.json)o(`${d.info} no tunnel recorded for profile ${E}.`);u(t,{ok:!0,killed:h})}catch(O){if(t.json){u(t,{ok:!1,error:A(O)});return}s(`Failed to kill: ${A(O)}`)}})}function ln(P){P.command("list").alias("ls").description("List all VibeControls agent instances").option("--json","Emit JSON").option("--plain","Force plain text output").action(async function(a){try{let t={...P.opts(),...a},r=new D;await y({mode:_(t),fetchData:()=>r.listInstances(),plain:(h)=>{if(g("Agent Instances"),c(),!h||h.length===0){o(`${d.info} No agent instances found.`),o(`Run ${i.bold("vibe start")} to start an agent.`);return}let O=h.map((j)=>({Name:j.name,Status:G(j.status),PID:j.pid||"-",Port:j.port||"-",Host:j.config?.host||"-",Database:j.config?.dbPath||"-",Started:j.startTime?v(j.startTime):"-"}));F(O),c();let E=h.filter((j)=>j.status==="running").length,N=h.length-E;o(`${d.info} ${h.length} instance(s): ${i.green(String(E))} running, ${i.dim(String(N))} stopped`)},interactive:async(h)=>{if(!h||h.length===0){g("Agent Instances"),c(),o(`${d.info} No agent instances found.`),o(`Run ${i.bold("vibe start")} to start an agent.`);return}let O=h.map((E)=>{let N=[`${i.bold(E.name)} ${G(E.status)}`,"",` PID: ${E.pid??"-"}`,` Port: ${E.port??"-"}`,` Host: ${E.config?.host??"-"}`,` Database: ${E.config?.dbPath??"-"}`,` Started: ${E.startTime?v(E.startTime):"-"}`];return{id:E.name,label:E.name,hint:E.status==="running"?"running":"stopped",detail:N.join(`
|
|
3
3
|
`)}});await Q({title:`vibe list \u2014 ${h.length} instance(s)`,rows:O,footer:"\u2191/\u2193 navigate \xB7 q to quit"})},json:(h)=>h.map((O)=>({name:O.name,status:O.status,pid:O.pid??null,port:O.port??null,host:O.config?.host??null,database:O.config?.dbPath??null,startTime:O.startTime??null}))})}catch(t){s(`Failed to list instances: ${t.message}`)}})}var cn=5000;function dn(P){P.command("logs").description("View logs for a VibeControls agent instance").option("-n, --name <name>","Agent instance name","default").option("-f, --follow","Follow log output",!1).option("--tail <lines>","Number of lines to show from the end","100").option("--json","Emit JSON (one object per line, banners suppressed)").option("--plain","Force plain text output").action(async function(a){try{let t={...P.opts(),...a},r=new D,h=parseInt(t.tail??"100",10);if(isNaN(h)||h<1||h>cn){s(`Invalid tail value. Must be between 1 and ${cn}.`);return}let O=t.name??"default";if(!await r.getStatus(O)){s(`Agent instance ${i.bold(O)} not found.`);return}if(!t.json){if(t.follow)g(`Following logs: ${O}`),o(`${d.info} Press Ctrl+C to stop following.`);else g(`Logs: ${O}`);c()}await r.showLogs(O,{follow:!!t.follow,tail:h})}catch(t){s(`Failed to get logs: ${A(t)}`)}})}function un(P){P.command("setup").description("Install system dependencies and (optionally) write gateway auth config").option("--check","Only check dependencies without installing",!1).option("--client-id <id>","OAuth app client ID (for backend authentication)").option("--client-secret <secret>","OAuth app client secret").option("--workspace-id <id>","Workspace UUID this agent belongs to").option("--global-gateway-url <url>","Global public gateway URL (default: http://localhost:4000/global/graphql)").option("--workspace-gateway-url <url>","Workspace gateway URL (default: http://localhost:4001/workspaces/graphql)").option("--storage-adapter <name>","Named storage adapter (default: skalex, or custom:<path>)").option("--json","Emit JSON").action(async function(a){let t={...P.opts(),...a},r=[];try{if(!t.json)g("VibeControls Agent Setup");let h={};if(a.clientId)h.clientId=a.clientId;if(a.clientSecret)h.clientSecret=a.clientSecret;if(a.workspaceId)h.workspaceId=a.workspaceId;if(a.globalGatewayUrl)h.globalGatewayUrl=z(a.globalGatewayUrl,"globalGatewayUrl");if(a.workspaceGatewayUrl)h.workspaceGatewayUrl=z(a.workspaceGatewayUrl,"workspaceGatewayUrl");if(a.storageAdapter)h.storageAdapter=a.storageAdapter;if(Object.keys(h).length>0){let x=M(h);if(r.push(...Object.keys(h)),!t.json){l(`Agent config written to ${st()}`),n("clientId",x.clientId?i.dim("(set)"):i.dim("(unset)")),n("clientSecret",x.clientSecret?i.dim("(set)"):i.dim("(unset)")),n("workspaceId",x.workspaceId??i.dim("(unset)"));let L=Sr();if(n("globalGatewayUrl",x.globalGatewayUrl??L.globalGatewayUrl),n("workspaceGatewayUrl",x.workspaceGatewayUrl??L.workspaceGatewayUrl),x.storageAdapter)n("storageAdapter",x.storageAdapter);c()}}else{let x=w();if((x.clientId||x.clientSecret||x.workspaceId)&&!t.json)o(`Using existing agent config at ${st()} (pass --client-id/--client-secret/--workspace-id to update).`),c()}if(!t.json)o("Checking dependencies..."),c();let O=De(),E=[],N=[];for(let x of O){if(x.installed)N.push(x.name);if(!t.json){let L=x.installed?d.success:d.error,Z=x.version?i.dim(` (${x.version})`):"",B=x.required?"":i.dim(" [optional]");n(`${L} ${x.name}`,`${x.installed?i.green("installed"):i.red("missing")}${Z}${B}`)}if(!x.installed)E.push(x.name)}if(!t.json)c();if(E.length===0){if(u(t,{ok:!0,installed:N,configured:r}))return;l("All dependencies are installed.");return}if(a.check){if(t.json){u(t,{ok:!1,installed:N,missing:E,configured:r});return}p(`Missing: ${E.join(", ")}`),o(`Run ${i.bold("vibe setup")} to install them.`),process.exit(1)}if(!t.json)o(`Installing missing dependencies: ${E.join(", ")}...`),c();let j=await ct(E),T=E.filter((x)=>!j.failed.includes(x));if(j.failed.length>0){if(t.json){u(t,{ok:!1,installed:[...N,...T],failed:j.failed,configured:r});return}p(`${j.failed.length} tool(s) failed: ${j.failed.join(", ")}`),o("You may need to install manually or use sudo."),process.exit(1)}else{if(u(t,{ok:!0,installed:[...N,...T],configured:r}))return;l("All dependencies installed successfully.")}}catch(h){let O=h instanceof Error?A(h):String(h);if(t.json){u(t,{ok:!1,error:O});return}s(`Setup failed: ${O}`)}})}function vo(P){let a=b();return a.which(P)??`${P}${a.executableSuffix}`}function pn(P){P.command("update").description("Check for and install VibeControls agent updates").option("--check","Only check for updates without installing",!1).option("--allow-incompatible","Override engines.bun compatibility check (use with care)",!1).option("--no-restart","Skip the post-install idle-aware restart of any running agent").option("-n, --name <name>","Agent profile name to restart after update","default").option("--version-target <version>","Install a specific version instead of the latest (e.g. 2026.601.21)").option("--json","Emit JSON").action(async function(a){let t={...P.opts(),...a};try{if(!t.json)g("VibeControls Agent Update"),c(),o(`${d.info} Checking for updates...`),c();let r=await Le();if(r.error&&!r.latest){if(u(t,{ok:!1,current:r.current,error:r.error}))return;s(r.error);return}if(!t.json)n("Package",i.bold(r.name)),n("Registry",i.bold(r.registry)),n("Current version",i.bold(r.current)),n("Latest version",i.bold(r.latest??"unknown")),c();if(a.check){if(u(t,{ok:!0,current:r.current,latest:r.latest,upToDate:!r.hasUpdate}))return;if(!r.hasUpdate)l(`${d.success} You are running the latest version.`);else p(`${d.warning} A new version is available: ${i.green(r.latest??"")}`),o(`${d.info} Run ${i.bold("vibe update")} to install the update.`);return}let h=a.versionTarget;if(!h&&!r.hasUpdate){if(u(t,{ok:!0,current:r.current,latest:r.latest,upToDate:!0}))return;l(`${d.success} You are running the latest version.`);return}if(!t.json)o(`${d.info} Updating to ${i.bold(h??r.latest??"latest")}...`),c();let O=await ze({targetVersion:h,allowIncompatible:!!a.allowIncompatible,restart:a.restart!==!1,name:a.name,onLog:t.json?void 0:(E)=>o(`${d.info} ${E}`)});if(!O.ok){if(u(t,{ok:!1,current:O.current,previous:O.previous,latest:O.latest,rolledBack:O.rolledBack,error:O.error}))return;s(O.error??"Update failed.");return}if(!t.json)switch(O.restart){case"restarted":l(`${d.success} Restarted agent ${i.bold(a.name)} on the new version.`);break;case"not-running":o(`${d.info} No running agent for profile ${i.bold(a.name)}; nothing to restart.`);break;case"still-busy":p(`${d.warning} Agent still serving requests \u2014 run ${i.bold("vibe restart")} when it's quiet.`);break;case"error":p(`${d.warning} Auto-restart failed: ${O.restartError}. Run ${i.bold("vibe restart")} manually.`);break}if(u(t,{ok:!0,current:O.current,previous:O.previous,latest:O.latest,updated:O.updated,restart:O.restart,...O.restartError?{restartError:O.restartError}:{}}))return;if(c(),O.updated)l(`${d.success} Updated to ${i.bold(O.current)} (smoke: ${O.smoke?.step??"ok"}).`);else l(`${d.success} You are running the latest version.`);if(a.restart===!1)o(`${d.info} --no-restart set \u2014 restart running agents manually for the update to take effect.`)}catch(r){let h=r instanceof Error?A(r):String(r);if(t.json){u(t,{ok:!1,error:h});return}s(`Update failed: ${h}`)}}),P.command("rollback").description("Roll the global agent install back to a specific version").argument("<version>","Target CalVer version (e.g. 2026.428.3)").action(async(a)=>{try{g("VibeControls Agent Rollback");let t=await Ar();if(n("Package",i.bold(t.name)),n("Current version",i.bold(t.version)),n("Target version",i.bold(a)),c(),o(`${d.info} Rolling back\u2026`),Bun.spawnSync([vo("npm"),"install","-g",`${t.name}@${a}`,`--registry=${t.registry}`],{stdout:"inherit",stderr:"inherit"}).exitCode!==0){s("Rollback failed.");return}l(`${d.success} Rolled back to ${i.bold(a)}.`)}catch(t){s(`Rollback failed: ${t instanceof Error?A(t):String(t)}`)}})}import{existsSync as Be,mkdirSync as $o,writeFileSync as Rt,unlinkSync as So,readFileSync as $t}from"fs";import{join as Fe}from"path";import{homedir as Ye}from"os";var Co=/^[A-Za-z0-9][A-Za-z0-9:_-]{0,63}$/,Po=/^--[A-Za-z0-9][A-Za-z0-9-]{0,63}$/;function hn(P){return Co.test(P)?P:null}function bn(P){return P.filter((a)=>hn(a))}function Ro(P){return P.filter((a)=>Po.test(a))}function Qe(P){return P.commands.flatMap((a)=>{let t=hn(a.name());if(!t)return[];return[{name:t,description:a.description()||"",options:a.options.map((r)=>({flags:r.flags,description:r.description||""})),subcommands:Qe(a)}]})}function Ao(P){return bn(P.map((a)=>a.name))}function Io(P,a){let t=P.find((h)=>h.name===a);if(!t)return[];let r=[];for(let h of t.options){let O=h.flags.match(/--([\w-]+)/);if(O)r.push(`--${O[1]}`)}return Ro(r)}function yn(P){let a=Ao(P),r=P.filter((O)=>O.subcommands.length>0).map((O)=>({name:O.name,subs:bn(O.subcommands.map((E)=>E.name))})).map((O)=>` ${O.name})
|
|
4
4
|
COMPREPLY=($(compgen -W "${O.subs.join(" ")}" -- "\${cur}"))
|
|
5
5
|
return 0
|
|
@@ -112,5 +112,5 @@ Enter: print this help and exit
|
|
|
112
112
|
`);return}if(!r.plain&&ue()){if(await zr(P))return}no(P,!!r.plain)}})}var Yr="http://localhost:3005",Zr=5000;function Qr(P,a,t){let r=Number.parseInt(P,10);if(!Number.isInteger(r)||r<1)return a;return Math.min(r,t)}function io(P){P.command("audit").description("View persistent audit log").command("list").description("List recent audit events").option("--since <iso>","Lower-bound ISO 8601 timestamp").option("--limit <n>","Maximum events to show","100").option("--event <pattern>","Filter by event name (supports * glob)").option("--agent-url <url>","Agent URL",Yr).option("--json","Emit JSON (one object per line)").option("--plain","Force plain text output").action(async function(t){try{let r={...P.opts(),...t},h=f(r),O=encodeURIComponent(m(r)),E=new URLSearchParams;if(E.set("limit",String(Qr(String(r.limit),100,Zr))),r.since)E.set("since",String(r.since));if(r.event)E.set("event",String(r.event));let j=(await S(h,`/api/profiles/${O}/agent/audit?${E.toString()}`)).events??[];if(r.json){for(let T of j)process.stdout.write(`${JSON.stringify(T)}
|
|
113
113
|
`);return}if(j.length===0){o("No audit events found.");return}g("Audit events"),c();for(let T of j){let x=T.timestamp?i.dim(v(T.timestamp)):"",L=T.source?i.cyan(`[${T.source}]`):"",Z=i.bold(T.event??"?"),B=T.payload?i.dim(JSON.stringify(T.payload)):"";console.log(` ${Z} ${L} ${B} ${x}`)}}catch(r){s(A(r))}})}function so(P){let a=P.command("alias").description("Manage per-profile aliases");a.command("list").description("List aliases for the current profile").option("--json","Emit JSON").option("--plain","Force plain text output").action(async function(t){try{let r={...P.opts(),...t},h=f(r),O=encodeURIComponent(m(r));await y({mode:_(r),fetchData:async()=>(await S(h,`/api/profiles/${O}/agent/aliases`)).aliases??[],plain:(E)=>{if(g("Aliases"),c(),!E.length){o("No aliases defined.");return}let N=E.map((j)=>({Name:j.name,Command:j.command.length>60?`${j.command.slice(0,57)}\u2026`:j.command,Description:j.description??"-",Updated:v(j.updatedAt)}));F(N),c()}})}catch(r){s(A(r))}}),a.command("get <name>").description("Show an alias by name").option("--json","Emit JSON").action(async function(t,r){try{let h={...P.opts(),...r},O=f(h),E=encodeURIComponent(m(h)),N=await S(O,`/api/profiles/${E}/agent/aliases/${encodeURIComponent(t)}`);if(h.json){process.stdout.write(`${JSON.stringify(N,null,2)}
|
|
114
114
|
`);return}g(`Alias: ${N.name}`),c(),console.log(` ${i.bold("Command: ")} ${N.command}`),console.log(` ${i.bold("Description:")} ${N.description??"-"}`),console.log(` ${i.bold("Cwd: ")} ${N.cwd??"$HOME (default)"}`),console.log(` ${i.bold("Profile: ")} ${N.profile}`),console.log(` ${i.bold("Created: ")} ${N.createdAt}`),console.log(` ${i.bold("Updated: ")} ${N.updatedAt}`),c()}catch(h){s(A(h))}}),a.command("create <name>").description("Create a new alias").requiredOption("--command <cmd>","The shell command to run").option("--description <text>","Optional description").option("--cwd <dir>","Working directory the command runs in (supports ~, absolute, or relative-to-$HOME). Defaults to $HOME.").action(async function(t,r){try{let h={...P.opts(),...r},O=f(h),E=encodeURIComponent(m(h)),N=await q(O,`/api/profiles/${E}/agent/aliases`,{name:t,command:r.command,description:r.description,cwd:r.cwd});l(`Created alias '${N.name}'`)}catch(h){s(A(h))}}),a.command("update <name>").description("Update an existing alias").option("--command <cmd>","Replacement shell command").option("--description <text>","Replacement description").option("--cwd <dir>","Replacement working directory. Pass an empty string to reset to $HOME.").action(async function(t,r){try{if(r.command===void 0&&r.description===void 0&&r.cwd===void 0){s("Provide --command, --description, or --cwd to update.");return}let h={...P.opts(),...r},O=f(h),E=encodeURIComponent(m(h)),N=await Te(O,`/api/profiles/${E}/agent/aliases/${encodeURIComponent(t)}`,{command:r.command,description:r.description,cwd:r.cwd});l(`Updated alias '${N.name}'`)}catch(h){s(A(h))}}),a.command("delete <name>").description("Delete an alias").action(async function(t,r){try{let h={...P.opts(),...r},O=f(h),E=encodeURIComponent(m(h));await ge(O,`/api/profiles/${E}/agent/aliases/${encodeURIComponent(t)}`),l(`Deleted alias '${t}'`)}catch(h){s(A(h))}})}function ao(P){P.command("run <name> [args...]").description("Run a stored alias by name").allowUnknownOption(!0).action(async function(a,t=[],r){try{let h={...P.opts(),...r},O=f(h),E=encodeURIComponent(m(h)),N;try{N=await S(O,`/api/profiles/${E}/agent/aliases/${encodeURIComponent(a)}`)}catch{console.error(`alias '${a}' not found`),e().audit.emit("agent","alias.executed",{exit_code:1}),process.exit(1)}let{exitCode:j}=await Ii(N,t);e().audit.emit("agent","alias.executed",{exit_code:j}),Ke("alias.executed",{exit_code:j}),process.exit(j)}catch(h){s(A(h))}})}function lo(P){P.command("retry-config").description("Force the background finalize-retry worker to attempt finalize immediately. Use when the gateway came back online and you don't want to wait the current backoff.").option("--json","Emit JSON").action(async function(a){let t={...P.opts(),...a};try{let r=f(t),h=await fetch(`${r}/api/agent/retry-config`,{method:"POST"}),O;try{O=await h.json()}catch{if(t.json)u(t,{ok:!1,error:`agent returned non-JSON (HTTP ${h.status})`}),process.exit(1);s(`Agent returned non-JSON response (HTTP ${h.status}). The daemon may be on an older build without /api/agent/retry-config.`),process.exit(1);return}if(t.json){if(u(t,O),O.state!=="ready")process.exit(O.ok?0:3);return}if(h.status===409){g("Retry not available"),o(O.error??"No active finalize-retry worker."),process.exit(2);return}if(g("Force finalize retry"),n("Result",O.ok?i.green("ok"):i.red("failed")),O.state)n("Boot state",O.state);if(O.worker){if(n("Attempt",String(O.worker.attempt)),O.worker.nextAttemptAt)n("Next attempt",O.worker.nextAttemptAt)}if(c(),O.ok&&O.state==="ready")o(`${i.green("\u2713")} Agent finalized \u2014 state=ready.`),process.exit(0);else if(O.ok)o(`${i.yellow("\u26A0")} Attempt completed but agent is still in '${O.state}'. The worker will continue to retry in the background; check ${i.bold("vibe status")} for progress.`),process.exit(0);else p(`Retry failed: ${O.error??"unknown error"}. The worker will keep retrying on the configured backoff. View the full trace with ${i.bold("vibe logs --since 10m")}.`),process.exit(3)}catch(r){let h=r instanceof Error?A(r):String(r);if(t.json){u(t,{ok:!1,error:h}),process.exit(1);return}s(`Failed to reach agent: ${h}`),process.exit(1)}})}var Oe="http://localhost:3005";function ti(P){return(P||[]).map((a)=>({id:a.id??null,name:a.name??null,status:a.status??null,port:a.port??null,project:a.project??a.projectId??null}))}async function co(P,a,t,r,h){await y({mode:_(h),fetchData:async()=>(await S(P,a)).sessions||[],plain:(O)=>{if(!O||O.length===0){o(r);return}g(t),F(O.map((E)=>({ID:H(E.id||""),Name:E.name||"-",Status:G(E.status||""),Port:E.port??"-",Project:E.project||E.projectId||"-"})))},interactive:async(O)=>{if(!O||O.length===0){g(t),o(r);return}let E=O.map((N)=>({id:String(N.id??""),label:N.name||H(N.id||""),hint:N.status||"",detail:[`ID: ${N.id??"-"}`,`Name: ${N.name??"-"}`,`Status: ${G(N.status||"")}`,`Port: ${N.port??"-"}`,`Project: ${N.project??N.projectId??"-"}`].join(`
|
|
115
|
-
`)}));await Q({title:`${t} \u2014 ${O.length} session(s)`,rows:E})},json:(O)=>ti(O)})}function uo(P){let a=P.command("session").description("Manage terminal sessions");a.command("system").description("List system sessions (alias for `session list --system`)").option("--agent-url <url>","Agent URL",Oe).option("--json","Emit JSON").option("--plain","Force plain text output").action(async function(t){let r={...P.opts(),...t};try{let h=f(t),O=encodeURIComponent(m(r));await co(h,`/api/profiles/${O}/sessions/system`,"System Sessions","No system sessions found.",r)}catch(h){s(A(h))}}),a.command("list").description("List all sessions").option("--system","Show system sessions instead of user sessions").option("--agent-url <url>","Agent URL",Oe).option("--json","Emit JSON").option("--plain","Force plain text output").action(async function(t){let r={...P.opts(),...t};try{let h=f(t),O=encodeURIComponent(m(r)),E=t.system?`/api/profiles/${O}/sessions/system`:`/api/profiles/${O}/sessions`;await co(h,E,"Sessions","No sessions found.",r)}catch(h){s(A(h))}}),a.command("create").description("Create a new session").requiredOption("--name <name>","Session name").option("--project <id>","Project ID","default").option("--command <cmd>","Initial command to run").option("--cwd <dir>","Working directory").option("--agent-url <url>","Agent URL",Oe).option("--json","Emit JSON").action(async function(t){let r={...P.opts(),...t};try{let h=f(t),O=encodeURIComponent(m(r)),E={sessionName:t.name,projectId:t.project};if(t.command)E.command=t.command;if(t.cwd)E.startDirectory=t.cwd;let N=await q(h,`/api/profiles/${O}/sessions/create`,E),j=N?.session?.id||N?.id||N?.sessionId;if(u(r,{ok:!0,id:j,name:t.name,project:t.project}))return;l(`Session created: ${H(j)}`),n("Name",t.name),n("Project",t.project)}catch(h){if(r.json){u(r,{ok:!1,error:A(h)});return}s(A(h))}}),a.command("kill").description("Kill a session").requiredOption("-i, --id <id>","Session ID").option("--agent-url <url>","Agent URL",Oe).option("--json","Emit JSON").action(async function(t){let r={...P.opts(),...t};try{let h=f(t),O=encodeURIComponent(m(r));if(await ge(h,`/api/profiles/${O}/sessions/${t.id}`),u(r,{ok:!0,id:t.id}))return;l(`Session ${H(t.id)} killed.`)}catch(h){if(r.json){u(r,{ok:!1,error:A(h)});return}s(A(h))}}),a.command("exec").description("Execute a command in a session").requiredOption("-i, --id <id>","Session ID").requiredOption("-c, --command <cmd>","Command to execute").option("--agent-url <url>","Agent URL",Oe).option("--json","Emit JSON").action(async function(t){let r={...P.opts(),...t};try{let h=f(t),O=encodeURIComponent(m(r)),E=await q(h,`/api/profiles/${O}/sessions/${t.id}/command`,{command:t.command});if(u(r,{ok:!0,id:t.id,output:E?.output??null}))return;if(l("Command executed."),E?.output)c(),console.log(E.output)}catch(h){if(r.json){u(r,{ok:!1,error:A(h)});return}s(A(h))}}),a.command("capture").description("Capture session terminal output").requiredOption("-i, --id <id>","Session ID").option("--agent-url <url>","Agent URL",Oe).option("--json","Emit JSON").option("--plain","Force plain text output").action(async function(t){let r={...P.opts(),...t};try{let h=f(t),O=encodeURIComponent(m(r));await y({mode:_(r),fetchData:()=>S(h,`/api/profiles/${O}/sessions/${t.id}/capture`),plain:(E)=>{if(E?.content||E?.output)console.log(E.content||E.output);else o("No capture data available.")},json:(E)=>({id:t.id,content:E?.content??E?.output??null})})}catch(h){s(A(h))}}),a.command("keys").description("Send keys to a session").requiredOption("-i, --id <id>","Session ID").requiredOption("-k, --keys <keys>","Keys to send").option("--agent-url <url>","Agent URL",Oe).option("--json","Emit JSON").action(async function(t){let r={...P.opts(),...t};try{let h=f(t),O=encodeURIComponent(m(r));if(await q(h,`/api/profiles/${O}/sessions/${t.id}/keys`,{keys:t.keys}),u(r,{ok:!0,id:t.id}))return;l("Keys sent.")}catch(h){if(r.json){u(r,{ok:!1,error:A(h)});return}s(A(h))}}),a.command("interrupt").description("Send interrupt signal to a session").requiredOption("-i, --id <id>","Session ID").option("--agent-url <url>","Agent URL",Oe).option("--json","Emit JSON").action(async function(t){let r={...P.opts(),...t};try{let h=f(t),O=encodeURIComponent(m(r));if(await q(h,`/api/profiles/${O}/sessions/${t.id}/interrupt`,{}),u(r,{ok:!0,id:t.id}))return;l(`Session ${H(t.id)} interrupted.`)}catch(h){if(r.json){u(r,{ok:!1,error:A(h)});return}s(A(h))}}),a.command("rename").description("Rename a session").requiredOption("-i, --id <id>","Session ID").requiredOption("--name <name>","New session name").option("--agent-url <url>","Agent URL",Oe).option("--json","Emit JSON").action(async function(t){let r={...P.opts(),...t};try{let h=f(t),O=encodeURIComponent(m(r));if(await Te(h,`/api/profiles/${O}/sessions/${t.id}/rename`,{newName:t.name}),u(r,{ok:!0,id:t.id,name:t.name}))return;l(`Session ${H(t.id)} renamed to "${t.name}".`)}catch(h){if(r.json){u(r,{ok:!1,error:A(h)});return}s(A(h))}}),a.command("toggle-mouse").description("Toggle mouse support in a session").requiredOption("-i, --id <id>","Session ID").option("--agent-url <url>","Agent URL",Oe).option("--json","Emit JSON").action(async function(t){let r={...P.opts(),...t};try{let h=f(t),O=encodeURIComponent(m(r)),E=await q(h,`/api/profiles/${O}/sessions/${t.id}/toggle-mouse`,{});if(u(r,{ok:!0,id:t.id,mouseEnabled:!!E?.mouseEnabled}))return;l(`Mouse support ${E?.mouseEnabled?"enabled":"toggled"} for session ${H(t.id)}.`)}catch(h){if(r.json){u(r,{ok:!1,error:A(h)});return}s(A(h))}}),a.command("terminal-start").description("Start terminal for a session").requiredOption("-i, --id <id>","Session ID").option("--agent-url <url>","Agent URL",Oe).option("--json","Emit JSON").action(async function(t){let r={...P.opts(),...t};try{let h=f(t),O=encodeURIComponent(m(r)),E=await q(h,`/api/profiles/${O}/sessions/${t.id}/terminal`,{});if(u(r,{ok:!0,id:t.id,port:E?.port??null}))return;if(l(`Terminal started for session ${H(t.id)}.`),E?.port)n("Port",E.port)}catch(h){if(r.json){u(r,{ok:!1,error:A(h)});return}s(A(h))}}),a.command("terminal-stop").description("Stop terminal for a session").requiredOption("-i, --id <id>","Session ID").option("--agent-url <url>","Agent URL",Oe).option("--json","Emit JSON").action(async function(t){let r={...P.opts(),...t};try{let h=f(t),O=encodeURIComponent(m(r));if(await q(h,`/api/profiles/${O}/sessions/${t.id}/terminal/stop`,{}),u(r,{ok:!0,id:t.id}))return;l(`Terminal stopped for session ${H(t.id)}.`)}catch(h){if(r.json){u(r,{ok:!1,error:A(h)});return}s(A(h))}}),a.command("health-check").description("Run health check on all sessions").option("--agent-url <url>","Agent URL",Oe).option("--json","Emit JSON").action(async function(t){let r={...P.opts(),...t};try{let h=f(t),O=encodeURIComponent(m(r)),E=await S(h,`/api/profiles/${O}/sessions`),N=await q(h,`/api/profiles/${O}/sessions/health-check`,{sessionIds:(E.sessions||[]).map((j)=>j.id)});if(u(r,{ok:!0,healthy:N?.healthy??null,checked:N?.checked??null,fixed:N?.fixed??null}))return;if(l("Health check completed."),N?.healthy!==void 0)n("Healthy",N.healthy);if(N?.checked!==void 0)n("Checked",N.checked);if(N?.fixed!==void 0)n("Fixed",N.fixed)}catch(h){if(r.json){u(r,{ok:!1,error:A(h)});return}s(A(h))}})}function po(P){P.command("reuse-db").description("Point this agent at an EXISTING database (reuse data from another same-workspace agent)").option("--adapter <name>","Storage adapter to use (e.g. postgres, skalex). Defaults to the configured/default adapter.").option("--connection-string <conn>","Connection string for the adapter (e.g. postgres://user:pass@host/db)").option("--storage-options <json>","Raw adapter options as a JSON object (alternative/in addition to --connection-string)").option("--db-path <path>","Data directory the adapter should use (e.g. an existing Skalex agent-db dir)").option("-y, --yes","Skip the confirmation prompt").option("--json","Emit JSON").action(async function(a){let t={...P.opts(),...a};try{let r={};if(a.storageOptions){let E;try{E=JSON.parse(a.storageOptions)}catch{s("--storage-options must be valid JSON.");return}if(!E||typeof E!=="object"||Array.isArray(E)){s("--storage-options must be a JSON object.");return}for(let[N,j]of Object.entries(E))r[N]=typeof j==="string"?j:JSON.stringify(j)}if(a.connectionString)r.connectionString=String(a.connectionString);if(!a.adapter&&!a.dbPath&&Object.keys(r).length===0){s("Nothing to set. Provide --adapter with --connection-string (or --storage-options), and/or --db-path.");return}if(!t.json){if(g("Reuse an existing database"),a.adapter)n("Adapter",i.bold(a.adapter));if(a.dbPath)n("Data path",i.bold(a.dbPath));if(Object.keys(r).length>0)n("Options",i.dim(Object.keys(r).join(", ")));c(),p(`${d.warning} Reuse is safe ONLY for a database from the SAME workspace \u2014 the encryption key is per-workspace, so a foreign DB won't decrypt (the agent will go degraded).`),p(`${d.warning} Two agents writing the same database concurrently can corrupt it. Keep this a single-writer setup unless your adapter is explicitly configured for shared writes.`),c()}if(!a.yes&&!t.json){if(!await le(i.bold("Write this storage configuration to the agent config?"))){o("Cancelled.");return}}let h={};if(a.adapter)h.storageAdapter=String(a.adapter);if(Object.keys(r).length>0)h.storageOptions=r;if(a.dbPath)h.dbPath=String(a.dbPath);M(h);let O=w();if(u(t,{ok:!0,storageAdapter:O.storageAdapter??null,dbPath:O.dbPath??null,storageOptionKeys:Object.keys(O.storageOptions??{})}))return;l(`${d.success} Storage configuration written. Run ${i.bold("vibe restart")} so the agent connects to the existing database.`)}catch(r){let h=r instanceof Error?A(r):String(r);if(t.json){u(t,{ok:!1,error:h});return}s(`reuse-db failed: ${h}`)}})}function Kt(P){return new Set([...Ze(P)??sr()])}function qt(P){return Ce(process.platform,new Set(P)).map((a)=>a.packageName)}async function Wt(){let{PluginManager:P}=await import("./plugin-system-7qjqrq7s.js"),a=new P;return{install:(t)=>a.install(t),remove:(t)=>a.remove(t)}}function mo(P){let a=P.command("capability").alias("cap").description("Select agent capabilities (abilities) + providers");a.command("list",{isDefault:!0}).description("List capabilities and whether each is enabled").option("--json","Emit JSON").action((t)=>{let r={...P.opts(),...t},h=C(),O=Kt(h),E=Ot(h);if(u(r,{abilities:Y.map((N)=>({key:N.key,label:N.label,mandatory:N.mandatory,enabled:N.mandatory||O.has(N.key)})),providers:E}))return;if(g("Capabilities"),F(Y.map((N)=>({Key:N.key,Capability:N.label,Status:N.mandatory?"required":O.has(N.key)?"enabled":"disabled",Description:N.description}))),E.length>0){c(),g("Extra providers");for(let N of E)n("\u2022",N)}c(),o("Enable: vibe capability enable <key...> [--provider <pkg...>]"),o("Disable: vibe capability disable <key...>"),o("Re-run the interactive selector: vibe capability select")}),a.command("enable").description("Enable capabilities (installs their meta plugin) and/or extra providers").argument("[keys...]","Ability keys (e.g. gitops security)").option("--provider <pkg...>","Extra provider plugin(s) to install (short name or @vibecontrols/...)").option("--json","Emit JSON").action(async(t,r)=>{try{let h={...P.opts(),...r},O=C(),E=new Set(Y.map((oe)=>oe.key)),N=(t??[]).map((oe)=>oe.trim().toLowerCase()).filter((oe)=>E.has(oe));for(let oe of(t??[]).filter((K)=>!E.has(K.trim().toLowerCase())))p(`Unknown capability "${oe}" \u2014 see \`vibe capability list\`.`);let T=(Array.isArray(r.provider)?r.provider:r.provider?[r.provider]:[]).map((oe)=>Ue(oe)).filter((oe)=>Boolean(oe));if(N.length===0&&T.length===0){s("Provide at least one capability key or --provider <pkg>.");return}let x=Kt(O);for(let oe of N)x.add(oe);let L=[...new Set([...qt(N),...T])],Z=await Wt(),B=[];for(let oe of L)try{await Z.install(oe),B.push({package:oe,ok:!0})}catch(K){B.push({package:oe,ok:!1,error:A(K)})}let V=[...new Set([...Ot(O),...T])];if(ut(O,{abilities:x,providers:V}),u(h,{ok:!0,action:"enable",abilities:[...x],providers:V,installed:B}))return;for(let oe of B)if(oe.ok)l(`Installed ${oe.package}`);else p(`Failed to install ${oe.package}: ${oe.error}`);l("Capabilities updated. Restart the agent to load: vibe restart")}catch(h){s(A(h))}}),a.command("disable").description("Disable capabilities (removes their meta plugin)").argument("<keys...>","Ability keys").option("--json","Emit JSON").action(async(t,r)=>{try{let h={...P.opts(),...r},O=C(),E=new Set(Y.map((B)=>B.key)),N=new Set(Y.filter((B)=>B.mandatory).map((B)=>B.key)),j=(t??[]).map((B)=>B.trim().toLowerCase()).filter((B)=>E.has(B));for(let B of j.filter((V)=>N.has(V)))p(`"${B}" is required and cannot be disabled.`);let T=j.filter((B)=>!N.has(B));if(T.length===0){s("Nothing to disable.");return}let x=Kt(O);for(let B of T)x.delete(B);let L=await Wt(),Z=[];for(let B of qt(T))try{await L.remove(B),Z.push({package:B,ok:!0})}catch(V){Z.push({package:B,ok:!1,error:A(V)})}if(ut(O,{abilities:x}),u(h,{ok:!0,action:"disable",abilities:[...x],removed:Z}))return;for(let B of Z)if(B.ok)l(`Removed ${B.package}`);else p(`Failed to remove ${B.package}: ${B.error}`);l("Capabilities updated. Restart the agent to apply: vibe restart")}catch(h){s(A(h))}}),a.command("select").description("Re-run the interactive capability selector and apply it").option("--json","Emit JSON").action(async(t)=>{try{let r={...P.opts(),...t},h=C(),O=await nr(),E=await Wt();for(let N of qt(O))try{await E.install(N)}catch{}if(ut(h,{abilities:O}),u(r,{ok:!0,action:"select",abilities:[...O]}))return;l(`Selection saved (${[...O].join(", ")||"none"}). Restart to apply: vibe restart`)}catch(r){s(A(r))}})}function Mr(P){en(P),tn(P),nn(P),an(P),ln(P),dn(P),un(P),pn(P),Cn(P),Dr(P),On(P),Dn(P),Tn(P),Gn(P),Vn(P),Kn(P),zn(P),Yn(P),Xn(P),Qn(P),eo(P),to(P),ro(P),io(P),so(P),ao(P),lo(P),uo(P),po(P),mo(P)}
|
|
115
|
+
`)}));await Q({title:`${t} \u2014 ${O.length} session(s)`,rows:E})},json:(O)=>ti(O)})}function uo(P){let a=P.command("session").description("Manage terminal sessions");a.command("system").description("List system sessions (alias for `session list --system`)").option("--agent-url <url>","Agent URL",Oe).option("--json","Emit JSON").option("--plain","Force plain text output").action(async function(t){let r={...P.opts(),...t};try{let h=f(t),O=encodeURIComponent(m(r));await co(h,`/api/profiles/${O}/sessions/system`,"System Sessions","No system sessions found.",r)}catch(h){s(A(h))}}),a.command("list").description("List all sessions").option("--system","Show system sessions instead of user sessions").option("--agent-url <url>","Agent URL",Oe).option("--json","Emit JSON").option("--plain","Force plain text output").action(async function(t){let r={...P.opts(),...t};try{let h=f(t),O=encodeURIComponent(m(r)),E=t.system?`/api/profiles/${O}/sessions/system`:`/api/profiles/${O}/sessions`;await co(h,E,"Sessions","No sessions found.",r)}catch(h){s(A(h))}}),a.command("create").description("Create a new session").requiredOption("--name <name>","Session name").option("--project <id>","Project ID","default").option("--command <cmd>","Initial command to run").option("--cwd <dir>","Working directory").option("--agent-url <url>","Agent URL",Oe).option("--json","Emit JSON").action(async function(t){let r={...P.opts(),...t};try{let h=f(t),O=encodeURIComponent(m(r)),E={sessionName:t.name,projectId:t.project};if(t.command)E.command=t.command;if(t.cwd)E.startDirectory=t.cwd;let N=await q(h,`/api/profiles/${O}/sessions/create`,E),j=N?.session?.id||N?.id||N?.sessionId;if(u(r,{ok:!0,id:j,name:t.name,project:t.project}))return;l(`Session created: ${H(j)}`),n("Name",t.name),n("Project",t.project)}catch(h){if(r.json){u(r,{ok:!1,error:A(h)});return}s(A(h))}}),a.command("kill").description("Kill a session").requiredOption("-i, --id <id>","Session ID").option("--agent-url <url>","Agent URL",Oe).option("--json","Emit JSON").action(async function(t){let r={...P.opts(),...t};try{let h=f(t),O=encodeURIComponent(m(r));if(await ge(h,`/api/profiles/${O}/sessions/${t.id}`),u(r,{ok:!0,id:t.id}))return;l(`Session ${H(t.id)} killed.`)}catch(h){if(r.json){u(r,{ok:!1,error:A(h)});return}s(A(h))}}),a.command("exec").description("Execute a command in a session").requiredOption("-i, --id <id>","Session ID").requiredOption("-c, --command <cmd>","Command to execute").option("--agent-url <url>","Agent URL",Oe).option("--json","Emit JSON").action(async function(t){let r={...P.opts(),...t};try{let h=f(t),O=encodeURIComponent(m(r)),E=await q(h,`/api/profiles/${O}/sessions/${t.id}/command`,{command:t.command});if(u(r,{ok:!0,id:t.id,output:E?.output??null}))return;if(l("Command executed."),E?.output)c(),console.log(E.output)}catch(h){if(r.json){u(r,{ok:!1,error:A(h)});return}s(A(h))}}),a.command("capture").description("Capture session terminal output").requiredOption("-i, --id <id>","Session ID").option("--agent-url <url>","Agent URL",Oe).option("--json","Emit JSON").option("--plain","Force plain text output").action(async function(t){let r={...P.opts(),...t};try{let h=f(t),O=encodeURIComponent(m(r));await y({mode:_(r),fetchData:()=>S(h,`/api/profiles/${O}/sessions/${t.id}/capture`),plain:(E)=>{if(E?.content||E?.output)console.log(E.content||E.output);else o("No capture data available.")},json:(E)=>({id:t.id,content:E?.content??E?.output??null})})}catch(h){s(A(h))}}),a.command("keys").description("Send keys to a session").requiredOption("-i, --id <id>","Session ID").requiredOption("-k, --keys <keys>","Keys to send").option("--agent-url <url>","Agent URL",Oe).option("--json","Emit JSON").action(async function(t){let r={...P.opts(),...t};try{let h=f(t),O=encodeURIComponent(m(r));if(await q(h,`/api/profiles/${O}/sessions/${t.id}/keys`,{keys:t.keys}),u(r,{ok:!0,id:t.id}))return;l("Keys sent.")}catch(h){if(r.json){u(r,{ok:!1,error:A(h)});return}s(A(h))}}),a.command("interrupt").description("Send interrupt signal to a session").requiredOption("-i, --id <id>","Session ID").option("--agent-url <url>","Agent URL",Oe).option("--json","Emit JSON").action(async function(t){let r={...P.opts(),...t};try{let h=f(t),O=encodeURIComponent(m(r));if(await q(h,`/api/profiles/${O}/sessions/${t.id}/interrupt`,{}),u(r,{ok:!0,id:t.id}))return;l(`Session ${H(t.id)} interrupted.`)}catch(h){if(r.json){u(r,{ok:!1,error:A(h)});return}s(A(h))}}),a.command("rename").description("Rename a session").requiredOption("-i, --id <id>","Session ID").requiredOption("--name <name>","New session name").option("--agent-url <url>","Agent URL",Oe).option("--json","Emit JSON").action(async function(t){let r={...P.opts(),...t};try{let h=f(t),O=encodeURIComponent(m(r));if(await Te(h,`/api/profiles/${O}/sessions/${t.id}/rename`,{newName:t.name}),u(r,{ok:!0,id:t.id,name:t.name}))return;l(`Session ${H(t.id)} renamed to "${t.name}".`)}catch(h){if(r.json){u(r,{ok:!1,error:A(h)});return}s(A(h))}}),a.command("toggle-mouse").description("Toggle mouse support in a session").requiredOption("-i, --id <id>","Session ID").option("--agent-url <url>","Agent URL",Oe).option("--json","Emit JSON").action(async function(t){let r={...P.opts(),...t};try{let h=f(t),O=encodeURIComponent(m(r)),E=await q(h,`/api/profiles/${O}/sessions/${t.id}/toggle-mouse`,{});if(u(r,{ok:!0,id:t.id,mouseEnabled:!!E?.mouseEnabled}))return;l(`Mouse support ${E?.mouseEnabled?"enabled":"toggled"} for session ${H(t.id)}.`)}catch(h){if(r.json){u(r,{ok:!1,error:A(h)});return}s(A(h))}}),a.command("terminal-start").description("Start terminal for a session").requiredOption("-i, --id <id>","Session ID").option("--agent-url <url>","Agent URL",Oe).option("--json","Emit JSON").action(async function(t){let r={...P.opts(),...t};try{let h=f(t),O=encodeURIComponent(m(r)),E=await q(h,`/api/profiles/${O}/sessions/${t.id}/terminal`,{});if(u(r,{ok:!0,id:t.id,port:E?.port??null}))return;if(l(`Terminal started for session ${H(t.id)}.`),E?.port)n("Port",E.port)}catch(h){if(r.json){u(r,{ok:!1,error:A(h)});return}s(A(h))}}),a.command("terminal-stop").description("Stop terminal for a session").requiredOption("-i, --id <id>","Session ID").option("--agent-url <url>","Agent URL",Oe).option("--json","Emit JSON").action(async function(t){let r={...P.opts(),...t};try{let h=f(t),O=encodeURIComponent(m(r));if(await q(h,`/api/profiles/${O}/sessions/${t.id}/terminal/stop`,{}),u(r,{ok:!0,id:t.id}))return;l(`Terminal stopped for session ${H(t.id)}.`)}catch(h){if(r.json){u(r,{ok:!1,error:A(h)});return}s(A(h))}}),a.command("health-check").description("Run health check on all sessions").option("--agent-url <url>","Agent URL",Oe).option("--json","Emit JSON").action(async function(t){let r={...P.opts(),...t};try{let h=f(t),O=encodeURIComponent(m(r)),E=await S(h,`/api/profiles/${O}/sessions`),N=await q(h,`/api/profiles/${O}/sessions/health-check`,{sessionIds:(E.sessions||[]).map((j)=>j.id)});if(u(r,{ok:!0,healthy:N?.healthy??null,checked:N?.checked??null,fixed:N?.fixed??null}))return;if(l("Health check completed."),N?.healthy!==void 0)n("Healthy",N.healthy);if(N?.checked!==void 0)n("Checked",N.checked);if(N?.fixed!==void 0)n("Fixed",N.fixed)}catch(h){if(r.json){u(r,{ok:!1,error:A(h)});return}s(A(h))}})}function po(P){P.command("reuse-db").description("Point this agent at an EXISTING database (reuse data from another same-workspace agent)").option("--adapter <name>","Storage adapter to use (e.g. postgres, skalex). Defaults to the configured/default adapter.").option("--connection-string <conn>","Connection string for the adapter (e.g. postgres://user:pass@host/db)").option("--storage-options <json>","Raw adapter options as a JSON object (alternative/in addition to --connection-string)").option("--db-path <path>","Data directory the adapter should use (e.g. an existing Skalex agent-db dir)").option("-y, --yes","Skip the confirmation prompt").option("--json","Emit JSON").action(async function(a){let t={...P.opts(),...a};try{let r={};if(a.storageOptions){let E;try{E=JSON.parse(a.storageOptions)}catch{s("--storage-options must be valid JSON.");return}if(!E||typeof E!=="object"||Array.isArray(E)){s("--storage-options must be a JSON object.");return}for(let[N,j]of Object.entries(E))r[N]=typeof j==="string"?j:JSON.stringify(j)}if(a.connectionString)r.connectionString=String(a.connectionString);if(!a.adapter&&!a.dbPath&&Object.keys(r).length===0){s("Nothing to set. Provide --adapter with --connection-string (or --storage-options), and/or --db-path.");return}if(!t.json){if(g("Reuse an existing database"),a.adapter)n("Adapter",i.bold(a.adapter));if(a.dbPath)n("Data path",i.bold(a.dbPath));if(Object.keys(r).length>0)n("Options",i.dim(Object.keys(r).join(", ")));c(),p(`${d.warning} Reuse is safe ONLY for a database from the SAME workspace \u2014 the encryption key is per-workspace, so a foreign DB won't decrypt (the agent will go degraded).`),p(`${d.warning} Two agents writing the same database concurrently can corrupt it. Keep this a single-writer setup unless your adapter is explicitly configured for shared writes.`),c()}if(!a.yes&&!t.json){if(!await le(i.bold("Write this storage configuration to the agent config?"))){o("Cancelled.");return}}let h={};if(a.adapter)h.storageAdapter=String(a.adapter);if(Object.keys(r).length>0)h.storageOptions=r;if(a.dbPath)h.dbPath=String(a.dbPath);M(h);let O=w();if(u(t,{ok:!0,storageAdapter:O.storageAdapter??null,dbPath:O.dbPath??null,storageOptionKeys:Object.keys(O.storageOptions??{})}))return;l(`${d.success} Storage configuration written. Run ${i.bold("vibe restart")} so the agent connects to the existing database.`)}catch(r){let h=r instanceof Error?A(r):String(r);if(t.json){u(t,{ok:!1,error:h});return}s(`reuse-db failed: ${h}`)}})}function Kt(P){return new Set([...Ze(P)??sr()])}function qt(P){return Ce(process.platform,new Set(P)).map((a)=>a.packageName)}async function Wt(){let{PluginManager:P}=await import("./plugin-system-e690jr6e.js"),a=new P;return{install:(t)=>a.install(t),remove:(t)=>a.remove(t)}}function mo(P){let a=P.command("capability").alias("cap").description("Select agent capabilities (abilities) + providers");a.command("list",{isDefault:!0}).description("List capabilities and whether each is enabled").option("--json","Emit JSON").action((t)=>{let r={...P.opts(),...t},h=C(),O=Kt(h),E=Ot(h);if(u(r,{abilities:Y.map((N)=>({key:N.key,label:N.label,mandatory:N.mandatory,enabled:N.mandatory||O.has(N.key)})),providers:E}))return;if(g("Capabilities"),F(Y.map((N)=>({Key:N.key,Capability:N.label,Status:N.mandatory?"required":O.has(N.key)?"enabled":"disabled",Description:N.description}))),E.length>0){c(),g("Extra providers");for(let N of E)n("\u2022",N)}c(),o("Enable: vibe capability enable <key...> [--provider <pkg...>]"),o("Disable: vibe capability disable <key...>"),o("Re-run the interactive selector: vibe capability select")}),a.command("enable").description("Enable capabilities (installs their meta plugin) and/or extra providers").argument("[keys...]","Ability keys (e.g. gitops security)").option("--provider <pkg...>","Extra provider plugin(s) to install (short name or @vibecontrols/...)").option("--json","Emit JSON").action(async(t,r)=>{try{let h={...P.opts(),...r},O=C(),E=new Set(Y.map((oe)=>oe.key)),N=(t??[]).map((oe)=>oe.trim().toLowerCase()).filter((oe)=>E.has(oe));for(let oe of(t??[]).filter((K)=>!E.has(K.trim().toLowerCase())))p(`Unknown capability "${oe}" \u2014 see \`vibe capability list\`.`);let T=(Array.isArray(r.provider)?r.provider:r.provider?[r.provider]:[]).map((oe)=>Ue(oe)).filter((oe)=>Boolean(oe));if(N.length===0&&T.length===0){s("Provide at least one capability key or --provider <pkg>.");return}let x=Kt(O);for(let oe of N)x.add(oe);let L=[...new Set([...qt(N),...T])],Z=await Wt(),B=[];for(let oe of L)try{await Z.install(oe),B.push({package:oe,ok:!0})}catch(K){B.push({package:oe,ok:!1,error:A(K)})}let V=[...new Set([...Ot(O),...T])];if(ut(O,{abilities:x,providers:V}),u(h,{ok:!0,action:"enable",abilities:[...x],providers:V,installed:B}))return;for(let oe of B)if(oe.ok)l(`Installed ${oe.package}`);else p(`Failed to install ${oe.package}: ${oe.error}`);l("Capabilities updated. Restart the agent to load: vibe restart")}catch(h){s(A(h))}}),a.command("disable").description("Disable capabilities (removes their meta plugin)").argument("<keys...>","Ability keys").option("--json","Emit JSON").action(async(t,r)=>{try{let h={...P.opts(),...r},O=C(),E=new Set(Y.map((B)=>B.key)),N=new Set(Y.filter((B)=>B.mandatory).map((B)=>B.key)),j=(t??[]).map((B)=>B.trim().toLowerCase()).filter((B)=>E.has(B));for(let B of j.filter((V)=>N.has(V)))p(`"${B}" is required and cannot be disabled.`);let T=j.filter((B)=>!N.has(B));if(T.length===0){s("Nothing to disable.");return}let x=Kt(O);for(let B of T)x.delete(B);let L=await Wt(),Z=[];for(let B of qt(T))try{await L.remove(B),Z.push({package:B,ok:!0})}catch(V){Z.push({package:B,ok:!1,error:A(V)})}if(ut(O,{abilities:x}),u(h,{ok:!0,action:"disable",abilities:[...x],removed:Z}))return;for(let B of Z)if(B.ok)l(`Removed ${B.package}`);else p(`Failed to remove ${B.package}: ${B.error}`);l("Capabilities updated. Restart the agent to apply: vibe restart")}catch(h){s(A(h))}}),a.command("select").description("Re-run the interactive capability selector and apply it").option("--json","Emit JSON").action(async(t)=>{try{let r={...P.opts(),...t},h=C(),O=await nr(),E=await Wt();for(let N of qt(O))try{await E.install(N)}catch{}if(ut(h,{abilities:O}),u(r,{ok:!0,action:"select",abilities:[...O]}))return;l(`Selection saved (${[...O].join(", ")||"none"}). Restart to apply: vibe restart`)}catch(r){s(A(r))}})}function Mr(P){en(P),tn(P),nn(P),an(P),ln(P),dn(P),un(P),pn(P),Cn(P),Dr(P),On(P),Dn(P),Tn(P),Gn(P),Vn(P),Kn(P),zn(P),Yn(P),Xn(P),Qn(P),eo(P),to(P),ro(P),io(P),so(P),ao(P),lo(P),uo(P),po(P),mo(P)}
|
|
116
116
|
export{Pr,Mr};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{r,E}from"./index-1t74r13z.js";import{e}from"./index-7wm4bqx5.js";import{Et,Bi,cr,ur,kt,tt,Ue,ce,Lt,fe}from"./index-p1b10hs1.js";import{St,Qt}from"./index-x4z055t8.js";import"./index-j99tkngg.js";import{rr}from"./index-6b9vh0gq.js";import"./index-qzwbctkv.js";import"./index-p7fbnfwd.js";import{qt,Cr}from"./index-vhz1c474.js";import{i,s,A,l,p,o,g,n,F}from"./index-12gb48hg.js";import{Q,U}from"./index-sq5j8bjn.js";import"./index-0rmmrrfh.js";import"./index-6wfd7cv3.js";import{ue,le,_,y,u}from"./index-v77bb0rm.js";import{f,m,S,q}from"./index-damc6cvc.js";import{timingSafeEqual as ye}from"crypto";function he(){return(process.env.NPM_CONFIG_REGISTRY||process.env.npm_config_registry||"https://registry.npmjs.org").replace(/\/+$/,"")}async function Y(c,R){try{let b=await fetch(`${he()}/${c}/${R}`,{headers:{accept:"application/json"},signal:AbortSignal.timeout(1e4)});if(b.ok){let a=(await b.json()).dist?.integrity;if(typeof a==="string"&&a.startsWith("sha"))return a}}catch{}try{let b=Bun.spawn({cmd:["npm","view",`${c}@${R}`,"dist.integrity","--json"],stdout:"pipe",stderr:"pipe"});if(await b.exited!==0)return null;let d=(await new Response(b.stdout).text()).trim();if(!d)return null;if(d.startsWith('"'))try{let P=JSON.parse(d);return typeof P==="string"?P:null}catch{return null}return d}catch{return null}}function Z(c,R){let b=Buffer.from(c),t=Buffer.from(R);if(b.length!==t.length)return!1;try{return ye(b,t)}catch{return!1}}var be=Bi.map((c)=>({packageName:c.packageName,name:c.pluginName,description:c.description,cliCommand:c.cliCommand,apiPrefix:c.apiPrefix,installed:!1,category:c.category})),H=new Map;function O(c,R){let t=(H.get(c)??Promise.resolve()).then(R,R),a=t.then(()=>{return},()=>{return});return H.set(c,a),a.finally(()=>{if(H.get(c)===a)H.delete(c)}),t}function X(c){return H.has(c)}function ee(c){let R=c.getPluginDetails(),b=new Set(R.map((t)=>t.packageName));return{plugins:be.map((t)=>({...t,installed:b.has(t.packageName)}))}}function te(c){let{pluginManager:R}=c;return new E().get("/",()=>{let b=R.getPluginDetails();return{plugins:b,count:b.length}}).get("/available",()=>ee(R)).get("/catalog",()=>ee(R)).get("/contributions",({query:b})=>{let t=typeof b?.mountPoint==="string"&&b.mountPoint?b.mountPoint:null,a=[],d=new Map;for(let P of R.getPluginDetails())d.set(P.pluginName,P.packageName);for(let P of R.getAllPlugins()){let N=P.ui;if(!N||!N.contributions||N.contributions.length===0)continue;let v=N.capabilities??{restPaths:[],wsTopics:[],rpcMethods:[]};for(let k of N.contributions){if(t&&k.mountPoint!==t)continue;let h=k.meta,w=h&&typeof h.url==="string"?h.url:null,C=w&&w.startsWith("/")&&!w.startsWith("//")&&!w.includes("\x00")&&!w.includes("..")?w:null;a.push({pluginKey:P.name,pluginPackageName:d.get(P.name),contribution:k,capabilities:k.capabilities??v,url:C??`/ui/${encodeURIComponent(P.name)}`})}}return{contributions:a,count:a.length}}).post("/install",async({body:b,set:t})=>{if(!b.packageName||typeof b.packageName!=="string")return t.status=400,{error:"Missing required field: packageName"};if(b.packageName.startsWith("@burdenoff/"))b.packageName=b.packageName.replace(/^@burdenoff\//,"@vibecontrols/");if(!kt(b.packageName))return t.status=403,{error:"Plugin package is not in the trusted VibeControls catalog"};if(tt(b.packageName)&&b.confirmUntrusted!==!0)return t.status=428,{error:"confirmation_required",code:"CONFIRMATION_REQUIRED",packageName:b.packageName,message:`${b.packageName} is not a trusted plugin. Installing it needs confirmation.`};try{let a=fe(b.packageName);if(X(a)){let d=a.split("/").pop()?.replace("vibe-plugin-","");if(R.getAllPlugins().some((N)=>N.name===d))return{success:!0,message:`Plugin ${a} is already installed`,packageName:a,alreadyInstalled:!0};return t.status=409,{error:"Install for this package is already in progress. Wait for it to finish.",packageName:a}}return await O(a,async()=>{let d=a.split("/").pop()?.replace("vibe-plugin-",""),P=d?.startsWith("ai-")?d.slice(3):void 0,N=R.getAllPlugins().find((I)=>I.name===d||I.name===P),v=!!N,k=await R.install(a,{confirmUntrusted:b.confirmUntrusted===!0}),h=cr(a);if(h?.integrity){let I=await Y(a,k.version);if(I&&!Z(h.integrity,I)){try{await R.remove(a,c.hostServices)}catch(x){console.warn(`[plugin-mgr] integrity rollback uninstall failed for ${a}:`,x)}return e().audit.emit("agent","plugin.install.rejected",{packageName:a,version:k.version,reason:"integrity_mismatch",expected:h.integrity,actual:I}),t.status=400,{error:"integrity mismatch",expected:h.integrity,actual:I}}if(!I)console.warn(`[plugin-mgr] could not fetch registry integrity for ${a}@${k.version}; accepting the package-manager-verified tarball (pin present but unverifiable)`),e().audit.emit("agent","plugin.install.integrity_unverified",{packageName:a,version:k.version,expected:h.integrity})}else console.warn(`[plugin-mgr] plugin ${a} has no pinned integrity \u2014 accepting npm registry's hash`);let w=R.getAllPlugins().find((I)=>I.name===k.pluginName);if(w){let I=[];if(c.mountPlugin)c.mountPlugin(w);if(c.hostServices){if(v&&N?.onServerStop)try{await N.onServerStop()}catch(L){I.push(`onServerStop failed: ${L instanceof Error?L.message:String(L)}`)}R.registerProviders(w,c.hostServices);let x=R.hostServicesFor(w,c.hostServices);if(w.onServerStart&&c.app)try{await w.onServerStart(c.app,x),R.registerProviders(w,c.hostServices)}catch(L){I.push(`onServerStart failed: ${L instanceof Error?L.message:String(L)}`)}if(w.onServerReady&&c.app)try{await w.onServerReady(c.app,x)}catch(L){I.push(`onServerReady failed: ${L instanceof Error?L.message:String(L)}`)}}if(c.rebuildPluginSurfaces?.(),I.length>0)return t.status=500,{success:!1,message:`Plugin ${a} installed but failed to start`,lifecycleErrors:I,restartRequired:!0}}let C;if(w&&c.app)try{C=await qt(w,a,c.app,c.db,{skipInstall:!!b.skipPrereqs})}catch(I){C=void 0,console.warn(`[plugin-mgr] prereq run failed for ${a}:`,I)}return rr(c.db),e().audit.emit("agent","plugin.installed",{packageName:a,version:k.version,pluginName:k.pluginName,wasRunning:v}),{success:!0,message:`Plugin ${a} installed and loaded successfully`,prereqs:C?{satisfied:C.satisfied,missing:C.status?.missing??[],pendingSudo:C.pendingSudo,skipped:!!b.skipPrereqs}:void 0}})}catch(a){if(a instanceof ce)return t.status=400,{error:"signature_check_failed",reason:a.reason,details:a.message};if(a instanceof Lt)return t.status=428,{error:"confirmation_required",code:a.code,packageName:a.packageName,message:a.message};return t.status=500,{error:"Failed to install plugin",details:String(a)}}},{body:r.Object({packageName:r.String(),skipPrereqs:r.Optional(r.Boolean()),confirmUntrusted:r.Optional(r.Boolean())})}).post("/prereqs/status",async({body:b,set:t})=>{if(!b.packageName)return t.status=400,{error:"Missing packageName"};let a=b.packageName,d=R.getAllPlugins().find((P)=>P.name===a||R.getLoaded(a)?.name===P.name);if(!d||!c.app)return await Cr(c.db,a)??{satisfied:!0,missing:[]};try{let P=await qt(d,a,c.app,c.db,{skipInstall:!0});return{satisfied:P.satisfied,missing:P.status?.missing??[],noProtocol:P.noProtocol}}catch(P){return t.status=500,{error:String(P)}}},{body:r.Object({packageName:r.String()})}).post("/prereqs/install",async({body:b,set:t})=>{if(!b.packageName)return t.status=400,{error:"Missing packageName"};let a=b.packageName,d=R.getAllPlugins().find((P)=>P.name===a||R.getLoaded(a)?.name===P.name);if(!d||!c.app)return t.status=404,{error:"Plugin not loaded"};try{let P=await qt(d,a,c.app,c.db,{skipInstall:!1});return{satisfied:P.satisfied,installed:P.install?.installed??[],pendingSudo:P.pendingSudo,errors:P.install?.errors??[],noProtocol:P.noProtocol}}catch(P){return t.status=500,{error:String(P)}}},{body:r.Object({packageName:r.String(),approveSudo:r.Optional(r.Boolean())})}).post("/prereqs/uninstall",async({body:b,set:t})=>{if(!b.packageName)return t.status=400,{error:"Missing packageName"};let a=b.packageName,d=R.getAllPlugins().find((k)=>k.name===a);if(!d||!d.apiPrefix||!c.app)return t.status=404,{error:"Plugin not loaded"};let P=c.app.handle;if(typeof P!=="function")return t.status=500,{error:"App handle unavailable"};let N=`${d.apiPrefix.replace(/\/+$/,"")}/prereqs/uninstall`,v=await P.call(c.app,new Request(`http://agent.local${N}`,{method:"POST",headers:{"x-vc-profile-rewrite":"1",[St]:Qt()}}));if(v.status===404)return t.status=404,{error:"Plugin has no prereqs/uninstall endpoint"};return v.json()},{body:r.Object({packageName:r.String()})}).post("/nuke",async({body:b,set:t})=>{if(!c.hostServices)return t.status=503,{error:"hostServices unavailable"};let a=c.hostServices.getDataDir?.();return{ok:!0,...await R.runPluginNuke(b.packageName,c.hostServices,{agentDir:a,dryRun:!!b.dryRun})}},{body:r.Object({packageName:r.Optional(r.String()),dryRun:r.Optional(r.Boolean())})}).post("/remove",async({body:b,set:t})=>{if(!b.packageName||typeof b.packageName!=="string")return t.status=400,{error:"Missing required field: packageName"};if(b.packageName.startsWith("@burdenoff/"))b.packageName=b.packageName.replace(/^@burdenoff\//,"@vibecontrols/");if(Et(b.packageName))return{success:!0,message:`Plugin ${b.packageName} is critical and cannot be removed; treating remove as a no-op.`,skipped:!0};try{let a=fe(b.packageName);return await O(a,async()=>(await R.remove(a,c.hostServices),c.rebuildPluginSurfaces?.(),rr(c.db),e().audit.emit("agent","plugin.removed",{packageName:a}),{success:!0,message:`Plugin ${a} removed successfully`}))}catch(a){return t.status=500,{error:"Failed to remove plugin",details:String(a)}}},{body:r.Object({packageName:r.String()})}).post("/update",async({body:b,set:t})=>{if(!b.packageName||typeof b.packageName!=="string")return t.status=400,{error:"Missing required field: packageName"};let a=typeof b.version==="string"&&b.version.trim()?b.version.trim():void 0;if(a&&!/^[0-9][0-9A-Za-z.+-]{0,63}$/.test(a))return t.status=400,{error:`Invalid version "${a}"`};try{let d=fe(b.packageName);return await O(d,async()=>{let P=R.getLoaded(d);if(P?.onServerStop)await P.onServerStop({reason:"reload"});if(P&&c.hostServices)c.hostServices.serviceRegistry.unregisterPlugin(P.name);let N=await R.update(d,a),v=R.getLoaded(d);if(v&&c.hostServices){R.registerProviders(v,c.hostServices);let k=R.hostServicesFor(v,c.hostServices);if(v.onServerStart&&c.app)await v.onServerStart(c.app,k),R.registerProviders(v,c.hostServices);if(v.onServerReady&&c.app)await v.onServerReady(c.app,k)}return c.rebuildPluginSurfaces?.(),rr(c.db),{success:!0,message:`Plugin ${d} updated to v${N.version}`,version:N.version}})}catch(d){return t.status=500,{error:"Failed to update plugin",details:String(d)}}},{body:r.Object({packageName:r.String(),version:r.Optional(r.String())})}).post("/update-all",async({set:b})=>{try{let t=await O("*",()=>R.updateAll());return{success:!0,results:t,message:`Updated ${t.filter((a)=>a.success).length}/${t.length} plugin(s)`}}catch(t){return b.status=500,{error:"Failed to update all plugins",details:String(t)}}}).post("/remove-all",async({set:b})=>{try{let t=await O("*",async()=>{let a=await R.removeAll(c.hostServices);return c.rebuildPluginSurfaces?.(),a});return{success:!0,results:t,message:`Removed ${t.filter((a)=>a.success).length}/${t.length} plugin(s)`}}catch(t){return b.status=500,{error:"Failed to remove all plugins",details:String(t)}}}).post("/reload",async({set:b})=>{try{if(!c.app||!c.hostServices)return b.status=503,{error:"Plugin lifecycle services are not ready"};let t=await O("*",async()=>(await R.reloadAll(c.app,c.hostServices),c.rebuildPluginSurfaces?.(),R.getPluginDetails()));return{success:!0,plugins:t,message:`Reloaded ${t.length} plugin(s)`}}catch(t){return b.status=500,{error:"Failed to reload plugins",details:String(t)}}}).post("/:name/reload",async({params:b,set:t})=>{if(!c.app||!c.hostServices)return t.status=503,{error:"Plugin lifecycle services are not ready"};let a=b.name,d=R.getAllPlugins().find((v)=>v.name===a);if(!d)return t.status=404,{error:`Plugin "${a}" not found`};let N=R.getPluginDetails().find((v)=>v.pluginName===a)?.packageName??`core:${a}`;if(X(N))return t.status=409,{error:"Plugin lifecycle in progress; try again shortly",packageName:N};try{R.verifyLoadedSignature(N)}catch(v){if(!(v instanceof ce))throw v;try{await d.onServerStop?.({reason:"shutdown"})}catch(k){console.warn(`[plugin-mgr] onServerStop after a failed signature check of ${a}:`,k)}return c.hostServices.serviceRegistry.unregisterPlugin(d.name),await R.evictLoaded(N),t.status=400,{error:"signature_check_failed",reason:v.reason,details:v.message}}try{return await O(N,async()=>{if(d.onServerStop)try{await d.onServerStop({reason:"reload"})}catch(k){console.warn(`[plugin-mgr] onServerStop during reload of ${a}:`,k)}if(c.hostServices)c.hostServices.serviceRegistry.unregisterPlugin(d.name);R.registerProviders(d,c.hostServices);let v=R.hostServicesFor(d,c.hostServices);if(d.onServerStart)await d.onServerStart(c.app,v),R.registerProviders(d,c.hostServices);if(d.onServerReady)await d.onServerReady(c.app,v);return c.rebuildPluginSurfaces?.(),{success:!0,message:`Plugin ${a} reloaded`,version:d.version}})}catch(v){return t.status=500,{error:"Failed to reload plugin",details:String(v)}}},{params:r.Object({name:r.String()})})}import{mkdirSync as W,writeFileSync as M,existsSync as ne}from"fs";import{isAbsolute as Se,join as j,relative as Pe,resolve as G}from"path";var J="http://localhost:3005";async function we(c,R,b={interactive:ue,prompt:le,warn:p}){if(!tt(c))return!0;if(b.warn(ur(c)?`${c} is a desk plugin: it lets a BotManor Steward see and use this machine. Remote control stays off until you turn it on.`:`${c} is not a trusted plugin.`),R.yes===!0)return!0;if(!b.interactive())return b.warn("Re-run with --yes to confirm the install."),!1;return b.prompt(`Install ${c}?`)}var ke=/^[a-z0-9][a-z0-9-]{0,63}$/,$e=new Set(["backend","frontend","cli","provider","adapter","integration"]);function ie(c,R){let b=Pe(c,R);if(b.startsWith("..")||Se(b))throw Error("Plugin scaffold path escapes the selected directory.")}function T(c){return JSON.stringify(c)}function re(c){let R=c.command("plugin").description("Manage plugins");R.command("list").description("List installed plugins").option("--agent-url <url>","Agent URL",J).option("--profile <name>","Target a specific profile by name").option("--json","Emit JSON").option("--plain","Force plain text output").action(async(t)=>{try{let a={...c.opts(),...t},d=f(t),P=encodeURIComponent(m(a)),N=async()=>{try{return(await S(d,`/api/profiles/${P}/plugins`)).plugins||[]}catch{p("Agent not reachable. Attempting local plugin registry...");let{PluginManager:h}=await import("./plugin-system-7qjqrq7s.js");return new h().getPluginDetails()||[]}},v=(h)=>h.status??(h.loaded===!0||h.enabled===!0?"enabled":"disabled"),k=(h)=>h.pluginName||h.name||h.packageName||h.package||"-";await y({mode:_(a),fetchData:N,plain:(h)=>{if(!h.length){o("No plugins installed.");return}g("Installed Plugins"),F(h.map((w)=>({Name:k(w),Version:w.version||"-",Status:v(w),Description:w.description||"-"})))},interactive:async(h)=>{if(!h.length){g("Installed Plugins"),o("No plugins installed.");return}let w=h.map((C)=>{let I=k(C),x=v(C),L=[`${i.bold(I)} ${x==="enabled"?i.green(x):i.dim(x)}`,"",` Version: ${C.version||"-"}`,` Description: ${C.description||"-"}`];if(C.tags&&Array.isArray(C.tags))L.push(` Tags: ${C.tags.join(", ")}`);if(C.cliCommand)L.push(` CLI command: vibe ${C.cliCommand}`);return{id:I,label:I,hint:x,detail:L.join(`
|
|
3
|
-
`)}});await Q({title:`vibe plugin \u2014 ${h.length} installed`,rows:w,footer:"\u2191/\u2193 navigate \xB7 q to quit"})},json:(h)=>h.map((w)=>({name:k(w),version:w.version??null,status:v(w),description:w.description??null,tags:w.tags??null,cliCommand:w.cliCommand??null}))})}catch(a){s(A(a))}}),R.command("install").description("Install a plugin").argument("<package>","NPM package name to install").option("--agent-url <url>","Agent URL",J).option("--profile <name>","Target a specific profile by name").option("--skip-prereqs","Skip running the plugin's prereqs/install",!1).option("--json","Emit JSON result").option("-y, --yes","Confirm installing an untrusted plugin",!1).action(async(t,a)=>{try{let d={...c.opts(),...a},P=f(a),N=encodeURIComponent(m(d)),v=Ue(t)??t,k=tt(v);if(!await we(v,d)){s(`Install of ${v} cancelled.`);return}try{let h=await q(P,`/api/profiles/${N}/plugins/install`,{packageName:t,skipPrereqs:!!a.skipPrereqs,...k?{confirmUntrusted:!0}:{}});if(u(d,{ok:!0,action:"install",package:t,version:h?.version??null,prereqs:h?.prereqs??null}))return;if(l(`Plugin "${t}" installed.`),h?.version)n("Version",h.version);if(h?.prereqs){let w=h.prereqs;if(w.skipped)p(`Prerequisite install skipped. Run \`vibe plugin prereqs ${t} install\` later.`);else if(!w.satisfied)p(`Prerequisites not yet satisfied: ${(w.missing||[]).map((C)=>C.name).join(", ")||"(unknown)"}`);if((w.pendingSudo||[]).length>0){p(`${w.pendingSudo.length} command(s) need sudo. Run them and re-check with \`vibe plugin prereqs ${t} status\`:`);for(let C of w.pendingSudo)n(` ${C.name}`,C.command)}}}catch{p("Agent not reachable. Attempting local install...");try{let{PluginManager:h}=await import("./plugin-system-
|
|
2
|
+
import{r,E}from"./index-1t74r13z.js";import{e}from"./index-7wm4bqx5.js";import{Et,Bi,cr,ur,kt,tt,Ue,ce,Lt,fe}from"./index-8jk4a62x.js";import{St,Qt}from"./index-x4z055t8.js";import"./index-j99tkngg.js";import{rr}from"./index-5tghd67e.js";import"./index-qzwbctkv.js";import"./index-p7fbnfwd.js";import{qt,Cr}from"./index-vhz1c474.js";import{i,s,A,l,p,o,g,n,F}from"./index-12gb48hg.js";import{Q,U}from"./index-sq5j8bjn.js";import"./index-0rmmrrfh.js";import"./index-br9bakfm.js";import{ue,le,_,y,u}from"./index-v77bb0rm.js";import{f,m,S,q}from"./index-damc6cvc.js";import{timingSafeEqual as ye}from"crypto";function he(){return(process.env.NPM_CONFIG_REGISTRY||process.env.npm_config_registry||"https://registry.npmjs.org").replace(/\/+$/,"")}async function Y(c,R){try{let b=await fetch(`${he()}/${c}/${R}`,{headers:{accept:"application/json"},signal:AbortSignal.timeout(1e4)});if(b.ok){let a=(await b.json()).dist?.integrity;if(typeof a==="string"&&a.startsWith("sha"))return a}}catch{}try{let b=Bun.spawn({cmd:["npm","view",`${c}@${R}`,"dist.integrity","--json"],stdout:"pipe",stderr:"pipe"});if(await b.exited!==0)return null;let d=(await new Response(b.stdout).text()).trim();if(!d)return null;if(d.startsWith('"'))try{let P=JSON.parse(d);return typeof P==="string"?P:null}catch{return null}return d}catch{return null}}function Z(c,R){let b=Buffer.from(c),t=Buffer.from(R);if(b.length!==t.length)return!1;try{return ye(b,t)}catch{return!1}}var be=Bi.map((c)=>({packageName:c.packageName,name:c.pluginName,description:c.description,cliCommand:c.cliCommand,apiPrefix:c.apiPrefix,installed:!1,category:c.category})),H=new Map;function O(c,R){let t=(H.get(c)??Promise.resolve()).then(R,R),a=t.then(()=>{return},()=>{return});return H.set(c,a),a.finally(()=>{if(H.get(c)===a)H.delete(c)}),t}function X(c){return H.has(c)}function ee(c){let R=c.getPluginDetails(),b=new Set(R.map((t)=>t.packageName));return{plugins:be.map((t)=>({...t,installed:b.has(t.packageName)}))}}function te(c){let{pluginManager:R}=c;return new E().get("/",()=>{let b=R.getPluginDetails();return{plugins:b,count:b.length}}).get("/available",()=>ee(R)).get("/catalog",()=>ee(R)).get("/contributions",({query:b})=>{let t=typeof b?.mountPoint==="string"&&b.mountPoint?b.mountPoint:null,a=[],d=new Map;for(let P of R.getPluginDetails())d.set(P.pluginName,P.packageName);for(let P of R.getAllPlugins()){let N=P.ui;if(!N||!N.contributions||N.contributions.length===0)continue;let v=N.capabilities??{restPaths:[],wsTopics:[],rpcMethods:[]};for(let k of N.contributions){if(t&&k.mountPoint!==t)continue;let h=k.meta,w=h&&typeof h.url==="string"?h.url:null,C=w&&w.startsWith("/")&&!w.startsWith("//")&&!w.includes("\x00")&&!w.includes("..")?w:null;a.push({pluginKey:P.name,pluginPackageName:d.get(P.name),contribution:k,capabilities:k.capabilities??v,url:C??`/ui/${encodeURIComponent(P.name)}`})}}return{contributions:a,count:a.length}}).post("/install",async({body:b,set:t})=>{if(!b.packageName||typeof b.packageName!=="string")return t.status=400,{error:"Missing required field: packageName"};if(b.packageName.startsWith("@burdenoff/"))b.packageName=b.packageName.replace(/^@burdenoff\//,"@vibecontrols/");if(!kt(b.packageName))return t.status=403,{error:"Plugin package is not in the trusted VibeControls catalog"};if(tt(b.packageName)&&b.confirmUntrusted!==!0)return t.status=428,{error:"confirmation_required",code:"CONFIRMATION_REQUIRED",packageName:b.packageName,message:`${b.packageName} is not a trusted plugin. Installing it needs confirmation.`};try{let a=fe(b.packageName);if(X(a)){let d=a.split("/").pop()?.replace("vibe-plugin-","");if(R.getAllPlugins().some((N)=>N.name===d))return{success:!0,message:`Plugin ${a} is already installed`,packageName:a,alreadyInstalled:!0};return t.status=409,{error:"Install for this package is already in progress. Wait for it to finish.",packageName:a}}return await O(a,async()=>{let d=a.split("/").pop()?.replace("vibe-plugin-",""),P=d?.startsWith("ai-")?d.slice(3):void 0,N=R.getAllPlugins().find((I)=>I.name===d||I.name===P),v=!!N,k=await R.install(a,{confirmUntrusted:b.confirmUntrusted===!0}),h=cr(a);if(h?.integrity){let I=await Y(a,k.version);if(I&&!Z(h.integrity,I)){try{await R.remove(a,c.hostServices)}catch(x){console.warn(`[plugin-mgr] integrity rollback uninstall failed for ${a}:`,x)}return e().audit.emit("agent","plugin.install.rejected",{packageName:a,version:k.version,reason:"integrity_mismatch",expected:h.integrity,actual:I}),t.status=400,{error:"integrity mismatch",expected:h.integrity,actual:I}}if(!I)console.warn(`[plugin-mgr] could not fetch registry integrity for ${a}@${k.version}; accepting the package-manager-verified tarball (pin present but unverifiable)`),e().audit.emit("agent","plugin.install.integrity_unverified",{packageName:a,version:k.version,expected:h.integrity})}else console.warn(`[plugin-mgr] plugin ${a} has no pinned integrity \u2014 accepting npm registry's hash`);let w=R.getAllPlugins().find((I)=>I.name===k.pluginName);if(w){let I=[];if(c.mountPlugin)c.mountPlugin(w);if(c.hostServices){if(v&&N?.onServerStop)try{await N.onServerStop()}catch(L){I.push(`onServerStop failed: ${L instanceof Error?L.message:String(L)}`)}R.registerProviders(w,c.hostServices);let x=R.hostServicesFor(w,c.hostServices);if(w.onServerStart&&c.app)try{await w.onServerStart(c.app,x),R.registerProviders(w,c.hostServices)}catch(L){I.push(`onServerStart failed: ${L instanceof Error?L.message:String(L)}`)}if(w.onServerReady&&c.app)try{await w.onServerReady(c.app,x)}catch(L){I.push(`onServerReady failed: ${L instanceof Error?L.message:String(L)}`)}}if(c.rebuildPluginSurfaces?.(),I.length>0)return t.status=500,{success:!1,message:`Plugin ${a} installed but failed to start`,lifecycleErrors:I,restartRequired:!0}}let C;if(w&&c.app)try{C=await qt(w,a,c.app,c.db,{skipInstall:!!b.skipPrereqs})}catch(I){C=void 0,console.warn(`[plugin-mgr] prereq run failed for ${a}:`,I)}return rr(c.db),e().audit.emit("agent","plugin.installed",{packageName:a,version:k.version,pluginName:k.pluginName,wasRunning:v}),{success:!0,message:`Plugin ${a} installed and loaded successfully`,prereqs:C?{satisfied:C.satisfied,missing:C.status?.missing??[],pendingSudo:C.pendingSudo,skipped:!!b.skipPrereqs}:void 0}})}catch(a){if(a instanceof ce)return t.status=400,{error:"signature_check_failed",reason:a.reason,details:a.message};if(a instanceof Lt)return t.status=428,{error:"confirmation_required",code:a.code,packageName:a.packageName,message:a.message};return t.status=500,{error:"Failed to install plugin",details:String(a)}}},{body:r.Object({packageName:r.String(),skipPrereqs:r.Optional(r.Boolean()),confirmUntrusted:r.Optional(r.Boolean())})}).post("/prereqs/status",async({body:b,set:t})=>{if(!b.packageName)return t.status=400,{error:"Missing packageName"};let a=b.packageName,d=R.getAllPlugins().find((P)=>P.name===a||R.getLoaded(a)?.name===P.name);if(!d||!c.app)return await Cr(c.db,a)??{satisfied:!0,missing:[]};try{let P=await qt(d,a,c.app,c.db,{skipInstall:!0});return{satisfied:P.satisfied,missing:P.status?.missing??[],noProtocol:P.noProtocol}}catch(P){return t.status=500,{error:String(P)}}},{body:r.Object({packageName:r.String()})}).post("/prereqs/install",async({body:b,set:t})=>{if(!b.packageName)return t.status=400,{error:"Missing packageName"};let a=b.packageName,d=R.getAllPlugins().find((P)=>P.name===a||R.getLoaded(a)?.name===P.name);if(!d||!c.app)return t.status=404,{error:"Plugin not loaded"};try{let P=await qt(d,a,c.app,c.db,{skipInstall:!1});return{satisfied:P.satisfied,installed:P.install?.installed??[],pendingSudo:P.pendingSudo,errors:P.install?.errors??[],noProtocol:P.noProtocol}}catch(P){return t.status=500,{error:String(P)}}},{body:r.Object({packageName:r.String(),approveSudo:r.Optional(r.Boolean())})}).post("/prereqs/uninstall",async({body:b,set:t})=>{if(!b.packageName)return t.status=400,{error:"Missing packageName"};let a=b.packageName,d=R.getAllPlugins().find((k)=>k.name===a);if(!d||!d.apiPrefix||!c.app)return t.status=404,{error:"Plugin not loaded"};let P=c.app.handle;if(typeof P!=="function")return t.status=500,{error:"App handle unavailable"};let N=`${d.apiPrefix.replace(/\/+$/,"")}/prereqs/uninstall`,v=await P.call(c.app,new Request(`http://agent.local${N}`,{method:"POST",headers:{"x-vc-profile-rewrite":"1",[St]:Qt()}}));if(v.status===404)return t.status=404,{error:"Plugin has no prereqs/uninstall endpoint"};return v.json()},{body:r.Object({packageName:r.String()})}).post("/nuke",async({body:b,set:t})=>{if(!c.hostServices)return t.status=503,{error:"hostServices unavailable"};let a=c.hostServices.getDataDir?.();return{ok:!0,...await R.runPluginNuke(b.packageName,c.hostServices,{agentDir:a,dryRun:!!b.dryRun})}},{body:r.Object({packageName:r.Optional(r.String()),dryRun:r.Optional(r.Boolean())})}).post("/remove",async({body:b,set:t})=>{if(!b.packageName||typeof b.packageName!=="string")return t.status=400,{error:"Missing required field: packageName"};if(b.packageName.startsWith("@burdenoff/"))b.packageName=b.packageName.replace(/^@burdenoff\//,"@vibecontrols/");if(Et(b.packageName))return{success:!0,message:`Plugin ${b.packageName} is critical and cannot be removed; treating remove as a no-op.`,skipped:!0};try{let a=fe(b.packageName);return await O(a,async()=>(await R.remove(a,c.hostServices),c.rebuildPluginSurfaces?.(),rr(c.db),e().audit.emit("agent","plugin.removed",{packageName:a}),{success:!0,message:`Plugin ${a} removed successfully`}))}catch(a){return t.status=500,{error:"Failed to remove plugin",details:String(a)}}},{body:r.Object({packageName:r.String()})}).post("/update",async({body:b,set:t})=>{if(!b.packageName||typeof b.packageName!=="string")return t.status=400,{error:"Missing required field: packageName"};let a=typeof b.version==="string"&&b.version.trim()?b.version.trim():void 0;if(a&&!/^[0-9][0-9A-Za-z.+-]{0,63}$/.test(a))return t.status=400,{error:`Invalid version "${a}"`};try{let d=fe(b.packageName);return await O(d,async()=>{let P=R.getLoaded(d);if(P?.onServerStop)await P.onServerStop({reason:"reload"});if(P&&c.hostServices)c.hostServices.serviceRegistry.unregisterPlugin(P.name);let N=await R.update(d,a),v=R.getLoaded(d);if(v&&c.hostServices){R.registerProviders(v,c.hostServices);let k=R.hostServicesFor(v,c.hostServices);if(v.onServerStart&&c.app)await v.onServerStart(c.app,k),R.registerProviders(v,c.hostServices);if(v.onServerReady&&c.app)await v.onServerReady(c.app,k)}return c.rebuildPluginSurfaces?.(),rr(c.db),{success:!0,message:`Plugin ${d} updated to v${N.version}`,version:N.version}})}catch(d){return t.status=500,{error:"Failed to update plugin",details:String(d)}}},{body:r.Object({packageName:r.String(),version:r.Optional(r.String())})}).post("/update-all",async({set:b})=>{try{let t=await O("*",()=>R.updateAll());return{success:!0,results:t,message:`Updated ${t.filter((a)=>a.success).length}/${t.length} plugin(s)`}}catch(t){return b.status=500,{error:"Failed to update all plugins",details:String(t)}}}).post("/remove-all",async({set:b})=>{try{let t=await O("*",async()=>{let a=await R.removeAll(c.hostServices);return c.rebuildPluginSurfaces?.(),a});return{success:!0,results:t,message:`Removed ${t.filter((a)=>a.success).length}/${t.length} plugin(s)`}}catch(t){return b.status=500,{error:"Failed to remove all plugins",details:String(t)}}}).post("/reload",async({set:b})=>{try{if(!c.app||!c.hostServices)return b.status=503,{error:"Plugin lifecycle services are not ready"};let t=await O("*",async()=>(await R.reloadAll(c.app,c.hostServices),c.rebuildPluginSurfaces?.(),R.getPluginDetails()));return{success:!0,plugins:t,message:`Reloaded ${t.length} plugin(s)`}}catch(t){return b.status=500,{error:"Failed to reload plugins",details:String(t)}}}).post("/:name/reload",async({params:b,set:t})=>{if(!c.app||!c.hostServices)return t.status=503,{error:"Plugin lifecycle services are not ready"};let a=b.name,d=R.getAllPlugins().find((v)=>v.name===a);if(!d)return t.status=404,{error:`Plugin "${a}" not found`};let N=R.getPluginDetails().find((v)=>v.pluginName===a)?.packageName??`core:${a}`;if(X(N))return t.status=409,{error:"Plugin lifecycle in progress; try again shortly",packageName:N};try{R.verifyLoadedSignature(N)}catch(v){if(!(v instanceof ce))throw v;try{await d.onServerStop?.({reason:"shutdown"})}catch(k){console.warn(`[plugin-mgr] onServerStop after a failed signature check of ${a}:`,k)}return c.hostServices.serviceRegistry.unregisterPlugin(d.name),await R.evictLoaded(N),t.status=400,{error:"signature_check_failed",reason:v.reason,details:v.message}}try{return await O(N,async()=>{if(d.onServerStop)try{await d.onServerStop({reason:"reload"})}catch(k){console.warn(`[plugin-mgr] onServerStop during reload of ${a}:`,k)}if(c.hostServices)c.hostServices.serviceRegistry.unregisterPlugin(d.name);R.registerProviders(d,c.hostServices);let v=R.hostServicesFor(d,c.hostServices);if(d.onServerStart)await d.onServerStart(c.app,v),R.registerProviders(d,c.hostServices);if(d.onServerReady)await d.onServerReady(c.app,v);return c.rebuildPluginSurfaces?.(),{success:!0,message:`Plugin ${a} reloaded`,version:d.version}})}catch(v){return t.status=500,{error:"Failed to reload plugin",details:String(v)}}},{params:r.Object({name:r.String()})})}import{mkdirSync as W,writeFileSync as M,existsSync as ne}from"fs";import{isAbsolute as Se,join as j,relative as Pe,resolve as G}from"path";var J="http://localhost:3005";async function we(c,R,b={interactive:ue,prompt:le,warn:p}){if(!tt(c))return!0;if(b.warn(ur(c)?`${c} is a desk plugin: it lets a BotManor Steward see and use this machine. Remote control stays off until you turn it on.`:`${c} is not a trusted plugin.`),R.yes===!0)return!0;if(!b.interactive())return b.warn("Re-run with --yes to confirm the install."),!1;return b.prompt(`Install ${c}?`)}var ke=/^[a-z0-9][a-z0-9-]{0,63}$/,$e=new Set(["backend","frontend","cli","provider","adapter","integration"]);function ie(c,R){let b=Pe(c,R);if(b.startsWith("..")||Se(b))throw Error("Plugin scaffold path escapes the selected directory.")}function T(c){return JSON.stringify(c)}function re(c){let R=c.command("plugin").description("Manage plugins");R.command("list").description("List installed plugins").option("--agent-url <url>","Agent URL",J).option("--profile <name>","Target a specific profile by name").option("--json","Emit JSON").option("--plain","Force plain text output").action(async(t)=>{try{let a={...c.opts(),...t},d=f(t),P=encodeURIComponent(m(a)),N=async()=>{try{return(await S(d,`/api/profiles/${P}/plugins`)).plugins||[]}catch{p("Agent not reachable. Attempting local plugin registry...");let{PluginManager:h}=await import("./plugin-system-e690jr6e.js");return new h().getPluginDetails()||[]}},v=(h)=>h.status??(h.loaded===!0||h.enabled===!0?"enabled":"disabled"),k=(h)=>h.pluginName||h.name||h.packageName||h.package||"-";await y({mode:_(a),fetchData:N,plain:(h)=>{if(!h.length){o("No plugins installed.");return}g("Installed Plugins"),F(h.map((w)=>({Name:k(w),Version:w.version||"-",Status:v(w),Description:w.description||"-"})))},interactive:async(h)=>{if(!h.length){g("Installed Plugins"),o("No plugins installed.");return}let w=h.map((C)=>{let I=k(C),x=v(C),L=[`${i.bold(I)} ${x==="enabled"?i.green(x):i.dim(x)}`,"",` Version: ${C.version||"-"}`,` Description: ${C.description||"-"}`];if(C.tags&&Array.isArray(C.tags))L.push(` Tags: ${C.tags.join(", ")}`);if(C.cliCommand)L.push(` CLI command: vibe ${C.cliCommand}`);return{id:I,label:I,hint:x,detail:L.join(`
|
|
3
|
+
`)}});await Q({title:`vibe plugin \u2014 ${h.length} installed`,rows:w,footer:"\u2191/\u2193 navigate \xB7 q to quit"})},json:(h)=>h.map((w)=>({name:k(w),version:w.version??null,status:v(w),description:w.description??null,tags:w.tags??null,cliCommand:w.cliCommand??null}))})}catch(a){s(A(a))}}),R.command("install").description("Install a plugin").argument("<package>","NPM package name to install").option("--agent-url <url>","Agent URL",J).option("--profile <name>","Target a specific profile by name").option("--skip-prereqs","Skip running the plugin's prereqs/install",!1).option("--json","Emit JSON result").option("-y, --yes","Confirm installing an untrusted plugin",!1).action(async(t,a)=>{try{let d={...c.opts(),...a},P=f(a),N=encodeURIComponent(m(d)),v=Ue(t)??t,k=tt(v);if(!await we(v,d)){s(`Install of ${v} cancelled.`);return}try{let h=await q(P,`/api/profiles/${N}/plugins/install`,{packageName:t,skipPrereqs:!!a.skipPrereqs,...k?{confirmUntrusted:!0}:{}});if(u(d,{ok:!0,action:"install",package:t,version:h?.version??null,prereqs:h?.prereqs??null}))return;if(l(`Plugin "${t}" installed.`),h?.version)n("Version",h.version);if(h?.prereqs){let w=h.prereqs;if(w.skipped)p(`Prerequisite install skipped. Run \`vibe plugin prereqs ${t} install\` later.`);else if(!w.satisfied)p(`Prerequisites not yet satisfied: ${(w.missing||[]).map((C)=>C.name).join(", ")||"(unknown)"}`);if((w.pendingSudo||[]).length>0){p(`${w.pendingSudo.length} command(s) need sudo. Run them and re-check with \`vibe plugin prereqs ${t} status\`:`);for(let C of w.pendingSudo)n(` ${C.name}`,C.command)}}}catch{p("Agent not reachable. Attempting local install...");try{let{PluginManager:h}=await import("./plugin-system-e690jr6e.js");if(await new h().install(t,{confirmUntrusted:k}),u(d,{ok:!0,action:"install",package:t,local:!0}))return;l(`Plugin "${t}" installed locally.`)}catch(h){s(`Could not install plugin via agent or locally: ${A(h)}`)}}}catch(d){s(A(d))}}),R.command("remove").description("Remove a plugin").argument("<package>","NPM package name to remove").option("--agent-url <url>","Agent URL",J).option("--profile <name>","Target a specific profile by name").option("--json","Emit JSON result").action(async(t,a)=>{try{let d={...c.opts(),...a},P=f(a),N=encodeURIComponent(m(d));try{if(await q(P,`/api/profiles/${N}/plugins/remove`,{packageName:t}),u(d,{ok:!0,action:"remove",package:t}))return;l(`Plugin "${t}" removed.`)}catch{p("Agent not reachable. Attempting local removal...");try{let{PluginManager:v}=await import("./plugin-system-e690jr6e.js");if(await new v().remove(t),u(d,{ok:!0,action:"remove",package:t,local:!0}))return;l(`Plugin "${t}" removed locally.`)}catch(v){s(`Could not remove plugin via agent or locally: ${A(v)}`)}}}catch(d){s(A(d))}}),R.command("update").description("Update a plugin (or all plugins with --all)").argument("[package]","NPM package name to update").option("--all","Update all installed plugins",!1).option("--agent-url <url>","Agent URL",J).option("--profile <name>","Target a specific profile by name").option("--json","Emit JSON result").action(async(t,a)=>{try{let d={...c.opts(),...a},P=f(a),N=encodeURIComponent(m(d));if(a.all){o("Updating all plugins...");try{let v=await q(P,`/api/profiles/${N}/plugins/update-all`,{}),k=v?.results||[];if(u(d,{ok:!0,action:"update-all",results:k}))return;for(let h of k)if(h.success)l(`Updated ${h.packageName}${h.version?` to v${h.version}`:""}`);else p(`Failed to update ${h.packageName}: ${h.error}`);l(v?.message||"Done.")}catch{p("Agent not reachable. Attempting local update...");try{let{PluginManager:v}=await import("./plugin-system-e690jr6e.js"),h=await new v().updateAll();if(u(d,{ok:!0,action:"update-all",results:h,local:!0}))return;for(let w of h)if(w.success)l(`Updated ${w.packageName}${w.version?` to v${w.version}`:""}`);else p(`Failed to update ${w.packageName}: ${w.error}`)}catch(v){s(`Could not update plugins: ${A(v)}`)}}}else if(t){o(`Updating ${t}...`);try{let v=await q(P,`/api/profiles/${N}/plugins/update`,{packageName:t});if(u(d,{ok:!0,action:"update",package:t,version:v?.version??null,message:v?.message??null}))return;l(v?.message||`Plugin "${t}" updated.`)}catch{p("Agent not reachable. Attempting local update...");try{let{PluginManager:v}=await import("./plugin-system-e690jr6e.js"),h=await new v().update(t);if(u(d,{ok:!0,action:"update",package:t,version:h.version,local:!0}))return;l(`Plugin "${t}" updated to v${h.version}.`)}catch(v){s(`Could not update plugin: ${A(v)}`)}}}else s("Provide a package name to update, or use --all to update all plugins.")}catch(d){s(A(d))}}),R.command("uninstall").description("Uninstall a plugin (or all plugins with --all)").argument("[package]","NPM package name to uninstall").option("--all","Uninstall all external plugins",!1).option("--agent-url <url>","Agent URL",J).option("--profile <name>","Target a specific profile by name").option("--json","Emit JSON result").action(async(t,a)=>{try{let d={...c.opts(),...a},P=f(a),N=encodeURIComponent(m(d));if(a.all){o("Uninstalling all plugins...");try{let v=await q(P,`/api/profiles/${N}/plugins/remove-all`,{}),k=v?.results||[];if(u(d,{ok:!0,action:"uninstall-all",results:k}))return;for(let h of k)if(h.success)l(`Removed ${h.packageName}`);else p(`Failed to remove ${h.packageName}: ${h.error}`);l(v?.message||"Done.")}catch{p("Agent not reachable. Attempting local removal...");try{let{PluginManager:v}=await import("./plugin-system-e690jr6e.js"),h=await new v().removeAll();if(u(d,{ok:!0,action:"uninstall-all",results:h,local:!0}))return;for(let w of h)if(w.success)l(`Removed ${w.packageName}`);else p(`Failed to remove ${w.packageName}: ${w.error}`)}catch(v){s(`Could not uninstall plugins: ${A(v)}`)}}}else if(t)try{if(await q(P,`/api/profiles/${N}/plugins/remove`,{packageName:t}),u(d,{ok:!0,action:"uninstall",package:t}))return;l(`Plugin "${t}" uninstalled.`)}catch{p("Agent not reachable. Attempting local removal...");try{let{PluginManager:v}=await import("./plugin-system-e690jr6e.js");if(await new v().remove(t),u(d,{ok:!0,action:"uninstall",package:t,local:!0}))return;l(`Plugin "${t}" uninstalled locally.`)}catch(v){s(`Could not uninstall plugin: ${A(v)}`)}}else s("Provide a package name to uninstall, or use --all to uninstall all plugins.")}catch(d){s(A(d))}}),R.command("reload").description("Reload all plugins").option("--agent-url <url>","Agent URL",J).option("--profile <name>","Target a specific profile by name").option("--json","Emit JSON result").action(async(t)=>{try{let a={...c.opts(),...t},d=f(t),P=encodeURIComponent(m(a));if(await q(d,`/api/profiles/${P}/plugins/reload`,{}),u(a,{ok:!0,action:"reload"}))return;l("Plugins reloaded.")}catch(a){s(A(a))}}),R.command("available").description("Show available plugins").option("--agent-url <url>","Agent URL",J).option("--profile <name>","Target a specific profile by name").option("--json","Emit JSON").option("--plain","Force plain text output").action(async(t)=>{try{let a={...c.opts(),...t},d=f(t),P=encodeURIComponent(m(a)),N=async()=>(await S(d,`/api/profiles/${P}/plugins/available`)).plugins||[],v=(h)=>h.name||h.package||"-",k=(h)=>h.version||h.latestVersion||"-";await y({mode:_(a),fetchData:N,plain:(h)=>{if(!h||h.length===0){o("No available plugins found.");return}g("Available Plugins"),F(h.map((w)=>({Name:v(w),Version:k(w),Description:w.description||"-"})))},interactive:async(h)=>{if(!h||h.length===0){g("Available Plugins"),o("No available plugins found.");return}let w=h.map((C)=>{let I=v(C),x=[i.bold(I),"",` Version: ${k(C)}`,` Description: ${C.description||"-"}`];return{id:I,label:I,hint:k(C),detail:x.join(`
|
|
4
4
|
`)}});await Q({title:`vibe plugin available \u2014 ${h.length} plugin(s)`,rows:w,footer:"\u2191/\u2193 navigate \xB7 q to quit"})},json:(h)=>h.map((w)=>({name:v(w),version:k(w),description:w.description??null}))})}catch(a){s(A(a))}});let b=R.command("prereqs").description("Inspect or run a plugin's prerequisite-install protocol").argument("<package>","NPM package name (or short plugin name)");b.command("status",{isDefault:!0}).description("Show the plugin's prereq status").option("--agent-url <url>","Agent URL",J).option("--profile <name>","Target a specific profile by name").option("--json","Emit JSON").option("--plain","Force plain text output").action(async(t,a)=>{let d=a.parent?.args?.[0];if(!d){s("Missing plugin package argument.");return}try{let P={...c.opts(),...t},N=f(t),v=async()=>q(N,"/api/plugins/prereqs/status",{packageName:d});await y({mode:_(P),fetchData:v,plain:(k)=>{if(n("Plugin",d),n("Satisfied",k?.satisfied?"yes":"no"),Array.isArray(k?.missing)&&k.missing.length>0)n("Missing",k.missing.map((h)=>h.name).join(", "))},interactive:async(k)=>{let h=[`Plugin: ${d}`,`Satisfied: ${k?.satisfied?"yes":"no"}`];if(Array.isArray(k?.missing)&&k.missing.length>0)h.push(`Missing: ${k.missing.map((w)=>w.name).join(", ")}`);await U({title:`Prereqs: ${d}`,body:h.join(`
|
|
5
5
|
`),footer:"q / Esc to quit"})},json:(k)=>({plugin:d,satisfied:!!k?.satisfied,missing:Array.isArray(k?.missing)?k.missing:[],pendingSudo:Array.isArray(k?.pendingSudo)?k.pendingSudo:[]})})}catch(P){s(`Could not read prereq status: ${A(P)}`)}}),b.command("install").description("Run the plugin's prerequisite install endpoint").option("--agent-url <url>","Agent URL",J).option("--profile <name>","Target a specific profile by name").option("--approve-sudo","Auto-approve sudo commands the plugin returns",!1).option("--json","Emit JSON result").action(async(t,a)=>{let d=a.parent?.args?.[0];if(!d){s("Missing plugin package argument.");return}try{let P={...c.opts(),...t},N=f(t),v=await q(N,"/api/plugins/prereqs/install",{packageName:d,approveSudo:!!t.approveSudo});if(u(P,{ok:!0,action:"prereqs-install",plugin:d,satisfied:!!v?.satisfied,pendingSudo:v?.pendingSudo??[]}))return;if(v?.satisfied)l(`Prerequisites satisfied for ${d}.`);else p(`Prerequisites still missing for ${d}.`);if(Array.isArray(v?.pendingSudo)&&v.pendingSudo.length>0){p(`${v.pendingSudo.length} command(s) require sudo:`);for(let k of v.pendingSudo)n(` ${k.name}`,k.command)}}catch(P){s(`Prereq install failed: ${A(P)}`)}}),b.command("uninstall").description("Run the plugin's prerequisite uninstall endpoint (if supported)").option("--agent-url <url>","Agent URL",J).option("--profile <name>","Target a specific profile by name").option("--json","Emit JSON result").action(async(t,a)=>{let d=a.parent?.args?.[0];if(!d){s("Missing plugin package argument.");return}try{let P={...c.opts(),...t},N=f(t);if(await q(N,"/api/plugins/prereqs/uninstall",{packageName:d}),u(P,{ok:!0,action:"prereqs-uninstall",plugin:d}))return;l(`Prereq uninstall completed for ${d}.`)}catch(P){p(`Prereq uninstall not supported or failed: ${A(P)}`)}}),R.command("create").description("Scaffold a new plugin project").argument("<name>",'Plugin name (e.g. "docker" \u2192 vibe-plugin-docker)').option("-d, --dir <directory>","Parent directory",".").option("--tag <tag>","Plugin tag (backend, frontend, cli, provider, adapter, integration)","backend").option("--with-ui","Include a companion UI plugin scaffold",!1).option("--json","Emit JSON result").action(async(t,a)=>{try{let d={...c.opts(),...a},P=t.startsWith("vibe-plugin-")?t.slice(12):t;if(!ke.test(P)){s("Plugin name must use lowercase letters, numbers, and dashes only.");return}let N=a.tag;if(!$e.has(N)){s("Invalid plugin tag.");return}let v=`vibe-plugin-${P}`,k=G(a.dir),h=G(k,v);if(ie(k,h),ne(h)){s(`Directory "${h}" already exists.`);return}o(`Scaffolding ${v}...`),W(j(h,"src"),{recursive:!0}),W(j(h,"dist"),{recursive:!0});let w=`VibeControls plugin: ${P}`,C={name:`@vibecontrols/${v}`,version:"0.1.0",main:"./dist/index.js",type:"module",engines:{bun:">=1.3.0"},scripts:{build:"bun build ./src/index.ts --outdir ./dist --target bun",lint:"eslint ./src",format:"bunx prettier . --write","format:check":"bunx prettier . --check","type:check":"tsc --noEmit",clean:"rimraf dist",prebuild:"bun run clean",prepublishOnly:"bun run build",sanity:"bun run format:check && bun run lint && bun run type:check && bun run build"},keywords:["vibecontrols","vibe","vibe-plugin",P,"bun"],author:{name:"Your Name",email:"you@example.com"},license:"SEE LICENSE IN LICENSE",description:w,devDependencies:{"@types/bun":"^1.2.16","bun-types":"^1.3.9",commander:"^14.0.3",eslint:"^9.30.1",prettier:"^3.6.2",rimraf:"^6.0.1",typescript:"^5.8.3","typescript-eslint":"^8.56.0"},peerDependencies:{"@vibecontrols/agent":">=2.0.0"},peerDependenciesMeta:{"@vibecontrols/agent":{optional:!0}},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},files:["dist/**/*","README.md","LICENSE"]};M(j(h,"package.json"),JSON.stringify(C,null,2)+`
|
|
6
6
|
`);let I={compilerOptions:{target:"ES2022",module:"ES2022",moduleResolution:"bundler",types:["bun-types"],strict:!0,esModuleInterop:!0,skipLibCheck:!0,outDir:"./dist",rootDir:"./src",declaration:!0,sourceMap:!0},include:["src/**/*.ts"],exclude:["node_modules","dist"]};M(j(h,"tsconfig.json"),JSON.stringify(I,null,2)+`
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{ot,bt,Ji,Oe,Xt,O,I,C}from"./index-7wm4bqx5.js";import{Ae}from"./index-
|
|
2
|
+
import{ot,bt,Ji,Oe,Xt,O,I,C}from"./index-7wm4bqx5.js";import{Ae}from"./index-8jk4a62x.js";import{b}from"./index-w4jqdhc2.js";import{existsSync as f,readdirSync as R,readFileSync as h,writeFileSync as m,mkdirSync as y,openSync as P,closeSync as w,unlinkSync as v}from"fs";import{join as l}from"path";import{tmpdir as k}from"os";import{spawn as A}from"child_process";class D{registryPath;logsDir;productDir;constructor(){let t=C();this.productDir=t,this.registryPath=l(t,"agents.json");let s=I();this.logsDir=l(s,"logs"),y(t,{recursive:!0}),y(s,{recursive:!0}),y(this.logsDir,{recursive:!0})}async startDaemon(t){return O(t.name),this.withInstanceLock(t.name,async()=>{let s=await this.findProcessByName(t.name);if(s&&s.status==="running"){let u=s.version,g=Ae();if(u===g){console.log(`\u26A0\uFE0F Agent '${t.name}' is already running on port ${s.port}`);return}console.log(`\uD83D\uDD04 Agent '${t.name}' is running an older build (${u??"unknown"} \u2192 ${g}) \u2014 restarting to apply the update`);try{await this.stopInternal(t.name)}catch(d){console.log(`\u26A0\uFE0F Could not cleanly stop the stale daemon (${d instanceof Error?d.message:String(d)}); proceeding to start the new build`)}}let e=l(this.logsDir,`${t.name}.log`),n=P(e,"a"),i=l(import.meta.dir,"index.js"),r=l(import.meta.dir,"..","index.ts"),c=f(i)?i:r,a=A(process.execPath,["run",c],{detached:!0,windowsHide:!0,stdio:["ignore",n,n],env:{...process.env,VIBECONTROLS_PROFILE:t.profile||"default",PORT:t.port.toString(),DB_PATH:t.dbPath,NODE_ENV:"production",AGENT_LOG_FILE:e}});a.on("error",()=>{}),w(n),await new Promise((u)=>setTimeout(u,2000));let o=a.pid;if(!(o!==void 0&&await this.isProcessRunning(o))){let u="";try{u=h(e,"utf8").split(/\r?\n/).filter((S)=>S.trim()).slice(-25).join(`
|
|
3
3
|
`)}catch{}let g=`See ${e}`;throw Error(u?`Failed to start agent '${t.name}'. ${g}
|
|
4
4
|
--- last log lines ---
|
|
5
5
|
${u}`:`Failed to start agent '${t.name}'. ${g}`)}a.unref(),await this.saveProcessInfo(t.name,o,t),console.log(`\uD83D\uDE80 Agent '${t.name}' started (PID: ${o}, Port: ${t.port})`)})}async stop(t){return O(t),this.withInstanceLock(t,()=>this.stopInternal(t))}async stopInternal(t){let s=await this.findProcessByName(t);if(!s||s.status!=="running"){console.log(`\u26A0\uFE0F Agent '${t}' is not running`);return}try{if(process.kill(s.pid,"SIGTERM"),await new Promise((n)=>setTimeout(n,3000)),await this.isProcessRunning(s.pid))process.kill(s.pid,"SIGKILL");await this.updateProcessStatus(t,"stopped"),console.log(`\u2705 Agent '${t}' stopped (tunnel + API key preserved)`)}catch(e){throw Error(`Failed to stop agent '${t}': ${e}`,{cause:e})}}async restart(t,s){O(t),O(s.name);let e=await this.findProcessByName(t);if(e&&e.status==="running")await this.stop(t);await this.startDaemon(s),console.log(`\uD83D\uDD04 Agent '${t}' restarted (tunnel + API key preserved)`)}async kill(t){return O(t),this.withInstanceLock(t,async()=>{let s=await this.findProcessByName(t);if(!s||s.status!=="running"){console.log(`\u26A0\uFE0F Agent '${t}' is not running`);return}let e=l(k(),`.boff-vibecontrols-kill-${s.pid}`);try{await Bun.write(e,"kill")}catch{}try{process.kill(s.pid,"SIGTERM"),await new Promise((i)=>setTimeout(i,5000))}catch{}if(await this.isProcessRunning(s.pid))await this.killProcessTree(s.pid);await this.updateProcessStatus(t,"stopped"),console.log(`\uD83D\uDC80 Agent '${t}' killed (tunnel + state torn down)`)})}async getStatus(t){return O(t),this.findProcessByName(t)}discoverRuntimeInstances(){let t=l(this.productDir,"agents");if(!f(t))return[];let s;try{s=R(t,{withFileTypes:!0}).filter((n)=>n.isDirectory()).map((n)=>n.name)}catch{return[]}let e=[];for(let n of s){let i=l(t,n,"runtime.json");if(!f(i))continue;try{let r=JSON.parse(h(i,"utf8"));if(typeof r.pid!=="number"||typeof r.port!=="number")continue;let c=r.profile||n;try{O(c)}catch{continue}e.push({name:c,pid:r.pid,port:r.port,config:{name:c,port:r.port,daemon:!0,dbPath:l(t,n,"agent-db"),host:r.host,profile:c},startTime:r.startedAt??new Date(0).toISOString(),status:"unknown",version:r.version})}catch{}}return e}async getStatusAll(){let t=this.loadRegistry(),s=new Set(t.map((r)=>r.name)),e=[...t];for(let r of this.discoverRuntimeInstances())if(!s.has(r.name))e.push(r);let n=[];for(let r of e){let c=await this.isManagedProcessRunning(r);if(!s.has(r.name)&&!c)continue;n.push({...r,status:c?"running":"stopped"})}let i=n.filter((r)=>r.status==="running"&&!s.has(r.name));if(i.length>0)try{await ot(()=>{let r=this.loadRegistry(),c=new Set(r.map((o)=>o.name)),a=i.filter((o)=>!c.has(o.name));if(a.length>0)this.saveRegistry([...r,...a.map((o)=>({...o,status:"running"}))])})}catch{}return n}async listInstances(){return this.getStatusAll()}getDefaultProfile(){return Oe()}setDefaultProfile(t){Xt(O(t))}async showLogs(t,s){O(t);let e=l(this.logsDir,`${t}.log`);if(!f(e)){console.log(`No logs found for agent '${t}'`);return}if(s.follow)try{let n=async(o)=>{let p=await Bun.file(e).text(),g=p.split(`
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
3
|
-
import"./index-1t74r13z.js";import{gi,zt,xr,di,br}from"./index-
|
|
3
|
+
import"./index-1t74r13z.js";import{gi,zt,xr,di,br}from"./index-85jn7v8t.js";import"./index-5tghd67e.js";import{R,I,ee,C,e}from"./index-7wm4bqx5.js";import{Ae}from"./index-8jk4a62x.js";import{Re,K}from"./index-qzwbctkv.js";import{J,de,w,X,Ct,ai}from"./index-j99tkngg.js";import"./index-x4z055t8.js";import"./index-p7fbnfwd.js";import"./index-dr6rsnpk.js";import{Z}from"./index-wxb9dgwq.js";import"./index-ednz6yz2.js";import"./index-ppxayc0x.js";import{Tr}from"./index-rhn7wy1p.js";import"./index-twtvt4yt.js";import"./index-br9bakfm.js";import"./index-cn4p1ks0.js";import"./index-damc6cvc.js";async function G(t,i={}){let r=i.readConfig??(async()=>{let n=await X();return{clientId:n.clientId,clientSecret:n.clientSecret,workspaceId:n.workspaceId,organizationId:n.organizationId,globalGatewayUrl:n.globalGatewayUrl,workspaceGatewayUrl:n.workspaceGatewayUrl}});try{let n=i.pinned?.clientId&&i.pinned?.clientSecret?{clientId:i.pinned.clientId,clientSecret:i.pinned.clientSecret}:null,a=await r();if(!a.clientId||!a.clientSecret)return t;return{clientId:n?.clientId??a.clientId,clientSecret:n?.clientSecret??a.clientSecret,workspaceId:a.workspaceId??t.workspaceId,organizationId:a.organizationId??t.organizationId,globalGatewayUrl:a.globalGatewayUrl??t.globalGatewayUrl,workspaceGatewayUrl:a.workspaceGatewayUrl??t.workspaceGatewayUrl}}catch(n){let a=n instanceof Error?n.message:String(n);if(i.onReadError)i.onReadError(a);else e().logger.warn("finalize-retry","Could not re-read stored credentials; retrying with the boot-time pair",{error:a});return t}}import{isAbsolute as me}from"path";import{existsSync as y,mkdirSync as L,readFileSync as ne,readdirSync as B,renameSync as oe,unlinkSync as Pe,writeFileSync as D}from"fs";import{dirname as V,join as v}from"path";var ie=".secrets-migrated-v1",se=["static-api-key","clientId","clientSecret"];function ae(t,i){return`${t}:${i}`}function z(){return v(C(),ie)}function ce(){let t=z();L(V(t),{recursive:!0}),D(t,`${new Date().toISOString()}
|
|
4
4
|
`,{mode:384})}function le(t){if(!y(t))return null;try{let i=ne(t,"utf8"),r=JSON.parse(i);if(r&&typeof r==="object"&&!Array.isArray(r))return r}catch{}return null}function ge(t,i){L(V(t),{recursive:!0});let r=`${t}.${process.pid}.tmp`;D(r,`${JSON.stringify(i,null,2)}
|
|
5
|
-
`,{mode:384}),oe(r,t)}function pe(){let t=C(),i=v(t,"agents");if(!y(i))return[];let r=[],n;try{n=B(i)}catch{return[]}for(let a of n){let l=v(i,a,"config.json");if(!y(l))continue;r.push({path:l,scope:a})}return r}function ue(){let t=C(),i=v(t,"profiles");if(!y(i))return[];let r=[],n;try{n=B(i)}catch{return[]}for(let a of n){if(!a.endsWith(".json"))continue;r.push({path:v(i,a),scope:a.slice(0,-5)})}return r}async function fe(t,i){let r=le(t);if(!r)return 0;let n=0;for(let a of se){let l=r[a];if(typeof l!=="string"||l.length===0)continue;let p=ae(i,a);try{await de(p,l),delete r[a],n++,e().logger.info("secrets-migrator","migrated field",{path:t,scope:i,key:a})}catch(d){e().logger.warn("secrets-migrator","failed to migrate field",{path:t,scope:i,key:a,error:String(d)})}}if(n>0)ge(t,r);return n}async function F(){let t={alreadyMigrated:!1,fieldsMoved:0,filesUpdated:0};if(y(z()))return t.alreadyMigrated=!0,t;let i=[...pe(),...ue()];for(let r of i){let n;try{n=await fe(r.path,r.scope)}catch(a){e().logger.warn("secrets-migrator","skipping target after error",{path:r.path,error:String(a)});continue}if(n>0)t.fieldsMoved+=n,t.filesUpdated++}try{ce()}catch(r){e().logger.warn("secrets-migrator","failed to drop migration marker",{error:String(r)})}if(t.fieldsMoved>0)e().logger.info("secrets-migrator","migration complete",{fieldsMoved:t.fieldsMoved,filesUpdated:t.filesUpdated});return t}{let t=JSON.parse.bind(JSON);JSON.parse=(n,a)=>{try{return t(n,a)}catch(l){if(typeof n==="string"&&n.endsWith("}}"))try{return t(n.slice(0,-1),a)}catch{}throw l}};let r=globalThis.Request?.prototype;if(r&&typeof r.json==="function"){let n=r.json;r.json=async function(){let l=await this.text();if(!l)return;try{return t(l)}catch{if(l.endsWith("}}"))try{return t(l.slice(0,-1))}catch{}let p=new Request("http://shim/",{method:"POST",body:l});return n.call(p)}}}}Tr();Ct();if(!process.env.VIBECONTROLS_DATA_DIR)process.env.VIBECONTROLS_DATA_DIR=I();if(typeof Bun>"u")console.error("ERROR: VibeControls Agent requires Bun runtime."),console.error("Install Bun: https://bun.sh"),process.exit(1);function ye(t){if(t==="default")return 3005;let i=2166136261;for(let r=0;r<t.length;r++)i=Math.imul(i^t.charCodeAt(r),16777619);return 3100+Math.abs(i)%300}var b=(()=>{try{return R()}catch{return"default"}})(),T=Number.parseInt(process.env.PORT||String(ye(b)),10),_=Number.isInteger(T)&&T>0?T:3005,A=process.env.HOST||"0.0.0.0",we=(()=>{let t=process.env.DB_PATH;if(!t)return;if(me(t))return t;console.warn(`[boot] Ignoring relative DB_PATH=${t} (cwd=${process.cwd()}). Use an absolute path or unset to fall back to ${ee()}.`);return})(),P=process.env.AGENT_API_KEY||void 0,ve=process.env.LOG_LEVEL||"info",he=process.env.CORS_ORIGIN||void 0;async function Se(){try{await F()}catch(s){e().logger.warn("server","secrets migration encountered an error",{error:String(s)})}let t=w()["static-api-key"],i=(()=>{try{return R()}catch{return"default"}})(),r=t??await J(`${i}:static-api-key`),n=!P&&!r;await Re();let a={clientId:process.env.VIBE_CLIENT_ID,clientSecret:process.env.VIBE_CLIENT_SECRET};await ai();let l=process.env.VIBE_CLIENT_ID,p=process.env.VIBE_CLIENT_SECRET,d=process.env.VIBE_GLOBAL_GATEWAY_URL,N=process.env.VIBE_WORKSPACE_GATEWAY_URL,M=process.env.VIBE_WORKSPACE_ID,x=!!l&&!!p&&!!d&&!!N&&!!M;e().logger.info("server","Starting VibeControls Agent...",{runtime:"bun",bunVersion:Bun.version,port:_,host:A,env:"production"});try{let s=w(),o=s["telemetry.enabled"]===!0||s["telemetry.enabled"]==="true";Z.init({persisted:o});let c=Date.now();Z.emit("agent.started",{version:process.env.npm_package_version??"unknown",profile:b,platform:process.platform}),process.__vibe_started_at=c}catch{}let h=Math.max(1,Number.parseInt(process.env.VIBECONTROLS_AGENT_BOOT_RETRIES??"10",10)||10),W=(s)=>{let o=String(s?.message??s).toLowerCase();return o.includes("syntax")||o.includes("cannot find module")||o.includes("module not found")||o.includes("typeerror")||o.includes("config schema")||o.includes("invalid config")||o.includes("corrupt")||o.includes("eaccess")||o.includes("eperm")},g=null,u=0;while(!g){u++;try{g=await br({port:_,host:A,dbPath:we,apiKey:P,logLevel:ve,corsOrigin:he}),await g.start();try{let s=await import("fs"),o=`${I()}/runtime.json`;s.writeFileSync(o,JSON.stringify({pid:process.pid,port:_,host:A,profile:b,startedAt:new Date().toISOString(),version:Ae()},null,2));let c=()=>{try{if(s.existsSync(o))s.unlinkSync(o)}catch{}};process.once("SIGTERM",c),process.once("SIGINT",c),process.once("exit",c)}catch(s){e().logger.warn("server","Could not write runtime.json",{error:String(s)})}}catch(s){let o=W(s);if(e().logger.error("server","Failed to start agent server",{attempt:u,maxBootAttempts:h,fatal:o,error:String(s)}),o||u>=h)console.error(`\u274C Failed to start VibeControls Agent (attempt ${u}/${h}, fatal=${o}):`,s),process.exit(1);let c=Math.min(30000,1000*2**Math.min(5,u-1)),m=Math.floor(Math.random()*500),S=c+m;console.warn(`\u26A0\uFE0F Agent boot attempt ${u}/${h} failed (transient), retrying in ${Math.round(S/1000)}s...`),await new Promise((k)=>setTimeout(k,S)),g=null}}let O=g.getServiceRegistry().getProvider("tunnel"),f=null;if(O?.getActiveTunnelUrl)for(let s=0;s<30;s++){if(f=await O.getActiveTunnelUrl(),f)break;await new Promise((o)=>setTimeout(o,1000))}if(!f){let{sanitizeEnvSuffix:s}=await import("./tunnel-bootstrap-
|
|
5
|
+
`,{mode:384}),oe(r,t)}function pe(){let t=C(),i=v(t,"agents");if(!y(i))return[];let r=[],n;try{n=B(i)}catch{return[]}for(let a of n){let l=v(i,a,"config.json");if(!y(l))continue;r.push({path:l,scope:a})}return r}function ue(){let t=C(),i=v(t,"profiles");if(!y(i))return[];let r=[],n;try{n=B(i)}catch{return[]}for(let a of n){if(!a.endsWith(".json"))continue;r.push({path:v(i,a),scope:a.slice(0,-5)})}return r}async function fe(t,i){let r=le(t);if(!r)return 0;let n=0;for(let a of se){let l=r[a];if(typeof l!=="string"||l.length===0)continue;let p=ae(i,a);try{await de(p,l),delete r[a],n++,e().logger.info("secrets-migrator","migrated field",{path:t,scope:i,key:a})}catch(d){e().logger.warn("secrets-migrator","failed to migrate field",{path:t,scope:i,key:a,error:String(d)})}}if(n>0)ge(t,r);return n}async function F(){let t={alreadyMigrated:!1,fieldsMoved:0,filesUpdated:0};if(y(z()))return t.alreadyMigrated=!0,t;let i=[...pe(),...ue()];for(let r of i){let n;try{n=await fe(r.path,r.scope)}catch(a){e().logger.warn("secrets-migrator","skipping target after error",{path:r.path,error:String(a)});continue}if(n>0)t.fieldsMoved+=n,t.filesUpdated++}try{ce()}catch(r){e().logger.warn("secrets-migrator","failed to drop migration marker",{error:String(r)})}if(t.fieldsMoved>0)e().logger.info("secrets-migrator","migration complete",{fieldsMoved:t.fieldsMoved,filesUpdated:t.filesUpdated});return t}{let t=JSON.parse.bind(JSON);JSON.parse=(n,a)=>{try{return t(n,a)}catch(l){if(typeof n==="string"&&n.endsWith("}}"))try{return t(n.slice(0,-1),a)}catch{}throw l}};let r=globalThis.Request?.prototype;if(r&&typeof r.json==="function"){let n=r.json;r.json=async function(){let l=await this.text();if(!l)return;try{return t(l)}catch{if(l.endsWith("}}"))try{return t(l.slice(0,-1))}catch{}let p=new Request("http://shim/",{method:"POST",body:l});return n.call(p)}}}}Tr();Ct();if(!process.env.VIBECONTROLS_DATA_DIR)process.env.VIBECONTROLS_DATA_DIR=I();if(typeof Bun>"u")console.error("ERROR: VibeControls Agent requires Bun runtime."),console.error("Install Bun: https://bun.sh"),process.exit(1);function ye(t){if(t==="default")return 3005;let i=2166136261;for(let r=0;r<t.length;r++)i=Math.imul(i^t.charCodeAt(r),16777619);return 3100+Math.abs(i)%300}var b=(()=>{try{return R()}catch{return"default"}})(),T=Number.parseInt(process.env.PORT||String(ye(b)),10),_=Number.isInteger(T)&&T>0?T:3005,A=process.env.HOST||"0.0.0.0",we=(()=>{let t=process.env.DB_PATH;if(!t)return;if(me(t))return t;console.warn(`[boot] Ignoring relative DB_PATH=${t} (cwd=${process.cwd()}). Use an absolute path or unset to fall back to ${ee()}.`);return})(),P=process.env.AGENT_API_KEY||void 0,ve=process.env.LOG_LEVEL||"info",he=process.env.CORS_ORIGIN||void 0;async function Se(){try{await F()}catch(s){e().logger.warn("server","secrets migration encountered an error",{error:String(s)})}let t=w()["static-api-key"],i=(()=>{try{return R()}catch{return"default"}})(),r=t??await J(`${i}:static-api-key`),n=!P&&!r;await Re();let a={clientId:process.env.VIBE_CLIENT_ID,clientSecret:process.env.VIBE_CLIENT_SECRET};await ai();let l=process.env.VIBE_CLIENT_ID,p=process.env.VIBE_CLIENT_SECRET,d=process.env.VIBE_GLOBAL_GATEWAY_URL,N=process.env.VIBE_WORKSPACE_GATEWAY_URL,M=process.env.VIBE_WORKSPACE_ID,x=!!l&&!!p&&!!d&&!!N&&!!M;e().logger.info("server","Starting VibeControls Agent...",{runtime:"bun",bunVersion:Bun.version,port:_,host:A,env:"production"});try{let s=w(),o=s["telemetry.enabled"]===!0||s["telemetry.enabled"]==="true";Z.init({persisted:o});let c=Date.now();Z.emit("agent.started",{version:process.env.npm_package_version??"unknown",profile:b,platform:process.platform}),process.__vibe_started_at=c}catch{}let h=Math.max(1,Number.parseInt(process.env.VIBECONTROLS_AGENT_BOOT_RETRIES??"10",10)||10),W=(s)=>{let o=String(s?.message??s).toLowerCase();return o.includes("syntax")||o.includes("cannot find module")||o.includes("module not found")||o.includes("typeerror")||o.includes("config schema")||o.includes("invalid config")||o.includes("corrupt")||o.includes("eaccess")||o.includes("eperm")},g=null,u=0;while(!g){u++;try{g=await br({port:_,host:A,dbPath:we,apiKey:P,logLevel:ve,corsOrigin:he}),await g.start();try{let s=await import("fs"),o=`${I()}/runtime.json`;s.writeFileSync(o,JSON.stringify({pid:process.pid,port:_,host:A,profile:b,startedAt:new Date().toISOString(),version:Ae()},null,2));let c=()=>{try{if(s.existsSync(o))s.unlinkSync(o)}catch{}};process.once("SIGTERM",c),process.once("SIGINT",c),process.once("exit",c)}catch(s){e().logger.warn("server","Could not write runtime.json",{error:String(s)})}}catch(s){let o=W(s);if(e().logger.error("server","Failed to start agent server",{attempt:u,maxBootAttempts:h,fatal:o,error:String(s)}),o||u>=h)console.error(`\u274C Failed to start VibeControls Agent (attempt ${u}/${h}, fatal=${o}):`,s),process.exit(1);let c=Math.min(30000,1000*2**Math.min(5,u-1)),m=Math.floor(Math.random()*500),S=c+m;console.warn(`\u26A0\uFE0F Agent boot attempt ${u}/${h} failed (transient), retrying in ${Math.round(S/1000)}s...`),await new Promise((k)=>setTimeout(k,S)),g=null}}let O=g.getServiceRegistry().getProvider("tunnel"),f=null;if(O?.getActiveTunnelUrl)for(let s=0;s<30;s++){if(f=await O.getActiveTunnelUrl(),f)break;await new Promise((o)=>setTimeout(o,1000))}if(!f){let{sanitizeEnvSuffix:s}=await import("./tunnel-bootstrap-m51w4d94.js"),{getVibecontrolsProfile:o}=await import("./path-utils-qgkdkp5j.js"),c=s(o());f=process.env[`AGENT_TUNNEL_URL_${c}`]??process.env.AGENT_TUNNEL_URL??null}let j=w(),q=P||K()||j["static-api-key"]||"",E=e().getBootState(),Y=E==="ready"?null:gi();if(E==="ready")zt();Ie({port:_,host:A,tunnelUrl:f,apiKey:q,revealApiKey:n||process.env.AGENT_PRINT_API_KEY==="1",state:E,pairingToken:Y});try{xr({profile:b})}catch(s){e().logger.warn("server","Could not start autoupdate",{error:String(s)})}let{existsSync:H,unlinkSync:Q}=await import("fs"),{tmpdir:te}=await import("os"),{join:re}=await import("path"),U=async(s)=>{e().logger.info("server",`Received ${s}, shutting down...`),di();try{let c=process.__vibe_started_at??Date.now();Z.emit("agent.stopped",{uptime_s:Math.round((Date.now()-c)/1000),reason:s}),await Z.flush(),Z.stop()}catch{}let o=g.getLifecycle();if(s==="SIGTERM"){let c=re(te(),`.boff-vibecontrols-kill-${process.pid}`);if(H(c)){try{Q(c)}catch{}if(e().logger.info("server","Kill-intent flag detected \u2014 full shutdown"),o)await o.kill();else await g.stop({reason:"shutdown"}),process.exit(0)}else if(e().logger.info("server","No kill flag \u2014 treating as hot-reload (soft stop)"),o)await o.softStop();else await g.stop({reason:"reload"})}else if(o)await o.kill();else await g.stop({reason:"shutdown"}),process.exit(0)};if(process.on("SIGINT",()=>U("SIGINT")),process.on("SIGTERM",()=>U("SIGTERM")),x){let s=(()=>{let o=process.env.VIBECONTROLS_FINALIZE_TIMEOUT_MS,c=o?Number.parseInt(o,10):NaN;return Number.isFinite(c)&&c>0?c:300000})();e().logger.info("server",`VIBE_* env vars detected \u2014 running inline finalize (timeout ${Math.round(s/1000)}s)`),(async()=>{let o={clientId:l,clientSecret:p,workspaceId:M,globalGatewayUrl:d,workspaceGatewayUrl:N};try{let c=await Promise.race([g.finalize(o),new Promise((m)=>setTimeout(()=>m({ok:!1,error:`inline finalize timed out after ${Math.round(s/1000)}s`}),s))]);if(!c.ok){e().logger.warn("server","Inline finalize failed \u2014 agent stays awaiting-config. Background retry worker will keep trying.",{error:c.error});let{startFinalizeRetryWorker:m}=await import("./finalize-retry-worker-c38km3mt.js"),{setFinalizeRetryHandle:S}=await import("./finalize-retry-handle-registry-z9mbbjmj.js"),k=m({trigger:async()=>g.finalize(await G(o,{pinned:a}))});S(k)}}catch(c){e().logger.error("server","Inline finalize threw",{error:String(c)})}})()}else e().logger.info("server","Agent is awaiting gateway credentials. Add it on the VibeControls platform using the tunnel URL and API key shown above.")}function Ie(t){let r=(d)=>("\u2551 "+d).padEnd(65)+"\u2551",n="\u2560"+"\u2550".repeat(64)+"\u2563",a="\u2554"+"\u2550".repeat(64)+"\u2557",l="\u255A"+"\u2550".repeat(64)+"\u255D",p=t.revealApiKey?t.apiKey:t.apiKey?`${t.apiKey.substring(0,8)}****${t.apiKey.substring(t.apiKey.length-4)}`:"(none)";if(console.log(""),console.log(a),console.log(r("VibeControls Agent")),console.log(n),console.log(r(`State: ${t.state}`)),console.log(r(`Agent URL: http://${t.host}:${t.port}`)),console.log(r(`API Key: ${p}`)),console.log(r(`Tunnel URL: ${t.tunnelUrl??"(none)"}`)),t.pairingToken)console.log(r(`Pairing: ${t.pairingToken}`)),console.log(r(" (send as x-pairing-token on bootstrap)"));if(console.log(n),console.log(r(`Health: http://localhost:${t.port}/health`)),console.log(r(`Status: http://localhost:${t.port}/api/agent/status`)),console.log(l),!t.revealApiKey)console.log(" (Set AGENT_PRINT_API_KEY=1 to print the API key in full.)");console.log("")}Se();
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Lt,lr,fe,W}from"./index-
|
|
2
|
+
import{Lt,lr,fe,W}from"./index-8jk4a62x.js";import"./index-7wm4bqx5.js";export{Lt as PluginConfirmationRequiredError,W as PluginManager,lr as getPluginPackageRoot,fe as validatePluginPackageName};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Mr}from"./index-
|
|
2
|
+
import{Mr}from"./index-q4fht6h2.js";import"./index-zcnfj1q4.js";import"./index-0rmmrrfh.js";import"./index-4kf3nr14.js";import"./index-dr6rsnpk.js";import"./index-twtvt4yt.js";import"./index-8jk4a62x.js";import"./index-wxb9dgwq.js";import"./index-cn4p1ks0.js";import"./index-qzwbctkv.js";import"./index-x4z055t8.js";import"./index-1t74r13z.js";import"./index-v77bb0rm.js";import"./index-12gb48hg.js";import"./index-sq5j8bjn.js";import"./index-damc6cvc.js";import"./index-j99tkngg.js";import"./index-7wm4bqx5.js";export{Mr as registerCoreCommands};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{hi}from"./index-
|
|
2
|
+
import{hi}from"./index-5tghd67e.js";import"./index-br9bakfm.js";import"./index-8jk4a62x.js";import"./index-p7fbnfwd.js";import"./index-qzwbctkv.js";import"./index-x4z055t8.js";import"./index-1t74r13z.js";import"./index-j99tkngg.js";import"./index-7wm4bqx5.js";export{hi as attachSecondaryProfile};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{or,Nr,rn,ar,lt}from"./index-
|
|
2
|
+
import{or,Nr,rn,ar,lt}from"./index-dr6rsnpk.js";import"./index-wxb9dgwq.js";import"./index-cn4p1ks0.js";import"./index-7wm4bqx5.js";export{lt as getBootstrapTunnelUrl,or as sanitizeEnvSuffix,Nr as startBootstrapTunnel,ar as stopBootstrapTunnel,rn as tryHandoverBootstrapTunnel};
|