@vibecontrols/agent 2026.1127.1 → 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.
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{z,R,I,ne,ee,C,e}from"./index-7wm4bqx5.js";import{J,Wr,$i,Ht,Er,_e,$e,ye,Vt,Xr,It,nt,ei,_r,yr,st,Sr,w,M,Ct}from"./index-j99tkngg.js";import{i,d,s,A,l,p,o,g,n,c,F,v,G,H,Gt}from"./index-12gb48hg.js";import{Ee,Q,U}from"./index-sq5j8bjn.js";import{De,ct}from"./index-4kf3nr14.js";import{ie,Y,Ce,Pi,Ur,Ue,W}from"./index-awj0w14r.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-bp82hgag.js";import{Si}from"./index-0rmmrrfh.js";import{Ii}from"./index-90gn0b6x.js";import{D}from"./index-he4hy261.js";import{Nt}from"./index-qqnb0axh.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-yxztgnyz.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-1dqn9qaw.js"),fe=await he({port:K,host:se,dbPath:O});if(await fe.start(),ve&&de&&Me&&pe&&me){let He=await fe.finalize({clientId:ve,clientSecret:de,workspaceId:Me,globalGatewayUrl:pe,workspaceGatewayUrl:me});if(!He.ok)p(`Finalize failed \u2014 agent remains in awaiting-config state: ${He.error}`)}if(u(t,{ok:!0,name:a.name,port:K,host:se,pid:process.pid,url:Ie}));else await Gt(Ie);let be=async()=>{await fe.stop(),process.exit(0)};process.on("SIGTERM",be),process.on("SIGINT",be)}else{if(!t.json)g("Starting agent in daemon mode"),n("Name",a.name),n("Port",String(K)),n("Host",se),n("Database",O),c();if(a.installDeps===!1)process.env.VIBE_SKIP_PREREQ_INSTALL="1";await r.startDaemon({port:K,name:a.name,daemon:!0,dbPath:O,host:se,profile:h});let he=(await r.getStatus(a.name))?.port??K,fe;if(a.autostart!==!1){let{ensureAutostartConfigured:xe}=await import("./autostart.cmd-mdyv35dn.js"),we=await xe({name:a.name,port:he,dbPath:O,host:se,profile:h});if(fe=we,we.installed&&!t.json)o(`Configured ${we.serviceLabel} autostart \u2014 supervised from the next login/boot. `+"The daemon running now is not yet under it; hand it over with `vibe stop && vibe autostart install`.");else if(we.failed&&!t.json)p(`Could not configure autostart (${we.reason}). This agent will NOT come back after logout or reboot \u2014 fix the cause or run \`vibe autostart install\`.`)}let be=fe?{installed:fe.installed,failed:fe.failed??!1,reason:fe.reason}:{installed:!1,failed:!1,reason:"opted out"},Ae=`http://${se==="0.0.0.0"?"localhost":se}:${he}`,kt=a.waitReady,vt=a.wait===!1,zt=kt!==void 0;if(vt&&zt)p("--wait-ready is ignored because --no-wait was also passed.");let gt=!vt&&zt,Yt=!vt&&(gt||!t.json),Zt=(()=>{let xe=typeof kt==="string"?Number.parseInt(kt,10):NaN;if(Number.isInteger(xe)&&xe>0)return xe*1000;return gt?60000:25000})();if(t.json){if(Yt){let{trackAgentReady:xe}=await import("./agent-ready-tracker-7ebr09d9.js"),we=await xe(Ae,{timeoutMs:Zt,verbose:!1});if(gt&&(we.outcome==="degraded"||we.outcome==="timeout"))process.exitCode=1;u(t,{ok:we.outcome==="ready"||we.outcome==="awaiting-config",name:a.name,port:he,host:se,url:Ae,abilities:[...L],outcome:we.outcome,bootState:we.bootState,degradedReasons:we.degradedReasons,summary:we.summary,autostart:be})}else u(t,{ok:!0,name:a.name,port:he,host:se,url:Ae,autostart:be});return}if(await Gt(Ae),Yt){let{trackAgentReady:xe}=await import("./agent-ready-tracker-7ebr09d9.js");c();let we=await xe(Ae,{timeoutMs:Zt,verbose:!0});if(gt&&(we.outcome==="degraded"||we.outcome==="timeout"))process.exitCode=1}}}catch(r){let h=r instanceof Error?A(r):String(r);if(t.json){u(t,{ok:!1,error:h});return}s(`Failed to start agent: ${h}`)}})}function tn(P){P.command("stop").description("Stop a running VibeControls agent instance").option("-n, --name <name>","Agent instance name","default").option("--all","Stop all running agent instances",!1).option("--json","Emit JSON").action(async function(a){let t={...P.opts(),...a};try{let r=new D;if(a.all){let h=await r.listInstances();if(!h||h.length===0){if(u(t,{ok:!0,stopped:[]}))return;g("Stopping all agent instances"),c(),o(`${d.info} No running agent instances found.`);return}let O=[];if(!t.json)g("Stopping all agent instances"),c();for(let E of h)try{if(await r.stop(E.name),O.push(E.name),!t.json)l(`${d.success} Stopped ${i.bold(E.name)}`)}catch{if(!t.json)s(`Failed to stop ${i.bold(E.name)}`)}if(u(t,{ok:!0,stopped:O,total:h.length}))return;c(),l(`${d.success} Stopped ${O.length}/${h.length} instance(s).`)}else{if(await r.stop(a.name),u(t,{ok:!0,name:a.name}))return;g(`Stopping agent: ${a.name}`),c(),l(`${d.success} Agent ${i.bold(a.name)} stopped.`)}}catch(r){if(t.json){u(t,{ok:!1,error:A(r)});return}s(`Failed to stop agent: ${A(r)}`)}})}function nn(P){P.command("restart").description("Restart a running VibeControls agent instance").option("-n, --name <name>","Agent instance name","default").option("-p, --port <port>","Port to listen on").option("--db-path <path>","Path to the agent storage directory").option("--json","Emit JSON").option("--no-autostart","Don't configure OS-level autostart for this agent. Without it the daemon dies with the session that started it and will not come back.").action(async function(a){let t={...P.opts(),...a};try{let r=new D;if(!t.json)g(`Restarting agent: ${a.name}`),c(),o(`${d.info} Stopping agent ${i.bold(a.name)}...`);let h=await r.getStatus(a.name);try{if(await r.stop(a.name),!t.json)l(`${d.success} Agent stopped.`)}catch{if(!t.json)o(`${d.info} Agent was not running.`)}let O=a.port??h?.port??3005,E=typeof O==="number"?O:parseInt(O,10);if(isNaN(E)||E<1||E>65535){if(t.json){u(t,{ok:!1,error:"Invalid port number"});return}s("Invalid port number. Must be between 1 and 65535.");return}let N=t.profile??h?.config?.profile??process.env.VIBECONTROLS_PROFILE??"default";process.env.VIBECONTROLS_PROFILE=N;let j={port:E,name:a.name,daemon:!0,dbPath:a.dbPath??h?.config?.dbPath??ee(),host:h?.config?.host,profile:N};if(!t.json)c(),o(`${d.info} Starting agent ${i.bold(a.name)}...`);await r.startDaemon(j);let T;if(a.autostart!==!1){let{ensureAutostartConfigured:L}=await import("./autostart.cmd-mdyv35dn.js");T=await L({name:a.name,port:E,dbPath:j.dbPath,host:j.host,profile:j.profile});let Z=T;if(Z.installed&&!t.json)o(`Configured ${Z.serviceLabel} autostart \u2014 supervised from the next login/boot. `+"The daemon running now is not yet under it; hand it over with `vibe stop && vibe autostart install`.");else if(Z.failed&&!t.json)p(`Could not configure autostart (${Z.reason}). This agent will NOT come back after logout or reboot \u2014 fix the cause or run \`vibe autostart install\`.`)}let x=`http://localhost:${E}`;if(u(t,{ok:!0,name:a.name,port:E,url:x,autostart:T?{installed:T.installed,failed:T.failed??!1,reason:T.reason}:{installed:!1,failed:!1,reason:"opted out"}}))return;c(),l(`${d.success} Agent ${i.bold(a.name)} restarted.`),c(),n("Port",String(E)),n("Database",j.dbPath),c(),Gt(x)}catch(r){if(t.json){u(t,{ok:!1,error:A(r)});return}s(`Failed to restart agent: ${A(r)}`)}})}import{existsSync as bo,readFileSync as yo,unlinkSync as on}from"fs";import{join as sn}from"path";function wo(P){let a=sn(ne(),P,"runtime.json");if(!bo(a))return null;try{let t=JSON.parse(yo(a,"utf8"));if(typeof t.pid!=="number")return null;return{...t,pid:t.pid,path:a}}catch{return null}}async function rn(P){let a=wo(P);if(!a)return null;if(!ae(a.pid)){try{on(a.path)}catch{}return`agent pid=${a.pid} (${P}) already gone (cleaned runtime.json).`}let t=b();if(!t.killProcessTree(a.pid,"SIGTERM"))return`failed to SIGTERM agent pid=${a.pid}.`;if(await new Promise((r)=>setTimeout(r,3000)),ae(a.pid))t.killProcessTree(a.pid,"SIGKILL");try{on(a.path)}catch{}return`agent ${P} pid=${a.pid}${a.port?` (port ${a.port})`:""} killed.`}async function ko(P){let a=sn(ne(),P),t=te(a);if(!t)return null;if(!ae(t.pid))return re(a),`tunnel pid=${t.pid} already gone (cleaned state).`;let r=b();if(!r.killProcessTree(t.pid,"SIGTERM"))return`failed to SIGTERM tunnel pid=${t.pid}.`;if(await new Promise((h)=>setTimeout(h,3000)),ae(t.pid))r.killProcessTree(t.pid,"SIGKILL");return re(a),`tunnel ${t.provider} pid=${t.pid} (${t.url??"no url"}) killed.`}function an(P){P.command("kill").description("Force-kill an agent instance and its tunnel. Defaults to active profile.").option("-n, --name <name>","Agent instance name (alias of --profile, kept for back-compat)").option("--profile <name>","Kill a specific profile (overrides --name and VIBECONTROLS_PROFILE)").option("--all","Kill every agent instance and every profile's tunnel",!1).option("-y, --yes","Skip the confirmation prompt (for scripts/CI)",!1).option("--json","Emit JSON").action(async function(a){let t={...P.opts(),...a},r=a.all?"ALL agent instances + every profile's tunnel":`agent '${t.profile??t.name??"active profile"}'`;if(!await jt(t,`Force-kill ${r}? This sends SIGKILL (no graceful shutdown).`)){o("Aborted.");return}let h=[];try{let O=new D;if(a.all){if(!t.json)g("Force killing all agent instances + tunnels"),c();let T=await O.listInstances()??[],x=0,L=new Set;for(let V of T)try{if(await O.kill(V.name),!t.json)l(`${d.success} agent ${i.bold(V.name)} (pid=${V.pid||"?"}) killed.`);h.push(V.name),x++,L.add(V.name)}catch{if(!t.json)p(`${d.warning} could not kill agent ${V.name}.`)}try{let V=await import("fs"),oe=ne(),K=V.existsSync(oe)?V.readdirSync(oe):[];for(let X of K){if(L.has(X))continue;let se=await rn(X);if(se)l(`${d.success} ${se}`),x++}}catch(V){p(`${d.warning} runtime.json sweep failed: ${V instanceof Error?A(V):String(V)}`)}let Z=qi({allProfiles:!0}),B=0;for(let V of Z){if(!V.alive){re(V.profileDir);continue}let oe=b();if(oe.killProcessTree(V.pid,"SIGTERM"),await new Promise((K)=>setTimeout(K,3000)),ae(V.pid))oe.killProcessTree(V.pid,"SIGKILL");re(V.profileDir),l(`${d.success} tunnel ${V.provider} pid=${V.pid} (${V.url??"no url"}, ${V.profileDir.split("/").pop()}) killed.`),B++}if(u(t,{ok:!0,killed:h,tunnels:B}))return;c(),l(`${d.success} killed ${x} agent(s) and ${B} tunnel(s).`);return}let E=a.profile||a.name||R();if(!t.json)g(`Force killing profile: ${E}`),c();let N=await O.getStatus(E);if(N){if(await O.kill(E),h.push(E),!t.json)l(`${d.success} agent ${i.bold(E)} pid=${N.pid||"?"} killed.`)}else{let T=await rn(E);if(T){if(h.push(E),!t.json)l(`${d.success} ${T}`)}else if(!t.json)o(`${d.info} no running agent service for profile ${E}.`)}let j=await ko(E);if(j){if(!t.json)l(`${d.success} ${j}`)}else if(!t.json)o(`${d.info} no tunnel recorded for profile ${E}.`);u(t,{ok:!0,killed:h})}catch(O){if(t.json){u(t,{ok:!1,error:A(O)});return}s(`Failed to kill: ${A(O)}`)}})}function ln(P){P.command("list").alias("ls").description("List all VibeControls agent instances").option("--json","Emit JSON").option("--plain","Force plain text output").action(async function(a){try{let t={...P.opts(),...a},r=new D;await y({mode:_(t),fetchData:()=>r.listInstances(),plain:(h)=>{if(g("Agent Instances"),c(),!h||h.length===0){o(`${d.info} No agent instances found.`),o(`Run ${i.bold("vibe start")} to start an agent.`);return}let O=h.map((j)=>({Name:j.name,Status:G(j.status),PID:j.pid||"-",Port:j.port||"-",Host:j.config?.host||"-",Database:j.config?.dbPath||"-",Started:j.startTime?v(j.startTime):"-"}));F(O),c();let E=h.filter((j)=>j.status==="running").length,N=h.length-E;o(`${d.info} ${h.length} instance(s): ${i.green(String(E))} running, ${i.dim(String(N))} stopped`)},interactive:async(h)=>{if(!h||h.length===0){g("Agent Instances"),c(),o(`${d.info} No agent instances found.`),o(`Run ${i.bold("vibe start")} to start an agent.`);return}let O=h.map((E)=>{let N=[`${i.bold(E.name)} ${G(E.status)}`,"",` PID: ${E.pid??"-"}`,` Port: ${E.port??"-"}`,` Host: ${E.config?.host??"-"}`,` Database: ${E.config?.dbPath??"-"}`,` Started: ${E.startTime?v(E.startTime):"-"}`];return{id:E.name,label:E.name,hint:E.status==="running"?"running":"stopped",detail:N.join(`
2
+ import{z,R,I,ne,ee,C,e}from"./index-7wm4bqx5.js";import{J,Wr,$i,Ht,Er,_e,$e,ye,Vt,Xr,It,nt,ei,_r,yr,st,Sr,w,M,Ct}from"./index-j99tkngg.js";import{i,d,s,A,l,p,o,g,n,c,F,v,G,H,Gt}from"./index-12gb48hg.js";import{Ee,Q,U}from"./index-sq5j8bjn.js";import{De,ct}from"./index-4kf3nr14.js";import{ie,Y,Ce,Pi,Ur,Ue,W}from"./index-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
3
  `)}});await Q({title:`vibe list \u2014 ${h.length} instance(s)`,rows:O,footer:"\u2191/\u2193 navigate \xB7 q to quit"})},json:(h)=>h.map((O)=>({name:O.name,status:O.status,pid:O.pid??null,port:O.port??null,host:O.config?.host??null,database:O.config?.dbPath??null,startTime:O.startTime??null}))})}catch(t){s(`Failed to list instances: ${t.message}`)}})}var cn=5000;function dn(P){P.command("logs").description("View logs for a VibeControls agent instance").option("-n, --name <name>","Agent instance name","default").option("-f, --follow","Follow log output",!1).option("--tail <lines>","Number of lines to show from the end","100").option("--json","Emit JSON (one object per line, banners suppressed)").option("--plain","Force plain text output").action(async function(a){try{let t={...P.opts(),...a},r=new D,h=parseInt(t.tail??"100",10);if(isNaN(h)||h<1||h>cn){s(`Invalid tail value. Must be between 1 and ${cn}.`);return}let O=t.name??"default";if(!await r.getStatus(O)){s(`Agent instance ${i.bold(O)} not found.`);return}if(!t.json){if(t.follow)g(`Following logs: ${O}`),o(`${d.info} Press Ctrl+C to stop following.`);else g(`Logs: ${O}`);c()}await r.showLogs(O,{follow:!!t.follow,tail:h})}catch(t){s(`Failed to get logs: ${A(t)}`)}})}function un(P){P.command("setup").description("Install system dependencies and (optionally) write gateway auth config").option("--check","Only check dependencies without installing",!1).option("--client-id <id>","OAuth app client ID (for backend authentication)").option("--client-secret <secret>","OAuth app client secret").option("--workspace-id <id>","Workspace UUID this agent belongs to").option("--global-gateway-url <url>","Global public gateway URL (default: http://localhost:4000/global/graphql)").option("--workspace-gateway-url <url>","Workspace gateway URL (default: http://localhost:4001/workspaces/graphql)").option("--storage-adapter <name>","Named storage adapter (default: skalex, or custom:<path>)").option("--json","Emit JSON").action(async function(a){let t={...P.opts(),...a},r=[];try{if(!t.json)g("VibeControls Agent Setup");let h={};if(a.clientId)h.clientId=a.clientId;if(a.clientSecret)h.clientSecret=a.clientSecret;if(a.workspaceId)h.workspaceId=a.workspaceId;if(a.globalGatewayUrl)h.globalGatewayUrl=z(a.globalGatewayUrl,"globalGatewayUrl");if(a.workspaceGatewayUrl)h.workspaceGatewayUrl=z(a.workspaceGatewayUrl,"workspaceGatewayUrl");if(a.storageAdapter)h.storageAdapter=a.storageAdapter;if(Object.keys(h).length>0){let x=M(h);if(r.push(...Object.keys(h)),!t.json){l(`Agent config written to ${st()}`),n("clientId",x.clientId?i.dim("(set)"):i.dim("(unset)")),n("clientSecret",x.clientSecret?i.dim("(set)"):i.dim("(unset)")),n("workspaceId",x.workspaceId??i.dim("(unset)"));let L=Sr();if(n("globalGatewayUrl",x.globalGatewayUrl??L.globalGatewayUrl),n("workspaceGatewayUrl",x.workspaceGatewayUrl??L.workspaceGatewayUrl),x.storageAdapter)n("storageAdapter",x.storageAdapter);c()}}else{let x=w();if((x.clientId||x.clientSecret||x.workspaceId)&&!t.json)o(`Using existing agent config at ${st()} (pass --client-id/--client-secret/--workspace-id to update).`),c()}if(!t.json)o("Checking dependencies..."),c();let O=De(),E=[],N=[];for(let x of O){if(x.installed)N.push(x.name);if(!t.json){let L=x.installed?d.success:d.error,Z=x.version?i.dim(` (${x.version})`):"",B=x.required?"":i.dim(" [optional]");n(`${L} ${x.name}`,`${x.installed?i.green("installed"):i.red("missing")}${Z}${B}`)}if(!x.installed)E.push(x.name)}if(!t.json)c();if(E.length===0){if(u(t,{ok:!0,installed:N,configured:r}))return;l("All dependencies are installed.");return}if(a.check){if(t.json){u(t,{ok:!1,installed:N,missing:E,configured:r});return}p(`Missing: ${E.join(", ")}`),o(`Run ${i.bold("vibe setup")} to install them.`),process.exit(1)}if(!t.json)o(`Installing missing dependencies: ${E.join(", ")}...`),c();let j=await ct(E),T=E.filter((x)=>!j.failed.includes(x));if(j.failed.length>0){if(t.json){u(t,{ok:!1,installed:[...N,...T],failed:j.failed,configured:r});return}p(`${j.failed.length} tool(s) failed: ${j.failed.join(", ")}`),o("You may need to install manually or use sudo."),process.exit(1)}else{if(u(t,{ok:!0,installed:[...N,...T],configured:r}))return;l("All dependencies installed successfully.")}}catch(h){let O=h instanceof Error?A(h):String(h);if(t.json){u(t,{ok:!1,error:O});return}s(`Setup failed: ${O}`)}})}function vo(P){let a=b();return a.which(P)??`${P}${a.executableSuffix}`}function pn(P){P.command("update").description("Check for and install VibeControls agent updates").option("--check","Only check for updates without installing",!1).option("--allow-incompatible","Override engines.bun compatibility check (use with care)",!1).option("--no-restart","Skip the post-install idle-aware restart of any running agent").option("-n, --name <name>","Agent profile name to restart after update","default").option("--version-target <version>","Install a specific version instead of the latest (e.g. 2026.601.21)").option("--json","Emit JSON").action(async function(a){let t={...P.opts(),...a};try{if(!t.json)g("VibeControls Agent Update"),c(),o(`${d.info} Checking for updates...`),c();let r=await Le();if(r.error&&!r.latest){if(u(t,{ok:!1,current:r.current,error:r.error}))return;s(r.error);return}if(!t.json)n("Package",i.bold(r.name)),n("Registry",i.bold(r.registry)),n("Current version",i.bold(r.current)),n("Latest version",i.bold(r.latest??"unknown")),c();if(a.check){if(u(t,{ok:!0,current:r.current,latest:r.latest,upToDate:!r.hasUpdate}))return;if(!r.hasUpdate)l(`${d.success} You are running the latest version.`);else p(`${d.warning} A new version is available: ${i.green(r.latest??"")}`),o(`${d.info} Run ${i.bold("vibe update")} to install the update.`);return}let h=a.versionTarget;if(!h&&!r.hasUpdate){if(u(t,{ok:!0,current:r.current,latest:r.latest,upToDate:!0}))return;l(`${d.success} You are running the latest version.`);return}if(!t.json)o(`${d.info} Updating to ${i.bold(h??r.latest??"latest")}...`),c();let O=await ze({targetVersion:h,allowIncompatible:!!a.allowIncompatible,restart:a.restart!==!1,name:a.name,onLog:t.json?void 0:(E)=>o(`${d.info} ${E}`)});if(!O.ok){if(u(t,{ok:!1,current:O.current,previous:O.previous,latest:O.latest,rolledBack:O.rolledBack,error:O.error}))return;s(O.error??"Update failed.");return}if(!t.json)switch(O.restart){case"restarted":l(`${d.success} Restarted agent ${i.bold(a.name)} on the new version.`);break;case"not-running":o(`${d.info} No running agent for profile ${i.bold(a.name)}; nothing to restart.`);break;case"still-busy":p(`${d.warning} Agent still serving requests \u2014 run ${i.bold("vibe restart")} when it's quiet.`);break;case"error":p(`${d.warning} Auto-restart failed: ${O.restartError}. Run ${i.bold("vibe restart")} manually.`);break}if(u(t,{ok:!0,current:O.current,previous:O.previous,latest:O.latest,updated:O.updated,restart:O.restart,...O.restartError?{restartError:O.restartError}:{}}))return;if(c(),O.updated)l(`${d.success} Updated to ${i.bold(O.current)} (smoke: ${O.smoke?.step??"ok"}).`);else l(`${d.success} You are running the latest version.`);if(a.restart===!1)o(`${d.info} --no-restart set \u2014 restart running agents manually for the update to take effect.`)}catch(r){let h=r instanceof Error?A(r):String(r);if(t.json){u(t,{ok:!1,error:h});return}s(`Update failed: ${h}`)}}),P.command("rollback").description("Roll the global agent install back to a specific version").argument("<version>","Target CalVer version (e.g. 2026.428.3)").action(async(a)=>{try{g("VibeControls Agent Rollback");let t=await Ar();if(n("Package",i.bold(t.name)),n("Current version",i.bold(t.version)),n("Target version",i.bold(a)),c(),o(`${d.info} Rolling back\u2026`),Bun.spawnSync([vo("npm"),"install","-g",`${t.name}@${a}`,`--registry=${t.registry}`],{stdout:"inherit",stderr:"inherit"}).exitCode!==0){s("Rollback failed.");return}l(`${d.success} Rolled back to ${i.bold(a)}.`)}catch(t){s(`Rollback failed: ${t instanceof Error?A(t):String(t)}`)}})}import{existsSync as Be,mkdirSync as $o,writeFileSync as Rt,unlinkSync as So,readFileSync as $t}from"fs";import{join as Fe}from"path";import{homedir as Ye}from"os";var Co=/^[A-Za-z0-9][A-Za-z0-9:_-]{0,63}$/,Po=/^--[A-Za-z0-9][A-Za-z0-9-]{0,63}$/;function hn(P){return Co.test(P)?P:null}function bn(P){return P.filter((a)=>hn(a))}function Ro(P){return P.filter((a)=>Po.test(a))}function Qe(P){return P.commands.flatMap((a)=>{let t=hn(a.name());if(!t)return[];return[{name:t,description:a.description()||"",options:a.options.map((r)=>({flags:r.flags,description:r.description||""})),subcommands:Qe(a)}]})}function Ao(P){return bn(P.map((a)=>a.name))}function Io(P,a){let t=P.find((h)=>h.name===a);if(!t)return[];let r=[];for(let h of t.options){let O=h.flags.match(/--([\w-]+)/);if(O)r.push(`--${O[1]}`)}return Ro(r)}function yn(P){let a=Ao(P),r=P.filter((O)=>O.subcommands.length>0).map((O)=>({name:O.name,subs:bn(O.subcommands.map((E)=>E.name))})).map((O)=>` ${O.name})
4
4
  COMPREPLY=($(compgen -W "${O.subs.join(" ")}" -- "\${cur}"))
5
5
  return 0
@@ -112,5 +112,5 @@ Enter: print this help and exit
112
112
  `);return}if(!r.plain&&ue()){if(await zr(P))return}no(P,!!r.plain)}})}var Yr="http://localhost:3005",Zr=5000;function Qr(P,a,t){let r=Number.parseInt(P,10);if(!Number.isInteger(r)||r<1)return a;return Math.min(r,t)}function io(P){P.command("audit").description("View persistent audit log").command("list").description("List recent audit events").option("--since <iso>","Lower-bound ISO 8601 timestamp").option("--limit <n>","Maximum events to show","100").option("--event <pattern>","Filter by event name (supports * glob)").option("--agent-url <url>","Agent URL",Yr).option("--json","Emit JSON (one object per line)").option("--plain","Force plain text output").action(async function(t){try{let r={...P.opts(),...t},h=f(r),O=encodeURIComponent(m(r)),E=new URLSearchParams;if(E.set("limit",String(Qr(String(r.limit),100,Zr))),r.since)E.set("since",String(r.since));if(r.event)E.set("event",String(r.event));let j=(await S(h,`/api/profiles/${O}/agent/audit?${E.toString()}`)).events??[];if(r.json){for(let T of j)process.stdout.write(`${JSON.stringify(T)}
113
113
  `);return}if(j.length===0){o("No audit events found.");return}g("Audit events"),c();for(let T of j){let x=T.timestamp?i.dim(v(T.timestamp)):"",L=T.source?i.cyan(`[${T.source}]`):"",Z=i.bold(T.event??"?"),B=T.payload?i.dim(JSON.stringify(T.payload)):"";console.log(` ${Z} ${L} ${B} ${x}`)}}catch(r){s(A(r))}})}function so(P){let a=P.command("alias").description("Manage per-profile aliases");a.command("list").description("List aliases for the current profile").option("--json","Emit JSON").option("--plain","Force plain text output").action(async function(t){try{let r={...P.opts(),...t},h=f(r),O=encodeURIComponent(m(r));await y({mode:_(r),fetchData:async()=>(await S(h,`/api/profiles/${O}/agent/aliases`)).aliases??[],plain:(E)=>{if(g("Aliases"),c(),!E.length){o("No aliases defined.");return}let N=E.map((j)=>({Name:j.name,Command:j.command.length>60?`${j.command.slice(0,57)}\u2026`:j.command,Description:j.description??"-",Updated:v(j.updatedAt)}));F(N),c()}})}catch(r){s(A(r))}}),a.command("get <name>").description("Show an alias by name").option("--json","Emit JSON").action(async function(t,r){try{let h={...P.opts(),...r},O=f(h),E=encodeURIComponent(m(h)),N=await S(O,`/api/profiles/${E}/agent/aliases/${encodeURIComponent(t)}`);if(h.json){process.stdout.write(`${JSON.stringify(N,null,2)}
114
114
  `);return}g(`Alias: ${N.name}`),c(),console.log(` ${i.bold("Command: ")} ${N.command}`),console.log(` ${i.bold("Description:")} ${N.description??"-"}`),console.log(` ${i.bold("Cwd: ")} ${N.cwd??"$HOME (default)"}`),console.log(` ${i.bold("Profile: ")} ${N.profile}`),console.log(` ${i.bold("Created: ")} ${N.createdAt}`),console.log(` ${i.bold("Updated: ")} ${N.updatedAt}`),c()}catch(h){s(A(h))}}),a.command("create <name>").description("Create a new alias").requiredOption("--command <cmd>","The shell command to run").option("--description <text>","Optional description").option("--cwd <dir>","Working directory the command runs in (supports ~, absolute, or relative-to-$HOME). Defaults to $HOME.").action(async function(t,r){try{let h={...P.opts(),...r},O=f(h),E=encodeURIComponent(m(h)),N=await q(O,`/api/profiles/${E}/agent/aliases`,{name:t,command:r.command,description:r.description,cwd:r.cwd});l(`Created alias '${N.name}'`)}catch(h){s(A(h))}}),a.command("update <name>").description("Update an existing alias").option("--command <cmd>","Replacement shell command").option("--description <text>","Replacement description").option("--cwd <dir>","Replacement working directory. Pass an empty string to reset to $HOME.").action(async function(t,r){try{if(r.command===void 0&&r.description===void 0&&r.cwd===void 0){s("Provide --command, --description, or --cwd to update.");return}let h={...P.opts(),...r},O=f(h),E=encodeURIComponent(m(h)),N=await Te(O,`/api/profiles/${E}/agent/aliases/${encodeURIComponent(t)}`,{command:r.command,description:r.description,cwd:r.cwd});l(`Updated alias '${N.name}'`)}catch(h){s(A(h))}}),a.command("delete <name>").description("Delete an alias").action(async function(t,r){try{let h={...P.opts(),...r},O=f(h),E=encodeURIComponent(m(h));await ge(O,`/api/profiles/${E}/agent/aliases/${encodeURIComponent(t)}`),l(`Deleted alias '${t}'`)}catch(h){s(A(h))}})}function ao(P){P.command("run <name> [args...]").description("Run a stored alias by name").allowUnknownOption(!0).action(async function(a,t=[],r){try{let h={...P.opts(),...r},O=f(h),E=encodeURIComponent(m(h)),N;try{N=await S(O,`/api/profiles/${E}/agent/aliases/${encodeURIComponent(a)}`)}catch{console.error(`alias '${a}' not found`),e().audit.emit("agent","alias.executed",{exit_code:1}),process.exit(1)}let{exitCode:j}=await Ii(N,t);e().audit.emit("agent","alias.executed",{exit_code:j}),Ke("alias.executed",{exit_code:j}),process.exit(j)}catch(h){s(A(h))}})}function lo(P){P.command("retry-config").description("Force the background finalize-retry worker to attempt finalize immediately. Use when the gateway came back online and you don't want to wait the current backoff.").option("--json","Emit JSON").action(async function(a){let t={...P.opts(),...a};try{let r=f(t),h=await fetch(`${r}/api/agent/retry-config`,{method:"POST"}),O;try{O=await h.json()}catch{if(t.json)u(t,{ok:!1,error:`agent returned non-JSON (HTTP ${h.status})`}),process.exit(1);s(`Agent returned non-JSON response (HTTP ${h.status}). The daemon may be on an older build without /api/agent/retry-config.`),process.exit(1);return}if(t.json){if(u(t,O),O.state!=="ready")process.exit(O.ok?0:3);return}if(h.status===409){g("Retry not available"),o(O.error??"No active finalize-retry worker."),process.exit(2);return}if(g("Force finalize retry"),n("Result",O.ok?i.green("ok"):i.red("failed")),O.state)n("Boot state",O.state);if(O.worker){if(n("Attempt",String(O.worker.attempt)),O.worker.nextAttemptAt)n("Next attempt",O.worker.nextAttemptAt)}if(c(),O.ok&&O.state==="ready")o(`${i.green("\u2713")} Agent finalized \u2014 state=ready.`),process.exit(0);else if(O.ok)o(`${i.yellow("\u26A0")} Attempt completed but agent is still in '${O.state}'. The worker will continue to retry in the background; check ${i.bold("vibe status")} for progress.`),process.exit(0);else p(`Retry failed: ${O.error??"unknown error"}. The worker will keep retrying on the configured backoff. View the full trace with ${i.bold("vibe logs --since 10m")}.`),process.exit(3)}catch(r){let h=r instanceof Error?A(r):String(r);if(t.json){u(t,{ok:!1,error:h}),process.exit(1);return}s(`Failed to reach agent: ${h}`),process.exit(1)}})}var Oe="http://localhost:3005";function ti(P){return(P||[]).map((a)=>({id:a.id??null,name:a.name??null,status:a.status??null,port:a.port??null,project:a.project??a.projectId??null}))}async function co(P,a,t,r,h){await y({mode:_(h),fetchData:async()=>(await S(P,a)).sessions||[],plain:(O)=>{if(!O||O.length===0){o(r);return}g(t),F(O.map((E)=>({ID:H(E.id||""),Name:E.name||"-",Status:G(E.status||""),Port:E.port??"-",Project:E.project||E.projectId||"-"})))},interactive:async(O)=>{if(!O||O.length===0){g(t),o(r);return}let E=O.map((N)=>({id:String(N.id??""),label:N.name||H(N.id||""),hint:N.status||"",detail:[`ID: ${N.id??"-"}`,`Name: ${N.name??"-"}`,`Status: ${G(N.status||"")}`,`Port: ${N.port??"-"}`,`Project: ${N.project??N.projectId??"-"}`].join(`
115
- `)}));await Q({title:`${t} \u2014 ${O.length} session(s)`,rows:E})},json:(O)=>ti(O)})}function uo(P){let a=P.command("session").description("Manage terminal sessions");a.command("system").description("List system sessions (alias for `session list --system`)").option("--agent-url <url>","Agent URL",Oe).option("--json","Emit JSON").option("--plain","Force plain text output").action(async function(t){let r={...P.opts(),...t};try{let h=f(t),O=encodeURIComponent(m(r));await co(h,`/api/profiles/${O}/sessions/system`,"System Sessions","No system sessions found.",r)}catch(h){s(A(h))}}),a.command("list").description("List all sessions").option("--system","Show system sessions instead of user sessions").option("--agent-url <url>","Agent URL",Oe).option("--json","Emit JSON").option("--plain","Force plain text output").action(async function(t){let r={...P.opts(),...t};try{let h=f(t),O=encodeURIComponent(m(r)),E=t.system?`/api/profiles/${O}/sessions/system`:`/api/profiles/${O}/sessions`;await co(h,E,"Sessions","No sessions found.",r)}catch(h){s(A(h))}}),a.command("create").description("Create a new session").requiredOption("--name <name>","Session name").option("--project <id>","Project ID","default").option("--command <cmd>","Initial command to run").option("--cwd <dir>","Working directory").option("--agent-url <url>","Agent URL",Oe).option("--json","Emit JSON").action(async function(t){let r={...P.opts(),...t};try{let h=f(t),O=encodeURIComponent(m(r)),E={sessionName:t.name,projectId:t.project};if(t.command)E.command=t.command;if(t.cwd)E.startDirectory=t.cwd;let N=await q(h,`/api/profiles/${O}/sessions/create`,E),j=N?.session?.id||N?.id||N?.sessionId;if(u(r,{ok:!0,id:j,name:t.name,project:t.project}))return;l(`Session created: ${H(j)}`),n("Name",t.name),n("Project",t.project)}catch(h){if(r.json){u(r,{ok:!1,error:A(h)});return}s(A(h))}}),a.command("kill").description("Kill a session").requiredOption("-i, --id <id>","Session ID").option("--agent-url <url>","Agent URL",Oe).option("--json","Emit JSON").action(async function(t){let r={...P.opts(),...t};try{let h=f(t),O=encodeURIComponent(m(r));if(await ge(h,`/api/profiles/${O}/sessions/${t.id}`),u(r,{ok:!0,id:t.id}))return;l(`Session ${H(t.id)} killed.`)}catch(h){if(r.json){u(r,{ok:!1,error:A(h)});return}s(A(h))}}),a.command("exec").description("Execute a command in a session").requiredOption("-i, --id <id>","Session ID").requiredOption("-c, --command <cmd>","Command to execute").option("--agent-url <url>","Agent URL",Oe).option("--json","Emit JSON").action(async function(t){let r={...P.opts(),...t};try{let h=f(t),O=encodeURIComponent(m(r)),E=await q(h,`/api/profiles/${O}/sessions/${t.id}/command`,{command:t.command});if(u(r,{ok:!0,id:t.id,output:E?.output??null}))return;if(l("Command executed."),E?.output)c(),console.log(E.output)}catch(h){if(r.json){u(r,{ok:!1,error:A(h)});return}s(A(h))}}),a.command("capture").description("Capture session terminal output").requiredOption("-i, --id <id>","Session ID").option("--agent-url <url>","Agent URL",Oe).option("--json","Emit JSON").option("--plain","Force plain text output").action(async function(t){let r={...P.opts(),...t};try{let h=f(t),O=encodeURIComponent(m(r));await y({mode:_(r),fetchData:()=>S(h,`/api/profiles/${O}/sessions/${t.id}/capture`),plain:(E)=>{if(E?.content||E?.output)console.log(E.content||E.output);else o("No capture data available.")},json:(E)=>({id:t.id,content:E?.content??E?.output??null})})}catch(h){s(A(h))}}),a.command("keys").description("Send keys to a session").requiredOption("-i, --id <id>","Session ID").requiredOption("-k, --keys <keys>","Keys to send").option("--agent-url <url>","Agent URL",Oe).option("--json","Emit JSON").action(async function(t){let r={...P.opts(),...t};try{let h=f(t),O=encodeURIComponent(m(r));if(await q(h,`/api/profiles/${O}/sessions/${t.id}/keys`,{keys:t.keys}),u(r,{ok:!0,id:t.id}))return;l("Keys sent.")}catch(h){if(r.json){u(r,{ok:!1,error:A(h)});return}s(A(h))}}),a.command("interrupt").description("Send interrupt signal to a session").requiredOption("-i, --id <id>","Session ID").option("--agent-url <url>","Agent URL",Oe).option("--json","Emit JSON").action(async function(t){let r={...P.opts(),...t};try{let h=f(t),O=encodeURIComponent(m(r));if(await q(h,`/api/profiles/${O}/sessions/${t.id}/interrupt`,{}),u(r,{ok:!0,id:t.id}))return;l(`Session ${H(t.id)} interrupted.`)}catch(h){if(r.json){u(r,{ok:!1,error:A(h)});return}s(A(h))}}),a.command("rename").description("Rename a session").requiredOption("-i, --id <id>","Session ID").requiredOption("--name <name>","New session name").option("--agent-url <url>","Agent URL",Oe).option("--json","Emit JSON").action(async function(t){let r={...P.opts(),...t};try{let h=f(t),O=encodeURIComponent(m(r));if(await Te(h,`/api/profiles/${O}/sessions/${t.id}/rename`,{newName:t.name}),u(r,{ok:!0,id:t.id,name:t.name}))return;l(`Session ${H(t.id)} renamed to "${t.name}".`)}catch(h){if(r.json){u(r,{ok:!1,error:A(h)});return}s(A(h))}}),a.command("toggle-mouse").description("Toggle mouse support in a session").requiredOption("-i, --id <id>","Session ID").option("--agent-url <url>","Agent URL",Oe).option("--json","Emit JSON").action(async function(t){let r={...P.opts(),...t};try{let h=f(t),O=encodeURIComponent(m(r)),E=await q(h,`/api/profiles/${O}/sessions/${t.id}/toggle-mouse`,{});if(u(r,{ok:!0,id:t.id,mouseEnabled:!!E?.mouseEnabled}))return;l(`Mouse support ${E?.mouseEnabled?"enabled":"toggled"} for session ${H(t.id)}.`)}catch(h){if(r.json){u(r,{ok:!1,error:A(h)});return}s(A(h))}}),a.command("terminal-start").description("Start terminal for a session").requiredOption("-i, --id <id>","Session ID").option("--agent-url <url>","Agent URL",Oe).option("--json","Emit JSON").action(async function(t){let r={...P.opts(),...t};try{let h=f(t),O=encodeURIComponent(m(r)),E=await q(h,`/api/profiles/${O}/sessions/${t.id}/terminal`,{});if(u(r,{ok:!0,id:t.id,port:E?.port??null}))return;if(l(`Terminal started for session ${H(t.id)}.`),E?.port)n("Port",E.port)}catch(h){if(r.json){u(r,{ok:!1,error:A(h)});return}s(A(h))}}),a.command("terminal-stop").description("Stop terminal for a session").requiredOption("-i, --id <id>","Session ID").option("--agent-url <url>","Agent URL",Oe).option("--json","Emit JSON").action(async function(t){let r={...P.opts(),...t};try{let h=f(t),O=encodeURIComponent(m(r));if(await q(h,`/api/profiles/${O}/sessions/${t.id}/terminal/stop`,{}),u(r,{ok:!0,id:t.id}))return;l(`Terminal stopped for session ${H(t.id)}.`)}catch(h){if(r.json){u(r,{ok:!1,error:A(h)});return}s(A(h))}}),a.command("health-check").description("Run health check on all sessions").option("--agent-url <url>","Agent URL",Oe).option("--json","Emit JSON").action(async function(t){let r={...P.opts(),...t};try{let h=f(t),O=encodeURIComponent(m(r)),E=await S(h,`/api/profiles/${O}/sessions`),N=await q(h,`/api/profiles/${O}/sessions/health-check`,{sessionIds:(E.sessions||[]).map((j)=>j.id)});if(u(r,{ok:!0,healthy:N?.healthy??null,checked:N?.checked??null,fixed:N?.fixed??null}))return;if(l("Health check completed."),N?.healthy!==void 0)n("Healthy",N.healthy);if(N?.checked!==void 0)n("Checked",N.checked);if(N?.fixed!==void 0)n("Fixed",N.fixed)}catch(h){if(r.json){u(r,{ok:!1,error:A(h)});return}s(A(h))}})}function po(P){P.command("reuse-db").description("Point this agent at an EXISTING database (reuse data from another same-workspace agent)").option("--adapter <name>","Storage adapter to use (e.g. postgres, skalex). Defaults to the configured/default adapter.").option("--connection-string <conn>","Connection string for the adapter (e.g. postgres://user:pass@host/db)").option("--storage-options <json>","Raw adapter options as a JSON object (alternative/in addition to --connection-string)").option("--db-path <path>","Data directory the adapter should use (e.g. an existing Skalex agent-db dir)").option("-y, --yes","Skip the confirmation prompt").option("--json","Emit JSON").action(async function(a){let t={...P.opts(),...a};try{let r={};if(a.storageOptions){let E;try{E=JSON.parse(a.storageOptions)}catch{s("--storage-options must be valid JSON.");return}if(!E||typeof E!=="object"||Array.isArray(E)){s("--storage-options must be a JSON object.");return}for(let[N,j]of Object.entries(E))r[N]=typeof j==="string"?j:JSON.stringify(j)}if(a.connectionString)r.connectionString=String(a.connectionString);if(!a.adapter&&!a.dbPath&&Object.keys(r).length===0){s("Nothing to set. Provide --adapter with --connection-string (or --storage-options), and/or --db-path.");return}if(!t.json){if(g("Reuse an existing database"),a.adapter)n("Adapter",i.bold(a.adapter));if(a.dbPath)n("Data path",i.bold(a.dbPath));if(Object.keys(r).length>0)n("Options",i.dim(Object.keys(r).join(", ")));c(),p(`${d.warning} Reuse is safe ONLY for a database from the SAME workspace \u2014 the encryption key is per-workspace, so a foreign DB won't decrypt (the agent will go degraded).`),p(`${d.warning} Two agents writing the same database concurrently can corrupt it. Keep this a single-writer setup unless your adapter is explicitly configured for shared writes.`),c()}if(!a.yes&&!t.json){if(!await le(i.bold("Write this storage configuration to the agent config?"))){o("Cancelled.");return}}let h={};if(a.adapter)h.storageAdapter=String(a.adapter);if(Object.keys(r).length>0)h.storageOptions=r;if(a.dbPath)h.dbPath=String(a.dbPath);M(h);let O=w();if(u(t,{ok:!0,storageAdapter:O.storageAdapter??null,dbPath:O.dbPath??null,storageOptionKeys:Object.keys(O.storageOptions??{})}))return;l(`${d.success} Storage configuration written. Run ${i.bold("vibe restart")} so the agent connects to the existing database.`)}catch(r){let h=r instanceof Error?A(r):String(r);if(t.json){u(t,{ok:!1,error:h});return}s(`reuse-db failed: ${h}`)}})}function Kt(P){return new Set([...Ze(P)??sr()])}function qt(P){return Ce(process.platform,new Set(P)).map((a)=>a.packageName)}async function Wt(){let{PluginManager:P}=await import("./plugin-system-yxztgnyz.js"),a=new P;return{install:(t)=>a.install(t),remove:(t)=>a.remove(t)}}function mo(P){let a=P.command("capability").alias("cap").description("Select agent capabilities (abilities) + providers");a.command("list",{isDefault:!0}).description("List capabilities and whether each is enabled").option("--json","Emit JSON").action((t)=>{let r={...P.opts(),...t},h=C(),O=Kt(h),E=Ot(h);if(u(r,{abilities:Y.map((N)=>({key:N.key,label:N.label,mandatory:N.mandatory,enabled:N.mandatory||O.has(N.key)})),providers:E}))return;if(g("Capabilities"),F(Y.map((N)=>({Key:N.key,Capability:N.label,Status:N.mandatory?"required":O.has(N.key)?"enabled":"disabled",Description:N.description}))),E.length>0){c(),g("Extra providers");for(let N of E)n("\u2022",N)}c(),o("Enable: vibe capability enable <key...> [--provider <pkg...>]"),o("Disable: vibe capability disable <key...>"),o("Re-run the interactive selector: vibe capability select")}),a.command("enable").description("Enable capabilities (installs their meta plugin) and/or extra providers").argument("[keys...]","Ability keys (e.g. gitops security)").option("--provider <pkg...>","Extra provider plugin(s) to install (short name or @vibecontrols/...)").option("--json","Emit JSON").action(async(t,r)=>{try{let h={...P.opts(),...r},O=C(),E=new Set(Y.map((oe)=>oe.key)),N=(t??[]).map((oe)=>oe.trim().toLowerCase()).filter((oe)=>E.has(oe));for(let oe of(t??[]).filter((K)=>!E.has(K.trim().toLowerCase())))p(`Unknown capability "${oe}" \u2014 see \`vibe capability list\`.`);let T=(Array.isArray(r.provider)?r.provider:r.provider?[r.provider]:[]).map((oe)=>Ue(oe)).filter((oe)=>Boolean(oe));if(N.length===0&&T.length===0){s("Provide at least one capability key or --provider <pkg>.");return}let x=Kt(O);for(let oe of N)x.add(oe);let L=[...new Set([...qt(N),...T])],Z=await Wt(),B=[];for(let oe of L)try{await Z.install(oe),B.push({package:oe,ok:!0})}catch(K){B.push({package:oe,ok:!1,error:A(K)})}let V=[...new Set([...Ot(O),...T])];if(ut(O,{abilities:x,providers:V}),u(h,{ok:!0,action:"enable",abilities:[...x],providers:V,installed:B}))return;for(let oe of B)if(oe.ok)l(`Installed ${oe.package}`);else p(`Failed to install ${oe.package}: ${oe.error}`);l("Capabilities updated. Restart the agent to load: vibe restart")}catch(h){s(A(h))}}),a.command("disable").description("Disable capabilities (removes their meta plugin)").argument("<keys...>","Ability keys").option("--json","Emit JSON").action(async(t,r)=>{try{let h={...P.opts(),...r},O=C(),E=new Set(Y.map((B)=>B.key)),N=new Set(Y.filter((B)=>B.mandatory).map((B)=>B.key)),j=(t??[]).map((B)=>B.trim().toLowerCase()).filter((B)=>E.has(B));for(let B of j.filter((V)=>N.has(V)))p(`"${B}" is required and cannot be disabled.`);let T=j.filter((B)=>!N.has(B));if(T.length===0){s("Nothing to disable.");return}let x=Kt(O);for(let B of T)x.delete(B);let L=await Wt(),Z=[];for(let B of qt(T))try{await L.remove(B),Z.push({package:B,ok:!0})}catch(V){Z.push({package:B,ok:!1,error:A(V)})}if(ut(O,{abilities:x}),u(h,{ok:!0,action:"disable",abilities:[...x],removed:Z}))return;for(let B of Z)if(B.ok)l(`Removed ${B.package}`);else p(`Failed to remove ${B.package}: ${B.error}`);l("Capabilities updated. Restart the agent to apply: vibe restart")}catch(h){s(A(h))}}),a.command("select").description("Re-run the interactive capability selector and apply it").option("--json","Emit JSON").action(async(t)=>{try{let r={...P.opts(),...t},h=C(),O=await nr(),E=await Wt();for(let N of qt(O))try{await E.install(N)}catch{}if(ut(h,{abilities:O}),u(r,{ok:!0,action:"select",abilities:[...O]}))return;l(`Selection saved (${[...O].join(", ")||"none"}). Restart to apply: vibe restart`)}catch(r){s(A(r))}})}function Mr(P){en(P),tn(P),nn(P),an(P),ln(P),dn(P),un(P),pn(P),Cn(P),Dr(P),On(P),Dn(P),Tn(P),Gn(P),Vn(P),Kn(P),zn(P),Yn(P),Xn(P),Qn(P),eo(P),to(P),ro(P),io(P),so(P),ao(P),lo(P),uo(P),po(P),mo(P)}
115
+ `)}));await Q({title:`${t} \u2014 ${O.length} session(s)`,rows:E})},json:(O)=>ti(O)})}function uo(P){let a=P.command("session").description("Manage terminal sessions");a.command("system").description("List system sessions (alias for `session list --system`)").option("--agent-url <url>","Agent URL",Oe).option("--json","Emit JSON").option("--plain","Force plain text output").action(async function(t){let r={...P.opts(),...t};try{let h=f(t),O=encodeURIComponent(m(r));await co(h,`/api/profiles/${O}/sessions/system`,"System Sessions","No system sessions found.",r)}catch(h){s(A(h))}}),a.command("list").description("List all sessions").option("--system","Show system sessions instead of user sessions").option("--agent-url <url>","Agent URL",Oe).option("--json","Emit JSON").option("--plain","Force plain text output").action(async function(t){let r={...P.opts(),...t};try{let h=f(t),O=encodeURIComponent(m(r)),E=t.system?`/api/profiles/${O}/sessions/system`:`/api/profiles/${O}/sessions`;await co(h,E,"Sessions","No sessions found.",r)}catch(h){s(A(h))}}),a.command("create").description("Create a new session").requiredOption("--name <name>","Session name").option("--project <id>","Project ID","default").option("--command <cmd>","Initial command to run").option("--cwd <dir>","Working directory").option("--agent-url <url>","Agent URL",Oe).option("--json","Emit JSON").action(async function(t){let r={...P.opts(),...t};try{let h=f(t),O=encodeURIComponent(m(r)),E={sessionName:t.name,projectId:t.project};if(t.command)E.command=t.command;if(t.cwd)E.startDirectory=t.cwd;let N=await q(h,`/api/profiles/${O}/sessions/create`,E),j=N?.session?.id||N?.id||N?.sessionId;if(u(r,{ok:!0,id:j,name:t.name,project:t.project}))return;l(`Session created: ${H(j)}`),n("Name",t.name),n("Project",t.project)}catch(h){if(r.json){u(r,{ok:!1,error:A(h)});return}s(A(h))}}),a.command("kill").description("Kill a session").requiredOption("-i, --id <id>","Session ID").option("--agent-url <url>","Agent URL",Oe).option("--json","Emit JSON").action(async function(t){let r={...P.opts(),...t};try{let h=f(t),O=encodeURIComponent(m(r));if(await ge(h,`/api/profiles/${O}/sessions/${t.id}`),u(r,{ok:!0,id:t.id}))return;l(`Session ${H(t.id)} killed.`)}catch(h){if(r.json){u(r,{ok:!1,error:A(h)});return}s(A(h))}}),a.command("exec").description("Execute a command in a session").requiredOption("-i, --id <id>","Session ID").requiredOption("-c, --command <cmd>","Command to execute").option("--agent-url <url>","Agent URL",Oe).option("--json","Emit JSON").action(async function(t){let r={...P.opts(),...t};try{let h=f(t),O=encodeURIComponent(m(r)),E=await q(h,`/api/profiles/${O}/sessions/${t.id}/command`,{command:t.command});if(u(r,{ok:!0,id:t.id,output:E?.output??null}))return;if(l("Command executed."),E?.output)c(),console.log(E.output)}catch(h){if(r.json){u(r,{ok:!1,error:A(h)});return}s(A(h))}}),a.command("capture").description("Capture session terminal output").requiredOption("-i, --id <id>","Session ID").option("--agent-url <url>","Agent URL",Oe).option("--json","Emit JSON").option("--plain","Force plain text output").action(async function(t){let r={...P.opts(),...t};try{let h=f(t),O=encodeURIComponent(m(r));await y({mode:_(r),fetchData:()=>S(h,`/api/profiles/${O}/sessions/${t.id}/capture`),plain:(E)=>{if(E?.content||E?.output)console.log(E.content||E.output);else o("No capture data available.")},json:(E)=>({id:t.id,content:E?.content??E?.output??null})})}catch(h){s(A(h))}}),a.command("keys").description("Send keys to a session").requiredOption("-i, --id <id>","Session ID").requiredOption("-k, --keys <keys>","Keys to send").option("--agent-url <url>","Agent URL",Oe).option("--json","Emit JSON").action(async function(t){let r={...P.opts(),...t};try{let h=f(t),O=encodeURIComponent(m(r));if(await q(h,`/api/profiles/${O}/sessions/${t.id}/keys`,{keys:t.keys}),u(r,{ok:!0,id:t.id}))return;l("Keys sent.")}catch(h){if(r.json){u(r,{ok:!1,error:A(h)});return}s(A(h))}}),a.command("interrupt").description("Send interrupt signal to a session").requiredOption("-i, --id <id>","Session ID").option("--agent-url <url>","Agent URL",Oe).option("--json","Emit JSON").action(async function(t){let r={...P.opts(),...t};try{let h=f(t),O=encodeURIComponent(m(r));if(await q(h,`/api/profiles/${O}/sessions/${t.id}/interrupt`,{}),u(r,{ok:!0,id:t.id}))return;l(`Session ${H(t.id)} interrupted.`)}catch(h){if(r.json){u(r,{ok:!1,error:A(h)});return}s(A(h))}}),a.command("rename").description("Rename a session").requiredOption("-i, --id <id>","Session ID").requiredOption("--name <name>","New session name").option("--agent-url <url>","Agent URL",Oe).option("--json","Emit JSON").action(async function(t){let r={...P.opts(),...t};try{let h=f(t),O=encodeURIComponent(m(r));if(await Te(h,`/api/profiles/${O}/sessions/${t.id}/rename`,{newName:t.name}),u(r,{ok:!0,id:t.id,name:t.name}))return;l(`Session ${H(t.id)} renamed to "${t.name}".`)}catch(h){if(r.json){u(r,{ok:!1,error:A(h)});return}s(A(h))}}),a.command("toggle-mouse").description("Toggle mouse support in a session").requiredOption("-i, --id <id>","Session ID").option("--agent-url <url>","Agent URL",Oe).option("--json","Emit JSON").action(async function(t){let r={...P.opts(),...t};try{let h=f(t),O=encodeURIComponent(m(r)),E=await q(h,`/api/profiles/${O}/sessions/${t.id}/toggle-mouse`,{});if(u(r,{ok:!0,id:t.id,mouseEnabled:!!E?.mouseEnabled}))return;l(`Mouse support ${E?.mouseEnabled?"enabled":"toggled"} for session ${H(t.id)}.`)}catch(h){if(r.json){u(r,{ok:!1,error:A(h)});return}s(A(h))}}),a.command("terminal-start").description("Start terminal for a session").requiredOption("-i, --id <id>","Session ID").option("--agent-url <url>","Agent URL",Oe).option("--json","Emit JSON").action(async function(t){let r={...P.opts(),...t};try{let h=f(t),O=encodeURIComponent(m(r)),E=await q(h,`/api/profiles/${O}/sessions/${t.id}/terminal`,{});if(u(r,{ok:!0,id:t.id,port:E?.port??null}))return;if(l(`Terminal started for session ${H(t.id)}.`),E?.port)n("Port",E.port)}catch(h){if(r.json){u(r,{ok:!1,error:A(h)});return}s(A(h))}}),a.command("terminal-stop").description("Stop terminal for a session").requiredOption("-i, --id <id>","Session ID").option("--agent-url <url>","Agent URL",Oe).option("--json","Emit JSON").action(async function(t){let r={...P.opts(),...t};try{let h=f(t),O=encodeURIComponent(m(r));if(await q(h,`/api/profiles/${O}/sessions/${t.id}/terminal/stop`,{}),u(r,{ok:!0,id:t.id}))return;l(`Terminal stopped for session ${H(t.id)}.`)}catch(h){if(r.json){u(r,{ok:!1,error:A(h)});return}s(A(h))}}),a.command("health-check").description("Run health check on all sessions").option("--agent-url <url>","Agent URL",Oe).option("--json","Emit JSON").action(async function(t){let r={...P.opts(),...t};try{let h=f(t),O=encodeURIComponent(m(r)),E=await S(h,`/api/profiles/${O}/sessions`),N=await q(h,`/api/profiles/${O}/sessions/health-check`,{sessionIds:(E.sessions||[]).map((j)=>j.id)});if(u(r,{ok:!0,healthy:N?.healthy??null,checked:N?.checked??null,fixed:N?.fixed??null}))return;if(l("Health check completed."),N?.healthy!==void 0)n("Healthy",N.healthy);if(N?.checked!==void 0)n("Checked",N.checked);if(N?.fixed!==void 0)n("Fixed",N.fixed)}catch(h){if(r.json){u(r,{ok:!1,error:A(h)});return}s(A(h))}})}function po(P){P.command("reuse-db").description("Point this agent at an EXISTING database (reuse data from another same-workspace agent)").option("--adapter <name>","Storage adapter to use (e.g. postgres, skalex). Defaults to the configured/default adapter.").option("--connection-string <conn>","Connection string for the adapter (e.g. postgres://user:pass@host/db)").option("--storage-options <json>","Raw adapter options as a JSON object (alternative/in addition to --connection-string)").option("--db-path <path>","Data directory the adapter should use (e.g. an existing Skalex agent-db dir)").option("-y, --yes","Skip the confirmation prompt").option("--json","Emit JSON").action(async function(a){let t={...P.opts(),...a};try{let r={};if(a.storageOptions){let E;try{E=JSON.parse(a.storageOptions)}catch{s("--storage-options must be valid JSON.");return}if(!E||typeof E!=="object"||Array.isArray(E)){s("--storage-options must be a JSON object.");return}for(let[N,j]of Object.entries(E))r[N]=typeof j==="string"?j:JSON.stringify(j)}if(a.connectionString)r.connectionString=String(a.connectionString);if(!a.adapter&&!a.dbPath&&Object.keys(r).length===0){s("Nothing to set. Provide --adapter with --connection-string (or --storage-options), and/or --db-path.");return}if(!t.json){if(g("Reuse an existing database"),a.adapter)n("Adapter",i.bold(a.adapter));if(a.dbPath)n("Data path",i.bold(a.dbPath));if(Object.keys(r).length>0)n("Options",i.dim(Object.keys(r).join(", ")));c(),p(`${d.warning} Reuse is safe ONLY for a database from the SAME workspace \u2014 the encryption key is per-workspace, so a foreign DB won't decrypt (the agent will go degraded).`),p(`${d.warning} Two agents writing the same database concurrently can corrupt it. Keep this a single-writer setup unless your adapter is explicitly configured for shared writes.`),c()}if(!a.yes&&!t.json){if(!await le(i.bold("Write this storage configuration to the agent config?"))){o("Cancelled.");return}}let h={};if(a.adapter)h.storageAdapter=String(a.adapter);if(Object.keys(r).length>0)h.storageOptions=r;if(a.dbPath)h.dbPath=String(a.dbPath);M(h);let O=w();if(u(t,{ok:!0,storageAdapter:O.storageAdapter??null,dbPath:O.dbPath??null,storageOptionKeys:Object.keys(O.storageOptions??{})}))return;l(`${d.success} Storage configuration written. Run ${i.bold("vibe restart")} so the agent connects to the existing database.`)}catch(r){let h=r instanceof Error?A(r):String(r);if(t.json){u(t,{ok:!1,error:h});return}s(`reuse-db failed: ${h}`)}})}function Kt(P){return new Set([...Ze(P)??sr()])}function qt(P){return Ce(process.platform,new Set(P)).map((a)=>a.packageName)}async function Wt(){let{PluginManager:P}=await import("./plugin-system-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
116
  export{Pr,Mr};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{z,ci,Wt,xt,T,O,C,N,e,at}from"./index-7wm4bqx5.js";import{M,X}from"./index-j99tkngg.js";import{Ae,W}from"./index-awj0w14r.js";import{K}from"./index-qzwbctkv.js";import{_t}from"./index-p7fbnfwd.js";import{xe,Ie,ve}from"./index-qqnb0axh.js";import{b}from"./index-w4jqdhc2.js";import{existsSync as Ja,readFileSync as Ya}from"fs";import{dirname as wi,join as Qa}from"path";import{fileURLToPath as Za}from"url";import{closeSync as eo,existsSync as to,mkdirSync as io,openSync as ro,readFileSync as so,unlinkSync as $r,writeFileSync as no}from"fs";import{join as ao}from"path";import oo from"crypto";import it from"path";import G from"fs";import Ai from"zlib";import lo from"http";import{closeSync as co,existsSync as uo,mkdirSync as ho,openSync as fo,readFileSync as _o,unlinkSync as kr,writeFileSync as po}from"fs";import{join as go}from"path";import mo from"crypto";import rt from"path";import H from"fs";import vi from"zlib";import yo from"http";import{closeSync as wo,existsSync as Ao,mkdirSync as vo,openSync as Eo,readFileSync as xo,unlinkSync as Dr,writeFileSync as So}from"fs";import{join as Io}from"path";import bo from"crypto";import st from"path";import J from"fs";import Ei from"zlib";import To from"http";import{closeSync as Oo,existsSync as Ro,mkdirSync as Co,openSync as No,readFileSync as $o,unlinkSync as Lr,writeFileSync as ko}from"fs";import{join as Do}from"path";import Lo from"crypto";import nt from"path";import Y from"fs";import xi from"zlib";import Po from"http";function Mo(){let t=Date.now().toString(16),i;try{i=oo.randomBytes(8).toString("hex")}catch{let r=new Uint8Array(8);crypto.getRandomValues(r),i=Array.from(r).map((s)=>s.toString(16).padStart(2,"0")).join("")}return`${t}${i}`}function Pr(t,i){let r=t instanceof Error?t.message:t;if(i==="error")console.error(r);else console.log(r)}var Mr=new Set(["__proto__","constructor","prototype"]);function ti(t,i){if(!i.includes(".")){if(Mr.has(i))return;return t[i]}let r=t;for(let s of i.split(".")){if(Mr.has(s))return;if(r==null)return;r=r[s]}return r}class Je extends Error{constructor(t,i,r={}){super(i);this.name=this.constructor.name,this.code=t,this.details=r}}class D extends Je{}class De extends Je{}class Ce extends Je{}class Ve extends Je{}class be extends Je{}class ut extends Je{}function $i(t,i){if(t===i)return!0;if(t==null||i==null)return!1;if(typeof t!==typeof i)return!1;if(t instanceof Date&&i instanceof Date)return t.getTime()===i.getTime();if(t instanceof RegExp&&i instanceof RegExp)return t.source===i.source&&t.flags===i.flags;if(Array.isArray(t)){if(!Array.isArray(i)||t.length!==i.length)return!1;for(let r=0;r<t.length;r++)if(!$i(t[r],i[r]))return!1;return!0}if(typeof t==="object"){if(Array.isArray(i))return!1;let r=Object.keys(t);if(r.length!==Object.keys(i).length)return!1;for(let s of r){if(!Object.prototype.hasOwnProperty.call(i,s))return!1;if(!$i(t[s],i[s]))return!1}return!0}return!1}function ie(t,i){if(typeof i==="function")return i(t);if(i==null)return!0;if(typeof i==="object"&&Object.keys(i).length===0)return!0;if("$or"in i){let r=i.$or;if(!Array.isArray(r))throw new ut("ERR_SKALEX_QUERY_INVALID_OPERATOR","$or must be an array of filters",{operator:"$or"});if(!r.some((s)=>ie(t,s)))return!1}if("$and"in i){let r=i.$and;if(!Array.isArray(r))throw new ut("ERR_SKALEX_QUERY_INVALID_OPERATOR","$and must be an array of filters",{operator:"$and"});if(!r.every((s)=>ie(t,s)))return!1}if("$not"in i){if(ie(t,i.$not))return!1}for(let r in i){if(r==="$or"||r==="$and"||r==="$not")continue;let s=i[r],n;try{n=ti(t,r)}catch{return!1}if(s instanceof RegExp){if(!s.test(String(n)))return!1}else if(typeof s==="object"&&s!==null){if(Object.keys(s).some((a)=>a.startsWith("$"))){if("$eq"in s&&n!==s.$eq)return!1;if("$ne"in s&&n===s.$ne)return!1;if("$gt"in s&&!(n>s.$gt))return!1;if("$lt"in s&&!(n<s.$lt))return!1;if("$gte"in s&&!(n>=s.$gte))return!1;if("$lte"in s&&!(n<=s.$lte))return!1;if("$in"in s&&!s.$in.includes(n))return!1;if("$nin"in s&&s.$nin.includes(n))return!1;if("$regex"in s){if(!(s.$regex instanceof RegExp?s.$regex:new RegExp(s.$regex)).test(String(n)))return!1}if("$fn"in s&&!s.$fn(n))return!1}else if(!$i(n,s))return!1}else if(n!==s)return!1}return!0}function jo(t,i=new Set){if(typeof t!=="object"||t===null||typeof t==="function")return t;let r=[],s=[],n=[],a=[],o=[];for(let l in t){if(l==="$or"||l==="$and"||l==="$not"){o.push(l);continue}let d=t[l];if(i.has(l))r.push(l);else if(d instanceof RegExp||typeof d==="object"&&d!==null&&(("$regex"in d)||("$fn"in d))||typeof d==="function")a.push(l);else if(typeof d==="object"&&d!==null&&(("$gt"in d)||("$lt"in d)||("$gte"in d)||("$lte"in d)||("$ne"in d)||("$in"in d)||("$nin"in d)))n.push(l);else s.push(l)}let c={};for(let l of[...r,...s,...n,...a,...o])c[l]=t[l];return c}var ki=new Set(["string","number","boolean","object","array","date","any"]);function Ui(t){if(Array.isArray(t))return"array";if(t instanceof Date)return"date";return typeof t}function Ls(t){let i=new Map,r=[];for(let[s,n]of Object.entries(t)){let a;if(typeof n==="string"){if(!ki.has(n))throw new D("ERR_SKALEX_VALIDATION_UNKNOWN_TYPE",`Unknown schema type "${n}" for field "${s}"`,{field:s,type:n});a={type:n,required:!1,unique:!1}}else if(typeof n==="object"&&n!==null){let{type:o="any",required:c=!1,unique:l=!1,enum:d}=n;if(!ki.has(o))throw new D("ERR_SKALEX_VALIDATION_UNKNOWN_TYPE",`Unknown schema type "${o}" for field "${s}"`,{field:s,type:o});if(a={type:o,required:c,unique:l,enum:d},l)r.push(s)}else throw new D("ERR_SKALEX_VALIDATION_INVALID_SCHEMA",`Invalid schema definition for field "${s}"`,{field:s});i.set(s,a)}return{fields:i,uniqueFields:r}}function jr(t,i,r=!1){let s=[];for(let[n,a]of i){let o=t[n],c=o===void 0||o===null;if(a.required&&c){s.push(`Field "${n}" is required`);continue}if(c)continue;if(a.type!=="any"){let l=Ui(o);if(l!==a.type)s.push(`Field "${n}" must be of type "${a.type}", got "${l}"`)}if(a.enum&&!a.enum.includes(o))s.push(`Field "${n}" must be one of [${a.enum.map((l)=>JSON.stringify(l)).join(", ")}], got ${JSON.stringify(o)}`)}if(r){for(let n of Object.keys(t))if(!n.startsWith("_")&&!i.has(n))s.push(`Unknown field "${n}" (strict mode)`)}return s}function qr(t,i){let r={};for(let[s,n]of Object.entries(t)){if(s.startsWith("_")){r[s]=n;continue}if(!i.has(s))continue;let a=i.get(s);if(a.type!=="any"){if(Ui(n)!==a.type)continue}if(a.enum&&!a.enum.includes(n))continue;r[s]=n}return r}function qo(t){let i={};for(let[r,s]of Object.entries(t)){if(r.startsWith("_"))continue;let n=Ui(s);i[r]=ki.has(n)?n:"any"}return i}function Uo(t){if(typeof t==="number"){if(t<=0)throw new D("ERR_SKALEX_VALIDATION_TTL",`TTL must be positive, got ${t}`,{ttl:t});return t*1000}if(typeof t!=="string")throw new D("ERR_SKALEX_VALIDATION_TTL",`Invalid TTL value: ${t}`,{ttl:t});let i=t.match(/^(\d+(?:\.\d+)?)(ms|s|m|h|d)$/);if(!i)throw new D("ERR_SKALEX_VALIDATION_TTL_FORMAT",`Invalid TTL format: "${t}". Use e.g. 300 (seconds), "30m", "24h", "7d"`,{ttl:t});let r=parseFloat(i[1]);if(r<=0)throw new D("ERR_SKALEX_VALIDATION_TTL",`TTL must be positive, got "${t}"`,{ttl:t});let s=i[2],n=r*{ms:1,s:1000,m:60000,h:3600000,d:86400000}[s];if(!isFinite(n))throw new D("ERR_SKALEX_VALIDATION_TTL",`TTL value "${t}" is too large`,{ttl:t});return n}function Fo(t){return new Date(Date.now()+Uo(t))}function Ko(t,i,r=null){let s=Date.now(),n=0,a=t.length;while(a--){let o=t[a];if(o._expiresAt&&new Date(o._expiresAt).getTime()<=s){if(t.splice(a,1),i.delete(o._id),r)r(o);n++}}return n}function Ur(t,i){if(t.length!==i.length)throw new ut("ERR_SKALEX_QUERY_VECTOR_MISMATCH",`Vector dimension mismatch: ${t.length} vs ${i.length}`,{expected:t.length,got:i.length});let r=0,s=0,n=0;for(let o=0;o<t.length;o++)r+=t[o]*i[o],s+=t[o]*t[o],n+=i[o]*i[o];let a=Math.sqrt(s*n);return a===0?0:r/a}function Q(t){if(!("_vector"in t))return{...t};let{_vector:i,...r}=t;return r}function zo(t){return t.length}function Bo(t,i){let r=0;for(let s of t){let n=ti(s,i);if(typeof n==="number"&&!isNaN(n))r+=n}return r}function Xo(t,i){let r=0,s=0;for(let n of t){let a=ti(n,i);if(typeof a==="number"&&!isNaN(a))r+=a,s++}return s===0?null:r/s}function Vo(t,i){let r=Object.create(null);for(let s of t){let n=String(ti(s,i)??"__null__");if(!r[n])r[n]=[];r[n].push(s)}return r}class Ps{constructor(t){this._col=t}get _ctx(){return this._col._ctx}async execute({op:t,beforeHook:i,afterHook:r,hookPayload:s,mutate:n,afterHookPayload:a,save:o,session:c}){let l=this._ctx;await l.ensureConnected(),this._col._txSnapshotIfNeeded();let d=l.txManager,u=d.active&&this._col._activeTxId===d.context?.id,f=u?d.context.id:null,h=this._col._createdInTxId,_=()=>{if(f!==null&&d._abortedIds.has(f))throw new Ce("ERR_SKALEX_TX_ABORTED",`Transaction ${f} was aborted. No further mutations allowed.`);if(h!==null&&d._abortedIds.has(h))throw new Ce("ERR_SKALEX_TX_ABORTED",`Transaction ${h} was aborted. Collection obtained inside that transaction cannot be used for further mutations.`)};if(u||h!==null)_();if(i)await l.plugins.run(i,s);let{docs:p,prevDocs:g=[]}=await n(_);if(l.persistence.markDirty(l.collections,this._col.name),await this._col._saveIfNeeded(o),this._col._changelogEnabled)for(let m=0;m<p.length;m++)await l.logChange(t,this._col.name,p[m],g[m]??null,c||null);if(!u||!d.defer(()=>l.sessionStats.recordWrite(c)))l.sessionStats.recordWrite(c);for(let m of p)l.emitEvent(this._col.name,{op:t,collection:this._col.name,doc:Q(m)});if(r)if(a)await l.runAfterHook(r,a(p));else for(let m of p)await l.runAfterHook(r,{collection:this._col.name,doc:Q(m)});return{docs:p,prevDocs:g}}}function Go(t){let i={};for(let r in t){if(r.startsWith("$"))continue;let s=t[r];if(s&&typeof s==="object"&&!Array.isArray(s)){let n=Object.keys(s);if(n.length===1&&n[0]==="$eq")i[r]=s.$eq}else i[r]=s}return i}var Ms=new Set(["__proto__","constructor","prototype"]);function js(t){if(typeof t!=="object"||t===null||Array.isArray(t))return t;let i={};for(let r of Object.keys(t)){if(Ms.has(r))continue;i[r]=js(t[r])}return i}class qs{constructor(t,i){this.name=t.collectionName,this.database=i,this._ctx=i._buildCollectionContext(),this._store=t,this._pipeline=new Ps(this),this._createdInTxId=i._txManager.context?.id??null,this._activeTxId=null}get _data(){return this._store.data}set _data(t){this._store.data=t}get _index(){return this._store.index}get _fieldIndex(){return this._store.fieldIndex||null}get _schema(){return this._store.schema?this._store.schema.fields:null}get _changelogEnabled(){return this._store.changelog===!0}get _softDelete(){return this._store.softDelete===!0}get _versioning(){return this._store.versioning===!0}get _strict(){return this._store.strict===!0}get _onSchemaError(){return this._store.onSchemaError??"throw"}get _defaultTtl(){return this._store.defaultTtl||null}get _defaultEmbed(){return this._store.defaultEmbed||null}get _maxDocs(){return this._store.maxDocs||null}async insertOne(t,i={}){let{save:r,ifNotExists:s,ttl:n,embed:a,session:o}=i;if(s){await this._ctx.ensureConnected();let l=this._findRaw(t);if(l)return Q({...l})}let{docs:c}=await this._insertCore([t],{ttl:n,embed:a,session:o,save:r});return Q(c[0])}async insertMany(t,i={}){let{save:r,ttl:s,embed:n,session:a}=i,{docs:o}=await this._insertCore(t,{ttl:s,embed:n,session:a,save:r});return o.map(Q)}async _insertCore(t,{ttl:i,embed:r,session:s,save:n}){return this._pipeline.execute({op:"insert",beforeHook:null,afterHook:"afterInsert",hookPayload:null,save:n,session:s,mutate:async(a)=>{let o=[],c=new Set;for(let l of t){let d=this._applyValidation(l);await this._ctx.plugins.run("beforeInsert",{collection:this.name,doc:d});let u=await this._buildDoc(d,{ttl:i,embed:r});if(this._index.has(u._id)||c.has(u._id))throw new De("ERR_SKALEX_UNIQUE_DUPLICATE_ID",`Duplicate _id "${u._id}" in collection "${this.name}"`,{id:u._id,collection:this.name});c.add(u._id),o.push(u)}if(a(),this._fieldIndex)this._fieldIndex.assertUniqueBatch(o);for(let l of o)this._addToIndex(l);this._data.push(...o);for(let l of o)this._index.set(l._id,l);return this._enforceCapAfterInsert(),{docs:o}}})}async updateOne(t,i,r={}){await this._ctx.ensureConnected();let s=this._findRaw(t);if(!s)return null;let{save:n,session:a}=r,{docs:o}=await this._updateCore([s],t,i,{save:n,session:a});return Q(o[0])}async updateMany(t,i,r={}){await this._ctx.ensureConnected();let s=this._findAllRaw(t);if(s.length===0)return[];let{save:n,session:a}=r,{docs:o}=await this._updateCore(s,t,i,{save:n,session:a});return o.map(Q)}async _updateCore(t,i,r,{save:s,session:n}){return this._pipeline.execute({op:"update",beforeHook:"beforeUpdate",afterHook:"afterUpdate",hookPayload:{collection:this.name,filter:i,update:r},save:s,session:n,afterHookPayload:(a)=>({collection:this.name,filter:i,update:r,result:a.length===1?a[0]:a}),mutate:async(a)=>{let o=this._changelogEnabled?t.map((u)=>structuredClone(u)):t.map(()=>null),c=t.map((u)=>this._prepareUpdatedDoc(u,r));this._assertUniqueCandidates(t,c),a();let l=new Set(t),d=new Map;for(let u=0;u<this._data.length;u++)if(l.has(this._data[u]))d.set(this._data[u],u);for(let u=0;u<t.length;u++)this._commitUpdatedDoc(t[u],c[u],d);return{docs:c,prevDocs:o}}})}applyUpdate(t,i){for(let r in i){if(Ms.has(r))continue;if(r==="_id"||r==="createdAt")continue;let s=i[r];if(Array.isArray(s))t[r]=s;else if(typeof s==="object"&&s!==null){let n=Object.keys(s);if(n.some((a)=>a.startsWith("$"))){for(let a of n)if(a==="$inc"&&typeof t[r]==="number")t[r]+=s[a];else if(a==="$push"){if(!Array.isArray(t[r]))t[r]=[];t[r].push(s[a])}}else t[r]=js(s)}else t[r]=s}if(t.updatedAt=new Date,this._versioning)t._version=(t._version??0)+1;return t}_prepareUpdatedDoc(t,i){let r=structuredClone(t),s=structuredClone(t);if(this.applyUpdate(s,i),!this._schema)return s;let n=jr(s,this._schema,this._strict);if(!n.length)return s;switch(this._onSchemaError){case"throw":throw new D("ERR_SKALEX_VALIDATION_UPDATE",`Update validation failed on doc "${t._id}": ${n.join("; ")}`,{id:t._id,errors:n});case"strip":return this._stripCandidateToValid(s,r);default:return this._ctx.logger(`[${this.name}] Update validation warning: ${n.join("; ")}`,"warn"),s}}_stripCandidateToValid(t,i){let r=qr(t,this._schema),s=structuredClone(i);for(let[n,a]of Object.entries(r)){if(n.startsWith("_"))continue;s[n]=a}if(s.updatedAt=t.updatedAt,this._versioning)s._version=t._version;return s}_commitUpdatedDoc(t,i,r){let s=r?r.get(t):this._data.indexOf(t);if(s===void 0||s===-1)throw new Ve("ERR_SKALEX_PERSISTENCE_DOC_MISSING",`Document "${t._id}" no longer exists in collection "${this.name}"`,{id:t._id,collection:this.name});this._data[s]=i,this._index.set(i._id,i),this._updateInIndex(t,i)}_assertUniqueCandidates(t,i){this._fieldIndex?.assertUniqueCandidates(t,i)}async upsert(t,i,r={}){if(await this._ctx.ensureConnected(),this._findRaw(t))return this.updateOne(t,i,r);return this.insertOne({...Go(t),...i},r)}async upsertMany(t,i,r={}){await this._ctx.ensureConnected();let{save:s,...n}=r,a=[];for(let o of t)a.push(await this.upsert({[i]:o[i]},o,{...n,save:!1}));return await this._saveIfNeeded(s),a}async restore(t,i={}){if(!this._softDelete)throw new ut("ERR_SKALEX_QUERY_SOFT_DELETE_REQUIRED",`restore() requires softDelete on "${this.name}"`,{collection:this.name});await this._ctx.ensureConnected();let{save:r,session:s}=i,n=this._findRaw(t,{includeDeleted:!0});if(!n||!n._deletedAt)return null;let{docs:a}=await this._pipeline.execute({op:"restore",beforeHook:null,afterHook:null,hookPayload:null,save:r,session:s,mutate:async(o)=>(o(),delete n._deletedAt,n.updatedAt=new Date,this._index.set(n._id,n),{docs:[n]})});return Q(a[0])}watch(t,i){if(typeof t==="function")i=t,t=null;if(i)return this._ctx.eventBus.on(this.name,(r)=>{if(!t||ie(r.doc,t))i(r)});return this._watchIterator(t)}_watchIterator(t){let i=[],r=null,s=!1,n=this._ctx.eventBus.on(this.name,(a)=>{if(t&&!ie(a.doc,t))return;if(r){let o=r;r=null,o({value:a,done:!1})}else i.push(a)});return{[Symbol.asyncIterator](){return this},next(){if(i.length>0)return Promise.resolve({value:i.shift(),done:!1});if(s)return Promise.resolve({value:void 0,done:!0});return new Promise((a)=>{r=a})},return(){if(s=!0,n(),r){let a=r;r=null,a({value:void 0,done:!0})}return Promise.resolve({value:void 0,done:!0})}}}async count(t={}){return await this._ctx.ensureConnected(),zo(this._findAllRaw(t))}async sum(t,i={}){return await this._ctx.ensureConnected(),Bo(this._findAllRaw(i),t)}async avg(t,i={}){return await this._ctx.ensureConnected(),Xo(this._findAllRaw(i),t)}async groupBy(t,i={}){return await this._ctx.ensureConnected(),Vo(this._findAllRaw(i),t)}async findOne(t,i={}){await this._ctx.ensureConnected();let{populate:r,select:s,includeDeleted:n=!1}=i,a=this._findRaw(t,{includeDeleted:n});if(!a)return null;let o=this._projectDoc(a,s);if(r)await this._populateDoc(o,a,r);return o}async find(t,i={}){await this._ctx.ensureConnected();let r=Date.now(),{populate:s,select:n,sort:a,page:o=1,limit:c,session:l,includeDeleted:d=!1}=i;await this._ctx.plugins.run("beforeFind",{collection:this.name,filter:t,options:i});let u=this._getCandidates(t),f=jo(t,this._fieldIndex?this._fieldIndex.indexedFields:new Set),h=[];for(let p of u){if(this._softDelete&&p._deletedAt&&!d)continue;if(!ie(p,f))continue;let g=this._projectDoc(p,n);if(s)await this._populateDoc(g,p,s);h.push(g)}if(a){let p=Object.keys(a);h.sort((g,m)=>{for(let w of p){let v=a[w];if(g[w]<m[w])return-v;if(g[w]>m[w])return v}return 0})}let _;if(c){let p=h.length,g=Math.ceil(p/c),m=(o-1)*c;h=h.slice(m,m+c),_={page:o,totalDocs:p,totalPages:g}}return this._ctx.queryLog?.record({collection:this.name,op:"find",filter:t,duration:Date.now()-r,resultCount:h.length}),this._ctx.sessionStats.recordRead(l),await this._ctx.plugins.run("afterFind",{collection:this.name,filter:t,options:i,docs:h}),_?{docs:h,..._}:{docs:h}}async search(t,{filter:i,limit:r=10,minScore:s=0,session:n}={}){await this._ctx.ensureConnected();let a=Date.now();await this._ctx.plugins.run("beforeSearch",{collection:this.name,query:t,options:{filter:i,limit:r,minScore:s}});let o=await this._ctx.embed(t),c=i?this._findAllRaw(i):this._data,l=[];for(let h of c){if(!h._vector)continue;let _=Ur(o,h._vector);if(_>=s)l.push({doc:h,score:_})}l.sort((h,_)=>_.score-h.score);let d=l.slice(0,r);this._ctx.queryLog?.record({collection:this.name,op:"search",query:t,duration:Date.now()-a,resultCount:d.length}),this._ctx.sessionStats.recordRead(n);let u=d.map((h)=>Q(h.doc)),f=d.map((h)=>h.score);return await this._ctx.plugins.run("afterSearch",{collection:this.name,query:t,options:{filter:i,limit:r,minScore:s},docs:u,scores:f}),{docs:u,scores:f}}async similar(t,{limit:i=10,minScore:r=0}={}){await this._ctx.ensureConnected();let s=this._index.get(t);if(!s||!s._vector)return{docs:[],scores:[]};let n=[];for(let o of this._data){if(o._id===t||!o._vector)continue;let c=Ur(s._vector,o._vector);if(c>=r)n.push({doc:o,score:c})}n.sort((o,c)=>c.score-o.score);let a=n.slice(0,i);return{docs:a.map((o)=>Q(o.doc)),scores:a.map((o)=>o.score)}}async deleteOne(t,i={}){await this._ctx.ensureConnected();let{save:r,session:s}=i;if(this._softDelete){let a=this._findRaw(t);if(!a)return null;let{docs:o}=await this._deleteCore("soft",[a],t,{save:r,session:s});return Q(o[0])}let{docs:n}=await this._deleteCore("hard",null,t,{save:r,session:s});if(n.length===0)return null;return Q(n[0])}async deleteMany(t,i={}){await this._ctx.ensureConnected();let{save:r,session:s}=i;if(this._softDelete){let a=this._findAllRaw(t);if(a.length===0)return[];let{docs:o}=await this._deleteCore("soft",a,t,{save:r,session:s});return o.map(Q)}let{docs:n}=await this._deleteCore("hardMany",null,t,{save:r,session:s});return n.map(Q)}async _deleteCore(t,i,r,{save:s,session:n}){return this._pipeline.execute({op:"delete",beforeHook:"beforeDelete",afterHook:"afterDelete",hookPayload:{collection:this.name,filter:r},save:s,session:n,afterHookPayload:(a)=>({collection:this.name,filter:r,result:a.length===1?a[0]:a}),mutate:async(a)=>{if(a(),t==="soft"){let l=new Date;for(let d of i)d._deletedAt=l,d.updatedAt=l,this._index.set(d._id,d);return{docs:i}}if(t==="hard"){let l=this._findIndex(r);if(l===-1)return{docs:[]};let d=this._data.splice(l,1)[0];return this._index.delete(d._id),this._removeFromIndex(d),{docs:[d]}}let o=[],c=[];for(let l of this._data)if(ie(l,r))o.push(l),this._index.delete(l._id),this._removeFromIndex(l);else c.push(l);return this._data=c,{docs:o}}})}async export(t={},i={}){let{dir:r,name:s,format:n="json"}=i;try{let a=this._data.filter((u)=>ie(u,t));if(a.length===0)throw new ut("ERR_SKALEX_QUERY_EXPORT_EMPTY",`export(): no documents matched the filter in "${this.name}"`,{collection:this.name});let o;if(n==="json")o=JSON.stringify(a,null,2);else{let u=(_)=>{if(_==null)return"";let p=typeof _==="object"?JSON.stringify(_):String(_);return p.includes(",")||p.includes('"')||p.includes(`
2
+ import{z,ci,Wt,xt,T,O,C,N,e,at}from"./index-7wm4bqx5.js";import{M,X}from"./index-j99tkngg.js";import{Ae,W}from"./index-p1b10hs1.js";import{K}from"./index-qzwbctkv.js";import{_t}from"./index-p7fbnfwd.js";import{xe,Ie,ve}from"./index-6wfd7cv3.js";import{b}from"./index-w4jqdhc2.js";import{existsSync as Ja,readFileSync as Ya}from"fs";import{dirname as wi,join as Qa}from"path";import{fileURLToPath as Za}from"url";import{closeSync as eo,existsSync as to,mkdirSync as io,openSync as ro,readFileSync as so,unlinkSync as $r,writeFileSync as no}from"fs";import{join as ao}from"path";import oo from"crypto";import it from"path";import G from"fs";import Ai from"zlib";import lo from"http";import{closeSync as co,existsSync as uo,mkdirSync as ho,openSync as fo,readFileSync as _o,unlinkSync as kr,writeFileSync as po}from"fs";import{join as go}from"path";import mo from"crypto";import rt from"path";import H from"fs";import vi from"zlib";import yo from"http";import{closeSync as wo,existsSync as Ao,mkdirSync as vo,openSync as Eo,readFileSync as xo,unlinkSync as Dr,writeFileSync as So}from"fs";import{join as Io}from"path";import bo from"crypto";import st from"path";import J from"fs";import Ei from"zlib";import To from"http";import{closeSync as Oo,existsSync as Ro,mkdirSync as Co,openSync as No,readFileSync as $o,unlinkSync as Lr,writeFileSync as ko}from"fs";import{join as Do}from"path";import Lo from"crypto";import nt from"path";import Y from"fs";import xi from"zlib";import Po from"http";function Mo(){let t=Date.now().toString(16),i;try{i=oo.randomBytes(8).toString("hex")}catch{let r=new Uint8Array(8);crypto.getRandomValues(r),i=Array.from(r).map((s)=>s.toString(16).padStart(2,"0")).join("")}return`${t}${i}`}function Pr(t,i){let r=t instanceof Error?t.message:t;if(i==="error")console.error(r);else console.log(r)}var Mr=new Set(["__proto__","constructor","prototype"]);function ti(t,i){if(!i.includes(".")){if(Mr.has(i))return;return t[i]}let r=t;for(let s of i.split(".")){if(Mr.has(s))return;if(r==null)return;r=r[s]}return r}class Je extends Error{constructor(t,i,r={}){super(i);this.name=this.constructor.name,this.code=t,this.details=r}}class D extends Je{}class De extends Je{}class Ce extends Je{}class Ve extends Je{}class be extends Je{}class ut extends Je{}function $i(t,i){if(t===i)return!0;if(t==null||i==null)return!1;if(typeof t!==typeof i)return!1;if(t instanceof Date&&i instanceof Date)return t.getTime()===i.getTime();if(t instanceof RegExp&&i instanceof RegExp)return t.source===i.source&&t.flags===i.flags;if(Array.isArray(t)){if(!Array.isArray(i)||t.length!==i.length)return!1;for(let r=0;r<t.length;r++)if(!$i(t[r],i[r]))return!1;return!0}if(typeof t==="object"){if(Array.isArray(i))return!1;let r=Object.keys(t);if(r.length!==Object.keys(i).length)return!1;for(let s of r){if(!Object.prototype.hasOwnProperty.call(i,s))return!1;if(!$i(t[s],i[s]))return!1}return!0}return!1}function ie(t,i){if(typeof i==="function")return i(t);if(i==null)return!0;if(typeof i==="object"&&Object.keys(i).length===0)return!0;if("$or"in i){let r=i.$or;if(!Array.isArray(r))throw new ut("ERR_SKALEX_QUERY_INVALID_OPERATOR","$or must be an array of filters",{operator:"$or"});if(!r.some((s)=>ie(t,s)))return!1}if("$and"in i){let r=i.$and;if(!Array.isArray(r))throw new ut("ERR_SKALEX_QUERY_INVALID_OPERATOR","$and must be an array of filters",{operator:"$and"});if(!r.every((s)=>ie(t,s)))return!1}if("$not"in i){if(ie(t,i.$not))return!1}for(let r in i){if(r==="$or"||r==="$and"||r==="$not")continue;let s=i[r],n;try{n=ti(t,r)}catch{return!1}if(s instanceof RegExp){if(!s.test(String(n)))return!1}else if(typeof s==="object"&&s!==null){if(Object.keys(s).some((a)=>a.startsWith("$"))){if("$eq"in s&&n!==s.$eq)return!1;if("$ne"in s&&n===s.$ne)return!1;if("$gt"in s&&!(n>s.$gt))return!1;if("$lt"in s&&!(n<s.$lt))return!1;if("$gte"in s&&!(n>=s.$gte))return!1;if("$lte"in s&&!(n<=s.$lte))return!1;if("$in"in s&&!s.$in.includes(n))return!1;if("$nin"in s&&s.$nin.includes(n))return!1;if("$regex"in s){if(!(s.$regex instanceof RegExp?s.$regex:new RegExp(s.$regex)).test(String(n)))return!1}if("$fn"in s&&!s.$fn(n))return!1}else if(!$i(n,s))return!1}else if(n!==s)return!1}return!0}function jo(t,i=new Set){if(typeof t!=="object"||t===null||typeof t==="function")return t;let r=[],s=[],n=[],a=[],o=[];for(let l in t){if(l==="$or"||l==="$and"||l==="$not"){o.push(l);continue}let d=t[l];if(i.has(l))r.push(l);else if(d instanceof RegExp||typeof d==="object"&&d!==null&&(("$regex"in d)||("$fn"in d))||typeof d==="function")a.push(l);else if(typeof d==="object"&&d!==null&&(("$gt"in d)||("$lt"in d)||("$gte"in d)||("$lte"in d)||("$ne"in d)||("$in"in d)||("$nin"in d)))n.push(l);else s.push(l)}let c={};for(let l of[...r,...s,...n,...a,...o])c[l]=t[l];return c}var ki=new Set(["string","number","boolean","object","array","date","any"]);function Ui(t){if(Array.isArray(t))return"array";if(t instanceof Date)return"date";return typeof t}function Ls(t){let i=new Map,r=[];for(let[s,n]of Object.entries(t)){let a;if(typeof n==="string"){if(!ki.has(n))throw new D("ERR_SKALEX_VALIDATION_UNKNOWN_TYPE",`Unknown schema type "${n}" for field "${s}"`,{field:s,type:n});a={type:n,required:!1,unique:!1}}else if(typeof n==="object"&&n!==null){let{type:o="any",required:c=!1,unique:l=!1,enum:d}=n;if(!ki.has(o))throw new D("ERR_SKALEX_VALIDATION_UNKNOWN_TYPE",`Unknown schema type "${o}" for field "${s}"`,{field:s,type:o});if(a={type:o,required:c,unique:l,enum:d},l)r.push(s)}else throw new D("ERR_SKALEX_VALIDATION_INVALID_SCHEMA",`Invalid schema definition for field "${s}"`,{field:s});i.set(s,a)}return{fields:i,uniqueFields:r}}function jr(t,i,r=!1){let s=[];for(let[n,a]of i){let o=t[n],c=o===void 0||o===null;if(a.required&&c){s.push(`Field "${n}" is required`);continue}if(c)continue;if(a.type!=="any"){let l=Ui(o);if(l!==a.type)s.push(`Field "${n}" must be of type "${a.type}", got "${l}"`)}if(a.enum&&!a.enum.includes(o))s.push(`Field "${n}" must be one of [${a.enum.map((l)=>JSON.stringify(l)).join(", ")}], got ${JSON.stringify(o)}`)}if(r){for(let n of Object.keys(t))if(!n.startsWith("_")&&!i.has(n))s.push(`Unknown field "${n}" (strict mode)`)}return s}function qr(t,i){let r={};for(let[s,n]of Object.entries(t)){if(s.startsWith("_")){r[s]=n;continue}if(!i.has(s))continue;let a=i.get(s);if(a.type!=="any"){if(Ui(n)!==a.type)continue}if(a.enum&&!a.enum.includes(n))continue;r[s]=n}return r}function qo(t){let i={};for(let[r,s]of Object.entries(t)){if(r.startsWith("_"))continue;let n=Ui(s);i[r]=ki.has(n)?n:"any"}return i}function Uo(t){if(typeof t==="number"){if(t<=0)throw new D("ERR_SKALEX_VALIDATION_TTL",`TTL must be positive, got ${t}`,{ttl:t});return t*1000}if(typeof t!=="string")throw new D("ERR_SKALEX_VALIDATION_TTL",`Invalid TTL value: ${t}`,{ttl:t});let i=t.match(/^(\d+(?:\.\d+)?)(ms|s|m|h|d)$/);if(!i)throw new D("ERR_SKALEX_VALIDATION_TTL_FORMAT",`Invalid TTL format: "${t}". Use e.g. 300 (seconds), "30m", "24h", "7d"`,{ttl:t});let r=parseFloat(i[1]);if(r<=0)throw new D("ERR_SKALEX_VALIDATION_TTL",`TTL must be positive, got "${t}"`,{ttl:t});let s=i[2],n=r*{ms:1,s:1000,m:60000,h:3600000,d:86400000}[s];if(!isFinite(n))throw new D("ERR_SKALEX_VALIDATION_TTL",`TTL value "${t}" is too large`,{ttl:t});return n}function Fo(t){return new Date(Date.now()+Uo(t))}function Ko(t,i,r=null){let s=Date.now(),n=0,a=t.length;while(a--){let o=t[a];if(o._expiresAt&&new Date(o._expiresAt).getTime()<=s){if(t.splice(a,1),i.delete(o._id),r)r(o);n++}}return n}function Ur(t,i){if(t.length!==i.length)throw new ut("ERR_SKALEX_QUERY_VECTOR_MISMATCH",`Vector dimension mismatch: ${t.length} vs ${i.length}`,{expected:t.length,got:i.length});let r=0,s=0,n=0;for(let o=0;o<t.length;o++)r+=t[o]*i[o],s+=t[o]*t[o],n+=i[o]*i[o];let a=Math.sqrt(s*n);return a===0?0:r/a}function Q(t){if(!("_vector"in t))return{...t};let{_vector:i,...r}=t;return r}function zo(t){return t.length}function Bo(t,i){let r=0;for(let s of t){let n=ti(s,i);if(typeof n==="number"&&!isNaN(n))r+=n}return r}function Xo(t,i){let r=0,s=0;for(let n of t){let a=ti(n,i);if(typeof a==="number"&&!isNaN(a))r+=a,s++}return s===0?null:r/s}function Vo(t,i){let r=Object.create(null);for(let s of t){let n=String(ti(s,i)??"__null__");if(!r[n])r[n]=[];r[n].push(s)}return r}class Ps{constructor(t){this._col=t}get _ctx(){return this._col._ctx}async execute({op:t,beforeHook:i,afterHook:r,hookPayload:s,mutate:n,afterHookPayload:a,save:o,session:c}){let l=this._ctx;await l.ensureConnected(),this._col._txSnapshotIfNeeded();let d=l.txManager,u=d.active&&this._col._activeTxId===d.context?.id,f=u?d.context.id:null,h=this._col._createdInTxId,_=()=>{if(f!==null&&d._abortedIds.has(f))throw new Ce("ERR_SKALEX_TX_ABORTED",`Transaction ${f} was aborted. No further mutations allowed.`);if(h!==null&&d._abortedIds.has(h))throw new Ce("ERR_SKALEX_TX_ABORTED",`Transaction ${h} was aborted. Collection obtained inside that transaction cannot be used for further mutations.`)};if(u||h!==null)_();if(i)await l.plugins.run(i,s);let{docs:p,prevDocs:g=[]}=await n(_);if(l.persistence.markDirty(l.collections,this._col.name),await this._col._saveIfNeeded(o),this._col._changelogEnabled)for(let m=0;m<p.length;m++)await l.logChange(t,this._col.name,p[m],g[m]??null,c||null);if(!u||!d.defer(()=>l.sessionStats.recordWrite(c)))l.sessionStats.recordWrite(c);for(let m of p)l.emitEvent(this._col.name,{op:t,collection:this._col.name,doc:Q(m)});if(r)if(a)await l.runAfterHook(r,a(p));else for(let m of p)await l.runAfterHook(r,{collection:this._col.name,doc:Q(m)});return{docs:p,prevDocs:g}}}function Go(t){let i={};for(let r in t){if(r.startsWith("$"))continue;let s=t[r];if(s&&typeof s==="object"&&!Array.isArray(s)){let n=Object.keys(s);if(n.length===1&&n[0]==="$eq")i[r]=s.$eq}else i[r]=s}return i}var Ms=new Set(["__proto__","constructor","prototype"]);function js(t){if(typeof t!=="object"||t===null||Array.isArray(t))return t;let i={};for(let r of Object.keys(t)){if(Ms.has(r))continue;i[r]=js(t[r])}return i}class qs{constructor(t,i){this.name=t.collectionName,this.database=i,this._ctx=i._buildCollectionContext(),this._store=t,this._pipeline=new Ps(this),this._createdInTxId=i._txManager.context?.id??null,this._activeTxId=null}get _data(){return this._store.data}set _data(t){this._store.data=t}get _index(){return this._store.index}get _fieldIndex(){return this._store.fieldIndex||null}get _schema(){return this._store.schema?this._store.schema.fields:null}get _changelogEnabled(){return this._store.changelog===!0}get _softDelete(){return this._store.softDelete===!0}get _versioning(){return this._store.versioning===!0}get _strict(){return this._store.strict===!0}get _onSchemaError(){return this._store.onSchemaError??"throw"}get _defaultTtl(){return this._store.defaultTtl||null}get _defaultEmbed(){return this._store.defaultEmbed||null}get _maxDocs(){return this._store.maxDocs||null}async insertOne(t,i={}){let{save:r,ifNotExists:s,ttl:n,embed:a,session:o}=i;if(s){await this._ctx.ensureConnected();let l=this._findRaw(t);if(l)return Q({...l})}let{docs:c}=await this._insertCore([t],{ttl:n,embed:a,session:o,save:r});return Q(c[0])}async insertMany(t,i={}){let{save:r,ttl:s,embed:n,session:a}=i,{docs:o}=await this._insertCore(t,{ttl:s,embed:n,session:a,save:r});return o.map(Q)}async _insertCore(t,{ttl:i,embed:r,session:s,save:n}){return this._pipeline.execute({op:"insert",beforeHook:null,afterHook:"afterInsert",hookPayload:null,save:n,session:s,mutate:async(a)=>{let o=[],c=new Set;for(let l of t){let d=this._applyValidation(l);await this._ctx.plugins.run("beforeInsert",{collection:this.name,doc:d});let u=await this._buildDoc(d,{ttl:i,embed:r});if(this._index.has(u._id)||c.has(u._id))throw new De("ERR_SKALEX_UNIQUE_DUPLICATE_ID",`Duplicate _id "${u._id}" in collection "${this.name}"`,{id:u._id,collection:this.name});c.add(u._id),o.push(u)}if(a(),this._fieldIndex)this._fieldIndex.assertUniqueBatch(o);for(let l of o)this._addToIndex(l);this._data.push(...o);for(let l of o)this._index.set(l._id,l);return this._enforceCapAfterInsert(),{docs:o}}})}async updateOne(t,i,r={}){await this._ctx.ensureConnected();let s=this._findRaw(t);if(!s)return null;let{save:n,session:a}=r,{docs:o}=await this._updateCore([s],t,i,{save:n,session:a});return Q(o[0])}async updateMany(t,i,r={}){await this._ctx.ensureConnected();let s=this._findAllRaw(t);if(s.length===0)return[];let{save:n,session:a}=r,{docs:o}=await this._updateCore(s,t,i,{save:n,session:a});return o.map(Q)}async _updateCore(t,i,r,{save:s,session:n}){return this._pipeline.execute({op:"update",beforeHook:"beforeUpdate",afterHook:"afterUpdate",hookPayload:{collection:this.name,filter:i,update:r},save:s,session:n,afterHookPayload:(a)=>({collection:this.name,filter:i,update:r,result:a.length===1?a[0]:a}),mutate:async(a)=>{let o=this._changelogEnabled?t.map((u)=>structuredClone(u)):t.map(()=>null),c=t.map((u)=>this._prepareUpdatedDoc(u,r));this._assertUniqueCandidates(t,c),a();let l=new Set(t),d=new Map;for(let u=0;u<this._data.length;u++)if(l.has(this._data[u]))d.set(this._data[u],u);for(let u=0;u<t.length;u++)this._commitUpdatedDoc(t[u],c[u],d);return{docs:c,prevDocs:o}}})}applyUpdate(t,i){for(let r in i){if(Ms.has(r))continue;if(r==="_id"||r==="createdAt")continue;let s=i[r];if(Array.isArray(s))t[r]=s;else if(typeof s==="object"&&s!==null){let n=Object.keys(s);if(n.some((a)=>a.startsWith("$"))){for(let a of n)if(a==="$inc"&&typeof t[r]==="number")t[r]+=s[a];else if(a==="$push"){if(!Array.isArray(t[r]))t[r]=[];t[r].push(s[a])}}else t[r]=js(s)}else t[r]=s}if(t.updatedAt=new Date,this._versioning)t._version=(t._version??0)+1;return t}_prepareUpdatedDoc(t,i){let r=structuredClone(t),s=structuredClone(t);if(this.applyUpdate(s,i),!this._schema)return s;let n=jr(s,this._schema,this._strict);if(!n.length)return s;switch(this._onSchemaError){case"throw":throw new D("ERR_SKALEX_VALIDATION_UPDATE",`Update validation failed on doc "${t._id}": ${n.join("; ")}`,{id:t._id,errors:n});case"strip":return this._stripCandidateToValid(s,r);default:return this._ctx.logger(`[${this.name}] Update validation warning: ${n.join("; ")}`,"warn"),s}}_stripCandidateToValid(t,i){let r=qr(t,this._schema),s=structuredClone(i);for(let[n,a]of Object.entries(r)){if(n.startsWith("_"))continue;s[n]=a}if(s.updatedAt=t.updatedAt,this._versioning)s._version=t._version;return s}_commitUpdatedDoc(t,i,r){let s=r?r.get(t):this._data.indexOf(t);if(s===void 0||s===-1)throw new Ve("ERR_SKALEX_PERSISTENCE_DOC_MISSING",`Document "${t._id}" no longer exists in collection "${this.name}"`,{id:t._id,collection:this.name});this._data[s]=i,this._index.set(i._id,i),this._updateInIndex(t,i)}_assertUniqueCandidates(t,i){this._fieldIndex?.assertUniqueCandidates(t,i)}async upsert(t,i,r={}){if(await this._ctx.ensureConnected(),this._findRaw(t))return this.updateOne(t,i,r);return this.insertOne({...Go(t),...i},r)}async upsertMany(t,i,r={}){await this._ctx.ensureConnected();let{save:s,...n}=r,a=[];for(let o of t)a.push(await this.upsert({[i]:o[i]},o,{...n,save:!1}));return await this._saveIfNeeded(s),a}async restore(t,i={}){if(!this._softDelete)throw new ut("ERR_SKALEX_QUERY_SOFT_DELETE_REQUIRED",`restore() requires softDelete on "${this.name}"`,{collection:this.name});await this._ctx.ensureConnected();let{save:r,session:s}=i,n=this._findRaw(t,{includeDeleted:!0});if(!n||!n._deletedAt)return null;let{docs:a}=await this._pipeline.execute({op:"restore",beforeHook:null,afterHook:null,hookPayload:null,save:r,session:s,mutate:async(o)=>(o(),delete n._deletedAt,n.updatedAt=new Date,this._index.set(n._id,n),{docs:[n]})});return Q(a[0])}watch(t,i){if(typeof t==="function")i=t,t=null;if(i)return this._ctx.eventBus.on(this.name,(r)=>{if(!t||ie(r.doc,t))i(r)});return this._watchIterator(t)}_watchIterator(t){let i=[],r=null,s=!1,n=this._ctx.eventBus.on(this.name,(a)=>{if(t&&!ie(a.doc,t))return;if(r){let o=r;r=null,o({value:a,done:!1})}else i.push(a)});return{[Symbol.asyncIterator](){return this},next(){if(i.length>0)return Promise.resolve({value:i.shift(),done:!1});if(s)return Promise.resolve({value:void 0,done:!0});return new Promise((a)=>{r=a})},return(){if(s=!0,n(),r){let a=r;r=null,a({value:void 0,done:!0})}return Promise.resolve({value:void 0,done:!0})}}}async count(t={}){return await this._ctx.ensureConnected(),zo(this._findAllRaw(t))}async sum(t,i={}){return await this._ctx.ensureConnected(),Bo(this._findAllRaw(i),t)}async avg(t,i={}){return await this._ctx.ensureConnected(),Xo(this._findAllRaw(i),t)}async groupBy(t,i={}){return await this._ctx.ensureConnected(),Vo(this._findAllRaw(i),t)}async findOne(t,i={}){await this._ctx.ensureConnected();let{populate:r,select:s,includeDeleted:n=!1}=i,a=this._findRaw(t,{includeDeleted:n});if(!a)return null;let o=this._projectDoc(a,s);if(r)await this._populateDoc(o,a,r);return o}async find(t,i={}){await this._ctx.ensureConnected();let r=Date.now(),{populate:s,select:n,sort:a,page:o=1,limit:c,session:l,includeDeleted:d=!1}=i;await this._ctx.plugins.run("beforeFind",{collection:this.name,filter:t,options:i});let u=this._getCandidates(t),f=jo(t,this._fieldIndex?this._fieldIndex.indexedFields:new Set),h=[];for(let p of u){if(this._softDelete&&p._deletedAt&&!d)continue;if(!ie(p,f))continue;let g=this._projectDoc(p,n);if(s)await this._populateDoc(g,p,s);h.push(g)}if(a){let p=Object.keys(a);h.sort((g,m)=>{for(let w of p){let v=a[w];if(g[w]<m[w])return-v;if(g[w]>m[w])return v}return 0})}let _;if(c){let p=h.length,g=Math.ceil(p/c),m=(o-1)*c;h=h.slice(m,m+c),_={page:o,totalDocs:p,totalPages:g}}return this._ctx.queryLog?.record({collection:this.name,op:"find",filter:t,duration:Date.now()-r,resultCount:h.length}),this._ctx.sessionStats.recordRead(l),await this._ctx.plugins.run("afterFind",{collection:this.name,filter:t,options:i,docs:h}),_?{docs:h,..._}:{docs:h}}async search(t,{filter:i,limit:r=10,minScore:s=0,session:n}={}){await this._ctx.ensureConnected();let a=Date.now();await this._ctx.plugins.run("beforeSearch",{collection:this.name,query:t,options:{filter:i,limit:r,minScore:s}});let o=await this._ctx.embed(t),c=i?this._findAllRaw(i):this._data,l=[];for(let h of c){if(!h._vector)continue;let _=Ur(o,h._vector);if(_>=s)l.push({doc:h,score:_})}l.sort((h,_)=>_.score-h.score);let d=l.slice(0,r);this._ctx.queryLog?.record({collection:this.name,op:"search",query:t,duration:Date.now()-a,resultCount:d.length}),this._ctx.sessionStats.recordRead(n);let u=d.map((h)=>Q(h.doc)),f=d.map((h)=>h.score);return await this._ctx.plugins.run("afterSearch",{collection:this.name,query:t,options:{filter:i,limit:r,minScore:s},docs:u,scores:f}),{docs:u,scores:f}}async similar(t,{limit:i=10,minScore:r=0}={}){await this._ctx.ensureConnected();let s=this._index.get(t);if(!s||!s._vector)return{docs:[],scores:[]};let n=[];for(let o of this._data){if(o._id===t||!o._vector)continue;let c=Ur(s._vector,o._vector);if(c>=r)n.push({doc:o,score:c})}n.sort((o,c)=>c.score-o.score);let a=n.slice(0,i);return{docs:a.map((o)=>Q(o.doc)),scores:a.map((o)=>o.score)}}async deleteOne(t,i={}){await this._ctx.ensureConnected();let{save:r,session:s}=i;if(this._softDelete){let a=this._findRaw(t);if(!a)return null;let{docs:o}=await this._deleteCore("soft",[a],t,{save:r,session:s});return Q(o[0])}let{docs:n}=await this._deleteCore("hard",null,t,{save:r,session:s});if(n.length===0)return null;return Q(n[0])}async deleteMany(t,i={}){await this._ctx.ensureConnected();let{save:r,session:s}=i;if(this._softDelete){let a=this._findAllRaw(t);if(a.length===0)return[];let{docs:o}=await this._deleteCore("soft",a,t,{save:r,session:s});return o.map(Q)}let{docs:n}=await this._deleteCore("hardMany",null,t,{save:r,session:s});return n.map(Q)}async _deleteCore(t,i,r,{save:s,session:n}){return this._pipeline.execute({op:"delete",beforeHook:"beforeDelete",afterHook:"afterDelete",hookPayload:{collection:this.name,filter:r},save:s,session:n,afterHookPayload:(a)=>({collection:this.name,filter:r,result:a.length===1?a[0]:a}),mutate:async(a)=>{if(a(),t==="soft"){let l=new Date;for(let d of i)d._deletedAt=l,d.updatedAt=l,this._index.set(d._id,d);return{docs:i}}if(t==="hard"){let l=this._findIndex(r);if(l===-1)return{docs:[]};let d=this._data.splice(l,1)[0];return this._index.delete(d._id),this._removeFromIndex(d),{docs:[d]}}let o=[],c=[];for(let l of this._data)if(ie(l,r))o.push(l),this._index.delete(l._id),this._removeFromIndex(l);else c.push(l);return this._data=c,{docs:o}}})}async export(t={},i={}){let{dir:r,name:s,format:n="json"}=i;try{let a=this._data.filter((u)=>ie(u,t));if(a.length===0)throw new ut("ERR_SKALEX_QUERY_EXPORT_EMPTY",`export(): no documents matched the filter in "${this.name}"`,{collection:this.name});let o;if(n==="json")o=JSON.stringify(a,null,2);else{let u=(_)=>{if(_==null)return"";let p=typeof _==="object"?JSON.stringify(_):String(_);return p.includes(",")||p.includes('"')||p.includes(`
3
3
  `)||p.includes("\r")?`"${p.replace(/"/g,'""')}"`:p},f=Object.keys(a[0]).map(u).join(","),h=a.map((_)=>Object.values(_).map(u).join(","));o=[f,...h].join(`
4
4
  `)}if(typeof this._ctx.fs.writeRaw!=="function")throw new be("ERR_SKALEX_ADAPTER_NO_RAW_WRITE","export() requires a file-system adapter (FsAdapter). The current adapter does not support raw file writes.");let c=r||`${this._ctx.dataDirectory}/exports`,l=`${s||this.name}.${n}`,d=this._ctx.fs.join(c,l);this._ctx.fs.ensureDir(c),await this._ctx.fs.writeRaw(d,o)}catch(a){throw this._ctx.logger(`Error exporting "${this.name}": ${a.message}`,"error"),a}}_txSnapshotIfNeeded(){let t=this._ctx.txManager;if(!t.active)return;if(this._activeTxId!==t.context?.id)return;t.snapshotIfNeeded(this.name,this._store,(i)=>this._ctx.snapshotCollection(i))}async _saveIfNeeded(t){let i=this._ctx.txManager;if(i.active&&this._activeTxId===i.context?.id)return;if(t??this._ctx.autoSave)await this._ctx.saveCollection(this.name)}_applyValidation(t){if(!this._schema)return t;let i=jr(t,this._schema,this._strict);if(!i.length)return t;switch(this._onSchemaError){case"warn":return this._ctx.logger(`[${this.name}] Validation warning: ${i.join("; ")}`,"warn"),t;case"strip":return qr(t,this._schema);default:throw new D("ERR_SKALEX_VALIDATION_FAILED",`Validation failed: ${i.join("; ")}`,{errors:i})}}_enforceCapAfterInsert(){let t=this._maxDocs;if(!t||this._data.length<=t)return;let i=this._data.splice(0,this._data.length-t);for(let r of i)this._index.delete(r._id),this._removeFromIndex(r)}_findRaw(t,{includeDeleted:i=!1}={}){if(typeof t==="function"){for(let r of this._data){if(this._softDelete&&r._deletedAt&&!i)continue;if(t(r))return r}return null}if(t._id){let r=this._index.get(t._id)||null;if(!r)return null;if(this._softDelete&&r._deletedAt&&!i)return null;if(Object.keys(t).length>1)return ie(r,t)?r:null;return r}if(this._fieldIndex)for(let r in t){if(r==="$or"||r==="$and"||r==="$not")continue;let s=t[r];if(typeof s!=="object"||s===null){let n=this._fieldIndex._lookupIterable(r,s);if(n!==null){for(let a of n){if(this._softDelete&&a._deletedAt&&!i)continue;if(ie(a,t))return a}return null}}}for(let r of this._data){if(this._softDelete&&r._deletedAt&&!i)continue;if(ie(r,t))return r}return null}_findAllRaw(t,{includeDeleted:i=!1}={}){if(t&&typeof t!=="function"&&t._id){let s=this._index.get(t._id);if(!s)return[];if(this._softDelete&&s._deletedAt&&!i)return[];return ie(s,t)?[s]:[]}let r=[];for(let s of this._getCandidates(t)){if(this._softDelete&&s._deletedAt&&!i)continue;if(ie(s,t))r.push(s)}return r}_getCandidates(t){if(!this._fieldIndex)return this._data;if(this._fieldIndex._compoundIndexes.size>0){let i={};for(let r in t){if(r==="$or"||r==="$and"||r==="$not")continue;let s=t[r];if(typeof s!=="object"||s===null)i[r]=s}if(Object.keys(i).length>=2){let r=this._fieldIndex.lookupCompound(i);if(r!==null)return r}}for(let i in t){if(i==="$or"||i==="$and"||i==="$not")continue;let r=t[i];if(typeof r!=="object"||r===null){let s=this._fieldIndex._lookupIterable(i,r);if(s!==null)return s}}return this._data}_findIndex(t){for(let i=0;i<this._data.length;i++)if(ie(this._data[i],t))return i;return-1}_addToIndex(t){if(this._fieldIndex)this._fieldIndex.add(t)}_removeFromIndex(t){if(this._fieldIndex)this._fieldIndex.remove(t)}_updateInIndex(t,i){if(this._fieldIndex)this._fieldIndex.update(t,i)}async _buildDoc(t,{ttl:i,embed:r}={}){let s={...t,_id:t._id??(this._ctx.idGenerator??Mo)(),createdAt:new Date,updatedAt:new Date},n=i??this._defaultTtl;if(n)s._expiresAt=Fo(n);let a=r??this._defaultEmbed;if(a){let o=typeof a==="function"?a(s):s[a];s._vector=await this._ctx.embed(String(o))}if(this._versioning)s._version=1;return s}_projectDoc(t,i){if(i){let s={};for(let n of i){if(n==="_vector")continue;s[n]=t[n]}return s}let r={...t};return delete r._vector,r}async _populateDoc(t,i,r){for(let s of r){let n=await this._ctx.getCollection(s).findOne({_id:i[s]});if(n)t[s]=n}}}class Fi{async read(t){throw Error("StorageAdapter.read() not implemented")}async write(t,i){throw Error("StorageAdapter.write() not implemented")}async delete(t){throw Error("StorageAdapter.delete() not implemented")}async list(){throw Error("StorageAdapter.list() not implemented")}async writeAll(t){for(let{name:i,data:r}of t)await this.write(i,r)}}class Us extends Fi{constructor({dir:t,format:i="gz"}){super();this.dir=it.resolve(t),this.format=i,this._ensureDir(this.dir)}_ensureDir(t){if(!G.existsSync(t))G.mkdirSync(t,{recursive:!0})}_filePath(t){return it.join(this.dir,`${t}.${this.format}`)}async read(t){let i=this._filePath(t);try{let r=await G.promises.readFile(i);if(this.format==="gz")r=Ai.inflateSync(r);return r.toString("utf8")}catch(r){if(r.code==="ENOENT")return null;throw r}}async write(t,i){let r=this._filePath(t),s=it.join(this.dir,`${t}_${globalThis.crypto.randomUUID()}.tmp.${this.format}`);if(this.format==="gz"){let n=Ai.deflateSync(i);await G.promises.writeFile(s,n)}else await G.promises.writeFile(s,i,"utf8");await G.promises.rename(s,r)}async writeAll(t){let i=[];try{for(let{name:r,data:s}of t){let n=this._filePath(r),a=it.join(this.dir,`${r}_${globalThis.crypto.randomUUID()}.tmp.${this.format}`);if(this.format==="gz"){let o=Ai.deflateSync(s);await G.promises.writeFile(a,o)}else await G.promises.writeFile(a,s,"utf8");i.push({tmp:a,fp:n})}for(let{tmp:r,fp:s}of i)await G.promises.rename(r,s)}catch(r){for(let{tmp:s}of i)try{await G.promises.unlink(s)}catch{}throw r}}async delete(t){let i=this._filePath(t);try{await G.promises.unlink(i)}catch(r){if(r.code!=="ENOENT")throw r}}async list(){try{let t=await G.promises.readdir(this.dir),i=`.${this.format}`;return t.filter((r)=>r.endsWith(i)&&!r.includes(".tmp.")).map((r)=>r.slice(0,-i.length))}catch(t){if(t.code==="ENOENT")return[];throw t}}join(...t){return it.join(...t)}ensureDir(t){this._ensureDir(t)}async writeRaw(t,i){this._ensureDir(it.dirname(t)),await G.promises.writeFile(t,i,"utf8")}async readRaw(t){return G.promises.readFile(it.resolve(t),"utf8")}}class Fs{constructor(){this._migrations=[]}add(t){let{version:i,up:r}=t;if(typeof i!=="number"||i<1)throw new D("ERR_SKALEX_VALIDATION_MIGRATION",`Migration version must be a positive integer, got ${i}`,{version:i});if(typeof r!=="function")throw new D("ERR_SKALEX_VALIDATION_MIGRATION",`Migration version ${i} must have an "up" function`,{version:i});if(this._migrations.some((s)=>s.version===i))throw new D("ERR_SKALEX_VALIDATION_MIGRATION_DUPLICATE",`Migration version ${i} is already registered`,{version:i});this._migrations.push({...t}),this._migrations.sort((s,n)=>s.version-n.version)}async run(t,i=[]){let r=new Set(i),s=this._migrations.filter((n)=>!r.has(n.version));for(let n of s){let a=t(n.version);await n.up(a),r.add(n.version)}return[...r].sort((n,a)=>n-a)}status(t=[]){let i=new Set(t),r=this._migrations.map((s)=>s.version).filter((s)=>!i.has(s));return{current:t.length?Math.max(...t):0,applied:[...i].sort((s,n)=>s-n),pending:r}}}var Fr={[Symbol.iterator](){return{next(){return{done:!0}}}},size:0};function Kr(t){return{[Symbol.iterator](){return t[Symbol.iterator]()},get size(){return t.size}}}function Si(t){return t.map((i)=>{if(i===null||i===void 0)return"\x00";if(typeof i==="boolean")return i?"\x01T":"\x01F";if(typeof i==="number")return`\x02${i}`;return`\x03${String(i)}`}).join("\x1F")}class Yt{constructor(t=[],i=[]){this._fields=new Set,this._compoundFields=[];for(let r of t)if(Array.isArray(r)){for(let s of r)this._validateFieldName(s);this._compoundFields.push(r)}else this._validateFieldName(r),this._fields.add(r);for(let r of i)this._validateFieldName(r);this._uniqueFields=new Set(i),this._indexedFields=new Set([...this._fields,...this._uniqueFields]),this._fieldIndexes=new Map,this._uniqueIndexes=new Map;for(let r of this._fields)this._fieldIndexes.set(r,new Map);for(let r of this._uniqueFields)if(this._uniqueIndexes.set(r,new Map),!this._fieldIndexes.has(r))this._fieldIndexes.set(r,new Map);this._compoundIndexes=new Map;for(let r of this._compoundFields)this._compoundIndexes.set(r.join("\x00"),{fields:r,map:new Map})}get indexedFields(){return this._indexedFields}buildFromData(t){for(let[,i]of this._fieldIndexes)i.clear();for(let[,i]of this._uniqueIndexes)i.clear();for(let[,i]of this._compoundIndexes)i.map.clear();for(let i of t)this._indexDoc(i)}add(t){this._checkUnique(t,null),this._indexDoc(t)}remove(t){for(let[i,r]of this._fieldIndexes){let s=t[i];if(s!==void 0){let n=r.get(s);if(n){if(n.delete(t),n.size===0)r.delete(s)}}}for(let[i,r]of this._uniqueIndexes){let s=t[i];if(s!==void 0)r.delete(s)}for(let[,i]of this._compoundIndexes){let r=Si(i.fields.map((n)=>t[n])),s=i.map.get(r);if(s){if(s.delete(t),s.size===0)i.map.delete(r)}}}update(t,i){this._checkUnique(i,t),this.remove(t);try{this._indexDoc(i)}catch(r){try{this._indexDoc(t)}catch{}throw r}}lookup(t,i){let r=this._fieldIndexes.get(t);if(!r)return null;let s=r.get(i);return s?[...s]:[]}_lookupIterable(t,i){let r=this._fieldIndexes.get(t);if(!r)return null;let s=r.get(i);return s?Kr(s):Fr}lookupCompound(t){let i=Object.keys(t).sort();for(let[,r]of this._compoundIndexes){let s=[...r.fields].sort();if(s.length!==i.length)continue;if(s.every((n,a)=>n===i[a])){let n=Si(r.fields.map((o)=>t[o])),a=r.map.get(n);return a?Kr(a):Fr}}return null}isUniqueTaken(t,i){let r=this._uniqueIndexes.get(t);if(!r)return!1;return r.has(i)}assertUniqueCandidates(t,i){if(this._uniqueFields.size===0)return;let r=new Set(t.map((s)=>s._id));for(let s of this._uniqueFields){let n=new Set,a=this._uniqueIndexes.get(s);if(a){for(let[c,l]of a.entries())if(!r.has(l._id))n.add(c)}let o=new Map;for(let c=0;c<i.length;c++){let l=i[c][s];if(l===void 0)continue;if(n.has(l))throw new De("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: field "${s}" value "${l}" already exists`,{field:s,value:l});let d=o.get(l);if(d&&d!==t[c]._id)throw new De("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: field "${s}" value "${l}" already exists`,{field:s,value:l});o.set(l,t[c]._id)}}}assertUniqueBatch(t){if(this._uniqueFields.size===0)return;for(let i of this._uniqueFields){let r=this._uniqueIndexes.get(i),s=new Set;for(let n of t){let a=n[i];if(a===void 0)continue;if(r&&r.has(a))throw new De("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: field "${i}" value "${a}" already exists`,{field:i,value:a});if(s.has(a))throw new De("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: duplicate "${i}" value "${a}" within batch`,{field:i,value:a});s.add(a)}}}_validateFieldName(t){if(t.includes("."))throw new D("ERR_SKALEX_VALIDATION_INDEX_DOT_PATH",`Index fields cannot use dot-notation: "${t}". Use a flat field name.`,{field:t})}_indexDoc(t){for(let[i,r]of this._fieldIndexes){let s=t[i];if(s!==void 0){if(!r.has(s))r.set(s,new Set);r.get(s).add(t)}}for(let[i,r]of this._uniqueIndexes){let s=t[i];if(s!==void 0)r.set(s,t)}for(let[,i]of this._compoundIndexes){for(let s of i.fields){let n=t[s];if(n!==void 0&&n!==null&&typeof n==="object")throw new D("ERR_SKALEX_VALIDATION_COMPOUND_INDEX",`Compound index field "${s}" must be a scalar value (string, number, or boolean), got ${Array.isArray(n)?"array":typeof n}`,{field:s})}let r=Si(i.fields.map((s)=>t[s]));if(!i.map.has(r))i.map.set(r,new Set);i.map.get(r).add(t)}}_checkUnique(t,i){for(let r of this._uniqueFields){let s=t[r];if(s===void 0)continue;let n=this._uniqueIndexes.get(r);if(!n)continue;let a=n.get(s);if(a&&a._id!==i?._id)throw new De("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: field "${r}" value "${s}" already exists`,{field:r,value:s})}}}var jt="_flush",qt="migrations";class Ks{constructor({adapter:t,serializer:i,deserializer:r,logger:s,debug:n=!1,lenientLoad:a=!1}){this._adapter=t,this._serializer=i,this._deserializer=r,this._logger=s,this._debug=n,this._lenientLoad=a,this._saveLock=Promise.resolve()}_withSaveLock(t){let i=this._saveLock.then(t);return this._saveLock=i.catch(()=>{}),i}async loadAll(t,{parseSchema:i,buildIndex:r,IndexEngine:s}){try{let n=await this._adapter.list();await Promise.all(n.map(async(a)=>{try{let o=await this._adapter.read(a);if(!o)return;let c=this._deserializer(o),{collectionName:l,data:d}=c;if(!l)return;let u=t[l],f=u?.rawSchema??c.rawSchema??null,h=u?.schema??(f?i(f):null),_=u?.changelog??c.changelog??!1,p=u?.softDelete??c.softDelete??!1,g=u?.versioning??c.versioning??!1,m=u?.strict??c.strict??!1,w=u?.onSchemaError??c.onSchemaError??"throw",v=u?.defaultTtl??c.defaultTtl??null,q=u?.defaultEmbed??c.defaultEmbed??null,E=u?.maxDocs??c.maxDocs??null,A=u?u.fieldIndex:null;if(!A&&h?.uniqueFields?.length)A=new s([],h.uniqueFields);let tt=r(d,"_id");if(A)A.buildFromData(d);t[l]={collectionName:l,data:d,index:tt,isSaving:!1,_pendingSave:!1,_dirty:!1,schema:h,rawSchema:f,fieldIndex:A,changelog:_,softDelete:p,versioning:g,strict:m,onSchemaError:w,defaultTtl:v,defaultEmbed:q,maxDocs:E}}catch(o){if(o.code==="ENOENT")return;if(this._lenientLoad){this._logger(`WARNING: Could not load collection "${a}": ${o.message}. Collection will be empty.`,"error");return}throw new Ve("ERR_SKALEX_PERSISTENCE_CORRUPT",`Failed to load collection "${a}": ${o.message}`,{collection:a})}})),this._detectIncompleteFlush(t),await this._cleanOrphanTempFiles()}catch(n){if(n.code!=="ENOENT")throw this._logger(`Error loading data: ${n}`,"error"),n}}async save(t,i){if(i)await this._saveOne(t,i);else await Promise.all(Object.keys(t).map((r)=>this._saveOne(t,r)))}async saveDirty(t){let i=Object.keys(t).filter((r)=>t[r]._dirty);if(i.length===0)return;await Promise.all(i.map((r)=>this._saveOne(t,r)))}saveAtomic(t,i){return this._withSaveLock(async()=>{if(i.length===0)return;this._writeFlushSentinel(t,i);let r=new Set(i);r.add("_meta");let s=[...r].filter((n)=>t[n]).map((n)=>({name:n,data:this._serializeCollection(t[n])}));try{await this._adapter.writeAll(s)}catch(n){throw new Ve("ERR_SKALEX_PERSISTENCE_FLUSH_FAILED",`Batch save failed during writeAll: ${n.message}`,{collections:i})}for(let n of i)if(t[n])t[n]._dirty=!1;try{this._clearFlushSentinel(t),await this._adapter.write("_meta",this._serializeCollection(t._meta))}catch(n){this._logger(`WARNING: Batch data committed but sentinel clear failed: ${n.message}. Next load will report an incomplete flush (false positive).`,"error")}})}markDirty(t,i){let r=t[i];if(r)r._dirty=!0}_serializeCollection(t){let i={collectionName:t.collectionName,data:t.data};if(t.rawSchema)i.rawSchema=t.rawSchema;if(t.changelog)i.changelog=t.changelog;if(t.softDelete)i.softDelete=t.softDelete;if(t.versioning)i.versioning=t.versioning;if(t.strict)i.strict=t.strict;if(t.onSchemaError!=="throw")i.onSchemaError=t.onSchemaError;if(t.defaultTtl)i.defaultTtl=t.defaultTtl;if(t.defaultEmbed)i.defaultEmbed=t.defaultEmbed;if(t.maxDocs)i.maxDocs=t.maxDocs;return this._serializer(i)}async _saveOne(t,i){let r=t[i];if(!r)return;if(r.isSaving)return r._pendingSave=!0,new Promise((s,n)=>{(r._saveWaiters??=[]).push({resolve:s,reject:n})});r.isSaving=!0,r._pendingSave=!1;try{await this._writeCollection(i,r);while(r._pendingSave)r._pendingSave=!1,await this._writeCollection(i,r);this._resolveSaveWaiters(r)}catch(s){throw this._rejectSaveWaiters(r,s),s}finally{r.isSaving=!1}}async _writeCollection(t,i){try{await this._adapter.write(t,this._serializeCollection(i)),i._dirty=!1}catch(r){throw this._logger(`Error saving "${t}": ${r.message}`,"error"),r}}_resolveSaveWaiters(t){let i=t._saveWaiters?.splice(0)??[];for(let r of i)r.resolve()}_rejectSaveWaiters(t,i){let r=t._saveWaiters?.splice(0)??[];for(let s of r)s.reject(i)}_writeFlushSentinel(t,i){let r=this._getOrCreateMeta(t);r[jt]={startedAt:new Date().toISOString(),collections:i,completedAt:null}}_clearFlushSentinel(t){let i=this._getOrCreateMeta(t);if(i[jt])i[jt].completedAt=new Date().toISOString()}_detectIncompleteFlush(t){let i=t._meta;if(!i)return;let r=i.index.get(qt);if(!r)return;let s=r[jt];if(!s)return;if(s.startedAt&&!s.completedAt)this._logger(`WARNING: Incomplete flush detected (started ${s.startedAt}, collections: ${s.collections?.join(", ")}). Data may be inconsistent.`,"error")}async _cleanOrphanTempFiles(){if(typeof this._adapter.join!=="function")return;if(typeof this._adapter.list!=="function")return;try{let t=await import("fs"),i=await import("path"),r=this._adapter.dir;if(!r)return;let s=(await t.default.promises.readdir(r)).filter((n)=>n.includes(".tmp."));for(let n of s){let a=i.default.join(r,n);try{await t.default.promises.unlink(a),this._log(`Cleaned orphan temp file: ${n}`)}catch{}}}catch{}}_getOrCreateMeta(t){if(!t._meta)t._meta={collectionName:"_meta",data:[],index:new Map,isSaving:!1,_pendingSave:!1,_dirty:!1,schema:null,rawSchema:null,fieldIndex:null,changelog:!1,softDelete:!1,versioning:!1,strict:!1,onSchemaError:"throw",defaultTtl:null,defaultEmbed:null,maxDocs:null};let i=t._meta,r=i.index.get(qt);if(!r)r={_id:qt},i.data.push(r),i.index.set(qt,r);return r}_log(t){if(this._debug)this._logger(t,"info")}}var Ho=0;class zs{constructor(){this._txLock=Promise.resolve(),this._ctx=null,this._abortedIds=new Set}get active(){return this._ctx!==null&&!this._ctx.aborted}get context(){return this._ctx}async run(t,i,{timeout:r=0}={}){let s=async()=>{await i._ensureConnected();let a=new Set(Object.keys(i.collections)),o={id:++Ho,startedAt:Date.now(),aborted:!1,preExisting:a,touchedCollections:new Set,snapshots:new Map,deferredEffects:[],timeout:r};this._ctx=o;let c=null,l=r>0?new Promise((f,h)=>{c=setTimeout(()=>{o.aborted=!0,h(new Ce("ERR_SKALEX_TX_TIMEOUT",`Transaction ${o.id} timed out after ${r}ms`))},r)}):null,d=this,u=new Proxy(i,{get(f,h){if(h==="_txId")return o.id;if(o!==d._ctx)throw new Ce("ERR_SKALEX_TX_STALE_PROXY",`Transaction ${o.id} has ended. This proxy is no longer usable.`);if(h==="collections")throw new Ce("ERR_SKALEX_TX_DIRECT_ACCESS","Direct access to db.collections inside transaction() is not covered by rollback. Use the collection API (db.useCollection) instead.");if(h==="useCollection")return(p)=>{let g=f.useCollection(p);return g._activeTxId=o.id,g};let _=Reflect.get(f,h);return typeof _==="function"?_.bind(f):_}});try{let f=t(u),h=l?await Promise.race([f,l]):await f;if(o.aborted)throw new Ce("ERR_SKALEX_TX_ABORTED",`Transaction ${o.id} was aborted`);let _=[...o.touchedCollections];if(_.length>0)await i._persistence.saveAtomic(i.collections,_);for(let p of o.deferredEffects)await p();return h}catch(f){for(let[h,_]of o.snapshots)if(o.preExisting.has(h)){if(i._applySnapshot(h,_),i.collections[h])i.collections[h]._dirty=_._dirty}for(let h in i.collections)if(!o.preExisting.has(h))delete i.collections[h],delete i._collectionInstances[h];throw f}finally{if(c)clearTimeout(c);if(o.aborted)this._abortedIds.add(o.id);this._ctx=null;for(let f in i._collectionInstances){let h=i._collectionInstances[f];if(h._createdInTxId===o.id)h._createdInTxId=null;if(h._activeTxId===o.id)h._activeTxId=null}}},n=this._txLock.then(s);return this._txLock=n.catch(()=>{}),n}snapshotIfNeeded(t,i,r){let s=this._ctx;if(!s)return;if(this._assertCtxNotAborted(s),!s.snapshots.has(t)){let n=r(i);n._dirty=i._dirty??!1,s.snapshots.set(t,n)}s.touchedCollections.add(t)}assertNotAborted(){let t=this._ctx;if(t)this._assertCtxNotAborted(t)}_assertCtxNotAborted(t){if(t.aborted)throw new Ce("ERR_SKALEX_TX_ABORTED",`Transaction ${t.id} was aborted. No further mutations allowed.`)}defer(t){if(this._ctx)return this._ctx.deferredEffects.push(t),!0;return!1}}class Bs{constructor(t){this._CollectionClass=t,this.stores={},this._instances={}}get(t,i){if(this._instances[t])return this._instances[t];if(!this.stores[t])this.createStore(t);let r=new this._CollectionClass(this.stores[t],i);return this._instances[t]=r,r}create(t,i={},r){this.createStore(t,i);let s=new this._CollectionClass(this.stores[t],r);return this._instances[t]=s,s}createStore(t,{schema:i,indexes:r=[],changelog:s=!1,softDelete:n=!1,versioning:a=!1,strict:o=!1,onSchemaError:c="throw",defaultTtl:l=null,defaultEmbed:d=null,maxDocs:u=null}={}){let f=null,h=null;if(i){f=Ls(i);let _=f.uniqueFields;if(r.length||_.length)h=new Yt(r,_)}else if(r.length)h=new Yt(r,[]);this.stores[t]={collectionName:t,data:[],index:new Map,isSaving:!1,_pendingSave:!1,_dirty:!1,schema:f,rawSchema:i||null,fieldIndex:h,changelog:s,softDelete:n,versioning:a,strict:o,onSchemaError:c,defaultTtl:l,defaultEmbed:d,maxDocs:u}}rename(t,i){if(!this.stores[t])throw new Ve("ERR_SKALEX_PERSISTENCE_COLLECTION_NOT_FOUND",`Collection "${t}" not found`,{collection:t});if(this.stores[i])throw new Ve("ERR_SKALEX_PERSISTENCE_COLLECTION_EXISTS",`Collection "${i}" already exists`,{collection:i});let r=this.stores[t];if(r.collectionName=i,this.stores[i]=r,delete this.stores[t],this._instances[t]){let s=this._instances[t];s.name=i,this._instances[i]=s,delete this._instances[t]}}buildIndex(t,i){let r=new Map;for(let s of t)r.set(s[i],s);return r}inspect(t){if(t){let r=this.stores[t];if(!r)return null;return{name:t,count:r.data.length,schema:r.schema?Object.fromEntries(r.schema.fields):null,indexes:r.fieldIndex?[...r.fieldIndex.indexedFields]:[],softDelete:r.softDelete??!1,versioning:r.versioning??!1,strict:r.strict??!1,onSchemaError:r.onSchemaError??"throw",maxDocs:r.maxDocs??null}}let i={};for(let r in this.stores)i[r]=this.inspect(r);return i}dump(){let t={};for(let i in this.stores)if(!i.startsWith("_"))t[i]=structuredClone(this.stores[i].data);return t}schema(t){let i=this.stores[t];if(!i)return null;if(i.schema)return Object.fromEntries([...i.schema.fields.entries()].map(([r,s])=>[r,s.type]));if(i.data.length>0)return qo(i.data[0]);return null}stats(t){let i=(r)=>{let s=this.stores[r];if(!s)return null;let n=s.data.length,a=0;for(let o of s.data)try{a+=JSON.stringify(o).length}catch(c){}return{collection:r,count:n,estimatedSize:a,avgDocSize:n>0?Math.round(a/n):0}};if(t)return i(t);return Object.keys(this.stores).map(i)}clear(){this.stores={},this._instances={}}}class Ki{async embed(t){throw Error("EmbeddingAdapter.embed() not implemented")}}var ye=(t)=>globalThis.process?.env?.[t]??globalThis.Deno?.env?.get(t);class Xs extends Ki{constructor({apiKey:t=ye("OPENAI_API_KEY"),model:i=ye("OPENAI_EMBED_MODEL")??"text-embedding-3-small",baseUrl:r=ye("OPENAI_EMBED_BASE_URL")??"https://api.openai.com/v1/embeddings",dimensions:s=ye("OPENAI_EMBED_DIMENSIONS")!=null?Number(ye("OPENAI_EMBED_DIMENSIONS")):void 0,organization:n=ye("OPENAI_ORGANIZATION")??void 0,timeout:a=ye("OPENAI_EMBED_TIMEOUT")!=null?Number(ye("OPENAI_EMBED_TIMEOUT")):void 0,retries:o=Number(ye("OPENAI_EMBED_RETRIES")??0),retryDelay:c=Number(ye("OPENAI_EMBED_RETRY_DELAY")??1000),headers:l={},fetch:d=globalThis.fetch}={}){super();if(!t)throw Error("OpenAIEmbeddingAdapter requires an apiKey");this.apiKey=t,this.model=i,this.baseUrl=r,this.dimensions=s,this.organization=n,this.timeout=a,this.retries=o,this.retryDelay=c,this.headers=l,this._fetch=d}async embed(t){let i;for(let r=0;r<=this.retries;r++){let s=this.timeout!=null?new AbortController:null,n=s?setTimeout(()=>s.abort(),this.timeout):null;try{let a=await this._fetch(this.baseUrl,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,...this.organization&&{"OpenAI-Organization":this.organization},...this.headers},body:JSON.stringify({input:t,model:this.model,...this.dimensions!==void 0&&{dimensions:this.dimensions}}),...s&&{signal:s.signal}});if(!a.ok){let o=(await a.text()).slice(0,200);throw Error(`OpenAI embedding API error ${a.status}: ${o}`)}return(await a.json()).data[0].embedding}catch(a){if(i=a,r<this.retries)await new Promise((o)=>setTimeout(o,this.retryDelay*2**r))}finally{if(n!==null)clearTimeout(n)}}throw i}}var mt=(t)=>globalThis.process?.env?.[t]??globalThis.Deno?.env?.get(t);class Vs extends Ki{constructor({model:t=mt("OLLAMA_EMBED_MODEL")??"nomic-embed-text",host:i=mt("OLLAMA_HOST")??"http://localhost:11434",timeout:r=mt("OLLAMA_EMBED_TIMEOUT")!=null?Number(mt("OLLAMA_EMBED_TIMEOUT")):void 0,retries:s=Number(mt("OLLAMA_EMBED_RETRIES")??0),retryDelay:n=Number(mt("OLLAMA_EMBED_RETRY_DELAY")??1000),headers:a={},fetch:o=globalThis.fetch}={}){super();this.model=t,this.host=i,this.timeout=r,this.retries=s,this.retryDelay=n,this.headers=a,this._fetch=o}async embed(t){let i;for(let r=0;r<=this.retries;r++){let s=this.timeout!=null?new AbortController:null,n=s?setTimeout(()=>s.abort(),this.timeout):null;try{let a=await this._fetch(`${this.host}/api/embeddings`,{method:"POST",headers:{"Content-Type":"application/json",...this.headers},body:JSON.stringify({model:this.model,prompt:t}),...s&&{signal:s.signal}});if(!a.ok){let o=(await a.text()).slice(0,200);throw Error(`Ollama embedding API error ${a.status}: ${o}`)}return(await a.json()).embedding}catch(a){if(i=a,r<this.retries)await new Promise((o)=>setTimeout(o,this.retryDelay*2**r))}finally{if(n!==null)clearTimeout(n)}}throw i}}class ii{async generate(t,i){throw Error("LLMAdapter.generate() not implemented")}async summarize(t){throw Error("LLMAdapter.summarize() not implemented")}}var zi=`You are a database query assistant. Convert the user's natural language request into a JSON filter object for a document database.
5
5
 
@@ -174,5 +174,5 @@ data: /message
174
174
  mutation NotifyVibecontrolsAgentPluginChange($agentId: ID!) {
175
175
  notifyVibecontrolsAgentPluginChange(agentId: $agentId)
176
176
  }
177
- `;async function rr(t){try{if(!T.isConfigured())return;let i=await t.getConfig("gateway-auth:agentRecordId");if(!i)return;let r=await T.workspaceQuery(Fd,{agentId:i});if(r.errors?.length)e().logger.debug(y,"Plugin-change notify returned errors",{errors:r.errors.map((s)=>s.message)})}catch(i){e().logger.debug(y,`Plugin-change notify failed: ${i instanceof Error?i.message:String(i)}`)}}var Nt=null,gt=null,Ct=!1;function Pt(t,i,r){if(Nt)return;let s=Number(process.env.VIBE_TUNNEL_SYNC_MS),n=Number.isFinite(s)&&s>0?s:r??60000;Nt=setInterval(async()=>{if(!T.isConfigured())return;try{let a=i.getProvider("tunnel");if(!a||!a.getActiveTunnelUrl)return;let o=Wt(await a.getActiveTunnelUrl()),c=await t.getConfig("gateway-auth:agentRecordId");if(!c)return;if(await _i(c),!o){if(!Ct)Ct=!(await T.workspaceQuery(Mt,{id:c,input:{tunnelStatus:"DISCONNECTED"}})).errors?.length,e().logger.warn(y,"No active tunnel URL \u2014 reported tunnel as DISCONNECTED",{reported:Ct});return}let l=Ct,d=T.getConfig()?.workspaceId||"",u;if(d)u=(await T.workspaceQuery(gi,{workspaceId:d})).data?.vibecontrolsAgents?.find((g)=>g.id===c)?.tunnelUrl??null;let f=o!==gt,h=u!==void 0&&u!==o;if(!f&&!h&&!l)return;e().logger.info(y,"Re-publishing tunnel URL",{reason:l?"tunnel-recovered":h?"backend-drift":"local-change",backend:u,local:o,lastReported:gt});let _=await T.workspaceQuery(Mt,{id:c,input:{tunnelUrl:o,tunnelStatus:"CONNECTED"}});if(!_.errors?.length)gt=o,Ct=!1,e().logger.info(y,"Tunnel URL synced to backend",{tunnelUrl:o});else e().logger.warn(y,"Tunnel URL sync returned errors",{errors:_.errors.map((p)=>p.message)})}catch(a){e().logger.debug(y,`Tunnel sync check failed: ${a instanceof Error?a.message:String(a)}`)}},n),Nt.unref?.()}function pi(){if(Nt)clearInterval(Nt),Nt=null;Ct=!1,gt=null}async function Rr(t,i){if(process.env.VIBE_BRIDGE_DISABLED==="1")return;try{let{bridgeClient:r}=await import("./bridge-client-9ax1cvj6.js"),{registerBridgeCommands:s,registerPluginBridgeService:n}=await import("./bridge-commands-6dj7ewgx.js");s(r,t),n(t,r);let a=process.env.VIBECONTROLS_PROFILE||"default";r.start(i,a)}catch(r){e().logger.warn(y,`bridge-client start failed: ${r instanceof Error?r.message:String(r)}`)}}async function mi(t,i,r){if(!T.isConfigured()){e().logger.debug(y,"Gateway auth not configured \u2014 skipping auto-report");return}let s=await t.getConfig("gateway-auth:workspaceId");if(!s){e().logger.warn(y,"No workspaceId configured \u2014 skipping auto-report. "+"Configure via POST /api/agent/gateway-auth with workspaceId.");return}e().logger.info(y,"Starting auto-report to backend...");try{let n=process.env.VIBE_AGENT_NAME||ui.hostname(),a=ui.platform(),o=ui.arch(),c=Ae(),l=await qd(i),d=await Nr(t,n);if(d){e().logger.info(y,`Updating agent record ${d} via workspace gateway`);let f=await T.workspaceQuery(Mt,{id:d,input:{tunnelUrl:l||null,tunnelStatus:l?"CONNECTED":"DISCONNECTED",agentApiKey:r}});if(f.errors?.length){if(e().logger.warn(y,"Update mutation returned errors",{errors:f.errors.map((_)=>_.message)}),await Ud(s,d)){e().logger.warn(y,"Agent record still exists \u2014 treating update failure as transient; will retry on next sync (NOT registering a duplicate)",{agentRecordId:d}),await Rr(i,d),await Ha(s,{hostname:n,platform:a,arch:o,tunnelUrl:l,apiKey:r}),await _i(d),gt=l,Pt(t,i),Ot(t);return}e().logger.info(y,"Cached agent record no longer exists \u2014 clearing cache and registering fresh",{agentRecordId:d}),await t.setConfig("gateway-auth:agentRecordId",""),d=null}else{e().logger.info(y,"Agent record updated successfully",{agentRecordId:d,tunnelUrl:l}),await Rr(i,d),await Ga(d,l,s),await Ha(s,{hostname:n,platform:a,arch:o,tunnelUrl:l,apiKey:r}),await _i(d),gt=l,Pt(t,i),Ot(t);return}}e().logger.info(y,`Registering installed agent via workspace gateway (hostname: ${n})`);for(let f=1;f<=et&&!d;f++){if(f>1){let g=await Nr(t,n);if(g){d=g,e().logger.info(y,"Adopted an agent record discovered after a retry (not registering a duplicate)",{agentRecordId:d});break}}let h=await T.workspaceQuery(Wa,{workspaceId:s,input:{name:n,hostname:n,platform:a,architecture:o,tunnelUrl:l||null,agentApiKey:r}}),_=h.errors?.length?void 0:h.data?.registerInstalledAgent?.id;if(_){await t.setConfig("gateway-auth:agentRecordId",_),d=_,e().logger.info(y,"Agent registered successfully",{agentRecordId:_,name:h.data?.registerInstalledAgent?.name,tunnelUrl:l,version:c,attempt:f});break}let p=h.errors?.length?h.errors.map((g)=>g.message):["registerInstalledAgent returned no id"];if(f<et){let g=Math.min(30000,Cr*2**(f-1));e().logger.warn(y,`Register installed agent failed (attempt ${f}/${et}) \u2014 retrying in ${Math.round(g/1000)}s`,{errors:p}),await new Promise((m)=>setTimeout(m,g));continue}e().logger.error(y,"Register installed agent failed after retries \u2014 agent is running but NOT registered with the workspace",{errors:p}),e().recordDegradedReason("agent-registration",`registerInstalledAgent failed after ${et} attempts: ${p.join("; ")}`)}if(!d){Pt(t,i),Ot(t);return}let u=await T.workspaceQuery(Mt,{id:d,input:{tunnelUrl:l||null,tunnelStatus:l?"CONNECTED":"DISCONNECTED"}});if(u.errors?.length)e().logger.warn(y,"Post-registration agent update returned errors",{errors:u.errors.map((f)=>f.message)});else e().logger.info(y,"Post-registration agent sync completed",{agentRecordId:d,tunnelUrl:l});await Rr(i,d),await Ga(d,l,s),await _i(d),gt=l,Pt(t,i),Ot(t)}catch(n){e().logger.error(y,`Auto-report failed: ${n instanceof Error?n.message:String(n)}`);try{Pt(t,i),Ot(t)}catch{}}}var x="lifecycle";class Rt{serviceRegistry;pluginManager;db;app;hostServices;appStopFn;state="running";transition=Promise.resolve();constructor(t,i,r,s,n,a){this.serviceRegistry=t;this.pluginManager=i;this.db=r;this.app=s;this.hostServices=n;this.appStopFn=a}getState(){return this.state}enqueueTransition(t,i){let r=this.transition.then(i,i);return this.transition=r.catch((s)=>{e().logger.warn(x,`Lifecycle transition '${t}' failed`,{error:String(s)})}),r}async stop(){return this.enqueueTransition("stop",async()=>{if(this.state==="stopped"){e().logger.warn(x,"Agent is already stopped");return}e().logger.info(x,"Stopping agent..."),this.state="stopped";let t=this.serviceRegistry.getProvider("session");if(t)try{let i=await t.list();for(let r of i)if(r.status==="active")try{await t.kill(r.id),e().logger.debug(x,`Killed session ${r.id}`)}catch(s){e().logger.warn(x,`Failed to kill session ${r.id}`,{error:String(s)})}}catch(i){e().logger.warn(x,"Failed to list/stop sessions",{error:String(i)})}try{await this.pluginManager.dispatchServerStop()}catch(i){e().logger.warn(x,"Error during plugin stop dispatch",{error:String(i)})}e().logger.info(x,"Agent stopped (tunnel + HTTP still alive)");try{await yi(this.db,"stopped")}catch(i){e().logger.warn(x,"Failed to report stopped state to backend",{error:String(i)})}})}async start(){return this.enqueueTransition("start",async()=>{if(this.state==="running"){e().logger.warn(x,"Agent is already running");return}e().logger.info(x,"Starting agent..."),this.state="running";try{await this.pluginManager.dispatchServerStart(this.app,this.hostServices),await this.pluginManager.dispatchServerReady(this.app,this.hostServices)}catch(t){e().logger.warn(x,"Error during plugin start dispatch",{error:String(t)})}e().logger.info(x,"Agent started");try{await yi(this.db,"running")}catch(t){e().logger.warn(x,"Failed to report running state to backend",{error:String(t)})}})}async softStop(){return this.enqueueTransition("softStop",async()=>{e().logger.info(x,"Soft-stopping agent (hot-reload)...");try{await this.pluginManager.dispatchServerStop({reason:"reload"})}catch(t){e().logger.warn(x,"Error during plugin soft-stop dispatch",{error:String(t)})}try{await this.appStopFn({reason:"reload"})}catch{}e().logger.info(x,"Agent soft-stopped \u2014 exiting for reload"),process.exit(0)})}async prepareForReset(){return this.enqueueTransition("prepareForReset",async()=>{e().logger.info(x,"Preparing agent for reset..."),this.state="stopped";try{await this.pluginManager.dispatchServerStop({reason:"shutdown"})}catch(t){e().logger.warn(x,"Error during reset stop dispatch",{error:String(t)})}})}async kill(){return this.enqueueTransition("kill",async()=>{e().logger.info(x,"Killing agent...");try{await Promise.race([yi(this.db,"killed"),new Promise((i,r)=>setTimeout(()=>r(Error("Timeout")),5000))])}catch(i){e().logger.warn(x,"Failed to report killed state to backend",{error:String(i)})}let t=this.serviceRegistry.getProvider("tunnel");if(t)try{let i=await t.list();for(let r of i)try{await t.stop(r.id)}catch{}}catch(i){e().logger.warn(x,"Failed to stop tunnels",{error:String(i)})}try{await this.appStopFn()}catch{}e().logger.info(x,"Agent killed \u2014 exiting process"),process.exit(0)})}}
177
+ `;async function rr(t){try{if(!T.isConfigured())return;let i=await t.getConfig("gateway-auth:agentRecordId");if(!i)return;let r=await T.workspaceQuery(Fd,{agentId:i});if(r.errors?.length)e().logger.debug(y,"Plugin-change notify returned errors",{errors:r.errors.map((s)=>s.message)})}catch(i){e().logger.debug(y,`Plugin-change notify failed: ${i instanceof Error?i.message:String(i)}`)}}var Nt=null,gt=null,Ct=!1;function Pt(t,i,r){if(Nt)return;let s=Number(process.env.VIBE_TUNNEL_SYNC_MS),n=Number.isFinite(s)&&s>0?s:r??60000;Nt=setInterval(async()=>{if(!T.isConfigured())return;try{let a=i.getProvider("tunnel");if(!a||!a.getActiveTunnelUrl)return;let o=Wt(await a.getActiveTunnelUrl()),c=await t.getConfig("gateway-auth:agentRecordId");if(!c)return;if(await _i(c),!o){if(!Ct)Ct=!(await T.workspaceQuery(Mt,{id:c,input:{tunnelStatus:"DISCONNECTED"}})).errors?.length,e().logger.warn(y,"No active tunnel URL \u2014 reported tunnel as DISCONNECTED",{reported:Ct});return}let l=Ct,d=T.getConfig()?.workspaceId||"",u;if(d)u=(await T.workspaceQuery(gi,{workspaceId:d})).data?.vibecontrolsAgents?.find((g)=>g.id===c)?.tunnelUrl??null;let f=o!==gt,h=u!==void 0&&u!==o;if(!f&&!h&&!l)return;e().logger.info(y,"Re-publishing tunnel URL",{reason:l?"tunnel-recovered":h?"backend-drift":"local-change",backend:u,local:o,lastReported:gt});let _=await T.workspaceQuery(Mt,{id:c,input:{tunnelUrl:o,tunnelStatus:"CONNECTED"}});if(!_.errors?.length)gt=o,Ct=!1,e().logger.info(y,"Tunnel URL synced to backend",{tunnelUrl:o});else e().logger.warn(y,"Tunnel URL sync returned errors",{errors:_.errors.map((p)=>p.message)})}catch(a){e().logger.debug(y,`Tunnel sync check failed: ${a instanceof Error?a.message:String(a)}`)}},n),Nt.unref?.()}function pi(){if(Nt)clearInterval(Nt),Nt=null;Ct=!1,gt=null}async function Rr(t,i){if(process.env.VIBE_BRIDGE_DISABLED==="1")return;try{let{bridgeClient:r}=await import("./bridge-client-9ax1cvj6.js"),{registerBridgeCommands:s,registerPluginBridgeService:n}=await import("./bridge-commands-xhzhghxt.js");s(r,t),n(t,r);let a=process.env.VIBECONTROLS_PROFILE||"default";r.start(i,a)}catch(r){e().logger.warn(y,`bridge-client start failed: ${r instanceof Error?r.message:String(r)}`)}}async function mi(t,i,r){if(!T.isConfigured()){e().logger.debug(y,"Gateway auth not configured \u2014 skipping auto-report");return}let s=await t.getConfig("gateway-auth:workspaceId");if(!s){e().logger.warn(y,"No workspaceId configured \u2014 skipping auto-report. "+"Configure via POST /api/agent/gateway-auth with workspaceId.");return}e().logger.info(y,"Starting auto-report to backend...");try{let n=process.env.VIBE_AGENT_NAME||ui.hostname(),a=ui.platform(),o=ui.arch(),c=Ae(),l=await qd(i),d=await Nr(t,n);if(d){e().logger.info(y,`Updating agent record ${d} via workspace gateway`);let f=await T.workspaceQuery(Mt,{id:d,input:{tunnelUrl:l||null,tunnelStatus:l?"CONNECTED":"DISCONNECTED",agentApiKey:r}});if(f.errors?.length){if(e().logger.warn(y,"Update mutation returned errors",{errors:f.errors.map((_)=>_.message)}),await Ud(s,d)){e().logger.warn(y,"Agent record still exists \u2014 treating update failure as transient; will retry on next sync (NOT registering a duplicate)",{agentRecordId:d}),await Rr(i,d),await Ha(s,{hostname:n,platform:a,arch:o,tunnelUrl:l,apiKey:r}),await _i(d),gt=l,Pt(t,i),Ot(t);return}e().logger.info(y,"Cached agent record no longer exists \u2014 clearing cache and registering fresh",{agentRecordId:d}),await t.setConfig("gateway-auth:agentRecordId",""),d=null}else{e().logger.info(y,"Agent record updated successfully",{agentRecordId:d,tunnelUrl:l}),await Rr(i,d),await Ga(d,l,s),await Ha(s,{hostname:n,platform:a,arch:o,tunnelUrl:l,apiKey:r}),await _i(d),gt=l,Pt(t,i),Ot(t);return}}e().logger.info(y,`Registering installed agent via workspace gateway (hostname: ${n})`);for(let f=1;f<=et&&!d;f++){if(f>1){let g=await Nr(t,n);if(g){d=g,e().logger.info(y,"Adopted an agent record discovered after a retry (not registering a duplicate)",{agentRecordId:d});break}}let h=await T.workspaceQuery(Wa,{workspaceId:s,input:{name:n,hostname:n,platform:a,architecture:o,tunnelUrl:l||null,agentApiKey:r}}),_=h.errors?.length?void 0:h.data?.registerInstalledAgent?.id;if(_){await t.setConfig("gateway-auth:agentRecordId",_),d=_,e().logger.info(y,"Agent registered successfully",{agentRecordId:_,name:h.data?.registerInstalledAgent?.name,tunnelUrl:l,version:c,attempt:f});break}let p=h.errors?.length?h.errors.map((g)=>g.message):["registerInstalledAgent returned no id"];if(f<et){let g=Math.min(30000,Cr*2**(f-1));e().logger.warn(y,`Register installed agent failed (attempt ${f}/${et}) \u2014 retrying in ${Math.round(g/1000)}s`,{errors:p}),await new Promise((m)=>setTimeout(m,g));continue}e().logger.error(y,"Register installed agent failed after retries \u2014 agent is running but NOT registered with the workspace",{errors:p}),e().recordDegradedReason("agent-registration",`registerInstalledAgent failed after ${et} attempts: ${p.join("; ")}`)}if(!d){Pt(t,i),Ot(t);return}let u=await T.workspaceQuery(Mt,{id:d,input:{tunnelUrl:l||null,tunnelStatus:l?"CONNECTED":"DISCONNECTED"}});if(u.errors?.length)e().logger.warn(y,"Post-registration agent update returned errors",{errors:u.errors.map((f)=>f.message)});else e().logger.info(y,"Post-registration agent sync completed",{agentRecordId:d,tunnelUrl:l});await Rr(i,d),await Ga(d,l,s),await _i(d),gt=l,Pt(t,i),Ot(t)}catch(n){e().logger.error(y,`Auto-report failed: ${n instanceof Error?n.message:String(n)}`);try{Pt(t,i),Ot(t)}catch{}}}var x="lifecycle";class Rt{serviceRegistry;pluginManager;db;app;hostServices;appStopFn;state="running";transition=Promise.resolve();constructor(t,i,r,s,n,a){this.serviceRegistry=t;this.pluginManager=i;this.db=r;this.app=s;this.hostServices=n;this.appStopFn=a}getState(){return this.state}enqueueTransition(t,i){let r=this.transition.then(i,i);return this.transition=r.catch((s)=>{e().logger.warn(x,`Lifecycle transition '${t}' failed`,{error:String(s)})}),r}async stop(){return this.enqueueTransition("stop",async()=>{if(this.state==="stopped"){e().logger.warn(x,"Agent is already stopped");return}e().logger.info(x,"Stopping agent..."),this.state="stopped";let t=this.serviceRegistry.getProvider("session");if(t)try{let i=await t.list();for(let r of i)if(r.status==="active")try{await t.kill(r.id),e().logger.debug(x,`Killed session ${r.id}`)}catch(s){e().logger.warn(x,`Failed to kill session ${r.id}`,{error:String(s)})}}catch(i){e().logger.warn(x,"Failed to list/stop sessions",{error:String(i)})}try{await this.pluginManager.dispatchServerStop()}catch(i){e().logger.warn(x,"Error during plugin stop dispatch",{error:String(i)})}e().logger.info(x,"Agent stopped (tunnel + HTTP still alive)");try{await yi(this.db,"stopped")}catch(i){e().logger.warn(x,"Failed to report stopped state to backend",{error:String(i)})}})}async start(){return this.enqueueTransition("start",async()=>{if(this.state==="running"){e().logger.warn(x,"Agent is already running");return}e().logger.info(x,"Starting agent..."),this.state="running";try{await this.pluginManager.dispatchServerStart(this.app,this.hostServices),await this.pluginManager.dispatchServerReady(this.app,this.hostServices)}catch(t){e().logger.warn(x,"Error during plugin start dispatch",{error:String(t)})}e().logger.info(x,"Agent started");try{await yi(this.db,"running")}catch(t){e().logger.warn(x,"Failed to report running state to backend",{error:String(t)})}})}async softStop(){return this.enqueueTransition("softStop",async()=>{e().logger.info(x,"Soft-stopping agent (hot-reload)...");try{await this.pluginManager.dispatchServerStop({reason:"reload"})}catch(t){e().logger.warn(x,"Error during plugin soft-stop dispatch",{error:String(t)})}try{await this.appStopFn({reason:"reload"})}catch{}e().logger.info(x,"Agent soft-stopped \u2014 exiting for reload"),process.exit(0)})}async prepareForReset(){return this.enqueueTransition("prepareForReset",async()=>{e().logger.info(x,"Preparing agent for reset..."),this.state="stopped";try{await this.pluginManager.dispatchServerStop({reason:"shutdown"})}catch(t){e().logger.warn(x,"Error during reset stop dispatch",{error:String(t)})}})}async kill(){return this.enqueueTransition("kill",async()=>{e().logger.info(x,"Killing agent...");try{await Promise.race([yi(this.db,"killed"),new Promise((i,r)=>setTimeout(()=>r(Error("Timeout")),5000))])}catch(i){e().logger.warn(x,"Failed to report killed state to backend",{error:String(i)})}let t=this.serviceRegistry.getProvider("tunnel");if(t)try{let i=await t.list();for(let r of i)try{await t.stop(r.id)}catch{}}catch(i){e().logger.warn(x,"Failed to stop tunnels",{error:String(i)})}try{await this.appStopFn()}catch{}e().logger.info(x,"Agent killed \u2014 exiting process"),process.exit(0)})}}
178
178
  export{er,tr,Rt,hi,fi,rr,pi,mi};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{e}from"./index-7wm4bqx5.js";import{E}from"./index-1t74r13z.js";import{lr}from"./index-awj0w14r.js";import{je,Kt,me,yt,rt,it,K}from"./index-qzwbctkv.js";var T=["tunnel","session","ai","plan","gitops","security","desk"];class xe{providers=new Map;providerOrder=new Map;defaults=new Map;services=new Map;db;constructor(t){this.db=t}getDb(){return this.db}setProviderDefault(t,r){this.defaults.set(t,r)}clearProviderDefault(t,r){if(!r||this.defaults.get(t)===r)this.defaults.delete(t)}async hydrateDefaultsFromDb(){if(!this.db)return;for(let t of T)try{let r=await this.db.getConfig(`provider:default:${t}`);if(r)this.defaults.set(t,r)}catch{}}registerProvider(t,r,i){if(!this.providers.has(t))this.providers.set(t,new Map),this.providerOrder.set(t,[]);let n=this.providers.get(t),o=this.providerOrder.get(t);if(n.has(i))e().logger.info("service-registry",`Updating ${t} provider from plugin '${i}'`);else e().logger.info("service-registry",`Registered ${t} provider from plugin '${i}'`);if(n.set(i,{provider:r,pluginName:i,registeredAt:new Date}),!o.includes(i))o.push(i)}getProvider(t){let r=this.providers.get(t);if(!r||r.size===0)return;let i=this.defaults.get(t);if(i&&r.has(i))return r.get(i).provider;let n=this.providerOrder.get(t);if(n&&n.length>0){let o=n[0];return r.get(o)?.provider}return}getProviderByName(t,r){let i=this.providers.get(t);if(!i)return;return i.get(r)?.provider}hasProvider(t){let r=this.providers.get(t);return!!r&&r.size>0}unregisterProvider(t,r){let i=this.providers.get(t);if(!i)return!1;let n=i.delete(r);if(n){let o=this.providerOrder.get(t);if(o){let s=o.indexOf(r);if(s!==-1)o.splice(s,1)}this.clearProviderDefault(t,r),e().logger.info("service-registry",`Unregistered ${t} provider from plugin '${r}'`)}return n}unregisterPlugin(t){for(let r of T)this.unregisterProvider(r,t);this.unregisterServices(t)}listProvidersForType(t){let r=this.providers.get(t);if(!r)return[];let i=this.defaults.get(t);if(!i||!r.has(i)){let n=this.providerOrder.get(t);i=n&&n.length>0?n[0]:void 0}return Array.from(r.keys()).map((n)=>({pluginName:n,isDefault:n===i}))}registerService(t,r,i){let n=`${t}:${r}`;this.services.set(n,{service:i,pluginName:t}),e().logger.debug("service-registry",`Registered service '${n}'`)}getService(t,r){let i=`${t}:${r}`;return this.services.get(i)?.service}unregisterServices(t){let r=[];for(let[i,n]of this.services)if(n.pluginName===t)r.push(i);for(let i of r)this.services.delete(i);if(r.length>0)e().logger.info("service-registry",`Unregistered ${r.length} services from ${t}`)}listProviders(){let t=[];for(let[r,i]of this.providers)for(let[n,o]of i)t.push({type:r,name:n,pluginName:o.pluginName});return t}listServices(){return Array.from(this.services.entries()).map(([t,r])=>({pluginName:r.pluginName,serviceName:t.split(":").slice(1).join(":")}))}clear(){this.providers.clear(),this.providerOrder.clear(),this.defaults.clear(),this.services.clear()}}class Ie{statusSections=[];doctorChecks=[];addStatusSection(t){this.statusSections.push(t)}addDoctorCheck(t){this.doctorChecks.push(t)}getStatusSections(){return this.statusSections}getDoctorChecks(){return this.doctorChecks}}var y=null;function Fi(t){y=t}function Nt(){if(!y)y=new Ie;return y}import{extname as N,relative as j,resolve as O}from"path";import{realpath as b}from"fs/promises";var B=["'self'","http://localhost:*","http://127.0.0.1:*","https://localhost:*","https://127.0.0.1:*","https://*.local.burdenoff.com","https://vibecontrols.com","https://*.vibecontrols.com","https://burdenoff.com","https://app.burdenoff.com","https://alphaapp.burdenoff.com"],R=!1;function f(){let t=process.env.VIBE_UI_FRAME_ANCESTORS?.trim(),r=t?t.split(/[\s,]+/).filter(Boolean):B;if(t&&!R&&(r.includes("*")||!r.includes("'self'")))R=!0,console.warn(`[ui-server] VIBE_UI_FRAME_ANCESTORS override does not include "'self'" or contains "*". This significantly weakens CSP frame-ancestors and is almost never intended. Override: ${t}`);return`frame-ancestors ${r.join(" ")}`}var M={".html":"text/html",".js":"application/javascript",".mjs":"application/javascript",".css":"text/css",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".map":"application/json",".wasm":"application/wasm"};function F(t){return M[N(t).toLowerCase()]||"application/octet-stream"}var k=`<script>
2
+ import{e}from"./index-7wm4bqx5.js";import{E}from"./index-1t74r13z.js";import{lr}from"./index-p1b10hs1.js";import{je,Kt,me,yt,rt,it,K}from"./index-qzwbctkv.js";var T=["tunnel","session","ai","plan","gitops","security","desk"];class xe{providers=new Map;providerOrder=new Map;defaults=new Map;services=new Map;db;constructor(t){this.db=t}getDb(){return this.db}setProviderDefault(t,r){this.defaults.set(t,r)}clearProviderDefault(t,r){if(!r||this.defaults.get(t)===r)this.defaults.delete(t)}async hydrateDefaultsFromDb(){if(!this.db)return;for(let t of T)try{let r=await this.db.getConfig(`provider:default:${t}`);if(r)this.defaults.set(t,r)}catch{}}registerProvider(t,r,i){if(!this.providers.has(t))this.providers.set(t,new Map),this.providerOrder.set(t,[]);let n=this.providers.get(t),o=this.providerOrder.get(t);if(n.has(i))e().logger.info("service-registry",`Updating ${t} provider from plugin '${i}'`);else e().logger.info("service-registry",`Registered ${t} provider from plugin '${i}'`);if(n.set(i,{provider:r,pluginName:i,registeredAt:new Date}),!o.includes(i))o.push(i)}getProvider(t){let r=this.providers.get(t);if(!r||r.size===0)return;let i=this.defaults.get(t);if(i&&r.has(i))return r.get(i).provider;let n=this.providerOrder.get(t);if(n&&n.length>0){let o=n[0];return r.get(o)?.provider}return}getProviderByName(t,r){let i=this.providers.get(t);if(!i)return;return i.get(r)?.provider}hasProvider(t){let r=this.providers.get(t);return!!r&&r.size>0}unregisterProvider(t,r){let i=this.providers.get(t);if(!i)return!1;let n=i.delete(r);if(n){let o=this.providerOrder.get(t);if(o){let s=o.indexOf(r);if(s!==-1)o.splice(s,1)}this.clearProviderDefault(t,r),e().logger.info("service-registry",`Unregistered ${t} provider from plugin '${r}'`)}return n}unregisterPlugin(t){for(let r of T)this.unregisterProvider(r,t);this.unregisterServices(t)}listProvidersForType(t){let r=this.providers.get(t);if(!r)return[];let i=this.defaults.get(t);if(!i||!r.has(i)){let n=this.providerOrder.get(t);i=n&&n.length>0?n[0]:void 0}return Array.from(r.keys()).map((n)=>({pluginName:n,isDefault:n===i}))}registerService(t,r,i){let n=`${t}:${r}`;this.services.set(n,{service:i,pluginName:t}),e().logger.debug("service-registry",`Registered service '${n}'`)}getService(t,r){let i=`${t}:${r}`;return this.services.get(i)?.service}unregisterServices(t){let r=[];for(let[i,n]of this.services)if(n.pluginName===t)r.push(i);for(let i of r)this.services.delete(i);if(r.length>0)e().logger.info("service-registry",`Unregistered ${r.length} services from ${t}`)}listProviders(){let t=[];for(let[r,i]of this.providers)for(let[n,o]of i)t.push({type:r,name:n,pluginName:o.pluginName});return t}listServices(){return Array.from(this.services.entries()).map(([t,r])=>({pluginName:r.pluginName,serviceName:t.split(":").slice(1).join(":")}))}clear(){this.providers.clear(),this.providerOrder.clear(),this.defaults.clear(),this.services.clear()}}class Ie{statusSections=[];doctorChecks=[];addStatusSection(t){this.statusSections.push(t)}addDoctorCheck(t){this.doctorChecks.push(t)}getStatusSections(){return this.statusSections}getDoctorChecks(){return this.doctorChecks}}var y=null;function Fi(t){y=t}function Nt(){if(!y)y=new Ie;return y}import{extname as N,relative as j,resolve as O}from"path";import{realpath as b}from"fs/promises";var B=["'self'","http://localhost:*","http://127.0.0.1:*","https://localhost:*","https://127.0.0.1:*","https://*.local.burdenoff.com","https://vibecontrols.com","https://*.vibecontrols.com","https://burdenoff.com","https://app.burdenoff.com","https://alphaapp.burdenoff.com"],R=!1;function f(){let t=process.env.VIBE_UI_FRAME_ANCESTORS?.trim(),r=t?t.split(/[\s,]+/).filter(Boolean):B;if(t&&!R&&(r.includes("*")||!r.includes("'self'")))R=!0,console.warn(`[ui-server] VIBE_UI_FRAME_ANCESTORS override does not include "'self'" or contains "*". This significantly weakens CSP frame-ancestors and is almost never intended. Override: ${t}`);return`frame-ancestors ${r.join(" ")}`}var M={".html":"text/html",".js":"application/javascript",".mjs":"application/javascript",".css":"text/css",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".map":"application/json",".wasm":"application/wasm"};function F(t){return M[N(t).toLowerCase()]||"application/octet-stream"}var k=`<script>
3
3
  window.__VIBE_AUTH__={apiKey:null};
4
4
  (function(){
5
5
  var p=new URLSearchParams(window.location.search);