@vibecontrols/agent 2026.902.1 → 2026.1125.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-a95wetk5.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-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-4527yp1c.js +178 -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-75hk5q9s.js +13 -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-9xrhb68w.js +14 -0
- package/dist/index-a0vx2zyx.js +3 -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-ec08v08h.js +116 -0
- package/dist/index-g08z6z5v.js +5 -0
- package/dist/index-gaztfvyz.js +158 -0
- package/dist/index-gnb8xw13.js +83 -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-mmx2kp76.js +16 -0
- package/dist/index-ne8q0a64.js +26 -0
- package/dist/index-nzfqdhsx.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-v35k2y31.js +17 -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-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-zj50tg4k.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-vng5hdga.js +2 -0
- package/dist/secondary-profile-attach-pyqqf4ny.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-zwyzxrkt.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-g08z6z5v.js";import{Et,kt}from"./index-5021rk8n.js";import"./index-kwhx023z.js";import{Xt}from"./index-4527yp1c.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-gnb8xw13.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,k){try{let P=await fetch(`${fe()}/${c}/${k}`,{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}@${k}`,"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,k){let P=Buffer.from(c),t=Buffer.from(k);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})),H=new Map;function O(c,k){let t=(H.get(c)??Promise.resolve()).then(k,k),a=t.then(()=>{return},()=>{return});return H.set(c,a),a.finally(()=>{if(H.get(c)===a)H.delete(c)}),t}function X(c){return H.has(c)}function ee(c){let k=c.getPluginDetails(),P=new Set(k.map((t)=>t.packageName));return{plugins:ve.map((t)=>({...t,installed:P.has(t.packageName)}))}}function te(c){let{pluginManager:k}=c;return new E().get("/",()=>{let P=k.getPluginDetails();return{plugins:P,count:P.length}}).get("/available",()=>ee(k)).get("/catalog",()=>ee(k)).get("/contributions",({query:P})=>{let t=typeof P?.mountPoint==="string"&&P.mountPoint?P.mountPoint:null,a=[],d=new Map;for(let b of k.getPluginDetails())d.set(b.pluginName,b.packageName);for(let b of k.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,R=h&&typeof h.url==="string"?h.url:null,I=R&&R.startsWith("/")&&!R.startsWith("//")&&!R.includes("\x00")&&!R.includes("..")?R:null;a.push({pluginKey:b.name,pluginPackageName:d.get(b.name),contribution:w,capabilities:w.capabilities??v,url:I??`/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(k.getAllPlugins().some((N)=>N.name===d))return{success:!0,message:`Plugin ${a} is already installed`,packageName:a,alreadyInstalled:!0};return t.status=409,{error:"Install for this package is already in progress. Wait for it to finish.",packageName:a}}return await O(a,async()=>{let d=a.split("/").pop()?.replace("vibe-plugin-",""),b=d?.startsWith("ai-")?d.slice(3):void 0,N=k.getAllPlugins().find((C)=>C.name===d||C.name===b),v=!!N,w=await k.install(a),h=wi(a);if(h?.integrity){let C=await Y(a,w.version);if(C&&!Z(h.integrity,C)){try{await k.remove(a,c.hostServices)}catch(x){console.warn(`[plugin-mgr] integrity rollback uninstall failed for ${a}:`,x)}return e().audit.emit("agent","plugin.install.rejected",{packageName:a,version: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 R=k.getAllPlugins().find((C)=>C.name===w.pluginName);if(R){let C=[];if(c.mountPlugin)c.mountPlugin(R);if(c.hostServices){if(v&&N?.onServerStop)try{await N.onServerStop()}catch(L){C.push(`onServerStop failed: ${L instanceof Error?L.message:String(L)}`)}k.registerProviders(R,c.hostServices);let x=k.hostServicesFor(R,c.hostServices);if(R.onServerStart&&c.app)try{await R.onServerStart(c.app,x),k.registerProviders(R,c.hostServices)}catch(L){C.push(`onServerStart failed: ${L instanceof Error?L.message:String(L)}`)}if(R.onServerReady&&c.app)try{await R.onServerReady(c.app,x)}catch(L){C.push(`onServerReady failed: ${L instanceof Error?L.message:String(L)}`)}}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 I;if(R&&c.app)try{I=await xt(R,a,c.app,c.db,{skipInstall:!!P.skipPrereqs})}catch(C){I=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:I?{satisfied:I.satisfied,missing:I.status?.missing??[],pendingSudo:I.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=k.getAllPlugins().find((b)=>b.name===a||k.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=k.getAllPlugins().find((b)=>b.name===a||k.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=k.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 k.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 O(a,async()=>(await k.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 O(d,async()=>{let b=k.getLoaded(d);if(b?.onServerStop)await b.onServerStop({reason:"reload"});if(b&&c.hostServices)c.hostServices.serviceRegistry.unregisterPlugin(b.name);let N=await k.update(d,a),v=k.getLoaded(d);if(v&&c.hostServices){k.registerProviders(v,c.hostServices);let w=k.hostServicesFor(v,c.hostServices);if(v.onServerStart&&c.app)await v.onServerStart(c.app,w),k.registerProviders(v,c.hostServices);if(v.onServerReady&&c.app)await v.onServerReady(c.app,w)}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 O("*",()=>k.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 O("*",async()=>{let a=await k.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 O("*",async()=>(await k.reloadAll(c.app,c.hostServices),c.rebuildPluginSurfaces?.(),k.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=k.getAllPlugins().find((v)=>v.name===a);if(!d)return t.status=404,{error:`Plugin "${a}" not found`};let N=k.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 O(N,async()=>{if(d.onServerStop)try{await d.onServerStop({reason:"reload"})}catch(w){console.warn(`[plugin-mgr] onServerStop during reload of ${a}:`,w)}if(c.hostServices)c.hostServices.serviceRegistry.unregisterPlugin(d.name);k.registerProviders(d,c.hostServices);let v=k.hostServicesFor(d,c.hostServices);if(d.onServerStart)await d.onServerStart(c.app,v),k.registerProviders(d,c.hostServices);if(d.onServerReady)await d.onServerReady(c.app,v);return c.rebuildPluginSurfaces?.(),{success:!0,message:`Plugin ${a} reloaded`,version:d.version}})}catch(v){return t.status=500,{error:"Failed to reload plugin",details:String(v)}}},{params:r.Object({name:r.String()})})}import{mkdirSync as W,writeFileSync as M,existsSync as ne}from"fs";import{isAbsolute as ye,join as j,relative as he,resolve as G}from"path";var D="http://localhost:3005",be=/^[a-z0-9][a-z0-9-]{0,63}$/,Se=new Set(["backend","frontend","cli","provider","adapter","integration"]);function ie(c,k){let P=he(c,k);if(P.startsWith("..")||ye(P))throw Error("Plugin scaffold path escapes the selected directory.")}function T(c){return JSON.stringify(c)}function re(c){let k=c.command("plugin").description("Manage plugins");k.command("list").description("List installed plugins").option("--agent-url <url>","Agent URL",D).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-zj50tg4k.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((R)=>({Name:w(R),Version:R.version||"-",Status:v(R),Description:R.description||"-"})))},interactive:async(h)=>{if(!h.length){g("Installed Plugins"),o("No plugins installed.");return}let R=h.map((I)=>{let C=w(I),x=v(I),L=[`${i.bold(C)} ${x==="enabled"?i.green(x):i.dim(x)}`,"",` Version: ${I.version||"-"}`,` Description: ${I.description||"-"}`];if(I.tags&&Array.isArray(I.tags))L.push(` Tags: ${I.tags.join(", ")}`);if(I.cliCommand)L.push(` CLI command: vibe ${I.cliCommand}`);return{id:C,label:C,hint:x,detail:L.join(`
|
|
3
|
+
`)}});await Q({title:`vibe plugin \u2014 ${h.length} installed`,rows:R,footer:"\u2191/\u2193 navigate \xB7 q to quit"})},json:(h)=>h.map((R)=>({name:w(R),version:R.version??null,status:v(R),description:R.description??null,tags:R.tags??null,cliCommand:R.cliCommand??null}))})}catch(a){s(A(a))}}),k.command("install").description("Install a plugin").argument("<package>","NPM package name to install").option("--agent-url <url>","Agent URL",D).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-zj50tg4k.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))}}),k.command("remove").description("Remove a plugin").argument("<package>","NPM package name to remove").option("--agent-url <url>","Agent URL",D).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-zj50tg4k.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))}}),k.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",D).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-zj50tg4k.js"),h=await new v().updateAll();if(u(d,{ok:!0,action:"update-all",results:h,local:!0}))return;for(let R of h)if(R.success)l(`Updated ${R.packageName}${R.version?` to v${R.version}`:""}`);else p(`Failed to update ${R.packageName}: ${R.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-zj50tg4k.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))}}),k.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",D).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-zj50tg4k.js"),h=await new v().removeAll();if(u(d,{ok:!0,action:"uninstall-all",results:h,local:!0}))return;for(let R of h)if(R.success)l(`Removed ${R.packageName}`);else p(`Failed to remove ${R.packageName}: ${R.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-zj50tg4k.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))}}),k.command("reload").description("Reload all plugins").option("--agent-url <url>","Agent URL",D).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))}}),k.command("available").description("Show available plugins").option("--agent-url <url>","Agent URL",D).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((R)=>({Name:v(R),Version:w(R),Description:R.description||"-"})))},interactive:async(h)=>{if(!h||h.length===0){g("Available Plugins"),o("No available plugins found.");return}let R=h.map((I)=>{let C=v(I),x=[i.bold(C),"",` Version: ${w(I)}`,` Description: ${I.description||"-"}`];return{id:C,label:C,hint:w(I),detail:x.join(`
|
|
4
|
+
`)}});await Q({title:`vibe plugin available \u2014 ${h.length} plugin(s)`,rows:R,footer:"\u2191/\u2193 navigate \xB7 q to quit"})},json:(h)=>h.map((R)=>({name:v(R),version:w(R),description:R.description??null}))})}catch(a){s(A(a))}});let P=k.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",D).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((R)=>R.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",D).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",D).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)}`)}}),k.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=G(a.dir),h=G(w,v);if(ie(w,h),ne(h)){s(`Directory "${h}" already exists.`);return}o(`Scaffolding ${v}...`),W(j(h,"src"),{recursive:!0}),W(j(h,"dist"),{recursive:!0});let R=`VibeControls plugin: ${b}`,I={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:R,devDependencies:{"@types/bun":"^1.2.16","bun-types":"^1.3.9",commander:"^14.0.3",eslint:"^9.30.1",prettier:"^3.6.2",rimraf:"^6.0.1",typescript:"^5.8.3","typescript-eslint":"^8.56.0"},peerDependencies:{"@vibecontrols/agent":">=2.0.0"},peerDependenciesMeta:{"@vibecontrols/agent":{optional:!0}},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},files:["dist/**/*","README.md","LICENSE"]};M(j(h,"package.json"),JSON.stringify(I,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"]};M(j(h,"tsconfig.json"),JSON.stringify(C,null,2)+`
|
|
7
|
+
`),M(j(h,".gitignore"),["node_modules/","dist/","bun.lock",".env",".env.local","*.tgz"].join(`
|
|
8
|
+
`)+`
|
|
9
|
+
`);let x=b,L=T(v),K=T(R),se=T(N),z=T(x),oe=`import type { Command } from "commander";
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* @vibecontrols/${v}
|
|
13
|
+
*
|
|
14
|
+
* ${R}
|
|
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: ${L},
|
|
44
|
+
version: "0.1.0",
|
|
45
|
+
description: ${K},
|
|
46
|
+
tags: [${se}],
|
|
47
|
+
cliCommand: ${z},
|
|
48
|
+
|
|
49
|
+
onCliSetup(program: Command, _hostServices?: HostServices): void {
|
|
50
|
+
const cmd = program
|
|
51
|
+
.command(${z})
|
|
52
|
+
.description(${K});
|
|
53
|
+
|
|
54
|
+
cmd
|
|
55
|
+
.command("status")
|
|
56
|
+
.description(`+T(`Show ${b} status`)+`)
|
|
57
|
+
.action(() => {
|
|
58
|
+
console.log(`+T(`${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
|
+
`;M(j(h,"src","index.ts"),oe);let ce=`# ${v}
|
|
77
|
+
|
|
78
|
+
${R}
|
|
79
|
+
|
|
80
|
+
## Installation
|
|
81
|
+
|
|
82
|
+
\`\`\`bash
|
|
83
|
+
vibe plugin install @vibecontrols/${v}
|
|
84
|
+
\`\`\`
|
|
85
|
+
|
|
86
|
+
## Usage
|
|
87
|
+
|
|
88
|
+
\`\`\`bash
|
|
89
|
+
vibe ${x} status
|
|
90
|
+
vibe ${x} 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
|
+
`;M(j(h,"README.md"),ce);let V={ok:!0,action:"create",plugin:v,packageName:`@vibecontrols/${v}`,cliCommand:x,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 ${x}`),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=G(w,B);if(ie(w,J),ne(J)){if(!d.json)p(`UI directory "${J}" already exists, skipping.`);V.uiSkipped=!0,V.uiDir=J}else{W(j(J,"src"),{recursive:!0}),W(j(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"]};M(j(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
|
+
`;M(j(J,"src","main.tsx"),ge);let pe=`import { useState, useEffect } from "react";
|
|
119
|
+
|
|
120
|
+
const TITLE = ${T(`${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
|
+
`;M(j(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(M(j(J,"index.html"),de),!d.json)l(`Created UI plugin ${B} at ${J}`);V.uiPluginName=B,V.uiPackageName=`@vibecontrols/${B}`,V.uiDir=J}}u(d,V)}catch(d){s(A(d))}})}function ae(c,k){re(c)}function Fe(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:(k)=>te(k),onCliSetup:async(k,P)=>{ae(k,P)}}}export{Fe as createPlugin};
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{e}from"./index-0qjbnyg4.js";import{E}from"./index-w0m3jm0s.js";import{Mr}from"./index-g08z6z5v.js";import{Ke,Lt,de,mt,Xe,ze,K}from"./index-mmx2kp76.js";var T=["tunnel","session","ai","plan","gitops","security","desk"];class Te{providers=new Map;providerOrder=new Map;defaults=new Map;services=new Map;db;constructor(t){this.db=t}getDb(){return this.db}setProviderDefault(t,r){this.defaults.set(t,r)}clearProviderDefault(t,r){if(!r||this.defaults.get(t)===r)this.defaults.delete(t)}async hydrateDefaultsFromDb(){if(!this.db)return;for(let t of T)try{let r=await this.db.getConfig(`provider:default:${t}`);if(r)this.defaults.set(t,r)}catch{}}registerProvider(t,r,i){if(!this.providers.has(t))this.providers.set(t,new Map),this.providerOrder.set(t,[]);let n=this.providers.get(t),o=this.providerOrder.get(t);if(n.has(i))e().logger.info("service-registry",`Updating ${t} provider from plugin '${i}'`);else e().logger.info("service-registry",`Registered ${t} provider from plugin '${i}'`);if(n.set(i,{provider:r,pluginName:i,registeredAt:new Date}),!o.includes(i))o.push(i)}getProvider(t){let r=this.providers.get(t);if(!r||r.size===0)return;let i=this.defaults.get(t);if(i&&r.has(i))return r.get(i).provider;let n=this.providerOrder.get(t);if(n&&n.length>0){let o=n[0];return r.get(o)?.provider}return}getProviderByName(t,r){let i=this.providers.get(t);if(!i)return;return i.get(r)?.provider}hasProvider(t){let r=this.providers.get(t);return!!r&&r.size>0}unregisterProvider(t,r){let i=this.providers.get(t);if(!i)return!1;let n=i.delete(r);if(n){let o=this.providerOrder.get(t);if(o){let s=o.indexOf(r);if(s!==-1)o.splice(s,1)}this.clearProviderDefault(t,r),e().logger.info("service-registry",`Unregistered ${t} provider from plugin '${r}'`)}return n}unregisterPlugin(t){for(let r of T)this.unregisterProvider(r,t);this.unregisterServices(t)}listProvidersForType(t){let r=this.providers.get(t);if(!r)return[];let i=this.defaults.get(t);if(!i||!r.has(i)){let n=this.providerOrder.get(t);i=n&&n.length>0?n[0]:void 0}return Array.from(r.keys()).map((n)=>({pluginName:n,isDefault:n===i}))}registerService(t,r,i){let n=`${t}:${r}`;this.services.set(n,{service:i,pluginName:t}),e().logger.debug("service-registry",`Registered service '${n}'`)}getService(t,r){let i=`${t}:${r}`;return this.services.get(i)?.service}unregisterServices(t){let r=[];for(let[i,n]of this.services)if(n.pluginName===t)r.push(i);for(let i of r)this.services.delete(i);if(r.length>0)e().logger.info("service-registry",`Unregistered ${r.length} services from ${t}`)}listProviders(){let t=[];for(let[r,i]of this.providers)for(let[n,o]of i)t.push({type:r,name:n,pluginName:o.pluginName});return t}listServices(){return Array.from(this.services.entries()).map(([t,r])=>({pluginName:r.pluginName,serviceName:t.split(":").slice(1).join(":")}))}clear(){this.providers.clear(),this.providerOrder.clear(),this.defaults.clear(),this.services.clear()}}class Ee{statusSections=[];doctorChecks=[];addStatusSection(t){this.statusSections.push(t)}addDoctorCheck(t){this.doctorChecks.push(t)}getStatusSections(){return this.statusSections}getDoctorChecks(){return this.doctorChecks}}var y=null;function Ti(t){y=t}function Pt(){if(!y)y=new Ee;return y}import{extname as N,relative as j,resolve as O}from"path";import{realpath as b}from"fs/promises";var B=["'self'","http://localhost:*","http://127.0.0.1:*","https://localhost:*","https://127.0.0.1:*","https://*.local.burdenoff.com","https://vibecontrols.com","https://*.vibecontrols.com","https://burdenoff.com","https://app.burdenoff.com","https://alphaapp.burdenoff.com"],R=!1;function f(){let t=process.env.VIBE_UI_FRAME_ANCESTORS?.trim(),r=t?t.split(/[\s,]+/).filter(Boolean):B;if(t&&!R&&(r.includes("*")||!r.includes("'self'")))R=!0,console.warn(`[ui-server] VIBE_UI_FRAME_ANCESTORS override does not include "'self'" or contains "*". This significantly weakens CSP frame-ancestors and is almost never intended. Override: ${t}`);return`frame-ancestors ${r.join(" ")}`}var M={".html":"text/html",".js":"application/javascript",".mjs":"application/javascript",".css":"text/css",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".map":"application/json",".wasm":"application/wasm"};function F(t){return M[N(t).toLowerCase()]||"application/octet-stream"}var k=`<script>
|
|
3
|
+
window.__VIBE_AUTH__={apiKey:null};
|
|
4
|
+
(function(){
|
|
5
|
+
var p=new URLSearchParams(window.location.search);
|
|
6
|
+
if(p.get('apiKey'))window.__VIBE_AUTH__.apiKey=p.get('apiKey');
|
|
7
|
+
function allowedOrigin(origin){
|
|
8
|
+
try{
|
|
9
|
+
var u=new URL(origin);
|
|
10
|
+
return u.hostname==='localhost'||u.hostname==='127.0.0.1'||u.hostname.endsWith('.local.burdenoff.com')||u.hostname==='vibecontrols.com'||u.hostname.endsWith('.vibecontrols.com')||u.hostname==='burdenoff.com'||u.hostname==='app.burdenoff.com'||u.hostname==='alphaapp.burdenoff.com';
|
|
11
|
+
}catch(e){return false;}
|
|
12
|
+
}
|
|
13
|
+
window.addEventListener('message',function(e){
|
|
14
|
+
if(!allowedOrigin(e.origin))return;
|
|
15
|
+
if(e.data&&e.data.type==='vibe-auth'&&e.data.apiKey){
|
|
16
|
+
window.__VIBE_AUTH__.apiKey=e.data.apiKey;
|
|
17
|
+
window.dispatchEvent(new CustomEvent('vibe-auth-ready'));
|
|
18
|
+
}
|
|
19
|
+
});
|
|
20
|
+
})();
|
|
21
|
+
</script>`;function p(t){if(!t.headers.has("Content-Security-Policy"))t.headers.set("Content-Security-Policy",f());return t}function U(t){if(t.includes("</head>"))return t.replace("</head>",k+"</head>");if(t.includes("</body>"))return t.replace("</body>",k+"</body>");return t+k}function S(t){return t.replace(/[&<>"']/g,(r)=>{switch(r){case"&":return"&";case"<":return"<";case">":return">";case'"':return""";case"'":return"'";default:return r}})}function A(t,r){let i=j(t,r);return i===""||!!i&&!i.startsWith("..")&&!i.startsWith("/")}async function D(t,r,i){let n=Mr(t);if(!n)return null;let o=await b(n),s=await b(r);if(!A(o,s))return null;let a=O(s,i),w=await b(a).catch(()=>a);if(!A(s,w))return null;return a}function L(t){return!1}function Br(t,r="/api/profiles/default/agent/ui-exchange"){let i=t.replace(/\\/g,"\\\\").replace(/'/g,"\\'"),n=r.replace(/\\/g,"\\\\").replace(/'/g,"\\'");return`<!doctype html>
|
|
22
|
+
<html>
|
|
23
|
+
<head>
|
|
24
|
+
<meta charset="utf-8">
|
|
25
|
+
<title>Loading plugin\u2026</title>
|
|
26
|
+
<style>
|
|
27
|
+
body { font: 14px/1.4 system-ui, -apple-system, sans-serif; color: #ccc; background: #111; padding: 2rem; }
|
|
28
|
+
.err { color: #f88; }
|
|
29
|
+
</style>
|
|
30
|
+
</head>
|
|
31
|
+
<body>
|
|
32
|
+
<p id="status">Loading plugin\u2026</p>
|
|
33
|
+
<script>
|
|
34
|
+
(async () => {
|
|
35
|
+
const PLUGIN = '${i}';
|
|
36
|
+
const EXCHANGE = '${n}';
|
|
37
|
+
const statusEl = document.getElementById('status');
|
|
38
|
+
function fail(msg) {
|
|
39
|
+
statusEl.textContent = msg;
|
|
40
|
+
statusEl.className = 'err';
|
|
41
|
+
}
|
|
42
|
+
const m = location.hash.match(/[#&]vt=([^&]+)/);
|
|
43
|
+
if (!m) { fail('Missing plugin token'); return; }
|
|
44
|
+
const token = decodeURIComponent(m[1]);
|
|
45
|
+
let r;
|
|
46
|
+
try {
|
|
47
|
+
r = await fetch(EXCHANGE, {
|
|
48
|
+
method: 'POST',
|
|
49
|
+
headers: { 'content-type': 'application/json' },
|
|
50
|
+
credentials: 'include',
|
|
51
|
+
body: JSON.stringify({ plugin: PLUGIN, token: token })
|
|
52
|
+
});
|
|
53
|
+
} catch (e) {
|
|
54
|
+
fail('Plugin authentication failed: network error');
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
if (!r.ok) { fail('Plugin authentication failed'); return; }
|
|
58
|
+
const url = new URL(location.href);
|
|
59
|
+
url.hash = '';
|
|
60
|
+
location.replace(url.toString());
|
|
61
|
+
})();
|
|
62
|
+
</script>
|
|
63
|
+
</body>
|
|
64
|
+
</html>`}function V(t){let r=t.map((i)=>{let n=(i.tags||[]).map((a)=>`<span class="tag">${S(a)}</span>`).join(" "),o=encodeURIComponent(i.name),s=S(i.title||i.name);return`<li><a href="/ui/${o}">${s}</a> ${n}</li>`}).join(`
|
|
65
|
+
`);return`<!DOCTYPE html>
|
|
66
|
+
<html lang="en">
|
|
67
|
+
<head>
|
|
68
|
+
<meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
|
69
|
+
<title>VibeControls - Plugin UIs</title>
|
|
70
|
+
<style>
|
|
71
|
+
body{font-family:system-ui,-apple-system,sans-serif;max-width:800px;margin:2rem auto;padding:0 1rem;background:#0a0a0a;color:#e0e0e0}
|
|
72
|
+
h1{color:#fff}a{color:#60a5fa;text-decoration:none}a:hover{text-decoration:underline}
|
|
73
|
+
ul{list-style:none;padding:0}li{padding:0.75rem 1rem;border:1px solid #333;border-radius:8px;margin-bottom:0.5rem;display:flex;align-items:center;gap:0.5rem}
|
|
74
|
+
.tag{font-size:0.75rem;padding:2px 8px;border-radius:4px;background:#1e3a5f;color:#93c5fd}
|
|
75
|
+
.empty{color:#888;font-style:italic}
|
|
76
|
+
</style>
|
|
77
|
+
</head>
|
|
78
|
+
<body>
|
|
79
|
+
<h1>VibeControls Plugin UIs</h1>
|
|
80
|
+
${t.length>0?`<ul>${r}</ul>`:'<p class="empty">No plugins with UIs installed.</p>'}
|
|
81
|
+
</body>
|
|
82
|
+
</html>`}function xi(t){return new E({prefix:"/ui"}).onAfterHandle(({set:r})=>{r.headers["Content-Security-Policy"]=f()}).get("/",()=>{let r=t.getAllPlugins().filter((i)=>i.ui).map((i)=>({name:i.name,title:i.ui?.title??i.name,tags:i.tags}));return p(new Response(V(r),{headers:{"Content-Type":"text/html; charset=utf-8"}}))}).get("/*",async({params:r,request:i,set:n})=>{let s=(r["*"]||"").split("/").filter(Boolean);if(s.length===0)return n.status=404,{error:"Plugin not specified"};let a=s[0];if(!de(a))return n.status=404,{error:`Invalid plugin name '${a}'`};let w=s.length===1||s.length===2&&!s[1],C=i.headers.get("sec-fetch-mode"),I=w&&(C==="navigate"||C===null),x=ze(i,a);if(!(!!x&&Xe(x,a))){if(I)return n.status=200,n.headers["content-type"]="text/html; charset=utf-8",n.headers["Content-Security-Policy"]=f(),Br(a);return n.status=401,{error:"Unauthorized: UI plugin cookie required"}}let c=t.getPluginByKey(a),P=s.slice(1).join("/");if(c&&s.length>=2){let l=t.getPluginByKey(s[1]);if(l?.ui)c=l,P=s.slice(2).join("/")}if(!c?.ui)return n.status=404,{error:`No UI available for plugin '${a}'`};if(c.ui.devUrl){if(!L(c.ui.devUrl))return n.status=403,{error:"Plugin UI dev proxy is disabled for this URL"};try{let l=new URL(c.ui.devUrl);l.pathname=`/${P}`.replace(/\/+/g,"/");let h=await fetch(l,{redirect:"manual"}),u=await h.arrayBuffer(),d=new Headers;return h.headers.forEach((m,g)=>d.set(g,m)),p(new Response(u,{status:h.status,headers:d}))}catch{return n.status=502,{error:`Failed to proxy to dev server at ${c.ui.devUrl}`}}}if(c.ui.staticDir){let l=c.ui.staticDir,u=await D(c,l,P||"index.html");if(!u)return n.status=403,{error:"Access denied"};let d=Bun.file(u);if(await d.exists()){let v=F(u);if(v==="text/html"){let _=await d.text();return p(new Response(U(_),{headers:{"Content-Type":"text/html; charset=utf-8"}}))}return p(new Response(d,{headers:{"Content-Type":v}}))}let m=await D(c,l,"index.html"),g=m?Bun.file(m):null;if(g&&await g.exists()){let v=await g.text();return p(new Response(U(v),{headers:{"Content-Type":"text/html; charset=utf-8"}}))}return n.status=404,{error:"File not found"}}return n.status=404,{error:"No UI configuration (neither staticDir nor devUrl)"}})}function ke(){return{getAgentApiKey:()=>K(),verifyIframeToken:(t,r)=>Ke(t,r),verifyUiCookieToken:(t,r)=>Xe(t,r),issueUiCookieToken:(t,r)=>{let i=mt(t,r);return{token:i.token,expiresAt:Date.parse(i.expiresAt)}},getIframeTokenFromRequest:(t,r)=>Lt(t,r),getUiCookieFromRequest:(t,r)=>ze(t,r),isValidUiPluginName:(t)=>de(t),frameAncestorsCsp:()=>f()}}
|
|
83
|
+
export{Te,Ee,Ti,Pt,Br,xi,ke};
|
|
@@ -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};
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{ue,R,I,C,e}from"./index-0qjbnyg4.js";import{existsSync as d,mkdirSync as O,readdirSync as Zt,readFileSync as h,renameSync as x,rmSync as te,writeFileSync as S}from"fs";import{dirname as B,join as L}from"path";import{randomUUID as ee}from"crypto";import{existsSync as k,mkdirSync as K,readFileSync as gt,renameSync as ut,unlinkSync as vt,writeFileSync as _}from"fs";import{dirname as W,join as f}from"path";import{spawnSync as Q}from"child_process";import{hostname as Ut,networkInterfaces as Ct,platform as dt,userInfo as Rt}from"os";import{createCipheriv as Ot,createDecipheriv as xt,pbkdf2Sync as Bt,randomBytes as Lt}from"crypto";var nt="secrets:fallback",ft="secrets:index",rt=10,Tt=100,it=new Map;function pt(t,n){let r=`${t}:${n}`,i=(it.get(r)??0)+1;if(it.set(r,i),i<=rt)return!0;return(i-rt)%Tt===0}var v="vibecontrols-agent",wt=".libsecret-install-attempted",mt="secrets.json";function Nt(){return globalThis.Bun?.secrets??null}class j{api;kind="bun-secrets";constructor(t){this.api=t}async get(t){return this.api.get({service:v,name:t})}async set(t,n){await this.api.set({service:v,name:t,value:n}),await Yt(t)}async delete(t){let n=await this.api.delete({service:v,name:t});return await qt(t),n}async list(t){return zt(t)}}var ht=".secrets-encrypted-v1",Vt=1e5,Dt=32,Ft="sha256",P=null,st=null;function Mt(){let t=Ct();for(let n of Object.values(t)){if(!n)continue;for(let r of n){let i=r?.mac;if(i&&i!=="00:00:00:00:00:00")return i}}return"no-mac"}function ot(){if(st!==null)return st;let t;try{t=Rt().username||"unknown"}catch{t=process.env.USER||process.env.USERNAME||"unknown"}return`${Ut()}|${t}|${Mt()}`}function kt(){if(P)return P;let t=`vibecontrols-agent::${ot()}`;return P=Bt(t,ot(),Vt,Dt,Ft),P}function at(t){let n=Lt(12),r=Ot("aes-256-gcm",kt(),n),i=Buffer.concat([r.update(t,"utf8"),r.final()]),s=r.getAuthTag();return`${n.toString("hex")}:${s.toString("hex")}:${i.toString("hex")}`}function Wt(t){let n=t.split(":");if(n.length!==3)return!1;let[r,i,s]=n;return/^[0-9a-f]+$/i.test(r)&&r.length===24&&/^[0-9a-f]+$/i.test(i)&&i.length===32&&/^[0-9a-f]*$/i.test(s)}function Kt(t){if(!Wt(t))return null;try{let[n,r,i]=t.split(":"),s=xt("aes-256-gcm",kt(),Buffer.from(n,"hex"));return s.setAuthTag(Buffer.from(r,"hex")),Buffer.concat([s.update(Buffer.from(i,"hex")),s.final()]).toString("utf8")}catch{return null}}class It{kind="json-fallback";path;constructor(){this.path=f(C(),mt)}async get(t){let{plain:n}=this.readWithMigration(),r=n[t];return typeof r==="string"?r:null}async set(t,n){await ue(nt,async()=>{let{encrypted:r}=this.readWithMigration();r[t]=at(n),this.writeEncrypted(r)})}async delete(t){return ue(nt,async()=>{let{encrypted:n}=this.readWithMigration();if(!(t in n))return!1;return delete n[t],this.writeEncrypted(n),!0})}async list(t){let{encrypted:n}=this.readWithMigration(),r=Object.keys(n);return(t?r.filter((s)=>s.startsWith(t)):r).sort().map((s)=>({name:s}))}readWithMigration(){if(!k(this.path))return{encrypted:{},plain:{}};let t;try{t=gt(this.path,"utf8")}catch{return{encrypted:{},plain:{}}}let n;try{n=JSON.parse(t)}catch{return{encrypted:{},plain:{}}}if(!n||typeof n!=="object"||Array.isArray(n))return{encrypted:{},plain:{}};let r={},i={},s=!1;for(let[o,a]of Object.entries(n)){if(typeof a!=="string")continue;let g=Kt(a);if(g!==null){r[o]=a,i[o]=g;continue}r[o]=at(a),i[o]=a,s=!0}if(s)try{this.writeEncrypted(r),this.writeMarker()}catch{}return{encrypted:r,plain:i}}writeEncrypted(t){K(W(this.path),{recursive:!0});let n=`${this.path}.${process.pid}.tmp`;if(_(n,`${JSON.stringify(t,null,2)}
|
|
3
|
+
`,{mode:384}),ut(n,this.path),!k(this.markerPath()))this.writeMarker()}markerPath(){return f(W(this.path),ht)}writeMarker(){try{_(this.markerPath(),`${new Date().toISOString()}
|
|
4
|
+
`,{mode:384})}catch{}}}var Jt=".secrets-index.json";function Y(){return f(C(),Jt)}function q(){let t=Y();if(!k(t))return new Set;try{let n=gt(t,"utf8"),r=JSON.parse(n);if(Array.isArray(r))return new Set(r.filter((i)=>typeof i==="string"))}catch{}return new Set}function At(t){let n=Y();K(W(n),{recursive:!0});let r=`${n}.${process.pid}.tmp`;_(r,`${JSON.stringify([...t].sort(),null,2)}
|
|
5
|
+
`,{mode:384}),ut(r,n)}async function Yt(t){await ue(ft,()=>{let n=q();if(n.has(t))return;n.add(t),At(n)})}async function qt(t){await ue(ft,()=>{let n=q();if(!n.delete(t))return;At(n)})}function zt(t){let r=[...q()];return(t?r.filter((s)=>s.startsWith(t)):r).sort().map((s)=>({name:s}))}function Ht(){if(dt()!=="linux")return{ok:!1};if(process.env.CI==="true")return{ok:!1,warning:"CI/test environment detected; using JSON fallback"};if(process.env.VIBE_SKIP_LIBSECRET_INSTALL==="1")return{ok:!1,warning:"VIBE_SKIP_LIBSECRET_INSTALL=1 set; using JSON fallback"};let t=C(),n=f(t,wt);if(k(n))return{ok:!1,warning:"previous attempt failed; not retrying"};try{K(t,{recursive:!0}),_(n,`${new Date().toISOString()}
|
|
6
|
+
`,{mode:384})}catch{return{ok:!1,warning:"could not write install marker"}}let r=[{check:["sh","-c","command -v apt-get"],install:["sudo","-n","apt-get","install","-y","libsecret-1-0"]},{check:["sh","-c","command -v dnf"],install:["sudo","-n","dnf","install","-y","libsecret"]},{check:["sh","-c","command -v pacman"],install:["sudo","-n","pacman","-S","--noconfirm","libsecret"]}];for(let i of r){if(Q(i.check[0],i.check.slice(1),{stdio:["ignore","pipe","pipe"]}).status!==0)continue;let o=Q(i.install[0],i.install.slice(1),{stdio:["ignore","pipe","pipe"]});if(o.status===0)return{ok:!0};return{ok:!1,warning:`auto-install via '${i.install.join(" ")}' failed (exit ${o.status??"unknown"})`}}return{ok:!1,warning:"no supported package manager found"}}var D=null,F=null,ct=null;async function lt(t){try{return await t.get({service:v,name:"__probe__"}),!0}catch{return!1}}async function Xt(){if(ct)return ct;let t=Nt();if(t&&await lt(t))return new j(t);if(dt()==="linux"&&t){let n=Ht();if(n.ok&&await lt(t))return new j(t);if(n.warning)console.warn(`[secrets] libsecret unavailable (${n.warning}); using JSON fallback`);else console.warn("[secrets] Bun.secrets unavailable; using JSON fallback. Install libsecret-1-0 (apt) / libsecret (dnf/pacman) for OS keychain support.")}else if(!t)console.warn("[secrets] Bun.secrets API not present in this runtime; using JSON fallback.");return new It}async function U(){if(D)return D;if(!F)F=Xt().then((t)=>(D=t,t));return F}async function J(t){let r=await(await U()).get(t);if(pt("read",t))e().audit.emit("agent","secret.read",{name:t,hit:r!==null});return r}async function ce(t,n){if(await(await U()).set(t,n),pt("written",t))e().audit.emit("agent","secret.written",{name:t,valueLen:n.length})}async function $r(){let t=await U(),n=(await t.list()).map((r)=>r.name);return{count:n.length,backend:n.length===0?"none":t.kind,names:n}}async function Ui(){let t=await U(),r=(await t.list()).map((i)=>i.name);for(let i of r)try{await t.delete(i)}catch{}if(t.kind==="bun-secrets")G(Y()),G(f(C(),wt));else if(t.kind==="json-fallback"){let i=C();G(f(i,mt)),G(f(i,ht))}return{count:r.length,backend:r.length===0?"none":t.kind,names:r}}function G(t){try{if(k(t))vt(t)}catch{}}function ne(t){return`agent-config:${t}`}var E=["clientId","clientSecret","gatewayClientId","gatewayClientSecret","static-api-key"];function bt(t){return E.includes(t)}function m(t,n){return`${t}:${n}`}function T(){try{return R()}catch{return"default"}}var y=1,re=[],N={globalGatewayUrl:"https://graphql.burdenoff.com/global/graphql",workspaceGatewayUrl:"https://graphqlworkspaces.burdenoff.com/workspaces/graphql"},ie={globalGatewayUrl:"https://alphagraphql.burdenoff.com/global/graphql",workspaceGatewayUrl:"https://alphagraphqlworkspaces.burdenoff.com/workspaces/graphql"},se={globalGatewayUrl:"http://localhost:4000/global/graphql",workspaceGatewayUrl:"http://localhost:4003/workspaces/graphql"},Qt={default:{...N}},lr={local:{...se},alpha:{...ie},prod:{...N}},A="default",St=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;function fe(t){if(!St.test(t))throw Error("Profile name must use 1-64 characters: letters, numbers, dot, underscore, or dash.");return t}function Et(){return L(C(),"profiles")}function H(){return L(C(),"active")}function je(t){return L(Et(),`${fe(t)}.json`)}function pe(){let t=H();if(!d(t))return A;try{let n=h(t,"utf8").trim();if(!n)return A;return fe(n)}catch{return A}}function jt(t){let n=fe(t),r=H();O(B(r),{recursive:!0});let i=`${r}.${process.pid}.tmp`;S(i,`${n}
|
|
7
|
+
`,{mode:384}),x(i,r)}function Hr(){let t=Et();if(!d(t))return[];return Zt(t,{withFileTypes:!0}).filter((n)=>n.isFile()&&n.name.endsWith(".json")).map((n)=>n.name.slice(0,-5)).filter((n)=>St.test(n)).sort()}function _t(t){let n=je(t);if(!d(n))return{};try{return V(h(n,"utf8"))}catch{return{}}}function Pt(t,n){let r=JSON.parse(t);if(!r||typeof r!=="object"||Array.isArray(r))throw Error(`${n} is not a JSON object`);return r}function Vr(t){let n=je(t);if(!d(n))return{};return Pt(h(n,"utf8"),`Profile ${n}`)}function et(t,n){let r=fe(t),i=je(r);O(B(i),{recursive:!0});let s={schemaVersion:y,...n},o={...s};for(let g of E){let c=o[g];if(typeof c==="string"&&c.length>0)ce(m(r,g),c).catch(()=>{});delete o[g]}let a=`${i}.${process.pid}.tmp`;return S(a,`${JSON.stringify(o,null,2)}
|
|
8
|
+
`,{mode:384}),x(a,i),s}function Yr(t){let n=je(t);if(!d(n))return!1;return te(n,{force:!0}),!0}function gr(t,n={}){let r=Qt[t];return{schemaVersion:y,globalGatewayUrl:r.globalGatewayUrl,workspaceGatewayUrl:r.workspaceGatewayUrl,...n}}function dr(){let t={created:[],activeWritten:null};for(let n of Object.keys(Qt))if(!d(je(n)))et(n,gr(n)),t.created.push(n);if(!d(H()))jt(A),t.activeWritten=A;return t}function oe(){return{...N}}function tt(t){let n=t?.dir??I();return L(n,"config.json")}function hr(){return{...N}}function Zr(t={}){let n=oe();return{schemaVersion:y,globalGatewayUrl:n.globalGatewayUrl,workspaceGatewayUrl:n.workspaceGatewayUrl,...t}}function V(t){try{let n=JSON.parse(t);if(n&&typeof n==="object")return n}catch{}return{}}function w(t){let n=tt(t);if(!d(n))return{};let r;try{let s=h(n,"utf8");r=t?.strict?Pt(s,`Agent config ${n}`):V(s)}catch(s){if(t?.strict)throw s;return{}}if((r.schemaVersion??0)>=y)return r;for(let s of re){if(s.from<(r.schemaVersion??0))continue;r=s.apply(r),r.schemaVersion=s.to}if(r.schemaVersion!==y)r.schemaVersion=y;if(!t?.strict)try{S(n,JSON.stringify(r,null,2),{mode:384})}catch{}return r}function Jr(t){let n=w(t);if(n.agentInstanceId)return n.agentInstanceId;let r=ee();return M({agentInstanceId:r},t),r}function M(t,n){let r=tt(n);O(B(r),{recursive:!0});let i=d(r)?V(h(r,"utf8")):{},s={...i},o={...i};for(let c of E)delete o[c];let a=n?.scope??T();for(let[c,l]of Object.entries(t)){if(l===void 0||l==="")continue;if(s[c]=l,bt(c)&&typeof l==="string"){ce(m(a,c),l).catch(()=>{});continue}o[c]=l}let g=`${r}.${process.pid}.tmp`;return S(g,`${JSON.stringify(o,null,2)}
|
|
9
|
+
`,{mode:384}),x(g,r),s}async function Gt(t,n){let r=tt(n);return ue(ne(r),async()=>{O(B(r),{recursive:!0});let i=d(r)?V(h(r,"utf8")):{},s={...i},o={...i};for(let l of E)delete o[l];let a=n?.scope??T(),g=[];for(let[l,p]of Object.entries(t)){if(p===void 0||p==="")continue;if(s[l]=p,bt(l)&&typeof p==="string"){g.push(ce(m(a,l),p));continue}o[l]=p}await Promise.all(g);let c=`${r}.${process.pid}.tmp`;return S(c,`${JSON.stringify(o,null,2)}
|
|
10
|
+
`,{mode:384}),x(c,r),s})}async function X(t){let n=w({dir:t?.dir,strict:t?.strict}),r=t?.scope??T();for(let i of E){if(n[i])continue;try{let s=await J(m(r,i));if(s)n[i]=s}catch(s){if(t?.strict)throw s}}return n}function ae(){return _t(pe())}function u(t){if(!t)return null;try{return new URL(t).origin}catch{return null}}function $t(t,n=new Date().toISOString()){let r={pairedAt:n},i=u(t.globalGatewayUrl);if(i)r.globalGatewayOrigin=i;let s=u(t.workspaceGatewayUrl);if(s)r.workspaceGatewayOrigin=s;if(t.workspaceId)r.workspaceId=t.workspaceId;if(t.agentRecordId)r.agentRecordId=t.agentRecordId;return r}function le(t){if(!Boolean(t.clientId||t.pairedIdentity||t.workspaceId||t.agentRecordId))return null;let r=t.pairedIdentity,i={workspaceId:r?.workspaceId??t.workspaceId,globalGatewayUrl:u(r?.globalGatewayOrigin??t.globalGatewayUrl)??void 0,workspaceGatewayUrl:u(r?.workspaceGatewayOrigin??t.workspaceGatewayUrl)??void 0};if(Boolean(i.workspaceId||i.globalGatewayUrl||i.workspaceGatewayUrl))return i;return null}function Wr(t,n){let r=le(t);if(!r)return null;let i=Z(r,n);if(!i.length)return null;let s=b(r),o=t.pairedIdentity?.pairedAt;return`${t.clientId?`This agent is already paired with ${s}.`:`This agent holds no credential right now, but it is still bound to ${s}${o?` (paired ${o})`:""} \u2014 a cleared `+"secrets store is not an unpaired agent."} Refusing a credential push from ${b(n)} (${i.join("; ")}): it would overwrite the only credential slot and strand the existing pairing on 401. Re-send with "force": true to repair deliberately, or run the other environment under its own profile (VIBECONTROLS_PROFILE).`}function Xr(t,n,r){let i=Z({globalGatewayUrl:t.globalGatewayUrl,workspaceGatewayUrl:t.workspaceGatewayUrl},{...n,workspaceId:void 0});if(!i.length)return null;let s=u(t.globalGatewayUrl)??u(t.workspaceGatewayUrl)??"its configured gateway";return`Profile "${r}" is configured for ${s}, but this credential push is for ${b(n)} (${i.join("; ")}). Accepting it would repoint the profile `+"without saying so \u2014 the agent would run against one environment while "+`"${r}" still describes another. Run that environment under its own profile (VIBECONTROLS_PROFILE=<name>, or \`vibe profile create <name>\`), or re-send with "force": true to repoint "${r}" deliberately.`}function b(t){return`${u(t.globalGatewayUrl)??"unknown gateway"} (workspace ${t.workspaceId??"unknown"})`}function Z(t,n){let r=[],i=u(t.globalGatewayUrl),s=u(n.globalGatewayUrl);if(i&&s&&i!==s)r.push(`global gateway ${i} -> ${s}`);let o=u(t.workspaceGatewayUrl),a=u(n.workspaceGatewayUrl);if(o&&a&&o!==a)r.push(`workspace gateway ${o} -> ${a}`);if(t.workspaceId&&n.workspaceId&&t.workspaceId!==n.workspaceId)r.push(`workspace ${t.workspaceId} -> ${n.workspaceId}`);return r}function zr(t,n){if(!t.clientId)return null;let r=Z(t,n);if(!r.length)return null;return`Credentials were issued for ${b(t)} but this agent is configured for ${b(n)} (${r.join("; ")}). `+"They cannot authenticate there \u2014 re-pair the agent from the environment "+"it should belong to, or clear the conflicting environment override (VIBE_GLOBAL_GATEWAY_URL / VIBE_WORKSPACE_GATEWAY_URL / VIBE_WORKSPACE_ID)."}var z=null;function ei(){return{...z??{}}}function yt(){try{dr()}catch{}let t=ae(),n=w(),r={...t,...n};if(z===null)z={globalGatewayUrl:process.env.VIBE_GLOBAL_GATEWAY_URL,workspaceGatewayUrl:process.env.VIBE_WORKSPACE_GATEWAY_URL};let i=(o,a)=>{if(!process.env[o]&&a)process.env[o]=a};i("VIBE_WORKSPACE_ID",r.workspaceId),i("VIBE_ORGANIZATION_ID",r.organizationId);let s=hr();return i("VIBE_GLOBAL_GATEWAY_URL",r.globalGatewayUrl??s.globalGatewayUrl),i("VIBE_WORKSPACE_GATEWAY_URL",r.workspaceGatewayUrl??s.workspaceGatewayUrl),i("VIBE_STORAGE_ADAPTER",r.storageAdapter),i("VIBECONTROLS_PLUGIN_INSTALL_SCOPE",r.pluginInstallScope),r}async function ti(){let t=(r,i)=>{if(!process.env[r]&&i)process.env[r]=i},n=T();try{let r=await J(m(n,"clientId"));t("VIBE_CLIENT_ID",r??void 0)}catch{}try{let r=await J(m(n,"clientSecret"));t("VIBE_CLIENT_SECRET",r??void 0)}catch{}}
|
|
11
|
+
export{J,ce,$r,Ui,Qt,lr,fe,je,pe,jt,Hr,_t,Vr,et,Yr,gr,dr,tt,hr,Zr,w,Jr,M,Gt,X,$t,Wr,Xr,zr,ei,yt,ti};
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{E}from"./index-w0m3jm0s.js";import{R,B,N,e}from"./index-0qjbnyg4.js";import{J,ce,w,M}from"./index-kwhx023z.js";import{ki}from"./index-5021rk8n.js";import{randomBytes as S,createHmac as X,timingSafeEqual as ke}from"crypto";var C=600,ie=600,H=S(32),P="p2.";function T(t){if(!t.startsWith("/"))return`/${t}`;return t.length>1&&t.endsWith("/")?t.slice(0,-1):t}var Ee=/^\/terminal\/[A-Za-z0-9_-]{1,128}(?:\/.*)?$/,_e=/^\/ui\/[a-z0-9-]{1,64}(?:\/.*)?$/,Ie=/^\/plan\/[A-Za-z0-9_-]{1,128}(?:\/.*)?$/,xe=/^\/git(?:\/.*)?$/,Pe="/ws/logs",Se=/^\/code-server(?:\/.*)?$/,Te=/^\/api\/plugins\/[a-z0-9-]{1,64}\/ui(?:\/.*)?$/;function se(t){if(typeof t!=="string"||t.length===0)return!1;if(t.includes("\x00")||t.includes(`
|
|
3
|
+
`)||t.includes("|"))return!1;if(t.includes(".."))return!1;if(new Set(["/","/api","/api/agent","/api/plugins","/api/profiles","/health","/metrics","/ws","/api/ai","/api/logs"]).has(t))return!1;if(Ee.test(t))return!0;if(_e.test(t))return!0;if(Ie.test(t))return!0;if(xe.test(t))return!0;if(t===Pe)return!0;if(Se.test(t))return!0;if(Te.test(t))return!0;return!1}var Re=new Set(["*","GET","HEAD","POST","PUT","PATCH","DELETE","OPTIONS"]);function ve(t){if(!t||t.length===0)return["*"];let n=new Set,r=[];for(let i of t){if(typeof i!=="string")continue;let s=i.toUpperCase();if(!Re.has(s))throw Error(`invalid method: ${i}`);if(!n.has(s))n.add(s),r.push(s)}if(r.length===0)return["*"];return r.sort()}function oe(t,n){if(t.includes("*"))return!0;return t.includes(n.toUpperCase())}var $e=/^[A-Za-z0-9_-]{1,128}$/;function be(t){return typeof t==="string"&&$e.test(t)}function Z(t,n,r){return X("sha256",H).update(`${t}
|
|
4
|
+
${n}
|
|
5
|
+
${r}`).digest("hex")}var O=new Map;function Fe(t){for(let[n,r]of O)if(r<=t)O.delete(n)}function ae(t,n){let r=Date.parse(n);if(!Number.isFinite(r))return;O.set(t,r)}function ue(t){return Fe(Date.now()),O.has(t)}function j(t,n,r,i){return X("sha256",H).update(`v2
|
|
6
|
+
${t}
|
|
7
|
+
${n}
|
|
8
|
+
${r}
|
|
9
|
+
${i}`).digest("hex")}function D(t){return Buffer.from(t,"utf8").toString("base64").replace(/=+$/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function U(t){try{let n=t.replace(/-/g,"+").replace(/_/g,"/"),r=n.length%4===0?n:n+"=".repeat(4-n.length%4);return Buffer.from(r,"base64").toString("utf8")}catch{return null}}var re=16;function Ne(t){if(t.length>re)throw Error(`pathPrefixes exceeds maximum count (${t.length} > ${re})`);let n=new Set,r=[];for(let i of t){if(!i||typeof i!=="string")continue;if(i.includes("..")||i.includes("\x00"))throw Error("invalid pathPrefix");let s=T(i);if(!se(s))throw Error(`pathPrefix '${s}' is not an allowed iframe surface`);if(!n.has(s))n.add(s),r.push(s)}return r.sort()}function Ar(t,n=C){if(!t||typeof t!=="string")throw Error("pathPrefix is required");if(t.includes("..")||t.includes("\x00"))throw Error("invalid pathPrefix");let r=Math.min(Math.max(1,Math.floor(n||C)),ie),i=T(t);if(!se(i))throw Error(`pathPrefix '${i}' is not an allowed iframe surface`);let s=new Date(Date.now()+r*1000).toISOString(),o=S(16).toString("hex"),a=Z(i,s,o);return{token:`${s}|${o}|${a}`,expiresAt:s}}function Nt(t,n=C){if(!t||!Array.isArray(t.pathPrefixes)||t.pathPrefixes.length===0)throw Error("pathPrefixes is required");let r=Ne(t.pathPrefixes);if(r.length===0)throw Error("pathPrefixes is required");let i=ve(t.methods),s=Math.min(Math.max(1,Math.floor(n||C)),ie),o=new Date(Date.now()+s*1000).toISOString(),a=S(16).toString("hex"),c=D(JSON.stringify(r)),u=D(JSON.stringify(i)),f=`${P}${c}.${u}`,l=j(c,u,o,a);return{token:`${o}|${a}|${f}|${l}`,expiresAt:o}}function _(t,n){if(t.length!==n.length)return!1;try{return ke(Buffer.from(t,"hex"),Buffer.from(n,"hex"))}catch{return!1}}function L(t,n){let r=T(n);return t===r||t.startsWith(`${r}/`)}function Ke(t,n,r="*"){return Ur(t,n,r).ok}function Ur(t,n,r="*"){if(!t||typeof t!=="string")return{ok:!1,reason:"missing"};let i=t.split("|");if(i.length===3)return Ce(i,n);if(i.length===4)return Oe(i,n,r);return{ok:!1,reason:"malformed"}}function Ce(t,n){let[r,i,s]=t;if(!r||!i||!s)return{ok:!1,reason:"malformed"};if(!I(r))return{ok:!1,reason:"expired"};let o=n.split("/").filter(Boolean),a=["/"],c="";for(let u of o)c+=`/${u}`,a.push(c);for(let u of a){let f=Z(T(u),r,i);if(_(f,s)){if(!L(n,u))return{ok:!1,reason:"path_mismatch"};if(ue(i))return{ok:!1,reason:"replayed"};return ae(i,r),{ok:!0}}}return{ok:!1,reason:"bad_signature"}}function Oe(t,n,r){let[i,s,o,a]=t;if(!i||!s||!o||!a)return{ok:!1,reason:"malformed"};if(!o.startsWith(P))return{ok:!1,reason:"malformed"};if(!I(i))return{ok:!1,reason:"expired"};let u=o.slice(P.length).split("."),f=u[0]??"",l=u[1]??D(JSON.stringify(["*"]));if(!f)return{ok:!1,reason:"malformed"};let h=j(f,l,i,s);if(!_(h,a))return{ok:!1,reason:"bad_signature"};let F=U(f);if(F===null)return{ok:!1,reason:"malformed"};let y;try{y=JSON.parse(F)}catch{return{ok:!1,reason:"malformed"}}if(!Array.isArray(y))return{ok:!1,reason:"malformed"};let A=U(l),x=["*"];if(A!==null)try{let g=JSON.parse(A);if(Array.isArray(g)&&g.every((d)=>typeof d==="string"))x=g}catch{return{ok:!1,reason:"malformed"}}if(r!=="*"&&!oe(x,r))return{ok:!1,reason:"method_mismatch"};for(let g of y){if(typeof g!=="string")continue;if(L(n,g)){if(ue(s))return{ok:!1,reason:"replayed"};return ae(s,i),{ok:!0}}}return{ok:!1,reason:"path_mismatch"}}function we(t,n,r="*"){if(!t||typeof t!=="string")return!1;let i=t.split("|");if(i.length===3){let[s,o,a]=i;if(!s||!o||!a)return!1;if(!I(s))return!1;let c=n.split("/").filter(Boolean),u=["/"],f="";for(let l of c)f+=`/${l}`,u.push(f);for(let l of u){let h=Z(T(l),s,o);if(_(h,a))return L(n,l)}return!1}if(i.length===4){let[s,o,a,c]=i;if(!s||!o||!a||!c)return!1;if(!a.startsWith(P))return!1;if(!I(s))return!1;let f=a.slice(P.length).split("."),l=f[0]??"",h=f[1]??D(JSON.stringify(["*"]));if(!l)return!1;let F=j(l,h,s,o);if(!_(F,c))return!1;let y=U(l);if(y===null)return!1;let A;try{A=JSON.parse(y)}catch{return!1}if(!Array.isArray(A))return!1;let x=U(h),g=["*"];if(x!==null)try{let d=JSON.parse(x);if(Array.isArray(d)&&d.every((Ae)=>typeof Ae==="string"))g=d}catch{return!1}if(r!=="*"&&!oe(g,r))return!1;for(let d of A){if(typeof d!=="string")continue;if(L(n,d))return!0}return!1}return!1}function I(t){let n=Date.parse(t);return Number.isFinite(n)&&Date.now()<n}function Lt(t,n){let r=t.headers.get("x-vibe-iframe-token")??t.headers.get("X-Vibe-Iframe-Token");if(r)return r;try{let i=new URL(t.url).searchParams.get("vt");if(i)return i}catch{}return null}var q="tc1|",z=600,De=600;function fe(t,n,r){return X("sha256",H).update(`tc1
|
|
10
|
+
${t}
|
|
11
|
+
${n}
|
|
12
|
+
${r}`).digest("hex")}function Pi(t,n=z){if(!be(t))throw Error("invalid sid");let r=Math.min(Math.max(1,Math.floor(n||z)||z),De),i=new Date(Date.now()+r*1000).toISOString(),s=S(16).toString("hex"),o=fe(t,i,s);return{token:`${q}${i}|${t}|${s}|${o}`,expiresAt:i}}function cr(t,n){if(!t||typeof t!=="string")return!1;if(!t.startsWith(q))return!1;let i=t.slice(q.length).split("|");if(i.length!==4)return!1;let[s,o,a,c]=i;if(!s||!o||!a||!c)return!1;if(o!==n)return!1;if(!I(s))return!1;let u=fe(o,s,a);return _(u,c)}function Kr(t,n){let r;if(t instanceof Headers)r=t.get("cookie")??t.get("Cookie")??void 0;else r=t.cookie??t.Cookie??void 0;if(!r)return null;let i=`vt_term_${n}`;for(let s of r.split(";")){let o=s.indexOf("=");if(o===-1)continue;if(s.slice(0,o).trim()!==i)continue;return s.slice(o+1).trim()||null}return null}function Qr(t,n){return Kr(t.headers,n)}var Y="uc1|",W=600,Me=600,Ue=/^[a-z0-9-]{1,64}$/;function de(t){return typeof t==="string"&&Ue.test(t)}function le(t,n,r){return X("sha256",H).update(`uc1
|
|
13
|
+
${t}
|
|
14
|
+
${n}
|
|
15
|
+
${r}`).digest("hex")}function mt(t,n=W){if(!de(t))throw Error("invalid plugin name");let r=Math.min(Math.max(1,Math.floor(n||W)||W),Me),i=new Date(Date.now()+r*1000).toISOString(),s=S(16).toString("hex"),o=le(t,i,s);return{token:`${Y}${i}|${t}|${s}|${o}`,expiresAt:i}}function Xe(t,n){if(!t||typeof t!=="string")return!1;if(!t.startsWith(Y))return!1;let i=t.slice(Y.length).split("|");if(i.length!==4)return!1;let[s,o,a,c]=i;if(!s||!o||!a||!c)return!1;if(o!==n)return!1;if(!I(s))return!1;let u=le(o,s,a);return _(u,c)}function Le(t,n){let r;if(t instanceof Headers)r=t.get("cookie")??t.get("Cookie")??void 0;else r=t.cookie??t.Cookie??void 0;if(!r)return null;let i=`vt_ui_${n}`;for(let s of r.split(";")){let o=s.indexOf("=");if(o===-1)continue;if(s.slice(0,o).trim()!==i)continue;return s.slice(o+1).trim()||null}return null}function ze(t,n){return Le(t.headers,n)}import{timingSafeEqual as Je}from"crypto";var Be=["/api/agent/api-key","/api/agent/reset-key","/api/agent/iframe-token","/api/agent/aliases","/api/agent/alias","/api/agent/commands","/api/agent/lifecycle","/api/agent/nuke","/api/agent/uninstall","/api/agent/gateway-auth","/api/agent/storage-key","/api/agent/sessions/share","/api/config","/api/security","/api/tasks","/api/editor","/api/code-server","/api/logs","/api/maintenance"],Ve=["/api/plugins/install","/api/plugins/prereqs"],He=["/api/plugins/remove","/api/plugins/remove-all"],Ge=["/api/agent/update","/api/plugins/update","/api/plugins/update-all"];var Q=new Set(["GET","HEAD","OPTIONS"]);function ee(t,n){return t===n||t.startsWith(`${n}/`)}function G(t,n){return n.some((r)=>ee(t,r))}function We(t){let n=new URL(t,"http://agent.local").pathname,r=/^\/api\/profiles\/[^/]+\/(.+)$/.exec(n);if(r?.[1])return`/api/${r[1]}`;return n}function ar(t,n,r){if(t.has("admin"))return!0;let i=We(r),s=n.toUpperCase();if(i==="/api/profiles"||/^\/api\/profiles\/[^/]+$/.test(i))return Q.has(s)&&t.has("read");if(G(i,Be))return!1;if(G(i,Ve)&&t.has("plugin:install"))return!0;if(G(i,He)&&t.has("plugin:remove"))return!0;if(G(i,Ge)&&t.has("update"))return!0;if(ee(i,"/api/mesh"))return!0;if(ee(i,"/api/plugins")&&!Q.has(s))return!1;if(Q.has(s))return t.has("read")||t.has("mutate");return t.has("mutate")}var Ye=["/health","/ui","/code-server","/terminal","/plan","/git","/api/agent/status","/api/agent/version","/api/agent/identity","/api/agent/terminal-exchange","/api/agent/ui-exchange","/api/agent/ui-exchange-plugin","/metrics"];function ge(t,n){if(!n||n==="/")return!1;let r=n.endsWith("/")?n.slice(0,-1):n;return t===r||t.startsWith(`${r}/`)}function Ze(t){let n=t.replace(/^\/api\/profiles\/[^/]+/,"/api");return n==="/api"?"/":n}function je(t){let n=/^\/api\/profiles\/([^/]+)(?:\/|$)/.exec(t);if(!n)return null;let r=n[1];if(!r)return null;return r}function pe(t,n){let r=[t],i=Ze(t);if(i!==t)r.push(i);for(let s of r){if(Ye.some((o)=>ge(s,o)))return!0;if(n.some((o)=>ge(s,o)))return!0}return!1}function ye(){let t=new Uint8Array(32);return crypto.getRandomValues(t),`vcak_${Buffer.from(t).toString("base64url")}`}var p=null;function ne(){return`${R()}:static-api-key`}async function qe(){let t=process.env.AGENT_API_KEY;if(t)return p=t,t;let n=ne(),r=await J(n);if(r)return p=r,r;let i=w({dir:e().dataDir})["static-api-key"];if(i){try{await ce(n,i)}catch(o){e().logger.warn("auth","could not persist legacy api key into secrets backend",{error:String(o)})}return p=i,i}let s=ye();return await ce(n,s),p=s,e().logger.info("auth","Generated and persisted new agent API key"),e().audit.emit("agent","apikey.minted",{profile:R(),via:"loadAgentApiKey"}),s}function K(){let t=process.env.AGENT_API_KEY;if(t)return t;if(p!==null)return p;let n=w()["static-api-key"];if(n)return p=n,n;let r=ye();p=r;try{M({"static-api-key":r},{dir:e().dataDir,scope:e().name})}catch{}return ce(ne(),r).catch(()=>{}),r}async function Mi(t){if(process.env.AGENT_API_KEY)throw Error("AGENT_API_KEY is pinned via the environment \u2014 cannot rotate the key at runtime. Update the env var and restart.");let n=(t??"").trim();if(!/^vcak_[A-Za-z0-9_-]{16,}$/.test(n))throw Error("Invalid agent API key format (expected vcak_<base64url>).");p=n,await ce(ne(),n);try{M({"static-api-key":n},{dir:e().dataDir,scope:e().name})}catch{}e().audit.emit("agent","apikey.rotated",{profile:R(),via:"reset-key"})}function k(t){let n=t["x-agent-api-key"]??t["X-Agent-Api-Key"];if(n)return n;let r=t.authorization??t.Authorization;if(r?.startsWith("Bearer "))return r.slice(7);return null}function Qe(t){return!1}function et(t,n){let r=k(Object.fromEntries(t.headers.entries()));if(r)return r;if(!Qe(n))return null;try{let i=new URL(t.url).searchParams.get("apiKey");if(i)return i}catch{}return null}function v(t,n){let r=Buffer.from(t),i=Buffer.from(n);if(r.length!==i.length)return!1;try{return Je(r,i)}catch{return!1}}function V(t){if(!t)return!1;return v(t,K())}var b={name:"default",scopes:new Set(["admin"])};async function tt(t,n){if(!t)return null;let r=je(n);if(r){let i=N.get(r);if(i){try{if(await i.keyVault.match(t))return b}catch{}if(r===e().name){try{if(await e().keyVault.match(t))return b}catch{}if(v(t,K()))return b;return me(t)}return null}}try{if(await e().keyVault.match(t))return b}catch{}if(v(t,K()))return b;return me(t)}function me(t){let n=ur(t);return n?{name:n.name,scopes:n.scopes}:null}function ur(t){if(!t)return null;if(v(t,K()))return{name:"default",scopes:new Set(["admin"])};let n=B()??e(),r=w({dir:n.dataDir}),i=Date.now();for(let s of r.apiKeys??[]){if(!v(t,s.key))continue;if(s.notBefore){let o=Date.parse(s.notBefore);if(Number.isFinite(o)&&i<o)return null}if(s.expiresAt){let o=Date.parse(s.expiresAt);if(Number.isFinite(o)&&i>=o)return null}return{name:s.name,scopes:new Set(s.scopes)}}return null}function Di(t,n){if(!t)return!1;if(t.scopes.has("admin"))return!0;return n.some((r)=>t.scopes.has(r))}var m=null;function te(t,n){try{e().audit.emit("auth",t,n)}catch{e().logger.warn("auth.audit",t,n)}}function nt(t){let n=new Set(t());if(m===null)for(let r of n)te("plugin.public_path.declared",{path:r});else{for(let r of n)if(!m.has(r))te("plugin.public_path.added",{path:r});for(let r of m)if(!n.has(r))te("plugin.public_path.removed",{path:r})}return m=n,n}function Ni(){m=null}function he(t){if(!t)return[];if(m===null)return[...nt(t)];return[...m]}function Li(t){let n=K();return e().logger.info("auth",`Agent API key: ${n.substring(0,8)}****${n.substring(n.length-4)}`),new E({name:"plugin/auth"}).decorate("apiKey",n).derive(async({request:r,path:i})=>{let s=he(t),o;if(pe(i,s))o=!0;else if(ki(r.headers))o=!0;else{let a=Lt(r,i);if(a&&Ke(a,i,r.method))o=!0;else{let c=et(r,i),u=await tt(c,i);if(o=u!==null,u&&!ar(u.scopes,r.method,i))return{isAuthenticated:o,scopeDenied:u.name}}}return{isAuthenticated:o,scopeDenied:null}}).onBeforeHandle(({isAuthenticated:r,scopeDenied:i,request:s,path:o,set:a})=>{if(i){try{e().audit.emit("auth","scoped_key.denied",{key:i,method:s.method,path:o})}catch{}return a.status=403,{error:"Forbidden",message:"This API key's scopes do not allow this operation"}}let c=he(t);if(!r&&!pe(o,c)){if(Lt(s,o))return a.status=401,{error:"invalid iframe token"};return a.status=401,{error:"Unauthorized",message:"Invalid or missing API key"}}}).as("global")}
|
|
16
|
+
export{ar,be,Ar,Nt,Ke,Ur,we,Lt,Pi,cr,Kr,Qr,de,mt,Xe,ze,qe,K,Mi,k,V,ur,Di,Ni,Li};
|