@vibecontrols/agent 2026.902.1 → 2026.1124.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent-config-v9d7gcz0.js +2 -0
- package/dist/agent-ready-tracker-mewxehg9.js +2 -0
- package/dist/app-k7z7tjem.js +2 -0
- package/dist/autostart.cmd-ahet7b1t.js +2 -0
- package/dist/bootstrap-workspace-3pb8qjsh.js +2 -0
- package/dist/bootstrap.service-9m7m1ksa.js +2 -0
- package/dist/bridge-client-xvqy3n15.js +2 -0
- package/dist/cli.js +2 -2
- package/dist/daemon-profile-sg8fp50z.js +2 -0
- package/dist/finalize-retry-handle-registry-z9mbbjmj.js +2 -0
- package/dist/finalize-retry-worker-az74f2qv.js +2 -0
- package/dist/gateway-client-ermpz52n.js +2 -0
- package/dist/getMachineId-bsd-4w1wmcjv.js +2 -0
- package/dist/getMachineId-darwin-kejwz8w5.js +3 -0
- package/dist/getMachineId-linux-mpm53wat.js +2 -0
- package/dist/getMachineId-unsupported-54seyw5v.js +2 -0
- package/dist/getMachineId-win-cva7ghz9.js +2 -0
- package/dist/highlights-3nz7pbkh.js +2 -0
- package/dist/highlights-6dgztt5d.js +2 -0
- package/dist/highlights-jq0g1547.js +2 -0
- package/dist/highlights-yc7cwzcr.js +2 -0
- package/dist/highlights-z2sw1kpq.js +2 -0
- package/dist/index-01fp85ft.js +171 -0
- package/dist/index-06bmw4xf.js +83 -0
- package/dist/index-0gmhd3hs.js +4 -0
- package/dist/index-0qjbnyg4.js +21 -0
- package/dist/index-2r6cmxxz.js +9 -0
- package/dist/index-2vcxt38h.js +3 -0
- package/dist/index-3b5xejjs.js +5 -0
- package/dist/index-3cbesatx.js +178 -0
- package/dist/index-4q8y6k1e.js +26 -0
- package/dist/index-4z1y39jt.js +3 -0
- package/dist/index-5021rk8n.js +3 -0
- package/dist/index-652f9scs.js +4 -0
- package/dist/index-76m37yd8.js +22 -0
- package/dist/index-7f2k4g6q.js +8 -0
- package/dist/index-7gk1x74m.js +15 -0
- package/dist/index-7wben1jx.js +3 -0
- package/dist/index-8rbhm4g8.js +7 -0
- package/dist/index-9bj65n3s.js +13 -0
- package/dist/index-9xrhb68w.js +14 -0
- package/dist/index-a0vx2zyx.js +3 -0
- package/dist/index-aav1drxa.js +158 -0
- package/dist/index-akk3rxnn.js +4 -0
- package/dist/index-b3v08awy.js +3 -0
- package/dist/index-byerrz46.js +3 -0
- package/dist/index-c4whjk5r.js +3 -0
- package/dist/index-cy97asyh.js +133 -0
- package/dist/index-d59kp6zr.js +3 -0
- package/dist/index-haww9jpq.js +27 -0
- package/dist/index-hsrt2v87.js +2 -0
- package/dist/index-jmx5awkj.js +3 -0
- package/dist/index-jnxjjx2y.js +3 -0
- package/dist/index-kwhx023z.js +11 -0
- package/dist/index-m942hydk.js +116 -0
- package/dist/index-mmx2kp76.js +16 -0
- package/dist/index-p0bbp16g.js +11 -0
- package/dist/index-qe3xpt41.js +3 -0
- package/dist/index-qfxwk38p.js +82 -0
- package/dist/index-ss5gez2p.js +2 -0
- package/dist/index-t5cfkz1e.js +4 -0
- package/dist/index-t6p4szqx.js +5 -0
- package/dist/index-tahaxp6n.js +3 -0
- package/dist/index-v16qz1fa.js +3 -0
- package/dist/index-vtsd74g0.js +9 -0
- package/dist/index-w0m3jm0s.js +408 -0
- package/dist/index-w4jqdhc2.js +5 -0
- package/dist/index-wr888ydc.js +17 -0
- package/dist/index-xtd0j8ve.js +3 -0
- package/dist/index-ywnfz6nm.js +3 -0
- package/dist/index.js +3 -3
- package/dist/injections-h25c1fmk.js +2 -0
- package/dist/interactive-vbz68zh5.js +2 -0
- package/dist/key.cmd-f6rjvjy8.js +2 -0
- package/dist/log-shipper-0erbwn0q.js +2 -0
- package/dist/path-utils-r4df8d3w.js +2 -0
- package/dist/plugin-system-kvg955t3.js +2 -0
- package/dist/prereqs-runner-gca0bytz.js +2 -0
- package/dist/profile-mount-s4mc1x18.js +2 -0
- package/dist/prune-stale-shims-4nqtv0xt.js +2 -0
- package/dist/register-core-31wm1d8m.js +2 -0
- package/dist/secondary-profile-attach-95kmnrhf.js +2 -0
- package/dist/subprocess-4gg77skg.js +2 -0
- package/dist/telemetry-nmtywcba.js +2 -0
- package/dist/tree-sitter-javascript-rfadfcwb.js +2 -0
- package/dist/tree-sitter-markdown-gkyb2qez.js +2 -0
- package/dist/tree-sitter-markdown_inline-xzttqkvb.js +2 -0
- package/dist/tree-sitter-typescript-4z897028.js +2 -0
- package/dist/tree-sitter-zig-y6n7djp6.js +2 -0
- package/dist/tunnel-bootstrap-rym0b0x5.js +2 -0
- package/package.json +10 -9
- package/dist/agent-config-5b0avmy6.js +0 -2
- package/dist/agent-ready-tracker-ez6r9djg.js +0 -2
- package/dist/app-mhms2gs0.js +0 -2
- package/dist/autostart.cmd-4zb9xhj0.js +0 -2
- package/dist/bootstrap-workspace-t5fyq07m.js +0 -2
- package/dist/bootstrap.service-nxhkrsf1.js +0 -2
- package/dist/bridge-client-bgkr7bcn.js +0 -2
- package/dist/daemon-profile-j2wt35x8.js +0 -2
- package/dist/esm-n9r8p5n2.js +0 -2
- package/dist/finalize-retry-handle-registry-fvm4gm8s.js +0 -2
- package/dist/finalize-retry-worker-wb8wj1yw.js +0 -2
- package/dist/gateway-client-6dqagbg4.js +0 -2
- package/dist/getMachineId-bsd-fgatzdd7.js +0 -2
- package/dist/getMachineId-darwin-gt8j2jw2.js +0 -3
- package/dist/getMachineId-linux-bcz4rr1x.js +0 -2
- package/dist/getMachineId-unsupported-079qwwb4.js +0 -2
- package/dist/getMachineId-win-2hk4e8bg.js +0 -2
- package/dist/highlights-0gfz787m.js +0 -2
- package/dist/highlights-86sbx76f.js +0 -2
- package/dist/highlights-n55f5jnk.js +0 -2
- package/dist/highlights-tbmszdr7.js +0 -2
- package/dist/highlights-wm2cs773.js +0 -2
- package/dist/index-06es0fmw.js +0 -10
- package/dist/index-0d4wfjbt.js +0 -171
- package/dist/index-29fmptfn.js +0 -13
- package/dist/index-2q2jadag.js +0 -11
- package/dist/index-2sn36kaj.js +0 -7
- package/dist/index-3p4n7nwg.js +0 -83
- package/dist/index-3tf12pw3.js +0 -3
- package/dist/index-54mmh1eb.js +0 -4
- package/dist/index-6jzsthh9.js +0 -3
- package/dist/index-7wejfjj9.js +0 -5
- package/dist/index-8q19ryt2.js +0 -28
- package/dist/index-8xh8m2z7.js +0 -8
- package/dist/index-98gr644s.js +0 -116
- package/dist/index-a8n6s2ae.js +0 -2
- package/dist/index-b16y8wyz.js +0 -15
- package/dist/index-bv1z3fxw.js +0 -3
- package/dist/index-cs78wq6y.js +0 -3
- package/dist/index-df19rrbe.js +0 -5
- package/dist/index-dx9hjdp4.js +0 -178
- package/dist/index-ea42kfvk.js +0 -5
- package/dist/index-ekr40gvh.js +0 -3
- package/dist/index-evnbrmdf.js +0 -4
- package/dist/index-f2asckf0.js +0 -26
- package/dist/index-ggxs7nwz.js +0 -3
- package/dist/index-gz5t0vvc.js +0 -4
- package/dist/index-hey6w5m0.js +0 -3
- package/dist/index-hp8jrj6j.js +0 -3
- package/dist/index-hrfkzecw.js +0 -3
- package/dist/index-hwpmdq5z.js +0 -4
- package/dist/index-hz5cy6vz.js +0 -11
- package/dist/index-jbxh0ffn.js +0 -407
- package/dist/index-js2r0men.js +0 -9
- package/dist/index-k3jkzj3k.js +0 -9
- package/dist/index-kteawn2b.js +0 -3
- package/dist/index-mbhq916m.js +0 -3
- package/dist/index-mxc61yr1.js +0 -3
- package/dist/index-qdbxvcwr.js +0 -17
- package/dist/index-qqq9qyy6.js +0 -21
- package/dist/index-rmh8pff5.js +0 -3
- package/dist/index-sspydg85.js +0 -15
- package/dist/index-tk81f249.js +0 -3
- package/dist/index-vjdg5qb2.js +0 -2
- package/dist/index-vkrf8kzp.js +0 -158
- package/dist/index-vnxqna70.js +0 -16
- package/dist/index-w7gctzhm.js +0 -83
- package/dist/index-wj5hx7gq.js +0 -4
- package/dist/index-x4eaagvr.js +0 -3
- package/dist/index-xjr60th0.js +0 -3
- package/dist/index-xtbppqnv.js +0 -3
- package/dist/index-y42xsgr6.js +0 -133
- package/dist/index-zr9rmjyp.js +0 -3
- package/dist/injections-2g0zh0bq.js +0 -2
- package/dist/interactive-08vyaapn.js +0 -2
- package/dist/key.cmd-642xcxb4.js +0 -2
- package/dist/log-shipper-9xfnjwr6.js +0 -2
- package/dist/path-utils-g449hqvm.js +0 -2
- package/dist/plugin-system-gpzcch00.js +0 -2
- package/dist/prereqs-runner-re9f51fp.js +0 -2
- package/dist/profile-mount-txvgkaz8.js +0 -2
- package/dist/prune-stale-shims-vs6a07tb.js +0 -2
- package/dist/register-core-ma4kse87.js +0 -2
- package/dist/secondary-profile-attach-m9x9e7py.js +0 -2
- package/dist/subprocess-zcgpccp1.js +0 -2
- package/dist/telemetry-k6em3vy2.js +0 -2
- package/dist/tree-sitter-javascript-qh90w7td.js +0 -2
- package/dist/tree-sitter-markdown-favzteb6.js +0 -2
- package/dist/tree-sitter-markdown_inline-x2726t9j.js +0 -2
- package/dist/tree-sitter-typescript-m7ep8z1h.js +0 -2
- package/dist/tree-sitter-zig-3vsxg5wh.js +0 -2
- package/dist/tunnel-bootstrap-y8dczezc.js +0 -2
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{r,E}from"./index-w0m3jm0s.js";import{e}from"./index-0qjbnyg4.js";import{ht,bi,wi,ft,le}from"./index-3b5xejjs.js";import{Et,kt}from"./index-5021rk8n.js";import"./index-kwhx023z.js";import{Xt}from"./index-3cbesatx.js";import"./index-mmx2kp76.js";import"./index-qfxwk38p.js";import{xt,pr}from"./index-v16qz1fa.js";import{i,s,A,l,p,o,g,n,F}from"./index-7f2k4g6q.js";import{Q,U}from"./index-vtsd74g0.js";import"./index-0gmhd3hs.js";import"./index-06bmw4xf.js";import{_,y,u}from"./index-t5cfkz1e.js";import{f,m,S,q}from"./index-byerrz46.js";import{timingSafeEqual as me}from"crypto";function fe(){return(process.env.NPM_CONFIG_REGISTRY||process.env.npm_config_registry||"https://registry.npmjs.org").replace(/\/+$/,"")}async function Y(c,R){try{let P=await fetch(`${fe()}/${c}/${R}`,{headers:{accept:"application/json"},signal:AbortSignal.timeout(1e4)});if(P.ok){let a=(await P.json()).dist?.integrity;if(typeof a==="string"&&a.startsWith("sha"))return a}}catch{}try{let P=Bun.spawn({cmd:["npm","view",`${c}@${R}`,"dist.integrity","--json"],stdout:"pipe",stderr:"pipe"});if(await P.exited!==0)return null;let d=(await new Response(P.stdout).text()).trim();if(!d)return null;if(d.startsWith('"'))try{let b=JSON.parse(d);return typeof b==="string"?b:null}catch{return null}return d}catch{return null}}function Z(c,R){let P=Buffer.from(c),t=Buffer.from(R);if(P.length!==t.length)return!1;try{return me(P,t)}catch{return!1}}var ve=bi.map((c)=>({packageName:c.packageName,name:c.pluginName,description:c.description,cliCommand:c.cliCommand,apiPrefix:c.apiPrefix,installed:!1,category:c.category})),W=new Map;function M(c,R){let t=(W.get(c)??Promise.resolve()).then(R,R),a=t.then(()=>{return},()=>{return});return W.set(c,a),a.finally(()=>{if(W.get(c)===a)W.delete(c)}),t}function X(c){return W.has(c)}function ee(c){let R=c.getPluginDetails(),P=new Set(R.map((t)=>t.packageName));return{plugins:ve.map((t)=>({...t,installed:P.has(t.packageName)}))}}function te(c){let{pluginManager:R}=c;return new E().get("/",()=>{let P=R.getPluginDetails();return{plugins:P,count:P.length}}).get("/available",()=>ee(R)).get("/catalog",()=>ee(R)).get("/contributions",({query:P})=>{let t=typeof P?.mountPoint==="string"&&P.mountPoint?P.mountPoint:null,a=[],d=new Map;for(let b of R.getPluginDetails())d.set(b.pluginName,b.packageName);for(let b of R.getAllPlugins()){let N=b.ui;if(!N||!N.contributions||N.contributions.length===0)continue;let v=N.capabilities??{restPaths:[],wsTopics:[],rpcMethods:[]};for(let w of N.contributions){if(t&&w.mountPoint!==t)continue;let h=w.meta,k=h&&typeof h.url==="string"?h.url:null,x=k&&k.startsWith("/")&&!k.startsWith("//")&&!k.includes("\x00")&&!k.includes("..")?k:null;a.push({pluginKey:b.name,pluginPackageName:d.get(b.name),contribution:w,capabilities:w.capabilities??v,url:x??`/ui/${encodeURIComponent(b.name)}`})}}return{contributions:a,count:a.length}}).post("/install",async({body:P,set:t})=>{if(!P.packageName||typeof P.packageName!=="string")return t.status=400,{error:"Missing required field: packageName"};if(P.packageName.startsWith("@burdenoff/"))P.packageName=P.packageName.replace(/^@burdenoff\//,"@vibecontrols/");if(!ft(P.packageName))return t.status=403,{error:"Plugin package is not in the trusted VibeControls catalog"};try{let a=le(P.packageName);if(X(a)){let d=a.split("/").pop()?.replace("vibe-plugin-","");if(R.getAllPlugins().some((N)=>N.name===d))return{success:!0,message:`Plugin ${a} is already installed`,packageName:a,alreadyInstalled:!0};return t.status=409,{error:"Install for this package is already in progress. Wait for it to finish.",packageName:a}}return await M(a,async()=>{let d=a.split("/").pop()?.replace("vibe-plugin-",""),b=d?.startsWith("ai-")?d.slice(3):void 0,N=R.getAllPlugins().find((C)=>C.name===d||C.name===b),v=!!N,w=await R.install(a),h=wi(a);if(h?.integrity){let C=await Y(a,w.version);if(C&&!Z(h.integrity,C)){try{await R.remove(a,c.hostServices)}catch(I){console.warn(`[plugin-mgr] integrity rollback uninstall failed for ${a}:`,I)}return e().audit.emit("agent","plugin.install.rejected",{packageName:a,version:w.version,reason:"integrity_mismatch",expected:h.integrity,actual:C}),t.status=400,{error:"integrity mismatch",expected:h.integrity,actual:C}}if(!C)console.warn(`[plugin-mgr] could not fetch registry integrity for ${a}@${w.version}; accepting the package-manager-verified tarball (pin present but unverifiable)`),e().audit.emit("agent","plugin.install.integrity_unverified",{packageName:a,version:w.version,expected:h.integrity})}else console.warn(`[plugin-mgr] plugin ${a} has no pinned integrity \u2014 accepting npm registry's hash`);let k=R.getAllPlugins().find((C)=>C.name===w.pluginName);if(k){let C=[];if(c.mountPlugin)c.mountPlugin(k);if(c.hostServices){if(v&&N?.onServerStop)try{await N.onServerStop()}catch(I){C.push(`onServerStop failed: ${I instanceof Error?I.message:String(I)}`)}if(R.registerProviders(k,c.hostServices),k.onServerStart&&c.app)try{await k.onServerStart(c.app,c.hostServices),R.registerProviders(k,c.hostServices)}catch(I){C.push(`onServerStart failed: ${I instanceof Error?I.message:String(I)}`)}if(k.onServerReady&&c.app)try{await k.onServerReady(c.app,c.hostServices)}catch(I){C.push(`onServerReady failed: ${I instanceof Error?I.message:String(I)}`)}}if(c.rebuildPluginSurfaces?.(),C.length>0)return t.status=500,{success:!1,message:`Plugin ${a} installed but failed to start`,lifecycleErrors:C,restartRequired:!0}}let x;if(k&&c.app)try{x=await xt(k,a,c.app,c.db,{skipInstall:!!P.skipPrereqs})}catch(C){x=void 0,console.warn(`[plugin-mgr] prereq run failed for ${a}:`,C)}return Xt(c.db),e().audit.emit("agent","plugin.installed",{packageName:a,version:w.version,pluginName:w.pluginName,wasRunning:v}),{success:!0,message:`Plugin ${a} installed and loaded successfully`,prereqs:x?{satisfied:x.satisfied,missing:x.status?.missing??[],pendingSudo:x.pendingSudo,skipped:!!P.skipPrereqs}:void 0}})}catch(a){return t.status=500,{error:"Failed to install plugin",details:String(a)}}},{body:r.Object({packageName:r.String(),skipPrereqs:r.Optional(r.Boolean())})}).post("/prereqs/status",async({body:P,set:t})=>{if(!P.packageName)return t.status=400,{error:"Missing packageName"};let a=P.packageName,d=R.getAllPlugins().find((b)=>b.name===a||R.getLoaded(a)?.name===b.name);if(!d||!c.app)return await pr(c.db,a)??{satisfied:!0,missing:[]};try{let b=await xt(d,a,c.app,c.db,{skipInstall:!0});return{satisfied:b.satisfied,missing:b.status?.missing??[],noProtocol:b.noProtocol}}catch(b){return t.status=500,{error:String(b)}}},{body:r.Object({packageName:r.String()})}).post("/prereqs/install",async({body:P,set:t})=>{if(!P.packageName)return t.status=400,{error:"Missing packageName"};let a=P.packageName,d=R.getAllPlugins().find((b)=>b.name===a||R.getLoaded(a)?.name===b.name);if(!d||!c.app)return t.status=404,{error:"Plugin not loaded"};try{let b=await xt(d,a,c.app,c.db,{skipInstall:!1});return{satisfied:b.satisfied,installed:b.install?.installed??[],pendingSudo:b.pendingSudo,errors:b.install?.errors??[],noProtocol:b.noProtocol}}catch(b){return t.status=500,{error:String(b)}}},{body:r.Object({packageName:r.String(),approveSudo:r.Optional(r.Boolean())})}).post("/prereqs/uninstall",async({body:P,set:t})=>{if(!P.packageName)return t.status=400,{error:"Missing packageName"};let a=P.packageName,d=R.getAllPlugins().find((w)=>w.name===a);if(!d||!d.apiPrefix||!c.app)return t.status=404,{error:"Plugin not loaded"};let b=c.app.handle;if(typeof b!=="function")return t.status=500,{error:"App handle unavailable"};let N=`${d.apiPrefix.replace(/\/+$/,"")}/prereqs/uninstall`,v=await b.call(c.app,new Request(`http://agent.local${N}`,{method:"POST",headers:{"x-vc-profile-rewrite":"1",[Et]:kt()}}));if(v.status===404)return t.status=404,{error:"Plugin has no prereqs/uninstall endpoint"};return v.json()},{body:r.Object({packageName:r.String()})}).post("/nuke",async({body:P,set:t})=>{if(!c.hostServices)return t.status=503,{error:"hostServices unavailable"};let a=c.hostServices.getDataDir?.();return{ok:!0,...await R.runPluginNuke(P.packageName,c.hostServices,{agentDir:a,dryRun:!!P.dryRun})}},{body:r.Object({packageName:r.Optional(r.String()),dryRun:r.Optional(r.Boolean())})}).post("/remove",async({body:P,set:t})=>{if(!P.packageName||typeof P.packageName!=="string")return t.status=400,{error:"Missing required field: packageName"};if(P.packageName.startsWith("@burdenoff/"))P.packageName=P.packageName.replace(/^@burdenoff\//,"@vibecontrols/");if(ht(P.packageName))return{success:!0,message:`Plugin ${P.packageName} is critical and cannot be removed; treating remove as a no-op.`,skipped:!0};try{let a=le(P.packageName);return await M(a,async()=>(await R.remove(a,c.hostServices),c.rebuildPluginSurfaces?.(),Xt(c.db),e().audit.emit("agent","plugin.removed",{packageName:a}),{success:!0,message:`Plugin ${a} removed successfully`}))}catch(a){return t.status=500,{error:"Failed to remove plugin",details:String(a)}}},{body:r.Object({packageName:r.String()})}).post("/update",async({body:P,set:t})=>{if(!P.packageName||typeof P.packageName!=="string")return t.status=400,{error:"Missing required field: packageName"};let a=typeof P.version==="string"&&P.version.trim()?P.version.trim():void 0;if(a&&!/^[0-9][0-9A-Za-z.+-]{0,63}$/.test(a))return t.status=400,{error:`Invalid version "${a}"`};try{let d=le(P.packageName);return await M(d,async()=>{let b=R.getLoaded(d);if(b?.onServerStop)await b.onServerStop({reason:"reload"});if(b&&c.hostServices)c.hostServices.serviceRegistry.unregisterPlugin(b.name);let N=await R.update(d,a),v=R.getLoaded(d);if(v&&c.hostServices){if(R.registerProviders(v,c.hostServices),v.onServerStart&&c.app)await v.onServerStart(c.app,c.hostServices),R.registerProviders(v,c.hostServices);if(v.onServerReady&&c.app)await v.onServerReady(c.app,c.hostServices)}return c.rebuildPluginSurfaces?.(),Xt(c.db),{success:!0,message:`Plugin ${d} updated to v${N.version}`,version:N.version}})}catch(d){return t.status=500,{error:"Failed to update plugin",details:String(d)}}},{body:r.Object({packageName:r.String(),version:r.Optional(r.String())})}).post("/update-all",async({set:P})=>{try{let t=await M("*",()=>R.updateAll());return{success:!0,results:t,message:`Updated ${t.filter((a)=>a.success).length}/${t.length} plugin(s)`}}catch(t){return P.status=500,{error:"Failed to update all plugins",details:String(t)}}}).post("/remove-all",async({set:P})=>{try{let t=await M("*",async()=>{let a=await R.removeAll(c.hostServices);return c.rebuildPluginSurfaces?.(),a});return{success:!0,results:t,message:`Removed ${t.filter((a)=>a.success).length}/${t.length} plugin(s)`}}catch(t){return P.status=500,{error:"Failed to remove all plugins",details:String(t)}}}).post("/reload",async({set:P})=>{try{if(!c.app||!c.hostServices)return P.status=503,{error:"Plugin lifecycle services are not ready"};let t=await M("*",async()=>(await R.reloadAll(c.app,c.hostServices),c.rebuildPluginSurfaces?.(),R.getPluginDetails()));return{success:!0,plugins:t,message:`Reloaded ${t.length} plugin(s)`}}catch(t){return P.status=500,{error:"Failed to reload plugins",details:String(t)}}}).post("/:name/reload",async({params:P,set:t})=>{if(!c.app||!c.hostServices)return t.status=503,{error:"Plugin lifecycle services are not ready"};let a=P.name,d=R.getAllPlugins().find((v)=>v.name===a);if(!d)return t.status=404,{error:`Plugin "${a}" not found`};let N=R.getPluginDetails().find((v)=>v.pluginName===a)?.packageName??`core:${a}`;if(X(N))return t.status=409,{error:"Plugin lifecycle in progress; try again shortly",packageName:N};try{return await M(N,async()=>{if(d.onServerStop)try{await d.onServerStop({reason:"reload"})}catch(v){console.warn(`[plugin-mgr] onServerStop during reload of ${a}:`,v)}if(c.hostServices)c.hostServices.serviceRegistry.unregisterPlugin(d.name);if(R.registerProviders(d,c.hostServices),d.onServerStart)await d.onServerStart(c.app,c.hostServices),R.registerProviders(d,c.hostServices);if(d.onServerReady)await d.onServerReady(c.app,c.hostServices);return c.rebuildPluginSurfaces?.(),{success:!0,message:`Plugin ${a} reloaded`,version:d.version}})}catch(v){return t.status=500,{error:"Failed to reload plugin",details:String(v)}}},{params:r.Object({name:r.String()})})}import{mkdirSync as G,writeFileSync as D,existsSync as ne}from"fs";import{isAbsolute as ye,join as L,relative as he,resolve as K}from"path";var J="http://localhost:3005",be=/^[a-z0-9][a-z0-9-]{0,63}$/,Se=new Set(["backend","frontend","cli","provider","adapter","integration"]);function ie(c,R){let P=he(c,R);if(P.startsWith("..")||ye(P))throw Error("Plugin scaffold path escapes the selected directory.")}function O(c){return JSON.stringify(c)}function re(c){let R=c.command("plugin").description("Manage plugins");R.command("list").description("List installed plugins").option("--agent-url <url>","Agent URL",J).option("--profile <name>","Target a specific profile by name").option("--json","Emit JSON").option("--plain","Force plain text output").action(async(t)=>{try{let a={...c.opts(),...t},d=f(t),b=encodeURIComponent(m(a)),N=async()=>{try{return(await S(d,`/api/profiles/${b}/plugins`)).plugins||[]}catch{p("Agent not reachable. Attempting local plugin registry...");let{PluginManager:h}=await import("./plugin-system-kvg955t3.js");return new h().getPluginDetails()||[]}},v=(h)=>h.status??(h.loaded===!0||h.enabled===!0?"enabled":"disabled"),w=(h)=>h.pluginName||h.name||h.packageName||h.package||"-";await y({mode:_(a),fetchData:N,plain:(h)=>{if(!h.length){o("No plugins installed.");return}g("Installed Plugins"),F(h.map((k)=>({Name:w(k),Version:k.version||"-",Status:v(k),Description:k.description||"-"})))},interactive:async(h)=>{if(!h.length){g("Installed Plugins"),o("No plugins installed.");return}let k=h.map((x)=>{let C=w(x),I=v(x),V=[`${i.bold(C)} ${I==="enabled"?i.green(I):i.dim(I)}`,"",` Version: ${x.version||"-"}`,` Description: ${x.description||"-"}`];if(x.tags&&Array.isArray(x.tags))V.push(` Tags: ${x.tags.join(", ")}`);if(x.cliCommand)V.push(` CLI command: vibe ${x.cliCommand}`);return{id:C,label:C,hint:I,detail:V.join(`
|
|
3
|
+
`)}});await Q({title:`vibe plugin \u2014 ${h.length} installed`,rows:k,footer:"\u2191/\u2193 navigate \xB7 q to quit"})},json:(h)=>h.map((k)=>({name:w(k),version:k.version??null,status:v(k),description:k.description??null,tags:k.tags??null,cliCommand:k.cliCommand??null}))})}catch(a){s(A(a))}}),R.command("install").description("Install a plugin").argument("<package>","NPM package name to install").option("--agent-url <url>","Agent URL",J).option("--profile <name>","Target a specific profile by name").option("--skip-prereqs","Skip running the plugin's prereqs/install",!1).option("--json","Emit JSON result").action(async(t,a)=>{try{let d={...c.opts(),...a},b=f(a),N=encodeURIComponent(m(d));try{let v=await q(b,`/api/profiles/${N}/plugins/install`,{packageName:t,skipPrereqs:!!a.skipPrereqs});if(u(d,{ok:!0,action:"install",package:t,version:v?.version??null,prereqs:v?.prereqs??null}))return;if(l(`Plugin "${t}" installed.`),v?.version)n("Version",v.version);if(v?.prereqs){let w=v.prereqs;if(w.skipped)p(`Prerequisite install skipped. Run \`vibe plugin prereqs ${t} install\` later.`);else if(!w.satisfied)p(`Prerequisites not yet satisfied: ${(w.missing||[]).map((h)=>h.name).join(", ")||"(unknown)"}`);if((w.pendingSudo||[]).length>0){p(`${w.pendingSudo.length} command(s) need sudo. Run them and re-check with \`vibe plugin prereqs ${t} status\`:`);for(let h of w.pendingSudo)n(` ${h.name}`,h.command)}}}catch{p("Agent not reachable. Attempting local install...");try{let{PluginManager:v}=await import("./plugin-system-kvg955t3.js");if(await new v().install(t),u(d,{ok:!0,action:"install",package:t,local:!0}))return;l(`Plugin "${t}" installed locally.`)}catch(v){s(`Could not install plugin via agent or locally: ${A(v)}`)}}}catch(d){s(A(d))}}),R.command("remove").description("Remove a plugin").argument("<package>","NPM package name to remove").option("--agent-url <url>","Agent URL",J).option("--profile <name>","Target a specific profile by name").option("--json","Emit JSON result").action(async(t,a)=>{try{let d={...c.opts(),...a},b=f(a),N=encodeURIComponent(m(d));try{if(await q(b,`/api/profiles/${N}/plugins/remove`,{packageName:t}),u(d,{ok:!0,action:"remove",package:t}))return;l(`Plugin "${t}" removed.`)}catch{p("Agent not reachable. Attempting local removal...");try{let{PluginManager:v}=await import("./plugin-system-kvg955t3.js");if(await new v().remove(t),u(d,{ok:!0,action:"remove",package:t,local:!0}))return;l(`Plugin "${t}" removed locally.`)}catch(v){s(`Could not remove plugin via agent or locally: ${A(v)}`)}}}catch(d){s(A(d))}}),R.command("update").description("Update a plugin (or all plugins with --all)").argument("[package]","NPM package name to update").option("--all","Update all installed plugins",!1).option("--agent-url <url>","Agent URL",J).option("--profile <name>","Target a specific profile by name").option("--json","Emit JSON result").action(async(t,a)=>{try{let d={...c.opts(),...a},b=f(a),N=encodeURIComponent(m(d));if(a.all){o("Updating all plugins...");try{let v=await q(b,`/api/profiles/${N}/plugins/update-all`,{}),w=v?.results||[];if(u(d,{ok:!0,action:"update-all",results:w}))return;for(let h of w)if(h.success)l(`Updated ${h.packageName}${h.version?` to v${h.version}`:""}`);else p(`Failed to update ${h.packageName}: ${h.error}`);l(v?.message||"Done.")}catch{p("Agent not reachable. Attempting local update...");try{let{PluginManager:v}=await import("./plugin-system-kvg955t3.js"),h=await new v().updateAll();if(u(d,{ok:!0,action:"update-all",results:h,local:!0}))return;for(let k of h)if(k.success)l(`Updated ${k.packageName}${k.version?` to v${k.version}`:""}`);else p(`Failed to update ${k.packageName}: ${k.error}`)}catch(v){s(`Could not update plugins: ${A(v)}`)}}}else if(t){o(`Updating ${t}...`);try{let v=await q(b,`/api/profiles/${N}/plugins/update`,{packageName:t});if(u(d,{ok:!0,action:"update",package:t,version:v?.version??null,message:v?.message??null}))return;l(v?.message||`Plugin "${t}" updated.`)}catch{p("Agent not reachable. Attempting local update...");try{let{PluginManager:v}=await import("./plugin-system-kvg955t3.js"),h=await new v().update(t);if(u(d,{ok:!0,action:"update",package:t,version:h.version,local:!0}))return;l(`Plugin "${t}" updated to v${h.version}.`)}catch(v){s(`Could not update plugin: ${A(v)}`)}}}else s("Provide a package name to update, or use --all to update all plugins.")}catch(d){s(A(d))}}),R.command("uninstall").description("Uninstall a plugin (or all plugins with --all)").argument("[package]","NPM package name to uninstall").option("--all","Uninstall all external plugins",!1).option("--agent-url <url>","Agent URL",J).option("--profile <name>","Target a specific profile by name").option("--json","Emit JSON result").action(async(t,a)=>{try{let d={...c.opts(),...a},b=f(a),N=encodeURIComponent(m(d));if(a.all){o("Uninstalling all plugins...");try{let v=await q(b,`/api/profiles/${N}/plugins/remove-all`,{}),w=v?.results||[];if(u(d,{ok:!0,action:"uninstall-all",results:w}))return;for(let h of w)if(h.success)l(`Removed ${h.packageName}`);else p(`Failed to remove ${h.packageName}: ${h.error}`);l(v?.message||"Done.")}catch{p("Agent not reachable. Attempting local removal...");try{let{PluginManager:v}=await import("./plugin-system-kvg955t3.js"),h=await new v().removeAll();if(u(d,{ok:!0,action:"uninstall-all",results:h,local:!0}))return;for(let k of h)if(k.success)l(`Removed ${k.packageName}`);else p(`Failed to remove ${k.packageName}: ${k.error}`)}catch(v){s(`Could not uninstall plugins: ${A(v)}`)}}}else if(t)try{if(await q(b,`/api/profiles/${N}/plugins/remove`,{packageName:t}),u(d,{ok:!0,action:"uninstall",package:t}))return;l(`Plugin "${t}" uninstalled.`)}catch{p("Agent not reachable. Attempting local removal...");try{let{PluginManager:v}=await import("./plugin-system-kvg955t3.js");if(await new v().remove(t),u(d,{ok:!0,action:"uninstall",package:t,local:!0}))return;l(`Plugin "${t}" uninstalled locally.`)}catch(v){s(`Could not uninstall plugin: ${A(v)}`)}}else s("Provide a package name to uninstall, or use --all to uninstall all plugins.")}catch(d){s(A(d))}}),R.command("reload").description("Reload all plugins").option("--agent-url <url>","Agent URL",J).option("--profile <name>","Target a specific profile by name").option("--json","Emit JSON result").action(async(t)=>{try{let a={...c.opts(),...t},d=f(t),b=encodeURIComponent(m(a));if(await q(d,`/api/profiles/${b}/plugins/reload`,{}),u(a,{ok:!0,action:"reload"}))return;l("Plugins reloaded.")}catch(a){s(A(a))}}),R.command("available").description("Show available plugins").option("--agent-url <url>","Agent URL",J).option("--profile <name>","Target a specific profile by name").option("--json","Emit JSON").option("--plain","Force plain text output").action(async(t)=>{try{let a={...c.opts(),...t},d=f(t),b=encodeURIComponent(m(a)),N=async()=>(await S(d,`/api/profiles/${b}/plugins/available`)).plugins||[],v=(h)=>h.name||h.package||"-",w=(h)=>h.version||h.latestVersion||"-";await y({mode:_(a),fetchData:N,plain:(h)=>{if(!h||h.length===0){o("No available plugins found.");return}g("Available Plugins"),F(h.map((k)=>({Name:v(k),Version:w(k),Description:k.description||"-"})))},interactive:async(h)=>{if(!h||h.length===0){g("Available Plugins"),o("No available plugins found.");return}let k=h.map((x)=>{let C=v(x),I=[i.bold(C),"",` Version: ${w(x)}`,` Description: ${x.description||"-"}`];return{id:C,label:C,hint:w(x),detail:I.join(`
|
|
4
|
+
`)}});await Q({title:`vibe plugin available \u2014 ${h.length} plugin(s)`,rows:k,footer:"\u2191/\u2193 navigate \xB7 q to quit"})},json:(h)=>h.map((k)=>({name:v(k),version:w(k),description:k.description??null}))})}catch(a){s(A(a))}});let P=R.command("prereqs").description("Inspect or run a plugin's prerequisite-install protocol").argument("<package>","NPM package name (or short plugin name)");P.command("status",{isDefault:!0}).description("Show the plugin's prereq status").option("--agent-url <url>","Agent URL",J).option("--profile <name>","Target a specific profile by name").option("--json","Emit JSON").option("--plain","Force plain text output").action(async(t,a)=>{let d=a.parent?.args?.[0];if(!d){s("Missing plugin package argument.");return}try{let b={...c.opts(),...t},N=f(t),v=async()=>q(N,"/api/plugins/prereqs/status",{packageName:d});await y({mode:_(b),fetchData:v,plain:(w)=>{if(n("Plugin",d),n("Satisfied",w?.satisfied?"yes":"no"),Array.isArray(w?.missing)&&w.missing.length>0)n("Missing",w.missing.map((h)=>h.name).join(", "))},interactive:async(w)=>{let h=[`Plugin: ${d}`,`Satisfied: ${w?.satisfied?"yes":"no"}`];if(Array.isArray(w?.missing)&&w.missing.length>0)h.push(`Missing: ${w.missing.map((k)=>k.name).join(", ")}`);await U({title:`Prereqs: ${d}`,body:h.join(`
|
|
5
|
+
`),footer:"q / Esc to quit"})},json:(w)=>({plugin:d,satisfied:!!w?.satisfied,missing:Array.isArray(w?.missing)?w.missing:[],pendingSudo:Array.isArray(w?.pendingSudo)?w.pendingSudo:[]})})}catch(b){s(`Could not read prereq status: ${A(b)}`)}}),P.command("install").description("Run the plugin's prerequisite install endpoint").option("--agent-url <url>","Agent URL",J).option("--profile <name>","Target a specific profile by name").option("--approve-sudo","Auto-approve sudo commands the plugin returns",!1).option("--json","Emit JSON result").action(async(t,a)=>{let d=a.parent?.args?.[0];if(!d){s("Missing plugin package argument.");return}try{let b={...c.opts(),...t},N=f(t),v=await q(N,"/api/plugins/prereqs/install",{packageName:d,approveSudo:!!t.approveSudo});if(u(b,{ok:!0,action:"prereqs-install",plugin:d,satisfied:!!v?.satisfied,pendingSudo:v?.pendingSudo??[]}))return;if(v?.satisfied)l(`Prerequisites satisfied for ${d}.`);else p(`Prerequisites still missing for ${d}.`);if(Array.isArray(v?.pendingSudo)&&v.pendingSudo.length>0){p(`${v.pendingSudo.length} command(s) require sudo:`);for(let w of v.pendingSudo)n(` ${w.name}`,w.command)}}catch(b){s(`Prereq install failed: ${A(b)}`)}}),P.command("uninstall").description("Run the plugin's prerequisite uninstall endpoint (if supported)").option("--agent-url <url>","Agent URL",J).option("--profile <name>","Target a specific profile by name").option("--json","Emit JSON result").action(async(t,a)=>{let d=a.parent?.args?.[0];if(!d){s("Missing plugin package argument.");return}try{let b={...c.opts(),...t},N=f(t);if(await q(N,"/api/plugins/prereqs/uninstall",{packageName:d}),u(b,{ok:!0,action:"prereqs-uninstall",plugin:d}))return;l(`Prereq uninstall completed for ${d}.`)}catch(b){p(`Prereq uninstall not supported or failed: ${A(b)}`)}}),R.command("create").description("Scaffold a new plugin project").argument("<name>",'Plugin name (e.g. "docker" \u2192 vibe-plugin-docker)').option("-d, --dir <directory>","Parent directory",".").option("--tag <tag>","Plugin tag (backend, frontend, cli, provider, adapter, integration)","backend").option("--with-ui","Include a companion UI plugin scaffold",!1).option("--json","Emit JSON result").action(async(t,a)=>{try{let d={...c.opts(),...a},b=t.startsWith("vibe-plugin-")?t.slice(12):t;if(!be.test(b)){s("Plugin name must use lowercase letters, numbers, and dashes only.");return}let N=a.tag;if(!Se.has(N)){s("Invalid plugin tag.");return}let v=`vibe-plugin-${b}`,w=K(a.dir),h=K(w,v);if(ie(w,h),ne(h)){s(`Directory "${h}" already exists.`);return}o(`Scaffolding ${v}...`),G(L(h,"src"),{recursive:!0}),G(L(h,"dist"),{recursive:!0});let k=`VibeControls plugin: ${b}`,x={name:`@vibecontrols/${v}`,version:"0.1.0",main:"./dist/index.js",type:"module",engines:{bun:">=1.3.0"},scripts:{build:"bun build ./src/index.ts --outdir ./dist --target bun",lint:"eslint ./src",format:"bunx prettier . --write","format:check":"bunx prettier . --check","type:check":"tsc --noEmit",clean:"rimraf dist",prebuild:"bun run clean",prepublishOnly:"bun run build",sanity:"bun run format:check && bun run lint && bun run type:check && bun run build"},keywords:["vibecontrols","vibe","vibe-plugin",b,"bun"],author:{name:"Your Name",email:"you@example.com"},license:"SEE LICENSE IN LICENSE",description:k,devDependencies:{"@types/bun":"^1.2.16","bun-types":"^1.3.9",commander:"^14.0.3",eslint:"^9.30.1",prettier:"^3.6.2",rimraf:"^6.0.1",typescript:"^5.8.3","typescript-eslint":"^8.56.0"},peerDependencies:{"@vibecontrols/agent":">=2.0.0"},peerDependenciesMeta:{"@vibecontrols/agent":{optional:!0}},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},files:["dist/**/*","README.md","LICENSE"]};D(L(h,"package.json"),JSON.stringify(x,null,2)+`
|
|
6
|
+
`);let C={compilerOptions:{target:"ES2022",module:"ES2022",moduleResolution:"bundler",types:["bun-types"],strict:!0,esModuleInterop:!0,skipLibCheck:!0,outDir:"./dist",rootDir:"./src",declaration:!0,sourceMap:!0},include:["src/**/*.ts"],exclude:["node_modules","dist"]};D(L(h,"tsconfig.json"),JSON.stringify(C,null,2)+`
|
|
7
|
+
`),D(L(h,".gitignore"),["node_modules/","dist/","bun.lock",".env",".env.local","*.tgz"].join(`
|
|
8
|
+
`)+`
|
|
9
|
+
`);let I=b,V=O(v),H=O(k),se=O(N),z=O(I),oe=`import type { Command } from "commander";
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* @vibecontrols/${v}
|
|
13
|
+
*
|
|
14
|
+
* ${k}
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
// \u2500\u2500 Plugin Interfaces \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
18
|
+
|
|
19
|
+
export interface HostServices {
|
|
20
|
+
logger?: {
|
|
21
|
+
info: (msg: string) => void;
|
|
22
|
+
warn: (msg: string) => void;
|
|
23
|
+
error: (msg: string) => void;
|
|
24
|
+
debug: (msg: string) => void;
|
|
25
|
+
};
|
|
26
|
+
config?: Record<string, unknown>;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export interface VibePlugin {
|
|
30
|
+
name: string;
|
|
31
|
+
version: string;
|
|
32
|
+
description: string;
|
|
33
|
+
tags?: Array<
|
|
34
|
+
"backend" | "frontend" | "cli" | "provider" | "adapter" | "integration"
|
|
35
|
+
>;
|
|
36
|
+
cliCommand: string;
|
|
37
|
+
onCliSetup: (program: Command, hostServices?: HostServices) => void;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// \u2500\u2500 Plugin Implementation \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
41
|
+
|
|
42
|
+
const plugin: VibePlugin = {
|
|
43
|
+
name: ${V},
|
|
44
|
+
version: "0.1.0",
|
|
45
|
+
description: ${H},
|
|
46
|
+
tags: [${se}],
|
|
47
|
+
cliCommand: ${z},
|
|
48
|
+
|
|
49
|
+
onCliSetup(program: Command, _hostServices?: HostServices): void {
|
|
50
|
+
const cmd = program
|
|
51
|
+
.command(${z})
|
|
52
|
+
.description(${H});
|
|
53
|
+
|
|
54
|
+
cmd
|
|
55
|
+
.command("status")
|
|
56
|
+
.description(`+O(`Show ${b} status`)+`)
|
|
57
|
+
.action(() => {
|
|
58
|
+
console.log(`+O(`${v} is ready.`)+`);
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
cmd
|
|
62
|
+
.command("info")
|
|
63
|
+
.description("Show plugin info")
|
|
64
|
+
.action(() => {
|
|
65
|
+
console.log(JSON.stringify({
|
|
66
|
+
name: plugin.name,
|
|
67
|
+
version: plugin.version,
|
|
68
|
+
description: plugin.description,
|
|
69
|
+
tags: plugin.tags,
|
|
70
|
+
}, null, 2));
|
|
71
|
+
});
|
|
72
|
+
},
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
export default plugin;
|
|
76
|
+
`;D(L(h,"src","index.ts"),oe);let ce=`# ${v}
|
|
77
|
+
|
|
78
|
+
${k}
|
|
79
|
+
|
|
80
|
+
## Installation
|
|
81
|
+
|
|
82
|
+
\`\`\`bash
|
|
83
|
+
vibe plugin install @vibecontrols/${v}
|
|
84
|
+
\`\`\`
|
|
85
|
+
|
|
86
|
+
## Usage
|
|
87
|
+
|
|
88
|
+
\`\`\`bash
|
|
89
|
+
vibe ${I} status
|
|
90
|
+
vibe ${I} info
|
|
91
|
+
\`\`\`
|
|
92
|
+
|
|
93
|
+
## Development
|
|
94
|
+
|
|
95
|
+
\`\`\`bash
|
|
96
|
+
bun install
|
|
97
|
+
bun run build
|
|
98
|
+
bun run sanity
|
|
99
|
+
\`\`\`
|
|
100
|
+
|
|
101
|
+
## Publishing
|
|
102
|
+
|
|
103
|
+
\`\`\`bash
|
|
104
|
+
bun run build
|
|
105
|
+
npm publish
|
|
106
|
+
\`\`\`
|
|
107
|
+
`;D(L(h,"README.md"),ce);let T={ok:!0,action:"create",plugin:v,packageName:`@vibecontrols/${v}`,cliCommand:I,tag:N,dir:h,withUi:a.withUi===!0};if(!d.json)l(`Created ${v} at ${h}`),n("Plugin Name",`@vibecontrols/${v}`),n("CLI Command",`vibe ${I}`),n("Tag",N),o(`
|
|
108
|
+
Next steps:`),o(` cd ${v}`),o(" bun install"),o(" bun run build"),o(` publish @vibecontrols/${v}, then install from catalog`);if(a.withUi){let B=`${v.replace("vibe-plugin-","vibe-plugin-ui-")}`,j=K(w,B);if(ie(w,j),ne(j)){if(!d.json)p(`UI directory "${j}" already exists, skipping.`);T.uiSkipped=!0,T.uiDir=j}else{G(L(j,"src"),{recursive:!0}),G(L(j,"public"),{recursive:!0});let ue={name:`@vibecontrols/${B}`,version:"0.1.0",private:!1,type:"module",scripts:{dev:"vite --port 5180",build:"tsc && vite build",preview:"vite preview",lint:"eslint ./src",format:"bunx prettier . --write","format:check":"bunx prettier . --check","type:check":"tsc --noEmit",sanity:"bun run format:check && bun run lint && bun run type:check && bun run build"},keywords:["vibecontrols","vibe-plugin","ui",b],author:{name:"Your Name",email:"you@example.com"},license:"SEE LICENSE IN LICENSE",description:`UI for ${v}`,dependencies:{react:"^19.0.0","react-dom":"^19.0.0"},devDependencies:{"@types/react":"^19.0.0","@types/react-dom":"^19.0.0","@vitejs/plugin-react":"^4.5.2",typescript:"^5.8.3",vite:"^7.0.0"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},files:["dist/**/*","README.md"]};D(L(j,"package.json"),JSON.stringify(ue,null,2)+`
|
|
109
|
+
`);let ge=`import React from "react";
|
|
110
|
+
import ReactDOM from "react-dom/client";
|
|
111
|
+
import App from "./App";
|
|
112
|
+
|
|
113
|
+
ReactDOM.createRoot(document.getElementById("root")!).render(
|
|
114
|
+
<React.StrictMode>
|
|
115
|
+
<App />
|
|
116
|
+
</React.StrictMode>
|
|
117
|
+
);
|
|
118
|
+
`;D(L(j,"src","main.tsx"),ge);let pe=`import { useState, useEffect } from "react";
|
|
119
|
+
|
|
120
|
+
const TITLE = ${O(`${b} UI`)};
|
|
121
|
+
|
|
122
|
+
export default function App() {
|
|
123
|
+
const [apiKey, setApiKey] = useState<string | null>(null);
|
|
124
|
+
const [status, setStatus] = useState("loading...");
|
|
125
|
+
|
|
126
|
+
useEffect(() => {
|
|
127
|
+
// Auth via postMessage (iframe) or URL param (new tab)
|
|
128
|
+
const params = new URLSearchParams(window.location.search);
|
|
129
|
+
const key = params.get("apiKey");
|
|
130
|
+
if (key) {
|
|
131
|
+
setApiKey(key);
|
|
132
|
+
setStatus("connected");
|
|
133
|
+
return;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
const handler = (e: MessageEvent) => {
|
|
137
|
+
if (e.data?.type === "vibe-auth" && e.data.apiKey) {
|
|
138
|
+
setApiKey(e.data.apiKey);
|
|
139
|
+
setStatus("connected");
|
|
140
|
+
}
|
|
141
|
+
};
|
|
142
|
+
window.addEventListener("message", handler);
|
|
143
|
+
return () => window.removeEventListener("message", handler);
|
|
144
|
+
}, []);
|
|
145
|
+
|
|
146
|
+
return (
|
|
147
|
+
<div style={{ background: "var(--vibe-surface, Canvas)", color: "var(--vibe-text, CanvasText)", minHeight: "100vh", padding: 24, fontFamily: "system-ui" }}>
|
|
148
|
+
<h1>{TITLE}</h1>
|
|
149
|
+
<p>Status: {status}</p>
|
|
150
|
+
{apiKey && <p style={{ color: "var(--vibe-success, CanvasText)" }}>Authenticated</p>}
|
|
151
|
+
</div>
|
|
152
|
+
);
|
|
153
|
+
}
|
|
154
|
+
`;D(L(j,"src","App.tsx"),pe);let de=`<!DOCTYPE html>
|
|
155
|
+
<html lang="en">
|
|
156
|
+
<head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>${b} UI</title></head>
|
|
157
|
+
<body><div id="root"></div><script type="module" src="/src/main.tsx"></script></body>
|
|
158
|
+
</html>`;if(D(L(j,"index.html"),de),!d.json)l(`Created UI plugin ${B} at ${j}`);T.uiPluginName=B,T.uiPackageName=`@vibecontrols/${B}`,T.uiDir=j}}u(d,T)}catch(d){s(A(d))}})}function ae(c,R){re(c)}function _e(c){return{name:"plugin-mgr",version:"2.2.0",description:"Plugin lifecycle management \u2014 install, remove, reload, catalog",capabilities:{storage:"rw",subprocess:!0,gateway:!0,audit:!0,telemetry:!0},tags:["backend","cli"],cliCommand:"plugin",apiPrefix:"/api/plugins",createRoutes:(R)=>te(R),onCliSetup:async(R,P)=>{ae(R,P)}}}export{_e as createPlugin};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{homedir as y}from"os";import{isAbsolute as b,join as p}from"path";function g({command:t,args:s,platform:r=process.platform}){if(r==="win32")return["cmd","/c",t,...s];return["sh","-c",`${t} "$@"`,"--",...s]}function l(t,s){let r=y();if(t===void 0||t===null||t==="")return s??r;let e=t.trim();if(e==="")return s??r;if(e==="~")return r;if(e.startsWith("~/"))return p(r,e.slice(2));if(b(e))return e;return p(r,e)}function h(){try{return process.cwd()}catch{return}}async function pi(t,s,r=Bun.spawn){let e=g({command:t.command,args:s}),n=t.cwd&&t.cwd.trim()!==""?l(t.cwd):l(t.cwd,h()),d;try{d=r(e,{cwd:n,stdin:"inherit",stdout:"inherit",stderr:"inherit"})}catch(o){let u=o instanceof Error?o.message:String(o);return process.stderr.write(`vibe run: spawn failed in cwd=${n}: ${u}
|
|
3
|
+
`),{exitCode:127}}let i=await d.exited;return{exitCode:typeof i==="number"?i:1}}var f=1048576,R=60000;async function w(t){if(!t)return{text:"",truncated:!1};let s=t.getReader(),r=new TextDecoder,e=0,a=!1,n="";try{while(!0){let{done:d,value:i}=await s.read();if(d)break;if(a)continue;let o=f-e;if(i.byteLength<=o)n+=r.decode(i,{stream:!0}),e+=i.byteLength;else n+=r.decode(i.subarray(0,o),{stream:!0}),e=f,a=!0}n+=r.decode()}finally{s.releaseLock()}if(a)n+="...[truncated]";return{text:n,truncated:a}}async function mi(t,s){let r=g({command:t.command,args:s}),e=l(t.cwd),a=Date.now(),n;try{n=Bun.spawn(r,{cwd:e,stdin:"ignore",stdout:"pipe",stderr:"pipe"})}catch(c){let x=c instanceof Error?c.message:String(c);return{exit_code:127,stdout:"",stderr:`vibe alias: spawn failed in cwd=${e}: ${x}`,duration_ms:Date.now()-a,truncated:{stdout:!1,stderr:!1},timed_out:!1,cwd:e}}let d=!1,i=setTimeout(()=>{d=!0;try{n.kill()}catch{}},R),[o,u,m]=await Promise.all([w(n.stdout),w(n.stderr),n.exited]);return clearTimeout(i),{exit_code:typeof m==="number"?m:1,stdout:o.text,stderr:u.text,duration_ms:Date.now()-a,truncated:{stdout:o.truncated,stderr:u.truncated},timed_out:d,cwd:e}}
|
|
4
|
+
export{pi,mi};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
var i=new Set(["static-api-key","plugin-state:external-config"]),o=["gateway-auth:"],s=[/(^|[-_:])secret($|[-_:])/i,/(^|[-_:])token($|[-_:])/i,/(^|[-_:])password($|[-_:])/i,/(^|[-_:])api[-_]?key($|[-_:])/i,/^static-api-key$/i,/^gateway-auth:/i,/^clientSecret$/i,/^plugin-state:external-config$/i],Ri="[redacted]";function Dt(t){return i.has(t)||o.some((n)=>t.startsWith(n))}function r(t){return s.some((n)=>n.test(t))}function xe(t,n){return r(t)&&n!==void 0?"[redacted]":n}function Fi(t){return Object.fromEntries(Object.entries(t).map(([n,e])=>[n,xe(n,e)]))}function L(t){if(Array.isArray(t))return t.map((n)=>L(n));if(!t||typeof t!=="object")return t;return Object.fromEntries(Object.entries(t).map(([n,e])=>[n,r(n)?"[redacted]":L(e)]))}
|
|
3
|
+
export{Ri,Dt,xe,Fi,L};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{R,C}from"./index-0qjbnyg4.js";import{J,w}from"./index-kwhx023z.js";import{existsSync as d,readFileSync as y}from"fs";import{join as T}from"path";var p="http://localhost:3005",h=new Set(["localhost","127.0.0.1","0.0.0.0","::1","[::1]"]);function A(r){return r.toLowerCase().replace(/^\[|\]$/g,"")}function Kt(r){try{let n=new URL(r);return h.has(A(n.hostname))}catch{return!1}}function u(r){let n=new URL(r.trim());if(n.protocol!=="http:"&&n.protocol!=="https:")throw Error("Agent URL must use http or https");if(n.username||n.password)throw Error("Agent URL must not include credentials");let t=n.toString().replace(/\/+$/,"");if(!Kt(t)&&process.env.VIBECONTROLS_ALLOW_REMOTE_AGENT_URL!=="1")throw Error("Refusing non-local agent URL. Set VIBECONTROLS_ALLOW_REMOTE_AGENT_URL=1 to target a remote/tunnel URL explicitly.");return t}function O(r){if(!Number.isInteger(r)||r<=0)return!1;try{return process.kill(r,0),!0}catch{return!1}}function _(){let r=T(C(),"agents.json");if(!d(r))return[];try{let n=JSON.parse(y(r,"utf-8"));return(Array.isArray(n)?n:n&&typeof n==="object"&&Array.isArray(n.instances)?n.instances:[]).filter((e)=>!!e&&typeof e==="object"&&typeof e.name==="string"&&typeof e.port==="number")}catch{return[]}}function E(r){let t=_().find((e)=>e.name===r);if(!t||!t.port)return null;if(typeof t.pid==="number"&&!O(t.pid))return null;return{url:`http://localhost:${t.port}`,port:t.port}}function f(r){let n=r?.agentUrl&&r.agentUrl!==p?r.agentUrl:void 0;if(n)return u(n);if(r?.profile){let t=E(r.profile);if(t)return t.url}if(process.env.AGENT_URL)return u(process.env.AGENT_URL);try{let t=m({}),e=E(t);if(e)return e.url}catch{}return u(p)}async function Re(r){let n=Kt(r);if(process.env.AGENT_API_KEY){if(n||process.env.VIBECONTROLS_SEND_API_KEY_TO_REMOTE==="1")return process.env.AGENT_API_KEY;throw Error("Refusing to send AGENT_API_KEY to a non-local agent URL. Set VIBECONTROLS_SEND_API_KEY_TO_REMOTE=1 only if you trust the target.")}if(!n)return;let t=R(),e=await J(`${t}:static-api-key`);if(e)return e;return w()["static-api-key"]}function m(r){if(r?.profile)return r.profile;if(process.env.VIBECONTROLS_PROFILE)return process.env.VIBECONTROLS_PROFILE;try{let n=T(C(),"agents.json");if(d(n)){let t=JSON.parse(y(n,"utf-8")),e=t&&typeof t==="object"&&!Array.isArray(t)?t.defaultProfile:void 0;if(typeof e==="string"&&e.length>0)return e}}catch{}return"default"}async function c(r,n,t={}){let e=await Re(r),s={...t.body?{"Content-Type":"application/json"}:{},...e?{"x-agent-api-key":e}:{},...t.headers??{}},o;try{o=await fetch(`${r}${n}`,{...t,headers:s})}catch(i){let g=i instanceof Error?i.message:String(i),l=/unable to connect|ECONNREFUSED|ENOTFOUND|EHOSTUNREACH|fetch failed/i.test(g);if(l&&Kt(r))throw Error(`Agent not reachable at ${r}. Is it running? Try 'vibe status' or 'vibe start'.`,{cause:i});if(l)throw Error(`Agent not reachable at ${r}. ${g}`,{cause:i});throw i}let a=await o.json().catch(()=>({}));return{ok:o.ok,status:o.status,data:a}}async function S(r,n){let{ok:t,status:e,data:s}=await c(r,n);if(!t){let o=s?.error||s?.message||`Agent returned ${e}`;throw Error(String(o))}return s}async function q(r,n,t){let{ok:e,status:s,data:o}=await c(r,n,{method:"POST",body:t!=null?JSON.stringify(t):void 0});if(!e){let a=o?.error||o?.message||`Agent returned ${s}`;throw Error(String(a))}return o}async function Ce(r,n,t){let{ok:e,status:s,data:o}=await c(r,n,{method:"PUT",body:t!=null?JSON.stringify(t):void 0});if(!e){let a=o?.error||o?.message||`Agent returned ${s}`;throw Error(String(a))}return o}async function Ae(r,n){let{ok:t,status:e,data:s}=await c(r,n,{method:"DELETE"});if(!t){let o=s?.error||s?.message||`Agent returned ${e}`;throw Error(String(o))}return s}
|
|
3
|
+
export{Kt,f,Re,m,S,q,Ce,Ae};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
var h=new Set(["localhost","127.0.0.1","::1","[::1]"]),g=new Set(["127.0.0.1","::1"]),m=new Set(["same-origin","none"]),S=new Set(["https://vibecontrols.com","https://app.vibecontrols.com","https://alphaapp.vibecontrols.com","https://burdenoff.com","https://app.burdenoff.com","https://alphaapp.burdenoff.com"]);function w(e){let t=e.trim().toLowerCase().replace(/^\[|\]$/g,"");if(t.startsWith("::ffff:"))return t.slice(7);return t}function y(e){return g.has(w(e))}function c(e){let t=e.trim().toLowerCase().replace(/^\[|\]$/g,"");return h.has(t)}function a(e){if(!e||e.length>255)return null;for(let l=0;l<e.length;l++){let s=e.charCodeAt(l);if(s<=32||s===127)return null}if(/[/\\@?#,'"`]/.test(e))return null;let t=e.toLowerCase();if(t.startsWith("[")){let l=t.indexOf("]");if(l<=1)return null;let s=t.slice(1,l);if(!/^[0-9a-f:.]+$/.test(s))return null;let i=t.slice(l+1);if(i==="")return{host:`[${s}]`,hostname:s,port:""};if(!i.startsWith(":"))return null;let u=i.slice(1);if(!f(u))return null;return{host:`[${s}]:${u}`,hostname:s,port:u}}let n=t.indexOf(":");if(n===-1){if(!/^[a-z0-9.-]+$/.test(t)||t.startsWith(".")||t.endsWith("."))return null;return{host:t,hostname:t,port:""}}if(t.indexOf(":",n+1)!==-1)return null;let r=t.slice(0,n),o=t.slice(n+1);if(!r||!/^[a-z0-9.-]+$/.test(r)||r.startsWith(".")||r.endsWith("."))return null;if(!f(o))return null;return{host:`${r}:${o}`,hostname:r,port:o}}function f(e){if(!/^\d{1,5}$/.test(e))return!1;let t=Number(e);return Number.isInteger(t)&&t>=1&&t<=65535}function p(e){if(e.headers.has("host"))return a(e.headers.get("host")??"");try{return a(new URL(e.url).host)}catch{return null}}function O(e){return e.has("cf-connecting-ip")||e.has("x-forwarded-for")||e.has("x-real-ip")||e.has("forwarded")}function R(e){if(!e.has("sec-fetch-site"))return!1;let t=(e.get("sec-fetch-site")??"").trim().toLowerCase();return!m.has(t)}function Ge(e){return e.headers.has("origin")||e.headers.has("sec-fetch-site")}function b(e,t){if(!t)return;try{let n=new URL(t);if(n.protocol!=="https:"&&n.protocol!=="http:")return;let r=a(n.host);if(!r||r.hostname==="0.0.0.0")return;if(e.add(r.host),!r.port){let o=n.protocol==="https:"?"443":"80";e.add(`${r.host}:${o}`)}}catch{}}function Cr(e,t){let n=p(e);if(!n)return!1;if(n.hostname==="0.0.0.0")return!1;let r=new Set,{port:o}=t;if(Number.isInteger(o)&&o>0){if(r.add(`localhost:${o}`),r.add(`127.0.0.1:${o}`),r.add(`[::1]:${o}`),o===80||o===443)r.add("localhost"),r.add("127.0.0.1"),r.add("[::1]")}else if(o===0&&c(n.hostname))return!0;if(t.tunnelUrls)for(let s of t.tunnelUrls)b(r,s);let l=(process.env.VIBECONTROLS_ALLOWED_HOSTS??"").split(",").map((s)=>s.trim()).filter(Boolean);for(let s of[...t.allowedHosts??[],...l]){let i=a(s);if(i&&i.hostname!=="0.0.0.0")r.add(i.host)}return r.has(n.host)}function L(e){let t=new Set,n=process.env.VIBECONTROLS_DEV_CORS_PORTS??"",r=[...(e??[]).map((o)=>String(o).trim()),...n.split(",").map((o)=>o.trim())];for(let o of r)if(f(o))t.add(o);return t}function gi(e,t){let n;try{n=new URL(e)}catch{return!1}if(n.protocol!=="http:"&&n.protocol!=="https:")return!1;let r=n.hostname.toLowerCase().replace(/^\[|\]$/g,"");if(r==="0.0.0.0")return!1;let o=(t?.nodeEnv??"production")==="production";if(S.has(n.origin))return!0;let l=t?.configuredOrigins??[];for(let s of l){if(!s||s==="*")continue;try{let i=new URL(s);if(i.hostname.toLowerCase().replace(/^\[|\]$/g,"")==="0.0.0.0")continue;if(i.origin===n.origin){if(o&&c(r))return!1;return!0}}catch{}}if(o)return!1;if(r.endsWith(".local.burdenoff.com"))return!0;if(r==="localhost"||r==="127.0.0.1"){let s=L(t?.devPorts),i=n.port||(n.protocol==="https:"?"443":"80");return s.has(i)}return!1}function Be(e,t){let n=e.headers;if(O(n))return!1;if(R(n))return!1;let r=p(e);if(!r||!c(r.hostname))return!1;if(t?.port&&Number.isInteger(t.port)&&t.port>0&&r.port&&Number(r.port)!==t.port)return!1;if(n.has("origin")){let l=n.get("origin")??"";try{let s=new URL(l),i=a(s.host);if(!i||!c(i.hostname)||i.host!==r.host)return!1}catch{return!1}}let o=t?.requestIP(e)?.address;if(!o)return!1;return y(o)}function x(e){return`security:${e.toLowerCase()}`}function d(e){if(!e)return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"||t==="yes"}async function Pe(e,t,n,r){if(Be(e,n))return null;if(d(process.env[t]))return null;if(r?.getConfig)try{let o=await r.getConfig(x(t));if(d(o))return null}catch{}return`This operation is local-only by default. Set ${t}=1 to allow it over a tunnel, or toggle it from the agent's Security Settings.`}
|
|
3
|
+
export{Ge,Cr,gi,Be,Pe};
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{I,ee}from"./index-0qjbnyg4.js";import{s,l,p,o,g,n,c}from"./index-7f2k4g6q.js";import{b}from"./index-w4jqdhc2.js";import{u}from"./index-t5cfkz1e.js";import{existsSync as L,mkdirSync as T,writeFileSync as U,unlinkSync as H,readFileSync as q}from"fs";import{join as v}from"path";import{homedir as A,platform as x}from"os";import{isAbsolute as J,resolve as K}from"path";function W(){return I()}function w(){return v(W(),"logs")}function B(){if(process.execPath&&process.execPath.includes("bun"))return process.execPath;let t=b().which("bun");if(t)return t;throw Error("Could not find bun binary. Ensure bun is installed and in PATH.")}function D(){return import.meta.dir.endsWith("/dist")||import.meta.dir.includes("/dist/")?v(import.meta.dir,"index.js"):v(import.meta.dir,"..","..","index.ts")}function R(t,e){if(/[\0\r\n]/.test(t))throw Error(`${e} contains invalid control characters`)}function C(t){if(!/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(t))throw Error("Agent name must use 1-64 characters: letters, numbers, dot, underscore, or dash.");return t}function Y(t){let e=parseInt(t,10);if(!Number.isInteger(e)||e<1||e>65535)throw Error("Port must be an integer between 1 and 65535");return e}function y(t){return R(t,"systemd value"),`"${t.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`}function tt(t){if(R(t,"systemd path"),!J(t))throw Error(`systemd path must be absolute, got: ${t}`);return t}function d(t){let e=String(t);return R(e,"plist value"),e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function V(t){let e=v(A(),".config","systemd","user");return T(e,{recursive:!0}),v(e,`vibecontrols-agent-${t}.service`)}function X(t){return`[Unit]
|
|
3
|
+
Description=VibeControls Agent (${t.name})
|
|
4
|
+
After=network.target
|
|
5
|
+
|
|
6
|
+
[Service]
|
|
7
|
+
Type=simple
|
|
8
|
+
ExecStart=${y(t.bunPath)} run ${y(t.entryPoint)}
|
|
9
|
+
Environment=${y(`PORT=${t.port}`)}
|
|
10
|
+
Environment=${y(`DB_PATH=${t.dbPath}`)}${t.host?`
|
|
11
|
+
Environment=${y(`HOST=${t.host}`)}`:""}
|
|
12
|
+
Environment=NODE_ENV=production${t.profile?`
|
|
13
|
+
Environment=${y(`VIBECONTROLS_PROFILE=${t.profile}`)}`:""}${t.profiles?`
|
|
14
|
+
Environment=${y(`VIBECONTROLS_PROFILES=${t.profiles}`)}`:""}${t.home?`
|
|
15
|
+
Environment=${y(`VIBECONTROLS_HOME=${t.home}`)}`:""}${t.isolatePlugins?`
|
|
16
|
+
Environment=${y(`VIBE_ISOLATE_PLUGINS=${t.isolatePlugins}`)}`:""}
|
|
17
|
+
Environment=${y(`AGENT_LOG_FILE=${t.logFile}`)}
|
|
18
|
+
Environment=${y(`HOME=${A()}`)}
|
|
19
|
+
Environment=${y(`PATH=${process.env.PATH??""}`)}
|
|
20
|
+
WorkingDirectory=${tt(A())}
|
|
21
|
+
Restart=always
|
|
22
|
+
RestartSec=5
|
|
23
|
+
StandardOutput=append:${t.logFile}
|
|
24
|
+
StandardError=append:${t.logFile}
|
|
25
|
+
|
|
26
|
+
[Install]
|
|
27
|
+
WantedBy=default.target
|
|
28
|
+
`}async function et(t,e,r,i={}){C(t),R(r,"dbPath");let a=B(),f=D(),h=v(w(),`${t}.log`),m=V(t),P=`vibecontrols-agent-${t}.service`;T(w(),{recursive:!0});let k=X({name:t,port:e,dbPath:r,bunPath:a,entryPoint:f,logFile:h,host:i.host,profile:i.profile,profiles:i.profiles,home:i.home,isolatePlugins:i.isolatePlugins});U(m,k),o(`Wrote systemd unit: ${m}`);let S=[["systemctl","--user","daemon-reload"],["systemctl","--user","enable",P],...i.skipStart?[]:[["systemctl","--user","start",P]]];for(let E of S){let O=Bun.spawnSync(E);if(O.exitCode!==0){let j=O.stderr.toString().trim();throw Error(`${E.join(" ")} failed (exit ${O.exitCode})${j?` \u2014 ${j}`:""}`)}}if(Bun.spawnSync(["loginctl","enable-linger",process.env.USER||""]).exitCode===0)o("Enabled user linger (service survives logout)");l(`Autostart installed for agent '${t}' on port ${e}`),n("Service",P),n("Unit file",m),n("Log file",h),c(),o(`Check status: systemctl --user status ${P}`)}async function nt(t){let e=`vibecontrols-agent-${t}.service`,r=V(t),i=[["systemctl","--user","stop",e],["systemctl","--user","disable",e]];for(let a of i)Bun.spawnSync(a);if(L(r))H(r),o(`Removed unit file: ${r}`);Bun.spawnSync(["systemctl","--user","daemon-reload"]),l(`Autostart removed for agent '${t}'`)}async function rt(t){let e=`vibecontrols-agent-${t}.service`,r=V(t);if(!L(r)){o(`Autostart is NOT configured for agent '${t}'`),n("Expected unit",r);return}g(`Autostart Status \u2014 ${t}`),n("Unit file",r),n("Service",e),c();let a=Bun.spawnSync(["systemctl","--user","status",e]).stdout.toString().trim();if(a)console.log(a);else o("Service status unavailable")}function F(t){let e=v(A(),"Library","LaunchAgents");return T(e,{recursive:!0}),v(e,`com.boff.vibecontrols.agent.${t}.plist`)}function z(t){return`<?xml version="1.0" encoding="UTF-8"?>
|
|
29
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
30
|
+
<plist version="1.0">
|
|
31
|
+
<dict>
|
|
32
|
+
<key>Label</key>
|
|
33
|
+
<string>com.boff.vibecontrols.agent.${d(t.name)}</string>
|
|
34
|
+
<key>ProgramArguments</key>
|
|
35
|
+
<array>
|
|
36
|
+
<string>${d(t.bunPath)}</string>
|
|
37
|
+
<string>run</string>
|
|
38
|
+
<string>${d(t.entryPoint)}</string>
|
|
39
|
+
</array>
|
|
40
|
+
<key>EnvironmentVariables</key>
|
|
41
|
+
<dict>
|
|
42
|
+
<key>PORT</key>
|
|
43
|
+
<string>${d(t.port)}</string>
|
|
44
|
+
<key>DB_PATH</key>
|
|
45
|
+
<string>${d(t.dbPath)}</string>${t.host?`
|
|
46
|
+
<key>HOST</key>
|
|
47
|
+
<string>${d(t.host)}</string>`:""}
|
|
48
|
+
<key>NODE_ENV</key>
|
|
49
|
+
<string>production</string>${t.profile?`
|
|
50
|
+
<key>VIBECONTROLS_PROFILE</key>
|
|
51
|
+
<string>${d(t.profile)}</string>`:""}${t.profiles?`
|
|
52
|
+
<key>VIBECONTROLS_PROFILES</key>
|
|
53
|
+
<string>${d(t.profiles)}</string>`:""}${t.home?`
|
|
54
|
+
<key>VIBECONTROLS_HOME</key>
|
|
55
|
+
<string>${d(t.home)}</string>`:""}${t.isolatePlugins?`
|
|
56
|
+
<key>VIBE_ISOLATE_PLUGINS</key>
|
|
57
|
+
<string>${d(t.isolatePlugins)}</string>`:""}
|
|
58
|
+
<key>AGENT_LOG_FILE</key>
|
|
59
|
+
<string>${d(t.logFile)}</string>
|
|
60
|
+
<key>HOME</key>
|
|
61
|
+
<string>${d(A())}</string>
|
|
62
|
+
<key>PATH</key>
|
|
63
|
+
<string>${d(process.env.PATH??"")}</string>
|
|
64
|
+
</dict>
|
|
65
|
+
<key>WorkingDirectory</key>
|
|
66
|
+
<string>${d(A())}</string>
|
|
67
|
+
<key>RunAtLoad</key>
|
|
68
|
+
<true/>
|
|
69
|
+
<key>KeepAlive</key>
|
|
70
|
+
<dict>
|
|
71
|
+
<key>SuccessfulExit</key>
|
|
72
|
+
<false/>
|
|
73
|
+
</dict>
|
|
74
|
+
<key>StandardOutPath</key>
|
|
75
|
+
<string>${d(t.logFile)}</string>
|
|
76
|
+
<key>StandardErrorPath</key>
|
|
77
|
+
<string>${d(t.logFile)}</string>
|
|
78
|
+
<key>ProcessType</key>
|
|
79
|
+
<string>Background</string>
|
|
80
|
+
</dict>
|
|
81
|
+
</plist>
|
|
82
|
+
`}async function st(t,e,r,i={}){C(t),R(r,"dbPath");let a=B(),f=D(),h=v(w(),`${t}.log`),m=F(t);T(w(),{recursive:!0});let P=z({name:t,port:e,dbPath:r,bunPath:a,entryPoint:f,logFile:h,host:i.host,profile:i.profile,profiles:i.profiles,home:i.home,isolatePlugins:i.isolatePlugins});if(U(m,P),o(`Wrote launchd plist: ${m}`),i.skipStart){l(`Autostart configured for agent '${t}' on port ${e}`),n("Plist",m),n("Log file",h);return}let k=Bun.spawnSync(["launchctl","load",m]);if(k.exitCode!==0){let S=k.stderr.toString().trim();p(`launchctl load failed: ${S}`),o("Trying bootstrap method...");let N=Bun.spawnSync(["id","-u"]).stdout.toString().trim(),E=Bun.spawnSync(["launchctl","bootstrap",`gui/${N}`,m]);if(E.exitCode!==0){let O=E.stderr.toString().trim();throw Error(`launchctl could not load ${m}: load failed${S?` \u2014 ${S}`:""}; bootstrap failed (exit ${E.exitCode})${O?` \u2014 ${O}`:""}`)}}l(`Autostart installed for agent '${t}' on port ${e}`),n("Plist",m),n("Log file",h)}async function it(t){let e=F(t),r=`com.boff.vibecontrols.agent.${t}`;Bun.spawnSync(["launchctl","unload",e]);let i=Bun.spawnSync(["id","-u"]).stdout.toString().trim();if(Bun.spawnSync(["launchctl","bootout",`gui/${i}/${r}`]),L(e))H(e),o(`Removed plist: ${e}`);l(`Autostart removed for agent '${t}'`)}async function ot(t){let e=F(t),r=`com.boff.vibecontrols.agent.${t}`;if(!L(e)){o(`Autostart is NOT configured for agent '${t}'`),n("Expected plist",e);return}g(`Autostart Status \u2014 ${t}`),n("Plist",e),n("Label",r),c();let f=Bun.spawnSync(["launchctl","list"]).stdout.toString().split(`
|
|
83
|
+
`).filter((h)=>h.includes("vibecontrols"));if(f.length>0)console.log(f.join(`
|
|
84
|
+
`));else o("Service not currently loaded")}function M(t){return`VibeControlsAgent_${t}`}function Q(t){return v(W(),`autostart-${t}.xml`)}function at(t){let e=[`<Variable><Name>VIBECONTROLS_PROFILE</Name><Value>${d(t.name)}</Value></Variable>`,`<Variable><Name>PORT</Name><Value>${d(t.port)}</Value></Variable>`,`<Variable><Name>VIBECONTROLS_HOME</Name><Value>${d(t.configDir)}</Value></Variable>`];if(t.dbPath)e.push(`<Variable><Name>DB_PATH</Name><Value>${d(t.dbPath)}</Value></Variable>`);let r=process.env.USERNAME??process.env.USER??"User";return`<?xml version="1.0" encoding="UTF-16"?>
|
|
85
|
+
<Task version="1.4" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
|
|
86
|
+
<RegistrationInfo>
|
|
87
|
+
<Description>VibeControls Agent (${d(t.name)}) \u2014 auto-start on logon, restart on crash</Description>
|
|
88
|
+
</RegistrationInfo>
|
|
89
|
+
<Triggers>
|
|
90
|
+
<LogonTrigger>
|
|
91
|
+
<Enabled>true</Enabled>
|
|
92
|
+
<UserId>${d(r)}</UserId>
|
|
93
|
+
</LogonTrigger>
|
|
94
|
+
</Triggers>
|
|
95
|
+
<Principals>
|
|
96
|
+
<Principal id="Author">
|
|
97
|
+
<UserId>${d(r)}</UserId>
|
|
98
|
+
<LogonType>InteractiveToken</LogonType>
|
|
99
|
+
<RunLevel>LeastPrivilege</RunLevel>
|
|
100
|
+
</Principal>
|
|
101
|
+
</Principals>
|
|
102
|
+
<Settings>
|
|
103
|
+
<MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
|
|
104
|
+
<DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
|
|
105
|
+
<StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
|
|
106
|
+
<AllowHardTerminate>true</AllowHardTerminate>
|
|
107
|
+
<StartWhenAvailable>true</StartWhenAvailable>
|
|
108
|
+
<RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
|
|
109
|
+
<IdleSettings>
|
|
110
|
+
<StopOnIdleEnd>false</StopOnIdleEnd>
|
|
111
|
+
<RestartOnIdle>false</RestartOnIdle>
|
|
112
|
+
</IdleSettings>
|
|
113
|
+
<AllowStartOnDemand>true</AllowStartOnDemand>
|
|
114
|
+
<Enabled>true</Enabled>
|
|
115
|
+
<Hidden>true</Hidden>
|
|
116
|
+
<RunOnlyIfIdle>false</RunOnlyIfIdle>
|
|
117
|
+
<WakeToRun>false</WakeToRun>
|
|
118
|
+
<ExecutionTimeLimit>PT0S</ExecutionTimeLimit>
|
|
119
|
+
<Priority>7</Priority>
|
|
120
|
+
<RestartOnFailure>
|
|
121
|
+
<Interval>PT1M</Interval>
|
|
122
|
+
<Count>3</Count>
|
|
123
|
+
</RestartOnFailure>
|
|
124
|
+
</Settings>
|
|
125
|
+
<Actions Context="Author">
|
|
126
|
+
<Exec>
|
|
127
|
+
<Command>${d(t.bunPath)}</Command>
|
|
128
|
+
<Arguments>${d(t.entryPoint)} start --foreground --port ${d(t.port)} --name ${d(t.name)}${t.host?` --host ${d(t.host)}`:""}</Arguments>
|
|
129
|
+
<WorkingDirectory>${d(t.configDir)}</WorkingDirectory>
|
|
130
|
+
</Exec>
|
|
131
|
+
</Actions>
|
|
132
|
+
</Task>`}async function lt(t,e,r,i={}){let a=M(t),f=Q(t),h=W(),m=w();T(h,{recursive:!0}),T(m,{recursive:!0});let P=B(),k=D(),S=at({name:t,port:e,host:i.host,dbPath:r,bunPath:P,entryPoint:k,configDir:h,logsDir:m}),N=Buffer.concat([Buffer.from([255,254]),Buffer.from(S,"utf16le")]);if(U(f,N),n("Task XML",f),Bun.spawnSync(["schtasks","/Create","/TN",a,"/XML",f,"/F"],{stdout:"inherit",stderr:"inherit"}).exitCode!==0)throw Error("schtasks /Create failed. Run from an elevated shell if your user lacks scheduler permission.");c(),l(`Autostart installed for agent '${t}' (Task: ${a})`),o("To start now without rebooting:"),o(` schtasks /Run /TN ${a}`)}async function ut(t){let e=M(t),r=Q(t),i=Bun.spawnSync(["schtasks","/Delete","/TN",e,"/F"],{stdout:"pipe",stderr:"pipe"});if(i.exitCode!==0)p(`schtasks /Delete returned non-zero (${i.exitCode}). Task may not have existed.`);else l(`Removed scheduled task ${e}`);if(L(r))try{H(r)}catch{}}async function ct(t){let e=M(t),r=Bun.spawnSync(["schtasks","/Query","/TN",e,"/V","/FO","LIST"],{stdout:"pipe",stderr:"pipe"});if(r.exitCode!==0){o(`Autostart is NOT configured for agent '${t}'`),n("Expected task",e);return}g(`Autostart Status \u2014 ${t}`),n("Task",e),c(),console.log(r.stdout.toString())}function G(t,e,r){if(!L(e))return!1;try{let i=r({bunPath:B(),entryPoint:D(),logFile:v(w(),`${t.name}.log`)});return q(e,"utf8")===i}catch{return!0}}function gt(t){try{let e=Bun.spawnSync(["systemctl","--user","is-enabled",`vibecontrols-agent-${t}.service`]);if(e.exitCode===0)return!0;let r=e.stdout.toString().trim();return!["disabled","masked","linked",""].includes(r)}catch{return!0}}var Z={linux:{label:"systemd",install:(t,e,r,i)=>et(t,e,r??"./agent-db",i),uninstall:nt,status:rt,isCurrent:(t)=>G(t,V(t.name),(e)=>X({...t,...e}))&>(t.name),autoConfigurable:!0},darwin:{label:"launchd",install:(t,e,r,i)=>st(t,e,r??"./agent-db",i),uninstall:it,status:ot,isCurrent:(t)=>G(t,F(t.name),(e)=>z({...t,...e})),autoConfigurable:!0},win32:{label:"Task Scheduler",install:lt,uninstall:ut,status:ct,isCurrent:()=>!0,autoConfigurable:!1}};function _(){let t=Z[x()];if(!t)throw Error(`Autostart is not supported on ${x()}. Supported: linux (systemd), darwin (launchd), win32 (Task Scheduler).`);return t}async function Zi(t){let e=process.env.VIBECONTROLS_PROFILES||void 0,r=process.env.VIBECONTROLS_HOME||void 0,i=process.env.VIBE_ISOLATE_PLUGINS||void 0;if(process.env.VIBE_NO_AUTOSTART==="1"||process.env.VIBE_AUTOSTART==="0")return{installed:!1,reason:"opted out via env"};let a=Z[x()];if(!a)return{installed:!1,reason:`unsupported platform ${x()}`};if(!a.autoConfigurable)return{installed:!1,reason:`${a.label} must be configured manually \u2014 run \`vibe autostart install\``};try{let f={name:t.name,port:t.port,dbPath:t.dbPath??"./agent-db",host:t.host,profile:t.profile,profiles:e,home:r,isolatePlugins:i};if(a.isCurrent(f))return{installed:!1,reason:"already configured"};return await a.install(t.name,t.port,t.dbPath,{skipStart:!0,host:t.host,profile:t.profile,profiles:e,home:r,isolatePlugins:i}),{installed:!0,serviceLabel:a.label}}catch(f){return{installed:!1,failed:!0,reason:f instanceof Error?f.message:String(f)}}}function qr(t){let e=t.command("autostart").description("Configure agent to auto-start on system boot");e.command("install").description("Generate and enable system service for auto-start on reboot").option("-n, --name <name>","Agent instance name","default").option("-p, --port <port>","Port to listen on","3005").option("--db-path <path>","Agent storage directory (absolute path; default: ~/.boff/vibecontrols/agents/<profile>/agent-db)").option("--json","Emit JSON").action(async function(r){let i={...t.opts(),...r};try{let a=_(),f=C(r.name),h=Y(r.port),m=r.dbPath??null,P=ee(),k=(()=>{if(!m)return P;if(J(m))return m;let S=K(P,"..",m);return p(`--db-path is relative; resolved to ${S}. Pass an absolute path to silence this warning.`),S})();if(!i.json)g("Installing Autostart"),n("Platform",`${x()} (${a.label})`),n("Agent",f),n("Port",String(h)),n("Database",k),c();await a.install(f,h,k),u(i,{ok:!0,enabled:!0,name:f,port:h})}catch(a){if(i.json)u(i,{ok:!1,error:String(a)}),process.exit(1);s(`Failed to install autostart: ${a}`),process.exit(1)}}),e.command("uninstall").description("Stop and remove the system service").option("-n, --name <name>","Agent instance name","default").option("--json","Emit JSON").action(async function(r){let i={...t.opts(),...r};try{let a=_(),f=C(r.name);if(!i.json)g("Removing Autostart");await a.uninstall(f),u(i,{ok:!0,enabled:!1,name:f})}catch(a){if(i.json)u(i,{ok:!1,error:String(a)}),process.exit(1);s(`Failed to uninstall autostart: ${a}`),process.exit(1)}}),e.command("status").description("Check if autostart is configured and running").option("-n, --name <name>","Agent instance name","default").action(async(r)=>{try{let i=_(),a=C(r.name);await i.status(a)}catch(i){s(`Failed to check autostart status: ${i}`),process.exit(1)}})}
|
|
133
|
+
export{Zi,qr};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{R}from"./index-0qjbnyg4.js";import{J,w,M,X}from"./index-kwhx023z.js";import{i,s,A,l,o,g,n,c,F}from"./index-7f2k4g6q.js";import{_,y,u}from"./index-t5cfkz1e.js";async function Vi(){if(process.env.AGENT_API_KEY)return process.env.AGENT_API_KEY;let a="default";try{a=R()}catch{}let d=await J(`${a}:static-api-key`);if(d)return d;return w()["static-api-key"]??null}var S=["read","mutate","plugin:install","plugin:remove","update","admin"];function K(a){if(a.length<=12)return"[redacted]";return`${a.slice(0,8)}...${a.slice(-4)}`}function I(){let a=new Uint8Array(32);return crypto.getRandomValues(a),`vcak_${Buffer.from(a).toString("base64url")}`}function N(){return crypto.randomUUID()}function b(a){if(!a)return;let d=/^(\d+)([smhdw]?)$/.exec(a.trim());if(!d)throw Error(`Invalid --expires-in: ${a} (use 30s, 12h, 7d, 4w; bare digits = days)`);let e=Number(d[1]),f=d[2]||"d",t=f==="s"?e*1000:f==="m"?e*60000:f==="h"?e*3600000:f==="w"?e*7*86400000:e*86400000;return new Date(Date.now()+t).toISOString()}function E(a){if(!a)return["read"];let d=a.split(",").map((e)=>e.trim()).filter(Boolean);for(let e of d)if(!S.includes(e))throw Error(`Unknown scope: ${e}. Allowed: ${S.join(", ")}`);return d}function jr(a){let d=a.command("key").description("Show or manage VibeControls agent API keys");d.command("show",{isDefault:!0}).description("Show the default agent API key").option("--show-secret","Print the full API key",!1).option("--json","Emit JSON").option("--plain","Force plain text output").action(async function(e){let f={...a.opts(),...e};try{await y({mode:_(f),fetchData:async()=>({apiKey:await Vi()??null}),plain:(t)=>{if(g("Agent API Key"),c(),!t.apiKey){s("No API key found in AGENT_API_KEY or local agent config.");return}if(n("API Key",i.bold(e.showSecret?t.apiKey:K(t.apiKey))),!e.showSecret)n("Full key",i.dim("hidden; rerun with --show-secret"));c()},json:(t)=>({apiKey:t.apiKey?e.showSecret?t.apiKey:"[redacted]":null})})}catch(t){s(`Failed to get API key: ${A(t)}`)}}),d.command("list").description("List all scoped API keys (default + minted)").option("--json","Emit JSON").option("--plain","Force plain text output").option("--show-secret","Include full key values in JSON output",!1).action(async function(e){let f={...a.opts(),...e};try{await y({mode:_(f),fetchData:()=>X(),plain:(t)=>{let r=[],m=t["static-api-key"];if(m)r.push({ID:"default",Name:"default",Scopes:"admin",Expires:"never",Key:K(m)});for(let p of t.apiKeys??[])r.push({ID:p.id??"(legacy)",Name:p.name,Scopes:p.scopes.join(","),Expires:p.expiresAt??"never",Key:K(p.key)});if(r.length===0){o("No keys configured.");return}g("Agent API Keys"),F(r)},json:(t)=>{let r=[],m=t["static-api-key"];if(m)r.push({id:"default",name:"default",scopes:["admin"],expiresAt:null,key:e.showSecret?m:"[redacted]"});for(let p of t.apiKeys??[])r.push({id:p.id??"(legacy)",name:p.name,scopes:p.scopes,expiresAt:p.expiresAt??null,key:e.showSecret?p.key:"[redacted]"});return r}})}catch(t){s(A(t))}}),d.command("add").description("Mint a new scoped API key").requiredOption("--name <name>","Display name (logs only)").option("--scope <scope>",`Comma-separated scope list (default: read). Allowed: ${S.join(",")}`,"read").option("--expires-in <duration>","TTL (e.g. 7d, 12h, 30m). Omit for no expiry.").option("--not-before <iso>","ISO timestamp before which the key is rejected.").option("--json","Emit JSON").action(function(e){let f={...a.opts(),...e};try{let t=E(e.scope),r=b(e.expiresIn),m=w(),p=N(),h=I(),k={id:p,name:e.name,key:h,scopes:t,expiresAt:r,notBefore:e.notBefore,createdAt:new Date().toISOString()},x=[...m.apiKeys??[],k];if(M({apiKeys:x}),u(f,{ok:!0,id:p,name:e.name,scopes:t,expiresAt:r??null,key:h}))return;if(l(`Minted key ${p}`),n("Name",e.name),n("Scopes",t.join(",")),r)n("Expires",r);if(e.notBefore)n("Not before",e.notBefore);c(),n("Key (save now)",i.bold(h))}catch(t){if(f.json){u(f,{ok:!1,error:A(t)});return}s(A(t))}}),d.command("revoke <id>").description("Revoke a scoped key by ID").option("--json","Emit JSON").action(function(e,f){let t={...a.opts(),...f};try{let r=w(),m=(r.apiKeys??[]).length,p=(r.apiKeys??[]).filter((h)=>h.id!==e);if(p.length===m){if(t.json){u(t,{ok:!1,error:`No key with id ${e}`});return}s(`No key with id ${e}`);return}if(M({apiKeys:p}),u(t,{ok:!0,id:e}))return;l(`Revoked key ${e}`)}catch(r){if(t.json){u(t,{ok:!1,error:A(r)});return}s(A(r))}}),d.command("rotate <id>").description("Rotate the secret of an existing scoped key (preserves scopes/expiry)").option("--json","Emit JSON").action(function(e,f){let t={...a.opts(),...f};try{let r=w();if(!(r.apiKeys??[]).find((k)=>k.id===e)){if(t.json){u(t,{ok:!1,error:`No key with id ${e}`});return}s(`No key with id ${e}`);return}let p=I(),h=(r.apiKeys??[]).map((k)=>k.id===e?{...k,key:p}:k);if(M({apiKeys:h}),u(t,{ok:!0,id:e,key:p}))return;l(`Rotated key ${e}`),n("New key (save now)",i.bold(p))}catch(r){if(t.json){u(t,{ok:!1,error:A(r)});return}s(A(r))}})}
|
|
3
|
+
export{Vi,jr};
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
class f extends Error{constructor(t,e,i){super(i);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=e,this.exitCode=t,this.nestedError=void 0}}class _ extends f{constructor(t){super(1,"commander.invalidArgument",t);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}}class C{constructor(t,e){switch(this.description=e||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,t[0]){case"<":this.required=!0,this._name=t.slice(1,-1);break;case"[":this.required=!1,this._name=t.slice(1,-1);break;default:this.required=!0,this._name=t;break}if(this._name.endsWith("..."))this.variadic=!0,this._name=this._name.slice(0,-3)}name(){return this._name}_collectValue(t,e){if(e===this.defaultValue||!Array.isArray(e))return[t];return e.push(t),e}default(t,e){return this.defaultValue=t,this.defaultValueDescription=e,this}argParser(t){return this.parseArg=t,this}choices(t){return this.argChoices=t.slice(),this.parseArg=(e,i)=>{if(!this.argChoices.includes(e))throw new _(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._collectValue(e,i);return e},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}}function b(t){let e=t.name()+(t.variadic===!0?"...":"");return t.required?"<"+e+">":"["+e+"]"}import{EventEmitter as P}from"events";import E from"child_process";import m from"path";import x from"fs";import p from"process";import{stripVTControlCharacters as W}from"util";import{stripVTControlCharacters as S}from"util";class A{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(t){this.helpWidth=this.helpWidth??t.helpWidth??80}visibleCommands(t){let e=t.commands.filter((n)=>!n._hidden),i=t._getHelpCommand();if(i&&!i._hidden)e.push(i);if(this.sortSubcommands)e.sort((n,s)=>n.name().localeCompare(s.name()));return e}compareOptions(t,e){let i=(n)=>n.short?n.short.replace(/^-/,""):n.long.replace(/^--/,"");return i(t).localeCompare(i(e))}visibleOptions(t){let e=t.options.filter((n)=>!n.hidden),i=t._getHelpOption();if(i&&!i.hidden){let n=i.short&&t._findOption(i.short),s=i.long&&t._findOption(i.long);if(!n&&!s)e.push(i);else if(i.long&&!s)e.push(t.createOption(i.long,i.description));else if(i.short&&!n)e.push(t.createOption(i.short,i.description))}if(this.sortOptions)e.sort(this.compareOptions);return e}visibleGlobalOptions(t){if(!this.showGlobalOptions)return[];let e=[];for(let i=t.parent;i;i=i.parent){let n=i.options.filter((s)=>!s.hidden);e.push(...n)}if(this.sortOptions)e.sort(this.compareOptions);return e}visibleArguments(t){if(t._argsDescription)t.registeredArguments.forEach((e)=>{e.description=e.description||t._argsDescription[e.name()]||""});if(t.registeredArguments.find((e)=>e.description))return t.registeredArguments;return[]}subcommandTerm(t){let e=t.registeredArguments.map((i)=>b(i)).join(" ");return t._name+(t._aliases[0]?"|"+t._aliases[0]:"")+(t.options.length?" [options]":"")+(e?" "+e:"")}optionTerm(t){return t.flags}argumentTerm(t){return t.name()}longestSubcommandTermLength(t,e){return e.visibleCommands(t).reduce((i,n)=>Math.max(i,this.displayWidth(e.styleSubcommandTerm(e.subcommandTerm(n)))),0)}longestOptionTermLength(t,e){return e.visibleOptions(t).reduce((i,n)=>Math.max(i,this.displayWidth(e.styleOptionTerm(e.optionTerm(n)))),0)}longestGlobalOptionTermLength(t,e){return e.visibleGlobalOptions(t).reduce((i,n)=>Math.max(i,this.displayWidth(e.styleOptionTerm(e.optionTerm(n)))),0)}longestArgumentTermLength(t,e){return e.visibleArguments(t).reduce((i,n)=>Math.max(i,this.displayWidth(e.styleArgumentTerm(e.argumentTerm(n)))),0)}commandUsage(t){let e=t._name;if(t._aliases[0])e=e+"|"+t._aliases[0];let i="";for(let n=t.parent;n;n=n.parent)i=n.name()+" "+i;return i+e+" "+t.usage()}commandDescription(t){return t.description()}subcommandDescription(t){return t.summary()||t.description()}optionDescription(t){let e=[];if(t.argChoices)e.push(`choices: ${t.argChoices.map((i)=>JSON.stringify(i)).join(", ")}`);if(t.defaultValue!==void 0){if(t.required||t.optional||t.isBoolean()&&typeof t.defaultValue==="boolean")e.push(`default: ${t.defaultValueDescription||JSON.stringify(t.defaultValue)}`)}if(t.presetArg!==void 0&&t.optional)e.push(`preset: ${JSON.stringify(t.presetArg)}`);if(t.envVar!==void 0)e.push(`env: ${t.envVar}`);if(e.length>0){let i=`(${e.join(", ")})`;if(t.description)return`${t.description} ${i}`;return i}return t.description}argumentDescription(t){let e=[];if(t.argChoices)e.push(`choices: ${t.argChoices.map((i)=>JSON.stringify(i)).join(", ")}`);if(t.defaultValue!==void 0)e.push(`default: ${t.defaultValueDescription||JSON.stringify(t.defaultValue)}`);if(e.length>0){let i=`(${e.join(", ")})`;if(t.description)return`${t.description} ${i}`;return i}return t.description}formatItemList(t,e,i){if(e.length===0)return[];return[i.styleTitle(t),...e,""]}groupItems(t,e,i){let n=new Map;return t.forEach((s)=>{let r=i(s);if(!n.has(r))n.set(r,[])}),e.forEach((s)=>{let r=i(s);if(!n.has(r))n.set(r,[]);n.get(r).push(s)}),n}formatHelp(t,e){let i=e.padWidth(t,e),n=e.helpWidth??80;function s(u,c){return e.formatItem(u,i,c,e)}let r=[`${e.styleTitle("Usage:")} ${e.styleUsage(e.commandUsage(t))}`,""],o=e.commandDescription(t);if(o.length>0)r=r.concat([e.boxWrap(e.styleCommandDescription(o),n),""]);let h=e.visibleArguments(t).map((u)=>s(e.styleArgumentTerm(e.argumentTerm(u)),e.styleArgumentDescription(e.argumentDescription(u))));if(r=r.concat(this.formatItemList("Arguments:",h,e)),this.groupItems(t.options,e.visibleOptions(t),(u)=>u.helpGroupHeading??"Options:").forEach((u,c)=>{let g=u.map((d)=>s(e.styleOptionTerm(e.optionTerm(d)),e.styleOptionDescription(e.optionDescription(d))));r=r.concat(this.formatItemList(c,g,e))}),e.showGlobalOptions){let u=e.visibleGlobalOptions(t).map((c)=>s(e.styleOptionTerm(e.optionTerm(c)),e.styleOptionDescription(e.optionDescription(c))));r=r.concat(this.formatItemList("Global Options:",u,e))}return this.groupItems(t.commands,e.visibleCommands(t),(u)=>u.helpGroup()||"Commands:").forEach((u,c)=>{let g=u.map((d)=>s(e.styleSubcommandTerm(e.subcommandTerm(d)),e.styleSubcommandDescription(e.subcommandDescription(d))));r=r.concat(this.formatItemList(c,g,e))}),r.join(`
|
|
3
|
+
`)}displayWidth(t){return S(t).length}styleTitle(t){return t}styleUsage(t){return t.split(" ").map((e)=>{if(e==="[options]")return this.styleOptionText(e);if(e==="[command]")return this.styleSubcommandText(e);if(e[0]==="["||e[0]==="<")return this.styleArgumentText(e);return this.styleCommandText(e)}).join(" ")}styleCommandDescription(t){return this.styleDescriptionText(t)}styleOptionDescription(t){return this.styleDescriptionText(t)}styleSubcommandDescription(t){return this.styleDescriptionText(t)}styleArgumentDescription(t){return this.styleDescriptionText(t)}styleDescriptionText(t){return t}styleOptionTerm(t){return this.styleOptionText(t)}styleSubcommandTerm(t){return t.split(" ").map((e)=>{if(e==="[options]")return this.styleOptionText(e);if(e[0]==="["||e[0]==="<")return this.styleArgumentText(e);return this.styleSubcommandText(e)}).join(" ")}styleArgumentTerm(t){return this.styleArgumentText(t)}styleOptionText(t){return t}styleArgumentText(t){return t}styleSubcommandText(t){return t}styleCommandText(t){return t}padWidth(t,e){return Math.max(e.longestOptionTermLength(t,e),e.longestGlobalOptionTermLength(t,e),e.longestSubcommandTermLength(t,e),e.longestArgumentTermLength(t,e))}preformatted(t){return/\n[^\S\r\n]/.test(t)}formatItem(t,e,i,n){let r=" ".repeat(2);if(!i)return r+t;let o=t.padEnd(e+t.length-n.displayWidth(t)),h=2,a=(this.helpWidth??80)-e-h-2,u;if(a<this.minWidthToWrap||n.preformatted(i))u=i;else u=n.boxWrap(i,a).replace(/\n/g,`
|
|
4
|
+
`+" ".repeat(e+h));return r+o+" ".repeat(h)+u.replace(/\n/g,`
|
|
5
|
+
${r}`)}boxWrap(t,e){if(e<this.minWidthToWrap)return t;let i=t.split(/\r\n|\n/),n=/[\s]*[^\s]+/g,s=[];return i.forEach((r)=>{let o=r.match(n);if(o===null){s.push("");return}let h=[o.shift()],l=this.displayWidth(h[0]);o.forEach((a)=>{let u=this.displayWidth(a);if(l+u<=e){h.push(a),l+=u;return}s.push(h.join(""));let c=a.trimStart();h=[c],l=this.displayWidth(c)}),s.push(h.join(""))}),s.join(`
|
|
6
|
+
`)}}class O{constructor(t,e){this.flags=t,this.description=e||"",this.required=t.includes("<"),this.optional=t.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(t),this.mandatory=!1;let i=T(t);if(this.short=i.shortFlag,this.long=i.longFlag,this.negate=!1,this.long)this.negate=this.long.startsWith("--no-");this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0,this.helpGroupHeading=void 0}default(t,e){return this.defaultValue=t,this.defaultValueDescription=e,this}preset(t){return this.presetArg=t,this}conflicts(t){return this.conflictsWith=this.conflictsWith.concat(t),this}implies(t){let e=t;if(typeof t==="string")e={[t]:!0};return this.implied=Object.assign(this.implied||{},e),this}env(t){return this.envVar=t,this}argParser(t){return this.parseArg=t,this}makeOptionMandatory(t=!0){return this.mandatory=!!t,this}hideHelp(t=!0){return this.hidden=!!t,this}_collectValue(t,e){if(e===this.defaultValue||!Array.isArray(e))return[t];return e.push(t),e}choices(t){return this.argChoices=t.slice(),this.parseArg=(e,i)=>{if(!this.argChoices.includes(e))throw new _(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._collectValue(e,i);return e},this}name(){if(this.long)return this.long.replace(/^--/,"");return this.short.replace(/^-/,"")}attributeName(){if(this.negate)return H(this.name().replace(/^no-/,""));return H(this.name())}helpGroup(t){return this.helpGroupHeading=t,this}is(t){return this.short===t||this.long===t}isBoolean(){return!this.required&&!this.optional&&!this.negate}}class y{constructor(t){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,t.forEach((e)=>{if(e.negate)this.negativeOptions.set(e.attributeName(),e);else this.positiveOptions.set(e.attributeName(),e)}),this.negativeOptions.forEach((e,i)=>{if(this.positiveOptions.has(i))this.dualOptions.add(i)})}valueFromOption(t,e){let i=e.attributeName();if(!this.dualOptions.has(i))return!0;let n=this.negativeOptions.get(i).presetArg,s=n!==void 0?n:!1;return e.negate===(s===t)}}function H(t){return t.split("-").reduce((e,i)=>e+i[0].toUpperCase()+i.slice(1))}function T(t){let e,i,n=/^-[^-]$/,s=/^--[^-]/,r=t.split(/[ |,]+/).concat("guard");if(n.test(r[0]))e=r.shift();if(s.test(r[0]))i=r.shift();if(!e&&n.test(r[0]))e=r.shift();if(!e&&s.test(r[0]))e=i,i=r.shift();if(r[0].startsWith("-")){let o=r[0],h=`option creation failed due to '${o}' in option flags '${t}'`;if(/^-[^-][^-]/.test(o))throw Error(`${h}
|
|
7
|
+
- a short flag is a single dash and a single character
|
|
8
|
+
- either use a single dash and a single character (for a short flag)
|
|
9
|
+
- or use a double dash for a long option (and can have two, like '--ws, --workspace')`);if(n.test(o))throw Error(`${h}
|
|
10
|
+
- too many short flags`);if(s.test(o))throw Error(`${h}
|
|
11
|
+
- too many long flags`);throw Error(`${h}
|
|
12
|
+
- unrecognised flag format`)}if(e===void 0&&i===void 0)throw Error(`option creation failed due to no flags found in '${t}'.`);return{shortFlag:e,longFlag:i}}function k(t,e){if(Math.abs(t.length-e.length)>3)return Math.max(t.length,e.length);let i=[];for(let n=0;n<=t.length;n++)i[n]=[n];for(let n=0;n<=e.length;n++)i[0][n]=n;for(let n=1;n<=e.length;n++)for(let s=1;s<=t.length;s++){let r;if(t[s-1]===e[n-1])r=0;else r=1;if(i[s][n]=Math.min(i[s-1][n]+1,i[s][n-1]+1,i[s-1][n-1]+r),s>1&&n>1&&t[s-1]===e[n-2]&&t[s-2]===e[n-1])i[s][n]=Math.min(i[s][n],i[s-2][n-2]+1)}return i[t.length][e.length]}function w(t,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let i=t.startsWith("--");if(i)t=t.slice(2),e=e.map((o)=>o.slice(2));let n=[],s=3,r=0.4;if(e.forEach((o)=>{if(o.length<=1)return;let h=k(t,o),l=Math.max(t.length,o.length);if((l-h)/l>r){if(h<s)s=h,n=[o];else if(h===s)n.push(o)}}),n.sort((o,h)=>o.localeCompare(h)),i)n=n.map((o)=>`--${o}`);if(n.length>1)return`
|
|
13
|
+
(Did you mean one of ${n.join(", ")}?)`;if(n.length===1)return`
|
|
14
|
+
(Did you mean ${n[0]}?)`;return""}class $e extends P{constructor(t){super();this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=t||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._savedState=null,this._outputConfiguration={writeOut:(e)=>p.stdout.write(e),writeErr:(e)=>p.stderr.write(e),outputError:(e,i)=>i(e),getOutHelpWidth:()=>p.stdout.isTTY?p.stdout.columns:void 0,getErrHelpWidth:()=>p.stderr.isTTY?p.stderr.columns:void 0,getOutHasColors:()=>V()??(p.stdout.isTTY&&p.stdout.hasColors?.()),getErrHasColors:()=>V()??(p.stderr.isTTY&&p.stderr.hasColors?.()),stripColor:(e)=>W(e)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={},this._helpGroupHeading=void 0,this._defaultCommandGroup=void 0,this._defaultOptionGroup=void 0}copyInheritedSettings(t){return this._outputConfiguration=t._outputConfiguration,this._helpOption=t._helpOption,this._helpCommand=t._helpCommand,this._helpConfiguration=t._helpConfiguration,this._exitCallback=t._exitCallback,this._storeOptionsAsProperties=t._storeOptionsAsProperties,this._combineFlagAndOptionalValue=t._combineFlagAndOptionalValue,this._allowExcessArguments=t._allowExcessArguments,this._enablePositionalOptions=t._enablePositionalOptions,this._showHelpAfterError=t._showHelpAfterError,this._showSuggestionAfterError=t._showSuggestionAfterError,this}_getCommandAndAncestors(){let t=[];for(let e=this;e;e=e.parent)t.push(e);return t}command(t,e,i){let n=e,s=i;if(typeof n==="object"&&n!==null)s=n,n=null;s=s||{};let[,r,o]=t.match(/([^ ]+) *(.*)/),h=this.createCommand(r);if(n)h.description(n),h._executableHandler=!0;if(s.isDefault)this._defaultCommandName=h._name;if(h._hidden=!!(s.noHelp||s.hidden),h._executableFile=s.executableFile||null,o)h.arguments(o);if(this._registerCommand(h),h.parent=this,h.copyInheritedSettings(this),n)return this;return h}createCommand(t){return new $e(t)}createHelp(){return Object.assign(new A,this.configureHelp())}configureHelp(t){if(t===void 0)return this._helpConfiguration;return this._helpConfiguration=t,this}configureOutput(t){if(t===void 0)return this._outputConfiguration;return this._outputConfiguration={...this._outputConfiguration,...t},this}showHelpAfterError(t=!0){if(typeof t!=="string")t=!!t;return this._showHelpAfterError=t,this}showSuggestionAfterError(t=!0){return this._showSuggestionAfterError=!!t,this}addCommand(t,e){if(!t._name)throw Error(`Command passed to .addCommand() must have a name
|
|
15
|
+
- specify the name in Command constructor or using .name()`);if(e=e||{},e.isDefault)this._defaultCommandName=t._name;if(e.noHelp||e.hidden)t._hidden=!0;return this._registerCommand(t),t.parent=this,t._checkForBrokenPassThrough(),this}createArgument(t,e){return new C(t,e)}argument(t,e,i,n){let s=this.createArgument(t,e);if(typeof i==="function")s.default(n).argParser(i);else s.default(i);return this.addArgument(s),this}arguments(t){return t.trim().split(/ +/).forEach((e)=>{this.argument(e)}),this}addArgument(t){let e=this.registeredArguments.slice(-1)[0];if(e?.variadic)throw Error(`only the last argument can be variadic '${e.name()}'`);if(t.required&&t.defaultValue!==void 0&&t.parseArg===void 0)throw Error(`a default value for a required argument is never used: '${t.name()}'`);return this.registeredArguments.push(t),this}helpCommand(t,e){if(typeof t==="boolean"){if(this._addImplicitHelpCommand=t,t&&this._defaultCommandGroup)this._initCommandGroup(this._getHelpCommand());return this}let i=t??"help [command]",[,n,s]=i.match(/([^ ]+) *(.*)/),r=e??"display help for command",o=this.createCommand(n);if(o.helpOption(!1),s)o.arguments(s);if(r)o.description(r);if(this._addImplicitHelpCommand=!0,this._helpCommand=o,t||e)this._initCommandGroup(o);return this}addHelpCommand(t,e){if(typeof t!=="object")return this.helpCommand(t,e),this;return this._addImplicitHelpCommand=!0,this._helpCommand=t,this._initCommandGroup(t),this}_getHelpCommand(){if(this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))){if(this._helpCommand===void 0)this.helpCommand(void 0,void 0);return this._helpCommand}return null}hook(t,e){let i=["preSubcommand","preAction","postAction"];if(!i.includes(t))throw Error(`Unexpected value for event passed to hook : '${t}'.
|
|
16
|
+
Expecting one of '${i.join("', '")}'`);if(this._lifeCycleHooks[t])this._lifeCycleHooks[t].push(e);else this._lifeCycleHooks[t]=[e];return this}exitOverride(t){if(t)this._exitCallback=t;else this._exitCallback=(e)=>{if(e.code!=="commander.executeSubCommandAsync")throw e};return this}_exit(t,e,i){if(this._exitCallback)this._exitCallback(new f(t,e,i));p.exit(t)}action(t){let e=(i)=>{let n=this.registeredArguments.length,s=i.slice(0,n);if(this._storeOptionsAsProperties)s[n]=this;else s[n]=this.opts();return s.push(this),t.apply(this,s)};return this._actionHandler=e,this}createOption(t,e){return new O(t,e)}_callParseArg(t,e,i,n){try{return t.parseArg(e,i)}catch(s){if(s.code==="commander.invalidArgument"){let r=`${n} ${s.message}`;this.error(r,{exitCode:s.exitCode,code:s.code})}throw s}}_registerOption(t){let e=t.short&&this._findOption(t.short)||t.long&&this._findOption(t.long);if(e){let i=t.long&&this._findOption(t.long)?t.long:t.short;throw Error(`Cannot add option '${t.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${i}'
|
|
17
|
+
- already used by option '${e.flags}'`)}this._initOptionGroup(t),this.options.push(t)}_registerCommand(t){let e=(n)=>[n.name()].concat(n.aliases()),i=e(t).find((n)=>this._findCommand(n));if(i){let n=e(this._findCommand(i)).join("|"),s=e(t).join("|");throw Error(`cannot add command '${s}' as already have command '${n}'`)}this._initCommandGroup(t),this.commands.push(t)}addOption(t){this._registerOption(t);let e=t.name(),i=t.attributeName();if(t.defaultValue!==void 0)this.setOptionValueWithSource(i,t.defaultValue,"default");let n=(s,r,o)=>{if(s==null&&t.presetArg!==void 0)s=t.presetArg;let h=this.getOptionValue(i);if(s!==null&&t.parseArg)s=this._callParseArg(t,s,h,r);else if(s!==null&&t.variadic)s=t._collectValue(s,h);if(s==null)if(t.negate)s=!1;else if(t.isBoolean()||t.optional)s=!0;else s="";this.setOptionValueWithSource(i,s,o)};if(this.on("option:"+e,(s)=>{let r=`error: option '${t.flags}' argument '${s}' is invalid.`;n(s,r,"cli")}),t.envVar)this.on("optionEnv:"+e,(s)=>{let r=`error: option '${t.flags}' value '${s}' from env '${t.envVar}' is invalid.`;n(s,r,"env")});return this}_optionEx(t,e,i,n,s){if(typeof e==="object"&&e instanceof O)throw Error("To add an Option object use addOption() instead of option() or requiredOption()");let r=this.createOption(e,i);if(r.makeOptionMandatory(!!t.mandatory),typeof n==="function")r.default(s).argParser(n);else if(n instanceof RegExp){let o=n;n=(h,l)=>{let a=o.exec(h);return a?a[0]:l},r.default(s).argParser(n)}else r.default(n);return this.addOption(r)}option(t,e,i,n){return this._optionEx({},t,e,i,n)}requiredOption(t,e,i,n){return this._optionEx({mandatory:!0},t,e,i,n)}combineFlagAndOptionalValue(t=!0){return this._combineFlagAndOptionalValue=!!t,this}allowUnknownOption(t=!0){return this._allowUnknownOption=!!t,this}allowExcessArguments(t=!0){return this._allowExcessArguments=!!t,this}enablePositionalOptions(t=!0){return this._enablePositionalOptions=!!t,this}passThroughOptions(t=!0){return this._passThroughOptions=!!t,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(t=!0){if(this.options.length)throw Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!t,this}getOptionValue(t){if(this._storeOptionsAsProperties)return this[t];return this._optionValues[t]}setOptionValue(t,e){return this.setOptionValueWithSource(t,e,void 0)}setOptionValueWithSource(t,e,i){if(this._storeOptionsAsProperties)this[t]=e;else this._optionValues[t]=e;return this._optionValueSources[t]=i,this}getOptionValueSource(t){return this._optionValueSources[t]}getOptionValueSourceWithGlobals(t){let e;return this._getCommandAndAncestors().forEach((i)=>{if(i.getOptionValueSource(t)!==void 0)e=i.getOptionValueSource(t)}),e}_prepareUserArgs(t,e){if(t!==void 0&&!Array.isArray(t))throw Error("first parameter to parse must be array or undefined");if(e=e||{},t===void 0&&e.from===void 0){if(p.versions?.electron)e.from="electron";let n=p.execArgv??[];if(n.includes("-e")||n.includes("--eval")||n.includes("-p")||n.includes("--print"))e.from="eval"}if(t===void 0)t=p.argv;this.rawArgs=t.slice();let i;switch(e.from){case void 0:case"node":this._scriptPath=t[1],i=t.slice(2);break;case"electron":if(p.defaultApp)this._scriptPath=t[1],i=t.slice(2);else i=t.slice(1);break;case"user":i=t.slice(0);break;case"eval":i=t.slice(1);break;default:throw Error(`unexpected parse option { from: '${e.from}' }`)}if(!this._name&&this._scriptPath)this.nameFromFilename(this._scriptPath);return this._name=this._name||"program",i}parse(t,e){this._prepareForParse();let i=this._prepareUserArgs(t,e);return this._parseCommand([],i),this}async parseAsync(t,e){this._prepareForParse();let i=this._prepareUserArgs(t,e);return await this._parseCommand([],i),this}_prepareForParse(){if(this._savedState===null)this.options.filter((t)=>t.negate&&t.defaultValue===void 0&&this.getOptionValue(t.attributeName())===void 0).forEach((t)=>{let e=t.long.replace(/^--no-/,"--");if(!this._findOption(e))this.setOptionValueWithSource(t.attributeName(),!0,"default")}),this.saveStateBeforeParse();else this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw Error(`Can not call parse again when storeOptionsAsProperties is true.
|
|
18
|
+
- either make a new Command for each call to parse, or stop storing options as properties`);this._name=this._savedState._name,this._scriptPath=null,this.rawArgs=[],this._optionValues={...this._savedState._optionValues},this._optionValueSources={...this._savedState._optionValueSources},this.args=[],this.processedArgs=[]}_checkForMissingExecutable(t,e,i){if(x.existsSync(t))return;let n=e?`searched for local subcommand relative to directory '${e}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",s=`'${t}' does not exist
|
|
19
|
+
- if '${i}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
|
20
|
+
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
|
21
|
+
- ${n}`;throw Error(s)}_executeSubCommand(t,e){e=e.slice();let i=[".js",".ts",".tsx",".mjs",".cjs"];function n(a,u){let c=m.resolve(a,u);if(x.existsSync(c))return c;if(i.includes(m.extname(u)))return;let g=i.find((d)=>x.existsSync(`${c}${d}`));if(g)return`${c}${g}`;return}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let s=t._executableFile||`${this._name}-${t._name}`,r=this._executableDir||"";if(this._scriptPath){let a;try{a=x.realpathSync(this._scriptPath)}catch{a=this._scriptPath}r=m.resolve(m.dirname(a),r)}if(r){let a=n(r,s);if(!a&&!t._executableFile&&this._scriptPath){let u=m.basename(this._scriptPath,m.extname(this._scriptPath));if(u!==this._name)a=n(r,`${u}-${t._name}`)}s=a||s}let o=i.includes(m.extname(s)),h;if(p.platform!=="win32")if(o)e.unshift(s),e=v(p.execArgv).concat(e),h=E.spawn(p.argv[0],e,{stdio:"inherit"});else h=E.spawn(s,e,{stdio:"inherit"});else this._checkForMissingExecutable(s,r,t._name),e.unshift(s),e=v(p.execArgv).concat(e),h=E.spawn(p.execPath,e,{stdio:"inherit"});if(!h.killed)["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach((u)=>{p.on(u,()=>{if(h.killed===!1&&h.exitCode===null)h.kill(u)})});let l=this._exitCallback;h.on("close",(a)=>{if(a=a??1,!l)p.exit(a);else l(new f(a,"commander.executeSubCommandAsync","(close)"))}),h.on("error",(a)=>{if(a.code==="ENOENT")this._checkForMissingExecutable(s,r,t._name);else if(a.code==="EACCES")throw Error(`'${s}' not executable`);if(!l)p.exit(1);else{let u=new f(1,"commander.executeSubCommandAsync","(error)");u.nestedError=a,l(u)}}),this.runningCommand=h}_dispatchSubcommand(t,e,i){let n=this._findCommand(t);if(!n)this.help({error:!0});n._prepareForParse();let s;return s=this._chainOrCallSubCommandHook(s,n,"preSubcommand"),s=this._chainOrCall(s,()=>{if(n._executableHandler)this._executeSubCommand(n,e.concat(i));else return n._parseCommand(e,i)}),s}_dispatchHelpCommand(t){if(!t)this.help();let e=this._findCommand(t);if(e&&!e._executableHandler)e.help();return this._dispatchSubcommand(t,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){if(this.registeredArguments.forEach((t,e)=>{if(t.required&&this.args[e]==null)this.missingArgument(t.name())}),this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)return;if(this.args.length>this.registeredArguments.length)this._excessArguments(this.args)}_processArguments(){let t=(i,n,s)=>{let r=n;if(n!==null&&i.parseArg){let o=`error: command-argument value '${n}' is invalid for argument '${i.name()}'.`;r=this._callParseArg(i,n,s,o)}return r};this._checkNumberOfArguments();let e=[];this.registeredArguments.forEach((i,n)=>{let s=i.defaultValue;if(i.variadic){if(n<this.args.length){if(s=this.args.slice(n),i.parseArg)s=s.reduce((r,o)=>t(i,o,r),i.defaultValue)}else if(s===void 0)s=[]}else if(n<this.args.length){if(s=this.args[n],i.parseArg)s=t(i,s,i.defaultValue)}e[n]=s}),this.processedArgs=e}_chainOrCall(t,e){if(t?.then&&typeof t.then==="function")return t.then(()=>e());return e()}_chainOrCallHooks(t,e){let i=t,n=[];if(this._getCommandAndAncestors().reverse().filter((s)=>s._lifeCycleHooks[e]!==void 0).forEach((s)=>{s._lifeCycleHooks[e].forEach((r)=>{n.push({hookedCommand:s,callback:r})})}),e==="postAction")n.reverse();return n.forEach((s)=>{i=this._chainOrCall(i,()=>s.callback(s.hookedCommand,this))}),i}_chainOrCallSubCommandHook(t,e,i){let n=t;if(this._lifeCycleHooks[i]!==void 0)this._lifeCycleHooks[i].forEach((s)=>{n=this._chainOrCall(n,()=>s(this,e))});return n}_parseCommand(t,e){let i=this.parseOptions(e);if(this._parseOptionsEnv(),this._parseOptionsImplied(),t=t.concat(i.operands),e=i.unknown,this.args=t.concat(e),t&&this._findCommand(t[0]))return this._dispatchSubcommand(t[0],t.slice(1),e);if(this._getHelpCommand()&&t[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(t[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(e),this._dispatchSubcommand(this._defaultCommandName,t,e);if(this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName)this.help({error:!0});this._outputHelpIfRequested(i.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let n=()=>{if(i.unknown.length>0)this.unknownOption(i.unknown[0])},s=`command:${this.name()}`;if(this._actionHandler){n(),this._processArguments();let r;if(r=this._chainOrCallHooks(r,"preAction"),r=this._chainOrCall(r,()=>this._actionHandler(this.processedArgs)),this.parent)r=this._chainOrCall(r,()=>{this.parent.emit(s,t,e)});return r=this._chainOrCallHooks(r,"postAction"),r}if(this.parent?.listenerCount(s))n(),this._processArguments(),this.parent.emit(s,t,e);else if(t.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",t,e);if(this.listenerCount("command:*"))this.emit("command:*",t,e);else if(this.commands.length)this.unknownCommand();else n(),this._processArguments()}else if(this.commands.length)n(),this.help({error:!0});else n(),this._processArguments()}_findCommand(t){if(!t)return;return this.commands.find((e)=>e._name===t||e._aliases.includes(t))}_findOption(t){return this.options.find((e)=>e.is(t))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach((t)=>{t.options.forEach((e)=>{if(e.mandatory&&t.getOptionValue(e.attributeName())===void 0)t.missingMandatoryOptionValue(e)})})}_checkForConflictingLocalOptions(){let t=this.options.filter((i)=>{let n=i.attributeName();if(this.getOptionValue(n)===void 0)return!1;return this.getOptionValueSource(n)!=="default"});t.filter((i)=>i.conflictsWith.length>0).forEach((i)=>{let n=t.find((s)=>i.conflictsWith.includes(s.attributeName()));if(n)this._conflictingOption(i,n)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach((t)=>{t._checkForConflictingLocalOptions()})}parseOptions(t){let e=[],i=[],n=e;function s(a){return a.length>1&&a[0]==="-"}let r=(a)=>{if(!/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(a))return!1;return!this._getCommandAndAncestors().some((u)=>u.options.map((c)=>c.short).some((c)=>/^-\d$/.test(c)))},o=null,h=null,l=0;while(l<t.length||h){let a=h??t[l++];if(h=null,a==="--"){if(n===i)n.push(a);n.push(...t.slice(l));break}if(o&&(!s(a)||r(a))){this.emit(`option:${o.name()}`,a);continue}if(o=null,s(a)){let u=this._findOption(a);if(u){if(u.required){let c=t[l++];if(c===void 0)this.optionMissingArgument(u);this.emit(`option:${u.name()}`,c)}else if(u.optional){let c=null;if(l<t.length&&(!s(t[l])||r(t[l])))c=t[l++];this.emit(`option:${u.name()}`,c)}else this.emit(`option:${u.name()}`);o=u.variadic?u:null;continue}}if(a.length>2&&a[0]==="-"&&a[1]!=="-"){let u=this._findOption(`-${a[1]}`);if(u){if(u.required||u.optional&&this._combineFlagAndOptionalValue)this.emit(`option:${u.name()}`,a.slice(2));else this.emit(`option:${u.name()}`),h=`-${a.slice(2)}`;continue}}if(/^--[^=]+=/.test(a)){let u=a.indexOf("="),c=this._findOption(a.slice(0,u));if(c&&(c.required||c.optional)){this.emit(`option:${c.name()}`,a.slice(u+1));continue}}if(n===e&&s(a)&&!(this.commands.length===0&&r(a)))n=i;if((this._enablePositionalOptions||this._passThroughOptions)&&e.length===0&&i.length===0){if(this._findCommand(a)){e.push(a),i.push(...t.slice(l));break}else if(this._getHelpCommand()&&a===this._getHelpCommand().name()){e.push(a,...t.slice(l));break}else if(this._defaultCommandName){i.push(a,...t.slice(l));break}}if(this._passThroughOptions){n.push(a,...t.slice(l));break}n.push(a)}return{operands:e,unknown:i}}opts(){if(this._storeOptionsAsProperties){let t={},e=this.options.length;for(let i=0;i<e;i++){let n=this.options[i].attributeName();t[n]=n===this._versionOptionName?this._version:this[n]}return t}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((t,e)=>Object.assign(t,e.opts()),{})}error(t,e){if(this._outputConfiguration.outputError(`${t}
|
|
22
|
+
`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError==="string")this._outputConfiguration.writeErr(`${this._showHelpAfterError}
|
|
23
|
+
`);else if(this._showHelpAfterError)this._outputConfiguration.writeErr(`
|
|
24
|
+
`),this.outputHelp({error:!0});let i=e||{},n=i.exitCode||1,s=i.code||"commander.error";this._exit(n,s,t)}_parseOptionsEnv(){this.options.forEach((t)=>{if(t.envVar&&t.envVar in p.env){let e=t.attributeName();if(this.getOptionValue(e)===void 0||["default","config","env"].includes(this.getOptionValueSource(e)))if(t.required||t.optional)this.emit(`optionEnv:${t.name()}`,p.env[t.envVar]);else this.emit(`optionEnv:${t.name()}`)}})}_parseOptionsImplied(){let t=new y(this.options),e=(i)=>this.getOptionValue(i)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(i));this.options.filter((i)=>i.implied!==void 0&&e(i.attributeName())&&t.valueFromOption(this.getOptionValue(i.attributeName()),i)).forEach((i)=>{Object.keys(i.implied).filter((n)=>!e(n)).forEach((n)=>{this.setOptionValueWithSource(n,i.implied[n],"implied")})})}missingArgument(t){let e=`error: missing required argument '${t}'`;this.error(e,{code:"commander.missingArgument"})}optionMissingArgument(t){let e=`error: option '${t.flags}' argument missing`;this.error(e,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(t){let e=`error: required option '${t.flags}' not specified`;this.error(e,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(t,e){let i=(r)=>{let o=r.attributeName(),h=this.getOptionValue(o),l=this.options.find((u)=>u.negate&&o===u.attributeName()),a=this.options.find((u)=>!u.negate&&o===u.attributeName());if(l&&(l.presetArg===void 0&&h===!1||l.presetArg!==void 0&&h===l.presetArg))return l;return a||r},n=(r)=>{let o=i(r),h=o.attributeName();if(this.getOptionValueSource(h)==="env")return`environment variable '${o.envVar}'`;return`option '${o.flags}'`},s=`error: ${n(t)} cannot be used with ${n(e)}`;this.error(s,{code:"commander.conflictingOption"})}unknownOption(t){if(this._allowUnknownOption)return;let e="";if(t.startsWith("--")&&this._showSuggestionAfterError){let n=[],s=this;do{let r=s.createHelp().visibleOptions(s).filter((o)=>o.long).map((o)=>o.long);n=n.concat(r),s=s.parent}while(s&&!s._enablePositionalOptions);e=w(t,n)}let i=`error: unknown option '${t}'${e}`;this.error(i,{code:"commander.unknownOption"})}_excessArguments(t){if(this._allowExcessArguments)return;let e=this.registeredArguments.length,i=e===1?"":"s",n=t.length,s=this.parent?` for '${this.name()}'`:"",r=t.join(", "),o=`error: too many arguments${s}. Expected ${e} argument${i} but got ${n}: ${r}.`;this.error(o,{code:"commander.excessArguments"})}unknownCommand(){let t=this.args[0],e="";if(this._showSuggestionAfterError){let n=[];this.createHelp().visibleCommands(this).forEach((s)=>{if(n.push(s.name()),s.alias())n.push(s.alias())}),e=w(t,n)}let i=`error: unknown command '${t}'${e}`;this.error(i,{code:"commander.unknownCommand"})}version(t,e,i){if(t===void 0)return this._version;this._version=t,e=e||"-V, --version",i=i||"output the version number";let n=this.createOption(e,i);return this._versionOptionName=n.attributeName(),this._registerOption(n),this.on("option:"+n.name(),()=>{this._outputConfiguration.writeOut(`${t}
|
|
25
|
+
`),this._exit(0,"commander.version",t)}),this}description(t,e){if(t===void 0&&e===void 0)return this._description;if(this._description=t,e)this._argsDescription=e;return this}summary(t){if(t===void 0)return this._summary;return this._summary=t,this}alias(t){if(t===void 0)return this._aliases[0];let e=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler)e=this.commands[this.commands.length-1];if(t===e._name)throw Error("Command alias can't be the same as its name");let i=this.parent?._findCommand(t);if(i){let n=[i.name()].concat(i.aliases()).join("|");throw Error(`cannot add alias '${t}' to command '${this.name()}' as already have command '${n}'`)}return e._aliases.push(t),this}aliases(t){if(t===void 0)return this._aliases;return t.forEach((e)=>this.alias(e)),this}usage(t){if(t===void 0){if(this._usage)return this._usage;let e=this.registeredArguments.map((i)=>b(i));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?e:[]).join(" ")}return this._usage=t,this}name(t){if(t===void 0)return this._name;return this._name=t,this}helpGroup(t){if(t===void 0)return this._helpGroupHeading??"";return this._helpGroupHeading=t,this}commandsGroup(t){if(t===void 0)return this._defaultCommandGroup??"";return this._defaultCommandGroup=t,this}optionsGroup(t){if(t===void 0)return this._defaultOptionGroup??"";return this._defaultOptionGroup=t,this}_initOptionGroup(t){if(this._defaultOptionGroup&&!t.helpGroupHeading)t.helpGroup(this._defaultOptionGroup)}_initCommandGroup(t){if(this._defaultCommandGroup&&!t.helpGroup())t.helpGroup(this._defaultCommandGroup)}nameFromFilename(t){return this._name=m.basename(t,m.extname(t)),this}executableDir(t){if(t===void 0)return this._executableDir;return this._executableDir=t,this}helpInformation(t){let e=this.createHelp(),i=this._getOutputContext(t);e.prepareContext({error:i.error,helpWidth:i.helpWidth,outputHasColors:i.hasColors});let n=e.formatHelp(this,e);if(i.hasColors)return n;return this._outputConfiguration.stripColor(n)}_getOutputContext(t){t=t||{};let e=!!t.error,i,n,s;if(e)i=(o)=>this._outputConfiguration.writeErr(o),n=this._outputConfiguration.getErrHasColors(),s=this._outputConfiguration.getErrHelpWidth();else i=(o)=>this._outputConfiguration.writeOut(o),n=this._outputConfiguration.getOutHasColors(),s=this._outputConfiguration.getOutHelpWidth();return{error:e,write:(o)=>{if(!n)o=this._outputConfiguration.stripColor(o);return i(o)},hasColors:n,helpWidth:s}}outputHelp(t){let e;if(typeof t==="function")e=t,t=void 0;let i=this._getOutputContext(t),n={error:i.error,write:i.write,command:this};this._getCommandAndAncestors().reverse().forEach((r)=>r.emit("beforeAllHelp",n)),this.emit("beforeHelp",n);let s=this.helpInformation({error:i.error});if(e){if(s=e(s),typeof s!=="string"&&!Buffer.isBuffer(s))throw Error("outputHelp callback must return a string or a Buffer")}if(i.write(s),this._getHelpOption()?.long)this.emit(this._getHelpOption().long);this.emit("afterHelp",n),this._getCommandAndAncestors().forEach((r)=>r.emit("afterAllHelp",n))}helpOption(t,e){if(typeof t==="boolean"){if(t){if(this._helpOption===null)this._helpOption=void 0;if(this._defaultOptionGroup)this._initOptionGroup(this._getHelpOption())}else this._helpOption=null;return this}if(this._helpOption=this.createOption(t??"-h, --help",e??"display help for command"),t||e)this._initOptionGroup(this._helpOption);return this}_getHelpOption(){if(this._helpOption===void 0)this.helpOption(void 0,void 0);return this._helpOption}addHelpOption(t){return this._helpOption=t,this._initOptionGroup(t),this}help(t){this.outputHelp(t);let e=Number(p.exitCode??0);if(e===0&&t&&typeof t!=="function"&&t.error)e=1;this._exit(e,"commander.help","(outputHelp)")}addHelpText(t,e){let i=["beforeAll","before","after","afterAll"];if(!i.includes(t))throw Error(`Unexpected value for position to addHelpText.
|
|
26
|
+
Expecting one of '${i.join("', '")}'`);let n=`${t}Help`;return this.on(n,(s)=>{let r;if(typeof e==="function")r=e({error:s.error,command:s.command});else r=e;if(r)s.write(`${r}
|
|
27
|
+
`)}),this}_outputHelpIfRequested(t){let e=this._getHelpOption();if(e&&t.find((n)=>e.is(n)))this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)")}}function v(t){return t.map((e)=>{if(!e.startsWith("--inspect"))return e;let i,n="127.0.0.1",s="9229",r;if((r=e.match(/^(--inspect(-brk)?)$/))!==null)i=r[1];else if((r=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null)if(i=r[1],/^\d+$/.test(r[3]))s=r[3];else n=r[3];else if((r=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null)i=r[1],n=r[3],s=r[4];if(i&&s!=="0")return`${i}=${n}:${parseInt(s)+1}`;return e})}function V(){if(p.env.NO_COLOR||p.env.FORCE_COLOR==="0"||p.env.FORCE_COLOR==="false")return!1;if(p.env.FORCE_COLOR||p.env.CLICOLOR_FORCE!==void 0)return!0;return}var at=new $e;export{$e};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{r,E}from"./index-w0m3jm0s.js";import"./index-0qjbnyg4.js";import{Z}from"./index-ywnfz6nm.js";import"./index-kwhx023z.js";import{i,d,s,A,l,o,g,n,c,F}from"./index-7f2k4g6q.js";import"./index-vtsd74g0.js";import{Dt,xe,Fi}from"./index-b3v08awy.js";import"./index-4z1y39jt.js";import{_,y,u}from"./index-t5cfkz1e.js";import{f,m,S,Ce,Ae}from"./index-byerrz46.js";function R(C,t){if(C==="telemetry.enabled")Z.setEnabled(t==="true")}function P(C){return Object.entries(C).map(([t,e])=>({key:t,value:e}))}function j(C){let{db:t}=C;return new E().get("/",async()=>{let e=await t.getAllConfig(),p=Fi(e);return{config:p,configs:P(p)}}).get("/status",async()=>await t.getConfigStatus()).get("/:key",async({params:e,set:p})=>{let k=await t.getConfig(e.key);if(k===void 0)return p.status=404,{error:"Configuration key not found"};return{key:e.key,value:xe(e.key,k)}}).put("/:key",async({params:e,body:p,set:k})=>{if(Dt(e.key))return k.status=403,{error:"Configuration key is managed by a dedicated endpoint"};try{return await t.setConfig(e.key,p.value),R(e.key,p.value),{success:!0}}catch(a){return k.status=500,{error:"Failed to set configuration",details:String(a)}}},{body:r.Object({value:r.String()})}).delete("/:key",async({params:e,set:p})=>{if(Dt(e.key))return p.status=403,{error:"Configuration key is managed by a dedicated endpoint"};if(await t.getConfig(e.key)===void 0)return p.status=404,{error:"Configuration key not found"};try{return await t.deleteConfig(e.key),{success:!0}}catch(a){return p.status=500,{error:"Failed to delete configuration",details:String(a)}}}).post("/",async({body:e,set:p})=>{if(Dt(e.key))return p.status=403,{error:"Configuration key is managed by a dedicated endpoint"};try{return await t.setConfig(e.key,e.value),R(e.key,e.value),{success:!0,key:e.key}}catch(k){return p.status=500,{error:"Failed to set configuration",details:String(k)}}},{body:r.Object({key:r.String(),value:r.String()})}).post("/bulk",async({body:e,set:p})=>{let k=Object.keys(e.configs).filter(Dt);if(k.length>0)return p.status=403,{error:"One or more configuration keys are managed by dedicated endpoints",keys:k};try{await t.bulkSetConfig(e.configs);for(let[a,v]of Object.entries(e.configs))R(a,v);return{success:!0}}catch(a){return p.status=500,{error:"Failed to set configuration",details:String(a)}}},{body:r.Object({configs:r.Record(r.String(),r.String())})})}var x="http://localhost:3005";function h(C){C.command("config").description("Manage VibeControls agent configuration").option("--set <key=value>","Set a configuration value").option("--get <key>","Get a configuration value").option("--delete <key>","Delete a configuration value").option("--list","List all configuration values",!1).option("--value <value>","Value used with `--set <key>` (alternative to `--set key=value`)").option("--agent-url <url>","Agent URL",x).option("--json","Emit JSON").option("--plain","Force plain text output").action(async function(t){let e={...C.opts(),...t};try{let p=f(t),k=encodeURIComponent(m(e));if(t.set){let a=t.set.indexOf("="),v,b;if(a===-1){if(t.value===void 0){if(e.json){u(e,{ok:!1,error:"Invalid format: use key=value or --set key --value v"});return}s(`Invalid format. Use ${i.bold("--set key=value")} or ${i.bold("--set key --value value")}`);return}v=t.set.trim(),b=String(t.value).trim()}else v=t.set.slice(0,a).trim(),b=t.set.slice(a+1).trim();if(!v){if(e.json){u(e,{ok:!1,error:"Configuration key cannot be empty"});return}s("Configuration key cannot be empty.");return}if(await Ce(p,`/api/profiles/${k}/config/${encodeURIComponent(v)}`,{value:b}),u(e,{ok:!0,key:v}))return;l(`${d.success} Set ${i.bold(v)} = ${i.cyan(String(xe(v,b)))}`)}else if(t.get)await y({mode:_(e),fetchData:()=>S(p,`/api/profiles/${k}/config/${encodeURIComponent(t.get)}`),plain:(a)=>{g("Configuration"),c(),n(a.key,i.bold(String(xe(a.key,a.value)))),c()},json:(a)=>({key:a.key,value:xe(a.key,a.value)})});else if(t.delete){if(await Ae(p,`/api/profiles/${k}/config/${encodeURIComponent(t.delete)}`),u(e,{ok:!0,key:t.delete}))return;l(`${d.success} Deleted configuration key: ${i.bold(t.delete)}`)}else if(t.list)await y({mode:_(e),fetchData:()=>S(p,`/api/profiles/${k}/config/`),plain:(a)=>{if(g("Agent Configuration"),c(),!a.configs||a.configs.length===0){o(`${d.info} No configuration entries found.`);return}let v=a.configs.map((b)=>({Key:b.key,Value:String(xe(b.key,b.value))}));F(v),c(),o(`${d.info} ${a.configs.length} configuration(s) found.`)},json:(a)=>(a.configs??[]).map((v)=>({key:v.key,value:xe(v.key,v.value)}))});else{if(e.json){u(e,{ok:!1,error:"No operation specified"});return}o(`${d.info} Usage:`),o(` ${i.bold("vibe config --list")} List all config values`),o(` ${i.bold("vibe config --get <key>")} Get a config value`),o(` ${i.bold("vibe config --set <key=value>")} Set a config value`),o(` ${i.bold("vibe config --delete <key>")} Delete a config value`)}}catch(p){if(e.json){u(e,{ok:!1,error:A(p)});return}s(`Config operation failed: ${A(p)}`)}})}function w(C,t){h(C)}function J(C){return{name:"config",version:"2.2.0",description:"Agent configuration key-value store",capabilities:{storage:"rw",audit:!0},tags:["backend","cli"],cliCommand:"config",apiPrefix:"/api/config",createRoutes:(t)=>j(t),onCliSetup:async(t,e)=>{w(t,e)}}}export{J as createPlugin};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{lstatSync as b,readdirSync as d,readlinkSync as f,statSync as y,unlinkSync as h}from"fs";import{homedir as S}from"os";import{isAbsolute as p,join as i,resolve as g}from"path";function xr(u={}){let o=S(),r=u.binDir??i(o,".bun","bin"),n={scanned:0,removed:[]},s;try{s=d(r)}catch{return n}let a=i(o,".bun","install","global","node_modules","@vibecontrols");for(let m of s){let t=i(r,m),e;try{if(!b(t).isSymbolicLink())continue;n.scanned+=1,e=f(t)}catch{continue}let c=p(e)?e:g(r,e);if(!c.startsWith(a))continue;let l=!0;try{y(c)}catch{l=!1}if(l)continue;try{h(t),n.removed.push(t)}catch{}}return n}
|
|
3
|
+
export{xr};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{promises as u,closeSync as N,constants as k,fstatSync as D,lstatSync as W,openSync as B,readSync as Y,realpathSync as w,statSync as M}from"fs";import l from"os";import o from"path";function R(t,e){let r=parseInt(process.env[t]??"",10);return Number.isInteger(r)&&r>0?r:e}var E=R("VIBECONTROLS_MAX_FILE_READ_BYTES",10485760),g=R("VIBECONTROLS_MAX_DIRECTORY_ENTRIES",2000),_=[/(?:^|\/)\.env(?:\..*)?$/,/\.pem$/,/\.key$/,/(?:^|\/)id_rsa(?:$|\.)/,/(?:^|\/)\.ssh(?:\/|$)/,/(?:^|\/)\.git\/config$/,/(?:^|\/)\.npmrc$/],P=["/","/etc","/usr","/bin","/sbin","/var","/opt"],v=["C:\\Windows","C:\\Program Files","C:\\Program Files (x86)","C:\\ProgramData"];function x(){return process.platform==="win32"?v:P}function c(t){return process.platform==="win32"?t.toLowerCase():t}function I(){let t=process.env.VIBECONTROLS_ALLOWED_ROOTS;if(t)return t.split(o.delimiter).map((e)=>e.trim()).filter(Boolean);return[process.cwd(),l.homedir(),l.tmpdir()].filter(Boolean)}async function f(t){try{return await u.realpath(t)}catch{return null}}async function T(){let t=[];for(let e of I()){let r=o.resolve(e),s=await f(r)??r;if(!t.includes(s))t.push(s)}return t}function z(t,e){let r=o.relative(e,t);return r===""||!!r&&!r.startsWith("..")&&!o.isAbsolute(r)}async function h(t){if(!(await T()).some((r)=>z(t,r)))throw Error("Access denied: path is outside allowed directories")}async function A(t){let e=o.dirname(t);while(e&&e!==o.dirname(e)){let s=await f(e);if(s)return s;e=o.dirname(e)}let r=await f(e||o.parse(t).root);if(!r)throw Error("Path parent does not exist");return r}async function C(t){if((await u.lstat(o.resolve(t)).catch(()=>null))?.isSymbolicLink())throw Error("Access denied: symbolic links are not allowed")}function zt(t){return _.some((e)=>e.test(t))}function L(t){if(!t.startsWith("/"))return!1;let e=t.replace(/\\/g,"/").replace(/\/+/g,"/");return P.some((r)=>e===r||e.startsWith(r==="/"?"/":`${r}/`))}function Tr(t){let e=o.resolve(t),r=(()=>{try{return w(e)}catch{return null}})(),s=r?[e,r]:[e],n=l.tmpdir(),d=l.homedir(),S=(()=>{try{return w(n)}catch{return n}})(),b=(()=>{try{return w(d)}catch{return d}})(),y=o.sep,O=[n,S,d,b];for(let m of s){let i=c(m);if(O.some((p)=>{let a=c(p);return i===a||i.startsWith(a+y)}))return!1}if(s.some((m)=>{let i=c(m);return x().some((p)=>{let a=c(p);return i===a||i.startsWith(a+y)})}))return!0;return L(t)}async function oe(t,e={}){if(!t||t.includes("\x00"))throw Error("Invalid path");let r=o.resolve(t);await C(r);let s=await f(r);if(s)return await h(s),{path:r,realPath:s};if(e.mustExist)throw Error("Path not found");if(!e.forWrite)return await h(r),{path:r,realPath:r};let n=await A(r);return await h(n),{path:r,realPath:r}}async function di(t){let e=await u.stat(t);if(e.isFile()&&e.size>E)throw Error(`File is too large to read safely (${e.size} bytes, max ${E})`)}async function wt(t){let e=await u.opendir(t),r=[];try{for await(let s of e)if(r.push(s),r.length>g)throw Error(`Directory has too many entries (>${g})`)}finally{let s=e.close?.();if(s&&typeof s.catch==="function")await s.catch(()=>{return})}return r}
|
|
3
|
+
export{zt,Tr,oe,di,wt};
|