@vibecontrols/agent 2026.1125.2 → 2026.1127.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent-config-xwvsmn6b.js +2 -0
- package/dist/{agent-ready-tracker-mewxehg9.js → agent-ready-tracker-7ebr09d9.js} +1 -1
- package/dist/app-4t875vbv.js +2 -0
- package/dist/autostart.cmd-mdyv35dn.js +2 -0
- package/dist/bootstrap-workspace-1pt0bwy6.js +2 -0
- package/dist/bootstrap.service-gehm65tt.js +2 -0
- package/dist/bridge-client-9ax1cvj6.js +2 -0
- package/dist/bridge-commands-xhzhghxt.js +2 -0
- package/dist/cli.js +2 -2
- package/dist/daemon-profile-fnhc7pcf.js +2 -0
- package/dist/{finalize-retry-worker-az74f2qv.js → finalize-retry-worker-c38km3mt.js} +1 -1
- package/dist/gateway-client-3zp6kkav.js +2 -0
- package/dist/{getMachineId-bsd-4w1wmcjv.js → getMachineId-bsd-qjqk66se.js} +1 -1
- package/dist/{getMachineId-darwin-kejwz8w5.js → getMachineId-darwin-tqhg8pqb.js} +1 -1
- package/dist/{getMachineId-linux-mpm53wat.js → getMachineId-linux-ygfapc26.js} +1 -1
- package/dist/{getMachineId-unsupported-54seyw5v.js → getMachineId-unsupported-87w3cred.js} +1 -1
- package/dist/{getMachineId-win-cva7ghz9.js → getMachineId-win-jrtkq63e.js} +1 -1
- package/dist/{index-0gmhd3hs.js → index-0rmmrrfh.js} +3 -3
- package/dist/{index-7s7ee1y9.js → index-0vbsve3v.js} +4 -4
- package/dist/{index-7f2k4g6q.js → index-12gb48hg.js} +4 -4
- package/dist/{index-4rasb3ph.js → index-12rehjp4.js} +9 -9
- package/dist/{index-7wben1jx.js → index-164mtd7z.js} +2 -2
- package/dist/index-1smr1csg.js +116 -0
- package/dist/{index-w0m3jm0s.js → index-1t74r13z.js} +2 -2
- package/dist/{index-9xrhb68w.js → index-31ssvzw8.js} +2 -2
- package/dist/{index-652f9scs.js → index-4kf3nr14.js} +2 -2
- package/dist/{index-qe3xpt41.js → index-5s4mtrqb.js} +2 -2
- package/dist/{index-jmx5awkj.js → index-62vfxd90.js} +2 -2
- package/dist/{index-5ccmrpb5.js → index-6b9vh0gq.js} +48 -48
- package/dist/{index-7gk1x74m.js → index-6nv5rdqh.js} +2 -2
- package/dist/{index-er5k6qtr.js → index-6wfd7cv3.js} +4 -4
- package/dist/{index-t6p4szqx.js → index-76vza24h.js} +3 -3
- package/dist/{index-76m37yd8.js → index-7bm1kptr.js} +3 -3
- package/dist/{index-0qjbnyg4.js → index-7wm4bqx5.js} +5 -5
- package/dist/{index-akk3rxnn.js → index-90gn0b6x.js} +3 -3
- package/dist/{index-2r6cmxxz.js → index-axkwyajz.js} +1 -1
- package/dist/index-bk17490n.js +3 -0
- package/dist/{index-2vcxt38h.js → index-bpzk441p.js} +2 -2
- package/dist/{index-4z1y39jt.js → index-cn4p1ks0.js} +2 -2
- package/dist/{index-byerrz46.js → index-damc6cvc.js} +2 -2
- package/dist/{index-xtd0j8ve.js → index-dgbe8jm8.js} +2 -2
- package/dist/index-dtxd2xmg.js +158 -0
- package/dist/index-e5jdx9c1.js +3 -0
- package/dist/{index-tahaxp6n.js → index-ednz6yz2.js} +2 -2
- package/dist/{index-hsrt2v87.js → index-f5nmxa9e.js} +1 -1
- package/dist/{index-thm1bzpj.js → index-j8j1h00a.js} +9 -9
- package/dist/{index-kwhx023z.js → index-j99tkngg.js} +10 -10
- package/dist/{index-fqz9n560.js → index-nz7mhjjn.js} +3 -3
- package/dist/index-p1b10hs1.js +11 -0
- package/dist/{index-qfxwk38p.js → index-p7fbnfwd.js} +2 -2
- package/dist/{index-jnxjjx2y.js → index-ppxayc0x.js} +2 -2
- package/dist/index-qzwbctkv.js +16 -0
- package/dist/{index-a0vx2zyx.js → index-rae5bn1c.js} +2 -2
- package/dist/{index-8rbhm4g8.js → index-rhn7wy1p.js} +2 -2
- package/dist/index-sd5bt3g5.js +2 -0
- package/dist/{index-vtsd74g0.js → index-sq5j8bjn.js} +6 -6
- package/dist/{index-t5cfkz1e.js → index-v77bb0rm.js} +3 -3
- package/dist/{index-v16qz1fa.js → index-vhz1c474.js} +2 -2
- package/dist/{index-ywnfz6nm.js → index-wxb9dgwq.js} +1 -1
- package/dist/index-x4z055t8.js +3 -0
- package/dist/{index-haww9jpq.js → index-xetd52ad.js} +2 -2
- package/dist/{index-d59kp6zr.js → index-yfk0pb00.js} +2 -2
- package/dist/{index-cy97asyh.js → index-zcnfj1q4.js} +3 -3
- package/dist/{index-c4whjk5r.js → index-zn9snqbg.js} +2 -2
- package/dist/index.js +3 -3
- package/dist/interactive-52x9hv6c.js +2 -0
- package/dist/key.cmd-y415ngam.js +2 -0
- package/dist/log-shipper-02rqvtq8.js +2 -0
- package/dist/{path-utils-r4df8d3w.js → path-utils-qgkdkp5j.js} +1 -1
- package/dist/plugin-system-7qjqrq7s.js +2 -0
- package/dist/prereqs-runner-w7z2dwa6.js +2 -0
- package/dist/profile-mount-ga5z1vx9.js +2 -0
- package/dist/prune-stale-shims-vejvb1rj.js +2 -0
- package/dist/register-core-vv5pddxj.js +2 -0
- package/dist/secondary-profile-attach-222s85md.js +2 -0
- package/dist/subprocess-p9bv9nqz.js +2 -0
- package/dist/telemetry-1d3t1mbf.js +2 -0
- package/dist/tunnel-bootstrap-20vwak7q.js +2 -0
- package/package.json +1 -1
- package/dist/agent-config-v9d7gcz0.js +0 -2
- package/dist/app-xc9c1d71.js +0 -2
- package/dist/autostart.cmd-ahet7b1t.js +0 -2
- package/dist/bootstrap-workspace-3pb8qjsh.js +0 -2
- package/dist/bootstrap.service-9m7m1ksa.js +0 -2
- package/dist/bridge-client-xvqy3n15.js +0 -2
- package/dist/daemon-profile-sg8fp50z.js +0 -2
- package/dist/gateway-client-ermpz52n.js +0 -2
- package/dist/index-5021rk8n.js +0 -3
- package/dist/index-b3v08awy.js +0 -3
- package/dist/index-mmx2kp76.js +0 -16
- package/dist/index-ss5gez2p.js +0 -2
- package/dist/index-tts92sdm.js +0 -5
- package/dist/index-x83tcr8f.js +0 -158
- package/dist/index-zcmhy3jv.js +0 -116
- package/dist/interactive-vbz68zh5.js +0 -2
- package/dist/key.cmd-f6rjvjy8.js +0 -2
- package/dist/log-shipper-0erbwn0q.js +0 -2
- package/dist/plugin-system-byzwda4c.js +0 -2
- package/dist/prereqs-runner-gca0bytz.js +0 -2
- package/dist/profile-mount-s4mc1x18.js +0 -2
- package/dist/prune-stale-shims-4nqtv0xt.js +0 -2
- package/dist/register-core-ws2axmcf.js +0 -2
- package/dist/secondary-profile-attach-em1tq7vq.js +0 -2
- package/dist/subprocess-4gg77skg.js +0 -2
- package/dist/telemetry-nmtywcba.js +0 -2
- package/dist/tunnel-bootstrap-tjwz90pb.js +0 -2
|
@@ -0,0 +1,116 @@
|
|
|
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(`
|
|
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
|
+
COMPREPLY=($(compgen -W "${O.subs.join(" ")}" -- "\${cur}"))
|
|
5
|
+
return 0
|
|
6
|
+
;;`).join(`
|
|
7
|
+
`),h=P.map((O)=>{let E=Io([O],O.name);if(E.length===0)return null;return` ${O.name})
|
|
8
|
+
COMPREPLY=($(compgen -W "${E.join(" ")}" -- "\${cur}"))
|
|
9
|
+
return 0
|
|
10
|
+
;;`}).filter(Boolean).join(`
|
|
11
|
+
`);return`# Bash completion for vibe CLI
|
|
12
|
+
# Generated by vibe completion bash
|
|
13
|
+
# Source this file or add to ~/.bashrc:
|
|
14
|
+
# eval "$(vibe completion bash)"
|
|
15
|
+
|
|
16
|
+
_vibe_completions() {
|
|
17
|
+
local cur prev words cword
|
|
18
|
+
_init_completion || return
|
|
19
|
+
|
|
20
|
+
local toplevel="${a.join(" ")}"
|
|
21
|
+
|
|
22
|
+
if [[ \${cword} -eq 1 ]]; then
|
|
23
|
+
COMPREPLY=($(compgen -W "\${toplevel}" -- "\${cur}"))
|
|
24
|
+
return 0
|
|
25
|
+
fi
|
|
26
|
+
|
|
27
|
+
local cmd="\${words[1]}"
|
|
28
|
+
|
|
29
|
+
if [[ "\${cur}" == -* ]]; then
|
|
30
|
+
case "\${cmd}" in
|
|
31
|
+
${h}
|
|
32
|
+
esac
|
|
33
|
+
return 0
|
|
34
|
+
fi
|
|
35
|
+
|
|
36
|
+
if [[ \${cword} -eq 2 ]]; then
|
|
37
|
+
case "\${cmd}" in
|
|
38
|
+
${r}
|
|
39
|
+
esac
|
|
40
|
+
fi
|
|
41
|
+
|
|
42
|
+
return 0
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
complete -F _vibe_completions vibe
|
|
46
|
+
`}function wn(P){let a=P.map((r)=>` '${r.name}:${mn(r.description||r.name)}'`).join(" \\\n"),t=P.filter((r)=>r.subcommands.length>0).map((r)=>{let h=r.subcommands.map((O)=>` '${O.name}:${mn(O.description||O.name)}'`).join(" \\\n");return` ${r.name})
|
|
47
|
+
local -a subcmds=(
|
|
48
|
+
${h}
|
|
49
|
+
)
|
|
50
|
+
_describe -t subcommands '${r.name} subcommand' subcmds
|
|
51
|
+
;;`}).join(`
|
|
52
|
+
`);return`#compdef vibe
|
|
53
|
+
# Zsh completion for vibe CLI
|
|
54
|
+
# Generated by vibe completion zsh
|
|
55
|
+
# Place in $fpath or: eval "$(vibe completion zsh)"
|
|
56
|
+
|
|
57
|
+
_vibe() {
|
|
58
|
+
local -a commands=(
|
|
59
|
+
${a}
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
_arguments -C \\
|
|
63
|
+
'1:command:->cmd' \\
|
|
64
|
+
'*::arg:->args'
|
|
65
|
+
|
|
66
|
+
case $state in
|
|
67
|
+
cmd)
|
|
68
|
+
_describe -t commands 'vibe command' commands
|
|
69
|
+
;;
|
|
70
|
+
args)
|
|
71
|
+
case $words[1] in
|
|
72
|
+
${t}
|
|
73
|
+
esac
|
|
74
|
+
;;
|
|
75
|
+
esac
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
_vibe "$@"
|
|
79
|
+
`}function mn(P){return P.replace(/'/g,"'\\''").replace(/:/g,"\\:")}function At(P){let a=["# Fish completion for vibe CLI","# Generated by vibe completion fish","# Save to ~/.config/fish/completions/vibe.fish","","complete -c vibe -f",""];for(let t of P)a.push(`complete -c vibe -n '__fish_use_subcommand' -a '${t.name}' -d '${fn(t.description||t.name)}'`);a.push("");for(let t of P){if(t.subcommands.length===0)continue;for(let r of t.subcommands)a.push(`complete -c vibe -n '__fish_seen_subcommand_from ${t.name}' -a '${r.name}' -d '${fn(r.description||r.name)}'`);a.push("")}return a.join(`
|
|
80
|
+
`)+`
|
|
81
|
+
`}function fn(P){return P.replace(/'/g,"\\'")}var rt="# >>> vibe completion >>>",bt="# <<< vibe completion <<<";function kn(){let P=process.env.SHELL||"";if(P.includes("zsh"))return"zsh";if(P.includes("fish"))return"fish";return"bash"}function vn(P,a){let t=a||kn();switch(t){case"bash":{let r=Sn(),h=`${rt}
|
|
82
|
+
eval "$(vibe completion bash)"
|
|
83
|
+
${bt}`;return gn(r,rt,h),{shell:t,path:r}}case"zsh":{let r=Fe(Ye(),".zshrc"),h=`${rt}
|
|
84
|
+
eval "$(vibe completion zsh)"
|
|
85
|
+
${bt}`;return gn(r,rt,h),{shell:t,path:r}}case"fish":{let r=Fe(process.env.XDG_CONFIG_HOME||Fe(Ye(),".config"),"fish","completions");if(!Be(r))$o(r,{recursive:!0});let h=Fe(r,"vibe.fish");return Rt(h,At(P),"utf8"),{shell:t,path:h}}}}function $n(P){let a=P||kn();switch(a){case"bash":{let t=Sn();return St(t),{shell:a,path:t}}case"zsh":{let t=Fe(Ye(),".zshrc");return St(t),{shell:a,path:t}}case"fish":{let t=Fe(process.env.XDG_CONFIG_HOME||Fe(Ye(),".config"),"fish","completions","vibe.fish");if(Be(t))So(t);return{shell:a,path:t}}}}function Sn(){let P=Fe(Ye(),".bashrc");if(Be(P))return P;let a=Fe(Ye(),".bash_profile");if(Be(a))return a;return P}function gn(P,a,t){let r="";if(Be(P))r=$t(P,"utf8");if(r.includes(a))St(P),r=Be(P)?$t(P,"utf8"):"";Rt(P,r+`
|
|
86
|
+
`+t+`
|
|
87
|
+
`,"utf8")}function St(P){if(!Be(P))return;let a=$t(P,"utf8"),t=a.indexOf(rt),r=a.indexOf(bt);if(t===-1||r===-1)return;Rt(P,a.substring(0,t)+a.substring(r+bt.length),"utf8")}function Cn(P){let a=P.command("completion").description("Generate shell completion scripts (bash, zsh, fish)");a.command("bash").description("Print Bash completion script").action(()=>{let t=Qe(P);process.stdout.write(yn(t))}),a.command("zsh").description("Print Zsh completion script").action(()=>{let t=Qe(P);process.stdout.write(wn(t))}),a.command("fish").description("Print Fish completion script").action(()=>{let t=Qe(P);process.stdout.write(At(t))}),a.command("install").description("Auto-install completions for your current shell").option("--shell <shell>","Force a specific shell (bash, zsh, fish). Auto-detects if omitted.").action((t)=>{try{let r=Qe(P),h=vn(r,t.shell);l(`Completions installed for ${h.shell}`),o(`Written to: ${h.path}`),o("Restart your shell or run:"),console.log(` source ${h.path}`),console.log()}catch(r){s(`Failed to install completions: ${r instanceof Error?A(r):r}`)}}),a.command("uninstall").description("Remove previously installed completions").option("--shell <shell>","Force a specific shell (bash, zsh, fish)").action((t)=>{try{let r=$n(t.shell);l(`Completions removed for ${r.shell}`),o(`Cleaned: ${r.path}`),console.log()}catch(r){s(`Failed to uninstall completions: ${r instanceof Error?A(r):r}`)}})}import{existsSync as Pn,readFileSync as Rn,writeFileSync as Oo}from"fs";import{join as An}from"path";var In=I();function On(P){P.command("export").description("Export plugin config and user preferences to a JSON file").option("--plugins","Export plugin registry only").option("--config","Export config file only").option("--state","Export plugin state from agent database").option("--all","Export everything (default)").option("--include-secrets","Include API keys and gateway secrets in the export",!1).option("-o, --output <path>","Output file path").option("--agent-url <url>","Agent URL","http://localhost:3005").option("--profile <name>","Target a specific profile by name").option("--json","Emit JSON manifest").action(async function(a){let t={...P.opts(),...a};try{if(!t.json)g("Export Agent Configuration");let r=a.all||!a.plugins&&!a.config&&!a.state,h=a.includeSecrets===!0;if(h&&!t.json)p("Export will include local secrets. Store the file securely."),c();let O={version:"1.0",exportedAt:new Date().toISOString()},E=0;if(r||a.plugins){let T=An(In,"plugins.json");if(Pn(T))try{O.plugins=JSON.parse(Rn(T,"utf-8")),E++,o(`Exported ${Array.isArray(O.plugins)?O.plugins.length:0} plugin(s)`)}catch{p("Could not read plugin registry")}else O.plugins=[],o("No plugin registry found (empty)")}if(r||a.config){let T=An(In,"config.json");if(Pn(T))try{let x=JSON.parse(Rn(T,"utf-8"));O.config=h?x:k(x),E++,o(`Exported ${Object.keys(O.config||{}).length} config key(s)`)}catch{p("Could not read config file")}else O.config={},o("No config file found (empty)")}if(r||a.state)try{let T=f(a),x=encodeURIComponent(m(t));try{let L=await S(T,`/api/profiles/${x}/config`);O.agentConfig=h?L:k(L),E++,o("Exported agent database config")}catch{p("Could not export agent config (agent may not be running)")}try{let L=await S(T,`/api/profiles/${x}/state`);O.pluginState=h?L:k(L),E++,o("Exported plugin state")}catch{p("Could not export plugin state (agent may not be running)")}}catch{p("Agent not reachable \u2014 skipping database exports")}if(E===0&&!O.plugins&&!O.config)s("Nothing to export.");let N=new Date().toISOString().replace(/[:.]/g,"-").replace("T","_").slice(0,19),j=a.output||`vibe-export-${N}.json`;if(Oo(j,JSON.stringify(O,null,2),{encoding:"utf-8",mode:384}),u(t,{ok:!0,file:j,sections:E,version:O.version,exportedAt:O.exportedAt}))return;c(),l(`Exported to ${i.bold(j)}`),n("Sections",String(E)),n("File",j),c()}catch(r){let h=r instanceof Error?A(r):String(r);if(t.json){u(t,{ok:!1,error:h});return}s(`Export failed: ${h}`)}})}import{existsSync as En,readFileSync as Nn,writeFileSync as Et,mkdirSync as Eo}from"fs";import{join as No}from"path";var jn=I(),jo=new Set(["static-api-key","agentRecordId","clientId","clientSecret","workspaceId","globalGatewayUrl","workspaceGatewayUrl","scopes","port","host","logLevel","corsOrigin","dbPath","storageAdapter","registry"]);function Do(P){let a={};for(let[t,r]of Object.entries(P)){if(!jo.has(t)||r===Mi)continue;if(typeof r==="string"||typeof r==="number"||Array.isArray(r))a[t]=r}return a}function Dn(P){P.command("import").description("Import plugin config and user preferences from a JSON file").argument("<file>","Path to the export JSON file").option("--install","Install plugins listed in the export",!1).option("--plugins","Import plugin registry only").option("--config","Import config file only").option("--merge","Merge with existing config instead of overwriting",!1).option("-y, --yes","Skip confirmation prompt").option("--json","Emit JSON").action(async function(a,t){let r={...P.opts(),...t},h=[];try{if(!r.json)g("Import Agent Configuration");if(!En(a))s(`File not found: ${a}`);let O;try{O=JSON.parse(Nn(a,"utf-8"))}catch{s("Invalid JSON file. Expected a file created by 'vibe export'.");return}if(!O.version)s("Invalid export file: missing version field. Expected a file created by 'vibe export'.");o(`Export file version: ${O.version}`),o(`Exported at: ${O.exportedAt||"unknown"}`),c();let E=!t.plugins&&!t.config;if(Eo(jn,{recursive:!0}),!t.yes){let N=[];if((E||t.plugins)&&O.plugins?.length)N.push(`${O.plugins.length} plugin(s)`);if((E||t.config)&&O.config)N.push(`${Object.keys(O.config).length} config key(s)`);if(N.length===0){o("Nothing to import from this file.");return}if(console.log(` ${d.warning} Will import: ${N.join(", ")}`),!t.merge)console.log(` ${i.dim("Mode: overwrite (use --merge to merge instead)")}`);if(c(),!await le(i.bold("Continue?"))){o("Import cancelled.");return}c()}if((E||t.plugins)&&O.plugins){h.push("plugins");let N=No(jn,"plugins.json");if(t.merge&&En(N))try{let j=JSON.parse(Nn(N,"utf-8")),T=new Map(j.map((x)=>[x.packageName,x]));for(let x of O.plugins)T.set(x.packageName,x);Et(N,JSON.stringify(Array.from(T.values()),null,2),{encoding:"utf-8",mode:384}),l(`Merged ${O.plugins.length} plugin(s) into registry`)}catch{Et(N,JSON.stringify(O.plugins,null,2),{encoding:"utf-8",mode:384}),l(`Wrote ${O.plugins.length} plugin(s) to registry`)}else Et(N,JSON.stringify(O.plugins,null,2),{encoding:"utf-8",mode:384}),l(`Wrote ${O.plugins.length} plugin(s) to registry`);if(t.install&&O.plugins.length>0){c(),o("Installing plugins...");let j=new W,T=0,x=0;for(let L of O.plugins)try{o(`Installing ${i.bold(L.packageName)}...`),await j.install(L.packageName),l(`Installed ${i.bold(L.packageName)}`),T++}catch(Z){p(`Failed to install ${L.packageName}: ${Z instanceof Error?A(Z):String(Z)}`),x++}if(c(),n("Installed",String(T)),x>0)n("Failed",String(x))}}if((E||t.config)&&O.config){let N=Do(O.config);if(Object.keys(N).length===0)p("No importable config keys found. Redacted secrets are skipped.");else if(M(N),h.push("config"),!r.json)l(`Imported ${Object.keys(N).length} config key(s)`)}if(u(r,{ok:!0,imported:h}))return;c(),l(`${i.bold("Import complete.")} Run ${i.bold("vibe start")} to apply changes.`),c()}catch(O){let E=O instanceof Error?A(O):String(O);if(r.json){u(r,{ok:!1,error:E});return}s(`Import failed: ${E}`)}})}import{existsSync as xn,mkdtempSync as xo,readFileSync as To,writeFileSync as Uo}from"fs";import{tmpdir as Lo}from"os";import{join as it}from"path";async function _o(P,a){try{return await S(P,`/api/profiles/${a}/agent/system`)}catch{return null}}async function Fo(P,a){try{return(await S(P,`/api/profiles/${a}/agent/version`)).version??null}catch{return null}}async function Mo(P){try{return await S(P,"/health/ready")}catch{return null}}function Jo(P,a){if(!xn(P))return[];try{let r=To(P,"utf8").split(`
|
|
88
|
+
`);return r.slice(Math.max(0,r.length-a))}catch{return[]}}function Go(){let P=/\bvibe\b|bun/i;try{if(process.platform==="win32")return Bun.spawnSync(["tasklist","/FO","CSV","/NH"],{stdout:"pipe",stderr:"ignore"}).stdout.toString().split(/\r?\n/).filter((r)=>P.test(r)).join(`
|
|
89
|
+
`);return Bun.spawnSync(["sh","-c","ps -o pid,ppid,cmd | grep -E 'vibe|bun' | grep -v grep"],{stdout:"pipe",stderr:"ignore"}).stdout.toString()}catch{return""}}function Bo(P){let a=[];return a.push({name:"Agent /health/ready",ok:P.health!==null,message:P.health!==null?"reachable":"not reachable",detail:P.health!==null?JSON.stringify(P.health,null,2):"Health endpoint did not respond."}),a.push({name:"Agent version",ok:P.agent.version!==null,message:P.agent.version??"(unknown)",detail:`Agent URL: ${P.agent.agentUrl}
|
|
90
|
+
Version: ${P.agent.version??"n/a"}`}),a.push({name:"System snapshot",ok:P.system!==null,message:P.system?`${P.system.platform??"?"} ${P.system.arch??""}`.trim():"unavailable",detail:P.system?JSON.stringify(P.system,null,2):"Could not query /api/agent/system."}),a.push({name:"Agent config",ok:Object.keys(P.config).length>0,message:`${Object.keys(P.config).length} key(s) (redacted)`,detail:JSON.stringify(P.config,null,2)}),a.push({name:"Log file",ok:P.logsTail.length>0,message:`${P.logFile} (${P.logsTail.length} lines)`,detail:P.logsTail.slice(-50).join(`
|
|
91
|
+
`)||"(empty)"}),a.push({name:"Related processes",ok:P.processes.split(`
|
|
92
|
+
`).filter(Boolean).length>0,message:`${P.processes.split(`
|
|
93
|
+
`).filter(Boolean).length} process(es)`,detail:P.processes||"(none found)"}),a}function Tn(P){P.command("diagnostics").alias("diag").description("Collect a redacted diagnostic dump for support").option("--agent-url <url>","Agent URL (default http://localhost:3005)","http://localhost:3005").option("--lines <n>","Tail this many log lines","1000").option("--out <path>","Write JSON dump to file").option("--json","Emit JSON to stdout").option("--plain","Force plain text output").action(async function(a){try{let t={...P.opts(),...a},r=f(t),h=encodeURIComponent(m(t)),O=Number.parseInt(t.lines??"1000",10)||1000;await y({mode:_(t),fetchData:async()=>{let[E,N,j]=await Promise.all([_o(r,h),Fo(r,h),Mo(r)]),T=w(),x=k(T),L=it(I(),"logs"),B=["default.log","agent.log"].map((X)=>it(L,X)).find((X)=>xn(X))??it(L,"default.log"),V=Jo(B,O),oe={timestamp:new Date().toISOString(),agent:{version:N,agentUrl:r},system:E,health:j,config:x,processes:Go(),logFile:B,logsTail:V},K=Bo(oe);return{dump:oe,probes:K}},plain:(E)=>{g("VibeControls Agent Diagnostics"),c(),o("Collecting agent state\u2026");let N=t.out?t.out:it(xo(it(Lo(),"vibe-diag-")),`vibe-diagnostics-${Date.now()}.json`);Uo(N,JSON.stringify(E.dump,null,2),"utf8"),n("Wrote",i.bold(N)),n("Log lines",String(E.dump.logsTail.length)),n("Processes",String(E.dump.processes.split(`
|
|
94
|
+
`).filter(Boolean).length)),c(),l("Diagnostics complete. Attach the JSON to your support ticket.")},interactive:async(E)=>{let N=E.probes.map((T,x)=>({id:`${x}-${T.name}`,label:T.name,hint:T.ok?"ok":"fail",detail:[`${T.ok?i.green("\u2714 ok"):i.red("\u2718 fail")} ${i.bold(T.name)}`,"",T.message,...T.detail?["",T.detail]:[]].join(`
|
|
95
|
+
`)})),j=E.probes.filter((T)=>T.ok).length;await Q({title:`Vibe Diagnostics \u2014 ${j}/${E.probes.length} ok`,rows:N,footer:"\u2191/\u2193 navigate \xB7 q to quit"})},json:(E)=>({checks:E.probes.map((N)=>({name:N.name,ok:N.ok,message:N.message})),dump:E.dump})})}catch(t){s(`Diagnostics failed: ${t instanceof Error?A(t):String(t)}`)}})}import{existsSync as tt,readFileSync as zo,readdirSync as Yo,renameSync as Zo,rmSync as Tt,statSync as Xo,writeFileSync as Qo}from"fs";import{join as Pe}from"path";import{existsSync as qe,readdirSync as Vo,rmSync as Ko,statSync as qo}from"fs";import{dirname as yt,join as je}from"path";var Ve="@vibecontrols";function Wo(){let a=b().npmGlobalBin();if(!a)return null;let t=je(yt(a),"lib","node_modules");if(qe(t))return t;let r=je(yt(a),"node_modules");if(qe(r))return r;let h=je(yt(a),"..","node_modules");if(qe(h))return h;return null}function Ho(){let P=b(),a=P.bunGlobalBin();if(a){let t=je(yt(a),"node_modules");if(qe(t))return t;let r=je(P.homeDir,".bun","install","global","node_modules");if(qe(r))return r}return null}function Un(P){let a=je(P,Ve);if(!qe(a))return[];try{return Vo(a).filter((t)=>{if(t.startsWith("."))return!1;try{return qo(je(a,t)).isDirectory()}catch{return!1}})}catch{return[]}}function Ln(){let P=[],a=Ho();if(a)for(let r of Un(a))P.push({packageName:`${Ve}/${r}`,root:"bun",rootDir:je(a,Ve)});let t=Wo();if(t)for(let r of Un(t))P.push({packageName:`${Ve}/${r}`,root:"npm",rootDir:je(t,Ve)});return P}function _n(P,a){if(a.dryRun)return{packageName:P.packageName,root:P.root,ok:!0,via:"skip"};let t=b();if(P.root==="bun"){let h=t.platform==="win32"?"bun.exe":"bun";try{if(Bun.spawnSync([h,"remove","-g",P.packageName],{timeout:60000,stdout:"pipe",stderr:"pipe"}).exitCode===0)return{packageName:P.packageName,root:P.root,ok:!0,via:"bun"}}catch{}}else{let h=t.platform==="win32"?"npm.cmd":"npm";try{if(Bun.spawnSync([h,"uninstall","-g",P.packageName],{timeout:120000,stdout:"pipe",stderr:"pipe"}).exitCode===0)return{packageName:P.packageName,root:P.root,ok:!0,via:"npm"}}catch{}}let r=je(P.rootDir,P.packageName.slice(Ve.length+1));try{if(qe(r))Ko(r,{recursive:!0,force:!0});return{packageName:P.packageName,root:P.root,ok:!0,via:"rm"}}catch(h){return{packageName:P.packageName,root:P.root,ok:!1,via:"rm",error:h instanceof Error?h.message:String(h)}}}var xt=`${Ve}/agent`;function Fn(P){return P===xt}var er=new Set(["db","plugins-registry","logs","binaries","subprocs"]);function tr(P){let a=new Set,t=[];if(!P)return{keep:a,unknown:t};for(let r of P.split(",").map((h)=>h.trim()).filter(Boolean))if(er.has(r))a.add(r);else t.push(r);return{keep:a,unknown:t}}var or=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;function rr(P,a){if(!or.test(a))return!1;let t=Pe(P,a);try{return Xo(t).isDirectory()}catch{return!1}}function ir(){let P=ne();if(!tt(P))return[];return Yo(P).filter((a)=>rr(P,a)).map((a)=>({profile:a,agentDir:Pe(P,a)}))}function ar(){let P=process.env.VIBECONTROLS_PROFILE||"default";return{profile:P,agentDir:Pe(ne(),P)}}function lr(P){if(!P)return[];return P.split(",").map((a)=>a.trim()).filter(Boolean)}function cr(P){let a=[],t=[],r=[];for(let h of P){let O=Ur(h);if(!O){t.push(h);continue}let E={packageName:O.packageName,pluginName:O.pluginName,isCore:!!O.isCore,raw:h};if(E.isCore)r.push(E);else a.push(E)}return{resolved:a,unknown:t,bundled:r}}async function dr(){let P=await import("./subprocess-p9bv9nqz.js");return P.killAllTracked()}function ur(P,a){let t=te(P);if(!t||typeof t.pid!=="number"||t.pid<=0)return{killed:0,skipped:0};let r=b();if(!r.isProcessAlive(t.pid)){if(!a)re(P);return{killed:0,skipped:1}}if(a)return o(` would kill tunnel pid ${t.pid} (${t.provider}) from ${i.dim(P)}`),{killed:1,skipped:0};let h=r.killProcessTree(t.pid,"SIGTERM");if(h&&r.isProcessAlive(t.pid))r.killProcessTree(t.pid,"SIGKILL");return re(P),{killed:h?1:0,skipped:h?0:1}}function Mn(){return Pe(b().homeDir,".bun","install","global")}function Jn(P,a){let t=Mn(),r=Pe(t,"package.json"),h=Pe(t,"bun.lock");if(!tt(r))return{droppedCount:0,manifestPath:r,lockPath:h};let O=typeof P==="function"?P:(Z)=>Z===P,E;try{E=zo(r,"utf8")}catch{return{droppedCount:0,manifestPath:r,lockPath:h}}let N;try{N=JSON.parse(E)}catch{return{droppedCount:0,manifestPath:r,lockPath:h}}if(!N.dependencies||typeof N.dependencies!=="object")return{droppedCount:0,manifestPath:r,lockPath:h};let j=Object.keys(N.dependencies),T={};for(let Z of j)if(!O(Z))T[Z]=N.dependencies[Z];let x=j.length-Object.keys(T).length;if(x===0)return{droppedCount:0,manifestPath:r,lockPath:h};if(a)return o(` would drop ${x} dep(s) from ${i.dim(r)} and remove ${i.dim(h)}`),{droppedCount:x,manifestPath:r,lockPath:h};N.dependencies=T;let L=`${r}.${process.pid}.tmp`;if(Qo(L,`${JSON.stringify(N,null,2)}
|
|
96
|
+
`,{encoding:"utf8"}),Zo(L,r),tt(h))try{Tt(h,{force:!0})}catch{}return{droppedCount:x,manifestPath:r,lockPath:h}}async function Ge(P,a){if(!tt(P))return;if(a){o(` would remove ${i.dim(P)}`);return}try{Tt(P,{recursive:!0,force:!0})}catch(t){p(`Failed to remove ${P}: ${t instanceof Error?A(t):String(t)}`)}}async function pr(P,a,t){if(a)return o(` would uninstall plugin ${i.bold(P)}`),!0;if(t)try{if((await fetch(`${t}/api/plugins/remove`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({packageName:P})})).ok)return!0}catch{}try{let O=b(),E=O.which("bun")??`bun${O.executableSuffix}`;if(Bun.spawnSync([E,"remove","-g",P],{timeout:60000,stdout:"pipe",stderr:"pipe"}).exitCode===0)return!0}catch{}let r=Pe(Mn(),"node_modules",P),h=!1;try{if(tt(r))Tt(r,{recursive:!0,force:!0}),h=!0}catch{}Jn(P,!1);try{let{pruneStaleBunBinShims:O}=await import("./prune-stale-shims-vejvb1rj.js");O()}catch{}return h||!0}async function mr(P,a){try{let t=await fetch(`${P}/api/plugins/prereqs/uninstall`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({packageName:a})});if(!t.ok)return{ok:!1,pendingSudo:[]};let r=await t.json();return{ok:!!r.ok,pendingSudo:r.pendingSudo??[]}}catch{return{ok:!1,pendingSudo:[]}}}async function fr(P,a,t){try{let r=await fetch(`${P}/api/plugins/nuke`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(a?{packageName:a,dryRun:t}:{dryRun:t})});if(!r.ok)return[];let h=await r.json(),O=[];for(let E of h.results??[]){if(E.error){O.push(`${E.plugin} (failed: ${E.error})`);continue}for(let N of E.reaped??[])O.push(`${E.plugin}: ${N}`)}return O}catch{return[]}}async function gr(P,a){g(`Nuking agent: ${P.profile}`),n("Path",P.agentDir);let t=null;try{let h=(await a.serviceManager.listInstances()).find((O)=>O.name===P.profile);if(h?.status==="running"){if(t=`http://localhost:${h.config?.port??3005}`,(!a.keep.has("binaries")||!a.keep.has("subprocs"))&&(a.nukeAllPlugins||a.removePlugins.length>0)){let N=a.nukeAllPlugins?[void 0]:a.removePlugins.map((j)=>j.packageName);for(let j of N){let T=await fr(t,j,a.dryRun);for(let x of T)if(a.dryRun)o(` would nuke \u2192 ${x}`);else l(`Plugin nuke \u2192 ${x}`)}}if(a.dryRun)o(` would stop running agent ${i.bold(P.profile)}`);else try{await a.serviceManager.stop(P.profile),l(`Stopped ${i.bold(P.profile)}`)}catch(N){p(`Failed to stop ${P.profile}: ${N}`)}}}catch{}if(!a.dryRun&&!a.keep.has("subprocs"))try{let{reaped:h}=await dr();if(h>0)l(`Reaped ${h} tracked subprocess(es)`)}catch{}else if(a.keep.has("subprocs"))o(" keeping tracked subprocesses (--keep includes subprocs)");if(!a.keep.has("subprocs"))try{let{killed:h}=ur(P.agentDir,a.dryRun);if(h>0&&!a.dryRun)l(`Killed persisted tunnel subprocess for ${P.profile}`)}catch(h){p(`Failed to kill tunnel for ${P.profile}: ${h instanceof Error?A(h):String(h)}`)}let r=[];if(!a.keep.has("binaries")){let h=Si(P.agentDir),O=new Map;for(let E of h){let N=O.get(E.pluginPackageName)??[];N.push(E),O.set(E.pluginPackageName,N)}if(O.size===0)o(" no agent-installed prerequisites tracked");else if(!t)p(` agent not running \u2014 cannot call prereqs/uninstall on ${O.size} plugin(s); rerun with the agent up to clean binaries`);else for(let[E,N]of O){if(a.dryRun){o(` would call prereqs/uninstall on ${i.bold(E)} (${N.length} item(s))`);continue}let j=await mr(t,E);if(j.ok)l(`Uninstalled prereqs for ${E}`);else p(`Plugin ${E} did not implement prereqs/uninstall`);for(let T of j.pendingSudo)r.push(T)}}else o(" keeping installed binaries (--keep includes binaries)");for(let h of a.removePlugins)if(await pr(h.packageName,a.dryRun,t))l(`Removed plugin ${h.packageName}`);else p(`Failed to remove plugin ${h.packageName}`);if(a.nukeAllPlugins||!a.keep.has("plugins-registry"))await Ge(Pe(P.agentDir,"agent-plugins"),a.dryRun);else o(" keeping local agent-plugins store (--keep includes plugins-registry)");if(!a.keep.has("db"))await Ge(Pe(P.agentDir,"agent-db"),a.dryRun);else o(" keeping encrypted DB (--keep includes db)");if(!a.keep.has("plugins-registry"))await Ge(Pe(P.agentDir,"plugins.json"),a.dryRun),await Ge(Pe(P.agentDir,"prereqs-installed.json"),a.dryRun);else o(" keeping plugins.json + prereqs-installed.json (--keep includes plugins-registry)");if(!a.keep.has("logs"))await Ge(Pe(P.agentDir,"logs"),a.dryRun);else o(" keeping log files (--keep includes logs)");if(a.removeConfig)await Ge(Pe(P.agentDir,"config.json"),a.dryRun),l(`Removed config.json for ${P.profile}`);return{pendingSudo:r}}function Gn(P){P.command("nuke").description("Cleanly remove agent state, tracked binaries, and (optionally) plugins/config across one or all agents.").option("--remove-plugins <csv>","Comma-separated plugin names (short or full) to uninstall").option("--remove-config","Also delete config.json").option("--all","Apply to every agent under .boff/vibecontrols/agents/ and wipe all external provider plugins").option("--keep <csv>","Comma-separated list of things to preserve. Valid: db, plugins-registry, logs, binaries, subprocs").option("--dry-run","Print what would happen without doing it").option("-y, --yes","Skip the confirmation prompt").option("--json","Emit JSON").action(async function(a){let t={...P.opts(),...a};try{let r=a.all?ir():[ar()].filter((V)=>tt(V.agentDir));if(r.length===0){o("Nothing to nuke \u2014 no agent state directories found.");return}let h=lr(a.removePlugins),{resolved:O,unknown:E,bundled:N}=cr(h);if(E.length>0){s(`Unknown plugin(s): ${E.join(", ")} \u2014 try the full @vibecontrols/* package name`);return}if(N.length>0)for(let V of N)p(`Skipping ${i.bold(V.packageName)}: bundled with the agent (uninstall the agent itself with \`npm uninstall -g @vibecontrols/agent\`)`);let{keep:j,unknown:T}=tr(a.keep);if(T.length>0){s(`Unknown --keep value(s): ${T.join(", ")} \u2014 valid: db, plugins-registry, logs, binaries, subprocs`);return}if(g(a.dryRun?"Dry-run nuke":"Nuke"),o(`Agents: ${r.map((V)=>V.profile).join(", ")}`),o(`Plugins: ${O.map((V)=>V.packageName).join(", ")||"(none)"}`),o(`Remove config: ${a.removeConfig?"yes":"no"}`),o(`Keep: ${j.size>0?[...j].sort().join(", "):"(nothing)"}`),o(`Wipe bun-global @vibecontrols/*: ${a.all?"yes":"no"}`),c(),!a.yes&&!a.dryRun){if(!await le(i.bold("This will permanently delete the listed state. Continue?"))){o("Cancelled.");return}c()}let x=new D,L=[];for(let V of r){let{pendingSudo:oe}=await gr(V,{serviceManager:x,removePlugins:O,nukeAllPlugins:!!a.all,removeConfig:!!a.removeConfig,keep:j,dryRun:!!a.dryRun});for(let K of oe)L.push(K);c()}let Z=[],B=null;if(a.all){try{if(a.dryRun){let X=await Wr();B=X,o(` would clear ${X.count} secret(s) from ${X.backend}`)}else{let X=await Wr(),se=!0;if(X.count>0&&!a.yes)se=await le(i.bold(`About to remove ${X.count} secret(s) from ${X.backend}. Continue?`));if(se)if(B=await $i(),B.count>0)l(`Cleared ${B.count} secret(s) from ${B.backend}`);else o(" no secrets to clear");else o(" skipped clearing secrets (user declined)"),B={count:0,backend:"none",names:[]}}}catch(X){p(`Failed to clear secrets: ${X instanceof Error?A(X):String(X)}`)}let V=Ln().filter((X)=>!Fn(X.packageName));if(V.length===0)o(" no @vibecontrols/* packages found in bun-global / npm-global");else{o(` found ${V.length} @vibecontrols/* package(s) in global roots`);for(let X of V){let se=_n(X,{dryRun:!!a.dryRun});if(Z.push(se),a.dryRun)o(` would uninstall ${i.bold(X.packageName)} (${X.root}-global)`);else if(se.ok)l(`Removed ${X.packageName} (${X.root}-global, via ${se.via})`);else p(`Failed to remove ${X.packageName} (${X.root}-global): ${se.error??"unknown"}`)}}let{droppedCount:oe,manifestPath:K}=Jn((X)=>X.startsWith("@vibecontrols/")&&X!==xt,!!a.dryRun);if(oe>0&&!a.dryRun)l(`Dropped ${oe} @vibecontrols/* dep(s) from ${K}`);await Ge(Pe(C(),"agents.json"),!!a.dryRun),await Ge(Pe(C(),".consent.json"),!!a.dryRun)}if(L.length>0){c(),p(`${L.length} command(s) require sudo to fully uninstall:`);for(let V of L)n(` ${V.name}`,V.command)}if(u(t,{ok:!0,deleted:r.map((V)=>V.profile),removedGlobalPackages:Z,clearedSecrets:B,dryRun:!!a.dryRun}))return;if(a.all&&Z.length>0&&!a.dryRun){let V=Z.filter((oe)=>oe.ok).length;c(),o(`${d.info} Uninstalled ${V}/${Z.length} global @vibecontrols/* package(s)`)}if(c(),l(a.dryRun?"Dry-run complete.":"Nuke complete."),a.all&&!a.dryRun)o(`${d.info} To remove the agent itself: ${i.bold("npm uninstall -g @vibecontrols/agent")} (or ${i.bold("bun remove -g @vibecontrols/agent")})`)}catch(r){let h=r instanceof Error?A(r):String(r);if(t.json){u(t,{ok:!1,error:h});return}s(h)}})}import{existsSync as hr}from"fs";import{platform as br}from"os";var wr="http://localhost:3005";function Bn(P){if(P==="pass")return i.green("\u2714 pass");if(P==="warn")return i.yellow("\u26A0 warn");return i.red("\u2718 fail")}async function kr(P){try{return await S(P,"/health"),{name:"Agent HTTP reachable",grade:"pass",message:P}}catch(a){return{name:"Agent HTTP reachable",grade:"fail",message:A(a),hint:"Run `vibe start` (or check `vibe status` if it should already be running)."}}}async function vr(){try{let P="default";try{P=R()}catch{}let a=await J(`${P}:static-api-key`),t=w();if(!Boolean(a||t["static-api-key"]||process.env.AGENT_API_KEY))return{name:"Agent config / API key",grade:"warn",message:"No persistent API key set; agent will mint a fresh one each restart.",hint:"Run `vibe config --set static-api-key=true` to persist."};return{name:"Agent config / API key",grade:"pass",message:"config.json present, API key persisted"}}catch(P){return{name:"Agent config / API key",grade:"fail",message:A(P)}}}function $r(){let P=I();if(!hr(P))return{name:"Agent working directory",grade:"warn",message:`${P} does not exist (will be created on first start)`};return{name:"Agent working directory",grade:"pass",message:P}}async function Cr(P,a){try{if((await S(P,`/api/profiles/${a}/agent/gateway-auth`))?.configured)return{name:"Gateway OAuth",grade:"pass",message:"configured"};return{name:"Gateway OAuth",grade:"warn",message:"not configured \u2014 agent works locally but won't sync with platform",hint:"Add the agent on the VibeControls platform and paste the credentials."}}catch{return{name:"Gateway OAuth",grade:"warn",message:"could not query agent for gateway-auth state"}}}async function Rr(P,a){try{let t=await S(P,`/api/profiles/${a}/plugins`),r=t?.plugins??t??[],h=r.filter((O)=>O.status==="error"||O.status==="failed");if(h.length>0)return{name:"Plugin registry",grade:"fail",message:`${h.length} plugin(s) failed to load`,hint:h.map((O)=>O.name??O.packageName).join(", ")};return{name:"Plugin registry",grade:"pass",message:`${r.length} plugin(s) loaded cleanly`}}catch{return{name:"Plugin registry",grade:"warn",message:"could not query agent for plugin list"}}}function Ir(){let P=br();if(!["linux","darwin","win32"].includes(P))return{name:"OS runtime",grade:"warn",message:`${P} is not officially supported (linux, darwin, win32)`};let t=typeof Bun<"u"?Bun.version:null;if(!t)return{name:"OS runtime",grade:"warn",message:`${P} / no Bun runtime detected`};return{name:"OS runtime",grade:"pass",message:`${P} / Bun ${t}`}}function Vn(P){P.command("doctor").description("Run a graded health check across the agent's subsystems").option("--agent-url <url>","Agent URL",wr).option("--profile <name>","Target a specific profile by name").option("--json","Emit machine-readable JSON instead of grading text").option("--plain","Force plain text output").action(async function(a){let t={...P.opts(),...a},r=f(t),h=encodeURIComponent(m(t)),O=[];if(await y({mode:_(t),fetchData:async()=>{let E=[];E.push(Ir()),E.push($r()),E.push(await vr()),E.push(await kr(r)),E.push(await Cr(r,h)),E.push(await Rr(r,h));let N=Nt();for(let j of N.getDoctorChecks())try{let T=await j.run();for(let x of T){let L=x.ok?"pass":x.grade??"fail";E.push({name:x.name,grade:L,message:x.message,hint:x.hint})}}catch(T){E.push({name:`${j.source}: doctor contributor`,grade:"warn",message:`contributor threw: ${T.message}`})}return O=E,E},plain:(E)=>{g("Vibe Doctor"),c();for(let x of E)if(console.log(`${Bn(x.grade)} ${i.bold(x.name)}`),console.log(` ${x.message}`),x.hint)console.log(` ${i.dim("\u2192 "+x.hint)}`);c();let N=E.filter((x)=>x.grade==="fail").length,j=E.filter((x)=>x.grade==="warn").length,T=E.filter((x)=>x.grade==="pass").length;if(o(`${T} pass, ${j} warn, ${N} fail`),N>0)s("Doctor found problems. See hints above."),process.exitCode=1;else if(j>0)o("Doctor finished with warnings.");else l("All checks pass.")},interactive:async(E)=>{let N=E.map((L,Z)=>{let B=[`${Bn(L.grade)} ${i.bold(L.name)}`,"",L.message];if(L.hint)B.push(""),B.push(i.dim("\u2192 "+L.hint));return{id:`${Z}-${L.name}`,label:L.name,hint:L.grade==="pass"?"ok":L.grade,detail:B.join(`
|
|
97
|
+
`)}}),j=E.filter((L)=>L.grade==="fail").length,T=E.filter((L)=>L.grade==="warn").length,x=E.filter((L)=>L.grade==="pass").length;if(await Q({title:`Vibe Doctor \u2014 ${x} pass, ${T} warn, ${j} fail`,rows:N,footer:"\u2191/\u2193 navigate \xB7 q to quit"}),j>0)process.exitCode=1},json:(E)=>({checks:E.map((N)=>({name:N.name,ok:N.grade==="pass",grade:N.grade,message:N.message,hint:N.hint??null}))})}),O.some((E)=>E.grade==="fail"))process.exitCode=1})}var Or="http://localhost:3005",Ut=new Set(["debug","info","warn","error","silent"]);function Kn(P){P.command("log-level [level]").description("Show or update the running agent's log level").option("--agent-url <url>","Agent URL",Or).option("--profile <name>","Target a specific profile by name").option("--json","Emit JSON").option("--plain","Force plain text output").action(async function(a,t){try{let r={...P.opts(),...t},h=f(r),O=encodeURIComponent(m(r));if(!a){await y({mode:_(r),fetchData:async()=>({level:(await S(h,`/api/profiles/${O}/agent/log-level`))?.level??"(unknown)"}),plain:(N)=>{g("Agent Log Level"),n("Current",N.level)},interactive:async(N)=>{await U({title:"Agent Log Level",body:`Current: ${N.level}`,footer:"press q to exit"})}});return}let E=a.toLowerCase();if(!Ut.has(E)){if(!u(r,{ok:!1,error:`Invalid log level: ${a}`,valid:[...Ut]}))s(`Invalid log level: ${a}. Use one of: ${[...Ut].join(", ")}`);return}if(await q(h,`/api/profiles/${O}/agent/log-level`,{level:E}),u(r,{ok:!0,level:E}))return;l(`Log level set to ${E}`)}catch(r){if(u({json:!!t.json},{ok:!1,error:A(r)}))return;s(A(r))}})}import{existsSync as qn,readdirSync as Wn,statSync as Hn,unlinkSync as Nr}from"fs";import{join as Lt}from"path";function jr(){let P=ne();if(!qn(P))return[];return Wn(P).map((a)=>Lt(P,a)).filter((a)=>Hn(a).isDirectory())}function xr(P,a,t){let r=Lt(P,"logs");if(!qn(r))return{count:0,bytes:0};let h=Date.now()-a*86400000,O=0,E=0;for(let N of Wn(r)){let j=Lt(r,N),T=Hn(j);if(!T.isFile())continue;if(T.mtimeMs>h)continue;if(O+=1,E+=T.size,!t)try{Nr(j)}catch{}}return{count:O,bytes:E}}function Tr(P,a){let t=te(P);if(!t)return 0;if(ae(t.pid))return 0;if(!a)re(P);return 1}function zn(P){P.command("gc").description("Garbage-collect stale agent state (tunnel files, old logs)").option("--keep-days <n>","Keep log files newer than N days","14").option("--dry-run","Show what would be removed without changing anything",!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};if(!a.dryRun&&!await jt(t,"Remove stale agent state now?")){o("Aborted.");return}try{let r=Number(a.keepDays);if(!Number.isFinite(r)||r<0){if(t.json){u(t,{ok:!1,error:`Invalid --keep-days: ${a.keepDays}`});return}s(`Invalid --keep-days: ${a.keepDays}`);return}let h=Boolean(a.dryRun);if(!t.json)g(h?"vibe gc (dry-run)":"vibe gc"),c();let O={staleTunnelStates:0,oldLogFiles:0,bytesFreed:0},E=[];for(let N of jr()){let j=Tr(N,h);O.staleTunnelStates+=j;let T=xr(N,r,h);if(O.oldLogFiles+=T.count,O.bytesFreed+=T.bytes,j>0||T.count>0)E.push(N)}if(u(t,{ok:!0,removed:E,staleTunnelStates:O.staleTunnelStates,oldLogFiles:O.oldLogFiles,freedBytes:O.bytesFreed,dryRun:h}))return;if(n("Stale tunnel state files",String(O.staleTunnelStates)),n("Old log files",String(O.oldLogFiles)),n("Bytes freed",`${(O.bytesFreed/1048576).toFixed(2)} MiB`),c(),h)o(i.dim("dry-run: no files were removed"));else l("gc complete")}catch(r){if(t.json){u(t,{ok:!1,error:A(r)});return}s(A(r))}})}async function wt(P,a,t,r){o(`\u2192 ${t}`);let h=await P.run(a,{timeoutMs:r});if(h.code!==0)throw p(h.stderr.slice(0,600)),Error(`${t} failed (exit ${h.code})`);return h.stdout}function Yn(P){P.command("deploy <target>").description("Install + auto-configure the VibeControls agent on a remote target (defaults to SSH)").option("--version <version>","Pin a specific agent version (default: latest)").option("--registry <url>","npm registry (default: https://registry.npmjs.org/)").option("-i, --identity-file <path>","SSH identity file (override ssh_config)").option("--label <label>","Friendly name to record this peer under (default: target host)").option("--permissions <list>","Permissions to grant ourselves on the new peer (comma-separated)","tunnel:read,session:list,plugin:list,diagnostics:read").option("--expires-in <duration>","TTL for the minted peer key (default: no expiry)").option("--install-plugins <list>","Comma-separated plugin packages to also install on the remote agent").option("--autostart","Run `vibe autostart install` on the remote agent",!1).option("--no-bun","Skip Bun runtime install on the remote (default: best-effort)").option("--confirm","Required to proceed (no destructive ops; this is a sanity gate)").option("--json","Emit JSON").action(async function(a,t){let r={...P.opts(),...t};try{if(!t.confirm){s("Pass --confirm to proceed. `vibe deploy` runs npm install on the remote host.");return}let h=et(a,{identityFile:t.identityFile}),O=dt(t.version??"latest"),E=ht(t.registry??"https://registry.npmjs.org/"),N=t.installPlugins?t.installPlugins.split(",").map((se)=>se.trim()).filter(Boolean).map((se)=>ft(se)):[],j=mt(t.label??h.id),T=Lr(t.permissions??"tunnel:read"),x=t.expiresIn?pt(t.expiresIn):void 0;g(`vibe deploy \u2192 ${h.id}`),c(),o("Probing remote host\u2026");let L=await h.probe();if(n("Remote OS",L.os??"(unknown)"),n("Remote arch",L.arch??"(unknown)"),L.npm)n("Remote npm",L.npm);if(L.bun)n("Remote bun",L.bun);if(L.vibe)n("Remote vibe (existing)",L.vibe);if(c(),!L.bun){if(t.bun===!1){s("Bun is required to run the agent but is not installed and --no-bun was passed. Install Bun manually, then re-run.");return}o("Installing Bun on remote\u2026");let se=await h.run(["sh","-c",`curl -fsSL https://bun.sh/install | bash && echo 'export PATH="$HOME/.bun/bin:$PATH"' >> ~/.bashrc`],{timeoutMs:300000});if(se.code!==0){p(se.stderr.slice(0,500)),s("Bun auto-install failed. Install Bun manually, then re-run.");return}let Ie=await h.run(["sh","-c","$HOME/.bun/bin/bun --version 2>/dev/null"],{timeoutMs:1e4});if(Ie.code===0&&Ie.stdout.trim())L.bun="$HOME/.bun/bin/bun",n("Remote bun (installed)",Ie.stdout.trim());else{s("Bun installer ran but the binary isn't reachable. Manual investigation needed.");return}}await wt(h,Pt(E,O),`Installing @vibecontrols/agent@${O} via bun`,600000);let Z='export PATH="$HOME/.bun/bin:$PATH"; ',B=await wt(h,["sh","-c",`${Z}vibe --version`],"Verifying remote vibe binary",15000);if(n("Remote agent version",B.trim()),t.autostart)await wt(h,["sh","-c",`${Z}vibe autostart install`],"Installing autostart unit",60000);for(let se of N)await wt(h,Mt(se),`Installing plugin ${se}`,300000);o("Starting remote agent in daemon mode\u2026"),await h.run(["sh","-c",`${Z}vibe start`],{timeoutMs:60000}),o("Waiting for remote tunnel\u2026");let V=null,oe=Dt({label:j,scope:T,expiresIn:x});for(let se=0;se<15;se++){let Ie=await h.run(oe,{timeoutMs:15000});if(Ie.code===0){let ve=Ie.stdout,de=ve.indexOf("{"),pe=ve.lastIndexOf("}");if(de>=0&&pe>de){let me=ve.slice(de,pe+1);try{JSON.parse(me),V=me;break}catch{}}}await new Promise((ve)=>setTimeout(ve,2000))}if(!V){p("Could not run `vibe peer-bootstrap` on the remote. The agent is installed but not registered as a peer. Run `vibe network add ...` manually with the remote's API key + tunnel URL.");return}let K;try{K=JSON.parse(V)}catch(se){p(`Could not parse peer-bootstrap output: ${se.message}`);return}if(!K.tunnelUrl)p("Remote agent has no tunnel URL yet \u2014 it may still be coming up. Re-run `vibe network test <id>` later.");if(We({id:K.id,label:j,tunnelUrl:K.tunnelUrl??"",apiKey:K.apiKey,permissions:K.permissions,addedAt:new Date().toISOString(),agentRecordId:K.agentRecordId??void 0,workspaceId:K.workspaceId??void 0,fingerprint:K.id}),u(r,{ok:!0,host:a,version:B.trim(),peerId:K.id,tunnelUrl:K.tunnelUrl??null}))return;if(c(),l(`Deployed agent + registered peer ${K.id}`),n("Remote tunnel",K.tunnelUrl??"(pending)"),n("Permissions",K.permissions.join(",")),K.expiresAt)n("Key expires",K.expiresAt);c(),o(`${i.dim("Try it")}: ${i.bold(`vibe network test ${K.id.substring(0,8)}`)}`);let X=await Se(K.id,"/api/profiles/default/agent/identity",{operation:"post-deploy-probe"});if(X.ok)l("Peer probe succeeded.");else p(`Peer probe failed: ${X.status} ${X.error??""}. Tunnel may still be warming up.`)}catch(h){if(r.json){u(r,{ok:!1,error:A(h)});return}s(A(h))}})}function Zn(P){let a=P.split(",").map((r)=>r.trim()).filter(Boolean),t=Xe(a);if(t.length!==a.length)throw Error(`Invalid permission(s). Allowed: ${Ne.join(",")}`);return t}function _t(P){let{apiKey:a,...t}=P;return k({...t,apiKey:"[REDACTED]"})}function Xn(P){let a=P.command("network").description("Manage the mesh of peer agents this agent talks to");a.command("list").description("List configured peer agents").option("--json","Emit JSON").option("--plain","Force plain text output").action(async function(t){try{let r={...P.opts(),...t};await y({mode:_(r),fetchData:()=>Ri(),plain:(h)=>{if(h.length===0){o("No peers configured. Add one via `vibe deploy <ssh-target>` or `vibe network add`.");return}g("Peer agents"),F(h.map((O)=>({ID:O.id.substring(0,8),Label:O.label,Tunnel:O.tunnelUrl,Permissions:O.permissions.join(","),Last_Reachable:O.lastReachable??"never"})))},interactive:async(h)=>{if(h.length===0){g("Peer agents"),c(),o("No peers configured. Add one via `vibe deploy <ssh-target>` or `vibe network add`.");return}let O=h.map((E)=>{let N=[`${i.bold(E.label)} ${E.id.substring(0,8)}`,"",` Tunnel: ${E.tunnelUrl}`,` Permissions: ${E.permissions.join(",")}`,` Added: ${E.addedAt}`,` Last reachable: ${E.lastReachable??"never"}`,` Workspace: ${E.workspaceId??"-"}`,` Agent record: ${E.agentRecordId??"-"}`];return{id:E.id,label:E.label,hint:E.lastReachable?"reachable":"never",detail:N.join(`
|
|
98
|
+
`)}});await Q({title:`vibe network \u2014 ${h.length} peer(s)`,rows:O})},json:(h)=>h.map(_t)})}catch(r){s(r.message)}}),a.command("add <id>").description("Manually add a peer (use deploy for the SSH-install flow)").requiredOption("--label <label>","Friendly name").requiredOption("--tunnel-url <url>","Peer's tunnel URL").requiredOption("--api-key <key>","Scoped API key the peer minted for us").option("--permissions <list>",`Comma-separated permissions (default: tunnel:read). Allowed: ${Ne.join(",")}`,"tunnel:read").option("--agent-record-id <id>","Platform-side agent ID for backend rotation lookup").option("--workspace-id <id>","Platform-side workspace ID").option("--json","Emit JSON result").action((t,r)=>{try{let h={...P.opts(),...r},O=Zn(r.permissions);if(We({id:t,label:r.label,tunnelUrl:r.tunnelUrl,apiKey:r.apiKey,permissions:O,addedAt:new Date().toISOString(),agentRecordId:r.agentRecordId,workspaceId:r.workspaceId}),u(h,{ok:!0,id:t,label:r.label,permissions:O}))return;l(`Added peer ${t} (${r.label})`)}catch(h){s(h.message)}}),a.command("remove <id>").description("Remove a peer record (does not revoke the key on the peer)").option("--json","Emit JSON result").action((t,r)=>{let h={...P.opts(),...r},O=Bt(t);if(u(h,{ok:O,id:t}))return;if(O)l(`Removed peer ${t}`);else s(`No peer with id ${t}`)}),a.command("update <id>").description("Modify permissions or label of an existing peer").option("--label <label>","Update friendly name").option("--permissions <list>",`Comma-separated permissions. Allowed: ${Ne.join(",")}`).option("--json","Emit JSON result").action((t,r)=>{try{let h={...P.opts(),...r},O={};if(r.label)O.label=r.label;if(r.permissions)O.permissions=Zn(r.permissions);let E=ke(t,O);if(!E){if(u(h,{ok:!1,id:t,error:"not_found"}))return;s(`No peer with id ${t}`);return}if(u(h,{ok:!0,id:t,peer:_t(E)}))return;l(`Updated peer ${t}`)}catch(h){s(h.message)}}),a.command("test <id>").description("Probe a peer (calls /api/agent/identity over its tunnel)").option("--json","Emit JSON").option("--plain","Force plain text output").action(async(t,r)=>{let h={...P.opts(),...r},O=Je(t);if(!O){if(u(h,{ok:!1,id:t,error:"not_found"}))return;s(`No peer with id ${t}`);return}try{await y({mode:_(h),fetchData:async()=>({peer:O,result:await Se(t,"/api/profiles/default/agent/identity",{operation:"network-test"})}),plain:({peer:E,result:N})=>{if(g(`Probing peer ${E.label} (${E.id})`),c(),N.ok){if(l(`Peer is reachable${N.rotated?" (recovered via backend rotation lookup)":""}`),N.data)console.log(JSON.stringify(N.data,null,2))}else s(`Peer call failed (${N.status}): ${N.error??"(no detail)"}`)},interactive:async({peer:E,result:N})=>{let j=[` Peer: ${E.label} (${E.id})`,` Tunnel: ${E.tunnelUrl}`,` Status: ${N.ok?"reachable":`failed (${N.status})`}`,` Rotated: ${N.rotated?"yes":"no"}`,` Error: ${N.error??"-"}`,"",` Identity: ${N.data?JSON.stringify(N.data,null,2):"-"}`];await U({title:`Probe ${E.label}`,body:j.join(`
|
|
99
|
+
`)})},json:({peer:E,result:N})=>({peer:_t(E),result:k({ok:N.ok,status:N.status,rotated:N.rotated??!1,error:N.error??null,data:N.data??null})})})}catch(E){s(E.message)}})}import{existsSync as Fr}from"fs";function at(P){return Fr($e(P))}function Qn(P){let a=P.command("profile").description("Manage gateway-environment profiles");a.command("list").description("List all profiles and mark the active one").option("--json","Emit JSON").option("--plain","Force plain text output").action(async function(t){try{let r={...P.opts(),...t},h=()=>{let O=ye(),N=Xr().map((j)=>{let T=It(j);return{name:j,active:j===O,globalGatewayUrl:T.globalGatewayUrl??null,workspaceGatewayUrl:T.workspaceGatewayUrl??null}});return{active:O,profiles:N}};await y({mode:_(r),fetchData:h,plain:(O)=>{if(O.profiles.length===0){o("No profiles yet. Run 'vibe profile seed' to create the default profile.");return}g("Profiles"),F(O.profiles.map((E)=>({Name:E.name,Active:E.active?i.green("\u25CF"):"","Global Gateway":E.globalGatewayUrl??i.dim("(unset)"),"Workspace Gateway":E.workspaceGatewayUrl??i.dim("(unset)")})))},interactive:async(O)=>{if(O.profiles.length===0){g("Profiles"),c(),o("No profiles yet. Run 'vibe profile seed' to create the default profile.");return}let E=O.profiles.map((N)=>{let j=[`${i.bold(N.name)}${N.active?" "+i.green("\u25CF active"):""}`,"",` Global gateway: ${N.globalGatewayUrl??i.dim("(unset)")}`,` Workspace gateway: ${N.workspaceGatewayUrl??i.dim("(unset)")}`];return{id:N.name,label:N.name,hint:N.active?"active":"",detail:j.join(`
|
|
100
|
+
`)}});await Q({title:`vibe profile \u2014 ${O.profiles.length} profile(s)`,rows:E,footer:"\u2191/\u2193 navigate \xB7 q to quit"})},json:(O)=>O})}catch(r){s(r.message)}}),a.command("current").description("Print the active profile name").option("--json","Emit JSON").option("--plain","Force plain text output").action(async function(t){try{let r={...P.opts(),...t};await y({mode:_(r),fetchData:()=>({active:ye()}),plain:(h)=>{console.log(h.active)},json:(h)=>h})}catch(r){s(r.message)}}),a.command("show [name]").description("Print a profile's config as JSON (apiKey + secrets redacted)").option("--json","Emit JSON").option("--plain","Force plain text output").action(async function(t,r){try{let h={...P.opts(),...r},O=t?_e(t):ye();if(!at(O)){s(`No profile named '${O}'. Try 'vibe profile list'.`);return}let E=()=>({name:O,active:O===ye(),config:It(O)});await y({mode:_(h),fetchData:E,plain:(N)=>{g(`Profile: ${N.name}`),n("Active",N.active?"yes":"no"),c(),console.log(JSON.stringify(k(N.config),null,2))},interactive:async(N)=>{let j=[`Active: ${N.active?"yes":"no"}`,"",JSON.stringify(k(N.config),null,2)].join(`
|
|
101
|
+
`);await U({title:`Profile: ${N.name}`,body:j,footer:"q / Esc to quit"})},json:(N)=>({name:N.name,active:N.active,config:k(N.config)})})}catch(h){s(h.message)}}),a.command("create <name>").description("Create a new profile (blank, or copied from another)").option("--from <existing>","Copy gateway URLs + config from an existing profile").option("--use","After creating, set this profile as active",!1).option("--json","Emit JSON result").action((t,r)=>{try{let h={...P.opts(),...r},O=_e(t);if(at(O)){s(`Profile '${O}' already exists.`);return}let E;if(r.from){let N=_e(r.from);if(!at(N)){s(`--from: profile '${N}' does not exist.`);return}let j=It(N);delete j["static-api-key"],delete j.agentRecordId,delete j.apiKeys,E=j}else if(O in Ht)E=_r(O);else if(O in Er){let N=Er[O];E={schemaVersion:void 0,globalGatewayUrl:N.globalGatewayUrl,workspaceGatewayUrl:N.workspaceGatewayUrl}}else E={};if(nt(O,E),r.use)Vt(O);if(u(h,{ok:!0,action:"create",profile:O,from:r.from??null,globalGatewayUrl:E.globalGatewayUrl??null,workspaceGatewayUrl:E.workspaceGatewayUrl??null,active:r.use===!0}))return;if(l(`Profile '${O}' created.`),E.globalGatewayUrl)n("Global gateway",E.globalGatewayUrl);if(E.workspaceGatewayUrl)n("Workspace gateway",E.workspaceGatewayUrl);if(r.use)o(`Active profile is now '${O}'.`);else c(),o(`Activate with: ${i.bold(`vibe profile use ${O}`)}`)}catch(h){s(h.message)}}),a.command("use <name>").description("Set the active profile pointer").option("--json","Emit JSON result").action((t,r)=>{try{let h={...P.opts(),...r},O=_e(t);if(!at(O)){s(`No profile named '${O}'. Create it with 'vibe profile create ${O}' first.`);return}if(Vt(O),u(h,{ok:!0,action:"use",profile:O}))return;l(`Active profile is now '${O}'.`)}catch(h){s(h.message)}}),a.command("delete <name>").description("Delete a profile (refuses if it is the active one)").option("--confirm","Required -- destructive",!1).option("--json","Emit JSON result").action((t,r)=>{try{let h={...P.opts(),...r},O=_e(t);if(!r.confirm){s(`Pass --confirm to delete profile '${O}' (this removes its config + secrets).`);return}if(!at(O)){s(`No profile named '${O}'.`);return}if(O===ye()){s(`Cannot delete the active profile '${O}'. Switch first: 'vibe profile use <other>'.`);return}let E=ei(O);if(u(h,{ok:E,action:"delete",profile:O}))return;if(E)l(`Deleted profile '${O}'.`);else s(`Profile '${O}' could not be removed.`)}catch(h){s(h.message)}}),a.command("seed").description("Idempotently create local/alpha/prod profiles").option("--json","Emit JSON result").action((t)=>{try{let r={...P.opts(),...t},h=yr();if(u(r,{ok:!0,action:"seed",created:h.created,activeWritten:h.activeWritten??null}))return;if(h.created.length>0)l(`Created profile(s): ${h.created.join(", ")}`);if(h.activeWritten)o(`Active profile set to '${h.activeWritten}'.`);if(h.created.length===0&&!h.activeWritten)o("Nothing to do -- profiles already initialized.")}catch(r){s(r.message)}})}function eo(P){let a=P.command("daemon-profile").description("Manage the running daemon's in-process ProfileRegistry (distinct from `vibe profile`, which manages gateway-environment profiles on disk).");a.command("list").description("List profiles known to the running daemon").option("--json","Emit JSON").option("--plain","Force plain text output").action(async function(t){let r={...P.opts(),...t};try{await y({mode:_(r),fetchData:()=>S(f(r),"/api/profiles"),plain:(h)=>{if(g("Daemon Profiles"),c(),!h||h.length===0){o("No profiles attached.");return}let O=h.map((E)=>({Name:E.name,Default:E.isDefault?"yes":"",Attached:E.attached?"yes":"",BootState:E.bootState??"-",Running:E.isRunning?"yes":"",Port:E.port??"-",PID:E.pid??"-"}));F(O)}})}catch(h){if(r.json){u(r,{ok:!1,error:A(h)});return}s(`Failed to list daemon profiles: ${A(h)}`)}}),a.command("create <name>").description("Create a new profile and attach it to the running daemon").option("--copy-from <source>","Copy config from an existing profile").option("--start","Spawn an out-of-process daemon for the new profile").option("--port <port>","Port for the spawned daemon (with --start)").option("--json","Emit JSON").action(async function(t,r){let h={...P.opts(),...r};try{let O={name:t};if(r.copyFrom)O.copyFrom=r.copyFrom;if(r.start)O.start=!0;if(r.port)O.port=parseInt(r.port,10);let E=await q(f(h),"/api/profiles",O);if(u(h,E))return;if(l(`Profile '${t}' created.`),n("Default",E.isDefault?"yes":"no"),n("Attached",E.attached?"yes":"no"),E.bootState)n("BootState",E.bootState)}catch(O){if(h.json){u(h,{ok:!1,error:A(O)});return}s(`Failed to create profile: ${A(O)}`)}}),a.command("delete <name>").alias("rm").description("Delete a profile from the running daemon").option("--purge","Also remove the on-disk dataDir (destructive)").option("--json","Emit JSON").action(async function(t,r){let h={...P.opts(),...r};try{let O=r.purge?`/api/profiles/${encodeURIComponent(t)}?purge=true`:`/api/profiles/${encodeURIComponent(t)}`,E=await ge(f(h),O);if(u(h,E))return;l(`Profile '${t}' deleted.`)}catch(O){if(h.json){u(h,{ok:!1,error:A(O)});return}s(`Failed to delete profile: ${A(O)}`)}}),a.command("start <name>").description("Ensure the profile is attached + running (idempotent)").option("--port <port>","Port for the spawned daemon").option("--json","Emit JSON").action(async function(t,r){let h={...P.opts(),...r};try{let O={};if(r.port)O.port=parseInt(r.port,10);let E=await q(f(h),`/api/profiles/${encodeURIComponent(t)}/start`,O);if(u(h,E))return;if(l(`Profile '${t}' started.`),E.bootState)n("BootState",E.bootState);if(E.port)n("Port",String(E.port))}catch(O){if(h.json){u(h,{ok:!1,error:A(O)});return}s(`Failed to start profile: ${A(O)}`)}}),a.command("stop <name>").description("Stop the profile (detach from registry, preserve dataDir)").option("--json","Emit JSON").action(async function(t,r){let h={...P.opts(),...r};try{let O=await q(f(h),`/api/profiles/${encodeURIComponent(t)}/stop`);if(u(h,O))return;l(`Profile '${t}' stopped.`)}catch(O){if(h.json){u(h,{ok:!1,error:A(O)});return}s(`Failed to stop profile: ${A(O)}`)}}),a.command("restart <name>").description("Stop then start the profile").option("--port <port>","Port for the spawned daemon").option("--json","Emit JSON").action(async function(t,r){let h={...P.opts(),...r};try{await q(f(h),`/api/profiles/${encodeURIComponent(t)}/stop`);let O={};if(r.port)O.port=parseInt(r.port,10);let E=await q(f(h),`/api/profiles/${encodeURIComponent(t)}/start`,O);if(u(h,E))return;if(l(`Profile '${t}' restarted.`),E.bootState)n("BootState",E.bootState)}catch(O){if(h.json){u(h,{ok:!1,error:A(O)});return}s(`Failed to restart profile: ${A(O)}`)}}),a.command("stats").description("Per-profile resource attribution (childPidCount, status, dataDir; CPU/heap reported at the process level)").option("--json","Emit JSON").option("--plain","Force plain text output").action(async function(t){let r={...P.opts(),...t};try{await y({mode:_(r),fetchData:()=>S(f(r),"/api/profile-stats"),plain:(h)=>{if(g("Profile Stats"),c(),n("PID",String(h.process.pid)),n("Uptime (s)",String(Math.round(h.process.uptimeSeconds))),n("CPU user (ms)",String(Math.round(h.process.cpuUserMs))),n("CPU system (ms)",String(Math.round(h.process.cpuSystemMs))),n("Heap used (MB)",String(Math.round(h.process.heapUsedBytes/1048576))),c(),!h.profiles||h.profiles.length===0){o("No profiles attached.");return}F(h.profiles.map((O)=>({Name:O.name,Status:O.status,ChildPids:String(O.childPidCount),DataDir:O.dataDir})))}})}catch(h){if(r.json){u(r,{ok:!1,error:A(h)});return}s(`Failed to fetch profile stats: ${A(h)}`)}})}import ot from"os";function Jr(){return crypto.randomUUID()}function Gr(){let P=new Uint8Array(32);return crypto.getRandomValues(P),`vcak_${Buffer.from(P).toString("base64url")}`}function Br(){let P=new Bun.CryptoHasher("sha256");return P.update(`${ot.hostname()}-${ot.platform()}-${ot.arch()}`),P.digest("hex").substring(0,16)}function Vr(P){if(!P)return;let a=/^(\d+)([smhdw]?)$/.exec(P.trim());if(!a)throw Error(`Invalid --expires-in: ${P}`);let t=Number(a[1]),r=a[2]||"d",h=r==="s"?t*1000:r==="m"?t*60000:r==="h"?t*3600000:r==="w"?t*7*86400000:t*86400000;return new Date(Date.now()+h).toISOString()}function to(P){P.command("peer-bootstrap").description("Mint a peer credential bundle (used by `vibe deploy` post-install handshake)").option("--label <label>","Friendly name for the caller (logged on this host)","peer").option("--scope <list>",`Comma-separated permissions for the minted key (default: tunnel:read). Allowed: ${Ne.join(",")}`,"tunnel:read").option("--expires-in <duration>","TTL for the minted key (e.g. 7d, 12h). Omit for no expiry.").option("--emit-default-key","Include this agent's FULL default API key in the bundle. Only used by `vibe deploy` over the trusted SSH channel to onboard the new agent to the backend (fresh OAuth app). Never expose this output otherwise.",!1).option("--no-output","Don't print the JSON bundle (for testing)").option("--json","Emit JSON bundle (default behaviour, kept for parity)").action(async function(a){try{let t=a.scope.split(",").map((V)=>V.trim()).filter(Boolean),r=Xe(t);if(r.length===0)throw Error(`No valid permissions in --scope. Allowed: ${Ne.join(",")}`);let h=Vr(a.expiresIn),O=Jr(),E=Gr(),N=r.includes("mesh:forward")?["read","mesh:forward"]:["read"],T=[...w().apiKeys??[],{id:O,name:`peer:${a.label}`,key:E,scopes:N,expiresAt:h,createdAt:new Date().toISOString()}];M({apiKeys:T});let x=w(),L=await Re(),Z={id:Br(),hostname:ot.hostname(),platform:ot.platform(),arch:ot.arch(),tunnelUrl:lt()||te()?.url||null,apiKey:E,keyId:O,permissions:r,expiresAt:h??null,defaultApiKey:L.substring(0,8)+"****",...a.emitDefaultKey?{fullDefaultApiKey:L}:{},agentRecordId:x.agentRecordId??null,workspaceId:x.workspaceId??null};if(a.output===!1)return;console.log(`VIBE_BOOTSTRAP_JSON=${JSON.stringify(Z)}`);let B={...P.opts(),...a};if(u(B,Z))return;console.log(JSON.stringify(Z,null,2))}catch(t){console.error(JSON.stringify({error:t instanceof Error?A(t):String(t)})),process.exit(1)}})}var Kr=[{title:"Lifecycle",commands:["start","stop","restart","kill","list","status"]},{title:"Setup",commands:["setup","autostart","deploy","update","completion"]},{title:"Profile",commands:["profile"]},{title:"Plugins",commands:["plugin"]},{title:"Network",commands:["tunnel","network","peer-bootstrap","gateway-auth","url"]},{title:"Data",commands:["export","import","file","project","session","task","bookmark","state","git","key","config"]},{title:"Diagnostics",commands:["doctor","diagnostics","health","info","system","log","logs","log-level","notify"]},{title:"Maintenance",commands:["gc","nuke"]},{title:"Help",commands:["help"]}];function Ft(P){let a=new Map;for(let t of P.commands){if(t._hidden)continue;let r=t.name();a.set(r,{name:r,description:t.description()||"",cmd:t})}return a}function qr(P,a){let t=P;for(let r of a){let h=t.commands.find((O)=>O.name()===r||O.aliases().includes(r));if(!h)return null;t=h}return t}function Jt(P){let a=new Set,t=[];for(let h of Kr)for(let O of h.commands){let E=P.get(O);if(!E)continue;a.add(O),t.push({group:h.title,entry:E})}let r=[...P.values()].filter((h)=>!a.has(h.name));for(let h of r.sort((O,E)=>O.name.localeCompare(E.name)))t.push({group:"Other",entry:h});return t}function Pr(P,a=!1){let t=Ft(P),r=Jt(t),h=r.length>0?Math.max(...r.map((j)=>j.entry.name.length)):0,O=[];O.push(""),O.push(`${i.bold("vibe")} ${i.dim("\u2014 VibeControls Agent CLI")}`),O.push(""),O.push(`Usage: ${i.bold("vibe")} <command> [options]`),O.push(` ${i.bold("vibe help")} <command>`);let E="";for(let{group:j,entry:T}of r){if(j!==E)O.push(""),O.push(i.cyan(j)),E=j;let x=" ".repeat(h-T.name.length+2);O.push(` ${i.bold(T.name)}${x}${T.description}`)}O.push(""),O.push(i.dim("Tip: pipe to a TTY to launch the interactive browser, or run `vibe help <command>` for full options.")),O.push("");let N=O.join(`
|
|
102
|
+
`);return a?Ee(N):N}function Hr(P){let a=Ft(P);return{commands:Jt(a).map(({group:r,entry:h})=>({name:h.name,description:h.description,group:r}))}}function no(P,a=!1){process.stdout.write(Pr(P,a))}function oo(P){process.stdout.write(P.helpInformation())}async function zr(P){let a;try{a=await import("./index-01fp85ft.js")}catch{return!1}let{createCliRenderer:t,BoxRenderable:r,TextRenderable:h,SelectRenderable:O,SelectRenderableEvents:E}=a,N=Ft(P),j=Jt(N);if(j.length===0)return!1;let T=await t({exitOnCtrlC:!0,targetFps:30}),x=[],L="";for(let de of j){if(de.group!==L)x.push({kind:"header",title:de.group}),L=de.group;x.push({kind:"cmd",entry:de.entry})}let Z=x.map((de,pe)=>de.kind==="header"?{name:`\u2500\u2500 ${de.title} \u2500\u2500`,description:"",value:pe}:{name:de.entry.name,description:de.entry.description,value:pe}),B=T.root.ctx,V=new r(B,{width:"100%",height:"100%",flexDirection:"column",backgroundColor:"#0b0d12"}),oe=new h(B,{content:" vibe \u2014 command browser \u2191/\u2193 navigate \xB7 Enter view \xB7 q quit",fg:"#8be9fd",height:1}),K=new r(B,{width:"100%",flexGrow:1,flexDirection:"row"}),X=new O(B,{width:28,height:"100%",options:Z,selectedIndex:x.findIndex((de)=>de.kind==="cmd"),showDescription:!1,backgroundColor:"#0b0d12",textColor:"#cdd6f4",focusedBackgroundColor:"#0b0d12",focusedTextColor:"#cdd6f4",selectedBackgroundColor:"#1f2335",selectedTextColor:"#a6e3a1",showScrollIndicator:!0,wrapSelection:!1}),se=new r(B,{flexGrow:1,height:"100%",flexDirection:"column",paddingLeft:2,paddingRight:2,backgroundColor:"#11141c"}),Ie=new h(B,{content:"",fg:"#cdd6f4"});se.add(Ie),K.add(X),K.add(se),V.add(oe),V.add(K),T.root.add(V),X.focus();let ve=(de)=>{let pe=x[de];if(!pe)return;if(pe.kind==="header"){Ie.content=`
|
|
103
|
+
${pe.title}
|
|
104
|
+
`;return}let me=pe.entry.cmd.helpInformation();Ie.content=`
|
|
105
|
+
${me}
|
|
106
|
+
${"\u2500".repeat(40)}
|
|
107
|
+
Enter: print this help and exit
|
|
108
|
+
`};return ve(X.getSelectedIndex()),X.on(E.SELECTION_CHANGED,(de)=>{ve(de)}),await new Promise((de)=>{let pe=(me)=>{try{T.destroy()}catch{}if(me)oo(me.cmd);de(!0)};X.on(E.ITEM_SELECTED,()=>{let me=x[X.getSelectedIndex()];if(!me||me.kind!=="cmd")return;pe(me.entry)}),T.keyInput.on("keypress",(me)=>{if(me.name==="escape"||me.name==="q")pe(null)})})}function ro(P){P.command("help [command...]").description("Show categorised help \u2014 interactive in a TTY, plain otherwise").option("--plain","Force plain text output (no interactive UI)").option("--json","Emit machine-readable JSON instead of grouped text").action(async function(a,t){let r={...P.opts(),...t};{if(a&&a.length>0){let O=qr(P,a);if(!O){let E=`
|
|
109
|
+
Unknown command: ${i.bold(a.join(" "))}
|
|
110
|
+
`;console.error(r.plain?Ee(E):E),no(P,!!r.plain),process.exitCode=1;return}if(r.json){process.stdout.write(JSON.stringify({name:O.name(),description:O.description(),usage:O.helpInformation()})+`
|
|
111
|
+
`);return}oo(O);return}if(r.json){process.stdout.write(JSON.stringify(Hr(P))+`
|
|
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
|
+
`);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
|
+
`);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)}
|
|
116
|
+
export{Pr,Mr};
|